airlab-lib 0.1.3

airlab backend
Documentation
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
#![allow(clippy::module_inception)]
use crate::ctx::Ctx;
use crate::model::ModelManager;
use crate::model::Result;
use crate::model::clone::{CloneBmc, CloneFilter};
use crate::model::conjugate::{Conjugate, ConjugateBmc, ConjugateFilter};
use crate::model::lot::LotFilter;
use crate::model::member::{Member, MemberBmc, MemberFilter};
use crate::model::protein::ProteinBmc;
use crate::model::species::{Species, SpeciesBmc, SpeciesFilter};
use crate::model::user::{User, UserBmc};
use crate::model::validation::{Validation, ValidationBmc, ValidationFilter};
use crate::model::validation_file::{ValidationFileBmc, ValidationFileFilter};
use crate::model::view_clone::ViewClone;
use crate::model::view_clone::ViewCloneBmc;
use crate::model::view_lot::{ViewLot, ViewLotBmc};
use modql::filter::ListOptions;
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::collections::HashMap;

#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct MinUser {
    id: i32,
    name: String,
    #[serde(rename = "isAdmin")]
    is_admin: bool,
}

#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct MinSpecies {
    id: i32,
    name: String,
}

#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct MinValidationFile {
    id: i32,
    name: String,
}

#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct MinLot {
    id: i32,
    name: String,
}

#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct MinConjugate {
    id: i32,
    #[serde(rename = "tubeNumber")]
    tube_number: i32,
}

#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct MinProtein {
    id: i32,
    name: String,
}

#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct MinClone {
    id: i32,
    name: String,
    protein: MinProtein,
}

#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct MinViewValidation {
    pub id: i32,
    #[serde(rename = "groupId")]
    pub group_id: i32,
    pub application: i32,
    #[serde(rename = "positiveControl")]
    pub positive_control: Option<String>,
    #[serde(rename = "negativeControl")]
    pub negative_control: Option<String>,
    #[serde(rename = "incubationConditions")]
    pub incubation_conditions: Option<String>,
    pub concentration: Option<String>,
    #[serde(rename = "concentrationUnit")]
    pub concentration_unit: Option<String>,
    pub tissue: Option<String>,
    pub fixation: Option<i32>,
    #[serde(rename = "fixationNotes")]
    pub fixation_notes: Option<String>,
    pub notes: Option<String>,
    pub status: i32,
    #[serde(rename = "antigenRetrievalTemperature")]
    pub antigen_retrieval_temperature: Option<String>,
    #[serde(rename = "antigenRetrievalTime")]
    pub antigen_retrieval_time: Option<String>,
    #[serde(rename = "antigenRetrievalType")]
    pub antigen_retrieval_type: Option<String>,
    pub saponin: Option<bool>,
    #[serde(rename = "saponinConcentration")]
    pub saponin_concentration: Option<String>,
    #[serde(rename = "methanolTreatment")]
    pub methanol_treatment: Option<bool>,
    #[serde(rename = "methanolTreatmentConcentration")]
    pub methanol_treatment_concentration: Option<String>,
    #[serde(rename = "surfaceStaining")]
    pub surface_staining: Option<bool>,
    #[serde(rename = "surfaceStainingConcentration")]
    pub surface_staining_concentration: Option<String>,
    #[serde(rename = "createdAt")]
    pub created_at: chrono::DateTime<chrono::Utc>,
    pub clone: MinClone,
    pub lot: Option<MinLot>,
    pub user: MinUser,
    pub species: Option<MinSpecies>,
    pub conjugate: Option<MinConjugate>,
    #[serde(rename = "validationFiles")]
    pub validation_files: Vec<MinValidationFile>,
}

