Skip to content

Commit

Permalink
task: refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
carlosthe19916 committed Jul 20, 2024
1 parent 5f33bd3 commit bfc4758
Show file tree
Hide file tree
Showing 46 changed files with 877 additions and 1,968 deletions.
477 changes: 1 addition & 476 deletions Cargo.lock

Large diffs are not rendered by default.

3 changes: 0 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,13 @@ resolver = "2"
members = [
"xbuilder",
"xsender",
# "xsigner",
"openubl/migration",
"openubl/entity",
"openubl/common",
"openubl/api",
"openubl/server",
"openubl/cli",
"openubl/oidc",
"openubl/storage",
# "openubl/index",
"openubl/signature",
]

Expand Down
10 changes: 5 additions & 5 deletions openubl/api/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
openubl-entity = {path = "../entity"}
openubl-common = {path = "../common"}
openubl-migration = {path = "../migration"}
openubl-entity = { path = "../entity" }
openubl-common = { path = "../common" }
openubl-migration = { path = "../migration" }
openubl-storage = { path = "../storage" }

xsender = {path = "../../xsender"}
xsender = { path = "../../xsender" }

sea-orm = { version = "0.12", features = [ "sea-query-binder", "sqlx-postgres", "runtime-tokio-rustls", "macros" ] }
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"
anyhow = "1.0.76"
Expand Down
99 changes: 98 additions & 1 deletion openubl/api/src/system/credentials.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
use sea_orm::ActiveModelTrait;
use sea_orm::ActiveValue::Set;
use sea_orm::ColumnTrait;
use sea_orm::QueryFilter;
use sea_orm::{ActiveModelTrait, EntityTrait, QuerySelect, RelationTrait};
use sea_query::JoinType;

use openubl_entity as entity;

Expand All @@ -21,6 +24,100 @@ impl From<(&InnerSystem, entity::credentials::Model)> for CredentialsContext {
}
}

impl InnerSystem {
pub async fn find_credentials_by_id(
&self,
id: i32,
tx: Transactional<'_>,
) -> Result<Option<CredentialsContext>, Error> {
Ok(entity::credentials::Entity::find_by_id(id)
.one(&self.connection(tx))
.await?
.map(|e| (self, e).into()))
}

pub async fn find_credentials_by_supplier_id(
&self,
supplier_id: &str,
tx: Transactional<'_>,
) -> Result<Option<CredentialsContext>, Error> {
let credential: Option<CredentialsContext> = entity::credentials::Entity::find()
.join(
JoinType::InnerJoin,
entity::credentials::Relation::SendRule.def(),
)
.filter(entity::send_rule::Column::SupplierId.eq(supplier_id))
.one(&self.connection(tx))
.await?
.map(|e| (self, e).into());

match credential {
Some(credential) => Ok(Some(credential)),

// If no credentials found, try the default one
None => Ok(entity::credentials::Entity::find()
.join(
JoinType::InnerJoin,
entity::credentials::Relation::SendRule.def(),
)
.filter(entity::send_rule::Column::SupplierId.eq("*"))
.one(&self.connection(tx))
.await?
.map(|e| (self, e).into())),
}
}

pub async fn list_credentials(
&self,
tx: Transactional<'_>,
) -> Result<Vec<CredentialsContext>, Error> {
Ok(entity::credentials::Entity::find()
.all(&self.connection(tx))
.await?
.drain(0..)
.map(|credentials| (self, credentials).into())
.collect())
}

pub async fn persist_credentials(
&self,
model: &entity::credentials::Model,
supplier_ids: &[String],
tx: Transactional<'_>,
) -> Result<CredentialsContext, Error> {
let entity = entity::credentials::ActiveModel {
name: Set(model.name.clone()),
description: Set(model.description.clone()),
username_sol: Set(model.username_sol.clone()),
password_sol: Set(model.password_sol.clone()),
client_id: Set(model.client_id.clone()),
client_secret: Set(model.client_secret.clone()),

url_invoice: Set(model.url_invoice.clone()),
url_despatch: Set(model.url_despatch.clone()),
url_perception_retention: Set(model.url_perception_retention.clone()),

id: Default::default(),
};

let result = entity.insert(&self.connection(tx)).await?;

let rules = supplier_ids
.iter()
.map(|supplier_id| entity::send_rule::ActiveModel {
id: Default::default(),
supplier_id: Set(supplier_id.clone()),
credentials_id: Set(result.id),
})
.collect::<Vec<_>>();
let _rules = entity::send_rule::Entity::insert_many(rules)
.exec(&self.connection(tx))
.await?;

Ok((self, result).into())
}
}

