Skip to content

Commit

Permalink
teams: safer with call operators (fixes #3252) (#3255)
Browse files Browse the repository at this point in the history
Co-authored-by: dogi <[email protected]>
  • Loading branch information
Okuro3499 and dogi authored Mar 15, 2024
1 parent 914cf2b commit 3b76407
Show file tree
Hide file tree
Showing 20 changed files with 258 additions and 225 deletions.
4 changes: 2 additions & 2 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ android {
applicationId "org.ole.planet.myplanet"
minSdkVersion 21
targetSdkVersion 34
versionCode 1420
versionName "0.14.20"
versionCode 1421
versionName "0.14.21"
ndkVersion '21.3.6528147'
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables.useSupportLibrary = true
Expand Down
12 changes: 6 additions & 6 deletions app/src/main/java/org/ole/planet/myplanet/model/RealmMyTeam.kt
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ open class RealmMyTeam : RealmObject() {
}

@JvmStatic
fun getResourceIds(teamId: String, realm: Realm): MutableList<String> {
fun getResourceIds(teamId: String?, realm: Realm): MutableList<String> {
val teams = realm.where(RealmMyTeam::class.java).equalTo("teamId", teamId).findAll()
val ids = mutableListOf<String>()
for (team in teams) {
Expand Down Expand Up @@ -239,8 +239,8 @@ open class RealmMyTeam : RealmObject() {
}

@JvmStatic
fun getTeamCreator(teamId: String, realm: Realm): String {
val teams = realm.where(RealmMyTeam::class.java).equalTo("teamId", teamId).findFirst()
fun getTeamCreator(teamId: String?, realm: Realm?): String {
val teams = realm?.where(RealmMyTeam::class.java)?.equalTo("teamId", teamId)?.findFirst()
return teams?.userId ?: ""
}

Expand Down Expand Up @@ -294,7 +294,7 @@ open class RealmMyTeam : RealmObject() {
}

@JvmStatic
fun isTeamLeader(teamId: String?, userId: String, realm: Realm): Boolean {
fun isTeamLeader(teamId: String?, userId: String?, realm: Realm): Boolean {
val team = realm.where(RealmMyTeam::class.java)
.equalTo("teamId", teamId)
.equalTo("docType", "membership")
Expand Down Expand Up @@ -322,7 +322,7 @@ open class RealmMyTeam : RealmObject() {
}

@JvmStatic
fun filterUsers(teamId: String, user: String, mRealm: Realm): MutableList<RealmUserModel> {
fun filterUsers(teamId: String?, user: String, mRealm: Realm): MutableList<RealmUserModel> {
val myteam = mRealm.where(RealmMyTeam::class.java).equalTo("teamId", teamId).findAll()
val list = mutableListOf<RealmUserModel>()
for (team in myteam) {
Expand Down Expand Up @@ -401,7 +401,7 @@ open class RealmMyTeam : RealmObject() {
}
}

fun requested(userId: String, mRealm: Realm): Boolean {
fun requested(userId: String?, mRealm: Realm): Boolean {
val m = mRealm.where(RealmMyTeam::class.java)
.equalTo("docType", "request")
.equalTo("teamId", _id)
Expand Down
18 changes: 11 additions & 7 deletions app/src/main/java/org/ole/planet/myplanet/model/RealmNews.kt
Original file line number Diff line number Diff line change
Expand Up @@ -199,16 +199,16 @@ open class RealmNews : RealmObject() {
}

@JvmStatic
fun createNews(map: HashMap<String?, String>, mRealm: Realm, user: RealmUserModel, imageUrls: RealmList<String>?): RealmNews {
fun createNews(map: HashMap<String?, String>, mRealm: Realm, user: RealmUserModel?, imageUrls: RealmList<String>?): RealmNews {
if (!mRealm.isInTransaction) mRealm.beginTransaction()
val news = mRealm.createObject(RealmNews::class.java, UUID.randomUUID().toString())
news.message = map["message"]
news.time = Date().time
news.createdOn = user.planetCode
news.createdOn = user?.planetCode
news.avatar = ""
news.docType = "message"
news.userName = user.name
news.parentCode = user.parentCode
news.userName = user?.name
news.parentCode = user?.parentCode
news.messagePlanetCode = map["messagePlanetCode"]
news.messageType = map["messageType"]
news.viewIn = getViewInJson(map)
Expand All @@ -217,9 +217,13 @@ open class RealmNews : RealmObject() {
} catch (e: Exception) {
e.printStackTrace()
}
news.userId = user.id
news.replyTo = if (map.containsKey("replyTo")) map["replyTo"] else ""
news.user = Gson().toJson(user.serialize())
news.userId = user?.id
news.replyTo = if (map.containsKey("replyTo")) {
map["replyTo"]
} else {
""
}
news.user = Gson().toJson(user?.serialize())
news.imageUrls = imageUrls
mRealm.commitTransaction()
return news
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,29 +28,35 @@ class AdapterFinance(private val context: Context, private val list: RealmResult
}

override fun onBindViewHolder(holder: ViewHolderFinance, position: Int) {
rowFinanceBinding.date.text = formatDate(list[position]!!.date, "MMM dd, yyyy")
rowFinanceBinding.note.text = list[position]!!.description
Utilities.log("Type " + list[position]!!.date)
if (TextUtils.equals(list[position]!!.type!!.lowercase(Locale.getDefault()), "debit")) {
rowFinanceBinding.debit.text = list[position]!!.amount.toString() + ""
rowFinanceBinding.credit.text = " -"
rowFinanceBinding.credit.setTextColor(Color.BLACK)
} else {
rowFinanceBinding.credit.text = list[position]!!.amount.toString() + ""
rowFinanceBinding.debit.text = " -"
rowFinanceBinding.debit.setTextColor(Color.BLACK)
list[position]?.let {
rowFinanceBinding.date.text = formatDate(it.date, "MMM dd, yyyy")
rowFinanceBinding.note.text = it.description
Utilities.log("Type " + it.date)
if (TextUtils.equals(it.type?.lowercase(Locale.getDefault()), "debit")) {
rowFinanceBinding.debit.text = "${it.amount}"
rowFinanceBinding.credit.text = " -"
rowFinanceBinding.credit.setTextColor(Color.BLACK)
} else {
rowFinanceBinding.credit.text = "${it.amount}"
rowFinanceBinding.debit.text = " -"
rowFinanceBinding.debit.setTextColor(Color.BLACK)
}
rowFinanceBinding.balance.text = getBalance(position)
updateBackgroundColor(rowFinanceBinding.llayout, position)
}
rowFinanceBinding.balance.text = getBalance(position) + ""
updateBackgroundColor(rowFinanceBinding.llayout, position)
}

private fun getBalance(position: Int): String {
var i = 0
var balance = 0
Utilities.log(position.toString() + "")
for (team in list) {
if ("debit".equals(team.type!!.lowercase(Locale.getDefault()), ignoreCase = true)) balance -= team.amount
else balance += team.amount
if ("debit".equals(team.type?.lowercase(Locale.getDefault()), ignoreCase = true)) {
balance -= team.amount
}
else {
balance += team.amount
}
if (i == position) break
i++
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,7 @@ class EnterpriseCalendarFragment : BaseTeamFragment() {
lateinit var start: Calendar
lateinit var end: Calendar

override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
fragmentEnterpriseCalendarBinding = FragmentEnterpriseCalendarBinding.inflate(inflater, container, false)
start = Calendar.getInstance()
end = Calendar.getInstance()
Expand All @@ -56,8 +54,11 @@ class EnterpriseCalendarFragment : BaseTeamFragment() {
if (requireArguments().getBoolean("fromLogin", false)) {
fragmentEnterpriseCalendarBinding.addEvent.visibility = View.GONE
} else if (user != null) {
if (user!!.isManager() || user!!.isLeader()) fragmentEnterpriseCalendarBinding.addEvent.visibility = View.VISIBLE
else fragmentEnterpriseCalendarBinding.addEvent.visibility = View.GONE
if (user?.isManager() == true || user?.isLeader() == true) {
fragmentEnterpriseCalendarBinding.addEvent.visibility = View.VISIBLE
} else {
fragmentEnterpriseCalendarBinding.addEvent.visibility = View.GONE
}
} else {
fragmentEnterpriseCalendarBinding.addEvent.visibility = View.GONE
}
Expand All @@ -71,51 +72,52 @@ class EnterpriseCalendarFragment : BaseTeamFragment() {
setTimePicker(addMeetupBinding.tvEndTime)

AlertDialog.Builder(requireActivity()).setView(addMeetupBinding.root)
.setPositiveButton("Save") { _, _ ->
val ttl = addMeetupBinding.etTitle.text.toString()
val desc = addMeetupBinding.etDescription.text.toString()
val loc = addMeetupBinding.etLocation.text.toString()
if (ttl.isEmpty()) {
Utilities.toast(activity, getString(R.string.title_is_required))
} else if (desc.isEmpty()) {
Utilities.toast(activity, getString(R.string.description_is_required))
} else {
if (!mRealm.isInTransaction) mRealm.beginTransaction()
val meetup =
mRealm.createObject(RealmMeetup::class.java, UUID.randomUUID().toString())
meetup.title = ttl
meetup.description = desc
meetup.meetupLocation = loc
meetup.creator = user?.id
meetup.startDate = start.timeInMillis
meetup.endDate = end.timeInMillis
meetup.endTime = addMeetupBinding.tvEndTime.text.toString()
meetup.startTime = addMeetupBinding.tvStartTime.text.toString()
val rb = addMeetupBinding.rgRecuring.findViewById<RadioButton>(addMeetupBinding.rgRecuring.checkedRadioButtonId)
if (rb != null) {
meetup.recurring = rb.text.toString()
}
val ob = JsonObject()
ob.addProperty("teams", teamId)
meetup.links = Gson().toJson(ob)
meetup.teamId = teamId
mRealm.commitTransaction()
Utilities.toast(activity, getString(R.string.meetup_added))
fragmentEnterpriseCalendarBinding.rvCalendar.adapter?.notifyDataSetChanged()
fragmentEnterpriseCalendarBinding.calendarView.notifyCalendarChanged()
}
}.setNegativeButton("Cancel", null).show()
.setPositiveButton("Save") { _, _ ->
val ttl = "${addMeetupBinding.etTitle.text}"
val desc = "${addMeetupBinding.etDescription.text}"
val loc = "${addMeetupBinding.etLocation.text}"
if (ttl.isEmpty()) {
Utilities.toast(activity, getString(R.string.title_is_required))
} else if (desc.isEmpty()) {
Utilities.toast(activity, getString(R.string.description_is_required))
} else {
if (!mRealm.isInTransaction) {
mRealm.beginTransaction()
}
val meetup = mRealm.createObject(RealmMeetup::class.java, "${UUID.randomUUID()}")
meetup.title = ttl
meetup.description = desc
meetup.meetupLocation = loc
meetup.creator = user?.id
meetup.startDate = start.timeInMillis
meetup.endDate = end.timeInMillis
meetup.endTime = "${addMeetupBinding.tvEndTime.text}"
meetup.startTime = "${addMeetupBinding.tvStartTime.text}"
val rb = addMeetupBinding.rgRecuring.findViewById<RadioButton>(addMeetupBinding.rgRecuring.checkedRadioButtonId)
if (rb != null) {
meetup.recurring = "${rb.text}"
}
val ob = JsonObject()
ob.addProperty("teams", teamId)
meetup.links = Gson().toJson(ob)
meetup.teamId = teamId
mRealm.commitTransaction()
Utilities.toast(activity, getString(R.string.meetup_added))
fragmentEnterpriseCalendarBinding.rvCalendar.adapter?.notifyDataSetChanged()
fragmentEnterpriseCalendarBinding.calendarView.notifyCalendarChanged()
}
}.setNegativeButton("Cancel", null).show()
}

private fun setDatePickerListener(view: TextView, date: Calendar?) {
val c = Calendar.getInstance()
view.setOnClickListener {

DatePickerDialog(requireActivity(), { _, year, monthOfYear, dayOfMonth ->
date!!.set(Calendar.YEAR, year)
date.set(Calendar.MONTH, monthOfYear)
date.set(Calendar.DAY_OF_MONTH, dayOfMonth)
view.text = TimeUtils.formatDate(date.timeInMillis, "yyyy-MM-dd")
date?.set(Calendar.YEAR, year)
date?.set(Calendar.MONTH, monthOfYear)
date?.set(Calendar.DAY_OF_MONTH, dayOfMonth)
view.text = date?.timeInMillis?.let { it1 -> TimeUtils.formatDate(it1, "yyyy-MM-dd") }
}, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)).show()

}
Expand All @@ -125,10 +127,9 @@ class EnterpriseCalendarFragment : BaseTeamFragment() {
val c = Calendar.getInstance()
time.setOnClickListener {
val timePickerDialog = TimePickerDialog(
activity, { _, hourOfDay, minute ->
time.text = String.format("%02d:%02d", hourOfDay, minute)
}, c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), true
)
activity, { _, hourOfDay, minute ->
time.text = String.format("%02d:%02d", hourOfDay, minute) },
c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), true)
timePickerDialog.show()
}

Expand All @@ -137,8 +138,7 @@ class EnterpriseCalendarFragment : BaseTeamFragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
Utilities.log(teamId)
list = mRealm.where(RealmMeetup::class.java).equalTo("teamId", teamId)
.greaterThanOrEqualTo("endDate", TimeUtils.currentDateLong()).findAll()
list = mRealm.where(RealmMeetup::class.java).equalTo("teamId", teamId).greaterThanOrEqualTo("endDate", TimeUtils.currentDateLong()).findAll()
fragmentEnterpriseCalendarBinding.rvCalendar.layoutManager = LinearLayoutManager(activity)
fragmentEnterpriseCalendarBinding.rvCalendar.adapter = AdapterCalendar(list)
fragmentEnterpriseCalendarBinding.calendarView.inDateStyle = InDateStyle.ALL_MONTHS
Expand All @@ -155,14 +155,17 @@ class EnterpriseCalendarFragment : BaseTeamFragment() {
override fun create(view: View) = MonthViewContainer(view)
override fun bind(container: MonthViewContainer, month: CalendarMonth) {
container.textView.setTextColor(ContextCompat.getColor(requireContext(), R.color.colorPrimaryDark))
container.textView.text =
"${month.yearMonth.month.name.lowercase(Locale.ROOT)
.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.ROOT) else it.toString() }} ${month.year}"
container.textView.text = "${month.yearMonth.month.name.lowercase(Locale.ROOT).replaceFirstChar {
if (it.isLowerCase()) {
it.titlecase(Locale.ROOT)
} else {
it.toString()
} }} ${month.year}"
}
}
}

fun setUpCalendar() {
private fun setUpCalendar() {

fragmentEnterpriseCalendarBinding.calendarView.dayBinder = object : DayBinder<DayViewContainer> {
override fun create(view: View) = DayViewContainer(view)
Expand All @@ -181,9 +184,7 @@ class EnterpriseCalendarFragment : BaseTeamFragment() {
}
if (event != null) {
container.textView.setOnClickListener {
DialogUtils.showAlert(
activity!!, event.title, event.description
)
DialogUtils.showAlert(context, event.title, event.description)
}
container.textView.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.colorPrimaryDark))
container.textView.setTextColor(ContextCompat.getColor(requireContext(), R.color.md_white_1000))
Expand All @@ -194,10 +195,8 @@ class EnterpriseCalendarFragment : BaseTeamFragment() {

private fun getEvent(time: Long): RealmMeetup? {
for (realmMeetup in list) {
if (time >= getTimeMills(realmMeetup.startDate, false) && time <= getTimeMills(
realmMeetup.endDate, true
)
) {
if (time >= getTimeMills(realmMeetup.startDate, false)
&& time <= getTimeMills(realmMeetup.endDate, true)) {
return realmMeetup
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ class FinanceFragment : BaseTeamFragment() {
private fun calculateTotal(list: List<RealmMyTeam>?) {
var debit = 0
var credit = 0
for (team in list!!) {
for (team in list ?: emptyList()) {
if ("credit".equals(team.type?.lowercase(Locale.getDefault()), ignoreCase = true)) {
credit += team.amount
} else {
Expand All @@ -129,8 +129,8 @@ class FinanceFragment : BaseTeamFragment() {
.setPositiveButton("Submit") { _: DialogInterface?, _: Int ->
val type = addTransactionBinding.spnType.selectedItem.toString()
Utilities.log("$type type")
val note = addTransactionBinding.tlNote.editText!!.text.toString().trim { it <= ' ' }
val amount = addTransactionBinding.tlAmount.editText!!.text.toString().trim { it <= ' ' }
val note = "${addTransactionBinding.tlNote.editText?.text}".trim { it <= ' ' }
val amount = "${addTransactionBinding.tlAmount.editText?.text}".trim { it <= ' ' }
if (note.isEmpty()) {
Utilities.toast(activity, getString(R.string.note_is_required))
} else if (amount.isEmpty()) {
Expand All @@ -139,7 +139,7 @@ class FinanceFragment : BaseTeamFragment() {
Utilities.toast(activity, getString(R.string.date_is_required))
} else {
fRealm.executeTransactionAsync(Realm.Transaction { realm: Realm ->
createTransactionObject(realm, type, note, amount, date!!)
createTransactionObject(realm, type, note, amount, date)
}, Realm.Transaction.OnSuccess {
Utilities.toast(activity, getString(R.string.transaction_added))
adapterFinance?.notifyDataSetChanged()
Expand All @@ -149,11 +149,15 @@ class FinanceFragment : BaseTeamFragment() {
}.setNegativeButton("Cancel", null).show()
}

private fun createTransactionObject(realm: Realm, type: String?, note: String, amount: String, date: Calendar) {
private fun createTransactionObject(realm: Realm, type: String?, note: String, amount: String, date: Calendar?) {
val team = realm.createObject(RealmMyTeam::class.java, UUID.randomUUID().toString())
team.status = "active"
team.date = date.timeInMillis
if (type != null) team.teamType = type
if (date != null) {
team.date = date.timeInMillis
}
if (type != null) {
team.teamType = type
}
team.type = type
team.description = note
team.teamId = teamId
Expand Down
Loading

0 comments on commit 3b76407

Please sign in to comment.