#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct ViewValidation {
    pub id: i32,
    pub tissue: Option<String>,
    pub notes: Option<String>,
    pub clone: ViewClone,
    #[serde(rename = "antigenRetrievalTemperature")]
    pub antigen_retrieval_temperature: Option<String>,
    #[serde(rename = "antigenRetrievalTime")]
    pub antigen_retrieval_time: Option<String>,
    #[serde(rename = "antigenRetrievalType")]
    pub antigen_retrieval_type: Option<String>,
    pub application: i32,
    #[serde(rename = "cloneId")]
    pub clone_id: i32,
    pub concentration: Option<String>,
    #[serde(rename = "concentrationUnit")]
    pub concentration_unit: Option<String>,
    #[serde(rename = "conjugateId")]
    pub conjugate_id: Option<i32>,
    #[serde(rename = "createdAt")]
    pub created_at: chrono::DateTime<chrono::Utc>,
    #[serde(rename = "createdBy")]
    pub created_by: i32,
    pub fixation: Option<i32>,
    #[serde(rename = "fixationNotes")]
    pub fixation_notes: Option<String>,
    #[serde(rename = "incubationConditions")]
    pub incubation_conditions: Option<String>,
    #[serde(rename = "isArchived")]
    pub is_archived: bool,
    #[serde(rename = "lotId")]
    pub lot_id: Option<i32>,
    #[serde(rename = "fileId")]
    pub file_id: Option<i32>,
    #[serde(rename = "methanolTreatment")]
    pub methanol_treatment: Option<bool>,
    #[serde(rename = "methanolTreatmentConcentration")]
    pub methanol_treatment_concentration: Option<String>,
    #[serde(rename = "negativeControl")]
    pub negative_control: Option<String>,
    #[serde(rename = "positiveControl")]
    pub positive_control: Option<String>,
    pub saponin: Option<bool>,
    #[serde(rename = "saponinConcentration")]
    pub saponin_concentration: Option<String>,
    #[serde(rename = "speciesId")]
    pub species_id: Option<i32>,
    pub status: i32,
    #[serde(rename = "surfaceStaining")]
    pub surface_staining: Option<bool>,
    #[serde(rename = "surfaceStainingConcentration")]
    pub surface_staining_concentration: Option<String>,
    #[serde(rename = "updatedAt")]
    pub updated_at: chrono::DateTime<chrono::Utc>,
    pub lot: Option<ViewLot>,
    pub conjugate: Option<Conjugate>,
    pub species: Option<Species>,
    pub user: Option<User>,
}

pub struct ViewValidationBmc;

