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

HAI-1844: Create hankekayttaja instance for Hanke perustaja #390

Merged
merged 13 commits into from
Aug 31, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -455,14 +455,14 @@ class HankeControllerITests(@Autowired override val mockMvc: MockMvc) : Controll
@Test
fun `Without permission returns 404`() {
val hanke = HankeFactory.create(version = null)
every { hankeService.loadHanke(HANKE_TUNNUS) } returns hanke
every { hankeService.findHankeOrThrow(HANKE_TUNNUS) } returns hanke
every { permissionService.hasPermission(hankeId, USERNAME, PermissionCode.EDIT) }
.returns(false)

put(url, hanke).andExpect(status().isNotFound).andExpect(hankeError(HankeError.HAI1001))

verifySequence {
hankeService.loadHanke(HANKE_TUNNUS)
hankeService.findHankeOrThrow(HANKE_TUNNUS)
permissionService.hasPermission(hankeId, USERNAME, PermissionCode.EDIT)
}
}
Expand All @@ -476,7 +476,7 @@ class HankeControllerITests(@Autowired override val mockMvc: MockMvc) : Controll
modifiedBy = USERNAME
status = HankeStatus.PUBLIC
}
every { hankeService.loadHanke(HANKE_TUNNUS) } returns HankeFactory.create()
every { hankeService.findHankeOrThrow(HANKE_TUNNUS) } returns HankeFactory.create()
every { permissionService.hasPermission(hankeId, USERNAME, PermissionCode.EDIT) }
.returns(true)
every { hankeService.updateHanke(any()) }.returns(updatedHanke)
Expand All @@ -488,7 +488,7 @@ class HankeControllerITests(@Autowired override val mockMvc: MockMvc) : Controll
.andExpect(jsonPath("$.status").value(HankeStatus.PUBLIC.name))

verifySequence {
hankeService.loadHanke(HANKE_TUNNUS)
hankeService.findHankeOrThrow(HANKE_TUNNUS)
permissionService.hasPermission(hankeId, USERNAME, PermissionCode.EDIT)
hankeService.updateHanke(any())
disclosureLogService.saveDisclosureLogsForHanke(updatedHanke, USERNAME)
Expand Down Expand Up @@ -525,7 +525,7 @@ class HankeControllerITests(@Autowired override val mockMvc: MockMvc) : Controll
expectedHanke.alueet[0].haittaAlkuPvm = expectedDateAlku
expectedHanke.alueet[0].haittaLoppuPvm = expectedDateLoppu
val expectedContent = expectedHanke.toJsonString()
every { hankeService.loadHanke(HANKE_TUNNUS) } returns hankeToBeUpdated
every { hankeService.findHankeOrThrow(HANKE_TUNNUS) } returns hankeToBeUpdated
every {
permissionService.hasPermission(expectedHanke.id!!, USERNAME, PermissionCode.EDIT)
} returns true
Expand All @@ -543,7 +543,7 @@ class HankeControllerITests(@Autowired override val mockMvc: MockMvc) : Controll
) // Note, here as string, not the enum.

