diff --git a/.gitignore b/.gitignore index 42a56c5..e6e0538 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,10 @@ back/.env back/repuestera_back mysql/.env +comms/.env +.metals/ +back/tmp/main +comms/.bsp/sbt.json +comms/project/project/ +comms/project/target/ +comms/target/ diff --git a/comms/.env.example b/comms/.env.example new file mode 100644 index 0000000..54a7625 --- /dev/null +++ b/comms/.env.example @@ -0,0 +1,6 @@ +SMTP_HOST=smtp.gmail.com +SMTP_PORT=587 +SMTP_USER=tu-usuario@gmail.com +SMTP_PASSWORD=tu-app-password +SMTP_FROM=tu-usuario@gmail.com +SMTP_TO=destinatario@example.com diff --git a/comms/README.md b/comms/README.md new file mode 100644 index 0000000..2e3651d --- /dev/null +++ b/comms/README.md @@ -0,0 +1,84 @@ +# comms + +Servicio de comunicaciones. Expone un endpoint HTTP que recibe un JSON y lo envía por email vía SMTP. + +## Requisitos + +- Java 21+ +- sbt 1.x + +## Configuración + +Crear un `.env` en esta carpeta (basado en `.env.example`): + +``` +SMTP_HOST=smtp.gmail.com +SMTP_PORT=587 +SMTP_USER=tu-usuario@gmail.com +SMTP_PASSWORD=tu-app-password +SMTP_FROM=tu-usuario@gmail.com +SMTP_TO=destinatario@example.com(solo se usa en testint `sbt test`) +``` + +- `SMTP_PORT`: `587` (STARTTLS) o `465` (SSL). Por defecto `587`. + +## Correr + +```sh +sbt run +``` + +El servidor escucha en `http://localhost:8088`. + +## Endpoint + +### `POST /email` + +Envía un email. `to` es el destinatario (viene en la request, no en el `.env`). + +```sh +curl -X POST http://localhost:8088/email \ + -H 'Content-Type: application/json' \ + -d '{ + "titulo": "Pedido #123", + "descripcion": "

Nuevo pedido

