1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
//! `Seed` endpoints.

use actix_web::web::Query;
use actix_web::{
    delete, get, patch, post, put,
    web::{Json, Path},
    HttpResponse, Result,
};
use uuid::Uuid;

use crate::{
    config::{
        auth::user_info::UserInfo,
        data::{SharedBroadcaster, SharedPool},
    },
    model::dto::{
        actions::{Action, ActionType, UpdatePlantingAdditionalNamePayload},
        ArchiveSeedDto, NewSeedDto, PageParameters, SeedSearchParameters,
    },
    service,
};

/// Endpoint for fetching all [`SeedDto`](crate::model::dto::SeedDto).
/// If no page parameters are provided, the first page is returned.
/// Seeds are ordered using their use_by date in an ascending fashion.
///
/// By default, archived seeds will not be returned.
/// This behaviour can be changed using `search_parameters`.
///
/// # Errors
/// * If the connection to the database could not be established.
#[utoipa::path(
    context_path = "/api/seeds",
    params(
        SeedSearchParameters,
        PageParameters
    ),
    responses(
        (status = 200, description = "Fetch all seeds", body = PageSeedDto)
    ),
    security(
        ("oauth2" = [])
    )
)]
#[get("")]
pub async fn find(
    search_query: Query<SeedSearchParameters>,
    page_query: Query<PageParameters>,
    user_info: UserInfo,
    pool: SharedPool,
) -> Result<HttpResponse> {
    let response = service::seed::find(
        search_query.into_inner(),
        page_query.into_inner(),
        user_info.id,
        &pool,
    )
    .await?;
    Ok(HttpResponse::Ok().json(response))
}

/// Endpoint for fetching a [`Seed`](crate::model::entity::Seed).
///
/// # Errors
/// * If the connection to the database could not be established.
#[utoipa::path(
    context_path = "/api/seeds",
    responses(
        (status = 200, description = "Fetch seed by id", body = SeedDto)
    ),
    security(
        ("oauth2" = [])
    )
)]
#[get("/{id}")]
pub async fn find_by_id(
    id: Path<i32>,
    user_info: UserInfo,
    pool: SharedPool,
) -> Result<HttpResponse> {
    let response = service::seed::find_by_id(*id, user_info.id, &pool).await?;
    Ok(HttpResponse::Ok().json(response))
}

/// Endpoint for creating a new [`Seed`](crate::model::entity::Seed).
///
/// # Errors
/// * If the connection to the database could not be established.
#[utoipa::path(
    context_path = "/api/seeds",
    request_body = NewSeedDto,
    responses(
        (status = 201, description = "Create a seed", body = SeedDto)
    ),
    security(
        ("oauth2" = [])
    )
)]
#[post("")]
pub async fn create(
    new_seed_json: Json<NewSeedDto>,
    user_info: UserInfo,
    pool: SharedPool,
) -> Result<HttpResponse> {
    let response = service::seed::create(new_seed_json.0, user_info.id, &pool).await?;
    Ok(HttpResponse::Created().json(response))
}

/// Endpoint for deleting a [`Seed`](crate::model::entity::Seed).
///
/// # Errors
/// * If the connection to the database could not be established.
#[utoipa::path(
    context_path = "/api/seeds",
    responses(
        (status = 200, description = "Delete a seed", body = String)
    ),
    security(
        ("oauth2" = [])
    )
)]
#[delete("/{id}")]
pub async fn delete_by_id(
    path: Path<i32>,
    user_info: UserInfo,
    pool: SharedPool,
) -> Result<HttpResponse> {
    service::seed::delete_by_id(*path, user_info.id, &pool).await?;
    Ok(HttpResponse::Ok().json(""))
}

/// Endpoint for editing a [`Seed`](crate::model::entity::Seed).
///
/// # Errors
/// * If the connection to the database could not be established.
#[put("/{id}")]
pub async fn edit_by_id(
    id: Path<i32>,
    edit_seed_json: Json<NewSeedDto>,
    user_info: UserInfo,
    pool: SharedPool,
    broadcaster: SharedBroadcaster,
) -> Result<HttpResponse> {
    let response = service::seed::edit(*id, user_info.id, edit_seed_json.0, &pool).await?;
    let affected_plantings = service::plantings::find_by_seed_id(*id, &pool);

    for planting in affected_plantings.await? {
        broadcaster
            .broadcast_all_maps(Action {
                action_id: Uuid::new_v4(),
                user_id: user_info.id,
                action: ActionType::UpdatePlantingAdditionalName(
                    UpdatePlantingAdditionalNamePayload::new(
                        &planting,
                        Some(response.name.clone()),
                    ),
                ),
            })
            .await;
    }

    Ok(HttpResponse::Accepted().json(response))
}

/// Endpoint archiving/unarchiving a [`Seed`](crate::model::entity::Seed).
/// A timestamp will be recorded when the seed is first archived.
///
/// # Errors
/// * If the connection to the database could not be established.
#[patch("/{id}/archive")]
pub async fn archive(
    id: Path<i32>,
    archive_seed_json: Json<ArchiveSeedDto>,
    user_info: UserInfo,
    pool: SharedPool,
) -> Result<HttpResponse> {
    let response = service::seed::archive(*id, user_info.id, archive_seed_json.0, &pool).await?;
    Ok(HttpResponse::Accepted().json(response))
}