1
0
Fork 0
forked from 2sys/shoutdotdev
shoutdotdev/src/projects.rs

85 lines
2.3 KiB
Rust
Raw Normal View History

2025-03-12 23:16:22 -07:00
use anyhow::Result;
2025-02-26 13:10:48 -08:00
use diesel::{
2025-03-12 23:16:22 -07:00
dsl::{auto_type, insert_into, AsSelect, Eq},
2025-02-26 13:10:48 -08:00
pg::Pg,
prelude::*,
};
2025-02-26 13:10:50 -08:00
use uuid::Uuid;
2025-02-26 13:10:45 -08:00
use crate::{
channels::Channel,
schema::{channel_selections, channels, projects},
2025-02-26 13:10:45 -08:00
teams::Team,
};
2025-02-26 13:10:50 -08:00
#[derive(Associations, Clone, Debug, Identifiable, Insertable, Queryable, Selectable)]
2025-02-26 13:10:47 -08:00
#[diesel(table_name = projects)]
2025-02-26 13:10:50 -08:00
#[diesel(belongs_to(Team))]
pub struct Project {
pub id: Uuid,
pub team_id: Uuid,
pub name: String,
}
2025-02-26 13:10:48 -08:00
impl Project {
2025-03-12 23:16:22 -07:00
pub fn insert_new<'a>(
db_conn: &mut diesel::PgConnection,
team_id: &'a Uuid,
name: &'a str,
) -> Result<Self> {
let default_channels = Channel::all()
.filter(Channel::with_team(team_id))
.filter(Channel::where_enabled_by_default())
.load(db_conn)?;
let id: Uuid = Uuid::now_v7();
let project: Self = insert_into(projects::table)
.values((
projects::id.eq(id),
projects::team_id.eq(team_id),
projects::name.eq(name),
))
.get_result(db_conn)?;
for channel in default_channels {
insert_into(channel_selections::table)
.values((
channel_selections::project_id.eq(&project.id),
channel_selections::channel_id.eq(&channel.id),
))
.execute(db_conn)?;
}
Ok(project)
}
2025-02-26 13:10:48 -08:00
#[auto_type(no_type_alias)]
pub fn all() -> _ {
let select: AsSelect<Project, Pg> = Project::as_select();
2025-02-26 13:10:47 -08:00
projects::table.select(select)
}
2025-02-26 13:10:45 -08:00
#[auto_type(no_type_alias)]
pub fn with_id(project_id: Uuid) -> _ {
projects::id.eq(project_id)
}
2025-02-26 13:10:47 -08:00
#[auto_type(no_type_alias)]
pub fn with_team(team_id: Uuid) -> _ {
projects::team_id.eq(team_id)
}
#[auto_type(no_type_alias)]
pub fn with_name(name: String) -> _ {
projects::name.eq(name)
2025-02-26 13:10:48 -08:00
}
2025-02-26 13:10:45 -08:00
#[auto_type(no_type_alias)]
pub fn selected_channels(&self) -> _ {
let select: AsSelect<Channel, Pg> = Channel::as_select();
let project_filter: Eq<channel_selections::project_id, Uuid> =
channel_selections::project_id.eq(self.id);
channels::table
.inner_join(channel_selections::table)
.filter(project_filter)
.select(select)
}
2025-02-26 13:10:48 -08:00
}