Skip to content

Commit

Permalink
[TRELLO-2775] Improve and add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
charlescd committed Jan 23, 2025
1 parent 08cd258 commit 32e9c80
Show file tree
Hide file tree
Showing 10 changed files with 220 additions and 47 deletions.
2 changes: 1 addition & 1 deletion app/controllers/WebsiteController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ class WebsiteController(
errors => Future.successful(BadRequest(JsError.toJson(errors))),
company =>
websitesOrchestrator
.updateCompany(websiteId, company, request.identity)
.updateCompany(websiteId, company, Some(request.identity))
.map(websiteAndCompany => Ok(Json.toJson(websiteAndCompany)))
)
}
Expand Down
10 changes: 5 additions & 5 deletions app/loader/SignalConsoApplicationLoader.scala
Original file line number Diff line number Diff line change
Expand Up @@ -223,16 +223,16 @@ class SignalConsoComponents(
val authAttemptRepository: AuthAttemptRepositoryInterface = new AuthAttemptRepository(dbConfig)
val authTokenRepository: AuthTokenRepositoryInterface = new AuthTokenRepository(dbConfig)
val proConnectSessionRepository: ProConnectSessionRepositoryInterface = new ProConnectSessionRepository(dbConfig)
val companyRepository: CompanyRepositoryInterface = new CompanyRepository(dbConfig)
def companyRepository: CompanyRepositoryInterface = new CompanyRepository(dbConfig)
val companyActivationAttemptRepository: CompanyActivationAttemptRepositoryInterface =
new CompanyActivationAttemptRepository(dbConfig)
val consumerRepository: ConsumerRepositoryInterface = new ConsumerRepository(dbConfig)
val emailValidationRepository: EmailValidationRepositoryInterface = new EmailValidationRepository(dbConfig)

val eventRepository: EventRepositoryInterface = new EventRepository(dbConfig)
def eventRepository: EventRepositoryInterface = new EventRepository(dbConfig)
val ratingRepository: RatingRepositoryInterface = new RatingRepository(dbConfig)
val influencerRepository: InfluencerRepositoryInterface = new InfluencerRepository(dbConfig)
val reportRepository: ReportRepositoryInterface = new ReportRepository(dbConfig)
def reportRepository: ReportRepositoryInterface = new ReportRepository(dbConfig)
val reportMetadataRepository: ReportMetadataRepositoryInterface = new ReportMetadataRepository(dbConfig)
val bookmarkRepository: BookmarkRepositoryInterface = new BookmarkRepository(dbConfig)
val reportNotificationBlockedRepository: ReportNotificationBlockedRepositoryInterface =
Expand All @@ -241,9 +241,9 @@ class SignalConsoComponents(
new ResponseConsumerReviewRepository(dbConfig)
val reportEngagementReviewRepository: ReportEngagementReviewRepositoryInterface =
new ReportEngagementReviewRepository(dbConfig)
val reportFileRepository: ReportFileRepositoryInterface = new ReportFileRepository(dbConfig)
def reportFileRepository: ReportFileRepositoryInterface = new ReportFileRepository(dbConfig)
val subscriptionRepository: SubscriptionRepositoryInterface = new SubscriptionRepository(dbConfig)
val userRepository: UserRepositoryInterface = new UserRepository(dbConfig, passwordHasherRegistry)
def userRepository: UserRepositoryInterface = new UserRepository(dbConfig, passwordHasherRegistry)
val websiteRepository: WebsiteRepositoryInterface = new WebsiteRepository(dbConfig)
val socialNetworkRepository: SocialNetworkRepositoryInterface = new SocialNetworkRepository(dbConfig)

Expand Down
10 changes: 7 additions & 3 deletions app/orchestrators/ImportOrchestrator.scala
Original file line number Diff line number Diff line change
Expand Up @@ -131,8 +131,12 @@ class ImportOrchestrator(
companyId = Some(company.id),
isMarketplace = true
)
updatedWebsite <- websitesOrchestrator.updateIdentification(websiteToUpdate, user)
_ <- websitesOrchestrator.updatePreviousReportsAssociatedToWebsite(website.host, company, user.id)
updatedWebsite <- websitesOrchestrator.updateIdentification(websiteToUpdate, Some(user))
_ <- websitesOrchestrator.updatePreviousReportsAssociatedToWebsite(
website.host,
company,
Some(user.id)
)
} yield updatedWebsite
}
case Nil =>
Expand All @@ -145,7 +149,7 @@ class ImportOrchestrator(
)
for {
createdWebsite <- websiteRepository.create(website)
_ <- websitesOrchestrator.updatePreviousReportsAssociatedToWebsite(website.host, company, user.id)
_ <- websitesOrchestrator.updatePreviousReportsAssociatedToWebsite(website.host, company, Some(user.id))
} yield createdWebsite

}
Expand Down
10 changes: 5 additions & 5 deletions app/orchestrators/ReportOrchestrator.scala
Original file line number Diff line number Diff line change
Expand Up @@ -618,14 +618,14 @@ class ReportOrchestrator(
updatedReport <- updateReportCompany(
existingReport,
reportCompany,
requestingUserId
Some(requestingUserId)
)
} yield updatedReport

