[Broken][BE] Attempt to refactor register creation

This commit is contained in:
Araozu 2023-10-02 22:17:51 -05:00
parent 659f2483fb
commit 9007994fc1
4 changed files with 64 additions and 45 deletions

View File

@ -1,6 +1,9 @@
use rocket::{http::Status, serde::json::Json}; use rocket::{http::Status, serde::json::Json};
use crate::{model::register::{Register, RegisterCreate}, json_result::JsonResult}; use crate::{
json_result::JsonResult,
model::register::{Register, RegisterCreate},
};
#[options("/register/batch")] #[options("/register/batch")]
pub fn options() -> Status { pub fn options() -> Status {
@ -13,17 +16,14 @@ pub fn options_delete(_r: i32) -> Status {
} }
#[post("/register/batch", format = "json", data = "<data>")] #[post("/register/batch", format = "json", data = "<data>")]
pub async fn insert_all(data: Json<Vec<RegisterCreate>>) -> Status { pub async fn insert_all(data: Json<Vec<RegisterCreate>>) -> (Status, Json<JsonResult<()>>) {
for register_create in data.iter() { match RegisterCreate::batch_create(data.0).await {
let res = register_create.create().await; Ok(_) => (Status::Ok, JsonResult::ok(())),
Err(err) => {
if let Err(err) = res { eprintln!("Error creating registers: {}", err);
eprintln!("Error creating register: {}", err); (Status::InternalServerError, JsonResult::err(err))
return Status::InternalServerError;
} }
} }
Status::Ok
} }
#[get("/register/<dni>")] #[get("/register/<dni>")]
@ -35,7 +35,10 @@ pub async fn get_by_dni(dni: i32) -> (Status, Json<JsonResult<Vec<Register>>>) {
Err(err) => { Err(err) => {
eprintln!("{:?}", err); eprintln!("{:?}", err);
(Status::InternalServerError, JsonResult::err(format!("Error recuperando certs de DB"))) (
Status::InternalServerError,
JsonResult::err(format!("Error recuperando certs de DB")),
)
} }
} }
} }

View File

@ -16,30 +16,40 @@ pub struct RegisterCreate {
date: String, date: String,
/// Foreign key to the custom_label table /// Foreign key to the custom_label table
custom_label: String, custom_label: String,
/// Id of the (optional) custom_label. If -1, a new custom_label will be created
/// with the value of self.custom_label
custom_label_id: i32,
is_preview: bool, is_preview: bool,
} }
impl RegisterCreate { impl RegisterCreate {
pub async fn create(&self) -> Result<(), sqlx::Error> { pub async fn batch_create(registers: Vec<RegisterCreate>) -> Result<(), String> {
let db = db(); let mut transaction = match db().begin().await {
Ok(t) => t,
// Get custom_label_id from db based of self.custom_label Err(err) => {
let custom_label_id = { eprintln!("Error starting transaction: {:?}", err);
if self.custom_label.is_empty() { return Err(format!("Error iniciando transaccion."));
1
} else {
// Get custom_label_id from db based of self.custom_label
let id = CustomLabel::get_id_by_value(&self.custom_label).await?;
if id > 0 {
id
} else {
CustomLabel::create(&self.custom_label).await?
}
} }
}; };
let next_register_code = Self::get_next_register_code(self.course_id).await?; for register in registers.iter() {
// Get custom_label_id from db based of self.custom_label
let custom_label_id = {
if register.custom_label_id > 0 {
register.custom_label_id
}
else if register.custom_label.is_empty() {
1
}
else {
// Create a new label
CustomLabel::create(&register.custom_label)
.await
.or_else(|_| Err("Error creando nueva denominacion"))?
}
};
let next_register_code = Self::get_next_register_code(register.course_id).await?;
// Current date in YYYY-MM-DD format // Current date in YYYY-MM-DD format
let current_date = chrono::Local::now().format("%Y-%m-%d").to_string(); let current_date = chrono::Local::now().format("%Y-%m-%d").to_string();
@ -56,14 +66,15 @@ impl RegisterCreate {
) VALUES (?, ?, ?, ?, ?, ?, ?)", ) VALUES (?, ?, ?, ?, ?, ?, ?)",
next_register_code, next_register_code,
current_date, current_date,
self.date, register.date,
custom_label_id, custom_label_id,
self.is_preview, register.is_preview,
self.person_id, register.person_id,
self.course_id register.course_id
) )
.execute(db) .execute(&mut *transaction)
.await?; .await;
}
Ok(()) Ok(())
} }

View File

@ -70,7 +70,7 @@ export function CustomLabelSelect(props: {
ref={inputElement} ref={inputElement}
class={`bg-c-background text-c-on-background border-c-outline class={`bg-c-background text-c-on-background border-c-outline
border-2 rounded-tl rounded-tr px-2 py-1 border-2 rounded-tl rounded-tr px-2 py-1
w-full w-full text-sm
invalid:border-c-error invalid:text-c-error invalid:border-c-error invalid:text-c-error
focus:border-c-primary outline-none focus:border-c-primary outline-none
disabled:opacity-50 disabled:cursor-not-allowed`} disabled:opacity-50 disabled:cursor-not-allowed`}
@ -85,13 +85,13 @@ export function CustomLabelSelect(props: {
<br /> <br />
<div <div
class="border-c-outline border-l-2 border-b-2 border-r-2 class="border-c-outline border-l-2 border-b-2 border-r-2
rounded-bl rounded-br overflow-y-scroll h-[4rem] rounded-bl rounded-br overflow-y-scroll h-[6rem]
absolute w-full" absolute w-full"
> >
<For each={filteredOptions()}> <For each={filteredOptions()}>
{([, label]) => ( {([, label]) => (
<button <button
class="w-full text-left py-1 px-2 class="w-full text-left py-1 px-2 text-sm
hover:bg-c-primary-container hover:text-c-on-primary-container" hover:bg-c-primary-container hover:text-c-on-primary-container"
onclick={(ev) => { onclick={(ev) => {
ev.preventDefault(); ev.preventDefault();

View File

@ -9,6 +9,11 @@ export type RegisterBatchCreate = Array<{
* Value of the custom label * Value of the custom label
*/ */
custom_label: string, custom_label: string,
/**
* Id of the (optional) custom_label. If -1, a new custom_label will be created
* with the value of self.custom_label
*/
custom_label_id: number,
is_preview: boolean, is_preview: boolean,
}> }>