", + "items": ["Bujía", "Filtro de aceite", "Pastillas de freno"], + "to": "cliente@example.com" + }' +``` + +- `titulo`: asunto del email (string). +- `descripcion`: cuerpo del email, se trata como HTML. +- `items`: lista de strings, se renderiza como tabla en el email. +- `to`: destinatario (string). + +Respuestas: + +- `200 OK` si se envió. +- `400 Bad Request` si el JSON no es válido. + +## Test de envío real + +Manda un email de verdad usando las credenciales del `.env` (el destinatario sale de `SMTP_TO`, o de `SMTP_FROM` si la variable no está): + +```sh +sbt "testOnly com.fede.comms.SmtpEmailSpec" +``` + +## Estructura + +``` +src/main/scala/com/fede/comms/ +├── Main.scala # entrypoint +├── CommsServer.scala # wiring del servidor +├── CommsRoutes.scala # rutas HTTP +├── config/ +│ └── SmtpConfig.scala # config SMTP + parser de .env +└── emails/ + ├── Emails.scala # modelo Mensaje + trait Email + └── SmtpEmail.scala # envío vía SMTP +``` + +## Futuro + +Pensado para agregar un webhook que también reciba el mismo JSON y lo envíe por otros canales. Basta con definir un trait por canal (como `Email[F]`) y encadenarlo en `CommsRoutes`. diff --git a/comms/build.sbt b/comms/build.sbt new file mode 100644 index 0000000..31c0203 --- /dev/null +++ b/comms/build.sbt @@ -0,0 +1,31 @@ +val Http4sVersion = "0.23.36" +val CirceVersion = "0.14.16" +val MunitVersion = "1.3.4" +val LogbackVersion = "1.6.1" +val MunitCatsEffectVersion = "2.2.0" +val JakartaMailVersion = "2.0.2" + +lazy val root = (project in file(".")) + .settings( + organization := "com.fede.comms", + name := "comms", + version := "0.0.1-SNAPSHOT", + scalaVersion := "2.13.18", + libraryDependencies ++= Seq( + "org.http4s" %% "http4s-ember-server" % Http4sVersion, + "org.http4s" %% "http4s-ember-client" % Http4sVersion, + "org.http4s" %% "http4s-circe" % Http4sVersion, + "org.http4s" %% "http4s-dsl" % Http4sVersion, + "io.circe" %% "circe-generic" % CirceVersion, + "org.scalameta" %% "munit" % MunitVersion % Test, + "org.typelevel" %% "munit-cats-effect" % MunitCatsEffectVersion % Test, + "com.sun.mail" % "jakarta.mail" % JakartaMailVersion, + "ch.qos.logback" % "logback-classic" % LogbackVersion % Runtime, + ), + addCompilerPlugin("org.typelevel" %% "kind-projector" % "0.13.4" cross CrossVersion.full), + addCompilerPlugin("com.olegpy" %% "better-monadic-for" % "0.3.1"), + assembly / assemblyMergeStrategy := { + case "module-info.class" => MergeStrategy.discard + case x => (assembly / assemblyMergeStrategy).value.apply(x) + } + ) diff --git a/comms/project/build.properties b/comms/project/build.properties new file mode 100644 index 0000000..e544c4d --- /dev/null +++ b/comms/project/build.properties @@ -0,0 +1 @@ +sbt.version=1.12.14 diff --git a/comms/project/plugins.sbt b/comms/project/plugins.sbt new file mode 100644 index 0000000..bcb3326 --- /dev/null +++ b/comms/project/plugins.sbt @@ -0,0 +1,3 @@ +addSbtPlugin("org.typelevel" % "sbt-tpolecat" % "0.5.7") +addSbtPlugin("io.spray" % "sbt-revolver" % "0.10.0") +addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "2.4.1") diff --git a/comms/src/main/resources/logback.xml b/comms/src/main/resources/logback.xml new file mode 100644 index 0000000..8ea8412 --- /dev/null +++ b/comms/src/main/resources/logback.xml @@ -0,0 +1,16 @@ + + + + true + + [%thread] %highlight(%-5level) %cyan(%logger{15}) - %msg %n + + + + + + diff --git a/comms/src/main/scala/com/fede/comms/CommsRoutes.scala b/comms/src/main/scala/com/fede/comms/CommsRoutes.scala new file mode 100644 index 0000000..a24953f --- /dev/null +++ b/comms/src/main/scala/com/fede/comms/CommsRoutes.scala @@ -0,0 +1,23 @@ +package com.fede.comms + +import cats.effect.Concurrent +import cats.syntax.all._ +import com.fede.comms.emails.{Email, Mensaje} +import org.http4s.HttpRoutes +import org.http4s.circe.CirceEntityDecoder._ +import org.http4s.dsl.Http4sDsl + +object CommsRoutes { + + def emailRoutes[F[_]: Concurrent](email: Email[F]): HttpRoutes[F] = { + val dsl = new Http4sDsl[F] {} + import dsl._ + HttpRoutes.of[F] { + case req @ POST -> Root / "email" => + req.attemptAs[Mensaje].foldF( + _ => BadRequest(), + mensaje => email.enviar(mensaje) *> Ok() + ) + } + } +} diff --git a/comms/src/main/scala/com/fede/comms/CommsServer.scala b/comms/src/main/scala/com/fede/comms/CommsServer.scala new file mode 100644 index 0000000..af43967 --- /dev/null +++ b/comms/src/main/scala/com/fede/comms/CommsServer.scala @@ -0,0 +1,31 @@ +package com.fede.comms + +import cats.effect.{Async, Resource} +import com.comcast.ip4s._ +import com.fede.comms.config.SmtpConfig +import com.fede.comms.emails.SmtpEmail +import fs2.io.net.Network +import org.http4s.ember.server.EmberServerBuilder +import org.http4s.implicits._ +import org.http4s.server.middleware.Logger + +object CommsServer { + + def run[F[_]: Async: Network]: F[Nothing] = { + for { + smtpConfig <- Resource.eval(SmtpConfig.load[F]()) + email = new SmtpEmail[F](smtpConfig) + + httpApp = CommsRoutes.emailRoutes[F](email).orNotFound + + finalHttpApp = Logger.httpApp(true, true)(httpApp) + + _ <- + EmberServerBuilder.default[F] + .withHost(ipv4"0.0.0.0") + .withPort(port"8088") + .withHttpApp(finalHttpApp) + .build + } yield () + }.useForever +} diff --git a/comms/src/main/scala/com/fede/comms/Main.scala b/comms/src/main/scala/com/fede/comms/Main.scala new file mode 100644 index 0000000..dd6afff --- /dev/null +++ b/comms/src/main/scala/com/fede/comms/Main.scala @@ -0,0 +1,7 @@ +package com.fede.comms + +import cats.effect.{IO, IOApp} + +object Main extends IOApp.Simple { + val run = CommsServer.run[IO] +} diff --git a/comms/src/main/scala/com/fede/comms/config/SmtpConfig.scala b/comms/src/main/scala/com/fede/comms/config/SmtpConfig.scala new file mode 100644 index 0000000..4422714 --- /dev/null +++ b/comms/src/main/scala/com/fede/comms/config/SmtpConfig.scala @@ -0,0 +1,69 @@ +package com.fede.comms.config + +import cats.effect.Sync + +import java.io.File +import scala.io.Source + +final case class SmtpConfig( + host: String, + port: Int, + user: String, + password: String, + from: String, + to: String +) + +object SmtpConfig { + + def load[F[_]: Sync](envFile: String = ".env"): F[SmtpConfig] = + Sync[F].delay { + val env = EnvFile.load(envFile) + + def required(key: String): String = + env.getOrElse(key, sys.error(s"Falta $key en $envFile")) + + SmtpConfig( + host = required("SMTP_HOST"), + port = env.get("SMTP_PORT").flatMap(_.toIntOption).getOrElse(587), + user = required("SMTP_USER"), + password = required("SMTP_PASSWORD"), + from = required("SMTP_FROM"), + to = required("SMTP_TO") + ) + } +} + +object EnvFile { + + def load(path: String): Map[String, String] = { + val file = new File(path) + if (!file.exists()) Map.empty + else { + val lines = Source.fromFile(file).getLines().toList + lines.flatMap(parseLine).toMap + } + } + + private def parseLine(line: String): Option[(String, String)] = { + val trimmed = line.trim + if (trimmed.isEmpty || trimmed.startsWith("#")) None + else { + val withoutExport = trimmed.stripPrefix("export").trim + val idx = withoutExport.indexOf('=') + if (idx <= 0) None + else { + val key = withoutExport.substring(0, idx).trim + val raw = withoutExport.substring(idx + 1).trim + val value = raw match { + case q if q.length >= 2 && q.head == '"' && q.last == '"' => + q.substring(1, q.length - 1) + case q if q.length >= 2 && q.head == '\'' && q.last == '\'' => + q.substring(1, q.length - 1) + case other => other + } + Some(key -> value) + } + } + } +} diff --git a/comms/src/main/scala/com/fede/comms/emails/Emails.scala b/comms/src/main/scala/com/fede/comms/emails/Emails.scala new file mode 100644 index 0000000..0ae15f4 --- /dev/null +++ b/comms/src/main/scala/com/fede/comms/emails/Emails.scala @@ -0,0 +1,25 @@ +package com.fede.comms.emails + +import cats.effect.Concurrent +import io.circe.{Decoder, Encoder} +import io.circe.generic.semiauto._ +import org.http4s.{EntityDecoder, EntityEncoder} +import org.http4s.circe._ + +final case class Mensaje(titulo: String, descripcion: String, items: List[String], to: String) + +object Mensaje { + implicit val mensajeDecoder: Decoder[Mensaje] = deriveDecoder + implicit def mensajeEntityDecoder[F[_]: Concurrent]: EntityDecoder[F, Mensaje] = jsonOf + + implicit val mensajeEncoder: Encoder[Mensaje] = deriveEncoder + implicit def mensajeEntityEncoder[F[_]]: EntityEncoder[F, Mensaje] = jsonEncoderOf +} + +trait Email[F[_]] { + def enviar(m: Mensaje): F[Unit] +} + +object Email { + def apply[F[_]](implicit ev: Email[F]): Email[F] = ev +} diff --git a/comms/src/main/scala/com/fede/comms/emails/SmtpEmail.scala b/comms/src/main/scala/com/fede/comms/emails/SmtpEmail.scala new file mode 100644 index 0000000..dfe7d93 --- /dev/null +++ b/comms/src/main/scala/com/fede/comms/emails/SmtpEmail.scala @@ -0,0 +1,60 @@ +package com.fede.comms.emails + +import cats.effect.Sync +import jakarta.mail.internet.{InternetAddress, MimeMessage} +import jakarta.mail.{Authenticator, Message, PasswordAuthentication, Session, Transport} + +import java.util.Properties + +final class SmtpEmail[F[_]: Sync](config: com.fede.comms.config.SmtpConfig) extends Email[F] { + + def enviar(m: Mensaje): F[Unit] = + Sync[F].blocking { + val props = new Properties() + props.put("mail.transport.protocol", "smtp") + props.put("mail.smtp.host", config.host) + props.put("mail.smtp.port", config.port.toString) + props.put("mail.smtp.auth", "true") + if (config.port == 465) { + props.put("mail.smtp.ssl.enable", "true") + } else { + props.put("mail.smtp.starttls.enable", "true") + } + + val session = Session.getInstance(props, new Authenticator { + override def getPasswordAuthentication: PasswordAuthentication = + new PasswordAuthentication(config.user, config.password) + }) + + val message = new MimeMessage(session) + message.setFrom(new InternetAddress(config.from)) + message.setRecipients(Message.RecipientType.TO, m.to) + message.setSubject(m.titulo, "UTF-8") + message.setContent(htmlBody(m), "text/html; charset=utf-8") + Transport.send(message) + } + + private def htmlBody(m: Mensaje): String = { + val itemsHtml = + if (m.items.isEmpty) "" + else + m.items.zipWithIndex + .map { case (item, i) => + s"""${i + 1}${escape(item)}""" + } + .mkString( + """ + | + |""".stripMargin, + "", + "
#Item
" + ) + s""" + |${m.descripcion} + |$itemsHtml + |""".stripMargin + } + + private def escape(s: String): String = + s.replace("&", "&").replace("<", "<").replace(">", ">") +} diff --git a/comms/src/test/scala/com/fede/comms/CommsRoutesSpec.scala b/comms/src/test/scala/com/fede/comms/CommsRoutesSpec.scala new file mode 100644 index 0000000..c83822c --- /dev/null +++ b/comms/src/test/scala/com/fede/comms/CommsRoutesSpec.scala @@ -0,0 +1,41 @@ +package com.fede.comms + +import cats.effect.IO +import cats.effect.kernel.Ref +import com.fede.comms.emails.{Email, Mensaje} +import org.http4s._ +import org.http4s.implicits._ +import munit.CatsEffectSuite + +class CommsRoutesSpec extends CatsEffectSuite { + + test("POST /email returns 200 and calls enviar") { + val testIO = for { + ref <- Ref.of[IO, List[Mensaje]](Nil) + email = new Email[IO] { + def enviar(m: Mensaje): IO[Unit] = ref.update(_ :+ m) + } + req = Request[IO](Method.POST, uri"/email") + .withEntity(Mensaje("Titulo", "Descripcion", List("a", "b"), "a@b.com")) + resp <- CommsRoutes.emailRoutes[IO](email).orNotFound(req) + sent <- ref.get + } yield (resp.status, sent) + + for { + r <- testIO + _ <- assertIO(IO.pure(r._1), Status.Ok) + _ <- assertIO(IO.pure(r._2), List(Mensaje("Titulo", "Descripcion", List("a", "b"), "a@b.com"))) + } yield () + } + + test("POST /email with invalid json returns 400") { + val email = new Email[IO] { + def enviar(m: Mensaje): IO[Unit] = IO.unit + } + val req = Request[IO](Method.POST, uri"/email").withEntity("{}") + assertIO( + CommsRoutes.emailRoutes[IO](email).orNotFound(req).map(_.status), + Status.BadRequest + ) + } +} diff --git a/comms/src/test/scala/com/fede/comms/SmtpEmailSpec.scala b/comms/src/test/scala/com/fede/comms/SmtpEmailSpec.scala new file mode 100644 index 0000000..5112a80 --- /dev/null +++ b/comms/src/test/scala/com/fede/comms/SmtpEmailSpec.scala @@ -0,0 +1,25 @@ +package com.fede.comms + +import cats.effect.IO +import com.fede.comms.config.SmtpConfig +import com.fede.comms.emails.{Mensaje, SmtpEmail} +import munit.CatsEffectSuite + +class SmtpEmailSpec extends CatsEffectSuite { + + test("envia un email real usando el .env") { + for { + config <- SmtpConfig.load[IO]() + email = new SmtpEmail[IO](config) + to = sys.env.getOrElse("SMTP_TO", config.from) + _ <- email.enviar( + Mensaje( + titulo = "[comms] prueba", + descripcion = "Email de prueba desde el servicio comms", + items = List("item 1", "item 2"), + to = to + ) + ) + } yield () + } +}