def updateReportCompanyForWebsite(
existingReport: Report,
reportCompany: ReportCompany,
adminUserId: UUID
adminUserId: Option[UUID]
) =
if (isReportTooOld(existingReport)) {
logger.debug(s"Report ${existingReport.id} is too old to be updated")
Expand All @@ -636,7 +636,7 @@ class ReportOrchestrator(
private def updateReportCompany(
existingReport: Report,
reportCompany: ReportCompany,
adminUserId: UUID
adminUserId: Option[UUID]
): Future[Report] = {
val updateDateTime = OffsetDateTime.now()

Expand Down Expand Up @@ -687,9 +687,9 @@ class ReportOrchestrator(
UUID.randomUUID(),
Some(updatedReport.id),
Some(company.id),
Some(adminUserId),
adminUserId,
updateDateTime,
Constants.EventType.ADMIN,
if (adminUserId.isDefined) Constants.EventType.ADMIN else Constants.EventType.SYSTEM,
Constants.ActionEvent.REPORT_COMPANY_CHANGE,
stringToDetailsJsValue(
s"Entreprise précédente : Siret ${existingReport.companySiret
Expand Down
20 changes: 12 additions & 8 deletions app/orchestrators/WebsitesOrchestrator.scala
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ class WebsitesOrchestrator(
identificationStatus = IdentificationStatus.Identified
)
createdWebsite <- repository.create(website)
_ <- updatePreviousReportsAssociatedToWebsite(website.host, createdCompany, user.id)
_ <- updatePreviousReportsAssociatedToWebsite(website.host, createdCompany, Some(user.id))
} yield createdWebsite

def searchByHost(host: String): Future[Seq[Country]] =
Expand Down Expand Up @@ -135,7 +135,7 @@ class WebsitesOrchestrator(
.getOrElse(Future.successful(None))
_ = logger.debug(s"Company Siret is ${maybeCompany.map(_.siret)}")
_ <- maybeCompany
.map(company => updatePreviousReportsAssociatedToWebsite(website.host, company, user.id))
.map(company => updatePreviousReportsAssociatedToWebsite(website.host, company, Some(user.id)))
.getOrElse(Future.unit)
} yield ()
} else Future.unit
Expand All @@ -152,7 +152,11 @@ class WebsitesOrchestrator(
} yield website
}

def updateCompany(websiteId: WebsiteId, companyToAssign: CompanyCreation, user: User): Future[WebsiteAndCompany] =
def updateCompany(
websiteId: WebsiteId,
companyToAssign: CompanyCreation,
user: Option[User]
): Future[WebsiteAndCompany] =
for {
company <- {
logger.debug(s"Updating website (id ${websiteId}) with company siret : ${companyToAssign.siret}")
Expand All @@ -171,7 +175,7 @@ class WebsitesOrchestrator(
companyId = Some(company.id)
)
updatedWebsite <- updateIdentification(websiteToUpdate, user)
_ <- updatePreviousReportsAssociatedToWebsite(website.host, company, user.id)
_ <- updatePreviousReportsAssociatedToWebsite(website.host, company, user.map(_.id))
} yield WebsiteAndCompany.toApi(updatedWebsite, Some(company))

def updateCompanyCountry(websiteId: WebsiteId, companyCountry: String, user: User): Future[WebsiteAndCompany] = for {
Expand All @@ -188,17 +192,17 @@ class WebsitesOrchestrator(
companyCountry = Some(companyCountry),
companyId = None
)
updatedWebsite <- updateIdentification(websiteToUpdate, user)
updatedWebsite <- updateIdentification(websiteToUpdate, Some(user))
} yield WebsiteAndCompany.toApi(updatedWebsite, maybeCompany = None)

def updateIdentification(website: Website, user: User): Future[Website] = {
def updateIdentification(website: Website, user: Option[User]): Future[Website] = {
logger.debug(s"Removing other websites with the same host : ${website.host}")
for {
_ <- repository
.removeOtherNonIdentifiedWebsitesWithSameHost(website)
_ = logger.debug(s"updating identification status when Admin is updating identification")
websiteToUpdate =
if (UserRole.isAdmin(user.userRole)) website.copy(identificationStatus = Identified) else website
if (user.map(_.userRole).forall(UserRole.isAdmin)) website.copy(identificationStatus = Identified) else website
_ = logger.debug(s"Website to update : ${websiteToUpdate}")
updatedWebsite <- update(websiteToUpdate)
_ = logger.debug(s"Website company country successfully updated")
Expand Down Expand Up @@ -264,7 +268,7 @@ class WebsitesOrchestrator(
def updatePreviousReportsAssociatedToWebsite(
websiteHost: String,
company: Company,
userId: UUID
userId: Option[UUID]
): Future[Unit] = {
val reportCompany = ReportCompany(
name = company.name,
Expand Down
42 changes: 26 additions & 16 deletions app/tasks/website/SiretExtractionTask.scala
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,18 @@ class SiretExtractionTask(

override val taskSettings: TaskSettings = FrequentTaskSettings(interval = 1.hour)

def matchingExtraction(company: Company, extractions: List[SiretExtractionApi]): Option[CompanySearchResult] = {
val a = extractions.find { extraction =>
extraction.sirene match {
case Some(sirene) => sirene.siret == company.siret
case None => false
def findMatchingAndValidExtraction(
company: Company,
extractions: List[SiretExtractionApi]
): Option[CompanySearchResult] = {
val a = extractions
.filter(extraction => extraction.siret.forall(_.valid) && extraction.siren.forall(_.valid))
.find { extraction =>
extraction.sirene match {
case Some(sirene) => sirene.siret == company.siret && company.isOpen
case None => false
}
}
}
a.flatMap(_.sirene)
}

Expand All @@ -63,23 +68,28 @@ class SiretExtractionTask(
}
}
)
// Sauvegarde des résultats en DB
_ <- results.traverse { case (_, extraction) => siretExtractionRepository.insertOrReplace(extraction) }

test = results.collect {
case (Website(id, _, _, _, _, Some(companyId), _, _, _), ExtractionResultApi(_, _, _, Some(l))) =>
(id, companyId, l)
// Association automatique si :
// - Un siret trouvé est valide et présent dans SIRENE
// - Le conso a fourni la même entreprise
// - L'entreprise est ouverte
companyIdsAndExtractions = results.collect {
case (Website(id, _, _, _, _, Some(companyId), _, _, _), ExtractionResultApi(_, _, _, Some(extractions))) =>
(id, companyId, extractions)
}
test2 <- test.traverse { case (websiteId, companyId, l) =>
companyAndExtractions <- companyIdsAndExtractions.traverse { case (websiteId, companyId, extractions) =>
companyRepository
.get(companyId)
.flatMap(_.liftTo[Future](CompanyNotFound(companyId)))
.map(company => (websiteId, company, l))
.map(company => (websiteId, company, extractions))
}
test3 = test2.flatMap { case (websiteId, company, extractions) =>
matchingExtraction(company, extractions).map(a => websiteId -> a)
websiteIdAndFoundCompany = companyAndExtractions.flatMap { case (websiteId, company, extractions) =>
findMatchingAndValidExtraction(company, extractions).map(companySearchResult => websiteId -> companySearchResult)
}
_ <- test3.traverse { case (websiteId, companySearchResult) =>
val a = CompanyCreation(
_ <- websiteIdAndFoundCompany.traverse { case (websiteId, companySearchResult) =>
val companyCreation = CompanyCreation(
siret = companySearchResult.siret,
name = companySearchResult.name.getOrElse(""),
address = companySearchResult.address,
Expand All @@ -91,7 +101,7 @@ class SiretExtractionTask(
commercialName = companySearchResult.commercialName,
establishmentCommercialName = companySearchResult.establishmentCommercialName
)
websitesOrchestrator.updateCompany(websiteId, a, null) // TODO
websitesOrchestrator.updateCompany(websiteId, companyCreation, None)
}
} yield ()
}
4 changes: 2 additions & 2 deletions test/controllers/ReportToExternalControllerSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -122,8 +122,8 @@ class ReportToExternalControllerSpec(implicit ee: ExecutionEnv)

override def load(context: ApplicationLoader.Context): Application = {
components = new SignalConsoComponents(context) {
override val reportRepository: ReportRepositoryInterface = mockReportRepository
override val reportFileRepository: ReportFileRepositoryInterface = mockReportFileRepository
override def reportRepository: ReportRepositoryInterface = mockReportRepository
override def reportFileRepository: ReportFileRepositoryInterface = mockReportFileRepository
override def configuration: Configuration = super.configuration
}
components.application
Expand Down
10 changes: 5 additions & 5 deletions test/controllers/report/GetReportSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -416,14 +416,14 @@ trait GetReportContext extends AppSpec {
override def load(context: ApplicationLoader.Context): Application = {
components = new SignalConsoComponents(context) {

override val reportRepository: ReportRepositoryInterface = mockReportRepository
override val companyRepository: CompanyRepositoryInterface = mockCompanyRepository
override val reportFileRepository: ReportFileRepositoryInterface = mockReportFileRepository
override def reportRepository: ReportRepositoryInterface = mockReportRepository
override def companyRepository: CompanyRepositoryInterface = mockCompanyRepository
override def reportFileRepository: ReportFileRepositoryInterface = mockReportFileRepository
override lazy val mailRetriesService: MailRetriesService = mockMailRetriesService
override val eventRepository: EventRepositoryInterface = mockEventRepository
override def eventRepository: EventRepositoryInterface = mockEventRepository
override def companiesVisibilityOrchestrator: CompaniesVisibilityOrchestrator =
mockCompaniesVisibilityOrchestrator
override val userRepository: UserRepositoryInterface = mockUserRepository
override def userRepository: UserRepositoryInterface = mockUserRepository

override def configuration: Configuration = Configuration(
"slick.dbs.default.db.connectionPool" -> "disabled",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,9 @@ class InactiveDgccrfAccountReminderTaskSpec(implicit ee: ExecutionEnv)

override lazy val mailRetriesService: MailRetriesService = mockMailRetriesService

override val eventRepository: EventRepositoryInterface = mockEventRepository
override def eventRepository: EventRepositoryInterface = mockEventRepository

override val userRepository: UserRepositoryInterface = mockUserRepository
override def userRepository: UserRepositoryInterface = mockUserRepository

override def configuration: Configuration = Configuration(
"slick.dbs.default.db.connectionPool" -> "disabled",
Expand Down
Loading

0 comments on commit 32e9c80

Please sign in to comment.