use jmap_tasks_types::Task;
use jmap_types::{Id, Invocation, JmapError, PatchObject};
use serde::Deserialize;
use serde_json::{json, Value};
use crate::backend::{BackendSetError, TasksBackend};
use crate::helpers::{extract_account_id, finalize_set_response, set_error_value, SetAccumulators};
pub async fn handle_task_get<B: TasksBackend>(
backend: &B,
caller: &B::CallerCtx,
args: Value,
) -> Result<(Value, Vec<Invocation>), JmapError> {
let want_utc = match args.get("properties") {
None | Some(Value::Null) => true, Some(Value::Array(props)) => props.iter().any(|p| {
p.as_str()
.map(|s| s == "utcStart" || s == "utcDue")
.unwrap_or(false)
}),
_ => false,
};
let (mut response, tail) =
jmap_server::handlers::handle_get::<Task, B>(backend, caller, args).await?;
if want_utc {
if let Some(Value::Array(list)) = response.get_mut("list") {
for item in list.iter_mut() {
if let Ok(task) = Task::deserialize(&*item) {
let (utc_start, utc_due) = backend.compute_task_utc_times(&task, None);
if let Some(s) = utc_start {
item["utcStart"] = Value::String(s.into_inner());
}
if let Some(d) = utc_due {
item["utcDue"] = Value::String(d.into_inner());
}
}
}
}
}
Ok((response, tail))
}
pub async fn handle_task_changes<B: TasksBackend>(
backend: &B,
caller: &B::CallerCtx,
args: Value,
) -> Result<(Value, Vec<Invocation>), JmapError> {
jmap_server::handlers::handle_changes::<Task, B>(backend, caller, args).await
}
pub async fn handle_task_set<B: TasksBackend>(
backend: &B,
caller: &B::CallerCtx,
args: Value,
) -> Result<(Value, Vec<Invocation>), JmapError> {
let (account_id, mut args) = extract_account_id(args)?;
if !backend
.account_exists(caller, &account_id)
.await
.map_err(|e| JmapError::server_fail(e.to_string()))?
{
return Err(JmapError::account_not_found());
}
let old_state = backend
.get_state::<Task>(caller, &account_id)
.await
.map_err(|e| JmapError::server_fail(e.to_string()))?;
if let Some(if_in_state) = args.get("ifInState").and_then(|v| v.as_str()) {
if if_in_state != old_state.as_ref() {
return Err(JmapError::state_mismatch());
}
}
let mut created = serde_json::Map::new();
let mut not_created = serde_json::Map::new();
let mut updated = serde_json::Map::new();
let mut not_updated = serde_json::Map::new();
let mut destroyed_list: Vec<Value> = Vec::new();
let mut not_destroyed = serde_json::Map::new();
let mut mutated = false;
if let Some(Value::Object(create_map)) = args.remove("create") {
for (create_id, obj_val) in create_map {
if obj_val.get("id").is_some() {
not_created.insert(
create_id,
json!({"type": "invalidProperties", "properties": ["id"]}),
);
continue;
}
let obj_with_id = match obj_val {
Value::Object(mut m) => {
m.entry("id")
.or_insert_with(|| Value::String("placeholder".to_owned()));
Value::Object(m)
}
other => other,
};
let task: Task = match serde_json::from_value(obj_with_id) {
Ok(t) => t,
Err(e) => {
not_created.insert(
create_id,
json!({ "type": "invalidProperties", "description": e.to_string() }),
);
continue;
}
};
match backend
.create_object::<Task>(caller, &account_id, &create_id, task)
.await
{
Ok((_new_id, created_obj)) => {
mutated = true;
created.insert(
create_id,
serde_json::to_value(&created_obj)
.expect("derive(Serialize) on plain data is infallible"),
);
}
Err(BackendSetError::SetError(set_err)) => {
not_created.insert(create_id, set_error_value(&set_err));
}
Err(BackendSetError::Other(e)) => {
not_created.insert(
create_id,
json!({ "type": "serverFail", "description": e.to_string() }),
);
}
Err(_) => {
not_created.insert(
create_id,
json!({
"type": "serverFail",
"description": "unhandled backend error variant",
}),
);
}
}
}
}
if let Some(Value::Object(update_map)) = args.remove("update") {
for (id_str, patch_val) in update_map {
if patch_val.get("isDraft").and_then(|v| v.as_bool()) == Some(true)
&& !backend.enforce_is_draft_atomically()
{
let task_id = Id::from(id_str.as_str());
match backend
.get_objects::<Task>(caller, &account_id, Some(&[task_id]), None)
.await
{
Ok((tasks, _)) => {
if tasks.first().and_then(|t| t.is_draft) == Some(false) {
not_updated.insert(
id_str,
json!({
"type": "invalidProperties",
"properties": ["isDraft"]
}),
);
continue;
}
}
Err(e) => {
not_updated.insert(
id_str,
json!({ "type": "serverFail", "description": e.to_string() }),
);
continue;
}
}
}
let id = Id::from(id_str.as_str());
let is_per_user_only = patch_val
.as_object()
.map(|m| {
m.iter()
.all(|(k, v)| v.is_null() || B::is_per_user_property(k))
})
.unwrap_or(false);
let patch = match serde_json::from_value::<PatchObject>(patch_val) {
Ok(p) => p,
Err(e) => {
not_updated.insert(
id_str,
json!({ "type": "invalidPatch", "description": e.to_string() }),
);
continue;
}
};
let update_result = if is_per_user_only {
backend
.update_task_per_user(caller, &account_id, &id, patch)
.await
} else {
backend
.update_object::<Task>(caller, &account_id, &id, patch)
.await
};
match update_result {
Ok(Some(obj)) => {
mutated = true;
updated.insert(
id_str,
serde_json::to_value(&obj)
.expect("derive(Serialize) on plain data is infallible"),
);
}
Ok(None) => {
mutated = true;
updated.insert(id_str, Value::Null);
}
Err(BackendSetError::SetError(set_err)) => {
not_updated.insert(id_str, set_error_value(&set_err));
}
Err(BackendSetError::Other(e)) => {
not_updated.insert(
id_str,
json!({ "type": "serverFail", "description": e.to_string() }),
);
}
Err(_) => {
not_updated.insert(
id_str,
json!({
"type": "serverFail",
"description": "unhandled backend error variant",
}),
);
}
}
}
}
if let Some(Value::Array(destroy_arr)) = args.remove("destroy") {
if let Some(bad) = destroy_arr.iter().find(|v| !v.is_string()) {
return Err(JmapError::invalid_arguments(format!(
"destroy: every element must be a string Id; got {bad}"
)));
}
for id_val in destroy_arr {
let id_str = match id_val.as_str() {
Some(s) => s.to_owned(),
None => continue, };
let id = Id::from(id_str.as_str());
match backend
.destroy_object::<Task>(caller, &account_id, &id)
.await
{
Ok(()) => {
mutated = true;
destroyed_list.push(Value::String(id_str));
}
Err(BackendSetError::SetError(set_err)) => {
not_destroyed.insert(id_str, set_error_value(&set_err));
}
Err(BackendSetError::Other(e)) => {
not_destroyed.insert(
id_str,
json!({ "type": "serverFail", "description": e.to_string() }),
);
}
Err(_) => {
not_destroyed.insert(
id_str,
json!({
"type": "serverFail",
"description": "unhandled backend error variant",
}),
);
}
}
}
}
finalize_set_response::<B, Task>(
backend,
caller,
&account_id,
old_state,
mutated,
SetAccumulators {
created,
updated,
destroyed: destroyed_list,
not_created,
not_updated,
not_destroyed,
},
)
.await
}
pub async fn handle_task_copy<B: TasksBackend>(
backend: &B,
caller: &B::CallerCtx,
args: Value,
) -> Result<(Value, Vec<Invocation>), JmapError> {
let (to_account_id, mut args) = extract_account_id(args)?;
let from_account_id_str = args
.remove("fromAccountId")
.and_then(|v| v.as_str().map(|s| s.to_owned()))
.ok_or_else(|| JmapError::invalid_arguments("fromAccountId is required"))?;
let from_account_id = Id::from(from_account_id_str.as_str());
if !backend
.account_exists(caller, &to_account_id)
.await
.map_err(|e| JmapError::server_fail(e.to_string()))?
{
return Err(JmapError::account_not_found());
}
let old_state = backend
.get_state::<Task>(caller, &to_account_id)
.await
.map_err(|e| JmapError::server_fail(e.to_string()))?;
let mut created = serde_json::Map::new();
let mut not_created = serde_json::Map::new();
let mut mutated = false;
if let Some(Value::Object(create_map)) = args.remove("create") {
for (create_id, obj_val) in create_map {
let obj_with_id = match obj_val {
Value::Object(mut m) => {
m.entry("id")
.or_insert_with(|| Value::String("placeholder".to_owned()));
Value::Object(m)
}
other => other,
};
let task: Task = match serde_json::from_value(obj_with_id) {
Ok(t) => t,
Err(e) => {
not_created.insert(
create_id,
json!({ "type": "invalidProperties", "description": e.to_string() }),
);
continue;
}
};
match backend
.copy_task(caller, &from_account_id, &to_account_id, task)
.await
{
Ok((_new_id, copied_task)) => {
mutated = true;
created.insert(
create_id,
serde_json::to_value(&copied_task)
.expect("derive(Serialize) on plain data is infallible"),
);
}
Err(BackendSetError::SetError(set_err)) => {
not_created.insert(create_id, set_error_value(&set_err));
}
Err(BackendSetError::Other(e)) => {
not_created.insert(
create_id,
json!({ "type": "serverFail", "description": e.to_string() }),
);
}
Err(_) => {
not_created.insert(
create_id,
json!({
"type": "serverFail",
"description": "unhandled backend error variant",
}),
);
}
}
}
}
let new_state = if mutated {
backend
.get_state::<Task>(caller, &to_account_id)
.await
.map_err(|e| JmapError::server_fail(e.to_string()))?
} else {
old_state.clone()
};
Ok((
json!({
"fromAccountId": from_account_id.as_ref(),
"accountId": to_account_id.as_ref(),
"oldState": old_state.as_ref(),
"newState": new_state.as_ref(),
"created": if created.is_empty() { Value::Null } else { Value::Object(created) },
"notCreated": if not_created.is_empty() { Value::Null } else { Value::Object(not_created) },
}),
vec![],
))
}
pub async fn handle_task_query<B: TasksBackend>(
backend: &B,
caller: &B::CallerCtx,
args: Value,
) -> Result<(Value, Vec<Invocation>), JmapError> {
jmap_server::handlers::handle_query::<Task, B>(backend, caller, args).await
}
pub async fn handle_task_query_changes<B: TasksBackend>(
backend: &B,
caller: &B::CallerCtx,
args: Value,
) -> Result<(Value, Vec<Invocation>), JmapError> {
jmap_server::handlers::handle_query_changes::<Task, B>(backend, caller, args).await
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
use crate::test_support::MockBackend;
#[tokio::test]
async fn get_unknown_account_returns_account_not_found() {
let backend = MockBackend::new();
let args = json!({ "accountId": "unknown", "ids": null });
let result = handle_task_get(&backend, &(), args).await;
let err = result.expect_err("must return error for unknown account");
assert_eq!(err.error_type.as_str(), "accountNotFound");
}
#[tokio::test]
async fn copy_missing_from_account_id_returns_invalid_arguments() {
let backend = MockBackend::new_with_account("acc1");
let args = json!({
"accountId": "acc1",
"create": {}
});
let result = handle_task_copy(&backend, &(), args).await;
let err = result.expect_err("must return error when fromAccountId missing");
assert_eq!(err.error_type.as_str(), "invalidArguments");
}
#[tokio::test]
async fn set_empty_destroy_returns_valid_response() {
let backend = MockBackend::new_with_account("acc1");
let args = json!({ "accountId": "acc1", "destroy": [] });
let (resp, _) = handle_task_set(&backend, &(), args)
.await
.expect("must not return top-level error");
assert_eq!(resp["accountId"], "acc1");
}
#[tokio::test]
async fn set_is_draft_revert_rejected_when_current_is_false() {
let mut backend = MockBackend::new_with_account("acc1");
backend.seed_task("acc1", "t1", false);
let args = json!({
"accountId": "acc1",
"update": {
"t1": { "isDraft": true }
}
});
let (resp, _) = handle_task_set(&backend, &(), args)
.await
.expect("must not return a top-level error");
let not_updated = resp["notUpdated"]
.as_object()
.expect("notUpdated must be an object");
assert!(
not_updated.contains_key("t1"),
"t1 must appear in notUpdated: {resp}"
);
assert_eq!(
not_updated["t1"]["type"].as_str(),
Some("invalidProperties"),
"error type must be invalidProperties"
);
assert_eq!(
not_updated["t1"]["properties"][0].as_str(),
Some("isDraft"),
"properties must list isDraft"
);
}
#[tokio::test]
async fn set_is_draft_true_on_draft_task_passes_to_backend() {
let mut backend = MockBackend::new_with_account("acc1");
backend.seed_task("acc1", "t2", true);
let args = json!({
"accountId": "acc1",
"update": {
"t2": { "isDraft": true }
}
});
let (resp, _) = handle_task_set(&backend, &(), args)
.await
.expect("must not return a top-level error");
if let Some(not_updated) = resp["notUpdated"].as_object() {
if let Some(err) = not_updated.get("t2") {
assert_ne!(
err["type"].as_str(),
Some("invalidProperties"),
"isDraft:true on an existing draft must not produce invalidProperties"
);
}
}
}
#[tokio::test]
async fn set_is_draft_false_passes_to_backend() {
let mut backend = MockBackend::new_with_account("acc1");
backend.seed_task("acc1", "t3", true);
let args = json!({
"accountId": "acc1",
"update": {
"t3": { "isDraft": false }
}
});
let (resp, _) = handle_task_set(&backend, &(), args)
.await
.expect("must not return a top-level error");
if let Some(not_updated) = resp["notUpdated"].as_object() {
if let Some(err) = not_updated.get("t3") {
assert_ne!(
err["type"].as_str(),
Some("invalidProperties"),
"isDraft:false must never produce invalidProperties"
);
}
}
}
#[tokio::test]
async fn get_without_utc_properties_omits_utc_fields() {
let backend = MockBackend::new_with_account("acc1");
let args = json!({
"accountId": "acc1",
"ids": null,
"properties": ["id", "title"] });
let (resp, _) = handle_task_get(&backend, &(), args)
.await
.expect("must succeed");
assert_eq!(resp["accountId"], "acc1");
let list = resp["list"].as_array().expect("list must be an array");
for item in list {
assert!(
item.get("utcStart").is_none(),
"utcStart must not appear when not in properties"
);
}
}
#[tokio::test]
async fn get_with_utc_start_in_properties_does_not_error() {
let backend = MockBackend::new_with_account("acc1");
let args = json!({
"accountId": "acc1",
"ids": null,
"properties": ["id", "utcStart", "utcDue"]
});
let (resp, _) = handle_task_get(&backend, &(), args)
.await
.expect("must succeed with utcStart in properties");
assert_eq!(resp["accountId"], "acc1");
}
#[tokio::test]
async fn set_per_user_only_patch_routes_to_per_user_update() {
let backend = MockBackend::new_with_account("acc1");
let args = json!({
"accountId": "acc1",
"update": { "t1": { "color": "#ff0000" } }
});
let (resp, _) = handle_task_set(&backend, &(), args)
.await
.expect("must not return top-level error");
if let Some(nu) = resp["notUpdated"].as_object() {
if let Some(err) = nu.get("t1") {
assert_ne!(
err["type"].as_str(),
Some("invalidProperties"),
"per-user-only patch must not produce invalidProperties"
);
}
}
}
#[tokio::test]
async fn set_shared_property_patch_routes_to_update_object() {
let backend = MockBackend::new_with_account("acc1");
let args = json!({
"accountId": "acc1",
"update": { "t1": { "title": "New title" } }
});
let (resp, _) = handle_task_set(&backend, &(), args)
.await
.expect("must not return top-level error");
if let Some(nu) = resp["notUpdated"].as_object() {
if let Some(err) = nu.get("t1") {
assert_ne!(
err["type"].as_str(),
Some("invalidProperties"),
"shared-property patch must not produce invalidProperties"
);
}
}
}
#[tokio::test]
async fn set_mixed_patch_routes_to_update_object() {
let backend = MockBackend::new_with_account("acc1");
let args = json!({
"accountId": "acc1",
"update": { "t1": { "color": "#ff0000", "title": "New" } }
});
let (resp, _) = handle_task_set(&backend, &(), args)
.await
.expect("must not return top-level error");
assert_eq!(resp["accountId"], "acc1");
}
#[tokio::test]
async fn set_is_draft_revert_rejected_with_prefetch() {
let mut backend = MockBackend::new_with_account("acc1");
backend.seed_task("acc1", "t1", false);
let args = json!({
"accountId": "acc1",
"update": { "t1": { "isDraft": true } }
});
let (resp, _) = handle_task_set(&backend, &(), args)
.await
.expect("must not return top-level error");
let not_updated = resp["notUpdated"].as_object().expect("notUpdated");
assert_eq!(
not_updated["t1"]["type"], "invalidProperties",
"pre-fetch path must reject isDraft revert: {resp}"
);
assert_eq!(not_updated["t1"]["properties"][0], "isDraft");
}
}