1use jmap_tasks_types::Task;
7use jmap_types::{Id, Invocation, JmapError, PatchObject};
8use serde::Deserialize;
9use serde_json::{json, Value};
10
11use crate::backend::{BackendSetError, TasksBackend};
12use crate::helpers::{extract_account_id, finalize_set_response, set_error_value, SetAccumulators};
13
14pub async fn handle_task_get<B: TasksBackend>(
25 backend: &B,
26 caller: &B::CallerCtx,
27 args: Value,
28) -> Result<(Value, Vec<Invocation>), JmapError> {
29 let want_utc = match args.get("properties") {
31 None | Some(Value::Null) => true, Some(Value::Array(props)) => props.iter().any(|p| {
33 p.as_str()
34 .map(|s| s == "utcStart" || s == "utcDue")
35 .unwrap_or(false)
36 }),
37 _ => false,
38 };
39
40 let (mut response, tail) =
42 jmap_server::handlers::handle_get::<Task, B>(backend, caller, args).await?;
43
44 if want_utc {
46 if let Some(Value::Array(list)) = response.get_mut("list") {
47 for item in list.iter_mut() {
48 if let Ok(task) = Task::deserialize(&*item) {
49 let (utc_start, utc_due) = backend.compute_task_utc_times(&task, None);
50 if let Some(s) = utc_start {
51 item["utcStart"] = Value::String(s.into_inner());
52 }
53 if let Some(d) = utc_due {
54 item["utcDue"] = Value::String(d.into_inner());
55 }
56 }
57 }
58 }
59 }
60
61 Ok((response, tail))
62}
63
64pub async fn handle_task_changes<B: TasksBackend>(
70 backend: &B,
71 caller: &B::CallerCtx,
72 args: Value,
73) -> Result<(Value, Vec<Invocation>), JmapError> {
74 jmap_server::handlers::handle_changes::<Task, B>(backend, caller, args).await
75}
76
77pub async fn handle_task_set<B: TasksBackend>(
94 backend: &B,
95 caller: &B::CallerCtx,
96 args: Value,
97) -> Result<(Value, Vec<Invocation>), JmapError> {
98 let (account_id, mut args) = extract_account_id(args)?;
99
100 if !backend
104 .account_exists(caller, &account_id)
105 .await
106 .map_err(|e| JmapError::server_fail(e.to_string()))?
107 {
108 return Err(JmapError::account_not_found());
109 }
110
111 let old_state = backend
112 .get_state::<Task>(caller, &account_id)
113 .await
114 .map_err(|e| JmapError::server_fail(e.to_string()))?;
115
116 if let Some(if_in_state) = args.get("ifInState").and_then(|v| v.as_str()) {
117 if if_in_state != old_state.as_ref() {
118 return Err(JmapError::state_mismatch());
119 }
120 }
121
122 let mut created = serde_json::Map::new();
123 let mut not_created = serde_json::Map::new();
124 let mut updated = serde_json::Map::new();
125 let mut not_updated = serde_json::Map::new();
126 let mut destroyed_list: Vec<Value> = Vec::new();
127 let mut not_destroyed = serde_json::Map::new();
128 let mut mutated = false;
129
130 if let Some(Value::Object(create_map)) = args.remove("create") {
134 for (create_id, obj_val) in create_map {
135 if obj_val.get("id").is_some() {
142 not_created.insert(
143 create_id,
144 json!({"type": "invalidProperties", "properties": ["id"]}),
145 );
146 continue;
147 }
148 let obj_with_id = match obj_val {
149 Value::Object(mut m) => {
150 m.entry("id")
151 .or_insert_with(|| Value::String("placeholder".to_owned()));
152 Value::Object(m)
153 }
154 other => other,
155 };
156
157 let task: Task = match serde_json::from_value(obj_with_id) {
158 Ok(t) => t,
159 Err(e) => {
160 not_created.insert(
161 create_id,
162 json!({ "type": "invalidProperties", "description": e.to_string() }),
163 );
164 continue;
165 }
166 };
167
168 match backend
169 .create_object::<Task>(caller, &account_id, &create_id, task)
170 .await
171 {
172 Ok((_new_id, created_obj)) => {
173 mutated = true;
174 created.insert(
175 create_id,
176 serde_json::to_value(&created_obj)
177 .expect("derive(Serialize) on plain data is infallible"),
178 );
179 }
180 Err(BackendSetError::SetError(set_err)) => {
181 not_created.insert(create_id, set_error_value(&set_err));
182 }
183 Err(BackendSetError::Other(e)) => {
184 not_created.insert(
185 create_id,
186 json!({ "type": "serverFail", "description": e.to_string() }),
187 );
188 }
189 Err(_) => {
190 not_created.insert(
191 create_id,
192 json!({
193 "type": "serverFail",
194 "description": "unhandled backend error variant",
195 }),
196 );
197 }
198 }
199 }
200 }
201
202 if let Some(Value::Object(update_map)) = args.remove("update") {
206 for (id_str, patch_val) in update_map {
207 if patch_val.get("isDraft").and_then(|v| v.as_bool()) == Some(true)
217 && !backend.enforce_is_draft_atomically()
218 {
219 let task_id = Id::from(id_str.as_str());
220 match backend
221 .get_objects::<Task>(caller, &account_id, Some(&[task_id]), None)
222 .await
223 {
224 Ok((tasks, _)) => {
225 if tasks.first().and_then(|t| t.is_draft) == Some(false) {
226 not_updated.insert(
228 id_str,
229 json!({
230 "type": "invalidProperties",
231 "properties": ["isDraft"]
232 }),
233 );
234 continue;
235 }
236 }
239 Err(e) => {
240 not_updated.insert(
241 id_str,
242 json!({ "type": "serverFail", "description": e.to_string() }),
243 );
244 continue;
245 }
246 }
247 }
248
249 let id = Id::from(id_str.as_str());
250
251 let is_per_user_only = patch_val
255 .as_object()
256 .map(|m| {
257 m.iter()
258 .all(|(k, v)| v.is_null() || B::is_per_user_property(k))
259 })
260 .unwrap_or(false);
261
262 let patch = match serde_json::from_value::<PatchObject>(patch_val) {
268 Ok(p) => p,
269 Err(e) => {
270 not_updated.insert(
271 id_str,
272 json!({ "type": "invalidPatch", "description": e.to_string() }),
273 );
274 continue;
275 }
276 };
277
278 let update_result = if is_per_user_only {
279 backend
280 .update_task_per_user(caller, &account_id, &id, patch)
281 .await
282 } else {
283 backend
284 .update_object::<Task>(caller, &account_id, &id, patch)
285 .await
286 };
287
288 match update_result {
289 Ok(Some(obj)) => {
290 mutated = true;
291 updated.insert(
292 id_str,
293 serde_json::to_value(&obj)
294 .expect("derive(Serialize) on plain data is infallible"),
295 );
296 }
297 Ok(None) => {
298 mutated = true;
299 updated.insert(id_str, Value::Null);
300 }
301 Err(BackendSetError::SetError(set_err)) => {
302 not_updated.insert(id_str, set_error_value(&set_err));
303 }
304 Err(BackendSetError::Other(e)) => {
305 not_updated.insert(
306 id_str,
307 json!({ "type": "serverFail", "description": e.to_string() }),
308 );
309 }
310 Err(_) => {
311 not_updated.insert(
312 id_str,
313 json!({
314 "type": "serverFail",
315 "description": "unhandled backend error variant",
316 }),
317 );
318 }
319 }
320 }
321 }
322
323 if let Some(Value::Array(destroy_arr)) = args.remove("destroy") {
327 if let Some(bad) = destroy_arr.iter().find(|v| !v.is_string()) {
331 return Err(JmapError::invalid_arguments(format!(
332 "destroy: every element must be a string Id; got {bad}"
333 )));
334 }
335 for id_val in destroy_arr {
336 let id_str = match id_val.as_str() {
337 Some(s) => s.to_owned(),
338 None => continue, };
340 let id = Id::from(id_str.as_str());
341
342 match backend
343 .destroy_object::<Task>(caller, &account_id, &id)
344 .await
345 {
346 Ok(()) => {
347 mutated = true;
348 destroyed_list.push(Value::String(id_str));
349 }
350 Err(BackendSetError::SetError(set_err)) => {
351 not_destroyed.insert(id_str, set_error_value(&set_err));
352 }
353 Err(BackendSetError::Other(e)) => {
354 not_destroyed.insert(
355 id_str,
356 json!({ "type": "serverFail", "description": e.to_string() }),
357 );
358 }
359 Err(_) => {
360 not_destroyed.insert(
361 id_str,
362 json!({
363 "type": "serverFail",
364 "description": "unhandled backend error variant",
365 }),
366 );
367 }
368 }
369 }
370 }
371
372 finalize_set_response::<B, Task>(
373 backend,
374 caller,
375 &account_id,
376 old_state,
377 mutated,
378 SetAccumulators {
379 created,
380 updated,
381 destroyed: destroyed_list,
382 not_created,
383 not_updated,
384 not_destroyed,
385 },
386 )
387 .await
388}
389
390pub async fn handle_task_copy<B: TasksBackend>(
400 backend: &B,
401 caller: &B::CallerCtx,
402 args: Value,
403) -> Result<(Value, Vec<Invocation>), JmapError> {
404 let (to_account_id, mut args) = extract_account_id(args)?;
405
406 let from_account_id_str = args
407 .remove("fromAccountId")
408 .and_then(|v| v.as_str().map(|s| s.to_owned()))
409 .ok_or_else(|| JmapError::invalid_arguments("fromAccountId is required"))?;
410 let from_account_id = Id::from(from_account_id_str.as_str());
411
412 if !backend
413 .account_exists(caller, &to_account_id)
414 .await
415 .map_err(|e| JmapError::server_fail(e.to_string()))?
416 {
417 return Err(JmapError::account_not_found());
418 }
419
420 let old_state = backend
421 .get_state::<Task>(caller, &to_account_id)
422 .await
423 .map_err(|e| JmapError::server_fail(e.to_string()))?;
424
425 let mut created = serde_json::Map::new();
426 let mut not_created = serde_json::Map::new();
427 let mut mutated = false;
428
429 if let Some(Value::Object(create_map)) = args.remove("create") {
430 for (create_id, obj_val) in create_map {
431 let obj_with_id = match obj_val {
432 Value::Object(mut m) => {
433 m.entry("id")
434 .or_insert_with(|| Value::String("placeholder".to_owned()));
435 Value::Object(m)
436 }
437 other => other,
438 };
439
440 let task: Task = match serde_json::from_value(obj_with_id) {
441 Ok(t) => t,
442 Err(e) => {
443 not_created.insert(
444 create_id,
445 json!({ "type": "invalidProperties", "description": e.to_string() }),
446 );
447 continue;
448 }
449 };
450
451 match backend
452 .copy_task(caller, &from_account_id, &to_account_id, task)
453 .await
454 {
455 Ok((_new_id, copied_task)) => {
456 mutated = true;
457 created.insert(
458 create_id,
459 serde_json::to_value(&copied_task)
460 .expect("derive(Serialize) on plain data is infallible"),
461 );
462 }
463 Err(BackendSetError::SetError(set_err)) => {
464 not_created.insert(create_id, set_error_value(&set_err));
465 }
466 Err(BackendSetError::Other(e)) => {
467 not_created.insert(
468 create_id,
469 json!({ "type": "serverFail", "description": e.to_string() }),
470 );
471 }
472 Err(_) => {
473 not_created.insert(
474 create_id,
475 json!({
476 "type": "serverFail",
477 "description": "unhandled backend error variant",
478 }),
479 );
480 }
481 }
482 }
483 }
484
485 let new_state = if mutated {
486 backend
487 .get_state::<Task>(caller, &to_account_id)
488 .await
489 .map_err(|e| JmapError::server_fail(e.to_string()))?
490 } else {
491 old_state.clone()
492 };
493
494 Ok((
495 json!({
496 "fromAccountId": from_account_id.as_ref(),
497 "accountId": to_account_id.as_ref(),
498 "oldState": old_state.as_ref(),
499 "newState": new_state.as_ref(),
500 "created": if created.is_empty() { Value::Null } else { Value::Object(created) },
501 "notCreated": if not_created.is_empty() { Value::Null } else { Value::Object(not_created) },
502 }),
503 vec![],
504 ))
505}
506
507pub async fn handle_task_query<B: TasksBackend>(
513 backend: &B,
514 caller: &B::CallerCtx,
515 args: Value,
516) -> Result<(Value, Vec<Invocation>), JmapError> {
517 jmap_server::handlers::handle_query::<Task, B>(backend, caller, args).await
518}
519
520pub async fn handle_task_query_changes<B: TasksBackend>(
526 backend: &B,
527 caller: &B::CallerCtx,
528 args: Value,
529) -> Result<(Value, Vec<Invocation>), JmapError> {
530 jmap_server::handlers::handle_query_changes::<Task, B>(backend, caller, args).await
531}
532
533#[cfg(test)]
538mod tests {
539 use super::*;
540 use serde_json::json;
541
542 use crate::test_support::MockBackend;
543
544 #[tokio::test]
546 async fn get_unknown_account_returns_account_not_found() {
547 let backend = MockBackend::new();
548 let args = json!({ "accountId": "unknown", "ids": null });
549 let result = handle_task_get(&backend, &(), args).await;
550 let err = result.expect_err("must return error for unknown account");
551 assert_eq!(err.error_type.as_str(), "accountNotFound");
552 }
553
554 #[tokio::test]
556 async fn copy_missing_from_account_id_returns_invalid_arguments() {
557 let backend = MockBackend::new_with_account("acc1");
558 let args = json!({
559 "accountId": "acc1",
560 "create": {}
561 });
562 let result = handle_task_copy(&backend, &(), args).await;
563 let err = result.expect_err("must return error when fromAccountId missing");
564 assert_eq!(err.error_type.as_str(), "invalidArguments");
565 }
566
567 #[tokio::test]
569 async fn set_empty_destroy_returns_valid_response() {
570 let backend = MockBackend::new_with_account("acc1");
571 let args = json!({ "accountId": "acc1", "destroy": [] });
572 let (resp, _) = handle_task_set(&backend, &(), args)
573 .await
574 .expect("must not return top-level error");
575 assert_eq!(resp["accountId"], "acc1");
576 }
577
578 #[tokio::test]
585 async fn set_is_draft_revert_rejected_when_current_is_false() {
586 let mut backend = MockBackend::new_with_account("acc1");
587 backend.seed_task("acc1", "t1", false);
589
590 let args = json!({
591 "accountId": "acc1",
592 "update": {
593 "t1": { "isDraft": true }
594 }
595 });
596 let (resp, _) = handle_task_set(&backend, &(), args)
597 .await
598 .expect("must not return a top-level error");
599
600 let not_updated = resp["notUpdated"]
601 .as_object()
602 .expect("notUpdated must be an object");
603 assert!(
604 not_updated.contains_key("t1"),
605 "t1 must appear in notUpdated: {resp}"
606 );
607 assert_eq!(
608 not_updated["t1"]["type"].as_str(),
609 Some("invalidProperties"),
610 "error type must be invalidProperties"
611 );
612 assert_eq!(
613 not_updated["t1"]["properties"][0].as_str(),
614 Some("isDraft"),
615 "properties must list isDraft"
616 );
617 }
618
619 #[tokio::test]
622 async fn set_is_draft_true_on_draft_task_passes_to_backend() {
623 let mut backend = MockBackend::new_with_account("acc1");
624 backend.seed_task("acc1", "t2", true);
626
627 let args = json!({
628 "accountId": "acc1",
629 "update": {
630 "t2": { "isDraft": true }
631 }
632 });
633 let (resp, _) = handle_task_set(&backend, &(), args)
634 .await
635 .expect("must not return a top-level error");
636
637 if let Some(not_updated) = resp["notUpdated"].as_object() {
641 if let Some(err) = not_updated.get("t2") {
642 assert_ne!(
643 err["type"].as_str(),
644 Some("invalidProperties"),
645 "isDraft:true on an existing draft must not produce invalidProperties"
646 );
647 }
648 }
649 }
650
651 #[tokio::test]
654 async fn set_is_draft_false_passes_to_backend() {
655 let mut backend = MockBackend::new_with_account("acc1");
656 backend.seed_task("acc1", "t3", true);
657
658 let args = json!({
659 "accountId": "acc1",
660 "update": {
661 "t3": { "isDraft": false }
662 }
663 });
664 let (resp, _) = handle_task_set(&backend, &(), args)
665 .await
666 .expect("must not return a top-level error");
667
668 if let Some(not_updated) = resp["notUpdated"].as_object() {
670 if let Some(err) = not_updated.get("t3") {
671 assert_ne!(
672 err["type"].as_str(),
673 Some("invalidProperties"),
674 "isDraft:false must never produce invalidProperties"
675 );
676 }
677 }
678 }
679
680 #[tokio::test]
686 async fn get_without_utc_properties_omits_utc_fields() {
687 let backend = MockBackend::new_with_account("acc1");
688 let args = json!({
689 "accountId": "acc1",
690 "ids": null,
691 "properties": ["id", "title"] });
693 let (resp, _) = handle_task_get(&backend, &(), args)
694 .await
695 .expect("must succeed");
696 assert_eq!(resp["accountId"], "acc1");
698 let list = resp["list"].as_array().expect("list must be an array");
701 for item in list {
702 assert!(
703 item.get("utcStart").is_none(),
704 "utcStart must not appear when not in properties"
705 );
706 }
707 }
708
709 #[tokio::test]
713 async fn get_with_utc_start_in_properties_does_not_error() {
714 let backend = MockBackend::new_with_account("acc1");
715 let args = json!({
716 "accountId": "acc1",
717 "ids": null,
718 "properties": ["id", "utcStart", "utcDue"]
719 });
720 let (resp, _) = handle_task_get(&backend, &(), args)
721 .await
722 .expect("must succeed with utcStart in properties");
723 assert_eq!(resp["accountId"], "acc1");
724 }
725
726 #[tokio::test]
734 async fn set_per_user_only_patch_routes_to_per_user_update() {
735 let backend = MockBackend::new_with_account("acc1");
736 let args = json!({
738 "accountId": "acc1",
739 "update": { "t1": { "color": "#ff0000" } }
740 });
741 let (resp, _) = handle_task_set(&backend, &(), args)
742 .await
743 .expect("must not return top-level error");
744 if let Some(nu) = resp["notUpdated"].as_object() {
748 if let Some(err) = nu.get("t1") {
749 assert_ne!(
750 err["type"].as_str(),
751 Some("invalidProperties"),
752 "per-user-only patch must not produce invalidProperties"
753 );
754 }
755 }
756 }
757
758 #[tokio::test]
763 async fn set_shared_property_patch_routes_to_update_object() {
764 let backend = MockBackend::new_with_account("acc1");
765 let args = json!({
766 "accountId": "acc1",
767 "update": { "t1": { "title": "New title" } }
768 });
769 let (resp, _) = handle_task_set(&backend, &(), args)
770 .await
771 .expect("must not return top-level error");
772 if let Some(nu) = resp["notUpdated"].as_object() {
773 if let Some(err) = nu.get("t1") {
774 assert_ne!(
775 err["type"].as_str(),
776 Some("invalidProperties"),
777 "shared-property patch must not produce invalidProperties"
778 );
779 }
780 }
781 }
782
783 #[tokio::test]
786 async fn set_mixed_patch_routes_to_update_object() {
787 let backend = MockBackend::new_with_account("acc1");
788 let args = json!({
790 "accountId": "acc1",
791 "update": { "t1": { "color": "#ff0000", "title": "New" } }
792 });
793 let (resp, _) = handle_task_set(&backend, &(), args)
794 .await
795 .expect("must not return top-level error");
796 assert_eq!(resp["accountId"], "acc1");
798 }
799
800 #[tokio::test]
811 async fn set_is_draft_revert_rejected_with_prefetch() {
812 let mut backend = MockBackend::new_with_account("acc1");
814 backend.seed_task("acc1", "t1", false); let args = json!({
817 "accountId": "acc1",
818 "update": { "t1": { "isDraft": true } }
819 });
820 let (resp, _) = handle_task_set(&backend, &(), args)
821 .await
822 .expect("must not return top-level error");
823
824 let not_updated = resp["notUpdated"].as_object().expect("notUpdated");
826 assert_eq!(
827 not_updated["t1"]["type"], "invalidProperties",
828 "pre-fetch path must reject isDraft revert: {resp}"
829 );
830 assert_eq!(not_updated["t1"]["properties"][0], "isDraft");
831 }
832}