84 lines
3.3 KiB
Rust
84 lines
3.3 KiB
Rust
use axum::{
|
|
http::StatusCode,
|
|
response::{IntoResponse, Response},
|
|
Json, Router, extract::State,
|
|
routing::post,
|
|
};
|
|
use crate::auth::structs::AppState;
|
|
use sqlx::query_as;
|
|
use crate::company::structs::Company;
|
|
|
|
pub async fn company_routes() -> Router<AppState> {
|
|
let router = Router::new().route("/company", post(update_or_create_company));
|
|
router
|
|
}
|
|
|
|
|
|
pub async fn update_or_create_company(
|
|
State(state): State<AppState>,
|
|
Json(company): Json<Company>,
|
|
) -> Response {
|
|
let result = query_as::<_, Company>(
|
|
"SELECT * FROM company WHERE id = $1",
|
|
)
|
|
.bind(company.id)
|
|
.fetch_optional(&*state.db)
|
|
.await;
|
|
|
|
match result {
|
|
Ok(existing_company) => {
|
|
match existing_company {
|
|
Some(_) => {
|
|
// Update existing company
|
|
let result = sqlx::query(
|
|
"UPDATE company SET active = $2, name = $3, address = $4, town = $5, state = $6, phone = $7, owner_name = $8, owner_phone_number = $9, email = $10, user_id = $11 WHERE id = $1"
|
|
)
|
|
.bind(company.id)
|
|
.bind(company.active)
|
|
.bind(company.name)
|
|
.bind(company.address)
|
|
.bind(company.town)
|
|
.bind(company.state)
|
|
.bind(company.phone)
|
|
.bind(company.owner_name)
|
|
.bind(company.owner_phone_number)
|
|
.bind(company.email)
|
|
.bind(company.user_id)
|
|
.execute(&*state.db)
|
|
.await;
|
|
|
|
match result {
|
|
Ok(_) => (StatusCode::OK, "Company updated successfully".to_string()).into_response(),
|
|
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("Error updating company: {}", e)).into_response(),
|
|
}
|
|
}
|
|
None => {
|
|
// Create new company
|
|
let result = sqlx::query(
|
|
"INSERT INTO company (active, created, name, address, town, state, phone, owner_name, owner_phone_number, email, user_id) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)"
|
|
)
|
|
.bind(company.active)
|
|
.bind(chrono::Utc::now().naive_utc().date())
|
|
.bind(company.name)
|
|
.bind(company.address)
|
|
.bind(company.town)
|
|
.bind(company.state)
|
|
.bind(company.phone)
|
|
.bind(company.owner_name)
|
|
.bind(company.owner_phone_number)
|
|
.bind(company.email)
|
|
.bind(company.user_id)
|
|
.execute(&*state.db)
|
|
.await;
|
|
|
|
match result {
|
|
Ok(_) => (StatusCode::CREATED, "Company created successfully".to_string()).into_response(),
|
|
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("Error creating company: {}", e)).into_response(),
|
|
}
|
|
}
|
|
}
|
|
}
|
|
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("Error checking for existing company: {}", e)).into_response(),
|
|
}
|
|
}
|