Skip to main content

close_duplicate_lead/
close_duplicate_lead.rs

1//! Close a lead as a duplicate of another one.
2//!
3//! A worked example of the shape most actions have: two GraphQL calls — a read,
4//! then a write — and several ways to refuse before either of them happens.
5//!
6//! Two things to take from it. Reads and writes are separate calls, so a read
7//! goes through `simple::graphql::query` and a write through
8//! `simple::graphql::mutate`. And every refusal is an `Error` with a code, a
9//! `details` object naming what went wrong and a `hint` saying what to do about
10//! it, so the caller can act on the refusal instead of guessing at it.
11
12use simpleplatform_sdk::prelude::*;
13
14/// The advertised input: the lead to close, and the one it duplicates.
15///
16/// No `#[simple(…)]` on either member, because this action asks nothing of
17/// these two strings that the type has not already said. They are required
18/// because they are not `Option<String>`, they are named by `serde`, and they
19/// are described by the doc comments below. A lead id has no shape to write a
20/// `pattern` for and no length to bound, and the one rule that does apply — the
21/// two ids are different — is about the pair rather than either member, so the
22/// handler is where it is checked and where the refusal explains it.
23#[derive(Deserialize, Schema)]
24struct Input {
25    /// The lead to close, by identifier.
26    lead_id: String,
27
28    /// The lead it duplicates, which is the one that survives.
29    duplicate_of: String,
30}
31
32#[derive(Deserialize)]
33struct Lead {
34    id: String,
35    status: String,
36    email: Option<String>,
37}
38
39#[derive(Deserialize)]
40struct Found {
41    leads: Vec<Lead>,
42}
43
44#[derive(Deserialize)]
45struct Closed {
46    result: Affected,
47}
48
49#[derive(Deserialize)]
50struct Affected {
51    affected_rows: i64,
52}
53
54// The output type needs `Serialize`, and that is all the SDK asks of it.
55// `Debug` is here for the tests below, where `Result::unwrap_err` wants the
56// `Ok` type to carry it.
57#[derive(Debug, Serialize)]
58struct Output {
59    closed: String,
60    merged_into: String,
61    rows_changed: i64,
62}
63
64const FIND_LEADS: &str = r#"
65    query FindLeads($ids: [ID!]!) {
66      leads: crm__lead(where: {id: {_in: $ids}}, limit: 2) {
67        id
68        status
69        email
70      }
71    }"#;
72
73const CLOSE_LEAD: &str = r#"
74    mutation CloseLead($id: ID!, $merged: ID!) {
75      result: update_crm__lead(
76        where: {id: {_eq: $id}}
77        _set: {status: "closed", merged_into: $merged}
78      ) {
79        affected_rows
80      }
81    }"#;
82
83fn main() {
84    simple::run(handler)
85}
86
87/// Close a duplicate lead and point it at the record that survives.
88///
89/// The surviving lead keeps its activity; the duplicate is marked closed and
90/// linked to it, so a later report still reaches both. Both leads have to
91/// exist and to carry the same email address before anything is written, and a
92/// lead that is already closed is left as it is.
93///
94/// @tool
95/// @shortdesc Close a duplicate lead, pointing it at the surviving record.
96/// @usewhen A lead is a duplicate of one already in the system.
97/// @usewhen Two leads share a contact and one should be retired.
98fn handler(request: Request<Input>) -> Result<Output, Error> {
99    let duplicate = request.data.lead_id.trim();
100    let survivor = request.data.duplicate_of.trim();
101
102    if duplicate == survivor {
103        return Err(Error::invalid("A lead cannot be a duplicate of itself.")
104            .hint("Pass two different lead ids."));
105    }
106
107    let found: Found = simple::graphql::query(FIND_LEADS, json!({ "ids": [duplicate, survivor] }))?;
108
109    let duplicate_lead = found
110        .leads
111        .iter()
112        .find(|lead| lead.id == duplicate)
113        .ok_or_else(|| {
114            Error::invalid(format!("Lead {duplicate} does not exist."))
115                .details(json!({ "missing": duplicate }))
116                .hint("Search for the lead before closing it.")
117        })?;
118
119    let survivor_lead = found
120        .leads
121        .iter()
122        .find(|lead| lead.id == survivor)
123        .ok_or_else(|| {
124            Error::invalid(format!("Lead {survivor} does not exist."))
125                .details(json!({ "missing": survivor }))
126                .hint("Search for the lead before merging into it.")
127        })?;
128
129    if duplicate_lead.status == "closed" {
130        return Err(Error::domain(
131            "LEAD_ALREADY_CLOSED",
132            format!("Lead {duplicate} is already closed."),
133        )
134        .hint("Nothing to do."));
135    }
136
137    if duplicate_lead.email != survivor_lead.email {
138        return Err(Error::domain(
139            "LEAD_EMAIL_MISMATCH",
140            "The two leads do not share an email address.",
141        )
142        .details(json!({
143            "duplicate": duplicate_lead.email,
144            "survivor": survivor_lead.email,
145        }))
146        .hint("Confirm these are the same person before merging them."));
147    }
148
149    let closed: Closed =
150        simple::graphql::mutate(CLOSE_LEAD, json!({ "id": duplicate, "merged": survivor }))?;
151
152    Ok(Output {
153        closed: duplicate.to_string(),
154        merged_into: survivor.to_string(),
155        rows_changed: closed.result.affected_rows,
156    })
157}
158
159#[cfg(test)]
160mod tests {
161    use simpleplatform_sdk::testing;
162
163    use super::*;
164
165    fn input(lead_id: &str, duplicate_of: &str) -> Request<Input> {
166        Request::new(Input {
167            lead_id: lead_id.to_string(),
168            duplicate_of: duplicate_of.to_string(),
169        })
170    }
171
172    fn two_leads() -> Value {
173        json!({
174            "leads": [
175                { "id": "LEAD1", "status": "open", "email": "a@example.com" },
176                { "id": "LEAD2", "status": "open", "email": "a@example.com" }
177            ]
178        })
179    }
180
181    #[test]
182    fn it_closes_the_duplicate_and_reports_what_changed() {
183        let session = testing::install(|_name, params| {
184            if params["query"].as_str().unwrap().contains("mutation") {
185                Ok(json!({ "result": { "affected_rows": 1 } }))
186            } else {
187                Ok(two_leads())
188            }
189        });
190
191        let output = handler(input("LEAD1", "LEAD2")).unwrap();
192
193        assert_eq!(output.closed, "LEAD1");
194        assert_eq!(output.rows_changed, 1);
195        assert_eq!(session.calls().len(), 2);
196    }
197
198    #[test]
199    fn a_lead_that_is_its_own_duplicate_is_refused_before_any_read() {
200        let session = testing::install(|_name, _params| Ok(json!(null)));
201
202        let error = handler(input("LEAD1", "LEAD1")).unwrap_err();
203
204        assert_eq!(error.code().as_str(), "INVALID_TOOL_INPUT");
205        assert!(session.calls().is_empty());
206    }
207
208    #[test]
209    fn a_mismatched_email_stops_the_write() {
210        let session = testing::install(|_name, _params| {
211            Ok(json!({
212                "leads": [
213                    { "id": "LEAD1", "status": "open", "email": "a@example.com" },
214                    { "id": "LEAD2", "status": "open", "email": "b@example.com" }
215                ]
216            }))
217        });
218
219        let error = handler(input("LEAD1", "LEAD2")).unwrap_err();
220
221        assert_eq!(error.code().as_str(), "LEAD_EMAIL_MISMATCH");
222        assert_eq!(session.calls().len(), 1, "nothing was written");
223    }
224
225    #[test]
226    fn a_write_the_host_refused_says_the_effect_is_unknown() {
227        let _session = testing::install(|_name, params| {
228            if params["query"].as_str().unwrap().contains("mutation") {
229                Err(Error::failed("deadlock detected"))
230            } else {
231                Ok(two_leads())
232            }
233        });
234
235        let error = handler(input("LEAD1", "LEAD2")).unwrap_err();
236
237        assert_eq!(error.code().as_str(), "MUTATION_EXECUTION_FAILED");
238    }
239
240    #[test]
241    fn the_whole_run_reports_one_envelope_the_platform_can_read() {
242        let session = testing::install(|_name, _params| Ok(json!(null)))
243            .with_request(json!({ "lead_id": "LEAD1", "duplicate_of": "LEAD1" }));
244
245        simple::run(handler);
246
247        let done = session.done().unwrap();
248
249        assert_eq!(done["ok"], json!(true));
250        assert_eq!(
251            done["data"]["error"]["extensions"]["retryable"],
252            json!(false)
253        );
254    }
255}