close_duplicate_lead/
close_duplicate_lead.rs1use simpleplatform_sdk::prelude::*;
13
14#[derive(Deserialize, Schema)]
24struct Input {
25 lead_id: String,
27
28 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#[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
87fn 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}