Skip to content

Commit

Permalink
Merge pull request #249 from effectivemade/backendApp/feature/events_…
Browse files Browse the repository at this point in the history
…converters_refactoring

Backend event converters refactoring
  • Loading branch information
zavyalov-daniil authored Apr 20, 2024
2 parents e7abdc0 + 0a6fbb8 commit 7773a21
Show file tree
Hide file tree
Showing 13 changed files with 337 additions and 144 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ object BookingConstants {
val WORKSPACE_CALENDAR: String = System.getenv("WORKSPACE_CALENDAR")
?: config.propertyOrNull("calendar.workspaceCalendar")?.getString()
?: throw Exception("Environment and config file does not contain workspace Google calendar id")

val DEFAULT_TIMEZONE_ID: String = config.propertyOrNull("calendar.defaultTimezone")?.getString()
?: throw Exception("Config file does not contain default timezone id")
const val UNTIL_FORMAT = "yyyyMMdd"
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import java.util.*
*
* Performs own database queries to user and workspace entities
*/
@Deprecated("Used to convert into db events. We don't store events into database.",ReplaceWith("GoogleCalendarConverter"), DeprecationLevel.WARNING)
class BookingRepositoryConverter(private val database: Database,
private val workspaceConverter: WorkspaceRepositoryConverter,
private val userConverter: UserModelEntityConverter,
Expand Down

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
package office.effective.features.booking.converters

import model.RecurrenceDTO
import office.effective.common.constants.BookingConstants
import office.effective.model.Ending
import office.effective.model.Recurrence
import office.effective.model.RecurrenceModel
import java.text.SimpleDateFormat
import java.util.*

//TODO: all converters should be classes
/**
Expand Down Expand Up @@ -43,4 +48,23 @@ object RecurrenceConverter {
dto.interval, dto.freq, dto.count, dto.until, dto.byDay, dto.byMonth, dto.byYearDay, dto.byHour
)
}

fun recurrenceToModel(recurrence: Recurrence): RecurrenceModel {
return RecurrenceModel(
interval =recurrence.interval,
freq =recurrence.freq.toString(),
count = if (recurrence.ending is Ending.Count) recurrence.ending.value else null,
until = if (recurrence.ending is Ending.Until) parseUntil(recurrence.ending.value) else null,
byDay = recurrence.byDay,
byMonth = recurrence.byMonth,
byYearDay = recurrence.byYearDay,
byHour = recurrence.byHour
)
}

private fun parseUntil(untilStr: String): Long {
val date: Date = SimpleDateFormat(BookingConstants.UNTIL_FORMAT).parse(untilStr)
println("UNTIL: $untilStr")
return date.time
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,18 @@ package office.effective.features.booking.di
import office.effective.features.booking.converters.BookingFacadeConverter
import office.effective.features.booking.converters.BookingRepositoryConverter
import office.effective.features.booking.facade.BookingFacade
import office.effective.features.booking.repository.BookingCalendarRepository
import office.effective.features.booking.repository.BookingMeetingRepository
import office.effective.features.booking.service.BookingService
import office.effective.features.booking.converters.GoogleCalendarConverter
import office.effective.features.booking.repository.BookingWorkspaceRepository
import office.effective.features.booking.repository.BookingRegularRepository
import office.effective.serviceapi.IBookingService
import org.koin.dsl.module

val bookingDiModule = module(createdAtStart = true) {
single { BookingRepositoryConverter(get(), get(), get(), get()) }
single { GoogleCalendarConverter(get(), get(), get(), get(), get(), get(), get()) }
single { BookingWorkspaceRepository(get(), get(), get(), get()) }
single { BookingCalendarRepository(get(), get(), get(), get()) }
single { BookingRegularRepository(get(), get(), get(), get()) }
single { BookingMeetingRepository(get(), get(), get(), get()) }
single<IBookingService> { BookingService(get(), get(), get(), get()) }
single { BookingFacadeConverter(get(), get()) }
single { BookingFacade(get(), get(), get(), get()) }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import com.google.api.client.googleapis.json.GoogleJsonResponseException
import com.google.api.client.util.DateTime
import com.google.api.services.calendar.Calendar
import com.google.api.services.calendar.model.Event
import kotlinx.coroutines.*
import office.effective.common.constants.BookingConstants
import office.effective.common.exception.InstanceNotFoundException
import office.effective.common.exception.MissingIdException
Expand All @@ -25,7 +24,7 @@ import java.util.concurrent.Executors
*
* Filters out all events that have a start less than the calendar.minTime from application.conf
*/
class BookingCalendarRepository(
class BookingMeetingRepository(
private val calendarIdsRepository: CalendarIdsRepository,
private val userRepository: UserRepository,
private val calendar: Calendar,
Expand Down Expand Up @@ -88,7 +87,7 @@ class BookingCalendarRepository(
override fun findById(bookingId: String): Booking? {
logger.debug("[findById] retrieving a booking with id={}", bookingId)
val event: Event? = findByCalendarIdAndBookingId(bookingId)
return event?.let { googleCalendarConverter.toBookingModel(it) }
return event?.let { googleCalendarConverter.toBookingModelForMeetingWorkspace(it) }
}

/**
Expand Down Expand Up @@ -152,7 +151,7 @@ class BookingCalendarRepository(
val eventsWithWorkspace = basicQuery(eventRangeFrom, eventRangeTo, getSingleEvents, workspaceCalendarId)
.execute().items

return eventsWithWorkspace.toList().map { googleCalendarConverter.toBookingModel(it) }
return eventsWithWorkspace.toList().map { googleCalendarConverter.toBookingModelForMeetingWorkspace(it) }
}

/**
Expand Down Expand Up @@ -266,7 +265,7 @@ class BookingCalendarRepository(
val result = mutableListOf<Booking>()
for (event in eventsWithUser) {
if (checkEventOrganizer(event, userEmail)) {
result.add(googleCalendarConverter.toBookingModel(event))
result.add(googleCalendarConverter.toBookingModelForMeetingWorkspace(event))
} else {
logger.trace("[findAllByOwnerId] filtered out event: {}", event)
}
Expand Down Expand Up @@ -307,7 +306,7 @@ class BookingCalendarRepository(
val result = mutableListOf<Booking>()
for (event in eventsWithUserAndWorkspace) {
if (checkEventOrganizer(event, userEmail)) {
result.add(googleCalendarConverter.toBookingModel(event))
result.add(googleCalendarConverter.toBookingModelForMeetingWorkspace(event))
} else {
logger.trace("[findAllByOwnerAndWorkspaceId] filtered out event: {}", event)
}
Expand All @@ -332,7 +331,7 @@ class BookingCalendarRepository(
)
val calendars: List<String> = calendarIdsRepository.findAllCalendarsId()
val events: List<Event> = getAllEvents(calendars, eventRangeFrom, eventRangeTo)
return events.map { googleCalendarConverter.toBookingModel(it) }
return events.map { googleCalendarConverter.toBookingModelForMeetingWorkspace(it) }
}

/**
Expand All @@ -348,11 +347,11 @@ class BookingCalendarRepository(
val workspaceCalendar = calendarIdsRepository.findByWorkspace(
booking.workspace.id ?: throw MissingIdException("Missing workspace id")
)
val event = googleCalendarConverter.toGoogleEvent(booking)
val event = googleCalendarConverter.toGoogleWorkspaceMeetingEvent(booking)

val savedEvent = calendar.Events().insert(defaultCalendar, event).execute()
if (checkBookingAvailable(savedEvent, workspaceCalendar)) {
val savedBooking = googleCalendarConverter.toBookingModel(savedEvent)
val savedBooking = googleCalendarConverter.toBookingModelForMeetingWorkspace(savedEvent)
logger.trace("[save] saved booking: {}", savedBooking)
return savedBooking
} else {
Expand Down Expand Up @@ -383,13 +382,13 @@ class BookingCalendarRepository(
WorkspaceBookingEntity::class, "Booking with id $bookingId not wound"
)
logger.trace("[update] previous version of event: {}", previousVersionOfEvent)
val eventOnUpdate = googleCalendarConverter.toGoogleEvent(booking)
val eventOnUpdate = googleCalendarConverter.toGoogleWorkspaceMeetingEvent(booking)

val updatedEvent: Event = calendarEvents.update(defaultCalendar, bookingId, eventOnUpdate).execute()

val sequence = updatedEvent.sequence
if (checkBookingAvailable(updatedEvent, workspaceCalendar)) {
val updatedBooking = googleCalendarConverter.toBookingModel(updatedEvent)
val updatedBooking = googleCalendarConverter.toBookingModelForMeetingWorkspace(updatedEvent)
logger.trace("[update] updated booking: {}", updatedBooking)
return updatedBooking
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@ import java.time.Instant
import java.util.*

/**
* Class that executes Google calendar queries for booking workspaces
* Class that executes Google calendar queries for booking regular workspaces
*
* Filters out all events that have a start less than the calendar.minTime from application.conf
*/
class BookingWorkspaceRepository(
class BookingRegularRepository(
private val calendar: Calendar,
private val googleCalendarConverter: GoogleCalendarConverter,
private val workspaceRepository: WorkspaceRepository,
Expand Down Expand Up @@ -249,7 +249,7 @@ class BookingWorkspaceRepository(
WorkspaceEntity::class, "User with id $workspaceId not wound"
)
}
val event = googleCalendarConverter.toGoogleWorkspaceEvent(booking)
val event = googleCalendarConverter.toGoogleWorkspaceRegularEvent(booking)

logger.trace("[save] booking to save: {}", event)
val savedEvent = calendar.Events().insert(workspaceCalendar, event).execute()
Expand Down Expand Up @@ -285,7 +285,7 @@ class BookingWorkspaceRepository(
WorkspaceBookingEntity::class, "Booking with id $bookingId not wound"
)
logger.trace("[update] previous version of event: {}", previousVersionOfEvent)
val eventOnUpdate = googleCalendarConverter.toGoogleWorkspaceEvent(booking)
val eventOnUpdate = googleCalendarConverter.toGoogleWorkspaceRegularEvent(booking)

logger.trace("[update] new version of event: {}", eventOnUpdate)
val updatedEvent: Event = calendarEvents.update(workspaceCalendar, bookingId, eventOnUpdate).execute()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import office.effective.model.Workspace
*
* TODO: should implements IBookingRepository interface (add minStartTime and maxStartTime to queries)
*/
@Deprecated("Used to store events inside database. We don't store events into database.",ReplaceWith("BookingCalendarRepository"), DeprecationLevel.ERROR)
class BookingRepository(private val database: Database,
private val converter: BookingRepositoryConverter,
private val uuidValidator: UuidValidator){
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ package office.effective.features.booking.service

import office.effective.common.exception.InstanceNotFoundException
import office.effective.common.exception.MissingIdException
import office.effective.features.booking.repository.BookingCalendarRepository
import office.effective.features.booking.repository.BookingWorkspaceRepository
import office.effective.features.booking.repository.BookingMeetingRepository
import office.effective.features.booking.repository.BookingRegularRepository
import office.effective.features.booking.repository.WorkspaceBookingEntity
import office.effective.features.user.repository.UserEntity
import office.effective.features.user.repository.UserRepository
Expand All @@ -16,12 +16,12 @@ import java.util.UUID
/**
* Class that implements the [IBookingService] methods
*
* Uses [BookingCalendarRepository] for operations with meeting rooms.
* Uses [BookingWorkspaceRepository] for operations with workspaces.
* Uses [BookingMeetingRepository] for operations with meeting rooms.
* Uses [BookingRegularRepository] for operations with workspaces.
*/
class BookingService(
private val bookingRepository: BookingCalendarRepository,
private val bookingWorkspaceRepository: BookingWorkspaceRepository,
private val bookingMeetingRepository: BookingMeetingRepository,
private val bookingRegularRepository: BookingRegularRepository,
private val userRepository: UserRepository,
private val workspaceRepository: WorkspaceRepository,
) : IBookingService {
Expand All @@ -35,7 +35,7 @@ class BookingService(
* @author Daniil Zavyalov
*/
override fun existsById(id: String): Boolean {
return bookingRepository.existsById(id) || bookingWorkspaceRepository.existsById(id)
return bookingMeetingRepository.existsById(id) || bookingRegularRepository.existsById(id)
}

/**
Expand All @@ -45,8 +45,8 @@ class BookingService(
* @author Daniil Zavyalov
*/
override fun deleteById(id: String) {
bookingRepository.deleteById(id)
bookingWorkspaceRepository.deleteById(id)
bookingMeetingRepository.deleteById(id)
bookingRegularRepository.deleteById(id)
}

/**
Expand All @@ -57,8 +57,8 @@ class BookingService(
* @author Daniil Zavyalov
*/
override fun findById(id: String): Booking? {
val booking = bookingRepository.findById(id)
?: bookingWorkspaceRepository.findById(id)
val booking = bookingMeetingRepository.findById(id)
?: bookingRegularRepository.findById(id)
?: return null
val userIds = mutableSetOf<UUID>()
for (participant in booking.participants) {
Expand Down Expand Up @@ -101,14 +101,14 @@ class BookingService(
)

if (workspace.tag == "meeting") {
bookingRepository.findAllByOwnerAndWorkspaceId(
bookingMeetingRepository.findAllByOwnerAndWorkspaceId(
userId,
workspaceId,
bookingRangeFrom,
bookingRangeTo
)
} else {
bookingWorkspaceRepository.findAllByOwnerAndWorkspaceId(
bookingRegularRepository.findAllByOwnerAndWorkspaceId(
userId,
workspaceId,
bookingRangeFrom,
Expand All @@ -122,13 +122,13 @@ class BookingService(
UserEntity::class, "User with id $userId not found", userId
)

val bookings = bookingRepository.findAllByOwnerId(
val bookings = bookingMeetingRepository.findAllByOwnerId(
userId,
bookingRangeFrom,
bookingRangeTo
).toMutableList()
bookings.addAll(
bookingWorkspaceRepository.findAllByOwnerId(
bookingRegularRepository.findAllByOwnerId(
userId,
bookingRangeFrom,
bookingRangeTo
Expand All @@ -144,13 +144,13 @@ class BookingService(
)

if (workspace.tag == "meeting") {
bookingRepository.findAllByWorkspaceId(
bookingMeetingRepository.findAllByWorkspaceId(
workspaceId,
bookingRangeFrom,
bookingRangeTo
)
} else {
bookingWorkspaceRepository.findAllByWorkspaceId(
bookingRegularRepository.findAllByWorkspaceId(
workspaceId,
bookingRangeFrom,
bookingRangeTo
Expand All @@ -160,8 +160,8 @@ class BookingService(
}

else -> {
val bookings = bookingRepository.findAll(bookingRangeFrom, bookingRangeTo).toMutableList()
bookings.addAll(bookingWorkspaceRepository.findAll(bookingRangeFrom, bookingRangeTo))
val bookings = bookingMeetingRepository.findAll(bookingRangeFrom, bookingRangeTo).toMutableList()
bookings.addAll(bookingRegularRepository.findAll(bookingRangeFrom, bookingRangeTo))
bookings
}
}
Expand Down Expand Up @@ -264,10 +264,10 @@ class BookingService(
?: throw InstanceNotFoundException(WorkspaceBookingEntity::class, "Workspace with id $workspaceId not wound")
return if (workspace.tag == "meeting") {
logger.error("Saving meeting room booking")
bookingRepository.save(booking)
bookingMeetingRepository.save(booking)
} else {
logger.error("Saving workspace booking")
bookingWorkspaceRepository.save(booking)
bookingRegularRepository.save(booking)
}
}

Expand All @@ -285,10 +285,10 @@ class BookingService(
?: throw InstanceNotFoundException(WorkspaceBookingEntity::class, "Workspace with id $workspaceId not wound")
return if (workspace.tag == "meeting") {
logger.error("Updating meeting room booking")
bookingRepository.update(booking)
bookingMeetingRepository.update(booking)
} else {
logger.error("Updating workspace booking")
bookingWorkspaceRepository.update(booking)
bookingRegularRepository.update(booking)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,34 @@ class UserRepository(
return entity?.let { converter.entityToModel(entity, integrations) }
}

/**
* Retrieves a user models by email list
*
* @return [UserModel]
* @throws InstanceNotFoundException if user with the given email doesn't exist in database
* @author Daniil Zavyalov
*/
fun findAllByEmail(email: List<String>): List<UserModel> {
logger.debug("[findAllByEmail] retrieving a users with specified emails {}", email)
val userEntities: MutableList<UserEntity> = mutableListOf()
val usersIds: MutableList<UUID> = mutableListOf()
val result: MutableList<UserModel> = mutableListOf()
db.from(Users)
.innerJoin(right = UsersTags, on = UsersTags.id eq Users.tagId)
.select()
.where { Users.email inList email }
.forEach { raw ->
val user: UserEntity = Users.createEntity(raw)
usersIds.add(user.id)
userEntities.add(user)
}
val integrations = findAllIntegrationsByUserIds(usersIds)
userEntities.forEach { userEntity ->
result.add(converter.entityToModel(userEntity, integrations[userEntity.id]))
}
return result
}

/**
* Returns Integration entity by id
* @return [IntegrationEntity]
Expand Down Expand Up @@ -178,7 +206,8 @@ class UserRepository(
val result = hashMapOf<UUID, MutableSet<IntegrationModel>>()
db.from(UsersIntegrations)
.innerJoin(right = Integrations, on = UsersIntegrations.integrationId eq Integrations.id).select()
.where { UsersIntegrations.userId inList ids }.forEach { row ->
.where { UsersIntegrations.userId inList ids }
.forEach { row ->
val userId: UUID = row[UsersIntegrations.userId] ?: return@forEach
val integration = integrationConverter.entityToModel(
Integrations.createEntity(row), row[UsersIntegrations.valueStr] ?: ""
Expand Down
Loading

0 comments on commit 7773a21

Please sign in to comment.