Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
118 commits
Select commit Hold shift + click to select a range
6f44443
feat: add id for recipe publication request table
Leropsis Jul 16, 2025
29c7ee8
Merge branch 'dev' into moderator-interface
Leropsis Jul 16, 2025
9df241b
feat: add id for recipe & ingredient publication request table
Leropsis Jul 16, 2025
b874e0e
chore: add retrieving of all pending requests from publication requests
Leropsis Jul 16, 2025
209d1bf
chore: add GET /moderation/publication-requests -> List[PublicationRe…
Leropsis Jul 16, 2025
5ddd295
chore: add GET /moderation/publication-requests/{id} -> PublicationRe…
Leropsis Jul 16, 2025
d20dd6b
chore: add PATCH /moderation/publication-requests/{id} endpoint
Leropsis Jul 16, 2025
bb75620
refactor: moved things around for more clarity
danielambda Jul 17, 2025
e642db7
refactor: introduce PublicationRequestId
danielambda Jul 17, 2025
6b00f9c
test: Create ingredient tests
danielambda Jul 17, 2025
3e00a1c
chore: modified recipes publication requests repo with getWithRecipe …
danielambda Jul 17, 2025
307d17e
refactor: change "get all pending" method for publication request rep…
Leropsis Jul 17, 2025
98b35d2
fix: patch up non-existing table
Leropsis Jul 17, 2025
b6b589d
feat: add name to inStorages
TheBugYouCantFix Jul 16, 2025
f08f3b5
fix: query
TheBugYouCantFix Jul 16, 2025
2bf50c2
fix: adjust tests according to new changes
TheBugYouCantFix Jul 16, 2025
0fd60ce
chore: resolve merge conflict
danielambda Jul 17, 2025
2094061
test: basic request recipe publication tests
danielambda Jul 17, 2025
014d9df
refactor: somethings
danielambda Jul 18, 2025
0e03a35
chore: made code compile
danielambda Jul 18, 2025
2a9a337
fix: added DbIngredientPublicationRequest create table to tables list
danielambda Jul 18, 2025
c43dcd5
feat: add created publication request id to request publication endpo…
danielambda Jul 18, 2025
87b343f
Merge pull request #104 from Endpool/request-recipe-publication-tests
danielambda Jul 19, 2025
2d4a36e
Merge branch 'dev' into moderator-interface
danielambda Jul 19, 2025
af67c24
fix: made code compile after resolving conflicts
danielambda Jul 19, 2025
004a80a
refactor: GetSomePending publication requests
danielambda Jul 19, 2025
35f5e30
fix: use infix in recipes publication requsts repo to make things work
danielambda Jul 19, 2025
ce038f9
fix: write proper encoder for publication request status enum
danielambda Jul 19, 2025
2db6bd2
refactor: pull publication_request_status typename to inline val
danielambda Jul 19, 2025
c427ad1
feat: ignore on insert conflict
TheBugYouCantFix Jul 19, 2025
d56d34f
feat: make creator id optional in models
TheBugYouCantFix Jul 19, 2025
9ac0aef
feat: change decoding logic to make creator name & id optional
TheBugYouCantFix Jul 19, 2025
ce7b832
feat: wrap the remaining creator related code in options
TheBugYouCantFix Jul 19, 2025
ab70e17
test: When requesting publication of recipe with public ingredients, …
danielambda Jul 19, 2025
44bc882
refactor: use for comprehension instead of manual option matching
danielambda Jul 19, 2025
3eb7493
Merge pull request #107 from Endpool/optional-recipe-creator
danielambda Jul 19, 2025
b136619
Merge pull request #108 from Endpool/request-recipe-publication-tests
danielambda Jul 19, 2025
8294c7c
fix: quill infix interpolation was surrounding everything in ' which …
danielambda Jul 19, 2025
f5e2cac
refactor: change GET /moderation/publication-requests/{id} and PATCH …
Leropsis Jul 19, 2025
0673e90
refactor: cosmetic changes
Leropsis Jul 19, 2025
b1b9b93
refactor: a little bit of rearrangement
Leropsis Jul 19, 2025
1487e6b
fix: patch up ignoring "recipe publication request" update operation'…
Leropsis Jul 19, 2025
573b8c4
Merge pull request #98 from Endpool/moderator-interface
danielambda Jul 19, 2025
3f5270c
feat: add isUserOwner method
TheBugYouCantFix Jul 19, 2025
e1490a3
feat: add getAllByRecipeId
TheBugYouCantFix Jul 19, 2025
972f1e0
feat: add isPublished check to customIngredientsQ
TheBugYouCantFix Jul 19, 2025
403c8a2
feat: moderationHistory endpoint
TheBugYouCantFix Jul 19, 2025
b0ea213
chore: add optional field "last publication request status" for GET /…
Leropsis Jul 19, 2025
d020d5c
feat: add isUserOwner method
TheBugYouCantFix Jul 19, 2025
c51f296
feat: add getAllByRecipeId
TheBugYouCantFix Jul 19, 2025
6fb4fd9
feat: add isPublished check to customIngredientsQ
TheBugYouCantFix Jul 19, 2025
0c9b4c0
feat: moderationHistory endpoint
TheBugYouCantFix Jul 19, 2025
825ac68
Merge branch 'recipe-moderation-history' of https://github.com/Endpoo…
TheBugYouCantFix Jul 19, 2025
7133a06
chore: add optional field "last publication request status" for GET /…
Leropsis Jul 19, 2025
76c281c
fix: increase inlining limit for better support of auto json derivation
Leropsis Jul 19, 2025
142a612
fix: add missing reversing for recipe publication requests sorting
Leropsis Jul 19, 2025
0a2f99c
fix: foreign key
TheBugYouCantFix Jul 19, 2025
ad56ef7
fix: use infix filter to parse enum value properly
TheBugYouCantFix Jul 19, 2025
3730044
Merge branch 'moderator-interface' into request-recipe-publication-tests
danielambda Jul 19, 2025
f7fa48a
refactor: remove unnecessary reversing
Leropsis Jul 19, 2025
97b11e5
feat: encoder
TheBugYouCantFix Jul 19, 2025
702c1d6
feat: new model
TheBugYouCantFix Jul 19, 2025
74d0e1d
Merge pull request #110 from Endpool/moderation-status
danielambda Jul 19, 2025
a4a09f6
fix: add missing publication action when updating publication request
Leropsis Jul 19, 2025
b19a781
Merge remote-tracking branch 'origin/dev' into dev
Leropsis Jul 19, 2025
0306ad3
feat: POST admin/recipes/
danielambda Jul 19, 2025
9458f44
fix: patch up listing all public ingredients
Leropsis Jul 19, 2025
170a6d4
fix: add filtering by request id in publication request repos method …
Leropsis Jul 19, 2025
bed6d5b
fix: add admin endpoint to endpoints list
danielambda Jul 19, 2025
a528c90
fix: sanititize duplicate ingredients when creating recipes
danielambda Jul 19, 2025
e3dfa09
fix: GET /recipes/{recipe-id} did not work with recipes with no creator
danielambda Jul 20, 2025
a82103b
feat: public recipes endpoints
danielambda Jul 20, 2025
b5b2f8d
Merge pull request #113 from Endpool/admin-endpoints
TheBugYouCantFix Jul 20, 2025
e734349
feat: getAllCreatedByMethod
TheBugYouCantFix Jul 20, 2025
ae1bed0
refactor: mv moderationHistoryResponse to moderation package
TheBugYouCantFix Jul 20, 2025
d5aec34
refactor: mv moderationHistoryResponse to moderation package
TheBugYouCantFix Jul 20, 2025
625f077
feat: full history endpoint
TheBugYouCantFix Jul 20, 2025
4c08425
fix: resolve merge conflicts
danielambda Jul 20, 2025
0342c3b
Merge pull request #111 from Endpool/recipe-moderation-history
danielambda Jul 20, 2025
5903082
fix: resolve merge conflicts
danielambda Jul 20, 2025
3b679ad
fix: rm reason from encoder
TheBugYouCantFix Jul 20, 2025
3a9b59b
feat: add decoder
TheBugYouCantFix Jul 20, 2025
46e8a7f
Merge pull request #116 from Endpool/status-serialization
TheBugYouCantFix Jul 20, 2025
29e3efd
chore: add search for shopping list
Leropsis Jul 20, 2025
d697e60
refactor: rm ownerId
TheBugYouCantFix Jul 20, 2025
9b7b4f2
feat: make activate endpoint return storage id & name
TheBugYouCantFix Jul 20, 2025
b6a0228
fix: tests
TheBugYouCantFix Jul 20, 2025
d1f8149
fix: error
TheBugYouCantFix Jul 20, 2025
4e3bd2e
Merge pull request #120 from Endpool/return-invite-activation-data
danielambda Jul 20, 2025
b93e1fd
Merge pull request #115 from Endpool/full-moderation-history
Rash1d1 Jul 21, 2025
7d319f0
feat: POST /admin/recipes
danielambda Jul 21, 2025
bfa65cb
Merge branch 'admin-endpoints' into dev
danielambda Jul 21, 2025
192936a
refactor: remove unused imports
danielambda Jul 21, 2025
00c58a0
fix: IngredientsRepo.addPublic isPublished -> true
danielambda Jul 21, 2025
b58c8db
chore: rename to /recipes/{recipe-id}/publication-requests
danielambda Jul 21, 2025
605abe0
refactor: create api/recipes/publicationRequests directory
danielambda Jul 21, 2025
ce96eee
fix: add full publication requests endpoint to endpoints list
danielambda Jul 21, 2025
7a6e8a4
refactor: a little bit of rearrangement in quill query
Leropsis Jul 21, 2025
da8db70
fix: customness of ingredient depended on publicity
Makcal Jul 21, 2025
df897da
fix: all published ingredients should be visible (not depend on owner)
Makcal Jul 21, 2025
802d04a
fix: remove not published ingredients without an owner from visibility
Makcal Jul 21, 2025
63e3fd5
fix: update route in RequestRecipePublicationTests
danielambda Jul 21, 2025
5e2900a
Merge pull request #118 from Endpool/search-for-shopping-list
danielambda Jul 21, 2025
c1e09ce
Merge pull request #121 from Endpool/makcal/bug_fixes
danielambda Jul 21, 2025
23fb21d
fix: bring storage id back to GET /storages/{storageId}
danielambda Jul 21, 2025
d853b2b
refactor: add name & request type
TheBugYouCantFix Jul 21, 2025
78b011e
feat: make query return request & db entity
TheBugYouCantFix Jul 21, 2025
705d2af
idc
TheBugYouCantFix Jul 21, 2025
f9cf40b
Merge pull request #122 from Endpool/full-moderation-history-refinement
danielambda Jul 21, 2025
2dbd9bc
refactor: use domain enum instead of custom enum
TheBugYouCantFix Jul 22, 2025
7992e03
feat: encoder & decoder
TheBugYouCantFix Jul 22, 2025
993e986
test: empty recipe and recipe with published custom ingredients reque…
danielambda Jul 22, 2025
e811854
fix: restrict usage of private ingredients when requesting recipe pub…
danielambda Jul 22, 2025
39d9e15
test: When requesting publication of recipe with private ingredients,…
danielambda Jul 22, 2025
e6a7ee0
Merge pull request #123 from Endpool/request-recipe-publication-tests
danielambda Jul 22, 2025
9be416b
Merge pull request #101 from Endpool/basic-tests-for-everything
danielambda Jul 22, 2025
9e6725e
fix: check recipe publicity in /suggested-recipes
danielambda Jul 23, 2025
e59721a
fix: use MD5 for shorter invitation hashs
danielambda Jul 23, 2025
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
1 change: 1 addition & 0 deletions build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ val circeVersion = "0.14.14"

lazy val root = (project in file("."))
.settings(
scalacOptions ++= Seq("-Xmax-inlines", "64"),
name := "CookCookHnya-backend",
scalacOptions ++= Seq(
"-Wunused:imports"
Expand Down
2 changes: 2 additions & 0 deletions src/main/scala/api/EndpointErrorVariants.scala
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import domain.{
StorageAccessForbidden,
StorageNotFound,
UserNotFound,
PublicationRequestNotFound
}

import io.circe.{Decoder, Encoder}
Expand All @@ -28,6 +29,7 @@ extension (sc: StatusCode)
object EndpointErrorVariants:
val ingredientNotFoundVariant = NotFound.variantJson[IngredientNotFound]
val storageNotFoundVariant = NotFound.variantJson[StorageNotFound]
val publicationRequestNotFound = NotFound.variantJson[PublicationRequestNotFound]
val storageAccessForbiddenVariant = Forbidden.variantJson[StorageAccessForbidden]
val recipeAccessForbiddenVariant = NotFound.variantJson[RecipeAccessForbidden]
val userNotFoundVariant = NotFound.variantJson[UserNotFound]
Expand Down
4 changes: 3 additions & 1 deletion src/main/scala/api/Endpoints.scala
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import api.users.usersEndpoints
import api.recipes.recipeEndpoints
import api.shoppinglist.shoppingListEndpoints
import api.invitations.invitationEndpoints

import api.moderation.moderationEndpoints
import sttp.tapir.ztapir.ZServerEndpoint
import sttp.tapir.ztapir.RichZServerEndpoint

Expand All @@ -18,3 +18,5 @@ object AppEndpoints:
++ recipeEndpoints.map(_.widen)
++ shoppingListEndpoints.map(_.widen)
++ invitationEndpoints.map(_.widen)
++ moderationEndpoints.map(_.widen)
:+ getPublicationRequestsHistory.widen
68 changes: 68 additions & 0 deletions src/main/scala/api/GetPublicationRequestsHistory.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package api

import api.Authentication.{AuthenticatedUser, zSecuredServerLogic}
import api.EndpointErrorVariants.serverErrorVariant
import api.common.search.PaginationParams
import api.moderation.ModerationHistoryResponse
import db.repositories.{IngredientPublicationRequestsRepo, RecipePublicationRequestsRepo}
import db.tables.{DbIngredient, DbRecipe}
import db.tables.publication.{DbIngredientPublicationRequest, DbRecipePublicationRequest}
import domain.InternalServerError
import io.circe.Decoder
import io.circe.derivation.Configuration
import io.circe.generic.auto.*
import sttp.tapir.generic.auto.*
import sttp.tapir.json.circe.*
import sttp.tapir.ztapir.*
import zio.ZIO

private type GetPublicationRequestsHistoryEnv
= RecipePublicationRequestsRepo
& IngredientPublicationRequestsRepo

val getPublicationRequestsHistory: ZServerEndpoint[GetPublicationRequestsHistoryEnv, Any] =
endpoint
.get
.in("publication-requests" / PaginationParams.query)
.errorOut(oneOf(serverErrorVariant))
.out(jsonBody[List[ModerationHistoryResponse]])
.zSecuredServerLogic(getPublicationRequestsHistoryHandler)

def getPublicationRequestsHistoryHandler(paginationParams: PaginationParams):
ZIO[
AuthenticatedUser & GetPublicationRequestsHistoryEnv,
InternalServerError,
List[ModerationHistoryResponse]
] =
for
dbRecipeRequests <- ZIO.serviceWithZIO[RecipePublicationRequestsRepo](_
.getAllCreatedBy
.orElseFail(InternalServerError())
)
recipeRequests = dbRecipeRequests.map {
case (dbRecipeReq: DbRecipePublicationRequest, recipe: DbRecipe) => ModerationHistoryResponse(
recipe.name,
"recipe",
dbRecipeReq.createdAt,
dbRecipeReq.updatedAt,
PublicationRequestStatusResp.fromDomain(dbRecipeReq.status.toDomain(dbRecipeReq.reason)),
dbRecipeReq.reason
)
}

dbIngredientRequests <- ZIO.serviceWithZIO[IngredientPublicationRequestsRepo](_
.getAllCreatedBy
.orElseFail(InternalServerError())
)
ingredientRequests = dbIngredientRequests.map {
case (dbRecipeReq: DbIngredientPublicationRequest, ingredient: DbIngredient) => ModerationHistoryResponse(
ingredient.name,
"ingredient",
dbRecipeReq.createdAt,
dbRecipeReq.updatedAt,
PublicationRequestStatusResp.fromDomain(dbRecipeReq.status.toDomain(dbRecipeReq.reason)),
dbRecipeReq.reason
)
}
yield (recipeRequests ++ ingredientRequests)
.sortBy(_.updatedAt)
35 changes: 35 additions & 0 deletions src/main/scala/api/PublicationRequestStatusResp.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package api

import domain.PublicationRequestStatus
import io.circe.{Decoder, DecodingFailure, Encoder, HCursor, Json}

enum PublicationRequestStatusResp:
case Pending
case Accepted
case Rejected(reason: Option[String])

object PublicationRequestStatusResp:
def fromDomain(domainModel: PublicationRequestStatus): PublicationRequestStatusResp =
domainModel match
case PublicationRequestStatus.Accepted => Accepted
case PublicationRequestStatus.Pending => Pending
case PublicationRequestStatus.Rejected(reason) => Rejected(reason)

given Encoder[PublicationRequestStatusResp] = Encoder.instance {
case Pending => Json.obj("type" -> Json.fromString("pending"))
case Accepted => Json.obj("type" -> Json.fromString("accepted"))
case Rejected(reason) =>
val baseObj = Json.obj("type" -> Json.fromString("rejected"))
reason match
case Some(r) => baseObj.deepMerge(Json.obj("reason" -> Json.fromString(r)))
case None => baseObj
}

given Decoder[PublicationRequestStatusResp] = (c: HCursor) =>
c.downField("type").as[String].flatMap {
case "pending" => Right(Pending)
case "accepted" => Right(Accepted)
case "rejected" =>
c.downField("reason").as[Option[String]].map(Rejected.apply)
case other => Left(DecodingFailure(s"Unknown status type: $other", c.history))
}
4 changes: 2 additions & 2 deletions src/main/scala/api/common/search/PaginationParams.scala
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package api.common.search

import scala.collection.immutable.IndexedSeqOps
import scala.collection.IterableOps
import sttp.tapir

case class PaginationParams(
Expand All @@ -15,7 +15,7 @@ object PaginationParams:
(PaginationParams.apply.tupled)
{case PaginationParams(size, offset) => (size, offset)}

extension[A, CC[_], C](seq: IndexedSeqOps[A, CC, C])
extension[A, CC[_], C](seq: IterableOps[A, CC, C])
def paginate(paginationParams: PaginationParams): C =
seq.slice(paginationParams.offset, paginationParams.offset + paginationParams.size)

3 changes: 2 additions & 1 deletion src/main/scala/api/ingredients/Create.scala
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import sttp.tapir.ztapir.*
import zio.ZIO

private type CreateEnv = IngredientsRepo & DataSource

private val create: ZServerEndpoint[CreateEnv, Any] =
ingredientsEndpoint
.post
Expand All @@ -42,4 +43,4 @@ private def createHandler(reqBody: CreateIngredientReqBody):
.map(_.id)
.orElseFail(InternalServerError())
)
yield ingredientId
yield ingredientId
3 changes: 3 additions & 0 deletions src/main/scala/api/ingredients/Endpoints.scala
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package api.ingredients
import sttp.tapir.Endpoint
import sttp.tapir.ztapir.*

import api.ingredients.admin.adminIngredientsEndpoints
import api.ingredients.public.publicEndpoints
import api.TapirExtensions.subTag

Expand All @@ -21,5 +22,7 @@ val ingredientsEndpoints = List(
search.widen,
searchForRecipe.widen,
searchForStorage.widen,
searchForShoppingList.widen,
requestPublication.widen
) ++ publicEndpoints.map(_.widen)
++ adminIngredientsEndpoints.map(_.widen)
7 changes: 6 additions & 1 deletion src/main/scala/api/ingredients/IngredientResp.scala
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
package api.ingredients

import api.common.search.Searchable
import api.PublicationRequestStatusResp
import domain.IngredientId
import db.tables.DbIngredient

final case class IngredientResp(id: IngredientId, name: String) extends Searchable
final case class IngredientResp(
id: IngredientId,
name: String,
moderationStatus: Option[PublicationRequestStatusResp] = None
) extends Searchable

object IngredientResp:
def fromDb(dbIngredient: DbIngredient): IngredientResp =
Expand Down
30 changes: 16 additions & 14 deletions src/main/scala/api/ingredients/RequestPublication.scala
Original file line number Diff line number Diff line change
Expand Up @@ -4,52 +4,54 @@ import api.Authentication.{AuthenticatedUser, zSecuredServerLogic}
import api.variantJson
import api.EndpointErrorVariants.{ingredientNotFoundVariant, serverErrorVariant}
import db.repositories.{
IngredientPublicationRequestsRepo, IngredientsQueries,
IngredientPublicationRequestsRepo,
IngredientsRepo, IngredientPublicationRequestsQueries
}
import domain.{IngredientId, IngredientNotFound, InternalServerError, RecipeId}
import db.tables.publication.DbPublicationRequestStatus.given
import domain.{IngredientId, IngredientNotFound, InternalServerError, PublicationRequestId}
import db.QuillConfig.provideDS
import db.QuillConfig.ctx.*

import io.circe.generic.auto.*
import io.getquill.*
import javax.sql.DataSource
import io.circe.generic.auto.*
import sttp.model.StatusCode.BadRequest
import sttp.model.StatusCode.{BadRequest, Created}
import sttp.tapir.generic.auto.*
import sttp.tapir.ztapir.*
import zio.ZIO

private final case class IngredientAlreadyPublished(
final case class IngredientAlreadyPublished(
ingredientId: IngredientId,
message: String = "Ingredient already published",
)
object IngredientAlreadyPublished:
val variant = BadRequest.variantJson[IngredientAlreadyPublished]

private final case class IngredientAlreadyPending(
final case class IngredientAlreadyPending(
ingredientId: IngredientId,
message: String = "Ingredient already pending"
)
object IngredientAlreadyPending:
val variant = BadRequest.variantJson[IngredientAlreadyPending]

private type RequestPublicationEnv = IngredientPublicationRequestsRepo & IngredientsRepo & DataSource

private val requestPublication: ZServerEndpoint[RequestPublicationEnv, Any] =
ingredientsEndpoint
.post
.in(path[IngredientId]("ingredientId") / "request-publication")
.out(statusCode(Created) and plainBody[PublicationRequestId])
.errorOut(oneOf(
serverErrorVariant, IngredientAlreadyPublished.variant,
IngredientAlreadyPending.variant, ingredientNotFoundVariant
))
.zSecuredServerLogic(requestPublicationHandler)

def requestPublicationHandler(ingredientId: IngredientId):
private def requestPublicationHandler(ingredientId: IngredientId):
ZIO[
AuthenticatedUser & RequestPublicationEnv,
InternalServerError | IngredientAlreadyPublished | IngredientAlreadyPending | IngredientNotFound,
Unit
InternalServerError | IngredientAlreadyPublished
| IngredientAlreadyPending | IngredientNotFound,
PublicationRequestId
] =
for
ingredient <- ZIO.serviceWithZIO[IngredientsRepo](_
Expand All @@ -58,19 +60,19 @@ def requestPublicationHandler(ingredientId: IngredientId):
)

_ <- ZIO.fail(IngredientAlreadyPublished(ingredientId))
.when(ingredient.isPublished)
.when(ingredient.isPublished)

dataSource <- ZIO.service[DataSource]
alreadyPending <- run(
IngredientPublicationRequestsQueries
.pendingRequestsByIdQ(lift(ingredientId)).nonEmpty
.pendingRequestsByIngredientIdQ(lift(ingredientId)).nonEmpty
).provideDS(using dataSource)
.orElseFail(InternalServerError())
_ <- ZIO.fail(IngredientAlreadyPending(ingredientId))
.when(alreadyPending)

_ <- ZIO.serviceWithZIO[IngredientPublicationRequestsRepo](_
reqId <- ZIO.serviceWithZIO[IngredientPublicationRequestsRepo](_
.requestPublication(ingredientId)
.orElseFail(InternalServerError())
)
yield ()
yield reqId
33 changes: 25 additions & 8 deletions src/main/scala/api/ingredients/Search.scala
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
package api.ingredients

import api.Authentication.{zSecuredServerLogic, AuthenticatedUser}
import api.common.search.{PaginationParams, paginate, SearchParams, Searchable}
import api.Authentication.{AuthenticatedUser, zSecuredServerLogic}
import api.common.search.{PaginationParams, SearchParams, Searchable, paginate}
import api.EndpointErrorVariants.serverErrorVariant
import db.repositories.{IngredientsRepo, StorageIngredientsRepo}
import api.ingredients.SearchIngredientsFilter.Custom
import api.PublicationRequestStatusResp
import db.repositories.{IngredientPublicationRequestsRepo, IngredientsRepo, StorageIngredientsRepo}
import domain.{IngredientId, InternalServerError}

import io.circe.generic.auto.*
import sttp.tapir.{Codec, Schema, Validator, EndpointInput}
import sttp.tapir.{Codec, EndpointInput, Schema, Validator}
import sttp.tapir.generic.auto.*
import sttp.tapir.json.circe.*
import sttp.tapir.ztapir.*
Expand All @@ -25,7 +26,7 @@ object SearchIngredientsFilter:
given Codec.PlainCodec[SearchIngredientsFilter] =
Codec.derivedEnumeration.defaultStringBased

private type SearchEnv = IngredientsRepo & StorageIngredientsRepo
private type SearchEnv = IngredientsRepo & StorageIngredientsRepo & IngredientPublicationRequestsRepo

private val search: ZServerEndpoint[SearchEnv, Any] =
ingredientsEndpoint
Expand All @@ -41,7 +42,17 @@ private def searchHandler(
searchParams: SearchParams,
paginationParams: PaginationParams,
filter: SearchIngredientsFilter,
): ZIO[AuthenticatedUser & SearchEnv, InternalServerError, SearchResp[IngredientResp]] =
): ZIO[AuthenticatedUser & SearchEnv, InternalServerError, SearchResp[IngredientResp]] = {

def getLastPublicationRequestStatus(ingredientId: IngredientId) =
ZIO.serviceWithZIO[IngredientPublicationRequestsRepo](
_.getAllRequestsForIngredient(ingredientId).map(
_.sortBy(_.updatedAt).lastOption.map(
req => PublicationRequestStatusResp.fromDomain(req.status.toDomain(req.reason))
)
)
)

for
getIngredients <- ZIO.serviceWith[IngredientsRepo](filter match
case SearchIngredientsFilter.Custom => _.getAllCustom
Expand All @@ -52,4 +63,10 @@ private def searchHandler(
.map(_.map(IngredientResp.fromDb))
.orElseFail(InternalServerError())
res = Searchable.search(Vector.from(allIngredients), searchParams)
yield SearchResp(res.paginate(paginationParams), res.length)
res <- ZIO.foreach(res) { resp =>
getLastPublicationRequestStatus(resp.id)
.map(status => resp.copy(moderationStatus = status))
.orElseFail(InternalServerError())
}.when(filter == Custom).someOrElse(res)
yield SearchResp(res.paginate(paginationParams), res.length)
}
Loading