Skip to content

Commit

Permalink
Add create project skeleton (project-openubl#288)
Browse files Browse the repository at this point in the history
  • Loading branch information
carlosthe19916 authored Dec 24, 2023
1 parent a390677 commit 90fd7a7
Show file tree
Hide file tree
Showing 15 changed files with 174 additions and 39 deletions.
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions ublhub/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
Starting:

```shell
docker-compose -f deploy/compose/compose.yaml up
docker-compose -f ublhub/deploy/compose/compose.yaml up
```

```shell
RUST_LOG=info cargo run -p ublhub-cli -- server --db-user user --db-password password
RUST_LOG=info cargo watch -x 'run -p ublhub-cli -- server --db-user user --db-password password'
```
1 change: 1 addition & 0 deletions ublhub/api/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ edition = "2021"
ublhub-entity = {path = "../entity"}
ublhub-common = {path = "../common"}
ublhub-migration = {path = "../migration"}

sea-orm = { version = "0.12", features = [ "sea-query-binder", "sqlx-postgres", "runtime-tokio-rustls", "macros" ] }
sea-query = "0.30.5"
async-trait = "0.1.75"
Expand Down
28 changes: 16 additions & 12 deletions ublhub/api/src/system/mod.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
use migration::{Migrator, MigratorTrait};
use sea_orm::{ConnectionTrait, Database, DatabaseConnection, DbErr, Statement};
use std::fmt::{Debug, Display, Formatter};
use std::sync::Arc;

use sea_orm::{ConnectionTrait, Database, DatabaseConnection, DbErr, Statement};

use migration::{Migrator, MigratorTrait};

use crate::db::{ConnectionOrTransaction, Transactional};

pub mod error;
pub mod project;

pub type System = Arc<InnerSystem>;

Expand Down Expand Up @@ -74,16 +79,15 @@ impl InnerSystem {
Ok(Self { db })
}

// todo
// pub(crate) fn connection<'db>(
// &'db self,
// tx: Transactional<'db>,
// ) -> ConnectionOrTransaction<'db> {
// match tx {
// Transactional::None => ConnectionOrTransaction::Connection(&self.db),
// Transactional::Some(tx) => ConnectionOrTransaction::Transaction(tx),
// }
// }
pub(crate) fn connection<'db>(
&'db self,
tx: Transactional<'db>,
) -> ConnectionOrTransaction<'db> {
match tx {
Transactional::None => ConnectionOrTransaction::Connection(&self.db),
Transactional::Some(tx) => ConnectionOrTransaction::Transaction(tx),
}
}

#[cfg(test)]
pub async fn for_test(name: &str) -> Result<Arc<Self>, anyhow::Error> {
Expand Down
83 changes: 83 additions & 0 deletions ublhub/api/src/system/project.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
use std::fmt::{Debug, Formatter};

use sea_orm::ActiveValue::Set;
use sea_orm::{ActiveModelTrait, ColumnTrait, EntityTrait, QueryFilter};

use ublhub_entity::project;

use crate::db::Transactional;
use crate::system::error::Error;
use crate::system::InnerSystem;

impl InnerSystem {
pub async fn create_project(
&self,
model: &project::Model,
tx: Transactional<'_>,
) -> Result<ProjectContext, Error> {
if let Some(found) = self.get_project(&model.name, tx).await? {
Ok(found)
} else {
let entity = project::ActiveModel {
name: Set(model.name.clone()),
description: Set(model.description.clone()),
sunat_username: Set(model.sunat_username.clone()),
sunat_password: Set(model.sunat_password.clone()),
sunat_factura_url: Set(model.sunat_factura_url.clone()),
sunat_guia_url: Set(model.sunat_guia_url.clone()),
sunat_percepcion_retencion_url: Set(model.sunat_percepcion_retencion_url.clone()),
};

Ok((self, entity.insert(&self.connection(tx)).await?).into())
}
}

pub async fn get_project(
&self,
name: &str,
tx: Transactional<'_>,
) -> Result<Option<ProjectContext>, Error> {
Ok(project::Entity::find()
.filter(project::Column::Name.eq(name))
.one(&self.connection(tx))
.await?
.map(|project| (self, project).into()))
}
}

#[derive(Clone)]
pub struct ProjectContext {
pub system: InnerSystem,
pub project: project::Model,
}

impl Debug for ProjectContext {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
self.project.fmt(f)
}
}

impl From<(&InnerSystem, project::Model)> for ProjectContext {
fn from((system, project): (&InnerSystem, project::Model)) -> Self {
Self {
system: system.clone(),
project,
}
}
}

// impl ProjectContext {
// pub async fn advisories(&self, tx: Transactional<'_>) -> Result<Vec<ProjectContext>, Error> {
// Ok(advisory::Entity::find()
// .join(
// JoinType::Join,
// advisory_vulnerability::Relation::Advisory.def().rev(),
// )
// .filter(advisory_vulnerability::Column::VulnerabilityId.eq(self.cve.id))
// .all(&self.system.connection(tx))
// .await?
// .drain(0..)
// .map(|advisory| (&self.system, advisory).into())
// .collect())
// }
// }
3 changes: 2 additions & 1 deletion ublhub/entity/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ edition = "2021"
publish = false

[dependencies]
sea-orm = { version = "0.12.10", features = ["sqlx-postgres", "runtime-tokio-rustls", "macros"] }
sea-orm = { version = "0.12.10", features = ["sqlx-postgres", "runtime-tokio-rustls", "macros"] }
serde = { version = "1.0.193", features = ["derive"] }
4 changes: 2 additions & 2 deletions ublhub/entity/src/project.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.10