impl ViewValidationBmc {
    pub async fn get_min(
        ctx: &Ctx,
        mm: &ModelManager,
        user_id: i32,
        id: i32,
    ) -> Result<MinViewValidation> {
        let item = ValidationBmc::get(ctx, mm, id).await?;
        let user: User = UserBmc::get(ctx, mm, user_id).await?;
        let clone = CloneBmc::get(ctx, mm, item.clone_id).await?;
        let protein = ProteinBmc::get(ctx, mm, clone.protein_id).await?;
        let species = match clone.species_id {
            Some(sid) => {
                let species = SpeciesBmc::get(ctx, mm, sid).await?;
                Some(MinSpecies {
                    id: species.id,
                    name: species.name,
                })
            }
            None => None,
        };
        let conjugate = match item.conjugate_id {
            Some(cid) => {
                let conj = ConjugateBmc::get(ctx, mm, cid).await?;
                Some(MinConjugate {
                    id: conj.id,
                    tube_number: conj.tube_number,
                })
            }
            None => None,
        };
        let lot = match item.lot_id {
            Some(lid) => {
                let lot = ViewLotBmc::get(ctx, mm, lid).await?;
                Some(MinLot {
                    id: lot.id,
                    name: lot.name,
                })
            }
            None => None,
        };
        let filters: Vec<ValidationFileFilter> =
            serde_json::from_value(json!([{"validation_id": {"$eq": item.id}}])).unwrap_or(vec![]);
        let op = ListOptions {
            limit: Some(10_000),
            ..Default::default()
        };
        let val_files = ValidationFileBmc::list(ctx, mm, Some(filters), Some(op)).await?;
        let validation_files = val_files
            .into_iter()
            .map(|e| MinValidationFile {
                id: e.id,
                name: e.name.unwrap_or_default(),
            })
            .collect();
        let ret = MinViewValidation {
            id: item.id,
            group_id: item.group_id,
            tissue: item.tissue,
            notes: item.notes,
            clone: MinClone {
                id: clone.id,
                name: clone.name.clone(),
                protein: MinProtein {
                    id: protein.id,
                    name: protein.name.clone(),
                },
            },
            antigen_retrieval_time: item.antigen_retrieval_time,
            antigen_retrieval_type: item.antigen_retrieval_type,
            antigen_retrieval_temperature: item.antigen_retrieval_temperature,
            application: item.application,
            concentration: item.concentration,
            concentration_unit: item.concentration_unit,
            created_at: item.created_at,
            fixation: item.fixation,
            fixation_notes: item.fixation_notes,
            incubation_conditions: item.incubation_conditions,
            methanol_treatment: item.methanol_treatment,
            methanol_treatment_concentration: item.methanol_treatment_concentration,
            negative_control: item.negative_control,
            positive_control: item.positive_control,
            saponin: item.saponin,
            saponin_concentration: item.saponin_concentration,
            status: item.status,
            surface_staining: item.surface_staining,
            surface_staining_concentration: item.surface_staining_concentration,
            user: MinUser {
                id: user.id,
                name: user.name.clone().unwrap_or_default(),
                is_admin: user.is_admin,
            },
            species,
            conjugate,
            lot,
            validation_files,
        };

        Ok(ret)
    }
    pub async fn get(ctx: &Ctx, mm: &ModelManager, id: i32) -> Result<ViewValidation> {
        let item = ValidationBmc::get(ctx, mm, id).await?;
        let clone = ViewCloneBmc::get(ctx, mm, item.clone_id).await?;
        let species = match clone.species_id {
            Some(sid) => Some(SpeciesBmc::get(ctx, mm, sid).await?),
            None => None,
        };
        let conjugate = match item.conjugate_id {
            Some(cid) => Some(ConjugateBmc::get(ctx, mm, cid).await?),
            None => None,
        };
        let lot = match item.lot_id {
            Some(lid) => Some(ViewLotBmc::get(ctx, mm, lid).await?),
            None => None,
        };
        let ret = ViewValidation {
            id: item.id,
            tissue: item.tissue,
            notes: item.notes,
            clone,
            antigen_retrieval_time: item.antigen_retrieval_time,
            antigen_retrieval_type: item.antigen_retrieval_type,
            antigen_retrieval_temperature: item.antigen_retrieval_temperature,
            application: item.application,
            clone_id: item.clone_id,
            concentration: item.concentration,
            concentration_unit: item.concentration_unit,
            conjugate_id: item.conjugate_id,
            created_at: item.created_at,
            created_by: item.created_by,
            fixation: item.fixation,
            fixation_notes: item.fixation_notes,
            incubation_conditions: item.incubation_conditions,
            is_archived: item.is_archived,
            lot_id: item.lot_id,
            file_id: item.file_id,
            methanol_treatment: item.methanol_treatment,
            methanol_treatment_concentration: item.methanol_treatment_concentration,
            negative_control: item.negative_control,
            positive_control: item.positive_control,
            saponin: item.saponin,
            saponin_concentration: item.saponin_concentration,
            species_id: item.species_id,
            status: item.status,
            surface_staining: item.surface_staining,
            surface_staining_concentration: item.surface_staining_concentration,
            updated_at: item.updated_at,
            user: None,
            species,
            conjugate,
            lot,
        };

        Ok(ret)
    }
    #[allow(clippy::too_many_lines)] // FIXME
    pub async fn list(
        ctx: &Ctx,
        mm: &ModelManager,
        group_id: i32,
        filters: Option<Vec<ValidationFilter>>,
        list_options: Option<ListOptions>,
    ) -> Result<Vec<ViewValidation>> {
        let mut clone_map = HashMap::new();
        let clone_filters: Option<Vec<CloneFilter>> = match serde_json::from_value(json!([
            {
                "group_id": {"$eq":group_id}
            }
        ])) {
            Ok(ok) => Some(ok),
            Err(_) => None,
        };
        let op = ListOptions {
            limit: Some(10_000),
            ..Default::default()
        };
        let clones: Vec<ViewClone> =
            ViewCloneBmc::list(ctx, mm, Some(group_id), clone_filters, Some(op)).await?;
        for clone in clones {
            clone_map.insert(clone.id, clone);
        }

        let mut species_map = HashMap::new();
        let species_filters: Option<Vec<SpeciesFilter>> = match serde_json::from_value(json!([
            {
                "group_id": {"$eq":group_id}
            }
        ])) {
            Ok(ok) => Some(ok),
            Err(_) => None,
        };
        let op = ListOptions {
            limit: Some(10_000),
            ..Default::default()
        };
        let speciess: Vec<Species> = SpeciesBmc::list(ctx, mm, species_filters, Some(op)).await?;
        for species in speciess {
            species_map.insert(species.id, species);
        }

        let mut conjugate_map = HashMap::new();
        let conjugate_filters: Option<Vec<ConjugateFilter>> = match serde_json::from_value(json!([
            {
                "group_id": {"$eq":group_id}
            }
        ])) {
            Ok(ok) => Some(ok),
            Err(_) => None,
        };
        let op = ListOptions {
            limit: Some(10_000),
            ..Default::default()
        };
        let conjugates: Vec<Conjugate> =
            ConjugateBmc::list(ctx, mm, conjugate_filters, Some(op)).await?;
        for conjugate in conjugates {
            conjugate_map.insert(conjugate.id, conjugate);
        }

        let mut lot_map = HashMap::new();
        let mut user_map = HashMap::new();
        let lot_filters: Option<Vec<LotFilter>> = match serde_json::from_value(json!([
            {
                "group_id": {"$eq":group_id}
            }
        ])) {
            Ok(ok) => Some(ok),
            Err(_) => None,
        };
        let op = ListOptions {
            limit: Some(10_000),
            ..Default::default()
        };
        let lots: Vec<ViewLot> =
            ViewLotBmc::list(ctx, mm, Some(group_id), lot_filters, Some(op)).await?;
        for lot in lots {
            lot_map.insert(lot.id, lot);
        }

        let mem_op = ListOptions {
            limit: Some(10_000),
            ..Default::default()
        };
        let mem_filters: Option<Vec<MemberFilter>> =
            match serde_json::from_value(json!([{"group_id": {"$eq": group_id}}])) {
                Ok(o) => Some(o),
                Err(_) => None,
            };
        let members: Vec<Member> = MemberBmc::list(ctx, mm, mem_filters, Some(mem_op)).await?;
        let mem_map: HashMap<i32, i32> = members.iter().map(|e| (e.user_id, e.id)).collect();

        let op = ListOptions {
            limit: Some(10_000),
            ..Default::default()
        };
        let users: Vec<User> = UserBmc::list(ctx, mm, None, Some(op)).await?;
        for user in users {
            let member_id = mem_map.get(&user.id).unwrap_or(&0);
            user_map.insert(*member_id, user);
        }

        let validations: Vec<Validation> =
            ValidationBmc::list(ctx, mm, filters, list_options).await?;
        let mut returns = vec![];
        for item in validations {
            let clone = match clone_map.get(&{ item.clone_id }) {
                Some(v) => v.clone(),
                None => ViewClone::default(),
            };
            let mut species = None;
            if let Some(species_id) = &item.species_id {
                species = species_map.get(species_id).cloned();
            };

            let mut conjugate = None;
            if let Some(conjugate_id) = &item.conjugate_id {
                conjugate = conjugate_map.get(conjugate_id).cloned();
            };

            let mut lot = None;
            if let Some(lot_id) = &item.lot_id {
                lot = lot_map.get(lot_id).cloned();
            };

            let user = match user_map.get(&item.created_by) {
                Some(v) => v.clone(),
                None => User::default(),
            };

            returns.push(ViewValidation {
                id: item.id,
                tissue: item.tissue,
                notes: item.notes,
                clone,
                antigen_retrieval_time: item.antigen_retrieval_time,
                antigen_retrieval_type: item.antigen_retrieval_type,
                antigen_retrieval_temperature: item.antigen_retrieval_temperature,
                application: item.application,
                clone_id: item.clone_id,
                concentration: item.concentration,
                concentration_unit: item.concentration_unit,
                conjugate_id: item.conjugate_id,
                created_at: item.created_at,
                created_by: item.created_by,
                fixation: item.fixation,
                fixation_notes: item.fixation_notes,
                incubation_conditions: item.incubation_conditions,
                is_archived: item.is_archived,
                lot_id: item.lot_id,
                file_id: item.file_id,
                methanol_treatment: item.methanol_treatment,
                methanol_treatment_concentration: item.methanol_treatment_concentration,
                negative_control: item.negative_control,
                positive_control: item.positive_control,
                saponin: item.saponin,
                saponin_concentration: item.saponin_concentration,
                species_id: item.species_id,
                status: item.status,
                surface_staining: item.surface_staining,
                surface_staining_concentration: item.surface_staining_concentration,
                updated_at: item.updated_at,
                user: Some(user),
                species,
                conjugate,
                lot,
            });
        }

        Ok(returns)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use anyhow::Result;

    #[ignore]
    #[tokio::test]
    async fn test_view_validation_list_all_ok() -> Result<()> {
        let mm = ModelManager::new().await?;
        let ctx = Ctx::root_ctx();

        let validations = ViewValidationBmc::list(&ctx, &mm, 1000, None, None).await?;

        let _validations: Vec<ViewValidation> = validations
            .into_iter()
            .filter(|t| {
                t.tissue
                    .as_ref()
                    .unwrap_or(&String::new())
                    .starts_with("test_list_all_ok-validation")
            })
            .collect();

        Ok(())
    }
}