From 326a3168b28c5b5a99881148f51c84f7cbb6c60f Mon Sep 17 00:00:00 2001 From: Michal Rus Date: Tue, 27 Jun 2017 16:05:45 +0200 Subject: [PATCH 1/2] Move around some stuff in core._ (A couple of FIXMEs as a nice break from bugs :P) --- phoenix-scala/core/app/core/db/Star.scala | 2 +- phoenix-scala/core/app/core/db/package.scala | 23 ++++++------------- .../app/objectframework/ObjectUtils.scala | 6 ++--- .../models/ObjectHeadLinks.scala | 3 ++- .../services/ContentManager.scala | 8 +++---- .../models/customer/CustomerGroup.scala | 2 +- .../models/discount/SearchReference.scala | 4 ++-- .../phoenix/responses/ReturnResponse.scala | 9 ++++---- .../cord/base/CordResponsePromotions.scala | 2 +- .../app/phoenix/routes/AuthRoutes.scala | 2 +- .../app/phoenix/services/Capture.scala | 18 ++++++++------- .../app/phoenix/services/CartValidator.scala | 8 +++---- .../app/phoenix/services/Checkout.scala | 15 ++++++------ .../phoenix/services/CreditCardManager.scala | 4 ++-- .../services/account/AccountManager.scala | 4 ++-- .../services/actors/RemorseTimer.scala | 2 +- .../services/carts/CartLineItemUpdater.scala | 2 +- .../services/carts/CartPromotionUpdater.scala | 4 ++-- .../services/category/CategoryManager.scala | 2 +- .../customerGroups/GroupMemberManager.scala | 10 ++++---- .../services/orders/OrderStateUpdater.scala | 4 ++-- .../services/product/ProductManager.scala | 11 +++++---- .../returns/ReturnLineItemManager.scala | 8 +++---- .../returns/ReturnPaymentManager.scala | 10 ++++---- .../services/returns/ReturnService.scala | 11 +++++---- .../services/returns/ReturnTotaler.scala | 3 ++- .../services/returns/ReturnValidator.scala | 5 ++-- .../services/taxonomy/TaxonomyManager.scala | 8 +++---- .../CreditCardsIntegrationTest.scala | 2 +- .../PromotionsIntegrationTest.scala | 4 ++-- .../integration/services/CheckoutTest.scala | 2 +- .../integration/testutils/TestSeeds.scala | 2 +- .../test/integration/utils/MockedApis.scala | 4 ++-- 33 files changed, 100 insertions(+), 104 deletions(-) diff --git a/phoenix-scala/core/app/core/db/Star.scala b/phoenix-scala/core/app/core/db/Star.scala index 4fe112a2d1..09ca267c13 100644 --- a/phoenix-scala/core/app/core/db/Star.scala +++ b/phoenix-scala/core/app/core/db/Star.scala @@ -37,7 +37,7 @@ object * extends LazyLogging { DbResultT.fromResult(fa) def <~[A](v: A)(implicit ec: EC): DbResultT[A] = - DbResultT.pure(v) + v.pure[DbResultT] def <~[A](v: Validated[Failures, A])(implicit ec: EC): DbResultT[A] = DbResultT.fromEither(v.toEither) diff --git a/phoenix-scala/core/app/core/db/package.scala b/phoenix-scala/core/app/core/db/package.scala index b3acfd16db..024bd8e7f1 100644 --- a/phoenix-scala/core/app/core/db/package.scala +++ b/phoenix-scala/core/app/core/db/package.scala @@ -105,20 +105,14 @@ package object db { } trait FoxyTFunctions[F[_]] { - def apply[A](a: A)(implicit F: Monad[F]): FoxyT[F, A] = // TODO: remove me? @michalrus - pure(a) - - def pure[A](a: A)(implicit F: Monad[F]): FoxyT[F, A] = - Monad[FoxyT[F, ?]].pure(a) - def good[A](a: A)(implicit F: Monad[F]): FoxyT[F, A] = // TODO: remove me @michalrus - pure(a) + a.pure[FoxyT[F, ?]] def unit(implicit F: Monad[F]): FoxyT[F, Unit] = - pure(()) // TODO: remove me? @michalrus + ().pure[FoxyT[F, ?]] // TODO: remove me? @michalrus def none[A](implicit F: Monad[F]): FoxyT[F, Option[A]] = - pure(None) // TODO: remove me? @michalrus + (None: Option[A]).pure[FoxyT[F, ?]] // TODO: remove me? @michalrus def uiWarning(f: Failure)(implicit F: Monad[F]): FoxyT[F, Unit] = StateT.modify(MetaResponse.Warning(f) :: _) @@ -161,7 +155,7 @@ package object db { L.map(lfa)(_.fold(Either.left(_), Either.right(_))).sequence.flatMap { xa ⇒ val failures = L.collect(xa) { case Left(f) ⇒ f.toList }.toList.flatten val values = L.collect(xa) { case Right(a) ⇒ a } - NonEmptyList.fromList(failures).fold(FoxyT[F].pure(values))(FoxyT[F].failures(_)) + NonEmptyList.fromList(failures).fold(values.pure[FoxyT[F, ?]])(FoxyT[F].failures(_)) } /** A bit like ``sequence`` but will ignore failed Foxies. */ @@ -276,15 +270,12 @@ package object db { def appendForUpdate[A, B <: slick.dbio.NoStream](sql: SqlAction[A, B, Effect.Read]): DBIO[A] = sql.overrideStatements(sql.statements.map(_ + " for update")) - def lift[A](value: A): DBIO[A] = DBIO.successful(value) - - def liftFuture[A](future: Future[A]): DBIO[A] = DBIO.from(future) - + // TODO: I don’t know… does this help? @michalrus def ifElse[A](condition: Boolean, ifBranch: ⇒ DbResultT[A], elseBranch: ⇒ DbResultT[A]) = if (condition) ifBranch else elseBranch - def doOrMeh(condition: Boolean, action: ⇒ DbResultT[_])(implicit ec: EC): DbResultT[Unit] = - if (condition) action.meh else DbResultT.unit + def when[F[_]](p: Boolean, s: ⇒ F[Unit])(implicit F: Applicative[F]): F[Unit] = + if (p) s.void else F.pure(()) def doOrGood[A](condition: Boolean, action: ⇒ DbResultT[A], good: ⇒ A)(implicit ec: EC): DbResultT[A] = if (condition) action else DbResultT.good(good) diff --git a/phoenix-scala/objectframework/app/objectframework/ObjectUtils.scala b/phoenix-scala/objectframework/app/objectframework/ObjectUtils.scala index 82d1675843..1c7bd5fc2e 100644 --- a/phoenix-scala/objectframework/app/objectframework/ObjectUtils.scala +++ b/phoenix-scala/objectframework/app/objectframework/ObjectUtils.scala @@ -220,7 +220,7 @@ object ObjectUtils { for { commit ← * <~ ObjectCommits.create(ObjectCommit(formId = form.id, shadowId = shadow.id)) } yield commit.some - else DbResultT.pure(None) + else none[ObjectCommit].pure[DbResultT] private def updateIfDifferent( old: FormAndShadow, @@ -244,7 +244,7 @@ object ObjectUtils { } _ ← * <~ validateShadow(form, shadow) } yield UpdateResult(form, shadow, updated = true) - else DbResultT.pure(UpdateResult(old.form, old.shadow, updated = false)) + else UpdateResult(old.form, old.shadow, updated = false).pure[DbResultT] private def validateShadow(form: ObjectForm, shadow: ObjectShadow)(implicit ec: EC, fmt: Formats): DbResultT[Unit] = @@ -252,6 +252,6 @@ object ObjectUtils { def failIfErrors(errors: Seq[Failure])(implicit ec: EC): DbResultT[Unit] = errors match { case head :: tail ⇒ DbResultT.failures(NonEmptyList(head, tail)) - case Nil ⇒ DbResultT.pure(Unit) + case Nil ⇒ ().pure[DbResultT] } } diff --git a/phoenix-scala/objectframework/app/objectframework/models/ObjectHeadLinks.scala b/phoenix-scala/objectframework/app/objectframework/models/ObjectHeadLinks.scala index 1fdbc98c28..328c1f92d4 100644 --- a/phoenix-scala/objectframework/app/objectframework/models/ObjectHeadLinks.scala +++ b/phoenix-scala/objectframework/app/objectframework/models/ObjectHeadLinks.scala @@ -2,6 +2,7 @@ package objectframework.models import java.time.Instant +import cats.implicits._ import core.db.ExPostgresDriver.api._ import core.db._ import objectframework.services.ObjectManager @@ -88,7 +89,7 @@ object ObjectHeadLinks { def createIfNotExist(left: L, right: R)(implicit ec: EC, db: DB): DbResultT[Unit] = for { linkExists ← * <~ filterLeft(left).filter(_.rightId === right.id).exists.result - _ ← * <~ doOrMeh(!linkExists, create(build(left, right))) + _ ← * <~ when(!linkExists, create(build(left, right)).void) } yield {} def build(left: L, right: R): M diff --git a/phoenix-scala/objectframework/app/objectframework/services/ContentManager.scala b/phoenix-scala/objectframework/app/objectframework/services/ContentManager.scala index b350aaa6dc..2dc86f5613 100644 --- a/phoenix-scala/objectframework/app/objectframework/services/ContentManager.scala +++ b/phoenix-scala/objectframework/app/objectframework/services/ContentManager.scala @@ -1,14 +1,12 @@ package objectframework.services import org.json4s._ - import cats.data._ import cats.implicits._ - +import cats.kernel.Monoid import core.db.ExPostgresDriver.api._ import core.db._ import core.failures.Failure - import objectframework.IlluminateAlgorithm import objectframework.content._ import objectframework.db._ @@ -54,7 +52,7 @@ object ContentManager { type FullContentRelations = Map[String, Seq[Content]] def getRelations(content: Content)(implicit ec: EC): DbResultT[FullContentRelations] = { - val empty = DbResultT.pure(Map.empty[String, Seq[Content]]) + val empty = (Map.empty : FullContentRelations).pure[DbResultT] content.relations.foldLeft(empty) { (accRelations, relation) ⇒ accRelations.flatMap { relations ⇒ @@ -106,6 +104,6 @@ object ContentManager { private def failIfErrors(errors: Seq[Failure])(implicit ec: EC): DbResultT[Unit] = errors match { case head :: tail ⇒ DbResultT.failures(NonEmptyList(head, tail)) - case Nil ⇒ DbResultT.pure(Unit) + case Nil ⇒ ().pure[DbResultT] } } diff --git a/phoenix-scala/phoenix/app/phoenix/models/customer/CustomerGroup.scala b/phoenix-scala/phoenix/app/phoenix/models/customer/CustomerGroup.scala index d04f09df38..84cc2e98f5 100644 --- a/phoenix-scala/phoenix/app/phoenix/models/customer/CustomerGroup.scala +++ b/phoenix-scala/phoenix/app/phoenix/models/customer/CustomerGroup.scala @@ -22,7 +22,7 @@ case class CustomerGroup(id: Int = 0, scope: LTree, createdBy: Int, name: String, - customersCount: Int = 0, + customersCount: Int = 0, // FIXME: is this denormalization needed at all? https://foxcommerce.slack.com/archives/C06696D1R/p1498564090580988 @michalrus clientState: Json, elasticRequest: Json, groupType: GroupType, diff --git a/phoenix-scala/phoenix/app/phoenix/models/discount/SearchReference.scala b/phoenix-scala/phoenix/app/phoenix/models/discount/SearchReference.scala index 7122281066..f5c5a287ac 100644 --- a/phoenix-scala/phoenix/app/phoenix/models/discount/SearchReference.scala +++ b/phoenix-scala/phoenix/app/phoenix/models/discount/SearchReference.scala @@ -104,6 +104,6 @@ object SearchReference { def productsSearchField: String = "productId" def skuSearchField: String = "code" - def pureMetrics(implicit ec: EC): Result[Long] = Result.pure(0L) - def pureBuckets(implicit ec: EC): Result[Buckets] = Result.pure(Seq.empty) + def pureMetrics(implicit ec: EC): Result[Long] = 0L.pure[Result] + def pureBuckets(implicit ec: EC): Result[Buckets] = (Seq.empty : Buckets).pure[Result] } diff --git a/phoenix-scala/phoenix/app/phoenix/responses/ReturnResponse.scala b/phoenix-scala/phoenix/app/phoenix/responses/ReturnResponse.scala index 82c006d319..25bc8082a4 100644 --- a/phoenix-scala/phoenix/app/phoenix/responses/ReturnResponse.scala +++ b/phoenix-scala/phoenix/app/phoenix/responses/ReturnResponse.scala @@ -2,9 +2,10 @@ package phoenix.responses import java.time.Instant +import cats.implicits._ import core.db._ import core.utils.Money._ -import phoenix.models.account.{Organization, Organizations, Users} +import phoenix.models.account.{Organization, Organizations, User, Users} import phoenix.models.admin.AdminsData import phoenix.models.customer.CustomersData import phoenix.models.payment.giftcard.GiftCard @@ -103,9 +104,9 @@ object ReturnResponse { // Either customer or storeAdmin as creator customer ← * <~ Users.findOneByAccountId(rma.accountId) customerData ← * <~ CustomersData.findOneByAccountId(rma.accountId) - storeAdmin ← * <~ rma.storeAdminId.map(Users.findOneByAccountId).getOrElse(lift(None)) - adminData ← * <~ rma.storeAdminId.map(AdminsData.findOneByAccountId).getOrElse(lift(None)) - organization ← * <~ rma.storeAdminId.map(Organizations.mustFindByAccountId) + storeAdmin ← rma.storeAdminId.flatTraverse(Users.findOneByAccountId(_).dbresult) + adminData ← * <~ rma.storeAdminId.flatTraverse(AdminsData.findOneByAccountId(_).dbresult) + organization ← * <~ rma.storeAdminId.traverse(Organizations.mustFindByAccountId) // Payment methods ccPayment ← * <~ ReturnPayments.findAllByReturnId(rma.id).creditCards.one applePayPayment ← * <~ ReturnPayments.findAllByReturnId(rma.id).applePays.one diff --git a/phoenix-scala/phoenix/app/phoenix/responses/cord/base/CordResponsePromotions.scala b/phoenix-scala/phoenix/app/phoenix/responses/cord/base/CordResponsePromotions.scala index 4af2b5ad09..0108aebcd6 100644 --- a/phoenix-scala/phoenix/app/phoenix/responses/cord/base/CordResponsePromotions.scala +++ b/phoenix-scala/phoenix/app/phoenix/responses/cord/base/CordResponsePromotions.scala @@ -40,7 +40,7 @@ object CordResponsePromotions { /** Try `fa` and if it’s `None`, evaluate and fallback to `fb`. Basically, `Option#orElse` lifted to `DbResultT`. */ private def lazyOrElse[A](fa: DbResultT[Option[A]], fb: ⇒ DbResultT[Option[A]])( implicit ec: EC): DbResultT[Option[A]] = - fa.flatMap(_.map(a ⇒ DbResultT.pure(a.some)).getOrElse(fb)) + fa.flatMap(_.map(a ⇒ a.some.pure[DbResultT]).getOrElse(fb)) private def renderPromotionResponse( promotion: Promotion)(implicit ec: EC, ctx: OC, db: DB): DbResultT[PromotionResponse.Root] = diff --git a/phoenix-scala/phoenix/app/phoenix/routes/AuthRoutes.scala b/phoenix-scala/phoenix/app/phoenix/routes/AuthRoutes.scala index 9dcf5a25f7..b5f79dfac6 100644 --- a/phoenix-scala/phoenix/app/phoenix/routes/AuthRoutes.scala +++ b/phoenix-scala/phoenix/app/phoenix/routes/AuthRoutes.scala @@ -36,7 +36,7 @@ object AuthRoutes { pathPrefix("public") { (post & path("login") & entity(as[LoginPayload])) { payload ⇒ - doLogin(DbResultT.pure(payload))(_.runDBIO()) + doLogin(payload.pure[DbResultT] )(_.runDBIO()) } ~ activityContext(defaultScope) { implicit ac ⇒ (post & path("send-password-reset") & pathEnd & entity(as[ResetPasswordSend])) { payload ⇒ diff --git a/phoenix-scala/phoenix/app/phoenix/services/Capture.scala b/phoenix-scala/phoenix/app/phoenix/services/Capture.scala index 6c70f12c90..2552c0e0c6 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/Capture.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/Capture.scala @@ -103,7 +103,7 @@ case class Capture(payload: CapturePayloads.Capture)(implicit ec: EC, db: DB, ap externalCaptureTotal ← * <~ determineExternalCapture(total, gcPayments, scPayments, order.currency) internalCaptureTotal = total - externalCaptureTotal _ ← * <~ internalCapture(internalCaptureTotal, order, customer, gcPayments, scPayments) - _ ← * <~ doOrMeh(externalCaptureTotal > 0, externalCapture(externalCaptureTotal, order)) + _ ← * <~ when(externalCaptureTotal > 0, externalCapture(externalCaptureTotal, order)) resp = CaptureResponse( order = order.refNum, @@ -142,8 +142,8 @@ case class Capture(payload: CapturePayloads.Capture)(implicit ec: EC, db: DB, ap scIds = scPayments.map { case (_, sc) ⇒ sc.id }.distinct gcCodes = gcPayments.map { case (_, gc) ⇒ gc.code }.distinct - _ ← * <~ doOrMeh(scTotal > 0, LogActivity().scFundsCaptured(customer, order, scIds, scTotal)) - _ ← * <~ doOrMeh(gcTotal > 0, LogActivity().gcFundsCaptured(customer, order, gcCodes, gcTotal)) + _ ← * <~ when(scTotal > 0, LogActivity().scFundsCaptured(customer, order, scIds, scTotal).void) + _ ← * <~ when(gcTotal > 0, LogActivity().gcFundsCaptured(customer, order, gcCodes, gcTotal).void) } yield {} private def externalCapture(total: Long, order: Order): DbResultT[Unit] = { @@ -277,10 +277,12 @@ case class Capture(payload: CapturePayloads.Capture)(implicit ec: EC, db: DB, ap private def getPrice(item: OrderLineItemProductData): DbResultT[LineItemPrice] = FormShadowGet.price(item.skuForm, item.skuShadow) match { case Some((price, currency)) ⇒ - DbResultT.pure(LineItemPrice(item.lineItem.referenceNumber, item.sku.code, price, currency)) + LineItemPrice(item.lineItem.referenceNumber, item.sku.code, price, currency).pure[DbResultT] case None ⇒ DbResultT.failure(CaptureFailures.SkuMissingPrice(item.sku.code)) } + // FIXME: use MonadError below, no need for DbResultT @michalrus + private def validatePayload(payload: CapturePayloads.Capture, orderSkus: Seq[OrderLineItemProductData]): DbResultT[Unit] = for { @@ -299,12 +301,12 @@ case class Capture(payload: CapturePayloads.Capture)(implicit ec: EC, db: DB, ap private def paymentStateMustBeInAuth(order: Order, paymentState: CordPaymentState.State): DbResultT[Unit] = if (paymentState != CordPaymentState.Auth) DbResultT.failure(CaptureFailures.OrderMustBeInAuthState(order.refNum)) - else DbResultT.pure(Unit) + else ().pure[DbResultT] private def mustHavePositiveShippingCost(shippingCost: CapturePayloads.ShippingCost): DbResultT[Unit] = if (shippingCost.total < 0) DbResultT.failure(CaptureFailures.ShippingCostNegative(shippingCost.total)) - else DbResultT.pure(Unit) + else ().pure[DbResultT] private def mustHaveCodes(items: Seq[CapturePayloads.CaptureLineItem], codes: Seq[String], @@ -316,10 +318,10 @@ case class Capture(payload: CapturePayloads.Capture)(implicit ec: EC, db: DB, ap private def mustHaveCode(item: CapturePayloads.CaptureLineItem, codes: Seq[String], orderRef: String): DbResultT[Unit] = - if (codes.contains(item.sku)) DbResultT.pure(Unit) + if (codes.contains(item.sku)) ().pure[DbResultT] else DbResultT.failure(CaptureFailures.SkuNotFoundInOrder(item.sku, orderRef)) private def mustHaveSameLineItems(lOne: Int, lTwo: Int, orderRef: String): DbResultT[Unit] = - if (lOne == lTwo) DbResultT.pure(Unit) + if (lOne == lTwo) ().pure[DbResultT] else DbResultT.failure(CaptureFailures.SplitCaptureNotSupported(orderRef)) } diff --git a/phoenix-scala/phoenix/app/phoenix/services/CartValidator.scala b/phoenix-scala/phoenix/app/phoenix/services/CartValidator.scala index 0edacb61bb..ed29479249 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/CartValidator.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/CartValidator.scala @@ -35,7 +35,7 @@ case class CartValidator(cart: Cart)(implicit ec: EC, db: DB, ctx: OC) extends C // Deactivation/archival don’t happen often enough to justify // this additional overhead for each cart GET request. hasActiveLineItems(state) - } else DbResultT.pure(state)) + } else state.pure[DbResultT]) state ← * <~ hasShipAddress(state) state ← * <~ validShipMethod(state) state ← * <~ sufficientPayments(state, isCheckout) @@ -145,7 +145,7 @@ case class CartValidator(cart: Cart)(implicit ec: EC, db: DB, ctx: OC) extends C // we'll find out if the `ExternalFunds` doesn't auth at checkout but we presume sufficient funds if we have a // `ExternalFunds` regardless of GC/SC funds availability if (payments.exists(_.isExternalFunds)) { - lift(response) + response.pure[DBIO] } else if (payments.nonEmpty) { cartFunds(payments).map { case Some(funds) if funds >= grandTotal ⇒ @@ -155,7 +155,7 @@ case class CartValidator(cart: Cart)(implicit ec: EC, db: DB, ctx: OC) extends C warning(response, InsufficientFunds(cart.refNum)) } } else { - lift(warning(response, InsufficientFunds(cart.refNum))) + warning(response, InsufficientFunds(cart.refNum)).pure[DBIO] } if (cart.grandTotal > 0 || cart.subTotal > 0) { @@ -164,7 +164,7 @@ case class CartValidator(cart: Cart)(implicit ec: EC, db: DB, ctx: OC) extends C .result .flatMap(availableFunds(cart.grandTotal, _)) } else { - lift(response) + response.pure[DBIO] } } diff --git a/phoenix-scala/phoenix/app/phoenix/services/Checkout.scala b/phoenix-scala/phoenix/app/phoenix/services/Checkout.scala index 87eb43afe8..8843b942e2 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/Checkout.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/Checkout.scala @@ -52,7 +52,7 @@ object PaymentHelper { apis: Apis, ac: AC): DbResultT[Long] = if (payments.isEmpty) { - DbResultT.pure(0L) + 0L.pure[DbResultT] } else { val amounts: Seq[Long] = payments.map { case (payment, _) ⇒ payment.getAmount() } @@ -195,6 +195,7 @@ object Checkout { } class ExternalCalls { + // FIXME: have mercy… @michalrus @volatile var authPaymentsSuccess: Boolean = false @volatile var middleWarehouseSuccess: Boolean = false } @@ -240,10 +241,10 @@ case class Checkout( liSkus ← * <~ CartLineItems.byCordRef(cart.refNum).countSkus inventoryTrackedSkus ← * <~ filterInventoryTrackingSkus(liSkus) skusToHold ← * <~ inventoryTrackedSkus.map(sku ⇒ SkuInventoryHold(sku.code, sku.qty)) - _ ← * <~ doOrMeh(skusToHold.nonEmpty, + _ ← * <~ when(skusToHold.nonEmpty, DbResultT.fromResult( apis.middlewarehouse.hold(OrderInventoryHold(cart.referenceNumber, skusToHold)))) - mutating = externalCalls.middleWarehouseSuccess = skusToHold.nonEmpty + mutating = externalCalls.middleWarehouseSuccess = skusToHold.nonEmpty // FIXME: I almost removed that, having read `==` here. Please, don’t… @michalrus } yield {} private def filterInventoryTrackingSkus(skus: Map[String, Int]) = @@ -331,13 +332,13 @@ case class Checkout( scIds = scPayments.map { case (_, sc) ⇒ sc.id }.distinct gcCodes = gcPayments.map { case (_, gc) ⇒ gc.code }.distinct - _ ← * <~ doOrMeh(scTotal > 0, LogActivity().scFundsAuthorized(customer, cart, scIds, scTotal)) - _ ← * <~ doOrMeh(gcTotal > 0, LogActivity().gcFundsAuthorized(customer, cart, gcCodes, gcTotal)) + _ ← * <~ when(scTotal > 0, LogActivity().scFundsAuthorized(customer, cart, scIds, scTotal).void) + _ ← * <~ when(gcTotal > 0, LogActivity().gcFundsAuthorized(customer, cart, gcCodes, gcTotal).void) grandTotal = cart.grandTotal internalPayments = gcTotal + scTotal - _ ← * <~ doOrMeh(grandTotal > internalPayments, // run external payments only if we have to pay more - doExternalPayment(grandTotal - internalPayments)) + _ ← * <~ when(grandTotal > internalPayments, // run external payments only if we have to pay more + doExternalPayment(grandTotal - internalPayments).void) mutatingResult = externalCalls.authPaymentsSuccess = true // fixme is this flag used anywhere? @aafa } yield {} diff --git a/phoenix-scala/phoenix/app/phoenix/services/CreditCardManager.scala b/phoenix-scala/phoenix/app/phoenix/services/CreditCardManager.scala index e66d60d071..032903bdd9 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/CreditCardManager.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/CreditCardManager.scala @@ -45,7 +45,7 @@ object CreditCardManager { .map(_.gatewayCustomerId) .one address = Address.fromPayload(payload.billingAddress, customer.accountId) - _ ← * <~ doOrMeh(payload.addressIsNew, Addresses.create(address)) + _ ← * <~ when(payload.addressIsNew, Addresses.create(address).void) stripes ← * <~ apis.stripe.createCardFromToken(email = customer.email, token = payload.token, stripeCustomerId = customerToken, @@ -69,7 +69,7 @@ object CreditCardManager { def createCard(customer: User, sCustomer: StripeCustomer, sCard: StripeCard, address: Address) = for { - _ ← * <~ doOrMeh(address.isNew, Addresses.create(address.copy(accountId = accountId))) + _ ← * <~ when(address.isNew, Addresses.create(address.copy(accountId = accountId)).void) cc = CreditCard.buildFromSource(accountId, sCustomer, sCard, payload, address) newCard ← * <~ CreditCards.create(cc) region ← * <~ Regions.findOneById(newCard.address.regionId).safeGet diff --git a/phoenix-scala/phoenix/app/phoenix/services/account/AccountManager.scala b/phoenix-scala/phoenix/app/phoenix/services/account/AccountManager.scala index bbe00a171c..d05f96a5fe 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/account/AccountManager.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/account/AccountManager.scala @@ -94,7 +94,7 @@ object AccountManager { .filter(_.state === (AdminData.Invited: AdminData.State)) .one _ ← * <~ adminCreated.map(ad ⇒ AdminsData.update(ad, ad.copy(state = AdminData.Active))) - _ ← * <~ doOrMeh(adminCreated.isEmpty, LogActivity().userPasswordReset(user)) + _ ← * <~ when(adminCreated.isEmpty, LogActivity().userPasswordReset(user).void) } yield ResetPasswordDoneAnswer(email = remind.email, org = organization.name) def getById(accountId: Int)(implicit ec: EC, db: DB): DbResultT[UserResponse] = @@ -114,7 +114,7 @@ object AccountManager { .findByNameInScope(context.org, scope.id) .mustFindOr(OrganizationNotFound(context.org, scope.path)) - _ ← * <~ doOrMeh(checkEmail, email.fold(DbResultT.unit)(Users.createEmailMustBeUnique)) + _ ← * <~ when(checkEmail, email.fold(DbResultT.unit)(Users.createEmailMustBeUnique)) account ← * <~ Accounts.create(Account()) diff --git a/phoenix-scala/phoenix/app/phoenix/services/actors/RemorseTimer.scala b/phoenix-scala/phoenix/app/phoenix/services/actors/RemorseTimer.scala index 894f30a539..e68cf23388 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/actors/RemorseTimer.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/actors/RemorseTimer.scala @@ -34,7 +34,7 @@ class RemorseTimer(implicit db: DB, ec: EC, apis: Apis) extends Actor { val query = for { cordRefs ← * <~ orders.result count ← * <~ orders.map(_.state).update(newState) - _ ← * <~ doOrMeh(count > 0, logAcitvity(newState, cordRefs)) + _ ← * <~ when(count > 0, logAcitvity(newState, cordRefs)) } yield count RemorseTimerResponse(query.runTxn) diff --git a/phoenix-scala/phoenix/app/phoenix/services/carts/CartLineItemUpdater.scala b/phoenix-scala/phoenix/app/phoenix/services/carts/CartLineItemUpdater.scala index 93dd725861..11e0cab9e1 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/carts/CartLineItemUpdater.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/carts/CartLineItemUpdater.scala @@ -149,7 +149,7 @@ object CartLineItemUpdater { .filterByContext(ctx.id) .filter(_.code === lineItem.sku) .mustFindOneOr(SkuNotFoundForContext(lineItem.sku, ctx.id)) - fullSku ← ObjectManager.getFullObject(DbResultT.pure(sku)) + fullSku ← ObjectManager.getFullObject(sku.pure[DbResultT]) _ ← * <~ IlluminatedSku.illuminate(ctx, fullSku).mustBeActive // TODO: check if that SKU’s Product is not archived/deactivated @michalrus _ ← * <~ mustFindProductIdForSku(sku, cart.refNum) diff --git a/phoenix-scala/phoenix/app/phoenix/services/carts/CartPromotionUpdater.scala b/phoenix-scala/phoenix/app/phoenix/services/carts/CartPromotionUpdater.scala index 8b0cb5b590..3a4f3e681a 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/carts/CartPromotionUpdater.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/carts/CartPromotionUpdater.scala @@ -79,7 +79,7 @@ object CartPromotionUpdater { case JNothing | JNull ⇒ None case cgis ⇒ cgis.extractOpt[Set[Int]] } - result ← * <~ customerGroupIdsO.fold(DbResultT.pure(true))(GroupMemberManager.isMemberOfAny(_, user)) + result ← * <~ customerGroupIdsO.fold(true.pure[DbResultT])(GroupMemberManager.isMemberOfAny(_, user)) } yield result promos.filterA(isApplicable) @@ -120,7 +120,7 @@ object CartPromotionUpdater { promotions ← * <~ promotionsQ.result.dbresult .map(_.toStream) >>= filterPromotionsUsingCustomerGroups(user) promotion ← * <~ promotions.headOption - .map(DbResultT.pure(_)) + .map(_.pure[DbResultT]) .getOrElse(DbResultT.failure(OrderHasNoPromotions)) // TODO: no function for that? Seems useful? @michalrus adjustments ← * <~ getAdjustmentsForPromotion(cart, promotion, failFatally) } yield (orderPromo, promotion, adjustments) diff --git a/phoenix-scala/phoenix/app/phoenix/services/category/CategoryManager.scala b/phoenix-scala/phoenix/app/phoenix/services/category/CategoryManager.scala index 70f3922a44..8c7eb5bcd4 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/category/CategoryManager.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/category/CategoryManager.scala @@ -106,7 +106,7 @@ object CategoryManager { Categories .update(category, category.copy(shadowId = categoryShadow.id, commitId = commit.id)) case None ⇒ - DbResultT.pure(category) + category.pure[DbResultT] } private def contextByName(contextName: String)(implicit ec: EC): DbResultT[ObjectContext] = diff --git a/phoenix-scala/phoenix/app/phoenix/services/customerGroups/GroupMemberManager.scala b/phoenix-scala/phoenix/app/phoenix/services/customerGroups/GroupMemberManager.scala index 4a72d19f65..cc667b3801 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/customerGroups/GroupMemberManager.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/customerGroups/GroupMemberManager.scala @@ -119,8 +119,8 @@ object GroupMemberManager { group ← * <~ CustomerGroups.mustFindById400(groupId) membership = CustomerGroupMember(customerDataId = customerData.id, groupId = groupId) result ← * <~ CustomerGroupMembers.create(membership) - _ ← * <~ doOrMeh(group.groupType == Manual, - CustomerGroups.update(group, group.copy(customersCount = group.customersCount + 1))) + _ ← * <~ when(group.groupType == Manual, + CustomerGroups.update(group, group.copy(customersCount = group.customersCount + 1)).void) } yield result private def deleteGroupMember(userId: Int, groupId: Int)(implicit ec: EC, db: DB): DbResultT[Unit] = @@ -132,8 +132,8 @@ object GroupMemberManager { .mustFindOneOr(NotFoundFailure400(User, userId)) _ ← * <~ CustomerGroupMembers .deleteById(membership.id, DbResultT.unit, userId ⇒ NotFoundFailure400(User, userId)) - _ ← * <~ doOrMeh(group.groupType == Manual, - CustomerGroups.update(group, group.copy(customersCount = group.customersCount - 1))) + _ ← * <~ when(group.groupType == Manual, + CustomerGroups.update(group, group.copy(customersCount = group.customersCount - 1)).void) } yield {} def isMemberOfAny(groupIds: Set[Int], customer: User)(implicit ec: EC, apis: Apis): DbResultT[Boolean] = @@ -161,7 +161,7 @@ object GroupMemberManager { } // FIXME: make sure the warning bubbles up to the final response — monad stack order should be different, we don’t want to lose warnings when a Failure happens @michalrus } yield (num > 0) - else DbResultT.pure(false) + else false.pure[DbResultT] private def narrowDownWithUserId(userId: Int)(elasticRequest: Json): Json = { val term = JObject(JField("term", JObject(JField("id", JInt(userId))))) diff --git a/phoenix-scala/phoenix/app/phoenix/services/orders/OrderStateUpdater.scala b/phoenix-scala/phoenix/app/phoenix/services/orders/OrderStateUpdater.scala index ae74377126..0168c9cd8e 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/orders/OrderStateUpdater.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/orders/OrderStateUpdater.scala @@ -31,10 +31,10 @@ object OrderStateUpdater { _ ← * <~ order.transitionState(newState) _ ← * <~ updateQueries(admin, Seq(refNum), newState) updated ← * <~ Orders.mustFindByRefNum(refNum) - _ ← * <~ doOrMeh(updated.state == Order.Canceled, + _ ← * <~ when(updated.state == Order.Canceled, DbResultT.fromResult(apis.middlewarehouse.cancelHold(refNum))) response ← * <~ OrderResponse.fromOrder(updated, grouped = true) - _ ← * <~ doOrMeh(order.state != newState, LogActivity().orderStateChanged(admin, response, order.state)) + _ ← * <~ when(order.state != newState, LogActivity().orderStateChanged(admin, response, order.state).void) } yield response def updateStates(admin: User, diff --git a/phoenix-scala/phoenix/app/phoenix/services/product/ProductManager.scala b/phoenix-scala/phoenix/app/phoenix/services/product/ProductManager.scala index 0911412297..9d35243cc1 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/product/ProductManager.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/product/ProductManager.scala @@ -2,6 +2,7 @@ package phoenix.services.product import java.time.Instant +import cats._ import cats.data._ import cats.implicits._ import com.typesafe.scalalogging.LazyLogging @@ -98,16 +99,16 @@ object ProductManager extends LazyLogging { oldProduct ← * <~ Products.mustFindFullByReference(productId) illuminated = IlluminatedProduct .illuminate(oc, oldProduct.model, oldProduct.form, oldProduct.shadow) - _ ← * <~ doOrMeh( + _ ← when( checkActive, { illuminated.mustBeActive match { case Left(err) ⇒ { logger.warn(err.toString) - DbResultT.failure(NotFoundFailure404(Product, oldProduct.model.slug)) + DbResultT.failure(NotFoundFailure404(Product, oldProduct.model.slug)).void } case Right(_) ⇒ DbResultT.unit } - } + } : DbResultT[Unit] ) albums ← * <~ ImageManager.getAlbumsForProduct(oldProduct.model.reference) @@ -409,14 +410,14 @@ object ProductManager extends LazyLogging { def mustFindFullProductById(productId: Int)(implicit ec: EC, db: DB): DbResultT[FullObject[Product]] = ObjectManager.getFullObject(Products.mustFindById404(productId)) - // This is an inefficient intensely quering method that does the trick + // This is an inefficient intensely querying method that does the trick private def skusToBeUnassociatedMustNotBePresentInCarts(productId: Int, payloadSkus: Seq[SkuPayload])( implicit ec: EC, db: DB): DbResultT[Unit] = for { skuIdsForProduct ← * <~ ProductSkuLinks.filter(_.leftId === productId).result.flatMap { case links @ Seq(_) ⇒ - lift(links.map(_.rightId)) + links.map(_.rightId).pure[DBIO] case _ ⇒ for { variantLinks ← ProductVariantLinks diff --git a/phoenix-scala/phoenix/app/phoenix/services/returns/ReturnLineItemManager.scala b/phoenix-scala/phoenix/app/phoenix/services/returns/ReturnLineItemManager.scala index 47571ef97e..3cef6a5c73 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/returns/ReturnLineItemManager.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/returns/ReturnLineItemManager.scala @@ -50,7 +50,7 @@ object ReturnLineItemManager { .to[List] .result _ ← * <~ skusLiQuery.deleteAll - _ ← * <~ doOrMeh(skus.nonEmpty, LogActivity().returnSkuLineItemsDropped(skus)) + _ ← * <~ when(skus.nonEmpty, LogActivity().returnSkuLineItemsDropped(skus).void) _ ← * <~ payload.map(p ⇒ ReturnReasons.mustFindById400(p.reasonId).flatMap(addSkuLineItem(rma, _, p))) updated ← * <~ Returns.refresh(rma) response ← * <~ ReturnResponse.fromRma(updated) @@ -167,11 +167,11 @@ object ReturnLineItemManager { rma ← * <~ Returns.mustFindActiveByRefNum404(refNum) li ← * <~ ReturnLineItems.mustFindById404(lineItemId) deleted ← * <~ ReturnLineItems.filter(_.id === li.id).deleteAllWithRowsBeingAffected - _ ← * <~ doOrMeh( + _ ← * <~ when( deleted, li.originType match { - case ReturnLineItem.ShippingCost ⇒ LogActivity().returnShippingCostItemDeleted(li) - case ReturnLineItem.SkuItem ⇒ LogActivity().returnSkuLineItemDeleted(li) + case ReturnLineItem.ShippingCost ⇒ LogActivity().returnShippingCostItemDeleted(li).void + case ReturnLineItem.SkuItem ⇒ LogActivity().returnSkuLineItemDeleted(li).void } ) updated ← * <~ Returns.refresh(rma) diff --git a/phoenix-scala/phoenix/app/phoenix/services/returns/ReturnPaymentManager.scala b/phoenix-scala/phoenix/app/phoenix/services/returns/ReturnPaymentManager.scala index 4cb0dcea1d..b06b304a14 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/returns/ReturnPaymentManager.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/returns/ReturnPaymentManager.scala @@ -121,7 +121,7 @@ object ReturnPaymentManager { amount = ccAmount, maxAmount = maxCCAmount)) } yield () - else DbResultT.pure(()) + else ().pure[DbResultT] } for { @@ -237,19 +237,19 @@ object ReturnPaymentManager { updated ← * <~ Returns.refresh(rma) response ← * <~ ReturnResponse.fromRma(rma) - _ ← * <~ doOrMeh(paymentWasDeleted, LogActivity().returnPaymentsDeleted(response, List(paymentMethod))) + _ ← * <~ when(paymentWasDeleted, LogActivity().returnPaymentsDeleted(response, List(paymentMethod)).void) } yield response private def deletePayments( rma: Return, payments: List[PaymentMethod.Type])(implicit ec: EC, db: DB, ac: AC): DbResultT[ReturnResponse.Root] = for { - deleted ← * <~ payments.map(pmt ⇒ processDeletePayment(rma.id, pmt).product(DbResultT.pure(pmt))) + deleted ← * <~ payments.map(pmt ⇒ processDeletePayment(rma.id, pmt).product(pmt.pure[DbResultT])) deletedPayments = deleted.collect { case (true, pmt) ⇒ pmt } updated ← * <~ Returns.refresh(rma) response ← * <~ ReturnResponse.fromRma(updated) - _ ← * <~ doOrMeh(deletedPayments.nonEmpty, - LogActivity().returnPaymentsDeleted(response, deletedPayments)) + _ ← * <~ when(deletedPayments.nonEmpty, + LogActivity().returnPaymentsDeleted(response, deletedPayments).void) } yield response private def processDeletePayment(returnId: Int, paymentMethod: PaymentMethod.Type)( diff --git a/phoenix-scala/phoenix/app/phoenix/services/returns/ReturnService.scala b/phoenix-scala/phoenix/app/phoenix/services/returns/ReturnService.scala index f538629136..5735c8dd1e 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/returns/ReturnService.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/returns/ReturnService.scala @@ -1,5 +1,6 @@ package phoenix.services.returns +import cats.implicits._ import core.db._ import phoenix.failures.InvalidCancellationReasonFailure import phoenix.failures.ReturnFailures.OrderMustBeShippedForReturn @@ -40,14 +41,14 @@ object ReturnService { for { rma ← * <~ Returns.mustFindByRefNum(refNum) _ ← * <~ rma.transitionState(payload.state) - reason ← * <~ payload.reasonId.map(Reasons.findOneById).getOrElse(lift(None)) + reason ← * <~ payload.reasonId.flatTraverse(Reasons.findOneById(_).dbresult) _ ← * <~ reason.map(r ⇒ failIfNot(r.reasonType == Cancellation, InvalidCancellationReasonFailure)) _ ← * <~ update(rma, reason, payload) updated ← * <~ Returns.refresh(rma) response ← * <~ ReturnResponse.fromRma(updated) customer ← * <~ Users.mustFindByAccountId(rma.accountId) - _ ← * <~ doOrMeh(rma.state != payload.state, - LogActivity().returnStateChanged(customer, response, payload.state)) + _ ← * <~ when(rma.state != payload.state, + LogActivity().returnStateChanged(customer, response, payload.state).void) } yield response private def update(rma: Return, @@ -56,8 +57,8 @@ object ReturnService { for { rma ← * <~ Returns .update(rma, rma.copy(state = payload.state, canceledReasonId = reason.map(_.id))) - _ ← * <~ doOrMeh(rma.state == Return.Complete, ReturnPaymentManager.issueRefunds(rma)) - _ ← * <~ doOrMeh(rma.state == Return.Canceled, ReturnPaymentManager.cancelRefunds(rma)) + _ ← * <~ when(rma.state == Return.Complete, ReturnPaymentManager.issueRefunds(rma)) + _ ← * <~ when(rma.state == Return.Canceled, ReturnPaymentManager.cancelRefunds(rma)) } yield rma // todo should be available for non-admin as well diff --git a/phoenix-scala/phoenix/app/phoenix/services/returns/ReturnTotaler.scala b/phoenix-scala/phoenix/app/phoenix/services/returns/ReturnTotaler.scala index 25daf8dd08..03802a6e25 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/returns/ReturnTotaler.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/returns/ReturnTotaler.scala @@ -1,5 +1,6 @@ package phoenix.services.returns +import cats.implicits._ import objectframework.models.{ObjectForms, ObjectShadows} import objectframework.DbObjectUtils._ import phoenix.models.returns._ @@ -7,7 +8,7 @@ import core.db.ExPostgresDriver.api._ import core.db._ object ReturnTotaler { - def adjustmentsTotal(rma: Return)(implicit ec: EC): DbResultT[Long] = DbResultT.pure(0) + def adjustmentsTotal(rma: Return)(implicit ec: EC): DbResultT[Long] = 0L.pure[DbResultT] def subTotal(rma: Return)(implicit ec: EC): DbResultT[Long] = (for { diff --git a/phoenix-scala/phoenix/app/phoenix/services/returns/ReturnValidator.scala b/phoenix-scala/phoenix/app/phoenix/services/returns/ReturnValidator.scala index 3324214dd7..4cb6340195 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/returns/ReturnValidator.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/returns/ReturnValidator.scala @@ -1,5 +1,6 @@ package phoenix.services.returns +import cats.implicits._ import core.failures.{Failure, Failures} import phoenix.failures.ReturnFailures.EmptyReturn import phoenix.models.returns._ @@ -35,13 +36,13 @@ case class ReturnValidator(rma: Return)(implicit ec: EC) extends ReturnValidatio */ // Query previous completed RMAs, find matches between line items private def hasNoPreviouslyRefundedItems(response: ReturnValidatorResponse): DBIO[ReturnValidatorResponse] = - lift(response) + response.pure[DBIO] // Has at least one payment method // Can refund up to the total charged on that order payment method // Can refund up to the total charged on that order private def hasValidPaymentMethods(response: ReturnValidatorResponse): DBIO[ReturnValidatorResponse] = - lift(response) + response.pure[DBIO] private def warning(response: ReturnValidatorResponse, failure: Failure): ReturnValidatorResponse = response.copy( diff --git a/phoenix-scala/phoenix/app/phoenix/services/taxonomy/TaxonomyManager.scala b/phoenix-scala/phoenix/app/phoenix/services/taxonomy/TaxonomyManager.scala index 2a47700d28..cda5acae3b 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/taxonomy/TaxonomyManager.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/taxonomy/TaxonomyManager.scala @@ -160,7 +160,7 @@ object TaxonomyManager { .map(Some(_))) _ ← * <~ location.position.fold(DbResultT.unit) { position ⇒ - doOrMeh( + when( position != 0, TaxonomyTaxonLinks .active() @@ -191,9 +191,7 @@ object TaxonomyManager { .mustFindOneOr(InvalidTaxonomiesForTaxon(taxonFull.model, 0)) taxonomy ← * <~ Taxonomies.findOneById(taxonomyTaxonLink.leftId).safeGet maybeParent ← * <~ TaxonomyTaxonLinks.parentOf(taxonomyTaxonLink) - parentTaxon ← * <~ maybeParent - .map(link ⇒ Taxons.findOneById(link.rightId)) - .getOrElse(lift(None)) + parentTaxon ← * <~ maybeParent.flatTraverse(link ⇒ Taxons.findOneById(link.rightId).dbresult) } yield FullTaxonResponse.build(taxonFull, taxonomy.formId, parentTaxon.map(_.formId)) private def updateTaxonomyHierarchy(taxon: Taxon, @@ -205,7 +203,7 @@ object TaxonomyManager { .active() .mustFindByTaxonomyAndTaxonFormId(taxonomy.model, taxon.formId) moveSpec ← * <~ MoveSpec(link, parentLink, location.position).validate - _ ← * <~ doOrMeh(moveSpec.isMoveRequired, moveTaxon(taxonomy.model, moveSpec)) + _ ← * <~ when(moveSpec.isMoveRequired, moveTaxon(taxonomy.model, moveSpec)) } yield taxonomy private def mustFindSingleTaxonomyForTaxon(taxon: Taxon)(implicit ec: EC, diff --git a/phoenix-scala/phoenix/test/integration/CreditCardsIntegrationTest.scala b/phoenix-scala/phoenix/test/integration/CreditCardsIntegrationTest.scala index d9e2d3ba2f..c962d8ce2e 100644 --- a/phoenix-scala/phoenix/test/integration/CreditCardsIntegrationTest.scala +++ b/phoenix-scala/phoenix/test/integration/CreditCardsIntegrationTest.scala @@ -22,7 +22,7 @@ import testutils.apis._ import testutils.fixtures.BakedFixtures import testutils.fixtures.PaymentFixtures.CreditCardsFixture import testutils.fixtures.api.ApiFixtureHelpers -import core.db._ +import core.db.{when => ifM, _} class CreditCardsIntegrationTest extends IntegrationTestBase diff --git a/phoenix-scala/phoenix/test/integration/PromotionsIntegrationTest.scala b/phoenix-scala/phoenix/test/integration/PromotionsIntegrationTest.scala index 2e7dde15e0..8dc4871311 100644 --- a/phoenix-scala/phoenix/test/integration/PromotionsIntegrationTest.scala +++ b/phoenix-scala/phoenix/test/integration/PromotionsIntegrationTest.scala @@ -90,14 +90,14 @@ class PromotionsIntegrationTest "creation" in new StoreAdmin_Seed with Promotion_Seed { ObjectManager - .getFullObject(DbResultT.pure(promotion)) + .getFullObject(promotion.pure[DbResultT]) .gimme .getAttribute("activeFrom") must !==(JNothing) } "updating" in new AutoApplyPromotionSeed { - var fullPromotion = ObjectManager.getFullObject(DbResultT.pure(promotion)).gimme + var fullPromotion = ObjectManager.getFullObject(promotion.pure[DbResultT]).gimme fullPromotion.getAttribute("activeFrom") must === (JNothing) val attributes: List[(String, JValue)] = diff --git a/phoenix-scala/phoenix/test/integration/services/CheckoutTest.scala b/phoenix-scala/phoenix/test/integration/services/CheckoutTest.scala index a2effda832..77e974ee5f 100644 --- a/phoenix-scala/phoenix/test/integration/services/CheckoutTest.scala +++ b/phoenix-scala/phoenix/test/integration/services/CheckoutTest.scala @@ -28,7 +28,7 @@ import phoenix.utils.seeds.Factories import slick.jdbc.PostgresProfile.api._ import testutils._ import testutils.fixtures.BakedFixtures -import core.db._ +import core.db.{when => ifM, _} import core.utils.Money._ import phoenix.services.carts.CartLineItemUpdater diff --git a/phoenix-scala/phoenix/test/integration/testutils/TestSeeds.scala b/phoenix-scala/phoenix/test/integration/testutils/TestSeeds.scala index ef9790a190..6841100f61 100644 --- a/phoenix-scala/phoenix/test/integration/testutils/TestSeeds.scala +++ b/phoenix-scala/phoenix/test/integration/testutils/TestSeeds.scala @@ -43,7 +43,7 @@ trait TestSeeds extends TestFixtureBase { .headOption ad ← * <~ (maybeAdmin match { - case Some(admin) ⇒ DbResultT.pure(admin) + case Some(admin) ⇒ admin.pure[DbResultT] case None ⇒ Factories.createStoreAdmin(user = Factories.storeAdmin, password = password, diff --git a/phoenix-scala/phoenix/test/integration/utils/MockedApis.scala b/phoenix-scala/phoenix/test/integration/utils/MockedApis.scala index ebe0978214..47fc7c03b2 100644 --- a/phoenix-scala/phoenix/test/integration/utils/MockedApis.scala +++ b/phoenix-scala/phoenix/test/integration/utils/MockedApis.scala @@ -2,7 +2,7 @@ package utils import cats.implicits._ import com.stripe.model.DeletedCard -import core.db._ +import core.db.{when => ifM, _} import java.io.File import org.apache.avro.generic.GenericData import org.apache.kafka.clients.producer.MockProducer @@ -129,7 +129,7 @@ trait MockedApis extends MockitoSugar with MustMatchers with OptionValues with A when(mocked.hold(any[OrderInventoryHold])(any[EC], any[AU])).thenReturn(Result.unit) when(mocked.cancelHold(any[String])(any[EC], any[AU])).thenReturn(Result.unit) when(mocked.createSku(any[Int], any[CreateSku])(any[EC], any[AU])) - .thenReturn(DbResultT.pure(ProductVariantSku(skuId = -1, mwhSkuId = -1))) + .thenReturn(ProductVariantSku(skuId = -1, mwhSkuId = -1).pure[DbResultT]) mocked } From fd29f48a5418b40c81a5c26ad17ef5a490bc0aba Mon Sep 17 00:00:00 2001 From: Michal Rus Date: Wed, 28 Jun 2017 15:21:20 +0200 Subject: [PATCH 2/2] Get rid of some more custom functions --- .../core/app/core/db/ExceptionWrapper.scala | 2 +- .../core/app/core/db/FoxTableQuery.scala | 2 +- .../core/app/core/db/SearchTerms.scala | 9 +-- phoenix-scala/core/app/core/db/Star.scala | 39 ++++++------ phoenix-scala/core/app/core/db/package.scala | 59 +++++++++---------- .../objectframework/IlluminateAlgorithm.scala | 5 +- .../app/objectframework/ObjectUtils.scala | 2 +- .../models/ObjectHeadLinks.scala | 4 +- .../objectframework/models/OrderedLinks.scala | 3 +- .../payloads/ObjectSchemaValidation.scala | 3 +- .../services/ContentManager.scala | 4 +- .../app/phoenix/models/account/User.scala | 2 +- .../phoenix/models/activity/Dimension.scala | 3 +- .../models/coupon/IlluminatedCoupon.scala | 3 +- .../models/customer/CustomerGroup.scala | 23 ++++---- .../models/discount/DiscountBase.scala | 1 + .../models/discount/DiscountValidator.scala | 3 +- .../models/discount/SearchReference.scala | 2 +- .../models/discount/offers/Offer.scala | 5 +- .../discount/qualifiers/Qualifier.scala | 4 +- .../app/phoenix/models/inventory/Sku.scala | 2 +- .../payment/creditcard/CreditCard.scala | 2 +- .../app/phoenix/models/product/MvpModel.scala | 2 +- .../app/phoenix/models/product/Product.scala | 2 +- .../models/taxonomy/TaxonomyTaxonLink.scala | 5 +- .../phoenix/responses/AddressResponse.scala | 2 +- .../phoenix/responses/ReturnResponse.scala | 6 +- .../app/phoenix/routes/AuthRoutes.scala | 2 +- .../app/phoenix/services/AddressManager.scala | 2 +- .../app/phoenix/services/Capture.scala | 2 +- .../app/phoenix/services/CartValidator.scala | 4 +- .../app/phoenix/services/Checkout.scala | 26 ++++---- .../phoenix/services/CreditCardManager.scala | 8 +-- .../phoenix/services/LineItemManager.scala | 38 +++++------- .../services/NotificationManager.scala | 8 ++- .../services/SaveForLaterManager.scala | 2 +- .../phoenix/services/ShippingManager.scala | 2 +- .../phoenix/services/StoreAdminManager.scala | 8 +-- .../phoenix/services/StoreCreditService.scala | 8 +-- .../services/account/AccountManager.scala | 4 +- .../services/actors/RemorseTimer.scala | 2 +- .../services/assignments/package.scala | 27 ++++----- .../services/carts/CartLineItemUpdater.scala | 14 ++--- .../services/carts/CartPaymentUpdater.scala | 6 +- .../services/category/CategoryManager.scala | 1 + .../services/coupon/CouponManager.scala | 2 +- .../services/coupon/CouponUsageService.scala | 13 ++-- .../customerGroups/GroupManager.scala | 3 +- .../customerGroups/GroupMemberManager.scala | 12 ++-- .../services/customers/CustomerManager.scala | 6 +- .../services/discount/DiscountManager.scala | 2 +- .../services/giftcards/GiftCardService.scala | 7 +-- .../phoenix/services/image/ImageManager.scala | 4 +- .../services/inventory/SkuManager.scala | 2 +- .../app/phoenix/services/notes/package.scala | 2 +- .../services/orders/OrderStateUpdater.scala | 9 +-- .../services/plugins/PluginsManager.scala | 3 +- .../services/product/ProductManager.scala | 12 ++-- .../services/promotion/PromotionManager.scala | 3 +- .../returns/ReturnPaymentManager.scala | 5 +- .../returns/ReturnReasonsManager.scala | 3 +- .../services/returns/ReturnService.scala | 2 +- .../review/ProductReviewManager.scala | 2 +- .../services/taxonomy/TaxonomyManager.scala | 39 ++++++------ .../phoenix/services/tree/TreeManager.scala | 9 ++- .../services/variant/VariantManager.scala | 5 +- .../phoenix/utils/apis/StripeWrapper.scala | 2 +- .../phoenix/utils/seeds/AddressSeeds.scala | 2 +- .../phoenix/utils/seeds/CreditCardSeeds.scala | 2 +- .../phoenix/utils/seeds/GiftCardSeeds.scala | 4 +- .../utils/seeds/GroupTemplatesSeeds.scala | 5 +- .../utils/seeds/ObjectSchemaSeeds.scala | 5 +- .../app/phoenix/utils/seeds/ReturnSeeds.scala | 2 +- .../utils/seeds/StoreCreditSeeds.scala | 2 +- .../seeds/generators/OrderGenerator.scala | 9 +-- .../seeds/generators/SeedsGenerator.scala | 2 +- .../AllOrdersIntegrationTest.scala | 2 +- .../integration/CartIntegrationTest.scala | 2 +- .../CartValidatorIntegrationTest.scala | 2 +- .../CreditCardsIntegrationTest.scala | 8 +-- .../integration/ProductIntegrationTest.scala | 8 +-- .../integration/services/CheckoutTest.scala | 14 ++--- .../integration/testutils/DbTestSupport.scala | 2 +- .../testutils/fixtures/RawFixtures.scala | 2 +- .../integration/utils/DbResultTTest.scala | 6 +- .../test/integration/utils/MockedApis.scala | 30 +++++----- .../utils/ModelIntegrationTest.scala | 5 +- .../utils/TransactionRollbackTest.scala | 6 +- phoenix-scala/seeder/app/seeds/Seeds.scala | 10 ++-- 89 files changed, 325 insertions(+), 315 deletions(-) diff --git a/phoenix-scala/core/app/core/db/ExceptionWrapper.scala b/phoenix-scala/core/app/core/db/ExceptionWrapper.scala index c7492f2a37..8416f42bbd 100644 --- a/phoenix-scala/core/app/core/db/ExceptionWrapper.scala +++ b/phoenix-scala/core/app/core/db/ExceptionWrapper.scala @@ -11,7 +11,7 @@ object ExceptionWrapper { import scala.util.{Failure, Success} dbio.asTry.dbresult.flatMap { - case Success(value) ⇒ DbResultT.good(value) + case Success(value) ⇒ value.pure[DbResultT] case Failure(e) ⇒ DbResultT.failure(DatabaseFailure(e.getMessage)) } } diff --git a/phoenix-scala/core/app/core/db/FoxTableQuery.scala b/phoenix-scala/core/app/core/db/FoxTableQuery.scala index 164468f848..29428ae3f8 100644 --- a/phoenix-scala/core/app/core/db/FoxTableQuery.scala +++ b/phoenix-scala/core/app/core/db/FoxTableQuery.scala @@ -86,7 +86,7 @@ abstract class FoxTableQuery[M <: FoxModel[M], T <: FoxTable[M]](construct: Tag } def refresh(model: M)(implicit ec: EC): DBIO[M] = - findOneById(model.id).safeGet + findOneById(model.id).unsafeGet type QuerySeq = Query[T, M, Seq] diff --git a/phoenix-scala/core/app/core/db/SearchTerms.scala b/phoenix-scala/core/app/core/db/SearchTerms.scala index 368ef53de8..817838d1e2 100644 --- a/phoenix-scala/core/app/core/db/SearchTerms.scala +++ b/phoenix-scala/core/app/core/db/SearchTerms.scala @@ -1,5 +1,6 @@ package core.db +import cats.implicits._ import core.failures.{Failure, NotFoundFailure400, NotFoundFailure404} import core.utils.Strings._ import slick.jdbc.PostgresProfile.api._ @@ -24,7 +25,7 @@ trait SearchById[M <: FoxModel[M], T <: FoxTable[M]] { private def mustFindById(id: M#Id, notFoundFailure: M#Id ⇒ Failure = notFound404K)(implicit ec: EC, db: DB): DbResultT[M] = this.findOneById(id).dbresult.flatMap { - case Some(model) ⇒ DbResultT.good(model) + case Some(model) ⇒ model.pure[DbResultT] case None ⇒ DbResultT.failure(notFoundFailure(id)) } } @@ -37,7 +38,7 @@ trait SearchByRefNum[M <: FoxModel[M], T <: FoxTable[M]] extends SearchById[M, T implicit ec: EC, db: DB): DbResultT[M] = findOneByRefNum(refNum).dbresult.flatMap { - case Some(model) ⇒ DbResultT.good(model) + case Some(model) ⇒ model.pure[DbResultT] case None ⇒ DbResultT.failure(notFoundFailure(refNum)) } } @@ -49,7 +50,7 @@ trait SearchByCode[M <: FoxModel[M], T <: FoxTable[M]] extends SearchById[M, T] def mustFindByCode(code: String, notFoundFailure: String ⇒ Failure = notFound404K)(implicit ec: EC, db: DB): DbResultT[M] = findOneByCode(code).dbresult.flatMap { - case Some(model) ⇒ DbResultT.good(model) + case Some(model) ⇒ model.pure[DbResultT] case None ⇒ DbResultT.failure(notFoundFailure(code)) } } @@ -62,7 +63,7 @@ trait SearchByIdAndName[M <: FoxModel[M], T <: FoxTable[M]] extends SearchById[M implicit ec: EC, db: DB): DbResultT[M] = findOneByIdAndName(id, name).dbresult.flatMap { - case Some(model) ⇒ DbResultT.good(model) + case Some(model) ⇒ model.pure[DbResultT] case None ⇒ DbResultT.failure(notFoundFailure(name)) } } diff --git a/phoenix-scala/core/app/core/db/Star.scala b/phoenix-scala/core/app/core/db/Star.scala index 09ca267c13..c84744143c 100644 --- a/phoenix-scala/core/app/core/db/Star.scala +++ b/phoenix-scala/core/app/core/db/Star.scala @@ -17,17 +17,17 @@ object * extends LazyLogging { def <~[A](v: SqlAction[A, NoStream, Effect.All])(implicit ec: EC): DbResultT[A] = <~(v.map(Either.right)) - def <~[A](v: DBIO[A])(implicit ec: EC): DbResultT[A] = - DbResultT.fromF(v) + def <~[A](fa: DBIO[A])(implicit ec: EC): DbResultT[A] = + DbResultT.fromF(fa) - def <~[A](v: Either[Failures, A])(implicit ec: EC): DbResultT[A] = - DbResultT.fromEither(v) + def <~[A](fa: Either[Failures, A])(implicit ec: EC): DbResultT[A] = + DbResultT.fromEither(fa) - def <~[A](v: Future[Either[Failures, A]])(implicit M1: Monad[DBIO], M2: Monad[Future]): DbResultT[A] = - DbResultT.fromResult(Result.fromFEither(v)) + def <~[A](gfa: Future[Either[Failures, A]])(implicit M1: Monad[DBIO], M2: Monad[Future]): DbResultT[A] = + DbResultT.fromResult(Result.fromFEither(gfa)) - def <~[A](v: Future[A])(implicit ec: EC): DbResultT[A] = - <~(v.map(Either.right(_)).recover { + def <~[A](fa: Future[A])(implicit ec: EC): DbResultT[A] = + <~(fa.map(Either.right).recover { case ex ⇒ logger.error("A Future failed during conversion to DbResultT.", ex) Either.left(GeneralFailure(ex.getMessage).single) @@ -36,22 +36,25 @@ object * extends LazyLogging { def <~[A](fa: Result[A])(implicit ec: EC): DbResultT[A] = DbResultT.fromResult(fa) - def <~[A](v: A)(implicit ec: EC): DbResultT[A] = - v.pure[DbResultT] + // TODO: Is this more readable than inlining? @michalrus + def <~[A](a: A)(implicit ec: EC): DbResultT[A] = + a.pure[DbResultT] def <~[A](v: Validated[Failures, A])(implicit ec: EC): DbResultT[A] = DbResultT.fromEither(v.toEither) - def <~[M[_]: TraverseFilter, A](v: M[DbResultT[A]])(implicit ec: EC): DbResultT[M[A]] = - DbResultT.seqCollectFailures(v) + def <~[M[_]: TraverseFilter, A](fas: M[DbResultT[A]])(implicit ec: EC): DbResultT[M[A]] = + DbResultT.seqCollectFailures(fas) // FIXME: Remove this function after switching all Seqs to List/Vector. Cats don’t have instances for Seq and Seq is unsound. PM me or @kjanosz for details. @michalrus - def <~[A](v: Seq[DbResultT[A]])(implicit ec: EC): DbResultT[List[A]] = - DbResultT.seqCollectFailures(v.toList) + def <~[A](fas: Seq[DbResultT[A]])(implicit ec: EC): DbResultT[List[A]] = + DbResultT.seqCollectFailures(fas.toList) - def <~[A](v: DbResultT[A]): DbResultT[A] = - v + // TODO: Is this more readable than inlining? @michalrus + def <~[A](fa: DbResultT[A]): DbResultT[A] = + fa - def <~[A](v: Option[DbResultT[A]])(implicit ec: EC): DbResultT[Option[A]] = // TODO: sequence? @michalrus - yes, please! @aafa - v.fold(DbResultT.none[A])(_.map(Some(_))) + // TODO: Is this more readable than inlining? @michalrus + def <~[A](ofa: Option[DbResultT[A]])(implicit ec: EC): DbResultT[Option[A]] = + ofa.sequence } diff --git a/phoenix-scala/core/app/core/db/package.scala b/phoenix-scala/core/app/core/db/package.scala index 024bd8e7f1..751d8742c6 100644 --- a/phoenix-scala/core/app/core/db/package.scala +++ b/phoenix-scala/core/app/core/db/package.scala @@ -86,9 +86,6 @@ package object db { def fold[B](ra: Failures ⇒ B, rb: A ⇒ B)(implicit F: Monad[F]): FoxyT[F, B] = // TODO: this is not fold… Find a better name or remove it? @michalrus fa.map(rb).handleError(ra) - def meh(implicit M: Monad[F]): FoxyT[F, Unit] = - fa.void // TODO: remove me? But it’s cute… @michalrus - def failuresToWarnings(valueIfWasFailed: A)(pf: PartialFunction[Failure, Boolean])( implicit F: Monad[F]): FoxyT[F, A] = fa.handleErrorWith { fs ⇒ @@ -105,15 +102,6 @@ package object db { } trait FoxyTFunctions[F[_]] { - def good[A](a: A)(implicit F: Monad[F]): FoxyT[F, A] = // TODO: remove me @michalrus - a.pure[FoxyT[F, ?]] - - def unit(implicit F: Monad[F]): FoxyT[F, Unit] = - ().pure[FoxyT[F, ?]] // TODO: remove me? @michalrus - - def none[A](implicit F: Monad[F]): FoxyT[F, Option[A]] = - (None: Option[A]).pure[FoxyT[F, ?]] // TODO: remove me? @michalrus - def uiWarning(f: Failure)(implicit F: Monad[F]): FoxyT[F, Unit] = StateT.modify(MetaResponse.Warning(f) :: _) @@ -149,6 +137,8 @@ package object db { case _ ⇒ EitherT.right(F.pure((s, ()))) }) + // TODO: maybe move the quasi-`sequence`-s from Functions to Ops? @michalrus + /** Just like ``sequence`` but—in case of a failure—unlawful, as it will join failures from all Foxies. */ def seqCollectFailures[L[_], A](lfa: L[FoxyT[F, A]])(implicit L: TraverseFilter[L], F: Monad[F]): FoxyT[F, L[A]] = @@ -270,32 +260,40 @@ package object db { def appendForUpdate[A, B <: slick.dbio.NoStream](sql: SqlAction[A, B, Effect.Read]): DBIO[A] = sql.overrideStatements(sql.statements.map(_ + " for update")) - // TODO: I don’t know… does this help? @michalrus + // TODO: Is this more readable than inlining? @michalrus def ifElse[A](condition: Boolean, ifBranch: ⇒ DbResultT[A], elseBranch: ⇒ DbResultT[A]) = if (condition) ifBranch else elseBranch - def when[F[_]](p: Boolean, s: ⇒ F[Unit])(implicit F: Applicative[F]): F[Unit] = - if (p) s.void else F.pure(()) + def when[F[_]: Applicative](p: Boolean, s: ⇒ F[Unit]): F[Unit] = + if (p) s else ().pure[F] - def doOrGood[A](condition: Boolean, action: ⇒ DbResultT[A], good: ⇒ A)(implicit ec: EC): DbResultT[A] = - if (condition) action else DbResultT.good(good) + // TODO: Is this more readable than inlining? @michalrus + def doOrGood[F[_]: Applicative, A](p: Boolean, action: ⇒ F[A], good: ⇒ A)(implicit ec: EC): F[A] = + if (p) action else good.pure[F] - def doOrFail[A](condition: Boolean, action: ⇒ DbResultT[A], failure: ⇒ Failure)( - implicit ec: EC): DbResultT[A] = - if (condition) action else DbResultT.failure(failure) + // TODO: Is this more readable than inlining? @michalrus + def doOrFail[F[_]: Monad, A](p: Boolean, action: ⇒ FoxyT[F, A], failure: ⇒ Failure)( + implicit ec: EC): FoxyT[F, A] = + if (p) action else FoxyT[F].failure(failure) + // TODO: Is this more readable than inlining? @michalrus + // FIXME: should be defined over FoxyT, but inference fails then… @michalrus def failIf(condition: Boolean, failure: ⇒ Failure)(implicit ec: EC): DbResultT[Unit] = - if (condition) DbResultT.failure(failure) else DbResultT.unit + if (condition) DbResultT.failure(failure) else ().pure[DbResultT] + // TODO: Is this more readable than inlining? @michalrus + // FIXME: should be defined over FoxyT, but inference fails then… @michalrus def failIfNot(condition: Boolean, failure: ⇒ Failure)(implicit ec: EC): DbResultT[Unit] = failIf(!condition, failure) - def failIfFailures(failures: Seq[Failure])(implicit ec: EC): DbResultT[Unit] = + // TODO: Is this more readable than inlining? @michalrus + // TODO: There’s only one usage in the whole codebase. @michalrus + def failIfFailures[F[_]: Monad](failures: Seq[Failure]): FoxyT[F, Unit] = failures match { case head :: tail ⇒ - DbResultT.failures(NonEmptyList.of(head, tail: _*)) + FoxyT[F].failures(NonEmptyList.of(head, tail: _*)) case _ ⇒ - DbResultT.unit + ().pure[FoxyT[F, ?]] } implicit class EnrichedSQLActionBuilder(val action: SQLActionBuilder) extends AnyVal { @@ -329,33 +327,32 @@ package object db { def findOrCreate(r: DbResultT[R])(implicit ec: EC): DbResultT[R] = dbio.dbresult.flatMap { - case Some(model) ⇒ DbResultT.good(model) + case Some(model) ⇒ model.pure[DbResultT] case None ⇒ r } // Last item in tuple determines if cart was created or not def findOrCreateExtended(r: DbResultT[R])(implicit ec: EC): DbResultT[(R, FoundOrCreated)] = dbio.dbresult.flatMap { - case Some(model) ⇒ DbResultT.good((model, Found)) + case Some(model) ⇒ (model, Found: FoundOrCreated).pure[DbResultT] case _ ⇒ r.map(result ⇒ (result, Created)) } def mustFindOr(notFoundFailure: Failure)(implicit ec: EC): DbResultT[R] = dbio.dbresult.flatMap { - case Some(model) ⇒ DbResultT.good(model) + case Some(model) ⇒ model.pure[DbResultT] case None ⇒ DbResultT.failure(notFoundFailure) } def mustNotFindOr(shouldNotBeHere: Failure)(implicit ec: EC): DbResultT[Unit] = dbio.dbresult.flatMap { - case None ⇒ DbResultT.unit + case None ⇒ ().pure[DbResultT] case Some(_) ⇒ DbResultT.failure(shouldNotBeHere) } - // we only use this when we *know* we can call head safely on a query. (e.g., you've created a record which + // we only use this when we *know* we can call head unsafely on a query. (e.g., you've created a record which // has a FK constraint to another table and you then fetch that associated record -- we already *know* it must // exist. - // FIXME: if you know it, prove it. Or s/safe/unsafe/ in the name *AND* comment. @michalrus - def safeGet(implicit ec: EC): DBIO[R] = dbio.map(_.get) + def unsafeGet(implicit ec: EC): DBIO[R] = dbio.map(_.get) } } diff --git a/phoenix-scala/objectframework/app/objectframework/IlluminateAlgorithm.scala b/phoenix-scala/objectframework/app/objectframework/IlluminateAlgorithm.scala index 9e94f6d10b..c83bc116ec 100644 --- a/phoenix-scala/objectframework/app/objectframework/IlluminateAlgorithm.scala +++ b/phoenix-scala/objectframework/app/objectframework/IlluminateAlgorithm.scala @@ -2,6 +2,7 @@ package objectframework import java.time.Instant +import cats.implicits._ import cats.data.NonEmptyList import com.networknt.schema.JsonSchemaFactory import com.typesafe.scalalogging.LazyLogging @@ -34,7 +35,7 @@ object IlluminateAlgorithm extends LazyLogging { implicit ec: ExecutionContext): DbResultT[JValue] = { val illuminated = projectFlatAttributes(form.attributes, shadow.attributes) getInternalAttributes(schema).fold { - DbResultT.good(illuminated) + illuminated.pure[DbResultT] } { jsonSchema ⇒ val jsonSchemaFactory = new JsonSchemaFactory val validator = jsonSchemaFactory.getSchema(asJsonNode(jsonSchema)) @@ -45,7 +46,7 @@ object IlluminateAlgorithm extends LazyLogging { ObjectValidationFailure(form.kind, shadow.id, err.getMessage) } match { case head :: tail ⇒ DbResultT.failures[JValue](NonEmptyList(head, tail)) - case Nil ⇒ DbResultT.good(illuminated) + case Nil ⇒ illuminated.pure[DbResultT] } } } diff --git a/phoenix-scala/objectframework/app/objectframework/ObjectUtils.scala b/phoenix-scala/objectframework/app/objectframework/ObjectUtils.scala index 1c7bd5fc2e..da1b331333 100644 --- a/phoenix-scala/objectframework/app/objectframework/ObjectUtils.scala +++ b/phoenix-scala/objectframework/app/objectframework/ObjectUtils.scala @@ -184,7 +184,7 @@ object ObjectUtils { .copy[T](form = updateResult.form, shadow = updateResult.shadow) updateHead(newObject, commit.id) case _ ⇒ - DbResultT.good(fullObject) + fullObject.pure[DbResultT] }) } yield committedObject diff --git a/phoenix-scala/objectframework/app/objectframework/models/ObjectHeadLinks.scala b/phoenix-scala/objectframework/app/objectframework/models/ObjectHeadLinks.scala index 328c1f92d4..b3f5b50a43 100644 --- a/phoenix-scala/objectframework/app/objectframework/models/ObjectHeadLinks.scala +++ b/phoenix-scala/objectframework/app/objectframework/models/ObjectHeadLinks.scala @@ -84,13 +84,13 @@ object ObjectHeadLinks { case right if !linkedRightIds.contains(right.id) ⇒ create(build(left, right)) } - } yield {} + } yield () def createIfNotExist(left: L, right: R)(implicit ec: EC, db: DB): DbResultT[Unit] = for { linkExists ← * <~ filterLeft(left).filter(_.rightId === right.id).exists.result _ ← * <~ when(!linkExists, create(build(left, right)).void) - } yield {} + } yield () def build(left: L, right: R): M } diff --git a/phoenix-scala/objectframework/app/objectframework/models/OrderedLinks.scala b/phoenix-scala/objectframework/app/objectframework/models/OrderedLinks.scala index 30727a0a43..6f9aa6829a 100644 --- a/phoenix-scala/objectframework/app/objectframework/models/OrderedLinks.scala +++ b/phoenix-scala/objectframework/app/objectframework/models/OrderedLinks.scala @@ -1,5 +1,6 @@ package objectframework.models +import cats.implicits._ import core.db.ExPostgresDriver.api._ import core.db._ import objectframework.ObjectFailures.{LinkAtPositionCannotBeFound, LinkCannotBeFound} @@ -44,7 +45,7 @@ abstract class OrderedObjectHeadLinkQueries[M <: OrderedObjectHeadLink[M], replacedLink ← * <~ allLefts .filter(_.position === newPosition) .mustFindOneOr(LinkAtPositionCannotBeFound(baseTableRow.getClass, left.id, newPosition)) - newLinks ← * <~ (if (link.position == newPosition) DbResultT.good((link, replacedLink)) + newLinks ← * <~ (if (link.position == newPosition) (link, replacedLink).pure[DbResultT] else swapLinkPositions(link, replacedLink)) (updatedLink, _) = newLinks } yield updatedLink diff --git a/phoenix-scala/objectframework/app/objectframework/payloads/ObjectSchemaValidation.scala b/phoenix-scala/objectframework/app/objectframework/payloads/ObjectSchemaValidation.scala index 3f3289b335..84cbc77650 100644 --- a/phoenix-scala/objectframework/app/objectframework/payloads/ObjectSchemaValidation.scala +++ b/phoenix-scala/objectframework/app/objectframework/payloads/ObjectSchemaValidation.scala @@ -1,5 +1,6 @@ package objectframework.payloads +import cats.implicits._ import cats.data.NonEmptyList import com.networknt.schema.JsonSchemaFactory import core.db._ @@ -35,7 +36,7 @@ object ObjectSchemaValidation { PayloadValidationFailure(error.getMessage) } match { case head :: tail ⇒ DbResultT.failures[M](NonEmptyList(head, tail)) - case Nil ⇒ DbResultT.good(payload) + case Nil ⇒ payload.pure[DbResultT] } } diff --git a/phoenix-scala/objectframework/app/objectframework/services/ContentManager.scala b/phoenix-scala/objectframework/app/objectframework/services/ContentManager.scala index 2dc86f5613..1f441b8a65 100644 --- a/phoenix-scala/objectframework/app/objectframework/services/ContentManager.scala +++ b/phoenix-scala/objectframework/app/objectframework/services/ContentManager.scala @@ -52,7 +52,7 @@ object ContentManager { type FullContentRelations = Map[String, Seq[Content]] def getRelations(content: Content)(implicit ec: EC): DbResultT[FullContentRelations] = { - val empty = (Map.empty : FullContentRelations).pure[DbResultT] + val empty = (Map.empty: FullContentRelations).pure[DbResultT] content.relations.foldLeft(empty) { (accRelations, relation) ⇒ accRelations.flatMap { relations ⇒ @@ -86,7 +86,7 @@ object ContentManager { acc :+ (for { actualIds ← * <~ ContentQueries.filterCommitIds(kind, expectedIds).result _ ← * <~ validateAllCommits(kind, expectedIds, actualIds) - } yield {}) + } yield ()) } private def validateAllCommits(kind: String, diff --git a/phoenix-scala/phoenix/app/phoenix/models/account/User.scala b/phoenix-scala/phoenix/app/phoenix/models/account/User.scala index 26075163e0..d4f3f1bf29 100644 --- a/phoenix-scala/phoenix/app/phoenix/models/account/User.scala +++ b/phoenix-scala/phoenix/app/phoenix/models/account/User.scala @@ -139,7 +139,7 @@ object Users extends FoxTableQuery[User, Users](new Users(_)) with ReturningId[U maybeEmail match { case Some(email) ⇒ otherUserByEmail(email, accountId).one.mustNotFindOr(UserEmailNotUnique) - case None ⇒ DbResultT.unit + case None ⇒ ().pure[DbResultT] } } diff --git a/phoenix-scala/phoenix/app/phoenix/models/activity/Dimension.scala b/phoenix-scala/phoenix/app/phoenix/models/activity/Dimension.scala index 0a760d4251..ed9d7b2813 100644 --- a/phoenix-scala/phoenix/app/phoenix/models/activity/Dimension.scala +++ b/phoenix-scala/phoenix/app/phoenix/models/activity/Dimension.scala @@ -1,5 +1,6 @@ package phoenix.models.activity +import cats.implicits._ import cats.data.ValidatedNel import core.db.ExPostgresDriver.api._ import core.db._ @@ -58,7 +59,7 @@ object Dimensions def findOrCreateByName(name: String)(implicit ec: EC): DbResultT[Dimension] = findByName(name).one.dbresult.flatMap { - case Some(dimension) ⇒ DbResultT.good(dimension) + case Some(dimension) ⇒ dimension.pure[DbResultT] case None ⇒ create(Dimension(name = name, description = name.capitalize)) } } diff --git a/phoenix-scala/phoenix/app/phoenix/models/coupon/IlluminatedCoupon.scala b/phoenix-scala/phoenix/app/phoenix/models/coupon/IlluminatedCoupon.scala index 5fcb933b30..871220fd9d 100644 --- a/phoenix-scala/phoenix/app/phoenix/models/coupon/IlluminatedCoupon.scala +++ b/phoenix-scala/phoenix/app/phoenix/models/coupon/IlluminatedCoupon.scala @@ -20,6 +20,7 @@ case class IlluminatedCoupon(id: Int, context: IlluminatedContext, attributes: J implicit val formats = JsonFormatters.phoenixFormats + // FIXME: duplicated code with IlluminatedModel? @michalrus def mustBeActive: Either[Failures, IlluminatedCoupon] = { val activeFrom = (attributes \ "activeFrom" \ "v").extractOpt[Instant] val activeTo = (attributes \ "activeTo" \ "v").extractOpt[Instant] @@ -58,7 +59,7 @@ case class IlluminatedCoupon(id: Int, context: IlluminatedContext, attributes: J .couponMustBeUsable(id, accountId, rules.usesPerCustomer.getOrElse(0), code.code) case Some(rules) if rules.isUnlimitedPerCode && rules.isUnlimitedPerCustomer ⇒ - DbResultT.unit + ().pure[DbResultT] case _ ⇒ DbResultT.failure(CouponUsageRulesAreEmpty(code.code)) diff --git a/phoenix-scala/phoenix/app/phoenix/models/customer/CustomerGroup.scala b/phoenix-scala/phoenix/app/phoenix/models/customer/CustomerGroup.scala index 84cc2e98f5..0c9a0e6fd9 100644 --- a/phoenix-scala/phoenix/app/phoenix/models/customer/CustomerGroup.scala +++ b/phoenix-scala/phoenix/app/phoenix/models/customer/CustomerGroup.scala @@ -18,17 +18,18 @@ import slick.ast.BaseTypedType import slick.jdbc.JdbcType import slick.lifted.Tag -case class CustomerGroup(id: Int = 0, - scope: LTree, - createdBy: Int, - name: String, - customersCount: Int = 0, // FIXME: is this denormalization needed at all? https://foxcommerce.slack.com/archives/C06696D1R/p1498564090580988 @michalrus - clientState: Json, - elasticRequest: Json, - groupType: GroupType, - updatedAt: Instant = Instant.now, - createdAt: Instant = Instant.now, - deletedAt: Option[Instant] = None) +case class CustomerGroup( + id: Int = 0, + scope: LTree, + createdBy: Int, + name: String, + customersCount: Int = 0, // FIXME: is this denormalization needed at all? https://foxcommerce.slack.com/archives/C06696D1R/p1498564090580988 @michalrus + clientState: Json, + elasticRequest: Json, + groupType: GroupType, + updatedAt: Instant = Instant.now, + createdAt: Instant = Instant.now, + deletedAt: Option[Instant] = None) extends FoxModel[CustomerGroup] { def mustBeOfType(expected: GroupType): Either[Failures, CustomerGroup] = diff --git a/phoenix-scala/phoenix/app/phoenix/models/discount/DiscountBase.scala b/phoenix-scala/phoenix/app/phoenix/models/discount/DiscountBase.scala index 8b573640b2..c8d536a209 100644 --- a/phoenix-scala/phoenix/app/phoenix/models/discount/DiscountBase.scala +++ b/phoenix-scala/phoenix/app/phoenix/models/discount/DiscountBase.scala @@ -3,6 +3,7 @@ package phoenix.models.discount /** * Methods, used across offers and qualifiers */ +// FIXME: subtyping (except for ADT/typeclass encoding) is a pretty radical method of solving problems… @michalrus trait DiscountBase { def unitsByProducts(lineItems: Seq[DqLineItem], productIds: Seq[String]): Int = diff --git a/phoenix-scala/phoenix/app/phoenix/models/discount/DiscountValidator.scala b/phoenix-scala/phoenix/app/phoenix/models/discount/DiscountValidator.scala index 89cb69c2e7..caf0c39254 100644 --- a/phoenix-scala/phoenix/app/phoenix/models/discount/DiscountValidator.scala +++ b/phoenix-scala/phoenix/app/phoenix/models/discount/DiscountValidator.scala @@ -7,6 +7,7 @@ import org.json4s.Formats import phoenix.models.discount.DiscountHelpers.{offer, qualifier} import phoenix.services.discount.compilers.{OfferAstCompiler, QualifierAstCompiler} import phoenix.utils.JsonFormatters +import slick.dbio.DBIO /** * An DiscountValidator checks to make sure a discount shadow is valid @@ -18,7 +19,7 @@ object DiscountValidator { def validate(fs: FormAndShadow)(implicit ec: EC): DbResultT[Unit] = for { failures ← * <~ IlluminateAlgorithm.validateAttributes(fs.form.attributes, fs.shadow.attributes) - _ ← * <~ failIfFailures(failures) + _ ← * <~ failIfFailures[DBIO](failures) // TODO: why no inference? @michalrus _ ← * <~ QualifierAstCompiler(qualifier(fs.form, fs.shadow)).compile() _ ← * <~ OfferAstCompiler(offer(fs.form, fs.shadow)).compile() } yield None diff --git a/phoenix-scala/phoenix/app/phoenix/models/discount/SearchReference.scala b/phoenix-scala/phoenix/app/phoenix/models/discount/SearchReference.scala index f5c5a287ac..e3d27c64ae 100644 --- a/phoenix-scala/phoenix/app/phoenix/models/discount/SearchReference.scala +++ b/phoenix-scala/phoenix/app/phoenix/models/discount/SearchReference.scala @@ -105,5 +105,5 @@ object SearchReference { def skuSearchField: String = "code" def pureMetrics(implicit ec: EC): Result[Long] = 0L.pure[Result] - def pureBuckets(implicit ec: EC): Result[Buckets] = (Seq.empty : Buckets).pure[Result] + def pureBuckets(implicit ec: EC): Result[Buckets] = (Seq.empty: Buckets).pure[Result] } diff --git a/phoenix-scala/phoenix/app/phoenix/models/discount/offers/Offer.scala b/phoenix-scala/phoenix/app/phoenix/models/discount/offers/Offer.scala index 88aaa60c22..5ca92bd16a 100644 --- a/phoenix-scala/phoenix/app/phoenix/models/discount/offers/Offer.scala +++ b/phoenix-scala/phoenix/app/phoenix/models/discount/offers/Offer.scala @@ -23,9 +23,9 @@ trait Offer extends DiscountBase { def buildResult(input: DiscountInput, subtract: Long, lineItemRefNum: Option[String] = None)( implicit ec: EC): Result[Seq[OfferResult]] = - Result.good(Seq(OfferResult(input, subtract, lineItemRefNum, offerType))) + Seq(OfferResult(input, subtract, lineItemRefNum, offerType)).pure[Result] - def pureResult()(implicit ec: EC): Result[Seq[OfferResult]] = Result.good(Seq.empty) + def pureResult()(implicit ec: EC): Result[Seq[OfferResult]] = Seq.empty[OfferResult].pure[Result] def pureEither(): Either[Failures, Seq[OfferResult]] = Either.left(SearchFailure.single) } @@ -40,7 +40,6 @@ object Offer { * Offers that subtract amount from base price */ trait AmountOffer { - // If discount amount is bigger than price - subtract price, otherwise subtract discount def subtract(price: Long, discount: Long): Long = { val delta = price - discount diff --git a/phoenix-scala/phoenix/app/phoenix/models/discount/qualifiers/Qualifier.scala b/phoenix-scala/phoenix/app/phoenix/models/discount/qualifiers/Qualifier.scala index 731f1a980d..5eb44555f5 100644 --- a/phoenix-scala/phoenix/app/phoenix/models/discount/qualifiers/Qualifier.scala +++ b/phoenix-scala/phoenix/app/phoenix/models/discount/qualifiers/Qualifier.scala @@ -16,7 +16,7 @@ trait Qualifier extends DiscountBase { def check(input: DiscountInput)(implicit db: DB, ec: EC, apis: Apis, au: AU): Result[Unit] - def accept()(implicit ec: EC, apis: Apis): Result[Unit] = Result.unit + def accept()(implicit ec: EC, apis: Apis): Result[Unit] = ().pure[Result] def reject(input: DiscountInput, message: String)(implicit ec: EC): Result[Unit] = Result.failure(QualifierRejectionFailure(this, input, message)) @@ -33,7 +33,7 @@ trait ItemsQualifier extends Qualifier { search: Seq[ProductSearch])(implicit db: DB, ec: EC, apis: Apis, au: AU): Result[Unit] = { val inAnyOf = search.map(_.query(input).mapEither(matchEither(input))) Result.onlySuccessful(inAnyOf.toList).flatMap { - case xs if xs.nonEmpty ⇒ Result.unit + case xs if xs.nonEmpty ⇒ ().pure[Result] case _ ⇒ Result.failure(SearchFailure) } } diff --git a/phoenix-scala/phoenix/app/phoenix/models/inventory/Sku.scala b/phoenix-scala/phoenix/app/phoenix/models/inventory/Sku.scala index fbde8ab7bc..76b91cecbc 100644 --- a/phoenix-scala/phoenix/app/phoenix/models/inventory/Sku.scala +++ b/phoenix-scala/phoenix/app/phoenix/models/inventory/Sku.scala @@ -48,7 +48,7 @@ case class Sku(id: Int = 0, for { inCartCount ← * <~ CartLineItems.filter(_.skuId === id).size.result _ ← * <~ failIf(inCartCount > 0, SkuIsPresentInCarts(code)) - } yield {} + } yield () } diff --git a/phoenix-scala/phoenix/app/phoenix/models/payment/creditcard/CreditCard.scala b/phoenix-scala/phoenix/app/phoenix/models/payment/creditcard/CreditCard.scala index 6cb6ceaafa..3cfe281512 100644 --- a/phoenix-scala/phoenix/app/phoenix/models/payment/creditcard/CreditCard.scala +++ b/phoenix-scala/phoenix/app/phoenix/models/payment/creditcard/CreditCard.scala @@ -250,7 +250,7 @@ object CreditCards def mustFindByIdAndAccountId(id: Int, accountId: Int)(implicit ec: EC): DbResultT[CreditCard] = filter(cc ⇒ cc.id === id && cc.accountId === accountId).one.dbresult.flatMap { - case Some(cc) ⇒ DbResultT.good(cc) + case Some(cc) ⇒ cc.pure[DbResultT] case None ⇒ DbResultT.failure(NotFoundFailure404(CreditCard, id)) } } diff --git a/phoenix-scala/phoenix/app/phoenix/models/product/MvpModel.scala b/phoenix-scala/phoenix/app/phoenix/models/product/MvpModel.scala index 4029f93d5e..0bbcba534f 100644 --- a/phoenix-scala/phoenix/app/phoenix/models/product/MvpModel.scala +++ b/phoenix-scala/phoenix/app/phoenix/models/product/MvpModel.scala @@ -332,7 +332,7 @@ object Mvp { private def linkProductAndSku(product: Product, sku: Sku)(implicit ec: EC) = for { _ ← * <~ ProductSkuLinks.create(ProductSkuLink(leftId = product.id, rightId = sku.id)) - } yield {} + } yield () def insertSku(scope: LTree, contextId: Int, s: SimpleSku): DbResultT[Sku] = for { diff --git a/phoenix-scala/phoenix/app/phoenix/models/product/Product.scala b/phoenix-scala/phoenix/app/phoenix/models/product/Product.scala index 1f557073b6..b907f2b516 100644 --- a/phoenix-scala/phoenix/app/phoenix/models/product/Product.scala +++ b/phoenix-scala/phoenix/app/phoenix/models/product/Product.scala @@ -63,7 +63,7 @@ case class Product(id: Int = 0, skus ← * <~ ProductSkuLinks.filter(_.leftId === id).result inCartCount ← * <~ CartLineItems.filter(_.skuId.inSetBind(skus.map(_.rightId))).size.result _ ← * <~ failIf(inCartCount > 0, ProductIsPresentInCarts(formId)) - } yield {} + } yield () def reference: ProductReference = ProductId(formId) diff --git a/phoenix-scala/phoenix/app/phoenix/models/taxonomy/TaxonomyTaxonLink.scala b/phoenix-scala/phoenix/app/phoenix/models/taxonomy/TaxonomyTaxonLink.scala index 4007c63f3e..c5b100805f 100644 --- a/phoenix-scala/phoenix/app/phoenix/models/taxonomy/TaxonomyTaxonLink.scala +++ b/phoenix-scala/phoenix/app/phoenix/models/taxonomy/TaxonomyTaxonLink.scala @@ -2,6 +2,7 @@ package phoenix.models.taxonomy import java.time.Instant +import cats.implicits._ import com.github.tminglei.slickpg.LTree import core.db.ExPostgresDriver.api._ import core.db._ @@ -123,10 +124,10 @@ object TaxonomyTaxonLinks def archive(link: TaxonomyTaxonLink)(implicit ec: EC): DbResultT[Unit] = for { - _ ← * <~ (if (link.archivedAt.isDefined) DbResultT.good(link) + _ ← * <~ (if (link.archivedAt.isDefined) link.pure[DbResultT] else TaxonomyTaxonLinks.update(link, link.copy(archivedAt = Some(Instant.now)))) _ ← * <~ shrinkPositions(link.taxonomyId, link.path, link.position) - } yield {} + } yield () def updatePaths(taxonomyId: Int, oldPrefix: LTree, newPrefix: LTree): DBIO[Int] = { val patternLength = oldPrefix.value.length diff --git a/phoenix-scala/phoenix/app/phoenix/responses/AddressResponse.scala b/phoenix-scala/phoenix/app/phoenix/responses/AddressResponse.scala index 670ee2f889..ef04690380 100644 --- a/phoenix-scala/phoenix/app/phoenix/responses/AddressResponse.scala +++ b/phoenix-scala/phoenix/app/phoenix/responses/AddressResponse.scala @@ -91,7 +91,7 @@ object AddressResponse { (addresses, regions) = fullAddress.unzip response ← * <~ ((addresses.headOption, regions.headOption) match { case (Some(address), Some(region)) ⇒ - DbResultT.good(buildFromOrder(address, region)) + buildFromOrder(address, region).pure[DbResultT] case (None, _) ⇒ DbResultT.failure( NotFoundFailure404(s"No addresses found for order with refNum=$cordRef")) diff --git a/phoenix-scala/phoenix/app/phoenix/responses/ReturnResponse.scala b/phoenix-scala/phoenix/app/phoenix/responses/ReturnResponse.scala index 25bc8082a4..4216945b32 100644 --- a/phoenix-scala/phoenix/app/phoenix/responses/ReturnResponse.scala +++ b/phoenix-scala/phoenix/app/phoenix/responses/ReturnResponse.scala @@ -104,9 +104,9 @@ object ReturnResponse { // Either customer or storeAdmin as creator customer ← * <~ Users.findOneByAccountId(rma.accountId) customerData ← * <~ CustomersData.findOneByAccountId(rma.accountId) - storeAdmin ← rma.storeAdminId.flatTraverse(Users.findOneByAccountId(_).dbresult) - adminData ← * <~ rma.storeAdminId.flatTraverse(AdminsData.findOneByAccountId(_).dbresult) - organization ← * <~ rma.storeAdminId.traverse(Organizations.mustFindByAccountId) + storeAdmin ← rma.storeAdminId.flatTraverse(Users.findOneByAccountId(_).dbresult) + adminData ← rma.storeAdminId.flatTraverse(AdminsData.findOneByAccountId(_).dbresult) + organization ← rma.storeAdminId.traverse(Organizations.mustFindByAccountId) // Payment methods ccPayment ← * <~ ReturnPayments.findAllByReturnId(rma.id).creditCards.one applePayPayment ← * <~ ReturnPayments.findAllByReturnId(rma.id).applePays.one diff --git a/phoenix-scala/phoenix/app/phoenix/routes/AuthRoutes.scala b/phoenix-scala/phoenix/app/phoenix/routes/AuthRoutes.scala index b5f79dfac6..37a6ee5aee 100644 --- a/phoenix-scala/phoenix/app/phoenix/routes/AuthRoutes.scala +++ b/phoenix-scala/phoenix/app/phoenix/routes/AuthRoutes.scala @@ -36,7 +36,7 @@ object AuthRoutes { pathPrefix("public") { (post & path("login") & entity(as[LoginPayload])) { payload ⇒ - doLogin(payload.pure[DbResultT] )(_.runDBIO()) + doLogin(payload.pure[DbResultT])(_.runDBIO()) } ~ activityContext(defaultScope) { implicit ac ⇒ (post & path("send-password-reset") & pathEnd & entity(as[ResetPasswordSend])) { payload ⇒ diff --git a/phoenix-scala/phoenix/app/phoenix/services/AddressManager.scala b/phoenix-scala/phoenix/app/phoenix/services/AddressManager.scala index 7939114ef1..317f9fbaeb 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/AddressManager.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/AddressManager.scala @@ -64,7 +64,7 @@ object AddressManager { updated ← * <~ Addresses.update(address, softDelete) response ← * <~ AddressResponse.fromAddress(updated) _ ← * <~ LogActivity().addressDeleted(originator, customer, response) - } yield {} + } yield () def setDefaultShippingAddress(addressId: Int, accountId: Int)(implicit ec: EC, db: DB): DbResultT[AddressResponse] = diff --git a/phoenix-scala/phoenix/app/phoenix/services/Capture.scala b/phoenix-scala/phoenix/app/phoenix/services/Capture.scala index 2552c0e0c6..9fe8129c0d 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/Capture.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/Capture.scala @@ -144,7 +144,7 @@ case class Capture(payload: CapturePayloads.Capture)(implicit ec: EC, db: DB, ap _ ← * <~ when(scTotal > 0, LogActivity().scFundsCaptured(customer, order, scIds, scTotal).void) _ ← * <~ when(gcTotal > 0, LogActivity().gcFundsCaptured(customer, order, gcCodes, gcTotal).void) - } yield {} + } yield () private def externalCapture(total: Long, order: Order): DbResultT[Unit] = { def capture(charge: ExternalCharge[_]) = captureFromStripe(total, charge, order) diff --git a/phoenix-scala/phoenix/app/phoenix/services/CartValidator.scala b/phoenix-scala/phoenix/app/phoenix/services/CartValidator.scala index ed29479249..fd79b40093 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/CartValidator.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/CartValidator.scala @@ -46,7 +46,7 @@ case class CartValidator(cart: Cart)(implicit ec: EC, db: DB, ctx: OC) extends C case Some(warnings) ⇒ DbResultT.failures(warnings) case _ ⇒ - DbResultT.good(validatorResponse) + validatorResponse.pure[DbResultT] } } } else { @@ -101,7 +101,7 @@ case class CartValidator(cart: Cart)(implicit ec: EC, db: DB, ctx: OC) extends C case _ ⇒ warning(response, InvalidShippingMethod(cart.refNum)) } // FIXME validator warning and actual failure differ case None ⇒ - DbResultT(warning(response, NoShipMethod(cart.refNum))) + warning(response, NoShipMethod(cart.refNum)).pure[DbResultT] }) } yield validatedResponse diff --git a/phoenix-scala/phoenix/app/phoenix/services/Checkout.scala b/phoenix-scala/phoenix/app/phoenix/services/Checkout.scala index 8843b942e2..fe7ae5343a 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/Checkout.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/Checkout.scala @@ -242,10 +242,10 @@ case class Checkout( inventoryTrackedSkus ← * <~ filterInventoryTrackingSkus(liSkus) skusToHold ← * <~ inventoryTrackedSkus.map(sku ⇒ SkuInventoryHold(sku.code, sku.qty)) _ ← * <~ when(skusToHold.nonEmpty, - DbResultT.fromResult( - apis.middlewarehouse.hold(OrderInventoryHold(cart.referenceNumber, skusToHold)))) + DbResultT.fromResult( + apis.middlewarehouse.hold(OrderInventoryHold(cart.referenceNumber, skusToHold)))) mutating = externalCalls.middleWarehouseSuccess = skusToHold.nonEmpty // FIXME: I almost removed that, having read `==` here. Please, don’t… @michalrus - } yield {} + } yield () private def filterInventoryTrackingSkus(skus: Map[String, Int]) = for { @@ -274,9 +274,9 @@ case class Checkout( for { maybePromo ← * <~ OrderPromotions.filterByCordRef(cart.refNum).one maybeCodeId = maybePromo.flatMap(_.couponCodeId) - _ ← * <~ maybePromo.fold(DbResultT.unit)(promotionMustBeActive) - _ ← * <~ maybeCodeId.fold(DbResultT.unit)(couponMustBeApplicable) - } yield {} + _ ← * <~ maybePromo.fold(().pure[DbResultT])(promotionMustBeActive) + _ ← * <~ maybeCodeId.fold(().pure[DbResultT])(couponMustBeApplicable) + } yield () private def promotionMustBeActive(orderPromotion: OrderPromotion)(implicit ctx: OC): DbResultT[Unit] = for { @@ -287,11 +287,11 @@ case class Checkout( promoShadow ← * <~ ObjectShadows.mustFindById404(promotion.shadowId) promoObject = IlluminatedPromotion.illuminate(ctx, promotion, promoForm, promoShadow) _ ← * <~ promoObject.mustBeActive - } yield {} + } yield () private def couponMustBeApplicable(codeId: Int)(implicit ctx: OC): DbResultT[Unit] = for { - couponCode ← * <~ CouponCodes.findById(codeId).extract.one.safeGet + couponCode ← * <~ CouponCodes.findById(codeId).extract.one.unsafeGet coupon ← * <~ Coupons .filterByContextAndFormId(ctx.id, couponCode.couponFormId) .mustFindOneOr(CouponWithCodeCannotBeFound(couponCode.code)) @@ -300,7 +300,7 @@ case class Checkout( couponObject = IlluminatedCoupon.illuminate(ctx, coupon, couponForm, couponShadow) _ ← * <~ couponObject.mustBeActive _ ← * <~ couponObject.mustBeApplicable(couponCode, cart.accountId) - } yield {} + } yield () private def updateCouponCountersForPromotion(customer: User)(implicit ctx: OC): DbResultT[Unit] = for { @@ -308,7 +308,7 @@ case class Checkout( _ ← * <~ maybePromo.map { promo ⇒ CouponUsageService.updateUsageCounts(promo.couponCodeId, customer) } - } yield {} + } yield () private def authPayments(customer: User): DbResultT[Unit] = for { @@ -338,10 +338,10 @@ case class Checkout( grandTotal = cart.grandTotal internalPayments = gcTotal + scTotal _ ← * <~ when(grandTotal > internalPayments, // run external payments only if we have to pay more - doExternalPayment(grandTotal - internalPayments).void) + doExternalPayment(grandTotal - internalPayments).void) mutatingResult = externalCalls.authPaymentsSuccess = true // fixme is this flag used anywhere? @aafa - } yield {} + } yield () private def doExternalPayment(authAmount: Long): DbResultT[Unit] = { require(authAmount > 0) @@ -361,7 +361,7 @@ case class Checkout( orderPayment.paymentMethodType match { case PaymentMethod.ApplePay ⇒ authApplePay(authAmount, orderPayment) case PaymentMethod.CreditCard ⇒ authCreditCard(authAmount, orderPayment) - case _ ⇒ DbResultT.unit + case _ ⇒ ().pure[DbResultT] } private def authCreditCard(authAmount: Long, orderPayment: OrderPayment): DbResultT[Unit] = diff --git a/phoenix-scala/phoenix/app/phoenix/services/CreditCardManager.scala b/phoenix-scala/phoenix/app/phoenix/services/CreditCardManager.scala index 032903bdd9..c078fac255 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/CreditCardManager.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/CreditCardManager.scala @@ -72,7 +72,7 @@ object CreditCardManager { _ ← * <~ when(address.isNew, Addresses.create(address.copy(accountId = accountId)).void) cc = CreditCard.buildFromSource(accountId, sCustomer, sCard, payload, address) newCard ← * <~ CreditCards.create(cc) - region ← * <~ Regions.findOneById(newCard.address.regionId).safeGet + region ← * <~ Regions.findOneById(newCard.address.regionId).unsafeGet _ ← * <~ LogActivity().ccCreated(customer, cc, admin) } yield buildResponse(newCard, region) @@ -102,7 +102,7 @@ object CreditCardManager { cc ← * <~ CreditCards.mustFindByIdAndAccountId(cardId, accountId) default = cc.copy(isDefault = true) _ ← * <~ CreditCards.filter(_.id === cardId).map(_.isDefault).update(true) - region ← * <~ Regions.findOneById(cc.address.regionId).safeGet + region ← * <~ Regions.findOneById(cc.address.regionId).unsafeGet } yield buildResponse(default, region) def removeDefaultCreditCard(accountId: Int)(implicit ec: EC, db: DB): DbResultT[Unit] = @@ -143,7 +143,7 @@ object CreditCardManager { } def createNewAddressIfProvided(cc: CreditCard) = - payload.address.fold(DbResultT.good(cc)) { _ ⇒ + payload.address.fold(cc.pure[DbResultT]) { _ ⇒ for { address ← * <~ Addresses.create(Address.fromCreditCard(cc).copy(accountId = accountId)) } yield cc @@ -162,7 +162,7 @@ object CreditCardManager { .map(_.paymentMethodId) .update(updated.id) .map(_ ⇒ updated) - region ← Regions.findOneById(cc.address.regionId).safeGet + region ← Regions.findOneById(cc.address.regionId).unsafeGet } yield buildResponse(cc, region) } diff --git a/phoenix-scala/phoenix/app/phoenix/services/LineItemManager.scala b/phoenix-scala/phoenix/app/phoenix/services/LineItemManager.scala index e30cd3942a..66e1e4c574 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/LineItemManager.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/LineItemManager.scala @@ -70,7 +70,7 @@ object LineItemManager { for { productId ← * <~ ProductSkuLinks.filter(_.rightId === sku.id).one.dbresult.flatMap { case Some(productLink) ⇒ - DbResultT.good(productLink.leftId) + productLink.leftId.pure[DbResultT] case None ⇒ for { valueLink ← * <~ VariantValueSkuLinks @@ -88,28 +88,20 @@ object LineItemManager { } yield product private def getLineItemImage(sku: Sku, product: Product)(implicit ec: EC, db: DB) = - for { - image ← * <~ getLineItemAlbumId(sku, product).flatMap { - case Some(albumId) ⇒ - for { - album ← * <~ Albums.mustFindById404(albumId) - image ← * <~ ImageManager.getFirstImageForAlbum(album) - } yield image - - case None ⇒ - DbResultT.none[String] - } - } yield image + getLineItemAlbumId(sku, product).flatMap(_.flatTraverse { albumId ⇒ + for { + album ← * <~ Albums.mustFindById404(albumId) + image ← * <~ ImageManager.getFirstImageForAlbum(album) + } yield image + }) private def getLineItemAlbumId(sku: Sku, product: Product)(implicit ec: EC, db: DB) = - for { - albumId ← * <~ SkuAlbumLinks.filterLeft(sku).one.dbresult.flatMap { - case Some(albumLink) ⇒ - DbResultT.good(albumLink.rightId.some) - case None ⇒ - for { - albumLink ← * <~ ProductAlbumLinks.filterLeft(product).one.dbresult - } yield albumLink.map(_.rightId) - } - } yield albumId + SkuAlbumLinks.filterLeft(sku).one.dbresult.flatMap { + case Some(albumLink) ⇒ + albumLink.rightId.some.pure[DbResultT] + case None ⇒ + for { + albumLink ← * <~ ProductAlbumLinks.filterLeft(product).one.dbresult + } yield albumLink.map(_.rightId) + } } diff --git a/phoenix-scala/phoenix/app/phoenix/services/NotificationManager.scala b/phoenix-scala/phoenix/app/phoenix/services/NotificationManager.scala index 267fb826c4..fc28dabdcc 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/NotificationManager.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/NotificationManager.scala @@ -1,5 +1,6 @@ package phoenix.services +import cats.implicits._ import core.db._ import core.failures._ import de.heikoseeberger.akkasse.scaladsl.model.{ServerSentEvent ⇒ SSE} @@ -104,15 +105,16 @@ object NotificationManager { implicit ec: EC): DbResultT[Unit] = for { d ← * <~ Dimensions.findByName(dimension).one - _ ← * <~ d.fold(DbResultT.unit) { dimension ⇒ + _ ← * <~ d.fold(().pure[DbResultT]) { dimension ⇒ Subs .filter(_.dimensionId === dimension.id) .filter(_.adminId.inSet(adminIds)) .filter(_.objectId.inSet(objectIds)) .filter(_.reason === reason) - .deleteAll(onSuccess = DbResultT.unit, onFailure = DbResultT.unit) + .deleteAll + .void } - } yield {} + } yield () private def dimensionIdByName(name: String)(implicit ec: EC) = Dimensions.findByName(name).map(_.id).mustFindOneOr(NotFoundFailure400(Dimension, name)) diff --git a/phoenix-scala/phoenix/app/phoenix/services/SaveForLaterManager.scala b/phoenix-scala/phoenix/app/phoenix/services/SaveForLaterManager.scala index 230d154a7d..22665c39e1 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/SaveForLaterManager.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/SaveForLaterManager.scala @@ -35,7 +35,7 @@ object SaveForLaterManager { } yield response def deleteSaveForLater(id: Int)(implicit ec: EC, db: DB): DbResultT[Unit] = - SaveForLaters.deleteById(id, DbResultT.unit, i ⇒ NotFoundFailure404(SaveForLater, i)) + SaveForLaters.deleteById(id, ().pure[DbResultT], i ⇒ NotFoundFailure404(SaveForLater, i)) private def findAllDbio(customer: User, contextId: Int)(implicit ec: EC, db: DB): DbResultT[SavedForLater] = for { diff --git a/phoenix-scala/phoenix/app/phoenix/services/ShippingManager.scala b/phoenix-scala/phoenix/app/phoenix/services/ShippingManager.scala index 7cd0bdf084..f05b3b15d7 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/ShippingManager.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/ShippingManager.scala @@ -99,7 +99,7 @@ object ShippingManager { if (QueryStatement.evaluate(shippingMethod.conditions, shippingData, evaluateCondition)) { val hasRestrictions = QueryStatement.evaluate(shippingMethod.restrictions, shippingData, evaluateCondition) - if (hasRestrictions) DbResultT.failure(failure) else DbResultT.unit + if (hasRestrictions) DbResultT.failure(failure) else ().pure[DbResultT] } else { DbResultT.failure(failure) } diff --git a/phoenix-scala/phoenix/app/phoenix/services/StoreAdminManager.scala b/phoenix-scala/phoenix/app/phoenix/services/StoreAdminManager.scala index 7d7df5550d..c16b07d967 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/StoreAdminManager.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/StoreAdminManager.scala @@ -70,17 +70,17 @@ object StoreAdminManager { for { _ ← * <~ AdminsData .filter(_.accountId === accountId) - .deleteAll(DbResultT.unit, DbResultT.failure[Unit](UserWithAccountNotFound(accountId))) + .deleteAll(().pure[DbResultT], DbResultT.failure[Unit](UserWithAccountNotFound(accountId))) _ ← * <~ CustomersData .filter(_.accountId === accountId) - .deleteAll(DbResultT.unit, DbResultT.failure[Unit](UserWithAccountNotFound(accountId))) + .deleteAll(().pure[DbResultT], DbResultT.failure[Unit](UserWithAccountNotFound(accountId))) admin ← * <~ Users.mustFindByAccountId(accountId) _ ← * <~ UserPasswordResets.filter(_.accountId === accountId).delete - result ← * <~ Users.deleteById(admin.id, DbResultT.unit, i ⇒ NotFoundFailure404(User, i)) + result ← * <~ Users.deleteById(admin.id, ().pure[DbResultT], i ⇒ NotFoundFailure404(User, i)) _ ← * <~ AccountAccessMethods.findByAccountId(accountId).delete _ ← * <~ AccountRoles.findByAccountId(accountId).delete _ ← * <~ AccountOrganizations.filterByAccountId(accountId).delete - _ ← * <~ Accounts.deleteById(accountId, DbResultT.unit, i ⇒ NotFoundFailure404(Account, i)) + _ ← * <~ Accounts.deleteById(accountId, ().pure[DbResultT], i ⇒ NotFoundFailure404(Account, i)) _ ← * <~ LogActivity().storeAdminDeleted(admin, author) } yield result diff --git a/phoenix-scala/phoenix/app/phoenix/services/StoreCreditService.scala b/phoenix-scala/phoenix/app/phoenix/services/StoreCreditService.scala index be5a148791..853f34b49c 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/StoreCreditService.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/StoreCreditService.scala @@ -29,7 +29,7 @@ object StoreCreditService { // Check subtype only if id is present in payload; discard actual model private def checkSubTypeExists(subTypeId: Option[Int], originType: StoreCredit.OriginType)( implicit ec: EC): DbResultT[Unit] = - subTypeId.fold(DbResultT.unit) { subtypeId ⇒ + subTypeId.traverse { subtypeId ⇒ StoreCreditSubtypes .byOriginType(originType) .filter(_.id === subtypeId) @@ -38,9 +38,9 @@ object StoreCreditService { .flatMap(_.fold { DbResultT.failure[Unit](NotFoundFailure400(StoreCreditSubtype, subtypeId)) } { _ ⇒ - DbResultT.unit + ().pure[DbResultT] }) - } + }.void def totalsForCustomer(accountId: Int)(implicit ec: EC, db: DB): DbResultT[StoreCreditResponse.Totals] = for { @@ -153,7 +153,7 @@ object StoreCreditService { .lastAuthByStoreCreditId(storeCredit.id) .one .mustNotFindOr(OpenTransactionsFailure) - _ ← * <~ reasonId.map(id ⇒ Reasons.mustFindById400(id)).getOrElse(DbResultT.unit) + _ ← * <~ reasonId.traverse(Reasons.mustFindById400) upd ← * <~ StoreCredits.update(storeCredit, storeCredit.copy(state = newState, canceledReason = reasonId, diff --git a/phoenix-scala/phoenix/app/phoenix/services/account/AccountManager.scala b/phoenix-scala/phoenix/app/phoenix/services/account/AccountManager.scala index d05f96a5fe..c092366fae 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/account/AccountManager.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/account/AccountManager.scala @@ -57,7 +57,7 @@ object AccountManager { updatedResetPw ← * <~ (foundOrCreated match { case Found ⇒ UserPasswordResets.update(resetPw, resetPw.updateCode()) - case Created ⇒ DbResultT.good(resetPw) + case Created ⇒ resetPw.pure[DbResultT] }) } yield updatedResetPw @@ -114,7 +114,7 @@ object AccountManager { .findByNameInScope(context.org, scope.id) .mustFindOr(OrganizationNotFound(context.org, scope.path)) - _ ← * <~ when(checkEmail, email.fold(DbResultT.unit)(Users.createEmailMustBeUnique)) + _ ← * <~ when(checkEmail, email.fold(().pure[DbResultT])(Users.createEmailMustBeUnique)) account ← * <~ Accounts.create(Account()) diff --git a/phoenix-scala/phoenix/app/phoenix/services/actors/RemorseTimer.scala b/phoenix-scala/phoenix/app/phoenix/services/actors/RemorseTimer.scala index e68cf23388..235dfe846a 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/actors/RemorseTimer.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/actors/RemorseTimer.scala @@ -59,7 +59,7 @@ class RemorseTimer(implicit db: DB, ec: EC, apis: Apis) extends Actor { LogActivity().withScope(scope).orderBulkStateChanged(newState, refNums) } .toList) - .meh + .void } /* diff --git a/phoenix-scala/phoenix/app/phoenix/services/assignments/package.scala b/phoenix-scala/phoenix/app/phoenix/services/assignments/package.scala index a4a58a7abf..f6201ce77b 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/assignments/package.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/assignments/package.scala @@ -1,5 +1,6 @@ package phoenix.services +import cats.implicits._ import core.db._ import phoenix.models.account.User import phoenix.responses.TheResponse @@ -17,37 +18,35 @@ package object assignments { reason = manager.notifyReason, objectIds = objectIds) else - DbResultT.good(TheResponse(None)) + TheResponse(none[Int]).pure[DbResultT] def unsubscribe[K, M <: FoxModel[M]](manager: AssignmentsManager[K, M], adminIds: Seq[Int], objectIds: Seq[String])(implicit ec: EC): DbResultT[Unit] = - if (objectIds.nonEmpty) + when( + objectIds.nonEmpty, NotificationManager.unsubscribe(adminIds = adminIds, dimension = manager.notifyDimension, reason = manager.notifyReason, objectIds = objectIds) - else - DbResultT.unit + ) // Activity logger helpers def logBulkAssign[K, M <: FoxModel[M]](manager: AssignmentsManager[K, M], originator: User, admin: User, keys: Seq[String])(implicit ec: EC, ac: AC) = - if (keys.nonEmpty) - LogActivity() - .bulkAssigned(originator, admin, keys, manager.assignmentType, manager.referenceType) - else - DbResultT.unit + when(keys.nonEmpty, + LogActivity() + .bulkAssigned(originator, admin, keys, manager.assignmentType, manager.referenceType) + .void) def logBulkUnassign[K, M <: FoxModel[M]](manager: AssignmentsManager[K, M], originator: User, admin: User, keys: Seq[String])(implicit ec: EC, ac: AC) = - if (keys.nonEmpty) - LogActivity() - .bulkUnassigned(originator, admin, keys, manager.assignmentType, manager.referenceType) - else - DbResultT.unit + when(keys.nonEmpty, + LogActivity() + .bulkUnassigned(originator, admin, keys, manager.assignmentType, manager.referenceType) + .void) } diff --git a/phoenix-scala/phoenix/app/phoenix/services/carts/CartLineItemUpdater.scala b/phoenix-scala/phoenix/app/phoenix/services/carts/CartLineItemUpdater.scala index 11e0cab9e1..ae9031de25 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/carts/CartLineItemUpdater.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/carts/CartLineItemUpdater.scala @@ -138,7 +138,7 @@ object CartLineItemUpdater { for { _ ← * <~ CartLineItems .byCordRef(cart.referenceNumber) - .deleteAll(DbResultT.unit, DbResultT.unit) + .deleteAll updateResult ← * <~ payload.filter(_.quantity > 0).map(updateLineItems(cart, _)) } yield updateResult.flatten @@ -175,19 +175,19 @@ object CartLineItemUpdater { .mustFindOneOr(SkuNotFoundForContext(lineItem.sku, ctx.id)) _ ← * <~ mustFindProductIdForSku(sku, cart.refNum) _ ← * <~ (if (lineItem.quantity > 0) - createLineItems(sku.id, lineItem.quantity, cart.refNum, lineItem.attributes).meh + createLineItems(sku.id, lineItem.quantity, cart.refNum, lineItem.attributes).void else removeLineItems(sku.id, -lineItem.quantity, cart.refNum, lineItem.attributes)) - } yield {} + } yield () } - DbResultT.seqCollectFailures(lineItemUpdActions.toList).meh + DbResultT.seqCollectFailures(lineItemUpdActions.toList).void } private def mustFindProductIdForSku(sku: Sku, refNum: String)(implicit ec: EC, oc: OC) = for { link ← * <~ ProductSkuLinks.filter(_.rightId === sku.id).one.dbresult.flatMap { case Some(productLink) ⇒ - DbResultT.good(productLink.leftId) + productLink.leftId.pure[DbResultT] case None ⇒ for { valueLink ← * <~ VariantValueSkuLinks @@ -218,7 +218,7 @@ object CartLineItemUpdater { val totalToDelete = Math.min(delta, lisMatchingPayload.length) val idsToDelete = lisMatchingPayload.take(totalToDelete) - CartLineItems.filter(_.id.inSet(idsToDelete)).deleteAll(DbResultT.unit, DbResultT.unit) + CartLineItems.filter(_.id.inSet(idsToDelete)).deleteAll } - .meh + .void } diff --git a/phoenix-scala/phoenix/app/phoenix/services/carts/CartPaymentUpdater.scala b/phoenix-scala/phoenix/app/phoenix/services/carts/CartPaymentUpdater.scala index a7a8390722..d098b8ffb7 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/carts/CartPaymentUpdater.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/carts/CartPaymentUpdater.scala @@ -97,9 +97,9 @@ object CartPaymentUpdater { _ ← * <~ OrderPayments .filter(_.cordRef === cart.refNum) .storeCredits - .deleteAll(onSuccess = DbResultT.unit, onFailure = DbResultT.unit) + .deleteAll _ ← * <~ OrderPayments.createAll(payments) - } yield {} + } yield () } for { @@ -122,7 +122,7 @@ object CartPaymentUpdater { cc ← * <~ CreditCards.mustFindById400(id) _ ← * <~ cc.mustBelongToAccount(cart.accountId) _ ← * <~ cc.mustBeInWallet - region ← * <~ Regions.findOneById(cc.address.regionId).safeGet + region ← * <~ Regions.findOneById(cc.address.regionId).unsafeGet _ ← * <~ OrderPayments.filter(_.cordRef === cart.refNum).creditCards.delete _ ← * <~ OrderPayments.create(OrderPayment.build(cc).copy(cordRef = cart.refNum, amount = None)) valid ← * <~ CartValidator(cart).validate() diff --git a/phoenix-scala/phoenix/app/phoenix/services/category/CategoryManager.scala b/phoenix-scala/phoenix/app/phoenix/services/category/CategoryManager.scala index 8c7eb5bcd4..3618d52967 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/category/CategoryManager.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/category/CategoryManager.scala @@ -1,5 +1,6 @@ package phoenix.services.category +import cats.implicits._ import objectframework.ObjectFailures._ import objectframework.ObjectResponses.ObjectContextResponse import objectframework.ObjectUtils diff --git a/phoenix-scala/phoenix/app/phoenix/services/coupon/CouponManager.scala b/phoenix-scala/phoenix/app/phoenix/services/coupon/CouponManager.scala index edf68cfa45..2f856aac6e 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/coupon/CouponManager.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/coupon/CouponManager.scala @@ -172,6 +172,6 @@ object CouponManager { case None ⇒ if (promotionId != coupon.promotionId) Coupons.update(coupon, coupon.copy(promotionId = promotionId)) - else DbResultT.good(coupon) + else coupon.pure[DbResultT] } } diff --git a/phoenix-scala/phoenix/app/phoenix/services/coupon/CouponUsageService.scala b/phoenix-scala/phoenix/app/phoenix/services/coupon/CouponUsageService.scala index b7e220816f..86e0cc2f9e 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/coupon/CouponUsageService.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/coupon/CouponUsageService.scala @@ -1,5 +1,6 @@ package phoenix.services.coupon +import cats.implicits._ import objectframework.models.{ObjectContexts, ObjectForms} import phoenix.failures.CouponFailures._ import phoenix.models.account.User @@ -26,7 +27,7 @@ object CouponUsageService { for { count ← * <~ couponCodeUsageCount(couponFormId, couponCodeId) _ ← * <~ failIf(usesAvailable <= count, CouponCodeCannotBeUsedAnymore(code)) - } yield {} + } yield () def couponMustBeUsable(couponFormId: Int, accountId: Int, usesAvailable: Int, code: String)( implicit ec: EC, @@ -34,7 +35,7 @@ object CouponUsageService { for { count ← * <~ couponUsageCount(couponFormId, accountId) _ ← * <~ failIf(usesAvailable <= count, CouponCodeCannotBeUsedByCustomerAnymore(code, accountId)) - } yield {} + } yield () def mustBeUsableByCustomer(couponFormId: Int, couponCodeId: Int, @@ -45,14 +46,14 @@ object CouponUsageService { for { _ ← * <~ couponCodeMustBeUsable(couponFormId, couponCodeId, usesAvailableForCustomer, couponCode) _ ← * <~ couponMustBeUsable(couponFormId, accountId, usesAvailableForCustomer, couponCode) - } yield {} + } yield () def updateUsageCounts(couponCodeId: Option[Int], customer: User)(implicit ec: EC, db: DB, ctx: OC): DbResultT[Unit] = couponCodeId match { case Some(codeId) ⇒ for { - couponCode ← * <~ CouponCodes.findById(codeId).extract.one.safeGet + couponCode ← * <~ CouponCodes.findById(codeId).extract.one.unsafeGet context ← * <~ ObjectContexts.mustFindById400(ctx.id) code ← * <~ CouponCodes.mustFindById400(codeId) coupon ← * <~ Coupons @@ -87,8 +88,8 @@ object CouponUsageService { _ ← * <~ CouponCustomerUsages.update( couponUsageByCustomer, couponUsageByCustomer.copy(count = couponUsageByCustomer.count + 1)) - } yield {} + } yield () case _ ⇒ - DbResultT.unit + ().pure[DbResultT] } } diff --git a/phoenix-scala/phoenix/app/phoenix/services/customerGroups/GroupManager.scala b/phoenix-scala/phoenix/app/phoenix/services/customerGroups/GroupManager.scala index 33c4cd3c30..8472135052 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/customerGroups/GroupManager.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/customerGroups/GroupManager.scala @@ -2,6 +2,7 @@ package phoenix.services.customerGroups import java.time.Instant +import cats.implicits._ import core.db.ExPostgresDriver.api._ import core.db._ import core.failures.NotFoundFailure404 @@ -62,7 +63,7 @@ object GroupManager { } _ ← * <~ CustomerGroupMembers.findByGroupId(groupId).delete _ ← * <~ LogActivity().customerGroupArchived(group, admin) - } yield DbResultT.unit + } yield ().pure[DbResultT] private def createCustom(payload: CustomerGroupPayload, admin: User)(implicit ec: EC, db: DB, au: AU, ac: AC): DbResultT[Root] = diff --git a/phoenix-scala/phoenix/app/phoenix/services/customerGroups/GroupMemberManager.scala b/phoenix-scala/phoenix/app/phoenix/services/customerGroups/GroupMemberManager.scala index cc667b3801..b969672974 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/customerGroups/GroupMemberManager.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/customerGroups/GroupMemberManager.scala @@ -44,7 +44,7 @@ object GroupMemberManager { _ ← * <~ forDeletion.map { userId ⇒ deleteGroupMember(userId, groupId) } - } yield {} + } yield () def sync(groupId: Int, payload: CustomerGroupMemberSyncPayload)(implicit ec: EC, db: DB, ac: AC): DbResultT[Unit] = @@ -66,7 +66,7 @@ object GroupMemberManager { _ ← * <~ forDeletion.intersect(memberIds).toSeq.map { userId ⇒ deleteGroupMember(userId, groupId) } - } yield {} + } yield () def addCustomerToGroups(accountId: Int, groupIds: Seq[Int])(implicit ec: EC, db: DB, ac: AC): DbResultT[CustomerResponse] = @@ -120,7 +120,7 @@ object GroupMemberManager { membership = CustomerGroupMember(customerDataId = customerData.id, groupId = groupId) result ← * <~ CustomerGroupMembers.create(membership) _ ← * <~ when(group.groupType == Manual, - CustomerGroups.update(group, group.copy(customersCount = group.customersCount + 1)).void) + CustomerGroups.update(group, group.copy(customersCount = group.customersCount + 1)).void) } yield result private def deleteGroupMember(userId: Int, groupId: Int)(implicit ec: EC, db: DB): DbResultT[Unit] = @@ -131,10 +131,10 @@ object GroupMemberManager { .findByGroupIdAndCustomerDataId(customerData.id, groupId) .mustFindOneOr(NotFoundFailure400(User, userId)) _ ← * <~ CustomerGroupMembers - .deleteById(membership.id, DbResultT.unit, userId ⇒ NotFoundFailure400(User, userId)) + .deleteById(membership.id, ().pure[DbResultT], userId ⇒ NotFoundFailure400(User, userId)) _ ← * <~ when(group.groupType == Manual, - CustomerGroups.update(group, group.copy(customersCount = group.customersCount - 1)).void) - } yield {} + CustomerGroups.update(group, group.copy(customersCount = group.customersCount - 1)).void) + } yield () def isMemberOfAny(groupIds: Set[Int], customer: User)(implicit ec: EC, apis: Apis): DbResultT[Boolean] = for { diff --git a/phoenix-scala/phoenix/app/phoenix/services/customers/CustomerManager.scala b/phoenix-scala/phoenix/app/phoenix/services/customers/CustomerManager.scala index 6c7ee40647..72c4cf68e5 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/customers/CustomerManager.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/customers/CustomerManager.scala @@ -185,7 +185,7 @@ object CustomerManager { for { customer ← * <~ Users.mustFindByAccountId(accountId) custData ← * <~ CustomersData.mustFindByAccountId(accountId) - _ ← * <~ (if (custData.isGuest) DbResultT.unit + _ ← * <~ (if (custData.isGuest) ().pure[DbResultT] else Users.updateEmailMustBeUnique(payload.email.map(_.toLowerCase), accountId)) updated ← * <~ Users.update(customer, updatedUser(customer, payload)) _ ← * <~ CustomersData.update(custData, updatedCustUser(custData, payload)) @@ -207,7 +207,7 @@ object CustomerManager { updatedAccess ← * <~ AccountAccessMethods .update(accessMethod, accessMethod.updatePassword(payload.newPassword)) _ ← * <~ LogActivity().userPasswordReset(user) - } yield {} + } yield () def updatedUser(customer: User, payload: UpdateCustomerPayload): User = customer.copy( @@ -229,7 +229,7 @@ object CustomerManager { customer ← * <~ Users.mustFindByAccountId(accountId) _ ← * <~ (customer.email match { case None ⇒ DbResultT.failure(CustomerMustHaveCredentials) - case _ ⇒ DbResultT.unit + case _ ⇒ ().pure[DbResultT] }) _ ← * <~ Users.updateEmailMustBeUnique(customer.email, accountId) updated ← * <~ Users.update(customer, customer.copy(name = payload.name.some)) diff --git a/phoenix-scala/phoenix/app/phoenix/services/discount/DiscountManager.scala b/phoenix-scala/phoenix/app/phoenix/services/discount/DiscountManager.scala index 1aa9a5f3d3..46adf5e9ca 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/discount/DiscountManager.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/discount/DiscountManager.scala @@ -146,6 +146,6 @@ object DiscountManager { case Some(commit) ⇒ Discounts.update(discount, discount.copy(shadowId = shadow.id, commitId = commit.id)) case None ⇒ - DbResultT.good(discount) + discount.pure[DbResultT] } } diff --git a/phoenix-scala/phoenix/app/phoenix/services/giftcards/GiftCardService.scala b/phoenix-scala/phoenix/app/phoenix/services/giftcards/GiftCardService.scala index 8b1b022f12..593000d3a5 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/giftcards/GiftCardService.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/giftcards/GiftCardService.scala @@ -47,7 +47,7 @@ object GiftCardService { customer ← * <~ Users.mustFindByAccountId(accountId) custData ← * <~ CustomersData.mustFindByAccountId(accountId) } yield GiftCardResponse.build(giftCard, Some(CustomerResponse.build(customer, custData)), None) - case _ ⇒ DbResultT.good(GiftCardResponse.build(giftCard, None, None)) + case _ ⇒ GiftCardResponse.build(giftCard, None, None).pure[DbResultT] } def createByAdmin( @@ -57,11 +57,10 @@ object GiftCardService { scope ← * <~ Scope.resolveOverride(payload.scope) _ ← * <~ Reasons.mustFindById400(payload.reasonId) // If `subTypeId` is absent, don't query. Check for model existence otherwise. - subtype ← * <~ payload.subTypeId.fold(DbResultT.none[GiftCardSubtype]) { subId ⇒ + subtype ← * <~ payload.subTypeId.traverse { subId ⇒ GiftCardSubtypes.csrAppeasements .filter(_.id === subId) .mustFindOneOr(NotFoundFailure400(GiftCardSubtype, subId)) - .map(Some(_)) // A bit silly but need to rewrap it back } origin ← * <~ GiftCardManuals.create( GiftCardManual(adminId = admin.accountId, reasonId = payload.reasonId)) @@ -110,7 +109,7 @@ object GiftCardService { payload: GiftCardUpdateStateByCsr, admin: User)(implicit ec: EC, db: DB, ac: AC): DbResultT[GiftCardResponse] = for { - _ ← * <~ payload.reasonId.map(id ⇒ Reasons.mustFindById400(id)).getOrElse(DbResultT.unit) + _ ← * <~ payload.reasonId.traverse(Reasons.mustFindById400) giftCard ← * <~ GiftCards.mustFindByCode(code) updated ← * <~ cancelOrUpdate(giftCard, payload.state, payload.reasonId, admin) _ ← * <~ LogActivity().gcUpdated(admin, giftCard, payload) diff --git a/phoenix-scala/phoenix/app/phoenix/services/image/ImageManager.scala b/phoenix-scala/phoenix/app/phoenix/services/image/ImageManager.scala index 66b1162d5b..3611578386 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/image/ImageManager.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/image/ImageManager.scala @@ -94,7 +94,7 @@ object ImageManager { case Some(imagesPayload) ⇒ createImagesForAlbum(album.model, imagesPayload, context) case None ⇒ - DbResultT.good(Seq.empty) + Seq.empty.pure[DbResultT] }) } yield (album, images) @@ -287,7 +287,7 @@ object ImageManager { def getFirstImageForAlbum(album: Album)(implicit ec: EC, db: DB): DbResultT[Option[String]] = for { imageLink ← * <~ AlbumImageLinks.filterLeft(album).sortBy(_.position).one.dbresult - src ← * <~ imageLink.fold(DbResultT.none[String]) { link ⇒ + src ← * <~ imageLink.flatTraverse { link ⇒ for { fullImage ← * <~ ObjectManager.getFullObject(Images.mustFindById404(link.rightId)) } yield diff --git a/phoenix-scala/phoenix/app/phoenix/services/inventory/SkuManager.scala b/phoenix-scala/phoenix/app/phoenix/services/inventory/SkuManager.scala index b2d8b3c44b..5cbb9b8cd3 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/inventory/SkuManager.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/inventory/SkuManager.scala @@ -140,7 +140,7 @@ object SkuManager { case Some(commit) ⇒ Skus.update(sku, sku.copy(code = code, shadowId = shadow.id, commitId = commit.id)) case None ⇒ - DbResultT.good(sku) + sku.pure[DbResultT] } def mustGetSkuCode(payload: SkuPayload): Either[Failures, String] = diff --git a/phoenix-scala/phoenix/app/phoenix/services/notes/package.scala b/phoenix-scala/phoenix/app/phoenix/services/notes/package.scala index 8a834e91cf..17530f826c 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/notes/package.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/notes/package.scala @@ -52,5 +52,5 @@ package object notes { note ← * <~ Notes.mustFindById404(noteId) _ ← * <~ Notes.update(note, note.copy(deletedAt = Some(Instant.now), deletedBy = Some(admin.accountId))) _ ← * <~ LogActivity().noteDeleted(admin, entity, note) - } yield {} + } yield () } diff --git a/phoenix-scala/phoenix/app/phoenix/services/orders/OrderStateUpdater.scala b/phoenix-scala/phoenix/app/phoenix/services/orders/OrderStateUpdater.scala index 0168c9cd8e..d43b94cb5a 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/orders/OrderStateUpdater.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/orders/OrderStateUpdater.scala @@ -32,9 +32,10 @@ object OrderStateUpdater { _ ← * <~ updateQueries(admin, Seq(refNum), newState) updated ← * <~ Orders.mustFindByRefNum(refNum) _ ← * <~ when(updated.state == Order.Canceled, - DbResultT.fromResult(apis.middlewarehouse.cancelHold(refNum))) + DbResultT.fromResult(apis.middlewarehouse.cancelHold(refNum))) response ← * <~ OrderResponse.fromOrder(updated, grouped = true) - _ ← * <~ when(order.state != newState, LogActivity().orderStateChanged(admin, response, order.state).void) + _ ← * <~ when(order.state != newState, + LogActivity().orderStateChanged(admin, response, order.state).void) } yield response def updateStates(admin: User, @@ -72,7 +73,7 @@ object OrderStateUpdater { .map(refNum ⇒ (refNum, NotFoundFailure400(Order, refNum).description)) val batchFailures = (invalid ++ notFound).toMap - DbResultT.good(BatchMetadata(BatchMetadataSource(Order, possibleRefNums, batchFailures))) + BatchMetadata(BatchMetadataSource(Order, possibleRefNums, batchFailures)).pure[DbResultT] } } } @@ -97,7 +98,7 @@ object OrderStateUpdater { cancelOrders(cordRefs) case _ ⇒ // FIXME: calling .dbresultt (which basically maps right) can be dangerous here. @anna - Orders.filter(_.referenceNumber.inSet(cordRefs)).map(_.state).update(newState).dbresult.meh + Orders.filter(_.referenceNumber.inSet(cordRefs)).map(_.state).update(newState).dbresult.void } private def cancelOrders(cordRefs: Seq[String])(implicit ec: EC, db: DB): DbResultT[Unit] = diff --git a/phoenix-scala/phoenix/app/phoenix/services/plugins/PluginsManager.scala b/phoenix-scala/phoenix/app/phoenix/services/plugins/PluginsManager.scala index 498c0bd383..d0f1250ca1 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/plugins/PluginsManager.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/plugins/PluginsManager.scala @@ -1,5 +1,6 @@ package phoenix.services.plugins +import cats.implicits._ import com.typesafe.scalalogging.LazyLogging import core.db.ExPostgresDriver.api._ import core.db._ @@ -31,7 +32,7 @@ object PluginsManager extends LazyLogging { val req = host(apiUrl) / "_settings" / "schema" DbResultT.fromF(DBIO.from(Http(req OK as.json4s.Json).map(_.extract[SettingsSchema]))) } - }(DbResultT.good(_)) + }(_.pure[DbResultT]) def uploadNewSettingsToPlugin(plugin: Plugin)(implicit ec: EC, formats: Formats): Future[String] = plugin.apiUrl().fold(Future.successful("")) { apiUrl ⇒ diff --git a/phoenix-scala/phoenix/app/phoenix/services/product/ProductManager.scala b/phoenix-scala/phoenix/app/phoenix/services/product/ProductManager.scala index 9d35243cc1..f20154b763 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/product/ProductManager.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/product/ProductManager.scala @@ -104,11 +104,11 @@ object ProductManager extends LazyLogging { illuminated.mustBeActive match { case Left(err) ⇒ { logger.warn(err.toString) - DbResultT.failure(NotFoundFailure404(Product, oldProduct.model.slug)).void + DbResultT.failure[Unit](NotFoundFailure404(Product, oldProduct.model.slug)) } - case Right(_) ⇒ DbResultT.unit + case Right(_) ⇒ ().pure[DbResultT] } - } : DbResultT[Unit] + } ) albums ← * <~ ImageManager.getAlbumsForProduct(oldProduct.model.reference) @@ -326,7 +326,7 @@ object ProductManager extends LazyLogging { val newProduct = withNewSlug.andThen(withCommit)(product) if (newProduct != product) Products.update(product, newProduct) - else DbResultT.good(product) + else product.pure[DbResultT] } private def findOrCreateSkusForProduct( @@ -440,7 +440,7 @@ object ProductManager extends LazyLogging { for { skuToUnassociate ← * <~ Skus.mustFindByCode(codeToUnassociate) _ ← * <~ skuToUnassociate.mustNotBePresentInCarts - } yield {} + } yield () }) - } yield {} + } yield () } diff --git a/phoenix-scala/phoenix/app/phoenix/services/promotion/PromotionManager.scala b/phoenix-scala/phoenix/app/phoenix/services/promotion/PromotionManager.scala index f6f1934e42..6dfab730ed 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/promotion/PromotionManager.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/promotion/PromotionManager.scala @@ -2,6 +2,7 @@ package phoenix.services.promotion import java.time.Instant +import cats.implicits._ import core.db._ import core.failures.NotFoundFailure404 import objectframework.ObjectFailures._ @@ -207,6 +208,6 @@ object PromotionManager { if (promotion.applyType != payload.applyType) Promotions.update(promotion, promotion.copy(applyType = payload.applyType)) else - DbResultT.good(promotion) + promotion.pure[DbResultT] } } diff --git a/phoenix-scala/phoenix/app/phoenix/services/returns/ReturnPaymentManager.scala b/phoenix-scala/phoenix/app/phoenix/services/returns/ReturnPaymentManager.scala index b06b304a14..a2f227e1a5 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/returns/ReturnPaymentManager.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/returns/ReturnPaymentManager.scala @@ -237,7 +237,8 @@ object ReturnPaymentManager { updated ← * <~ Returns.refresh(rma) response ← * <~ ReturnResponse.fromRma(rma) - _ ← * <~ when(paymentWasDeleted, LogActivity().returnPaymentsDeleted(response, List(paymentMethod)).void) + _ ← * <~ when(paymentWasDeleted, + LogActivity().returnPaymentsDeleted(response, List(paymentMethod)).void) } yield response private def deletePayments( @@ -249,7 +250,7 @@ object ReturnPaymentManager { updated ← * <~ Returns.refresh(rma) response ← * <~ ReturnResponse.fromRma(updated) _ ← * <~ when(deletedPayments.nonEmpty, - LogActivity().returnPaymentsDeleted(response, deletedPayments).void) + LogActivity().returnPaymentsDeleted(response, deletedPayments).void) } yield response private def processDeletePayment(returnId: Int, paymentMethod: PaymentMethod.Type)( diff --git a/phoenix-scala/phoenix/app/phoenix/services/returns/ReturnReasonsManager.scala b/phoenix-scala/phoenix/app/phoenix/services/returns/ReturnReasonsManager.scala index 2464deb4ee..f95a4b0525 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/returns/ReturnReasonsManager.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/returns/ReturnReasonsManager.scala @@ -1,5 +1,6 @@ package phoenix.services.returns +import cats.implicits._ import core.db._ import core.failures.NotFoundFailure404 import phoenix.models.returns._ @@ -29,7 +30,7 @@ object ReturnReasonsManager { def deleteReason(id: Int)(implicit ec: EC, db: DB): DbResultT[Unit] = for { result ← * <~ ReturnReasons - .deleteById(id, DbResultT.unit, i ⇒ NotFoundFailure404(ReturnReasons, i)) + .deleteById(id, ().pure[DbResultT], NotFoundFailure404(ReturnReasons, _)) } yield result } diff --git a/phoenix-scala/phoenix/app/phoenix/services/returns/ReturnService.scala b/phoenix-scala/phoenix/app/phoenix/services/returns/ReturnService.scala index 5735c8dd1e..64b8346bdd 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/returns/ReturnService.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/returns/ReturnService.scala @@ -48,7 +48,7 @@ object ReturnService { response ← * <~ ReturnResponse.fromRma(updated) customer ← * <~ Users.mustFindByAccountId(rma.accountId) _ ← * <~ when(rma.state != payload.state, - LogActivity().returnStateChanged(customer, response, payload.state).void) + LogActivity().returnStateChanged(customer, response, payload.state).void) } yield response private def update(rma: Return, diff --git a/phoenix-scala/phoenix/app/phoenix/services/review/ProductReviewManager.scala b/phoenix-scala/phoenix/app/phoenix/services/review/ProductReviewManager.scala index b3fa5c57da..9c4b021742 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/review/ProductReviewManager.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/review/ProductReviewManager.scala @@ -59,6 +59,6 @@ object ProductReviewManager { for { review ← * <~ ProductReviews.mustFindById404(reviewId) archived ← * <~ ProductReviews.update(review, review.copy(archivedAt = Some(Instant.now))) - } yield {} + } yield () } diff --git a/phoenix-scala/phoenix/app/phoenix/services/taxonomy/TaxonomyManager.scala b/phoenix-scala/phoenix/app/phoenix/services/taxonomy/TaxonomyManager.scala index cda5acae3b..24cb03450e 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/taxonomy/TaxonomyManager.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/taxonomy/TaxonomyManager.scala @@ -104,7 +104,7 @@ object TaxonomyManager { for { taxonomy ← * <~ Taxonomies.mustFindByFormId404(taxonomyFormId) archived ← * <~ Taxonomies.update(taxonomy, taxonomy.copy(archivedAt = Some(Instant.now))) - } yield {} + } yield () def getTaxon(taxonFormId: ObjectForm#Id)(implicit ec: EC, oc: OC, db: DB): DbResultT[FullTaxonResponse] = for { @@ -130,9 +130,8 @@ object TaxonomyManager { shadowId = ins.shadow.id, commitId = ins.commit.id)) - parentLink ← * <~ payload.location.fold(DbResultT.none[TaxonomyTaxonLink])(location ⇒ - validateLocation(taxonomy, taxon, location)) - index ← * <~ TaxonomyTaxonLinks.nextIndex(taxonomy.id).result + parentLink ← * <~ payload.location.flatTraverse(validateLocation(taxonomy, taxon, _)) + index ← * <~ TaxonomyTaxonLinks.nextIndex(taxonomy.id).result moveSpec ← * <~ MoveSpec(TaxonomyTaxonLink(index = index, taxonomyId = taxonomy.id, @@ -152,21 +151,20 @@ object TaxonomyManager { implicit ec: EC, oc: OC): DbResultT[Option[TaxonomyTaxonLink]] = for { - parentLink ← * <~ location.parent.fold(DbResultT.none[TaxonomyTaxonLink])( + parentLink ← * <~ location.parent.traverse( pid ⇒ TaxonomyTaxonLinks .active() - .mustFindByTaxonomyAndTaxonFormId(taxonomy, pid) - .map(Some(_))) + .mustFindByTaxonomyAndTaxonFormId(taxonomy, pid)) - _ ← * <~ location.position.fold(DbResultT.unit) { position ⇒ + _ ← * <~ location.position.fold(().pure[DbResultT]) { position ⇒ when( position != 0, TaxonomyTaxonLinks .active() .findByPathAndPosition(parentLink.map(_.childPath).getOrElse(LTree("")), position - 1) .mustFindOneOr(TaxonomyFailures.NoTaxonAtPosition(location.parent, position)) - .meh + .void ) } } yield parentLink @@ -175,11 +173,12 @@ object TaxonomyManager { oc: OC, db: DB): DbResultT[FullTaxonResponse] = for { - taxon ← * <~ Taxons.mustFindByFormId404(taxonId) - _ ← * <~ failIf(taxon.archivedAt.isDefined, TaxonIsArchived(taxonId)) - newTaxon ← * <~ updateTaxonAttributes(taxon, payload) - _ ← * <~ payload.location.fold(DbResultT.unit)(location ⇒ updateTaxonomyHierarchy(taxon, location).meh) - taxonFull ← * <~ ObjectManager.getFullObject(DbResultT.good(newTaxon)) + taxon ← * <~ Taxons.mustFindByFormId404(taxonId) + _ ← * <~ failIf(taxon.archivedAt.isDefined, TaxonIsArchived(taxonId)) + newTaxon ← * <~ updateTaxonAttributes(taxon, payload) + _ ← * <~ payload.location.fold(().pure[DbResultT])(location ⇒ + updateTaxonomyHierarchy(taxon, location).void) + taxonFull ← * <~ ObjectManager.getFullObject(newTaxon.pure[DbResultT]) response ← * <~ buildSingleTaxonResponse(taxonFull) } yield response @@ -189,7 +188,7 @@ object TaxonomyManager { taxonomyTaxonLink ← * <~ TaxonomyTaxonLinks .filterRight(taxonFull.model) .mustFindOneOr(InvalidTaxonomiesForTaxon(taxonFull.model, 0)) - taxonomy ← * <~ Taxonomies.findOneById(taxonomyTaxonLink.leftId).safeGet + taxonomy ← * <~ Taxonomies.findOneById(taxonomyTaxonLink.leftId).unsafeGet maybeParent ← * <~ TaxonomyTaxonLinks.parentOf(taxonomyTaxonLink) parentTaxon ← * <~ maybeParent.flatTraverse(link ⇒ Taxons.findOneById(link.rightId).dbresult) } yield FullTaxonResponse.build(taxonFull, taxonomy.formId, parentTaxon.map(_.formId)) @@ -211,7 +210,7 @@ object TaxonomyManager { for { taxonomies ← * <~ TaxonomyTaxonLinks.queryLeftByRight(taxon) taxonomy ← * <~ (taxonomies.toList match { - case t :: Nil ⇒ DbResultT.good(t) + case t :: Nil ⇒ t.pure[DbResultT] case _ ⇒ DbResultT.failure(InvalidTaxonomiesForTaxon(taxon, taxonomies.length)) }) @@ -231,7 +230,7 @@ object TaxonomyManager { moveSpec.taxon.childPath, newPath.copy(value = newPath.value ::: List(moveSpec.taxon.index.toString))) - } yield {} + } yield () private def updateTaxonAttributes(taxon: Taxon, payload: UpdateTaxonPayload)(implicit ec: EC, db: DB, @@ -241,7 +240,7 @@ object TaxonomyManager { val shadow = ObjectShadow.fromPayload(payload.attributes) for { - fullTaxon ← * <~ ObjectManager.getFullObject(DbResultT.good(taxon)) + fullTaxon ← * <~ ObjectManager.getFullObject(taxon.pure[DbResultT]) newTaxon ← * <~ ObjectUtils.commitUpdate(fullTaxon, form.attributes, fullTaxon.shadow.attributes.merge(shadow.attributes), @@ -258,7 +257,7 @@ object TaxonomyManager { children ← * <~ links.map(link ⇒ TaxonomyTaxonLinks.hasChildren(link).result.dbresult) _ ← * <~ failIf(children.exists(identity), TaxonomyFailures.CannotArchiveParentTaxon(taxonFormId)) _ ← * <~ links.map(TaxonomyTaxonLinks.archive) - } yield {} + } yield () def assignProduct( taxonFormId: ObjectForm#Id, @@ -279,7 +278,7 @@ object TaxonomyManager { r ← * <~ ProductTaxonLinks .filterLeft(product) .filter(_.rightId === taxon.id) - .deleteAll(DbResultT.none, + .deleteAll(().pure[DbResultT], DbResultT.failure(TaxonomyFailures.CannotUnassignProduct(taxon.formId, product.formId))) assigned ← * <~ getAssignedTaxons(product) } yield assigned diff --git a/phoenix-scala/phoenix/app/phoenix/services/tree/TreeManager.scala b/phoenix-scala/phoenix/app/phoenix/services/tree/TreeManager.scala index f1ba92360f..8a919c9eeb 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/tree/TreeManager.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/tree/TreeManager.scala @@ -53,7 +53,7 @@ object TreeManager { _ ← * <~ (if (shouldBeDeleted) GenericTreeNodes.deleteById( newChildNode.id, - DbResultT.unit, + ().pure[DbResultT], _ ⇒ DatabaseFailure( s"cannot delete node: index=${newChildNode.index}, tree=$treeName, context=$contextName")) @@ -101,7 +101,7 @@ object TreeManager { for { maybeTree ← * <~ GenericTrees.filterByNameAndContext(treeName, context.id).one - tree ← * <~ maybeTree.fold(ifEmptyAction)(tree ⇒ DbResultT.good(tree)) + tree ← * <~ maybeTree.fold(ifEmptyAction)(tree ⇒ tree.pure[DbResultT]) } yield tree } @@ -111,9 +111,8 @@ object TreeManager { parentNode ← * <~ GenericTreeNodes .findNodesByIndex(treeId, parentIndex) .mustFindOneOr(TreeNodeNotFound(treeId, parentIndex)) - _ ← * <~ (if (parentNode.path.value.contains(childNode.index.toString)) - DbResultT.failure(ParentChildSwapFailure(parentNode.index, childNode.index)) - else DbResultT.none) + _ ← * <~ when(parentNode.path.value.contains(childNode.index.toString), + DbResultT.failure(ParentChildSwapFailure(parentNode.index, childNode.index)).void) parentPath = parentNode.path.toString() patternLength = childNode.path.value.size - 1 diff --git a/phoenix-scala/phoenix/app/phoenix/services/variant/VariantManager.scala b/phoenix-scala/phoenix/app/phoenix/services/variant/VariantManager.scala index faa832228c..4ce6064983 100644 --- a/phoenix-scala/phoenix/app/phoenix/services/variant/VariantManager.scala +++ b/phoenix-scala/phoenix/app/phoenix/services/variant/VariantManager.scala @@ -1,5 +1,6 @@ package phoenix.services.variant +import cats.implicits._ import core.db._ import objectframework.ObjectUtils import objectframework.models._ @@ -135,7 +136,7 @@ object VariantManager { case Some(commit) ⇒ Variants.update(variant, variant.copy(shadowId = shadow.id, commitId = commit.id)) case None ⇒ - DbResultT.good(variant) + variant.pure[DbResultT] } def createVariantValue(contextName: String, variantId: Int, payload: VariantValuePayload)( @@ -219,7 +220,7 @@ object VariantManager { case Some(commit) ⇒ VariantValues.update(value, value.copy(shadowId = shadow.id, commitId = commit.id)) case None ⇒ - DbResultT.good(value) + value.pure[DbResultT] } def findVariantsByProduct(product: Product)( diff --git a/phoenix-scala/phoenix/app/phoenix/utils/apis/StripeWrapper.scala b/phoenix-scala/phoenix/app/phoenix/utils/apis/StripeWrapper.scala index 1dda61715d..7c1e9016ea 100644 --- a/phoenix-scala/phoenix/app/phoenix/utils/apis/StripeWrapper.scala +++ b/phoenix-scala/phoenix/app/phoenix/utils/apis/StripeWrapper.scala @@ -107,7 +107,7 @@ class StripeWrapper(timeout: FiniteDuration) extends StripeApiWrapper with LazyL case Left(xs) ⇒ Result.failures(xs) case Right(c: StripeCard) if c.getObject.equals("card") ⇒ - Result.good(c) + c.pure[Result] case _ ⇒ Result.failure(GeneralFailure("Not a stripe card: " ++ account.toString)) } diff --git a/phoenix-scala/phoenix/app/phoenix/utils/seeds/AddressSeeds.scala b/phoenix-scala/phoenix/app/phoenix/utils/seeds/AddressSeeds.scala index 5a19b5dee1..b3d2f0342a 100644 --- a/phoenix-scala/phoenix/app/phoenix/utils/seeds/AddressSeeds.scala +++ b/phoenix-scala/phoenix/app/phoenix/utils/seeds/AddressSeeds.scala @@ -20,7 +20,7 @@ trait AddressSeeds { canadaAddress2.copy(accountId = customers._3), rowAddress1.copy(accountId = customers._4) )) - } yield {} + } yield () def usAddress1 = Address( diff --git a/phoenix-scala/phoenix/app/phoenix/utils/seeds/CreditCardSeeds.scala b/phoenix-scala/phoenix/app/phoenix/utils/seeds/CreditCardSeeds.scala index ddbaf5167f..93cbac96d1 100644 --- a/phoenix-scala/phoenix/app/phoenix/utils/seeds/CreditCardSeeds.scala +++ b/phoenix-scala/phoenix/app/phoenix/utils/seeds/CreditCardSeeds.scala @@ -20,7 +20,7 @@ trait CreditCardSeeds extends CreditCardGenerator { creditCard4.copy(accountId = customers._3), creditCard5.copy(accountId = customers._4) )) - } yield {} + } yield () def creditCard1 = CreditCard( diff --git a/phoenix-scala/phoenix/app/phoenix/utils/seeds/GiftCardSeeds.scala b/phoenix-scala/phoenix/app/phoenix/utils/seeds/GiftCardSeeds.scala index d843ef8528..2685ccbba1 100644 --- a/phoenix-scala/phoenix/app/phoenix/utils/seeds/GiftCardSeeds.scala +++ b/phoenix-scala/phoenix/app/phoenix/utils/seeds/GiftCardSeeds.scala @@ -23,7 +23,7 @@ trait GiftCardSeeds { def insertCords: DbResultT[Unit] = for { _ ← * <~ Cords.create(Cord(1, "referenceNumber", true)) - } yield {} + } yield () def createGiftCards(implicit au: AU): DbResultT[Unit] = for { @@ -40,7 +40,7 @@ trait GiftCardSeeds { build(payload(balance = 10000, reasonId = reason.id), originId = origin.id, scope = scope)) _ ← * <~ Notes.createAll( giftCardNotes.map(_.copy(referenceId = gc1.id, storeAdminId = admin.accountId))) - } yield {} + } yield () def giftCardSubTypes: Seq[GiftCardSubtype] = Seq( GiftCardSubtype(title = "Appeasement Subtype A", originType = GiftCard.CsrAppeasement), diff --git a/phoenix-scala/phoenix/app/phoenix/utils/seeds/GroupTemplatesSeeds.scala b/phoenix-scala/phoenix/app/phoenix/utils/seeds/GroupTemplatesSeeds.scala index a09e85be3d..a12737d1ed 100644 --- a/phoenix-scala/phoenix/app/phoenix/utils/seeds/GroupTemplatesSeeds.scala +++ b/phoenix-scala/phoenix/app/phoenix/utils/seeds/GroupTemplatesSeeds.scala @@ -1,5 +1,6 @@ package phoenix.utils.seeds +import cats.implicits._ import core.db._ import org.json4s.JObject import org.json4s.jackson.JsonMethods.parse @@ -9,9 +10,7 @@ import phoenix.utils.aliases._ trait GroupTemplatesSeeds { def createGroupTemplates(scopeId: Int)(implicit db: DB, ac: AC, ec: EC): DbResultT[Unit] = - for { - _ ← CustomerGroupTemplates.create(abandonedCartsTemplate) - } yield DbResultT.unit + CustomerGroupTemplates.create(abandonedCartsTemplate).void private def abandonedCartsTemplate() = CustomerGroupTemplate( diff --git a/phoenix-scala/phoenix/app/phoenix/utils/seeds/ObjectSchemaSeeds.scala b/phoenix-scala/phoenix/app/phoenix/utils/seeds/ObjectSchemaSeeds.scala index 55f91cd53a..a264ff57bf 100644 --- a/phoenix-scala/phoenix/app/phoenix/utils/seeds/ObjectSchemaSeeds.scala +++ b/phoenix-scala/phoenix/app/phoenix/utils/seeds/ObjectSchemaSeeds.scala @@ -1,5 +1,6 @@ package phoenix.utils.seeds +import cats.implicits._ import core.db._ import objectframework.models._ import org.json4s.JValue @@ -39,10 +40,10 @@ trait ObjectSchemaSeeds { ObjectSchemas .update(current, current.copy(schema = newSchema.schema, dependencies = newSchema.dependencies)) - .meh + .void case _ ⇒ Console.err.println(s"Schema ${newSchema.name} not found, creating...") - ObjectSchemas.create(newSchema).meh + ObjectSchemas.create(newSchema).void } } } yield () diff --git a/phoenix-scala/phoenix/app/phoenix/utils/seeds/ReturnSeeds.scala b/phoenix-scala/phoenix/app/phoenix/utils/seeds/ReturnSeeds.scala index 054523ce5d..66589127a8 100644 --- a/phoenix-scala/phoenix/app/phoenix/utils/seeds/ReturnSeeds.scala +++ b/phoenix-scala/phoenix/app/phoenix/utils/seeds/ReturnSeeds.scala @@ -17,7 +17,7 @@ trait ReturnSeeds { case (sku, id) ⇒ sku.copy(id = id) }) _ ← * <~ Notes.createAll(returnNotes) - } yield {} + } yield () def createReturnReasons(implicit ec: EC): DbResultT[Option[Int]] = ReturnReasons.createAll(returnReasons) diff --git a/phoenix-scala/phoenix/app/phoenix/utils/seeds/StoreCreditSeeds.scala b/phoenix-scala/phoenix/app/phoenix/utils/seeds/StoreCreditSeeds.scala index 2334edca7a..96cd1b3cff 100644 --- a/phoenix-scala/phoenix/app/phoenix/utils/seeds/StoreCreditSeeds.scala +++ b/phoenix-scala/phoenix/app/phoenix/utils/seeds/StoreCreditSeeds.scala @@ -25,7 +25,7 @@ trait StoreCreditSeeds { sc2 ← * <~ StoreCredits.create(newSc.copy(originalBalance = 1000, accountId = cust1)) sc3 ← * <~ StoreCredits.create(newSc.copy(originalBalance = 500, accountId = cust1)) sc4 ← * <~ StoreCredits.create(newSc.copy(originalBalance = 2000, accountId = cust3)) - } yield {} + } yield () def storeCredit(implicit au: AU) = StoreCredit(accountId = 0, diff --git a/phoenix-scala/phoenix/app/phoenix/utils/seeds/generators/OrderGenerator.scala b/phoenix-scala/phoenix/app/phoenix/utils/seeds/generators/OrderGenerator.scala index 668d198895..7ee8be3134 100644 --- a/phoenix-scala/phoenix/app/phoenix/utils/seeds/generators/OrderGenerator.scala +++ b/phoenix-scala/phoenix/app/phoenix/utils/seeds/generators/OrderGenerator.scala @@ -73,7 +73,7 @@ trait OrderGenerator extends ShipmentSeeds { orderFun(accountId, context, randomSubset(skuIds), giftCard) } _ ← * <~ cartFun(accountId, context, randomSubset(skuIds), giftCard) - } yield {} + } yield () } private val yesterday: Instant = utils.time.yesterday.toInstant @@ -286,7 +286,7 @@ trait OrderGenerator extends ShipmentSeeds { skus ← * <~ Skus.filter(_.id inSet skuIds).result _ ← * <~ OrderLineItems.createAll(skus.map(sku ⇒ OrderLineItem(cordRef = orderRef, skuId = sku.id, skuShadowId = sku.shadowId, state = state))) - } yield {} + } yield () def addProductsToCart(skuIds: Seq[Int], cartRef: String)(implicit db: DB): DbResultT[Seq[CartLineItem]] = { val itemsToInsert = @@ -351,10 +351,11 @@ trait OrderGenerator extends ShipmentSeeds { op1 ← * <~ OrderPayments.create( OrderPayment.build(gc).copy(cordRef = cart.refNum, amount = deductFromGc.some)) op2 ← * <~ OrderPayments.create(OrderPayment.build(cc).copy(cordRef = cart.refNum, amount = none)) - } yield {} else + } yield () + else for { op ← * <~ OrderPayments.create(OrderPayment.build(cc).copy(cordRef = cart.refNum, amount = none)) - } yield {} + } yield () private def getCc(accountId: Int)(implicit db: DB) = CreditCards.findDefaultByAccountId(accountId).mustFindOneOr(CustomerHasNoCreditCard(accountId)) diff --git a/phoenix-scala/phoenix/app/phoenix/utils/seeds/generators/SeedsGenerator.scala b/phoenix-scala/phoenix/app/phoenix/utils/seeds/generators/SeedsGenerator.scala index 7e3c923b7e..b75b4df5aa 100644 --- a/phoenix-scala/phoenix/app/phoenix/utils/seeds/generators/SeedsGenerator.scala +++ b/phoenix-scala/phoenix/app/phoenix/utils/seeds/generators/SeedsGenerator.scala @@ -91,6 +91,6 @@ object SeedsGenerator _ ← * <~ randomSubset(customers, customers.length).map { customer ⇒ generateOrders(customer.accountId, context, skuIds, pickOne(giftCards)) } - } yield {} + } yield () } } diff --git a/phoenix-scala/phoenix/test/integration/AllOrdersIntegrationTest.scala b/phoenix-scala/phoenix/test/integration/AllOrdersIntegrationTest.scala index e9a292a271..ce0094c436 100644 --- a/phoenix-scala/phoenix/test/integration/AllOrdersIntegrationTest.scala +++ b/phoenix-scala/phoenix/test/integration/AllOrdersIntegrationTest.scala @@ -60,6 +60,6 @@ class AllOrdersIntegrationTest cart ← * <~ Carts.create(c.copy(referenceNumber = "baz")) order ← * <~ Orders.createFromCart(cart, subScope = None) _ ← * <~ Orders.update(order, order.copy(state = ManualHold)) - } yield {}).gimme + } yield ()).gimme } } diff --git a/phoenix-scala/phoenix/test/integration/CartIntegrationTest.scala b/phoenix-scala/phoenix/test/integration/CartIntegrationTest.scala index 9c31aee219..0fbd2fc058 100644 --- a/phoenix-scala/phoenix/test/integration/CartIntegrationTest.scala +++ b/phoenix-scala/phoenix/test/integration/CartIntegrationTest.scala @@ -72,7 +72,7 @@ class CartIntegrationTest (for { product ← * <~ Mvp.insertProduct(ctx.id, Factories.products.head.copy(image = imgUrl)) _ ← * <~ CartLineItems.create(CartLineItem(cordRef = cart.refNum, skuId = product.skuId)) - } yield {}).gimme + } yield ()).gimme cartsApi(cart.refNum).get().asTheResult[CartResponse].lineItems.skus.onlyElement.imagePath must === ( imgUrl) diff --git a/phoenix-scala/phoenix/test/integration/CartValidatorIntegrationTest.scala b/phoenix-scala/phoenix/test/integration/CartValidatorIntegrationTest.scala index bee3a6181f..562281e3e2 100644 --- a/phoenix-scala/phoenix/test/integration/CartValidatorIntegrationTest.scala +++ b/phoenix-scala/phoenix/test/integration/CartValidatorIntegrationTest.scala @@ -174,7 +174,7 @@ class CartValidatorIntegrationTest _ ← * <~ StoreCredits.create( Factories.storeCredit .copy(state = StoreCredit.Active, accountId = customer.accountId, originId = manual.id)) - } yield {}).gimme + } yield ()).gimme val refNum = cart.refNum } diff --git a/phoenix-scala/phoenix/test/integration/CreditCardsIntegrationTest.scala b/phoenix-scala/phoenix/test/integration/CreditCardsIntegrationTest.scala index c962d8ce2e..a327c73c37 100644 --- a/phoenix-scala/phoenix/test/integration/CreditCardsIntegrationTest.scala +++ b/phoenix-scala/phoenix/test/integration/CreditCardsIntegrationTest.scala @@ -22,7 +22,7 @@ import testutils.apis._ import testutils.fixtures.BakedFixtures import testutils.fixtures.PaymentFixtures.CreditCardsFixture import testutils.fixtures.api.ApiFixtureHelpers -import core.db.{when => ifM, _} +import core.db.{when ⇒ ifM, _} class CreditCardsIntegrationTest extends IntegrationTestBase @@ -86,7 +86,7 @@ class CreditCardsIntegrationTest .mustBeOk() val stripeCustomer2 = newStripeCustomer - when(stripeWrapperMock.createCustomer(m.any())).thenReturn(Result.good(stripeCustomer2)) + when(stripeWrapperMock.createCustomer(m.any())).thenReturn(stripeCustomer2.pure[Result]) customersApi(customer2.id).payments.creditCards .create(ccPayload.copy(token = "tok_2")) .mustBeOk() @@ -155,9 +155,9 @@ class CreditCardsIntegrationTest val ccResp1 = customersApi(customer.id).payments.creditCards.create(ccPayload).as[Root] val stripeCard2 = newStripeCard - when(stripeWrapperMock.createCard(m.any(), m.any())).thenReturn(Result.good(stripeCard2)) + when(stripeWrapperMock.createCard(m.any(), m.any())).thenReturn(stripeCard2.pure[Result]) when(stripeWrapperMock.findCardByCustomerId(stripeCustomer.getId, stripeCard2.getId)) - .thenReturn(Result.good(stripeCard2)) + .thenReturn(stripeCard2.pure[Result]) val ccResp2 = customersApi(customer.id).payments.creditCards.create(ccPayload).as[Root] diff --git a/phoenix-scala/phoenix/test/integration/ProductIntegrationTest.scala b/phoenix-scala/phoenix/test/integration/ProductIntegrationTest.scala index 0d015941c2..6a92490e05 100644 --- a/phoenix-scala/phoenix/test/integration/ProductIntegrationTest.scala +++ b/phoenix-scala/phoenix/test/integration/ProductIntegrationTest.scala @@ -597,8 +597,8 @@ class ProductIntegrationTest "Updates the SKUs on a product if variants are Some(Seq.empty)" in new Fixture { - ProductSkuLinks.filterLeft(product).deleteAll(DbResultT.none, DbResultT.none).gimme - ProductVariantLinks.filterLeft(product).deleteAll(DbResultT.none, DbResultT.none).gimme + ProductSkuLinks.filterLeft(product).deleteAll.gimme + ProductVariantLinks.filterLeft(product).deleteAll.gimme val payload = UpdateProductPayload(attributes = Map.empty, skus = Some(Seq(skuPayload)), @@ -615,8 +615,8 @@ class ProductIntegrationTest "Multiple calls with same params create single SKU link" in new Fixture { - ProductSkuLinks.filterLeft(product).deleteAll(DbResultT.none, DbResultT.none).gimme - ProductVariantLinks.filterLeft(product).deleteAll(DbResultT.none, DbResultT.none).gimme + ProductSkuLinks.filterLeft(product).deleteAll.gimme + ProductVariantLinks.filterLeft(product).deleteAll.gimme val payload = UpdateProductPayload(attributes = Map.empty, skus = Some(Seq(skuPayload)), diff --git a/phoenix-scala/phoenix/test/integration/services/CheckoutTest.scala b/phoenix-scala/phoenix/test/integration/services/CheckoutTest.scala index 77e974ee5f..6999c44d12 100644 --- a/phoenix-scala/phoenix/test/integration/services/CheckoutTest.scala +++ b/phoenix-scala/phoenix/test/integration/services/CheckoutTest.scala @@ -28,7 +28,7 @@ import phoenix.utils.seeds.Factories import slick.jdbc.PostgresProfile.api._ import testutils._ import testutils.fixtures.BakedFixtures -import core.db.{when => ifM, _} +import core.db.{when ⇒ ifM, _} import core.utils.Money._ import phoenix.services.carts.CartLineItemUpdater @@ -43,10 +43,10 @@ class CheckoutTest def cartValidator(resp: CartValidatorResponse = CartValidatorResponse()): CartValidation = { val m = mock[CartValidation] - when(m.validate(isCheckout = false, fatalWarnings = true)).thenReturn(DbResultT.good(resp)) - when(m.validate(isCheckout = false, fatalWarnings = false)).thenReturn(DbResultT.good(resp)) - when(m.validate(isCheckout = true, fatalWarnings = true)).thenReturn(DbResultT.good(resp)) - when(m.validate(isCheckout = true, fatalWarnings = false)).thenReturn(DbResultT.good(resp)) + when(m.validate(isCheckout = false, fatalWarnings = true)).thenReturn(resp.pure[DbResultT]) + when(m.validate(isCheckout = false, fatalWarnings = false)).thenReturn(resp.pure[DbResultT]) + when(m.validate(isCheckout = true, fatalWarnings = true)).thenReturn(resp.pure[DbResultT]) + when(m.validate(isCheckout = true, fatalWarnings = false)).thenReturn(resp.pure[DbResultT]) m } @@ -165,7 +165,7 @@ class CheckoutTest // If any of checkouts fail, rest of for comprehension is ignored and scalacheck just starts a new one. // Hence you have an attempt to create a second cart for customer which is prohibited. // This is a silly guard to see real errors, not customer_has_only_one_cart constraint. - _ ← * <~ Carts.deleteAll(DbResultT.unit, DbResultT.unit) + _ ← * <~ Carts.deleteAll(().pure[DbResultT], ().pure[DbResultT]) cart ← * <~ Carts.create(Cart(accountId = customer.accountId, scope = Scope.current)) @@ -250,6 +250,6 @@ class CheckoutTest (for { _ ← * <~ OrderShippingMethods.create(OrderShippingMethod.build(cart.refNum, shipMethod)) _ ← * <~ OrderShippingAddresses.copyFromAddress(address = address, cordRef = cart.refNum) - } yield {}).gimme + } yield ()).gimme } } diff --git a/phoenix-scala/phoenix/test/integration/testutils/DbTestSupport.scala b/phoenix-scala/phoenix/test/integration/testutils/DbTestSupport.scala index 4e531a62aa..cf432707cd 100644 --- a/phoenix-scala/phoenix/test/integration/testutils/DbTestSupport.scala +++ b/phoenix-scala/phoenix/test/integration/testutils/DbTestSupport.scala @@ -90,7 +90,7 @@ trait DbTestSupport extends SuiteMixin with BeforeAndAfterAll with GimmeSupport // Can't create all schemas right now because promo tests are fucky // FIXME @anna @michalrus _ ← * <~ Factories.FIXME_createAllButPromoSchemas - } yield {}).gimme + } yield ()).gimme } object DbTestSupport extends GimmeSupport { diff --git a/phoenix-scala/phoenix/test/integration/testutils/fixtures/RawFixtures.scala b/phoenix-scala/phoenix/test/integration/testutils/fixtures/RawFixtures.scala index 52292911e7..b61608ea01 100644 --- a/phoenix-scala/phoenix/test/integration/testutils/fixtures/RawFixtures.scala +++ b/phoenix-scala/phoenix/test/integration/testutils/fixtures/RawFixtures.scala @@ -45,7 +45,7 @@ trait RawFixtures extends RawPaymentFixtures with TestSeeds { .create(Factories.address.copy(accountId = customer.accountId, isDefaultShipping = true)) .gimme - lazy val region: Region = Regions.findOneById(address.regionId).safeGet.gimme + lazy val region: Region = Regions.findOneById(address.regionId).unsafeGet.gimme } // Cart diff --git a/phoenix-scala/phoenix/test/integration/utils/DbResultTTest.scala b/phoenix-scala/phoenix/test/integration/utils/DbResultTTest.scala index 62f2b87241..2da521fe8f 100644 --- a/phoenix-scala/phoenix/test/integration/utils/DbResultTTest.scala +++ b/phoenix-scala/phoenix/test/integration/utils/DbResultTTest.scala @@ -18,8 +18,8 @@ class DbResultTTest extends TestBase with DbTestSupport with CatsHelpers with Gi val transformer = for { _ ← DbResultT.fromEither(Either.right(Factories.rma)) - _ ← DbResultT.good(Factories.rma) - c ← DbResultT.good(Factories.address) + _ ← Factories.rma.pure[DbResultT] + c ← Factories.address.pure[DbResultT] } yield c val result = db.run(transformer.runEmptyA.value).futureValue @@ -33,7 +33,7 @@ class DbResultTTest extends TestBase with DbTestSupport with CatsHelpers with Gi val transformer = for { _ ← DbResultT.fromEither(Either.right(Factories.rma)) _ ← DbResultT.failures[Unit](failure.single) - c ← DbResultT.good(Factories.address) + c ← Factories.address.pure[DbResultT] } yield c db.run(transformer.runEmptyA.value).futureValue.leftVal.head must === (failure) diff --git a/phoenix-scala/phoenix/test/integration/utils/MockedApis.scala b/phoenix-scala/phoenix/test/integration/utils/MockedApis.scala index 47fc7c03b2..50d6e2cb1c 100644 --- a/phoenix-scala/phoenix/test/integration/utils/MockedApis.scala +++ b/phoenix-scala/phoenix/test/integration/utils/MockedApis.scala @@ -2,7 +2,7 @@ package utils import cats.implicits._ import com.stripe.model.DeletedCard -import core.db.{when => ifM, _} +import core.db.{when ⇒ ifM, _} import java.io.File import org.apache.avro.generic.GenericData import org.apache.kafka.clients.producer.MockProducer @@ -67,18 +67,18 @@ trait MockedApis extends MockitoSugar with MustMatchers with OptionValues with A def initStripeApiMock(mocked: StripeWrapper): StripeWrapper = { reset(mocked) - when(mocked.findCustomer(any())).thenReturn(Result.good(stripeCustomer)) - when(mocked.createCustomer(any())).thenReturn(Result.good(stripeCustomer)) + when(mocked.findCustomer(any())).thenReturn(stripeCustomer.pure[Result]) + when(mocked.createCustomer(any())).thenReturn(stripeCustomer.pure[Result]) - when(mocked.findCardForCustomer(any(), any())).thenReturn(Result.good(stripeCard)) - when(mocked.getCustomersOnlyCard(any())).thenReturn(Result.good(stripeCard)) - when(mocked.findCardByCustomerId(any(), any())).thenReturn(Result.good(stripeCard)) - when(mocked.createCard(any(), any())).thenReturn(Result.good(stripeCard)) + when(mocked.findCardForCustomer(any(), any())).thenReturn(stripeCard.pure[Result]) + when(mocked.getCustomersOnlyCard(any())).thenReturn(stripeCard.pure[Result]) + when(mocked.findCardByCustomerId(any(), any())).thenReturn(stripeCard.pure[Result]) + when(mocked.createCard(any(), any())).thenReturn(stripeCard.pure[Result]) - when(mocked.updateCard(any(), any())).thenReturn(Result.good(stripeCard)) - when(mocked.deleteCard(any())).thenReturn(Result.good(new DeletedCard())) + when(mocked.updateCard(any(), any())).thenReturn(stripeCard.pure[Result]) + when(mocked.deleteCard(any())).thenReturn((new DeletedCard()).pure[Result]) - when(mocked.captureCharge(any(), any())).thenReturn(Result.good(new StripeCharge)) + when(mocked.captureCharge(any(), any())).thenReturn((new StripeCharge).pure[Result]) when(mocked.createCharge(any())).thenAnswer(new Answer[Result[StripeCharge]] { def answer(invocation: InvocationOnMock): Result[StripeCharge] = { val map = invocation.getArgument[Map[String, AnyRef]](0) @@ -86,7 +86,7 @@ trait MockedApis extends MockitoSugar with MustMatchers with OptionValues with A map.get("amount").flatMap(s ⇒ Try(s.toString.toInt).toOption).foreach(charge.setAmount(_)) map.get("currency").foreach(s ⇒ charge.setCurrency(s.toString)) charge.setId(Random.nextString(10)) - Result.good(charge) + charge.pure[Result] } }) when(mocked.refundCharge(any(), any())).thenAnswer(new Answer[Result[StripeCharge]] { @@ -99,7 +99,7 @@ trait MockedApis extends MockitoSugar with MustMatchers with OptionValues with A .flatMap(s ⇒ Try(s.toString.toInt).toOption) .foreach(charge.setAmountRefunded(_)) charge.setId(id) - Result.good(charge) + charge.pure[Result] } }) @@ -118,7 +118,7 @@ trait MockedApis extends MockitoSugar with MustMatchers with OptionValues with A lazy val amazonApiMock: AmazonApi = { val mocked = mock[AmazonApi] when(mocked.uploadFile(any[String], any[File], any[Boolean])(any[EC])) - .thenReturn(Result.good("http://amazon-image.url/1")) + .thenReturn("http://amazon-image.url/1".pure[Result]) when(mocked.uploadFileF(any[String], any[File], any[Boolean])(any[EC])) .thenReturn(Future.successful("http://amazon-image.url/1")) mocked @@ -126,8 +126,8 @@ trait MockedApis extends MockitoSugar with MustMatchers with OptionValues with A lazy val middlewarehouseApiMock: MiddlewarehouseApi = { val mocked = mock[MiddlewarehouseApi] - when(mocked.hold(any[OrderInventoryHold])(any[EC], any[AU])).thenReturn(Result.unit) - when(mocked.cancelHold(any[String])(any[EC], any[AU])).thenReturn(Result.unit) + when(mocked.hold(any[OrderInventoryHold])(any[EC], any[AU])).thenReturn(().pure[Result]) + when(mocked.cancelHold(any[String])(any[EC], any[AU])).thenReturn(().pure[Result]) when(mocked.createSku(any[Int], any[CreateSku])(any[EC], any[AU])) .thenReturn(ProductVariantSku(skuId = -1, mwhSkuId = -1).pure[DbResultT]) mocked diff --git a/phoenix-scala/phoenix/test/integration/utils/ModelIntegrationTest.scala b/phoenix-scala/phoenix/test/integration/utils/ModelIntegrationTest.scala index b77e0c6e86..4042e4b7da 100644 --- a/phoenix-scala/phoenix/test/integration/utils/ModelIntegrationTest.scala +++ b/phoenix-scala/phoenix/test/integration/utils/ModelIntegrationTest.scala @@ -1,5 +1,6 @@ package utils +import cats.implicits._ import core.failures.{DatabaseFailure, Failures, GeneralFailure} import phoenix.failures.StateTransitionNotAllowed import phoenix.models.account._ @@ -65,12 +66,12 @@ class ModelIntegrationTest extends IntegrationTestBase with TestObjectContext wi val customer = Users.create(Factories.customer.copy(accountId = account.id)).gimme val success = "Success" val failure = (_: User#Id) ⇒ GeneralFailure("Should not happen") - val delete = Users.deleteById(customer.id, DbResultT.good(success), failure).gimme + val delete = Users.deleteById(customer.id, success.pure[DbResultT], failure).gimme delete must === (success) } "returns failure for unsuccessful delete" in { - val success = DbResultT.good("Should not happen") + val success = "Should not happen".pure[DbResultT] val failure = (_: User#Id) ⇒ GeneralFailure("Boom") val delete = Users.deleteById(13, success, failure).gimmeFailures delete must === (failure(13).single) diff --git a/phoenix-scala/phoenix/test/integration/utils/TransactionRollbackTest.scala b/phoenix-scala/phoenix/test/integration/utils/TransactionRollbackTest.scala index 9ad528ba3b..056e096941 100644 --- a/phoenix-scala/phoenix/test/integration/utils/TransactionRollbackTest.scala +++ b/phoenix-scala/phoenix/test/integration/utils/TransactionRollbackTest.scala @@ -15,7 +15,7 @@ class TransactionRollbackTest extends IntegrationTestBase { (for { _ ← * <~ Addresses.create(Factories.address) _ ← * <~ DbResultT.failure[Unit](GeneralFailure("boom")) - } yield {}).gimmeTxnFailures + } yield ()).gimmeTxnFailures Addresses.result.gimme must have size 0 } @@ -25,7 +25,7 @@ class TransactionRollbackTest extends IntegrationTestBase { _ ← * <~ Addresses.create(Factories.address) _ ← * <~ Addresses.create(Factories.address.copy(name = "Jonh Doe")) _ ← * <~ DbResultT.failure[Unit](GeneralFailure("boom")) - } yield {}).gimmeTxnFailures + } yield ()).gimmeTxnFailures Addresses.result.gimme must have size 0 } @@ -37,7 +37,7 @@ class TransactionRollbackTest extends IntegrationTestBase { address1 ← * <~ Addresses.update(address, address.copy(name = "John Doe")) _ ← * <~ Addresses.update(address1, address1.copy(name = "Mary Jane")) _ ← * <~ DbResultT.failure[Unit](GeneralFailure("boom")) - } yield {}).gimmeTxnFailures + } yield ()).gimmeTxnFailures Addresses.result.headOption.gimme.value must === (address) } diff --git a/phoenix-scala/seeder/app/seeds/Seeds.scala b/phoenix-scala/seeder/app/seeds/Seeds.scala index 338afd6c79..1adab6c2de 100644 --- a/phoenix-scala/seeder/app/seeds/Seeds.scala +++ b/phoenix-scala/seeder/app/seeds/Seeds.scala @@ -239,9 +239,9 @@ object Seeds { for { _ ← * <~ SeedsGenerator.insertRandomizedSeeds(batchSize, appeasementsPerBatch) - } yield {} + } yield () } - } yield {} + } yield () step(s"Random batch $b", r) } @@ -268,7 +268,7 @@ object Seeds { admin ← * <~ Users.take(1).mustFindOneOr(NotFoundFailure404(User, "first")) _ ← * <~ Reasons.createAll(Factories.reasons.map(_.copy(storeAdminId = admin.id))) _ ← * <~ Factories.createReturnReasons - } yield {} + } yield () def createStageSeeds(implicit db: DB, ac: AC): DbResultT[Unit] = for { @@ -300,9 +300,9 @@ object Seeds { discounts ← * <~ Factories.createDiscounts(search) promotions ← * <~ Factories.createCouponPromotions(discounts) coupons ← * <~ Factories.createCoupons(promotions) - } yield {} + } yield () } - } yield {} + } yield () private def flyWayMigrate(config: Config)(implicit db: DB): Unit = { val flyway = newFlyway(jdbcDataSourceFromConfig("db", config), rootProjectSqlLocation)