verifySequence {
hankeService.loadHanke(HANKE_TUNNUS)
hankeService.findHankeOrThrow(HANKE_TUNNUS)
permissionService.hasPermission(expectedHanke.id!!, USERNAME, PermissionCode.EDIT)
hankeService.updateHanke(any())
disclosureLogService.saveDisclosureLogsForHanke(expectedHanke, USERNAME)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ import fi.hel.haitaton.hanke.application.CableReportWithoutHanke
import fi.hel.haitaton.hanke.domain.Hanke
import fi.hel.haitaton.hanke.domain.HankeYhteystieto
import fi.hel.haitaton.hanke.domain.Hankealue
import fi.hel.haitaton.hanke.domain.Perustaja
import fi.hel.haitaton.hanke.domain.YhteystietoTyyppi.YHTEISO
import fi.hel.haitaton.hanke.domain.YhteystietoTyyppi.YKSITYISHENKILO
import fi.hel.haitaton.hanke.domain.YhteystietoTyyppi.YRITYS
Expand All @@ -29,7 +28,6 @@ import fi.hel.haitaton.hanke.factory.HankeFactory.Companion.withGeneratedOmistaj
import fi.hel.haitaton.hanke.factory.HankeFactory.Companion.withGeneratedOmistajat
import fi.hel.haitaton.hanke.factory.HankeFactory.Companion.withGeneratedRakennuttaja
import fi.hel.haitaton.hanke.factory.HankeFactory.Companion.withHankealue
import fi.hel.haitaton.hanke.factory.HankeFactory.Companion.withPerustaja
import fi.hel.haitaton.hanke.factory.HankeFactory.Companion.withYhteystiedot
import fi.hel.haitaton.hanke.factory.HankealueFactory
import fi.hel.haitaton.hanke.geometria.Geometriat
Expand Down Expand Up @@ -117,8 +115,7 @@ class HankeServiceITests : DatabaseTest() {

@Test
fun `create Hanke with full data set succeeds and returns a new domain object with the correct values`() {
val hanke: Hanke =
getATestHanke().withYhteystiedot { it.id = null }.withPerustaja().withHankealue()
val hanke: Hanke = getATestHanke().withYhteystiedot { it.id = null }.withHankealue()
corvidian marked this conversation as resolved.
Show resolved Hide resolved

val datetimeAlku = hanke.alueet[0].haittaAlkuPvm // nextyear.2.20 23:45:56Z
val datetimeLoppu = hanke.alueet[0].haittaLoppuPvm // nextyear.2.21 0:12:34Z
Expand Down Expand Up @@ -149,7 +146,6 @@ class HankeServiceITests : DatabaseTest() {
assertThat(returnedHanke.loppuPvm).isEqualTo(expectedDateLoppu)
assertThat(returnedHanke.vaihe).isEqualTo(Vaihe.SUUNNITTELU)
assertThat(returnedHanke.suunnitteluVaihe).isEqualTo(SuunnitteluVaihe.RAKENNUS_TAI_TOTEUTUS)
assertThat(returnedHanke.perustaja).isEqualTo(Perustaja("Pertti Perustaja", "[email protected]"))
assertThat(returnedHanke.tyomaaKatuosoite).isEqualTo("Testikatu 1")
assertThat(returnedHanke.tyomaaTyyppi).contains(TyomaaTyyppi.VESI, TyomaaTyyppi.MUU)
assertThat(returnedHanke.alueet[0].kaistaHaitta)
Expand Down Expand Up @@ -210,14 +206,16 @@ class HankeServiceITests : DatabaseTest() {
assertThat(rakennuttaja.id).isNotEqualTo(firstId)
assertThat(toteuttaja.id).isNotEqualTo(firstId)
assertThat(toteuttaja.id).isNotEqualTo(rakennuttaja.id)
assertThat(hankeKayttajaRepository.findAll()).hasSize(5) // contacts + Hanke perustaja
assertThat(hankeKayttajaRepository.findAll()).hasSize(4)
assertThat(kayttajaTunnisteRepository.findAll()).hasSize(4)
}

@Test
fun `create Hanke with without perustaja and contacts does not create hanke users`() {
hankeService.createHanke(getATestHanke())
val hanke = hankeService.createHanke(getATestHanke())

val hankeEntity = hankeRepository.findByHankeTunnus(hanke.hankeTunnus!!)!!
assertThat(hankeEntity.perustaja).isNull()
assertThat(hankeKayttajaRepository.findAll()).isEmpty()
assertThat(kayttajaTunnisteRepository.findAll()).isEmpty()
}
Expand Down Expand Up @@ -952,10 +950,11 @@ class HankeServiceITests : DatabaseTest() {
val application = applications.first()
assertThat(hanke.hankeTunnus).isEqualTo(application.hankeTunnus)
assertThat(hanke.nimi).isEqualTo(application.applicationData.name)
assertThat(hanke.perustaja)
.isEqualTo(Perustaja("Teppo Testihenkilö", "[email protected]"))
assertThat(application.applicationData.name)
.isEqualTo(inputApplication.applicationData.name)
val hankePerustaja = hankeRepository.findByHankeTunnus(hanke.hankeTunnus!!)?.perustaja
assertThat(hankePerustaja?.nimi).isEqualTo("Teppo Testihenkilö")
assertThat(hankePerustaja?.email).isEqualTo("[email protected]")
}
}

Expand Down Expand Up @@ -1394,7 +1393,6 @@ class HankeServiceITests : DatabaseTest() {
TemplateData(
updatedHanke.id!!,
updatedHanke.hankeTunnus!!,
updatedHanke.perustaja != null,
updatedHanke.alueet[0].id,
updatedHanke.alueet[0].geometriat?.id,
hankeVersion = 1,
Expand Down Expand Up @@ -1520,7 +1518,6 @@ class HankeServiceITests : DatabaseTest() {
data class TemplateData(
val hankeId: Int,
val hankeTunnus: String,
val hankePerustaja: Boolean = false,
val alueId: Int? = null,
val geometriaId: Int? = null,
val geometriaVersion: Int = 0,
Expand Down Expand Up @@ -1550,7 +1547,6 @@ class HankeServiceITests : DatabaseTest() {
TemplateData(
hanke.id!!,
hanke.hankeTunnus!!,
hanke.perustaja != null,
alue?.id,
alue?.geometriat?.id,
geometriaVersion,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,6 @@
"version": {{hankeVersion}},
"generated": false,
"tyomaaKatuosoite": "Testikatu 1",
{{#hankkeenPerustaja}}
"perustaja": {
"nimi": "Pertti Perustaja",
"email": "[email protected]"
},
{{/hankkeenPerustaja}}
{{^hankkeenPerustaja}}
"perustaja": null,
{{/hankkeenPerustaja}}
"tyomaaTyyppi": [
"MUU",
"VESI"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,6 @@
"version": {{hankeVersion}},
"generated": false,
"tyomaaKatuosoite": "Testikatu 1",
{{#hankkeenPerustaja}}
"perustaja": {
"nimi": "Pertti Perustaja",
"email": "[email protected]"
},
{{/hankkeenPerustaja}}
{{^hankkeenPerustaja}}
"perustaja": null,
{{/hankkeenPerustaja}}
"tyomaaTyyppi": [
"MUU",
"VESI"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ class HankeController(
if (hanke == null) {
throw HankeArgumentException("No hanke given when creating hanke")
}
val sanitizedHanke = hanke.copy(id = null, generated = false, perustaja = null)
val sanitizedHanke = hanke.copy(id = null, generated = false)

val userId = currentUserId()
logger.info { "Creating Hanke for user $userId: ${hanke.toLogString()} " }
Expand Down Expand Up @@ -235,13 +235,9 @@ class HankeController(

logger.info { "Updating Hanke: ${hanke.toLogString()}" }

val existingHanke =
hankeService.loadHanke(hankeTunnus)?.also {
it.verifyUserAuthorization(currentUserId(), PermissionCode.EDIT)
}
?: throw HankeNotFoundException(hankeTunnus)

existingHanke.validateUpdatable(hanke, hankeTunnus)
val existingHanke = hankeService.findHankeOrThrow(hankeTunnus)
validateUpdatable(existing = existingHanke, updated = hanke, hankeTunnus)
existingHanke.verifyUserAuthorization(currentUserId(), PermissionCode.EDIT)

val updatedHanke = hankeService.updateHanke(hanke)
logger.info { "Updated hanke ${updatedHanke.hankeTunnus}." }
Expand Down Expand Up @@ -309,12 +305,15 @@ class HankeController(
}
}

private fun Hanke.validateUpdatable(updatedHanke: Hanke, hankeTunnusFromPath: String) {
if (hankeTunnusFromPath != updatedHanke.hankeTunnus) {
throw HankeArgumentException("Hanketunnus not given or doesn't match the hanke data")
}
if (perustaja != null && perustaja != updatedHanke.perustaja) {
throw HankeArgumentException("Updating perustaja not allowed.")
private fun validateUpdatable(existing: Hanke, updated: Hanke, hankeTunnusFromPath: String) {
val tunnusMatch =
listOf(existing.hankeTunnus, updated.hankeTunnus).all { it == hankeTunnusFromPath }
corvidian marked this conversation as resolved.
Show resolved Hide resolved

if (!tunnusMatch) {
throw HankeArgumentException(
"Hanketunnus mismatch. (Existing=${existing.hankeTunnus}, Updated=${updated.hankeTunnus}, " +
"Path=$hankeTunnusFromPath)"
)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -113,11 +113,11 @@ open class HankeServiceImpl(
override fun loadHankkeetByIds(ids: List<Int>) =
hankeRepository.findAllById(ids).map { createHankeDomainObjectFromEntity(it) }

/** @return a new Hanke instance with the added and possibly modified values. */
@Transactional
override fun createHanke(hanke: Hanke): Hanke {
// TODO: Only create that hanke-tunnus if a specific set of fields are non-empty/set.
override fun createHanke(hanke: Hanke): Hanke =
createHankeInternal(hanke = hanke, perustaja = null)

private fun createHankeInternal(hanke: Hanke, perustaja: Perustaja?): Hanke {
val userId = currentUserId()

val entity = HankeEntity()
Expand All @@ -128,6 +128,8 @@ open class HankeServiceImpl(
entity.hankeTunnus = hanketunnus
hanke.hankeTunnus = hanketunnus

entity.perustaja = perustaja?.toEntity()

// Copy values from the incoming domain object, and set some internal fields:
copyNonNullHankeFieldsToEntity(hanke, entity)

Expand All @@ -153,8 +155,8 @@ open class HankeServiceImpl(

postProcessAndSaveLogging(loggingEntryHolder, savedHankeEntity, userId)

return createHankeDomainObjectFromEntity(entity).also {
initAccessForCreatedHanke(it, userId)
return createHankeDomainObjectFromEntity(savedHankeEntity).also {
initAccessForCreatedHanke(it, savedHankeEntity.perustaja, userId)
hankeLoggingService.logCreate(it, userId)
}
}
Expand Down Expand Up @@ -242,12 +244,16 @@ open class HankeServiceImpl(
!applicationService.isStillPending(it)
}

private fun initAccessForCreatedHanke(hanke: Hanke, userId: String) {
private fun initAccessForCreatedHanke(
hanke: Hanke,
perustaja: PerustajaEntity?,
userId: String
) {
val hankeId = hanke.id!!
val permissionAll = permissionService.setPermission(hankeId, userId, Role.KAIKKI_OIKEUDET)

hanke.perustaja?.let { hankeKayttajaService.addHankeFounder(hankeId, it, permissionAll) }

perustaja?.let {
hankeKayttajaService.addHankeFounder(hankeId, it.toDomainObject(), permissionAll)
corvidian marked this conversation as resolved.
Show resolved Hide resolved
}
hankeKayttajaService.saveNewTokensFromHanke(hanke)
}

Expand Down Expand Up @@ -345,7 +351,6 @@ open class HankeServiceImpl(
if (hankeEntity.modifiedAt != null) ZonedDateTime.of(hankeEntity.modifiedAt, TZ_UTC)
else null,
hankeEntity.status,
hankeEntity.perustaja?.toDomainObject(),
hankeEntity.generated,
)

Expand Down Expand Up @@ -571,8 +576,6 @@ open class HankeServiceImpl(
hanke.onYKTHanke?.let { entity.onYKTHanke = hanke.onYKTHanke }
hanke.nimi?.let { entity.nimi = hanke.nimi }
hanke.kuvaus?.let { entity.kuvaus = hanke.kuvaus }

hanke.perustaja?.let { entity.perustaja = it.toEntity() }
entity.generated = hanke.generated
hanke.vaihe?.let { entity.vaihe = hanke.vaihe }
hanke.suunnitteluVaihe?.let { entity.suunnitteluVaihe = hanke.suunnitteluVaihe }
Expand Down Expand Up @@ -944,7 +947,7 @@ open class HankeServiceImpl(
* - Perustaja generated from application data orderer.
*/
private fun generateHankeFrom(cableReport: CableReportWithoutHanke): Hanke =
createHanke(
createHankeInternal(
Hanke(
id = null,
hankeTunnus = null,
Expand All @@ -959,9 +962,9 @@ open class HankeServiceImpl(
modifiedBy = null,
modifiedAt = null,
status = HankeStatus.DRAFT,
perustaja = generatePerustajaFrom(cableReport.applicationData),
generated = true,
)
),
perustaja = generatePerustajaFrom(cableReport.applicationData),
)

private fun generatePerustajaFrom(cableReport: CableReportApplicationData): Perustaja {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,6 @@ data class Hanke(
var status: HankeStatus? = HankeStatus.DRAFT,
//
@JsonView(ChangeLogView::class)
@field:Schema(description = "Hanke founder contact information")
var perustaja: Perustaja? = null,
//
@JsonView(ChangeLogView::class)
@field:Schema(description = "Indicates whether the Hanke data is generated, set by the service")
var generated: Boolean = false,
) : HasId<Int> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ class HankeControllerTest {
// mock HankeService response
Mockito.`when`(hankeService.updateHanke(partialHanke))
.thenReturn(partialHanke.copy(modifiedBy = username, modifiedAt = getCurrentTimeUTC()))
Mockito.`when`(hankeService.loadHanke("id123"))
Mockito.`when`(hankeService.findHankeOrThrow("id123"))
.thenReturn(HankeFactory.create(hankeTunnus = "id123"))
Mockito.`when`(permissionService.hasPermission(123, username, PermissionCode.EDIT))
.thenReturn(true)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -183,10 +183,6 @@ class HankeFactory(
return this
}

fun Hanke.withPerustaja(
newPerustaja: Perustaja? = Perustaja("Pertti Perustaja", "[email protected]")
): Hanke = apply { perustaja = newPerustaja }

/**
* Add a number of omistaja to a hanke. Generates the yhteystiedot with
* [HankeYhteystietoFactory.createDifferentiated] using the given ints for differentiating
Expand Down
Loading