Skip to main content

brep_plm/
sourcing.rs

1//! Sourcing: who makes a part and who sells it.
2//!
3//! Two lists of companies.
4//!
5//! Sourcing is PART-level, like catalog attributes, and it is deliberately
6//! not frozen by [`crate::model::Settings::lock_released_attributes`]: a
7//! released design does not stop the market moving, and a buyer adding a
8//! second source must not need an engineer to open a revision.
9//!
10//! Every write takes a JSON object and MERGES it, so the page, a script and a
11//! future importer all speak the same shape. A company may be named by its id
12//! or its name.
13
14use serde_json::{json, Map, Value};
15
16use crate::auth;
17use crate::db::{now, Db, State};
18use crate::model::{Company, ManufacturerPart, Part, PriceBreak, SourcingStatus, SupplierOffer};
19use crate::Error;
20
21/// Which list of companies a call is about.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum Companies {
24    Manufacturers,
25    Suppliers,
26}
27
28impl Companies {
29    /// "manufacturer" / "supplier", for messages.
30    pub fn one(self) -> &'static str {
31        match self {
32            Companies::Manufacturers => "manufacturer",
33            Companies::Suppliers => "supplier",
34        }
35    }
36
37    pub fn list(self, state: &State) -> &Vec<Company> {
38        match self {
39            Companies::Manufacturers => &state.manufacturers,
40            Companies::Suppliers => &state.suppliers,
41        }
42    }
43
44    fn list_mut(self, state: &mut State) -> &mut Vec<Company> {
45        match self {
46            Companies::Manufacturers => &mut state.manufacturers,
47            Companies::Suppliers => &mut state.suppliers,
48        }
49    }
50}
51
52/// The company `key` names in `list` — by id, or else by name without regard
53/// to ASCII case.
54pub fn find_company<'a>(list: &'a [Company], key: &str) -> Option<&'a Company> {
55    let key = key.trim();
56    list.iter()
57        .find(|c| c.id == key)
58        .or_else(|| list.iter().find(|c| c.name.eq_ignore_ascii_case(key)))
59}
60
61/// How many manufacturer parts (for a manufacturer) or offers (for a
62/// supplier) name `id`, across every part.
63pub fn uses(state: &State, which: Companies, id: &str) -> usize {
64    state
65        .parts
66        .iter()
67        .flat_map(|p| p.sourcing.iter())
68        .map(|mp| match which {
69            Companies::Manufacturers => usize::from(mp.manufacturer == id),
70            Companies::Suppliers => mp.offers.iter().filter(|o| o.supplier == id).count(),
71        })
72        .sum()
73}
74
75/// A part's sourcing with every company id resolved to its name — what a
76/// person, and a script, actually want to read.
77pub fn resolved(state: &State, part: &Part) -> Value {
78    let name = |list: &[Company], id: &str| find_company(list, id).map(|c| c.name.clone()).unwrap_or_default();
79    Value::Array(
80        part.sourcing
81            .iter()
82            .map(|mp| {
83                let mut out = serde_json::to_value(mp).unwrap_or(Value::Null);
84                out["manufacturer_name"] = json!(name(&state.manufacturers, &mp.manufacturer));
85                if let Some(offers) = out["offers"].as_array_mut() {
86                    for offer in offers {
87                        let id = offer["supplier"].as_str().unwrap_or_default().to_string();
88                        offer["supplier_name"] = json!(name(&state.suppliers, &id));
89                    }
90                }
91                out
92            })
93            .collect(),
94    )
95}
96
97// ===========================================================================
98// Field parsing — shared by every write
99// ===========================================================================
100
101fn object(fields: &Value) -> Result<&Map<String, Value>, Error> {
102    fields
103        .as_object()
104        .ok_or_else(|| Error::bad_request("the fields to change must be an object"))
105}
106
107fn only(fields: &Map<String, Value>, allowed: &[&str], what: &str) -> Result<(), Error> {
108    for key in fields.keys() {
109        if !allowed.contains(&key.as_str()) {
110            return Err(Error::bad_request(format!(
111                "'{key}' is not a field of a {what} — {}",
112                allowed.join(", ")
113            )));
114        }
115    }
116    Ok(())
117}
118
119fn text(fields: &Map<String, Value>, key: &str) -> Result<Option<String>, Error> {
120    match fields.get(key) {
121        None => Ok(None),
122        Some(Value::Null) => Ok(Some(String::new())),
123        Some(Value::String(s)) => Ok(Some(s.trim().to_string())),
124        Some(Value::Number(n)) => Ok(Some(n.to_string())),
125        Some(_) => Err(Error::bad_request(format!("'{key}' must be text"))),
126    }
127}
128
129/// A whole number ≥ 0, from a number or from form text; `null` or `""` clears.
130fn count(fields: &Map<String, Value>, key: &str) -> Result<Option<Option<u64>>, Error> {
131    let bad = || Error::bad_request(format!("'{key}' must be a whole number of 0 or more"));
132    match fields.get(key) {
133        None => Ok(None),
134        Some(Value::Null) => Ok(Some(None)),
135        Some(Value::String(s)) if s.trim().is_empty() => Ok(Some(None)),
136        Some(Value::String(s)) => s.trim().parse::<u64>().map(|n| Some(Some(n))).map_err(|_| bad()),
137        Some(Value::Number(n)) => n.as_u64().map(|n| Some(Some(n))).ok_or_else(bad),
138        Some(_) => Err(bad()),
139    }
140}
141
142fn flag(fields: &Map<String, Value>, key: &str) -> Result<Option<bool>, Error> {
143    match fields.get(key) {
144        None => Ok(None),
145        Some(Value::Bool(b)) => Ok(Some(*b)),
146        Some(_) => Err(Error::bad_request(format!("'{key}' must be true or false"))),
147    }
148}
149
150fn number(value: &Value) -> Option<f64> {
151    match value {
152        Value::Number(n) => n.as_f64(),
153        Value::String(s) => s.trim().parse().ok(),
154        _ => None,
155    }
156}
157
158/// Price breaks from `[{qty, unit_price}]`: each quantity at least 1, each
159/// price a finite number of 0 or more, no quantity twice; stored ascending.
160fn price_breaks(value: &Value) -> Result<Vec<PriceBreak>, Error> {
161    let items = match value {
162        Value::Null => return Ok(Vec::new()),
163        Value::Array(items) => items,
164        _ => return Err(Error::bad_request("price_breaks must be a list of {qty, unit_price}")),
165    };
166    let mut out: Vec<PriceBreak> = Vec::with_capacity(items.len());
167    for item in items {
168        let qty = number(&item["qty"])
169            .filter(|q| q.fract() == 0.0 && *q >= 1.0)
170            .ok_or_else(|| Error::bad_request(format!("a price break quantity must be a whole number of 1 or more: {item}")))?
171            as u64;
172        let unit_price = number(&item["unit_price"])
173            .filter(|p| p.is_finite() && *p >= 0.0)
174            .ok_or_else(|| Error::bad_request(format!("a unit price must be a number of 0 or more: {item}")))?;
175        if out.iter().any(|b| b.qty == qty) {
176            return Err(Error::bad_request(format!("quantity {qty} has two prices")));
177        }
178        out.push(PriceBreak { qty, unit_price });
179    }
180    out.sort_by_key(|b| b.qty);
181    Ok(out)
182}
183
184fn status(fields: &Map<String, Value>) -> Result<Option<SourcingStatus>, Error> {
185    let Some(value) = text(fields, "status")? else { return Ok(None) };
186    match value.to_ascii_lowercase().as_str() {
187        "" | "active" => Ok(Some(SourcingStatus::Active)),
188        "nrnd" => Ok(Some(SourcingStatus::Nrnd)),
189        "obsolete" => Ok(Some(SourcingStatus::Obsolete)),
190        other => Err(Error::bad_request(format!("'{other}' is not a status — active, nrnd or obsolete"))),
191    }
192}
193
194/// The longest MPN or SPN accepted. Long enough for any real catalogue.
195const MAX_PART_NUMBER: usize = 128;
196
197fn part_number_text(value: &str, what: &str) -> Result<(), Error> {
198    if value.chars().count() > MAX_PART_NUMBER || value.chars().any(char::is_control) {
199        return Err(Error::bad_request(format!(
200            "{what} must be at most {MAX_PART_NUMBER} characters with no control characters"
201        )));
202    }
203    Ok(())
204}
205
206fn part_mut<'a>(state: &'a mut State, part_id: &str) -> Result<&'a mut Part, Error> {
207    let id = state
208        .part_by_id_or_number(part_id)
209        .map(|p| p.id.clone())
210        .ok_or_else(|| Error::not_found("part"))?;
211    Ok(state.parts.get_mut(&id).expect("found above"))
212}
213
214fn company_id(state: &State, which: Companies, key: &str) -> Result<String, Error> {
215    find_company(which.list(state), key)
216        .map(|c| c.id.clone())
217        .ok_or_else(|| Error::bad_request(format!("there is no {} '{}'", which.one(), key.trim())))
218}
219
220// ===========================================================================
221// The store's sourcing operations
222// ===========================================================================
223
224impl Db {
225    // -- companies ---------------------------------------------------------
226
227    /// Add a manufacturer or supplier: `{name, website?, notes?}`.
228    pub fn create_company(&self, which: Companies, fields: &Value) -> Result<Company, Error> {
229        let fields = object(fields)?.clone();
230        only(&fields, &["name", "website", "notes"], which.one())?;
231        self.mutate(move |state| {
232            let mut company = Company {
233                id: auth::new_id(),
234                name: String::new(),
235                website: String::new(),
236                notes: String::new(),
237                created_at: now(),
238            };
239            apply_company(which.list(state), &mut company, &fields)?;
240            which.list_mut(state).push(company.clone());
241            Ok(company)
242        })
243    }
244
245    pub fn update_company(&self, which: Companies, id: &str, fields: &Value) -> Result<Company, Error> {
246        let fields = object(fields)?.clone();
247        only(&fields, &["name", "website", "notes"], which.one())?;
248        let id = id.to_string();
249        self.mutate(move |state| {
250            let list = which.list(state);
251            let index = list
252                .iter()
253                .position(|c| c.id == id)
254                .ok_or_else(|| Error::not_found(which.one()))?;
255            let mut company = list[index].clone();
256            apply_company(list, &mut company, &fields)?;
257            which.list_mut(state)[index] = company.clone();
258            Ok(company)
259        })
260    }
261
262    /// Remove a company that nothing names. One still named by a manufacturer
263    /// part or an offer is refused, with the count: deleting it would leave
264    /// sourcing pointing at nobody.
265    pub fn delete_company(&self, which: Companies, id: &str) -> Result<(), Error> {
266        let id = id.to_string();
267        self.mutate(move |state| {
268            let company = which
269                .list(state)
270                .iter()
271                .find(|c| c.id == id)
272                .cloned()
273                .ok_or_else(|| Error::not_found(which.one()))?;
274            let used = uses(state, which, &id);
275            if used > 0 {
276                let what = match which {
277                    Companies::Manufacturers => "manufacturer part",
278                    Companies::Suppliers => "offer",
279                };
280                return Err(Error::conflict(format!(
281                    "{} is named by {used} {what}{} — remove {} first",
282                    company.name,
283                    if used == 1 { "" } else { "s" },
284                    if used == 1 { "it" } else { "them" },
285                )));
286            }
287            which.list_mut(state).retain(|c| c.id != id);
288            Ok(())
289        })
290    }
291
292    // -- manufacturer parts -------------------------------------------------
293
294    /// Add a manufacturer part to a part:
295    /// `{manufacturer, mpn, status?, preferred?, datasheet?, notes?}`.
296    pub fn add_manufacturer_part(&self, part_id: &str, fields: &Value) -> Result<ManufacturerPart, Error> {
297        let fields = object(fields)?.clone();
298        only(&fields, MP_FIELDS, "manufacturer part")?;
299        let part_id = part_id.to_string();
300        self.mutate(move |state| {
301            let mut mp = ManufacturerPart {
302                id: auth::new_id(),
303                manufacturer: String::new(),
304                mpn: String::new(),
305                status: SourcingStatus::Active,
306                preferred: false,
307                datasheet: String::new(),
308                notes: String::new(),
309                offers: Vec::new(),
310                created_at: now(),
311            };
312            apply_mp(state, &mut mp, &fields)?;
313            let part = part_mut(state, &part_id)?;
314            check_mp_unique(part, &mp)?;
315            if mp.preferred {
316                part.sourcing.iter_mut().for_each(|other| other.preferred = false);
317            }
318            part.sourcing.push(mp.clone());
319            Ok(mp)
320        })
321    }
322
323    pub fn update_manufacturer_part(&self, part_id: &str, mp_id: &str, fields: &Value) -> Result<ManufacturerPart, Error> {
324        let fields = object(fields)?.clone();
325        only(&fields, MP_FIELDS, "manufacturer part")?;
326        let (part_id, mp_id) = (part_id.to_string(), mp_id.to_string());
327        self.mutate(move |state| {
328            let mut mp = find_mp(state, &part_id, &mp_id)?.clone();
329            apply_mp(state, &mut mp, &fields)?;
330            let part = part_mut(state, &part_id)?;
331            check_mp_unique(part, &mp)?;
332            if mp.preferred {
333                part.sourcing.iter_mut().for_each(|other| other.preferred = false);
334            }
335            let slot = part.sourcing.iter_mut().find(|m| m.id == mp_id).expect("found above");
336            *slot = mp.clone();
337            Ok(mp)
338        })
339    }
340
341    /// Remove a manufacturer part and every offer under it.
342    pub fn delete_manufacturer_part(&self, part_id: &str, mp_id: &str) -> Result<(), Error> {
343        let (part_id, mp_id) = (part_id.to_string(), mp_id.to_string());
344        self.mutate(move |state| {
345            find_mp(state, &part_id, &mp_id)?;
346            part_mut(state, &part_id)?.sourcing.retain(|m| m.id != mp_id);
347            Ok(())
348        })
349    }
350
351    // -- supplier offers ----------------------------------------------------
352
353    /// Add a supplier's offer to a manufacturer part:
354    /// `{supplier, spn?, url?, currency?, price_breaks?, lead_time_days?, moq?, stock?, notes?}`.
355    pub fn add_offer(&self, part_id: &str, mp_id: &str, fields: &Value) -> Result<SupplierOffer, Error> {
356        let fields = object(fields)?.clone();
357        only(&fields, OFFER_FIELDS, "supplier offer")?;
358        let (part_id, mp_id) = (part_id.to_string(), mp_id.to_string());
359        self.mutate(move |state| {
360            find_mp(state, &part_id, &mp_id)?;
361            let mut offer = SupplierOffer {
362                id: auth::new_id(),
363                supplier: String::new(),
364                spn: String::new(),
365                url: String::new(),
366                currency: String::new(),
367                price_breaks: Vec::new(),
368                lead_time_days: None,
369                moq: None,
370                stock: None,
371                notes: String::new(),
372                updated_at: now(),
373            };
374            apply_offer(state, &mut offer, &fields)?;
375            let part = part_mut(state, &part_id)?;
376            let mp = part.sourcing.iter_mut().find(|m| m.id == mp_id).expect("found above");
377            mp.offers.push(offer.clone());
378            Ok(offer)
379        })
380    }
381
382    pub fn update_offer(&self, part_id: &str, mp_id: &str, offer_id: &str, fields: &Value) -> Result<SupplierOffer, Error> {
383        let fields = object(fields)?.clone();
384        only(&fields, OFFER_FIELDS, "supplier offer")?;
385        let (part_id, mp_id, offer_id) = (part_id.to_string(), mp_id.to_string(), offer_id.to_string());
386        self.mutate(move |state| {
387            let mut offer = find_mp(state, &part_id, &mp_id)?
388                .offers
389                .iter()
390                .find(|o| o.id == offer_id)
391                .cloned()
392                .ok_or_else(|| Error::not_found("offer"))?;
393            apply_offer(state, &mut offer, &fields)?;
394            offer.updated_at = now();
395            let part = part_mut(state, &part_id)?;
396            let mp = part.sourcing.iter_mut().find(|m| m.id == mp_id).expect("found above");
397            let slot = mp.offers.iter_mut().find(|o| o.id == offer_id).expect("found above");
398            *slot = offer.clone();
399            Ok(offer)
400        })
401    }
402
403    pub fn delete_offer(&self, part_id: &str, mp_id: &str, offer_id: &str) -> Result<(), Error> {
404        let (part_id, mp_id, offer_id) = (part_id.to_string(), mp_id.to_string(), offer_id.to_string());
405        self.mutate(move |state| {
406            if !find_mp(state, &part_id, &mp_id)?.offers.iter().any(|o| o.id == offer_id) {
407                return Err(Error::not_found("offer"));
408            }
409            let part = part_mut(state, &part_id)?;
410            let mp = part.sourcing.iter_mut().find(|m| m.id == mp_id).expect("found above");
411            mp.offers.retain(|o| o.id != offer_id);
412            Ok(())
413        })
414    }
415}
416
417const MP_FIELDS: &[&str] = &["manufacturer", "mpn", "status", "preferred", "datasheet", "notes"];
418const OFFER_FIELDS: &[&str] =
419    &["supplier", "spn", "url", "currency", "price_breaks", "lead_time_days", "moq", "stock", "notes"];
420
421fn apply_company(list: &[Company], company: &mut Company, fields: &Map<String, Value>) -> Result<(), Error> {
422    if let Some(name) = text(fields, "name")? {
423        company.name = name;
424    }
425    if company.name.is_empty() {
426        return Err(Error::bad_request("a company needs a name"));
427    }
428    if let Some(clash) = list
429        .iter()
430        .find(|c| c.id != company.id && c.name.eq_ignore_ascii_case(&company.name))
431    {
432        return Err(Error::conflict(format!("there is already a company named {}", clash.name)));
433    }
434    if let Some(website) = text(fields, "website")? {
435        company.website = website;
436    }
437    if let Some(notes) = text(fields, "notes")? {
438        company.notes = notes;
439    }
440    Ok(())
441}
442
443fn find_mp<'a>(state: &'a State, part_id: &str, mp_id: &str) -> Result<&'a ManufacturerPart, Error> {
444    state
445        .part_by_id_or_number(part_id)
446        .ok_or_else(|| Error::not_found("part"))?
447        .sourcing
448        .iter()
449        .find(|m| m.id == mp_id)
450        .ok_or_else(|| Error::not_found("manufacturer part"))
451}
452
453fn apply_mp(state: &State, mp: &mut ManufacturerPart, fields: &Map<String, Value>) -> Result<(), Error> {
454    if let Some(key) = text(fields, "manufacturer")? {
455        mp.manufacturer = company_id(state, Companies::Manufacturers, &key)?;
456    }
457    if mp.manufacturer.is_empty() {
458        return Err(Error::bad_request("a manufacturer part needs a manufacturer"));
459    }
460    if let Some(mpn) = text(fields, "mpn")? {
461        mp.mpn = mpn;
462    }
463    if mp.mpn.is_empty() {
464        return Err(Error::bad_request("a manufacturer part needs an MPN"));
465    }
466    part_number_text(&mp.mpn, "an MPN")?;
467    if let Some(status) = status(fields)? {
468        mp.status = status;
469    }
470    if let Some(preferred) = flag(fields, "preferred")? {
471        mp.preferred = preferred;
472    }
473    if let Some(datasheet) = text(fields, "datasheet")? {
474        mp.datasheet = datasheet;
475    }
476    if let Some(notes) = text(fields, "notes")? {
477        mp.notes = notes;
478    }
479    Ok(())
480}
481
482/// One part never lists the same manufacturer's MPN twice. The same MPN on
483/// two DIFFERENT parts is allowed: two internal parts may well approve one
484/// catalogue item, and refusing it would block a legitimate setup.
485fn check_mp_unique(part: &Part, mp: &ManufacturerPart) -> Result<(), Error> {
486    if part
487        .sourcing
488        .iter()
489        .any(|m| m.id != mp.id && m.manufacturer == mp.manufacturer && m.mpn.eq_ignore_ascii_case(&mp.mpn))
490    {
491        return Err(Error::conflict(format!("{} already lists {} from that manufacturer", part.number, mp.mpn)));
492    }
493    Ok(())
494}
495
496fn apply_offer(state: &State, offer: &mut SupplierOffer, fields: &Map<String, Value>) -> Result<(), Error> {
497    if let Some(key) = text(fields, "supplier")? {
498        offer.supplier = company_id(state, Companies::Suppliers, &key)?;
499    }
500    if offer.supplier.is_empty() {
501        return Err(Error::bad_request("an offer needs a supplier"));
502    }
503    if let Some(spn) = text(fields, "spn")? {
504        part_number_text(&spn, "an SPN")?;
505        offer.spn = spn;
506    }
507    if let Some(url) = text(fields, "url")? {
508        offer.url = url;
509    }
510    if let Some(currency) = text(fields, "currency")? {
511        offer.currency = currency.to_ascii_uppercase();
512    }
513    if let Some(value) = fields.get("price_breaks") {
514        offer.price_breaks = price_breaks(value)?;
515    }
516    if let Some(days) = count(fields, "lead_time_days")? {
517        offer.lead_time_days = days
518            .map(|d| u32::try_from(d).map_err(|_| Error::bad_request("lead_time_days is too large")))
519            .transpose()?;
520    }
521    if let Some(moq) = count(fields, "moq")? {
522        offer.moq = moq;
523    }
524    if let Some(stock) = count(fields, "stock")? {
525        offer.stock = stock;
526    }
527    if let Some(notes) = text(fields, "notes")? {
528        offer.notes = notes;
529    }
530    Ok(())
531}