use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Deserialize, Serialize)]
#[sea_orm(table_name = "project")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub name: String,
pub description: Option<String>,
pub sunat_username: String,
Expand Down
6 changes: 3 additions & 3 deletions ublhub/entity/src/user_role.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,16 @@ pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub username: String,
#[sea_orm(primary_key, auto_increment = false)]
pub project_id: i32,
pub project_name: i32,
pub roles: String,
}

#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(
belongs_to = "super::project::Entity",
from = "Column::ProjectId",
to = "super::project::Column::Id",
from = "Column::ProjectName",
to = "super::project::Column::Name",
on_update = "NoAction",
on_delete = "Cascade"
)]
Expand Down
10 changes: 1 addition & 9 deletions ublhub/migration/src/m20231223_071007_create_project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,11 @@ impl MigrationTrait for Migration {
Table::create()
.table(Project::Table)
.if_not_exists()
.col(
ColumnDef::new(Project::Id)
.integer()
.not_null()
.auto_increment()
.primary_key(),
)
.col(
ColumnDef::new(Project::Name)
.string()
.not_null()
.unique_key(),
.primary_key(),
)
.col(ColumnDef::new(Project::Description).string())
.col(ColumnDef::new(Project::SunatUsername).string().not_null())
Expand All @@ -49,7 +42,6 @@ impl MigrationTrait for Migration {
#[derive(DeriveIden)]
pub enum Project {
Table,
Id,
Name,
Description,
SunatUsername,
Expand Down
10 changes: 5 additions & 5 deletions ublhub/migration/src/m20231223_075825_create_user_role.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,17 @@ impl MigrationTrait for Migration {
.table(UserRole::Table)
.if_not_exists()
.col(ColumnDef::new(UserRole::Username).string().not_null())
.col(ColumnDef::new(UserRole::ProjectId).integer().not_null())
.col(ColumnDef::new(UserRole::ProjectName).string().not_null())
.col(ColumnDef::new(UserRole::Roles).string().not_null())
.primary_key(
Index::create()
.col(UserRole::Username)
.col(UserRole::ProjectId),
.col(UserRole::ProjectName),
)
.foreign_key(
ForeignKey::create()
.from_col(UserRole::ProjectId)
.to(Project::Table, Project::Id)
.from_col(UserRole::ProjectName)
.to(Project::Table, Project::Name)
.on_delete(ForeignKeyAction::Cascade),
)
.to_owned(),
Expand All @@ -43,6 +43,6 @@ impl MigrationTrait for Migration {
pub enum UserRole {
Table,
Username,
ProjectId,
ProjectName,
Roles,
}
1 change: 1 addition & 0 deletions ublhub/server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ description = "Web service for managing UBL files from SUNAT"
[dependencies]
ublhub-api = { path = "../api" }
ublhub-common = { path = "../common" }
ublhub-entity = {path = "../entity"}
xsender = { path = "../../xsender" }
xbuilder = { path = "../../xbuilder" }

Expand Down
10 changes: 7 additions & 3 deletions ublhub/server/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
use actix_web::middleware::Logger;
use actix_web::{web, App, HttpServer};
use std::process::ExitCode;
use std::sync::Arc;

use actix_web::middleware::Logger;
use actix_web::{web, App, HttpServer};

use ublhub_api::system::InnerSystem;
use ublhub_common::config::Database;

use crate::server::project;
use crate::server::{health, project};

pub mod server;

Expand Down Expand Up @@ -61,5 +63,7 @@ pub struct AppState {
}

pub fn configure(config: &mut web::ServiceConfig) {
config.service(health::liveness);
config.service(health::readiness);
config.service(project::create_project);
}
24 changes: 24 additions & 0 deletions ublhub/server/src/server/health.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
use actix_web::{get, web, Responder};

use crate::server::Error;
use crate::AppState;

#[utoipa::path(
responses(
(status = 200, description = "Liveness"),
),
)]
#[get("/health/live")]
pub async fn liveness(_: web::Data<AppState>) -> Result<impl Responder, Error> {
Ok("Live")
}

#[utoipa::path(
responses(
(status = 200, description = "Readiness"),
),
)]
#[get("/health/read")]
pub async fn readiness(_: web::Data<AppState>) -> Result<impl Responder, Error> {
Ok("Read")
}
1 change: 1 addition & 0 deletions ublhub/server/src/server/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use actix_web::{HttpResponse, ResponseError};

use ublhub_api::system;

pub mod health;
pub mod project;

#[derive(Debug, thiserror::Error)]
Expand Down
26 changes: 24 additions & 2 deletions ublhub/server/src/server/project.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
use actix_web::{post, web, HttpResponse, Responder};

use ublhub_api::db::Transactional;
use ublhub_entity::project;

use crate::server::Error;
use crate::AppState;

#[utoipa::path(
Expand All @@ -8,6 +12,24 @@ use crate::AppState;
),
)]
#[post("projects")]
pub async fn create_project(_: web::Data<AppState>) -> actix_web::Result<impl Responder> {
Ok(HttpResponse::Ok().finish())
pub async fn create_project(
state: web::Data<AppState>,
json: web::Json<project::Model>,
) -> Result<impl Responder, Error> {
let prev = state
.system
.get_project(&json.name, Transactional::None)
.await?;

match prev {
None => {
let ctx = state
.system
.create_project(&json, Transactional::None)
.await
.map_err(Error::System)?;
Ok(HttpResponse::Ok().json(ctx.project))
}
Some(_) => Ok(HttpResponse::Conflict().body("Project name already exists")),
}
}

0 comments on commit 90fd7a7

Please sign in to comment.