impl CredentialsContext {
pub async fn update(
&self,
Expand Down
177 changes: 177 additions & 0 deletions openubl/api/src/system/document.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
use sea_orm::ActiveValue::Set;
use sea_orm::ColumnTrait;
use sea_orm::{ActiveModelTrait, EntityTrait, PaginatorTrait, QueryFilter, QueryOrder};
use sea_query::Order::Desc;

use openubl_entity as entity;
use openubl_entity::delivery::{TargetSendFileProtocolAction, TargetVerifyTicketProtocolAction};
use xsender::prelude::*;

use crate::db::{Paginated, PaginatedResults, Transactional};
use crate::system::error::Error;
use crate::system::InnerSystem;

pub struct DocumentContext {
pub system: InnerSystem,
pub document: entity::document::Model,
}

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

impl InnerSystem {
pub async fn find_document_by_id(
&self,
id: i32,
tx: Transactional<'_>,
) -> Result<Option<DocumentContext>, Error> {
Ok(entity::document::Entity::find_by_id(id)
.one(&self.connection(tx))
.await?
.map(|document| (self, document).into()))
}

pub async fn list_documents(
&self,
paginated: Paginated,
tx: Transactional<'_>,
) -> Result<PaginatedResults<DocumentContext>, Error> {
let connection = self.connection(tx);
let pagination = entity::document::Entity::find()
.order_by(entity::document::Column::Id, Desc)
.paginate(&connection, paginated.page_size());

Ok(PaginatedResults {
items: pagination
.fetch_page(paginated.page_number())
.await?
.drain(0..)
.map(|document| (self, document).into())
.collect::<Vec<DocumentContext>>(),
num_items: pagination.num_items().await?,
})
}

pub async fn find_document_by_ubl_params(
&self,
ruc: &str,
document_type: &str,
document_id: &str,
sha256: &str,
tx: Transactional<'_>,
) -> Result<Option<DocumentContext>, Error> {
Ok(entity::document::Entity::find()
.filter(entity::document::Column::Type.eq(document_type))
.filter(entity::document::Column::Identifier.eq(document_id))
.filter(entity::document::Column::SupplierId.eq(ruc))
.filter(entity::document::Column::Sha256.eq(sha256))
.one(&self.connection(tx))
.await?
.map(|document| (self, document).into()))
}

pub async fn persist_document(
&self,
model: &entity::document::Model,
tx: Transactional<'_>,
) -> Result<DocumentContext, Error> {
let entity = entity::document::ActiveModel {
file_id: Set(model.file_id.clone()),
r#type: Set(model.r#type.clone()),
identifier: Set(model.identifier.clone()),
supplier_id: Set(model.supplier_id.clone()),
voided_document_code: Set(model.voided_document_code.clone()),
digest_value: Set(model.digest_value.clone()),
sha256: Set(model.sha256.clone()),
id: Default::default(),
};

let result = entity.insert(&self.connection(tx)).await?;
Ok((self, result).into())
}
}

impl DocumentContext {
pub async fn add_delivery(
&self,
response_wrapper: &SendFileResponseWrapper,
tx: Transactional<'_>,
) -> Result<(), Error> {
let mut entity = match &response_wrapper.response {
SendFileAggregatedResponse::Cdr(crd_base64, cdr) => entity::delivery::ActiveModel {
document_id: Set(self.document.id),
response_cdr_response_code: Set(Some(cdr.response_code.clone())),
response_cdr_description: Set(Some(cdr.description.clone())),
response_cdr_notes: Set(Some(cdr.notes.clone())),
..Default::default()
},
SendFileAggregatedResponse::Ticket(ticket) => entity::delivery::ActiveModel {
document_id: Set(self.document.id),
response_ticket: Set(Some(ticket.clone())),
..Default::default()
},
SendFileAggregatedResponse::Error(error) => entity::delivery::ActiveModel {
document_id: Set(self.document.id),
response_error_code: Set(Some(error.code.clone())),
response_error_message: Set(Some(error.message.clone())),
..Default::default()
},
};

match &response_wrapper.send_file_target {
SendFileTarget::Soap(url, action) => {
entity.target_send_file_url = Set(url.clone());

match action {
SoapFileTargetAction::Bill => {
entity.target_send_file_protocol =
Set(TargetSendFileProtocolAction::SoapBill);
}
SoapFileTargetAction::Summary => {
entity.target_send_file_protocol =
Set(TargetSendFileProtocolAction::SoapSummary);
}
SoapFileTargetAction::Pack => {
entity.target_send_file_protocol =
Set(TargetSendFileProtocolAction::SoapPack);
}
}
}
SendFileTarget::Rest(url, action) => {
entity.target_send_file_url = Set(url.clone());

match action {
RestFileTargetAction::SendDocument => {
entity.target_send_file_protocol =
Set(TargetSendFileProtocolAction::RestSendDocument);
}
}
}
};

match &response_wrapper.verify_ticket_target {
None => {}
Some(verify_ticket_target) => match verify_ticket_target {
VerifyTicketTarget::Soap(url) => {
entity.target_verify_ticket_url = Set(Some(url.clone()));
entity.target_verify_ticket_protocol =
Set(Some(TargetVerifyTicketProtocolAction::SOAP));
}
VerifyTicketTarget::Rest(url) => {
entity.target_verify_ticket_url = Set(Some(url.clone()));
entity.target_verify_ticket_protocol =
Set(Some(TargetVerifyTicketProtocolAction::REST));
}
},
};

let _result = entity.insert(&self.system.connection(tx)).await?;
Ok(())
}
}
3 changes: 1 addition & 2 deletions openubl/api/src/system/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,8 @@ use migration::{Migrator, MigratorTrait};
use crate::db::{ConnectionOrTransaction, Transactional};

pub mod credentials;
pub mod document;
pub mod error;
pub mod project;
pub mod ubl_document;

pub type System = Arc<InnerSystem>;

Expand Down
Loading

0 comments on commit bfc4758

Please sign in to comment.