Skip to main content

brep_plm/api/
sourcing.rs

1//! Sourcing over HTTP: the manufacturer and supplier lists, and a part's
2//! manufacturer parts and offers.
3//!
4//! Who may do what:
5//! - everyone signed in reads;
6//! - the author group adds and edits companies, and edits a part's sourcing —
7//!   a buyer adding a second source is ordinary work, not administration;
8//! - only an administrator deletes a company, and only one nothing names.
9//!
10//! The rules are in [`crate::sourcing`]; these handlers decide who is asking.
11
12use axum::extract::{Path, State};
13use axum::http::HeaderMap;
14use axum::response::Response;
15use axum::Json;
16use serde::Serialize;
17use serde_json::Value;
18
19use super::{ok_seq, require_admin, require_author, require_user, Shared};
20use crate::model::{Company, ManufacturerPart, SupplierOffer};
21use crate::sourcing::{self, Companies};
22use crate::Error;
23
24/// A company as the page lists it, with how much sourcing names it.
25#[derive(Debug, Serialize)]
26pub struct CompanyRow {
27    #[serde(flatten)]
28    pub company: Company,
29    /// Manufacturer parts (for a manufacturer) or offers (for a supplier)
30    /// that name it.
31    pub uses: usize,
32    /// Distinct parts those belong to.
33    pub parts: usize,
34}
35
36fn rows(db: &Shared, which: Companies) -> Vec<CompanyRow> {
37    db.read(|state| {
38        let mut out: Vec<CompanyRow> = which
39            .list(state)
40            .iter()
41            .map(|company| CompanyRow {
42                company: company.clone(),
43                uses: sourcing::uses(state, which, &company.id),
44                parts: state
45                    .parts
46                    .iter()
47                    .filter(|p| {
48                        p.sourcing.iter().any(|mp| match which {
49                            Companies::Manufacturers => mp.manufacturer == company.id,
50                            Companies::Suppliers => mp.offers.iter().any(|o| o.supplier == company.id),
51                        })
52                    })
53                    .count(),
54            })
55            .collect();
56        out.sort_by_key(|row| row.company.name.to_ascii_lowercase());
57        out
58    })
59}
60
61macro_rules! company_routes {
62    ($which:expr, $list:ident, $create:ident, $update:ident, $remove:ident) => {
63        pub async fn $list(State(db): State<Shared>, headers: HeaderMap) -> Result<Json<Vec<CompanyRow>>, Error> {
64            require_user(&db, &headers)?;
65            Ok(Json(rows(&db, $which)))
66        }
67
68        pub async fn $create(
69            State(db): State<Shared>,
70            headers: HeaderMap,
71            Json(body): Json<Value>,
72        ) -> Result<Json<Company>, Error> {
73            require_author(&db, &headers)?;
74            Ok(Json(db.create_company($which, &body)?))
75        }
76
77        pub async fn $update(
78            State(db): State<Shared>,
79            headers: HeaderMap,
80            Path(id): Path<String>,
81            Json(body): Json<Value>,
82        ) -> Result<Json<Company>, Error> {
83            require_author(&db, &headers)?;
84            Ok(Json(db.update_company($which, &id, &body)?))
85        }
86
87        pub async fn $remove(
88            State(db): State<Shared>,
89            headers: HeaderMap,
90            Path(id): Path<String>,
91        ) -> Result<Response, Error> {
92            require_admin(&db, &headers)?;
93            db.delete_company($which, &id)?;
94            Ok(ok_seq(&db))
95        }
96    };
97}
98
99company_routes!(Companies::Manufacturers, list_manufacturers, create_manufacturer, update_manufacturer, delete_manufacturer);
100company_routes!(Companies::Suppliers, list_suppliers, create_supplier, update_supplier, delete_supplier);
101
102/// Only by part id in these paths — a part number in a URL could collide
103/// with an id.
104fn known_part(db: &Shared, id: &str) -> Result<(), Error> {
105    if db.read(|state| state.part(id).is_none()) {
106        return Err(Error::not_found("part"));
107    }
108    Ok(())
109}
110
111pub async fn add_manufacturer_part(
112    State(db): State<Shared>,
113    headers: HeaderMap,
114    Path(part): Path<String>,
115    Json(body): Json<Value>,
116) -> Result<Json<ManufacturerPart>, Error> {
117    require_author(&db, &headers)?;
118    known_part(&db, &part)?;
119    Ok(Json(db.add_manufacturer_part(&part, &body)?))
120}
121
122pub async fn update_manufacturer_part(
123    State(db): State<Shared>,
124    headers: HeaderMap,
125    Path((part, mp)): Path<(String, String)>,
126    Json(body): Json<Value>,
127) -> Result<Json<ManufacturerPart>, Error> {
128    require_author(&db, &headers)?;
129    known_part(&db, &part)?;
130    Ok(Json(db.update_manufacturer_part(&part, &mp, &body)?))
131}
132
133pub async fn delete_manufacturer_part(
134    State(db): State<Shared>,
135    headers: HeaderMap,
136    Path((part, mp)): Path<(String, String)>,
137) -> Result<Response, Error> {
138    require_author(&db, &headers)?;
139    known_part(&db, &part)?;
140    db.delete_manufacturer_part(&part, &mp)?;
141    Ok(ok_seq(&db))
142}
143
144pub async fn add_offer(
145    State(db): State<Shared>,
146    headers: HeaderMap,
147    Path((part, mp)): Path<(String, String)>,
148    Json(body): Json<Value>,
149) -> Result<Json<SupplierOffer>, Error> {
150    require_author(&db, &headers)?;
151    known_part(&db, &part)?;
152    Ok(Json(db.add_offer(&part, &mp, &body)?))
153}
154
155pub async fn update_offer(
156    State(db): State<Shared>,
157    headers: HeaderMap,
158    Path((part, mp, offer)): Path<(String, String, String)>,
159    Json(body): Json<Value>,
160) -> Result<Json<SupplierOffer>, Error> {
161    require_author(&db, &headers)?;
162    known_part(&db, &part)?;
163    Ok(Json(db.update_offer(&part, &mp, &offer, &body)?))
164}
165
166pub async fn delete_offer(
167    State(db): State<Shared>,
168    headers: HeaderMap,
169    Path((part, mp, offer)): Path<(String, String, String)>,
170) -> Result<Response, Error> {
171    require_author(&db, &headers)?;
172    known_part(&db, &part)?;
173    db.delete_offer(&part, &mp, &offer)?;
174    Ok(ok_seq(&db))
175}