db/models/
ticket_messages.rs1use sea_orm::{entity::prelude::*, ActiveValue::Set};
2use serde::{Deserialize, Serialize};
3use chrono::{DateTime, Utc};
4
5#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Deserialize, Serialize)]
6#[sea_orm(table_name = "ticket_messages")]
7pub struct Model {
8 #[sea_orm(primary_key)]
9 pub id: i64,
10
11 pub ticket_id: i64,
12 pub user_id: i64,
13
14 pub content: String,
15
16 pub created_at: DateTime<Utc>,
17 pub updated_at: DateTime<Utc>,
18}
19
20#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
21pub enum Relation {
22 #[sea_orm(
23 belongs_to = "super::tickets::Entity",
24 from = "Column::TicketId",
25 to = "super::tickets::Column::Id"
26 )]
27 Ticket,
28
29 #[sea_orm(
30 belongs_to = "super::user::Entity",
31 from = "Column::UserId",
32 to = "super::user::Column::Id"
33 )]
34 User,
35}
36
37impl Related<super::tickets::Entity> for Entity {
38 fn to() -> RelationDef {
39 Relation::Ticket.def()
40 }
41}
42
43impl Related<super::user::Entity> for Entity {
44 fn to() -> RelationDef {
45 Relation::User.def()
46 }
47}
48
49impl ActiveModelBehavior for ActiveModel {}
50
51impl Model {
52 pub async fn create(
53 db: &DbConn,
54 ticket_id: i64,
55 user_id: i64,
56 content: &str,
57 ) -> Result<Model, DbErr> {
58 let now = Utc::now();
59
60 let active = ActiveModel {
61 ticket_id: Set(ticket_id),
62 user_id: Set(user_id),
63 content: Set(content.to_owned()),
64 created_at: Set(now),
65 updated_at: Set(now),
66 ..Default::default()
67 };
68
69 active.insert(db).await
70 }
71
72 pub async fn update(
73 db: &DbConn,
74 message_id: i64,
75 content: &str,
76 ) -> Result<Model, DbErr> {
77 let now = Utc::now();
78
79 let active = ActiveModel {
80 id: Set(message_id),
81 content: Set(content.to_owned()),
82 updated_at: Set(now),
83 ..Default::default()
84 };
85
86 active.update(db).await
87 }
88
89 pub async fn delete(
90 db: &DbConn,
91 message_id: i64,
92 ) -> Result<(), DbErr> {
93 Entity::delete_by_id(message_id).exec(db).await?;
94 Ok(())
95 }
96
97 pub async fn is_author(message_id: i64, user_id: i64, db: &DbConn) -> bool {
98 let message = Entity::find_by_id(message_id).one(db).await;
99 match message {
100 Ok(Some(t)) => t.user_id == user_id,
101 _ => false,
102 }
103 }
104}