Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: Attendee fragment (#786) (#792) #796

Merged
merged 1 commit into from Dec 30, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
@@ -1,8 +1,6 @@
package org.fossasia.openevent.general.attendees

import android.app.Activity.RESULT_OK
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.text.Editable
Expand Down Expand Up @@ -61,7 +59,6 @@ import kotlinx.android.synthetic.main.fragment_attendee.view.time
import kotlinx.android.synthetic.main.fragment_attendee.view.view
import kotlinx.android.synthetic.main.fragment_attendee.view.year
import kotlinx.android.synthetic.main.fragment_attendee.view.yearText
import org.fossasia.openevent.general.AuthActivity
import org.fossasia.openevent.general.R
import org.fossasia.openevent.general.attendees.forms.CustomForm
import org.fossasia.openevent.general.event.Event
Expand All @@ -80,8 +77,6 @@ import org.koin.androidx.viewmodel.ext.android.viewModel
import java.util.Currency

private const val STRIPE_KEY = "com.stripe.android.API_KEY"
private const val PRIVACY_POLICY = "https://eventyay.com/privacy-policy/"
private const val TERMS_OF_SERVICE = "https://eventyay.com/terms/"

class AttendeeFragment : Fragment() {

Expand All @@ -93,7 +88,7 @@ class AttendeeFragment : Fragment() {

private lateinit var eventId: EventId
private var ticketIdAndQty: List<Pair<Int, Int>>? = null
private lateinit var selectedPaymentOption: String
private var selectedPaymentOption: Int = -1
private lateinit var paymentCurrency: String
private var expiryMonth: Int = -1
private lateinit var expiryYear: String
Expand All @@ -103,7 +98,6 @@ class AttendeeFragment : Fragment() {
private var singleTicket = false
private var identifierList = ArrayList<String>()
private var editTextList = ArrayList<EditText>()
private val AUTH_REQUEST_CODE = 1
private var amount: Float = 0.0f

override fun onCreate(savedInstanceState: Bundle?) {
Expand All @@ -127,14 +121,14 @@ class AttendeeFragment : Fragment() {
rootView = inflater.inflate(R.layout.fragment_attendee, container, false)
val activity = activity as? AppCompatActivity
activity?.supportActionBar?.setDisplayHomeAsUpEnabled(true)
activity?.supportActionBar?.title = "Attendee Details"
activity?.supportActionBar?.title = getString(R.string.attendee_details)
setHasOptionsMenu(true)

val paragraph = SpannableStringBuilder()
val startText = "I accept the "
val termsText = "terms of service "
val middleText = "and have read the "
val privacyText = "privacy policy."
val startText = getString(R.string.start_text)
val termsText = getString(R.string.terms_text)
val middleText = getString(R.string.middle_text)
val privacyText = getString(R.string.privacy_text)

paragraph.append(startText)
paragraph.append(termsText)
Expand All @@ -149,7 +143,7 @@ class AttendeeFragment : Fragment() {

override fun onClick(widget: View) {
context?.let {
Utils.openUrl(it, TERMS_OF_SERVICE)
Utils.openUrl(it, getString(R.string.terms_of_service))
}
}
}
Expand All @@ -162,7 +156,7 @@ class AttendeeFragment : Fragment() {

override fun onClick(widget: View) {
context?.let {
Utils.openUrl(it, PRIVACY_POLICY)
Utils.openUrl(it, getString(R.string.privacy_policy))
}
}
}
Expand Down Expand Up @@ -191,8 +185,8 @@ class AttendeeFragment : Fragment() {

attendeeViewModel.updatePaymentSelectorVisibility(ticketIdAndQty)
val paymentOptions = ArrayList<String>()
paymentOptions.add("PayPal")
paymentOptions.add("Stripe")
paymentOptions.add(getString(R.string.paypal))
paymentOptions.add(getString(R.string.stripe))
attendeeViewModel.paymentSelectorVisibility
.nonNull()
.observe(this, Observer {
Expand All @@ -209,9 +203,9 @@ class AttendeeFragment : Fragment() {
// Do nothing
}

override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
selectedPaymentOption = paymentOptions[p2]
if (selectedPaymentOption == "Stripe")
override fun onItemSelected(p0: AdapterView<*>?, p1: View?, position: Int, p3: Long) {
selectedPaymentOption = position
if (position == paymentOptions.indexOf(getString(R.string.stripe)))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use constant please

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can I compare directly with the position? if(position = 0 or 1).

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, for this, please remove the string resources and use constants

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm sorry to not getting it, because if (selectedPaymentOption == 0) in this case it is constant. Should I define value first like stripePaymentPosition = 0 and paypalPaymentOption = 1 and compare selectedPaymentOption with them.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Change it to selectedOption == STRIPE and don't use string resources in any of its cases

But I'm merging it now, create another issue to handle it

rootView.stripePayment.visibility = View.VISIBLE
else
rootView.stripePayment.visibility = View.GONE
Expand Down Expand Up @@ -275,27 +269,6 @@ class AttendeeFragment : Fragment() {
}
}

attendeeViewModel.loadEvent(id)

if (attendeeViewModel.isLoggedIn()) {
loadUser()
} else {
redirectToLogin()
Toast.makeText(context, "You need to log in first!", Toast.LENGTH_LONG).show()
}

attendeeViewModel.ticketSoldOut
.nonNull()
.observe(this, Observer {
showTicketSoldOutDialog(it)
})
return rootView
}

private fun loadUser() {
attendeeViewModel.loadUser(attendeeViewModel.getId())
attendeeViewModel.loadEvent(id)

attendeeViewModel.message
.nonNull()
.observe(this, Observer {
Expand Down Expand Up @@ -357,6 +330,9 @@ class AttendeeFragment : Fragment() {
openOrderCompletedFragment()
})

attendeeViewModel.loadUser()
attendeeViewModel.loadEvent(id)

attendeeViewModel.attendee
.nonNull()
.observe(this, Observer { user ->
Expand All @@ -368,7 +344,7 @@ class AttendeeFragment : Fragment() {

rootView.signOut.setOnClickListener {
attendeeViewModel.logout()
redirectToLogin()
activity?.onBackPressed()
}

attendeeViewModel.getCustomFormsForAttendees(eventId.id)
Expand All @@ -388,9 +364,6 @@ class AttendeeFragment : Fragment() {
})

rootView.register.setOnClickListener {
if (selectedPaymentOption == "Stripe")
sendToken()

val attendees = ArrayList<Attendee>()
if (singleTicket) {
val pos = ticketIdAndQty?.map { it.second }?.indexOf(1)
Expand All @@ -409,39 +382,33 @@ class AttendeeFragment : Fragment() {
attendees.addAll(attendeeRecyclerAdapter.attendeeList)
}
val country = if (country.text.isEmpty()) country.text.toString() else null
attendeeViewModel.createAttendees(attendees, country, selectedPaymentOption)
attendeeViewModel.createAttendees(attendees, country, paymentOptions[selectedPaymentOption])

attendeeViewModel.isAttendeeCreated.observe(this, Observer { isAttendeeCreated ->
if (isAttendeeCreated && selectedPaymentOption == paymentOptions.indexOf(getString(R.string.stripe))) {
sendToken()
}
})
}

attendeeViewModel.ticketSoldOut
.nonNull()
.observe(this, Observer {
showTicketSoldOutDialog(it)
})

return rootView
}

private fun showTicketSoldOutDialog(show: Boolean) {
if (show) {
val builder = AlertDialog.Builder(context)
builder.setMessage(context?.resources?.getString(R.string.tickets_sold_out))
.setPositiveButton(context?.resources?.getString(R.string.ok)) { dialog, _ -> dialog.cancel() }
builder.setMessage(getString(R.string.tickets_sold_out))
.setPositiveButton(getString(R.string.ok)) { dialog, _ -> dialog.cancel() }
builder.show()
}
}

private fun redirectToLogin() {
val intent = Intent(activity, AuthActivity::class.java)
val bundle = Bundle()
bundle.putLong(EVENT_ID, id)
if (ticketIdAndQty != null)
bundle.putSerializable(TICKET_ID_AND_QTY, ticketIdAndQty as ArrayList)
intent.putExtras(bundle)
startActivityForResult(intent, AUTH_REQUEST_CODE)
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == AUTH_REQUEST_CODE) {
if (resultCode == RESULT_OK)
loadUser()
else
Toast.makeText(context, "Sign in failed!", Toast.LENGTH_SHORT).show()
}
super.onActivityResult(requestCode, resultCode, data)
}

private fun sendToken() {
val card = Card(cardNumber.text.toString(), expiryMonth, expiryYear.toInt(), cvc.text.toString())
card.addressCountry = country.text.toString()
Expand All @@ -451,24 +418,21 @@ class AttendeeFragment : Fragment() {
rootView.selectCard.text = "Pay by ${card.brand}"

val validDetails: Boolean? = card.validateCard()
if (validDetails != null && !validDetails) {
if (validDetails != null && !validDetails)
Toast.makeText(context, "Invalid card data", Toast.LENGTH_LONG).show()
}

Stripe(requireContext()).createToken(
card,
API_KEY,
object : TokenCallback {
override fun onSuccess(token: Token) {
// Send this token to server
val charge = Charge(attendeeViewModel.getId().toInt(), token.id, null)
attendeeViewModel.completeOrder(charge)
}
else
Stripe(requireContext())
.createToken(card, API_KEY, object : TokenCallback {
override fun onSuccess(token: Token) {
// Send this token to server
val charge = Charge(attendeeViewModel.getId().toInt(), token.id, null)
attendeeViewModel.completeOrder(charge)
}

override fun onError(error: Exception) {
Toast.makeText(context, error.localizedMessage.toString(), Toast.LENGTH_LONG).show()
}
})
override fun onError(error: Exception) {
Toast.makeText(context, error.localizedMessage.toString(), Toast.LENGTH_LONG).show()
}
})
}

private fun loadEventDetails(event: Event) {
Expand Down
Expand Up @@ -60,6 +60,8 @@ class AttendeeViewModel(
val tickets: LiveData<MutableList<Ticket>> = mutableTickets
private val mutableForms = MutableLiveData<List<CustomForm>>()
val forms: LiveData<List<CustomForm>> = mutableForms
private val mutableIsAttendeeCreated = MutableLiveData<Boolean>()
val isAttendeeCreated: LiveData<Boolean> = mutableIsAttendeeCreated

val month = ArrayList<String>()
val year = ArrayList<String>()
Expand All @@ -76,8 +78,6 @@ class AttendeeViewModel(

fun getId() = authHolder.getId()

fun isLoggedIn() = authHolder.isLoggedIn()

fun initializeSpinner() {
// initialize months
month.add("Month")
Expand Down Expand Up @@ -163,6 +163,7 @@ class AttendeeViewModel(
private fun createAttendee(attendee: Attendee, totalAttendee: Int) {
if (attendee.email.isNullOrEmpty() || attendee.firstname.isNullOrEmpty() || attendee.lastname.isNullOrEmpty()) {
mutableMessage.value = "Please fill in all the fields"
mutableIsAttendeeCreated.value = false
return
}

Expand All @@ -179,6 +180,7 @@ class AttendeeViewModel(
attendees.add(it)
if (attendees.size == totalAttendee) {
loadTicketsAndCreateOrder()
mutableIsAttendeeCreated.value = true
mutableMessage.value = "Attendees created successfully!"
}
Timber.d("Success! %s", attendees.toList().toString())
Expand Down Expand Up @@ -365,7 +367,8 @@ class AttendeeViewModel(
)
}

fun loadUser(id: Long) {
fun loadUser() {
val id = getId()
if (id == -1L) {
throw IllegalStateException("ID should never be -1")
}
Expand Down
Expand Up @@ -24,9 +24,7 @@ import kotlinx.android.synthetic.main.fragment_login.view.sentEmailLayout
import kotlinx.android.synthetic.main.fragment_login.view.tick
import org.fossasia.openevent.general.MainActivity
import org.fossasia.openevent.general.R
import org.fossasia.openevent.general.order.LAUNCH_TICKETS
import org.fossasia.openevent.general.ticket.EVENT_ID
import org.fossasia.openevent.general.ticket.TICKET_ID_AND_QTY
import org.fossasia.openevent.general.ticket.REDIRECTED_FROM_TICKETS
import org.fossasia.openevent.general.utils.Utils
import org.fossasia.openevent.general.utils.Utils.hideSoftKeyboard
import org.fossasia.openevent.general.utils.extensions.nonNull
Expand All @@ -37,17 +35,10 @@ class LoginFragment : Fragment() {
private val loginViewModel by viewModel<LoginViewModel>()
private lateinit var rootView: View
private var bundle: Bundle? = null
private var ticketIdAndQty: List<Pair<Int, Int>>? = null
private var id: Long = -1

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val bundle = this.arguments
if (bundle != null && !bundle.getBoolean(LAUNCH_TICKETS)) {
id = bundle.getLong(EVENT_ID, -1)
ticketIdAndQty = bundle.getSerializable(TICKET_ID_AND_QTY) as List<Pair<Int, Int>>
}
this.bundle = bundle
bundle = this.arguments
}

override fun onCreateView(
Expand Down Expand Up @@ -136,7 +127,7 @@ class LoginFragment : Fragment() {
private fun redirectToMain(bundle: Bundle?) {
val intent = Intent(activity, MainActivity::class.java)
if (bundle != null) {
if (id != -1L && ticketIdAndQty != null) {
if (bundle.getBoolean(REDIRECTED_FROM_TICKETS)) {
activity?.setResult(RESULT_OK, intent)
} else {
intent.putExtras(bundle)
Expand Down
Expand Up @@ -129,7 +129,7 @@ val viewModelModule = module {
viewModel { AttendeeViewModel(get(), get(), get(), get(), get(), get()) }
viewModel { SearchLocationViewModel(get()) }
viewModel { SearchTimeViewModel(get()) }
viewModel { TicketsViewModel(get(), get()) }
viewModel { TicketsViewModel(get(), get(), get()) }
viewModel { AboutEventViewModel(get()) }
viewModel { SocialLinksViewModel(get()) }
viewModel { FavouriteEventsViewModel(get()) }
Expand Down