Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(customer-analytics): add atomic task bulk updates (#123651)

Arthur Moreira de Deus8ae782d72ffa
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index cbd59a30d7f0..25fb5cb1896d 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -5473,6 +5473,25 @@ def update_customer_task(
return _to_customer_task_view(task, fresh_user_access_control)
+def bulk_update_customer_tasks(
+ *,
+ team: Team,
+ task_ids: list[UUID],
+ input: contracts.UpdateCustomerTaskInput,
+ archived: bool | None,
+ actor: "User | None",
+ user_access_control: "UserAccessControl",
+) -> int | None:
+ return _customer_tasks_logic.bulk_update_customer_tasks(
+ team=team,
+ task_ids=task_ids,
+ input=input,
+ archived=archived,
+ actor=actor,
+ user_access_control=user_access_control,
+ )
+
+
def archive_customer_task(
*,
team_id: int,
diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.py
index 8a6e2caa40ec..22d194021395 100644
--- a/products/customer_analytics/backend/facade/contracts.py
+++ b/products/customer_analytics/backend/facade/contracts.py
@@ -1420,6 +1420,10 @@ class CustomerTaskAccessDenied(Exception):
pass
+class CustomerTaskBulkUpdateConflict(Exception):
+ pass
+
+
@stdlib_dataclass(frozen=True)
class CustomerTaskUserView:
id: int
diff --git a/products/customer_analytics/backend/logic/customer_tasks.py b/products/customer_analytics/backend/logic/customer_tasks.py
index d0e4a898f09d..2456b25b25b5 100644
--- a/products/customer_analytics/backend/logic/customer_tasks.py
+++ b/products/customer_analytics/backend/logic/customer_tasks.py
@@ -2,11 +2,12 @@ from __future__ import annotations
from collections.abc import Iterable
from datetime import datetime
+from functools import cached_property
from typing import cast
from uuid import UUID
from django.core.exceptions import ValidationError as DjangoValidationError
-from django.db import transaction
+from django.db import IntegrityError, transaction
from django.db.models import Case, CharField, F, IntegerField, Q, QuerySet, Value, When
from django.db.models.functions import Coalesce, Concat, Lower, NullIf, Trim
from django.utils import timezone
@@ -43,6 +44,13 @@ class _CustomerTaskActivityPage:
visible_account_ids: frozenset[str]
+@frozen
+class _CustomerTaskWrite:
+ task: CustomerTask
+ before_assignee: User | None
+ activity: CustomerTaskActivity
+
+
_ALLOWED_TRANSITIONS: dict[str, frozenset[str]] = {
CustomerTaskStatus.OPEN.value: frozenset(
{CustomerTaskStatus.IN_PROGRESS.value, CustomerTaskStatus.COMPLETED.value, CustomerTaskStatus.CANCELED.value}
@@ -88,6 +96,13 @@ def _account_for_write(team_id: int, account_id: UUID | None, user_access_contro
return account
+def _validate_assignee_access(*, team: Team, account: Account | None, access: UserAccessControl) -> None:
+ if not access.check_access_level_for_object(team, required_level="member"):
+ raise CustomerTaskAssigneeInvalid()
+ if account is not None and not access.check_access_level_for_object(account, required_level="viewer"):
+ raise CustomerTaskAssigneeCannotViewAccount()
+
+
def _validate_assignee(
*,
team: Team,
@@ -104,14 +119,57 @@ def _validate_assignee(
assignee = User.objects.filter(id=assignee_id).first()
if assignee is None:
raise CustomerTaskAssigneeInvalid()
- assignee_access = UserAccessControl(user=assignee, team=team)
- if not assignee_access.check_access_level_for_object(team, required_level="member"):
- raise CustomerTaskAssigneeInvalid()
- if account is not None and not assignee_access.check_access_level_for_object(account, required_level="viewer"):
- raise CustomerTaskAssigneeCannotViewAccount()
+ _validate_assignee_access(team=team, account=account, access=UserAccessControl(user=assignee, team=team))
return assignee
+class _CustomerTaskBulkValidation:
+ def __init__(
+ self,
+ *,
+ team: Team,
+ visible_tasks: list[CustomerTask],
+ input: contracts.UpdateCustomerTaskInput,
+ user_access_control: UserAccessControl,
+ ) -> None:
+ self.team = team
+ self.user_access_control = user_access_control
+ self.accounts = {task.account.id: task.account for task in visible_tasks if task.account is not None}
+ self.assignee_ids = {task.assigned_to_id for task in visible_tasks if task.assigned_to_id is not None}
+ if input.assigned_to_id_provided and input.assigned_to_id is not None:
+ self.assignee_ids.add(input.assigned_to_id)
+ self.validated_pairs: set[tuple[UUID | None, int]] = set()
+
+ @cached_property
+ def assignee_access(self) -> dict[int, UserAccessControl]:
+ return UserAccessControl.for_user_ids(user_ids=self.assignee_ids, team=self.team)
+
+ def can_edit(self, task: CustomerTask) -> bool:
+ return self.user_access_control.check_access_level_for_object(task, required_level="editor")
+
+ def get_account(self, account_id: UUID | None) -> Account | None:
+ if account_id is None:
+ return None
+ if account_id not in self.accounts:
+ account = _account_for_write(self.team.id, account_id, self.user_access_control)
+ if account is None:
+ raise CustomerTaskAccountNotFound()
+ self.accounts[account_id] = account
+ return self.accounts[account_id]
+
+ def get_assignee(self, account: Account | None, assignee_id: int | None) -> User | None:
+ if assignee_id is None:
+ return None
+ access = self.assignee_access.get(assignee_id)
+ if access is None:
+ raise CustomerTaskAssigneeInvalid()
+ pair = (account.id if account is not None else None, assignee_id)
+ if pair not in self.validated_pairs:
+ _validate_assignee_access(team=self.team, account=account, access=access)
+ self.validated_pairs.add(pair)
+ return access.user
+
+
def _set_customer_task_assignee_access(
*,
task: CustomerTask,
@@ -395,6 +453,156 @@ def create_customer_task(
return task
+def _prepare_customer_task_update(
+ *,
+ team: Team,
+ task: CustomerTask,
+ input: contracts.UpdateCustomerTaskInput,
+ actor: User | None,
+ user_access_control: UserAccessControl,
+ validation: _CustomerTaskBulkValidation | None = None,
+) -> _CustomerTaskWrite | None:
+ can_edit = (
+ validation.can_edit(task)
+ if validation is not None
+ else can_access_customer_task_object(task=task, user_access_control=user_access_control, write=True)
+ )
+ if not can_edit:
+ raise CustomerTaskAccessDenied()
+ if task.archived_at is not None:
+ raise CustomerTaskArchived()
+
+ before_account = task.account
+ before_name = task.name
+ before_description = task.description
+ before_status = task.status
+ before_assignee = task.assigned_to
+ before_due_at = task.due_at
+ semantic_change = (
+ (input.account_id_provided and input.account_id != task.account_id)
+ or (input.name_provided and input.name != task.name)
+ or (input.description_provided and input.description != task.description)
+ or (input.assigned_to_id_provided and input.assigned_to_id != task.assigned_to_id)
+ or (input.due_at_provided and input.due_at != task.due_at)
+ or (input.status_provided and input.status != task.status)
+ )
+ if not semantic_change:
+ return None
+
+ account_id = input.account_id if input.account_id_provided else task.account_id
+ assignee_id = input.assigned_to_id if input.assigned_to_id_provided else task.assigned_to_id
+ if validation is not None:
+ account = validation.get_account(account_id)
+ assignee = validation.get_assignee(account, assignee_id)
+ else:
+ account = _account_for_write(team.id, account_id, user_access_control)
+ assignee = _validate_assignee(team=team, account=account, assignee_id=assignee_id)
+ requested_status = input.status if input.status_provided else task.status
+ if requested_status is None:
+ raise CustomerTaskInvalidTransition(task.status, "")
+ if (
+ input.status_provided
+ and requested_status != task.status
+ and requested_status not in _ALLOWED_TRANSITIONS[task.status]
+ ):
+ raise CustomerTaskInvalidTransition(task.status, requested_status)
+
+ if requested_status == CustomerTaskStatus.COMPLETED and task.status != CustomerTaskStatus.COMPLETED:
+ completed_at = timezone.now()
+ completed_by = actor if actor is not None else assignee
+ elif requested_status == CustomerTaskStatus.OPEN and task.status == CustomerTaskStatus.COMPLETED:
+ completed_at = None
+ completed_by = None
+ else:
+ completed_at = task.completed_at
+ completed_by = task.completed_by
+
+ task.account = account
+ if input.name_provided:
+ task.name = cast(str, input.name)
+ task.description = input.description if input.description_provided else task.description
+ task.assigned_to = assignee
+ task.due_at = input.due_at if input.due_at_provided else task.due_at
+ task.status = requested_status
+ task.completed_at = completed_at
+ task.completed_by = completed_by
+ changes = _changes(
+ before_account=before_account,
+ after_account=task.account,
+ before_name=before_name,
+ after_name=task.name,
+ before_description=before_description,
+ after_description=task.description,
+ before_status=before_status,
+ after_status=task.status,
+ before_assignee=before_assignee,
+ after_assignee=task.assigned_to,
+ before_due_at=before_due_at,
+ after_due_at=task.due_at,
+ )
+ return _CustomerTaskWrite(
+ task=task,
+ before_assignee=before_assignee,
+ activity=CustomerTaskActivity(
+ team_id=team.id,
+ task=task,
+ actor=actor,
+ activity_type=CustomerTaskActivityType.UPDATED,
+ changes=changes,
+ ),
+ )
+
+
+def _update_customer_task_access(*, team: Team, write: _CustomerTaskWrite, actor: User | None) -> None:
+ _set_customer_task_assignee_access(
+ task=write.task,
+ organization_id=team.organization_id,
+ before_assignee=write.before_assignee,
+ after_assignee=write.task.assigned_to,
+ actor=actor,
+ )
+
+
+def _bulk_update_customer_task_access(*, team: Team, writes: list[_CustomerTaskWrite], actor: User | None) -> None:
+ assignment_changes = [write for write in writes if write.before_assignee != write.task.assigned_to]
+ if not assignment_changes:
+ return
+ user_ids = {
+ assignee.id
+ for write in assignment_changes
+ for assignee in (write.before_assignee, write.task.assigned_to)
+ if assignee is not None
+ }
+ membership_ids = dict(
+ OrganizationMembership.objects.filter(organization_id=team.organization_id, user_id__in=user_ids).values_list(
+ "user_id", "id"
+ )
+ )
+ inputs: list[access_control_contracts.SetObjectAccessControlInput] = []
+ for write in assignment_changes:
+ for assignee, access_level in ((write.before_assignee, None), (write.task.assigned_to, "editor")):
+ if assignee is None:
+ continue
+ membership_id = membership_ids.get(assignee.id)
+ if membership_id is None:
+ if access_level is not None:
+ raise CustomerTaskAssigneeInvalid()
+ continue
+ inputs.append(
+ access_control_contracts.SetObjectAccessControlInput(
+ resource="customer_task",
+ resource_id=str(write.task.id),
+ organization_member_id=membership_id,
+ access_level=access_level,
+ created_by_id=actor.id if actor is not None else None,
+ )
+ )
+ try:
+ access_control_api.bulk_set_object_access_controls(team_id=team.id, inputs=inputs)
+ except access_control_api.InvalidObjectAccessControlError as error:
+ raise CustomerTaskAssigneeInvalid() from error
+
+
def update_customer_task(
*,
team: Team,
@@ -407,89 +615,93 @@ def update_customer_task(
task = _task_for_write(team_id=team.id, task_id=task_id, user_access_control=user_access_control)
if task is None:
return None
- if not can_access_customer_task_object(task=task, user_access_control=user_access_control, write=True):
- raise CustomerTaskAccessDenied()
- if task.archived_at is not None:
- raise CustomerTaskArchived()
-
- before_account = task.account
- before_name = task.name
- before_description = task.description
- before_status = task.status
- before_assignee = task.assigned_to
- before_due_at = task.due_at
- semantic_change = (
- (input.account_id_provided and input.account_id != task.account_id)
- or (input.name_provided and input.name != task.name)
- or (input.description_provided and input.description != task.description)
- or (input.assigned_to_id_provided and input.assigned_to_id != task.assigned_to_id)
- or (input.due_at_provided and input.due_at != task.due_at)
- or (input.status_provided and input.status != task.status)
- )
- if not semantic_change:
- return task
-
- account = _account_for_write(
- team.id, input.account_id if input.account_id_provided else task.account_id, user_access_control
+ write = _prepare_customer_task_update(
+ team=team, task=task, input=input, actor=actor, user_access_control=user_access_control
)
- assignee_id = input.assigned_to_id if input.assigned_to_id_provided else task.assigned_to_id
- assignee = _validate_assignee(team=team, account=account, assignee_id=assignee_id)
- requested_status = input.status if input.status_provided else task.status
- if requested_status is None:
- raise CustomerTaskInvalidTransition(task.status, "")
- if (
- input.status_provided
- and requested_status != task.status
- and requested_status not in _ALLOWED_TRANSITIONS[task.status]
- ):
- raise CustomerTaskInvalidTransition(task.status, requested_status)
-
- if requested_status == CustomerTaskStatus.COMPLETED and task.status != CustomerTaskStatus.COMPLETED:
- completed_at = timezone.now()
- completed_by = actor if actor is not None else assignee
- elif requested_status == CustomerTaskStatus.OPEN and task.status == CustomerTaskStatus.COMPLETED:
- completed_at = None
- completed_by = None
- else:
- completed_at = task.completed_at
- completed_by = task.completed_by
-
- task.account = account
- if input.name_provided:
- task.name = cast(str, input.name)
- task.description = input.description if input.description_provided else task.description
- task.assigned_to = assignee
- task.due_at = input.due_at if input.due_at_provided else task.due_at
- task.status = requested_status
- task.completed_at = completed_at
- task.completed_by = completed_by
- task.save()
- _set_customer_task_assignee_access(
- task=task,
- organization_id=team.organization_id,
- before_assignee=before_assignee,
- after_assignee=assignee,
- actor=actor,
- )
- changes = _changes(
- before_account=before_account,
- after_account=task.account,
- before_name=before_name,
- after_name=task.name,
- before_description=before_description,
- after_description=task.description,
- before_status=before_status,
- after_status=task.status,
- before_assignee=before_assignee,
- after_assignee=task.assigned_to,
- before_due_at=before_due_at,
- after_due_at=task.due_at,
- )
- if changes:
- _record_activity(task=task, activity_type=CustomerTaskActivityType.UPDATED, actor=actor, changes=changes)
+ if write is not None:
+ task.save()
+ _update_customer_task_access(team=team, write=write, actor=actor)
+ write.activity.save()
return task
+def bulk_update_customer_tasks(
+ *,
+ team: Team,
+ task_ids: list[UUID],
+ input: contracts.UpdateCustomerTaskInput,
+ archived: bool | None,
+ actor: User | None,
+ user_access_control: UserAccessControl,
+) -> int | None:
+ try:
+ with transaction.atomic():
+ tasks = list(
+ _visible_task_queryset(team.id, user_access_control)
+ .filter(id__in=task_ids)
+ .order_by("id")
+ .select_for_update(of=("self",))
+ )
+ if len(tasks) != len(task_ids):
+ return None
+ validation = _CustomerTaskBulkValidation(
+ team=team, visible_tasks=tasks, input=input, user_access_control=user_access_control
+ )
+ writes: list[_CustomerTaskWrite] = []
+ now = timezone.now()
+ for task in tasks:
+ if archived is None:
+ write = _prepare_customer_task_update(
+ team=team,
+ task=task,
+ input=input,
+ actor=actor,
+ user_access_control=user_access_control,
+ validation=validation,
+ )
+ if write is None:
+ continue
+ else:
+ if not validation.can_edit(task):
+ raise CustomerTaskAccessDenied()
+ if (task.archived_at is not None) == archived:
+ continue
+ task.archived_at = now if archived else None
+ write = _CustomerTaskWrite(
+ task=task,
+ before_assignee=task.assigned_to,
+ activity=CustomerTaskActivity(
+ team_id=team.id,
+ task=task,
+ actor=actor,
+ activity_type=CustomerTaskActivityType.ARCHIVED
+ if archived
+ else CustomerTaskActivityType.RESTORED,
+ changes=[],
+ ),
+ )
+ task.updated_at = now
+ writes.append(write)
+ CustomerTask.objects.for_team(team.id).bulk_update(
+ [write.task for write in writes],
+ [
+ "account",
+ "assigned_to",
+ "due_at",
+ "status",
+ "completed_at",
+ "completed_by",
+ "archived_at",
+ "updated_at",
+ ],
+ )
+ _bulk_update_customer_task_access(team=team, writes=writes, actor=actor)
+ CustomerTaskActivity.objects.for_team(team.id).bulk_create([write.activity for write in writes])
+ return len(writes)
+ except IntegrityError as error:
+ raise contracts.CustomerTaskBulkUpdateConflict() from error
+
+
def archive_customer_task(
*, team_id: int, task_id: UUID | str, actor: User | None, user_access_control: UserAccessControl
) -> CustomerTask | None:
diff --git a/products/customer_analytics/backend/presentation/views/customer_tasks.py b/products/customer_analytics/backend/presentation/views/customer_tasks.py
index 024b723486e0..18a41e0c73dd 100644
--- a/products/customer_analytics/backend/presentation/views/customer_tasks.py
+++ b/products/customer_analytics/backend/presentation/views/customer_tasks.py
@@ -128,19 +128,10 @@ class CustomerTaskCreateSerializer(serializers.Serializer):
return attrs
-class CustomerTaskUpdateSerializer(serializers.Serializer):
+class CustomerTaskUpdateFieldsSerializer(serializers.Serializer):
account_id = serializers.UUIDField(
required=False, allow_null=True, help_text="UUID of a visible account, or null to remove the account link."
)
- name = serializers.CharField(
- max_length=400,
- allow_null=False,
- error_messages={"blank": "Enter a task name."},
- help_text="Replacement task name.",
- )
- description = serializers.CharField(
- required=False, allow_null=True, allow_blank=True, help_text="Replacement description, or null to clear it."
- )
assigned_to_id = serializers.IntegerField(
required=False, allow_null=True, help_text="Replacement assignee ID, or null to unassign."
)
@@ -154,19 +145,69 @@ class CustomerTaskUpdateSerializer(serializers.Serializer):
help_text="Replacement task status.",
)
+ def to_internal_value(self, data: Any) -> dict[str, Any]:
+ if isinstance(data, dict):
+ unexpected = set(data) - set(self.fields)
+ if unexpected:
+ raise serializers.ValidationError(dict.fromkeys(unexpected, "This field is not accepted."))
+ return super().to_internal_value(data)
+
+
+class CustomerTaskUpdateSerializer(CustomerTaskUpdateFieldsSerializer):
+ name = serializers.CharField(
+ max_length=400,
+ allow_null=False,
+ error_messages={"blank": "Enter a task name."},
+ help_text="Replacement task name.",
+ )
+ description = serializers.CharField(
+ required=False, allow_null=True, allow_blank=True, help_text="Replacement description, or null to clear it."
+ )
+
def validate_name(self, value: str) -> str:
value = value.strip()
if not value:
raise serializers.ValidationError("Enter a task name.")
return value
+
+class CustomerTaskBulkPatchSerializer(CustomerTaskUpdateFieldsSerializer):
+ archived = serializers.BooleanField(
+ required=False, help_text="Archive tasks when true, or restore them when false."
+ )
+
def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
- unexpected = set(self.initial_data) - set(self.fields)
- if unexpected:
- raise serializers.ValidationError(dict.fromkeys(unexpected, "This field is not accepted."))
+ attrs = super().validate(attrs)
+ if not attrs:
+ raise serializers.ValidationError("Change at least one task field.")
+ if "archived" in attrs and len(attrs) != 1:
+ raise serializers.ValidationError("Change archive state separately from other task fields.")
return attrs
+class CustomerTaskBulkUpdateSerializer(serializers.Serializer):
+ task_ids = serializers.ListField(
+ child=serializers.UUIDField(),
+ min_length=1,
+ max_length=100,
+ help_text="UUIDs of up to 100 tasks to update together.",
+ )
+ updates = CustomerTaskBulkPatchSerializer(help_text="Changes to apply to every selected task.")
+
+ def validate_task_ids(self, value: list[UUID]) -> list[UUID]:
+ if len(set(value)) != len(value):
+ raise serializers.ValidationError("Select each task once.")
+ return value
+
+
+class CustomerTaskBulkUpdateResultSerializer(serializers.Serializer):
+ updated_count = serializers.IntegerField(read_only=True, help_text="Number of tasks changed by this batch.")
+
+
+class CustomerTaskBulkUpdateErrorSerializer(serializers.Serializer):
+ detail = serializers.CharField(read_only=True, help_text="Reason the batch could not be updated.")
+
+
@extend_schema_field({"oneOf": [{"type": "string"}, {"type": "number"}, {"type": "boolean"}, {"type": "object"}]})
class CustomerTaskChangeValueField(serializers.JSONField):
pass
@@ -316,7 +357,7 @@ class CustomerTaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
pagination_class = None
posthog_feature_flag = CUSTOMER_ANALYTICS_CUSTOMER_TASKS_FLAG
scope_object_read_actions = ["list", "retrieve", "activities"]
- scope_object_write_actions = ["create", "update", "partial_update", "archive", "restore"]
+ scope_object_write_actions = ["create", "update", "partial_update", "archive", "restore", "bulk_update"]
permission_classes = [CustomerTaskCanonicalTeamAccessPermission, PostHogFeatureFlagPermission]
@cached_property
@@ -423,6 +464,37 @@ class CustomerTaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
def update(self, request: Request, *args: Any, **kwargs: Any) -> Response:
return self._update_customer_task(request, partial=False)
+ @validated_request(
+ request_serializer=CustomerTaskBulkUpdateSerializer,
+ responses={
+ 200: CustomerTaskBulkUpdateResultSerializer,
+ 404: CustomerTaskBulkUpdateErrorSerializer,
+ 409: CustomerTaskBulkUpdateErrorSerializer,
+ },
+ description="Update selected tasks in one transaction. No tasks change if any task fails validation.",
+ )
+ @action(detail=False, methods=["post"])
+ def bulk_update(self, request: ValidatedRequest, *args: Any, **kwargs: Any) -> Response:
+ updates = dict(request.validated_data["updates"])
+ archived = updates.pop("archived", None)
+ count = api.bulk_update_customer_tasks(
+ team=self.canonical_team,
+ task_ids=request.validated_data["task_ids"],
+ input=contracts.UpdateCustomerTaskInput(
+ **updates,
+ account_id_provided="account_id" in updates,
+ assigned_to_id_provided="assigned_to_id" in updates,
+ due_at_provided="due_at" in updates,
+ status_provided="status" in updates,
+ ),
+ archived=archived,
+ actor=cast(User, request.user),
+ user_access_control=self.user_access_control,
+ )
+ if count is None:
+ return Response({"detail": "Task not found."}, status=status.HTTP_404_NOT_FOUND)
+ return Response(CustomerTaskBulkUpdateResultSerializer(instance={"updated_count": count}).data)
+
@extend_schema(request=None, responses={200: CustomerTaskSerializer})
@action(detail=True, methods=["post"])
def archive(self, request: Request, *args: Any, **kwargs: Any) -> Response:
@@ -501,4 +573,9 @@ class CustomerTaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
)
if isinstance(exc, contracts.CustomerTaskArchived):
return Response({"detail": "Restore this task before editing it."}, status=status.HTTP_409_CONFLICT)
+ if isinstance(exc, contracts.CustomerTaskBulkUpdateConflict):
+ return Response(
+ {"detail": "Could not update the tasks. No tasks changed. Refresh the page and try again."},
+ status=status.HTTP_409_CONFLICT,
+ )
return super().handle_exception(exc)
diff --git a/products/customer_analytics/backend/test/test_customer_tasks.py b/products/customer_analytics/backend/test/test_customer_tasks.py
index 4c4c62de9bba..3d5d2fad75fd 100644
--- a/products/customer_analytics/backend/test/test_customer_tasks.py
+++ b/products/customer_analytics/backend/test/test_customer_tasks.py
@@ -1,16 +1,20 @@
+from collections import Counter
from datetime import UTC, datetime
from uuid import UUID
from posthog.test.base import APIBaseTest
from unittest.mock import patch
-from django.test import SimpleTestCase
+from django.db import IntegrityError, connection
+from django.test import SimpleTestCase, override_settings
+from django.test.utils import CaptureQueriesContext
from parameterized import parameterized
from rest_framework import serializers, status
from posthog.constants import AvailableFeature
from posthog.models import Organization, OrganizationMembership, PersonalAPIKey, Team, User
+from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.personal_api_key import hash_key_value
from posthog.models.utils import generate_random_token_personal
@@ -20,6 +24,7 @@ from products.customer_analytics.backend.logic import customer_tasks
from products.customer_analytics.backend.models import Account, CustomerTask, CustomerTaskActivity
from products.customer_analytics.backend.presentation.views.customer_tasks import (
CustomerTaskActivityQuerySerializer,
+ CustomerTaskBulkUpdateSerializer,
CustomerTaskCreateSerializer,
CustomerTaskListQuerySerializer,
CustomerTaskUpdateSerializer,
@@ -40,6 +45,22 @@ class CustomerTaskSerializerTest(SimpleTestCase):
assert not update_serializer.is_valid()
assert "properties" in update_serializer.errors
+ @parameterized.expand(
+ [
+ ("empty selection", [], {"status": "completed"}),
+ ("too many tasks", [str(UUID(int=i)) for i in range(101)], {"status": "completed"}),
+ ("duplicates", [str(UUID(int=1)), str(UUID(int=1))], {"status": "completed"}),
+ ("empty update", [str(UUID(int=1))], {}),
+ ("unknown field", [str(UUID(int=1))], {"properties": {}}),
+ ("mixed archive update", [str(UUID(int=1))], {"archived": True, "status": "completed"}),
+ ]
+ )
+ def test_bulk_update_rejects_invalid_batches(
+ self, _name: str, task_ids: list[str], updates: dict[str, object]
+ ) -> None:
+ serializer = CustomerTaskBulkUpdateSerializer(data={"task_ids": task_ids, "updates": updates})
+ assert not serializer.is_valid()
+
@parameterized.expand(
[
# str.isdigit() accepts this one, but the filter's int() cast does not.
@@ -95,6 +116,331 @@ class CustomerTaskAPI(APIBaseTest):
self.flag_patcher.start()
self.addCleanup(self.flag_patcher.stop)
+ @parameterized.expand(
+ [
+ ("complete", {"status": "completed"}),
+ ("reopen", {"status": "open"}),
+ ("account", {}),
+ ("assign", {}),
+ ("deadline", {"due_at": "2026-09-10T12:00:00Z"}),
+ ("clear deadline", {"due_at": None}),
+ ("remove account", {"account_id": None}),
+ ("unassign", {"assigned_to_id": None}),
+ ]
+ )
+ def test_bulk_update_changes_tasks_and_records_activity(self, name: str, updates: dict[str, object]) -> None:
+ account = Account.objects.for_team(self.team.id).create(team_id=self.team.id, name="Example account")
+ updates = dict(updates)
+ if name == "account":
+ replacement = Account.objects.for_team(self.team.id).create(
+ team_id=self.team.id, name="Replacement account"
+ )
+ updates["account_id"] = str(replacement.id)
+ assignee: User | None = None
+ if name == "assign":
+ assignee = User.objects.create_and_join(self.organization, "[email protected]", "testpassword")
+ updates["assigned_to_id"] = assignee.id
+ tasks = [
+ CustomerTask.objects.for_team(self.team.id).create(
+ team_id=self.team.id,
+ name=f"Example task {i}",
+ account=account,
+ status="completed" if name == "reopen" else "open",
+ completed_at=datetime(2026, 9, 9, tzinfo=UTC) if name == "reopen" else None,
+ completed_by=self.user if name == "reopen" else None,
+ assigned_to=self.user,
+ due_at=datetime(2026, 9, 9, tzinfo=UTC),
+ )
+ for i in range(3)
+ ]
+ selected_tasks = tasks[:-1]
+ before = tasks[0].updated_at
+ with CaptureQueriesContext(connection) as queries:
+ response = self.client.post(
+ f"{self.url}bulk_update/",
+ {"task_ids": [str(t.id) for t in selected_tasks], "updates": updates},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json() == {"updated_count": len(selected_tasks)}
+ task_updates = [
+ q for q in queries.captured_queries if q["sql"].startswith(f'UPDATE "{CustomerTask._meta.db_table}"')
+ ]
+ assert len(task_updates) == 1
+ for task in selected_tasks:
+ task.refresh_from_db()
+ assert task.updated_at > before
+ for field, expected in updates.items():
+ actual = getattr(task, field)
+ if field == "due_at" and expected is not None:
+ assert actual == datetime(2026, 9, 10, 12, tzinfo=UTC)
+ elif field == "account_id" and expected is not None:
+ assert str(actual) == expected
+ else:
+ assert actual == expected
+ if name == "reopen":
+ assert task.completed_at is None
+ assert task.completed_by_id is None
+ if assignee is not None:
+ assert AccessControl.objects.filter(
+ team=self.team,
+ resource="customer_task",
+ resource_id=str(task.id),
+ organization_member__user_id=assignee.id,
+ access_level="editor",
+ ).exists()
+ if updates.get("status") == "completed":
+ assert task.completed_at is not None
+ assert task.completed_by_id == self.user.id
+ activity = CustomerTaskActivity.objects.for_team(self.team.id).get(task=task)
+ assert activity.activity_type == "updated"
+ assert activity.actor_id == self.user.id
+ assert activity.changes
+ tasks[-1].refresh_from_db()
+ assert tasks[-1].status == ("completed" if name == "reopen" else "open")
+ assert CustomerTaskActivity.objects.for_team(self.team.id).count() == len(selected_tasks)
+
+ @parameterized.expand([(True,), (False,)])
+ def test_bulk_archive_and_restore_skip_unchanged_tasks(self, archived: bool) -> None:
+ tasks = [
+ CustomerTask.objects.for_team(self.team.id).create(
+ team_id=self.team.id,
+ name=f"Example task {i}",
+ archived_at=datetime(2026, 9, 9, tzinfo=UTC) if (i == 0) != archived else None,
+ )
+ for i in range(2)
+ ]
+ untouched_at = tasks[1].updated_at
+ response = self.client.post(
+ f"{self.url}bulk_update/",
+ {"task_ids": [str(t.id) for t in tasks], "updates": {"archived": archived}},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json() == {"updated_count": 1}
+ for task in tasks:
+ task.refresh_from_db()
+ assert (task.archived_at is not None) == archived
+ assert tasks[1].updated_at == untouched_at
+ activity = CustomerTaskActivity.objects.for_team(self.team.id).get()
+ assert activity.task_id == tasks[0].id
+ assert activity.activity_type == ("archived" if archived else "restored")
+
+ @parameterized.expand(
+ [
+ ("shared account and assignee", "deadline", False, False),
+ ("different accounts", "deadline", True, False),
+ ("different assignees", "deadline", False, True),
+ ("different accounts and assignees", "deadline", True, True),
+ ("status", "status", True, True),
+ ("account", "account", True, True),
+ ("assign", "assign", True, True),
+ ("assign with existing access", "assign existing", True, True),
+ ("unassign", "unassign", True, True),
+ ("archive", "archive", True, True),
+ ("restore", "restore", True, True),
+ ("unchanged", "unchanged", True, True),
+ ]
+ )
+ @override_settings(ORGANIZATION_ACCESS_CACHE_ENABLED=False)
+ def test_bulk_update_query_count_does_not_grow_with_batch_size(
+ self, _name: str, action: str, different_accounts: bool, different_assignees: bool
+ ) -> None:
+ self.organization.available_product_features = [
+ {"name": feature, "key": feature}
+ for feature in (AvailableFeature.ACCESS_CONTROL, AvailableFeature.ROLE_BASED_ACCESS)
+ ]
+ self.organization.save(update_fields=["available_product_features"])
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save(update_fields=["level"])
+ accounts = Account.objects.for_team(self.team.id).bulk_create(
+ [Account(team_id=self.team.id, name=f"Account {i}") for i in range(101 if different_accounts else 1)]
+ )
+ assignees = User.objects.bulk_create(
+ [User(email=f"assignee-{i}@example.com") for i in range(102 if different_assignees else 1)]
+ )
+ memberships = OrganizationMembership.objects.bulk_create(
+ [OrganizationMembership(organization=self.organization, user=user) for user in assignees]
+ )
+ role = Role.objects.create(organization=self.organization, name="Task editors")
+ RoleMembership.objects.bulk_create(
+ [RoleMembership(role=role, user_id=member.user_id, organization_member=member) for member in memberships]
+ + [RoleMembership(role=role, user=self.user, organization_member=self.organization_membership)]
+ )
+ AccessControl.objects.bulk_create(
+ [
+ AccessControl(team=self.team, resource="customer_analytics", access_level="none"),
+ AccessControl(team=self.team, resource="customer_analytics", role=role, access_level="editor"),
+ ]
+ )
+ tasks = CustomerTask.objects.for_team(self.team.id).bulk_create(
+ [
+ CustomerTask(
+ team_id=self.team.id,
+ name=f"Task {i}",
+ account=accounts[i if different_accounts else 0],
+ assigned_to=assignees[i if different_assignees else 0],
+ archived_at=datetime(2026, 9, 9, tzinfo=UTC) if action == "restore" else None,
+ )
+ for i in range(101)
+ ]
+ )
+ if action in ("assign", "assign existing", "unassign"):
+ AccessControl.objects.bulk_create(
+ [
+ AccessControl(
+ team=self.team,
+ resource="customer_task",
+ resource_id=str(task.id),
+ organization_member=memberships[i if different_assignees else 0],
+ access_level="editor",
+ )
+ for i, task in enumerate(tasks)
+ ]
+ )
+ if action == "assign existing":
+ AccessControl.objects.bulk_create(
+ [
+ AccessControl(
+ team=self.team,
+ resource="customer_task",
+ resource_id=str(task.id),
+ organization_member=memberships[-1],
+ access_level="viewer",
+ )
+ for task in tasks
+ ]
+ )
+ updates: dict[str, object]
+ if action == "account":
+ replacement = Account.objects.for_team(self.team.id).create(team_id=self.team.id, name="Replacement")
+ updates = {"account_id": str(replacement.id)}
+ elif action in ("assign", "assign existing"):
+ updates = {"assigned_to_id": assignees[-1].id}
+ elif action == "unassign":
+ updates = {"assigned_to_id": None}
+ elif action in ("archive", "restore"):
+ updates = {"archived": action == "archive"}
+ elif action == "deadline":
+ updates = {"due_at": "2026-09-10T12:00:00Z"}
+ else:
+ updates = {"status": "open" if action == "unchanged" else "completed"}
+
+ query_counts: list[Counter[str]] = []
+ for selected in (tasks[:1], tasks[1:]):
+ with CaptureQueriesContext(connection) as queries:
+ response = self.client.post(
+ f"{self.url}bulk_update/",
+ {"task_ids": [str(task.id) for task in selected], "updates": updates},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json() == {"updated_count": 0 if action == "unchanged" else len(selected)}
+ query_counts.append(Counter(query["sql"].split()[0] for query in queries.captured_queries))
+ for operation in ("SELECT", "INSERT", "UPDATE", "DELETE"):
+ assert query_counts[1][operation] <= query_counts[0][operation] + 1, query_counts
+ assert CustomerTaskActivity.objects.for_team(self.team.id).count() == (0 if action == "unchanged" else 101)
+ if action in ("assign", "assign existing", "unassign"):
+ assert not AccessControl.objects.filter(
+ team=self.team,
+ resource="customer_task",
+ organization_member_id__in=[member.id for member in memberships[:-1]],
+ ).exists()
+ assert AccessControl.objects.filter(
+ team=self.team, resource="customer_task", organization_member=memberships[-1]
+ ).count() == (0 if action == "unassign" else 101)
+ assert (
+ ActivityLog.objects.filter(team_id=self.team.id, scope="AccessControl", activity="deleted").count()
+ == 101
+ )
+ assert ActivityLog.objects.filter(
+ team_id=self.team.id, scope="AccessControl", activity="created"
+ ).count() == (101 if action == "assign" else 0)
+ assert ActivityLog.objects.filter(
+ team_id=self.team.id, scope="AccessControl", activity="updated"
+ ).count() == (101 if action == "assign existing" else 0)
+
+ @parameterized.expand(
+ [
+ ("archived", 409),
+ ("invalid transition", 400),
+ ("cross team", 404),
+ ("no access", 404),
+ ("assignee account", 400),
+ ("assignee project", 400),
+ ]
+ )
+ def test_bulk_validation_does_not_write_any_tasks(self, failure: str, expected_status: int) -> None:
+ first = CustomerTask.objects.for_team(self.team.id).create(
+ team_id=self.team.id, id=UUID(int=1), name="First task"
+ )
+ second = CustomerTask.objects.for_team(self.team.id).create(
+ team_id=self.team.id,
+ id=UUID(int=2),
+ name="Second task",
+ archived_at=datetime(2026, 9, 9, tzinfo=UTC) if failure == "archived" else None,
+ status="completed" if failure == "invalid transition" else "open",
+ completed_at=datetime(2026, 9, 9, tzinfo=UTC) if failure == "invalid transition" else None,
+ )
+ if failure == "cross team":
+ other_team = Team.objects.create(organization=self.organization)
+ second.team = other_team
+ second.save(update_fields=["team"])
+ if failure == "no access":
+ AccessControl.objects.create(
+ team=self.team,
+ resource="customer_task",
+ resource_id=str(second.id),
+ access_level="none",
+ organization_member=self.organization_membership,
+ )
+ if failure in ("assignee account", "assignee project"):
+ assignee = User.objects.create_and_join(self.organization, "[email protected]", "testpassword")
+ membership = OrganizationMembership.objects.get(user=assignee, organization=self.organization)
+ account = Account.objects.for_team(self.team.id).create(team_id=self.team.id, name="Account")
+ second.account = account
+ second.assigned_to = assignee
+ second.save(update_fields=["account", "assigned_to"])
+ AccessControl.objects.create(
+ team=self.team,
+ resource="account" if failure == "assignee account" else "project",
+ resource_id=str(account.id) if failure == "assignee account" else str(self.team.id),
+ organization_member=membership,
+ access_level="none",
+ )
+ response = self.client.post(
+ f"{self.url}bulk_update/",
+ {"task_ids": [str(first.id), str(second.id)], "updates": {"status": "in_progress"}},
+ format="json",
+ )
+ assert response.status_code == expected_status, response.json()
+ first.refresh_from_db()
+ assert first.status == "open"
+ assert CustomerTaskActivity.objects.for_team(self.team.id).count() == 0
+
+ def test_bulk_write_failure_rolls_back_tasks_activity_and_assignee_access(self) -> None:
+ assignee = User.objects.create_and_join(self.organization, "[email protected]", "testpassword")
+ task = CustomerTask.objects.for_team(self.team.id).create(team_id=self.team.id, name="Example task")
+ before = task.updated_at
+ with patch.object(CustomerTaskActivity.objects, "for_team") as activities:
+ activities.return_value.bulk_create.side_effect = IntegrityError("Write conflict")
+ response = self.client.post(
+ f"{self.url}bulk_update/",
+ {"task_ids": [str(task.id)], "updates": {"assigned_to_id": assignee.id}},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_409_CONFLICT
+ assert (
+ response.json()["detail"] == "Could not update the tasks. No tasks changed. Refresh the page and try again."
+ )
+ task.refresh_from_db()
+ assert task.assigned_to_id is None
+ assert task.updated_at == before
+ assert CustomerTaskActivity.objects.for_team(self.team.id).count() == 0
+ assert not AccessControl.objects.filter(
+ team=self.team, resource="customer_task", resource_id=str(task.id)
+ ).exists()
+
def test_accountless_create_omits_properties_and_records_activity(self) -> None:
response = self.client.post(self.url, {"name": "Follow up", "description": None}, format="json")
@@ -199,6 +545,13 @@ class CustomerTaskAPI(APIBaseTest):
== status.HTTP_403_FORBIDDEN
)
+ assert (
+ self.client.post(
+ f"{self.url}bulk_update/", {"task_ids": [task_id], "updates": {"status": "completed"}}, format="json"
+ ).status_code
+ == status.HTTP_403_FORBIDDEN
+ )
+
write_key = self.create_personal_api_key_with_scopes(["customer_task:write"])
self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {write_key}")
assert (
@@ -835,7 +1188,8 @@ class CustomerTaskAPI(APIBaseTest):
assert response.status_code == status.HTTP_200_OK
- def test_update_validates_the_final_account_and_assignee_together(self) -> None:
+ @parameterized.expand([(False,), (True,)])
+ def test_update_validates_the_final_account_and_assignee_together(self, bulk: bool) -> None:
assignee = User.objects.create_and_join(self.organization, "[email protected]", "testpassword")
account = Account.objects.unscoped().create(team=self.team, name="Final-state account")
membership = OrganizationMembership.objects.get(user=assignee, organization=self.organization)
@@ -848,10 +1202,15 @@ class CustomerTaskAPI(APIBaseTest):
)
created = self.client.post(self.url, {"name": "Final-state task"}, format="json")
- response = self.client.patch(
- f"{self.url}{created.json()['id']}/",
- {"account_id": str(account.id), "assigned_to_id": assignee.id},
- format="json",
+ updates = {"account_id": str(account.id), "assigned_to_id": assignee.id}
+ response = (
+ self.client.post(
+ f"{self.url}bulk_update/",
+ {"task_ids": [created.json()["id"]], "updates": updates},
+ format="json",
+ )
+ if bulk
+ else self.client.patch(f"{self.url}{created.json()['id']}/", updates, format="json")
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.ts
index 606f9b96432d..c2400a8aa01a 100644
--- a/products/customer_analytics/frontend/generated/api.schemas.ts
+++ b/products/customer_analytics/frontend/generated/api.schemas.ts
@@ -3617,16 +3617,6 @@ export interface CustomerTaskUpdateApi {
* @nullable
*/
account_id?: string | null
- /**
- * Replacement task name.
- * @maxLength 400
- */
- name: string
- /**
- * Replacement description, or null to clear it.
- * @nullable
- */
- description?: string | null
/**
* Replacement assignee ID, or null to unassign.
* @nullable
@@ -3644,24 +3634,24 @@ export interface CustomerTaskUpdateApi {
* * `completed` - Completed
* * `canceled` - Canceled */
status?: CustomerTaskStatusEnumApi
-}
-
-export interface PatchedCustomerTaskUpdateApi {
- /**
- * UUID of a visible account, or null to remove the account link.
- * @nullable
- */
- account_id?: string | null
/**
* Replacement task name.
* @maxLength 400
*/
- name?: string
+ name: string
/**
* Replacement description, or null to clear it.
* @nullable
*/
description?: string | null
+}
+
+export interface PatchedCustomerTaskUpdateApi {
+ /**
+ * UUID of a visible account, or null to remove the account link.
+ * @nullable
+ */
+ account_id?: string | null
/**
* Replacement assignee ID, or null to unassign.
* @nullable
@@ -3679,6 +3669,16 @@ export interface PatchedCustomerTaskUpdateApi {
* * `completed` - Completed
* * `canceled` - Canceled */
status?: CustomerTaskStatusEnumApi
+ /**
+ * Replacement task name.
+ * @maxLength 400
+ */
+ name?: string
+ /**
+ * Replacement description, or null to clear it.
+ * @nullable
+ */
+ description?: string | null
}
/**
@@ -3751,6 +3751,54 @@ export interface CustomerTaskActivityPageApi {
readonly results: readonly CustomerTaskActivityApi[]
}
+export interface CustomerTaskBulkPatchApi {
+ /**
+ * UUID of a visible account, or null to remove the account link.
+ * @nullable
+ */
+ account_id?: string | null
+ /**
+ * Replacement assignee ID, or null to unassign.
+ * @nullable
+ */
+ assigned_to_id?: number | null
+ /**
+ * Replacement ISO 8601 deadline, or null to clear it.
+ * @nullable
+ */
+ due_at?: string | null
+ /** Replacement task status.
+ *
+ * * `open` - Open
+ * * `in_progress` - In progress
+ * * `completed` - Completed
+ * * `canceled` - Canceled */
+ status?: CustomerTaskStatusEnumApi
+ /** Archive tasks when true, or restore them when false. */
+ archived?: boolean
+}
+
+export interface CustomerTaskBulkUpdateApi {
+ /**
+ * UUIDs of up to 100 tasks to update together.
+ * @minItems 1
+ * @maxItems 100
+ */
+ task_ids: string[]
+ /** Changes to apply to every selected task. */
+ updates: CustomerTaskBulkPatchApi
+}
+
+export interface CustomerTaskBulkUpdateResultApi {
+ /** Number of tasks changed by this batch. */
+ readonly updated_count: number
+}
+
+export interface CustomerTaskBulkUpdateErrorApi {
+ /** Reason the batch could not be updated. */
+ readonly detail: string
+}
+
/**
* The caller's event stream — a live feed of selected accounts' events posted to a
* Slack channel of their choice. One stream per user per project.
diff --git a/products/customer_analytics/frontend/generated/api.ts b/products/customer_analytics/frontend/generated/api.ts
index f4b519a9c53d..99e1e42e46cb 100644
--- a/products/customer_analytics/frontend/generated/api.ts
+++ b/products/customer_analytics/frontend/generated/api.ts
@@ -66,6 +66,8 @@ import type {
CustomerProfileConfigsListParams,
CustomerTaskActivityPageApi,
CustomerTaskApi,
+ CustomerTaskBulkUpdateApi,
+ CustomerTaskBulkUpdateResultApi,
CustomerTaskCreateApi,
CustomerTaskPageApi,
CustomerTaskUpdateApi,
@@ -1995,6 +1997,26 @@ export const customerTasksRestoreCreate = async (
})
}
+export const getCustomerTasksBulkUpdateCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/customer_tasks/bulk_update/`
+}
+
+/**
+ * Update selected tasks in one transaction. No tasks change if any task fails validation.
+ */
+export const customerTasksBulkUpdateCreate = async (
+ projectId: string,
+ customerTaskBulkUpdateApi: CustomerTaskBulkUpdateApi,
+ options?: RequestInit
+): Promise<CustomerTaskBulkUpdateResultApi> => {
+ return apiMutator<CustomerTaskBulkUpdateResultApi>(getCustomerTasksBulkUpdateCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(customerTaskBulkUpdateApi),
+ })
+}
+
export const getEventStreamsListUrl = (projectId: string) => {
return `/api/projects/${projectId}/event_streams/`
}
diff --git a/products/customer_analytics/frontend/generated/api.zod.ts b/products/customer_analytics/frontend/generated/api.zod.ts
index 1debc1c0d88a..090976d63852 100644
--- a/products/customer_analytics/frontend/generated/api.zod.ts
+++ b/products/customer_analytics/frontend/generated/api.zod.ts
@@ -1119,8 +1119,6 @@ export const customerTasksUpdateBodyNameMax = 400
export const CustomerTasksUpdateBody = /* @__PURE__ */ zod.object({
account_id: zod.uuid().nullish().describe('UUID of a visible account, or null to remove the account link.'),
- name: zod.string().max(customerTasksUpdateBodyNameMax).describe('Replacement task name.'),
- description: zod.string().nullish().describe('Replacement description, or null to clear it.'),
assigned_to_id: zod.number().nullish().describe('Replacement assignee ID, or null to unassign.'),
due_at: zod.iso
.datetime({ offset: true })
@@ -1135,14 +1133,14 @@ export const CustomerTasksUpdateBody = /* @__PURE__ */ zod.object({
.describe(
'Replacement task status.\n\n\* `open` - Open\n\* `in_progress` - In progress\n\* `completed` - Completed\n\* `canceled` - Canceled'
),
+ name: zod.string().max(customerTasksUpdateBodyNameMax).describe('Replacement task name.'),
+ description: zod.string().nullish().describe('Replacement description, or null to clear it.'),
})
export const customerTasksPartialUpdateBodyNameMax = 400
export const CustomerTasksPartialUpdateBody = /* @__PURE__ */ zod.object({
account_id: zod.uuid().nullish().describe('UUID of a visible account, or null to remove the account link.'),
- name: zod.string().max(customerTasksPartialUpdateBodyNameMax).optional().describe('Replacement task name.'),
- description: zod.string().nullish().describe('Replacement description, or null to clear it.'),
assigned_to_id: zod.number().nullish().describe('Replacement assignee ID, or null to unassign.'),
due_at: zod.iso
.datetime({ offset: true })
@@ -1157,6 +1155,41 @@ export const CustomerTasksPartialUpdateBody = /* @__PURE__ */ zod.object({
.describe(
'Replacement task status.\n\n\* `open` - Open\n\* `in_progress` - In progress\n\* `completed` - Completed\n\* `canceled` - Canceled'
),
+ name: zod.string().max(customerTasksPartialUpdateBodyNameMax).optional().describe('Replacement task name.'),
+ description: zod.string().nullish().describe('Replacement description, or null to clear it.'),
+})
+
+/**
+ * Update selected tasks in one transaction. No tasks change if any task fails validation.
+ */
+export const customerTasksBulkUpdateCreateBodyTaskIdsMax = 100
+
+export const CustomerTasksBulkUpdateCreateBody = /* @__PURE__ */ zod.object({
+ task_ids: zod
+ .array(zod.uuid())
+ .min(1)
+ .max(customerTasksBulkUpdateCreateBodyTaskIdsMax)
+ .describe('UUIDs of up to 100 tasks to update together.'),
+ updates: zod
+ .object({
+ account_id: zod.uuid().nullish().describe('UUID of a visible account, or null to remove the account link.'),
+ assigned_to_id: zod.number().nullish().describe('Replacement assignee ID, or null to unassign.'),
+ due_at: zod.iso
+ .datetime({ offset: true })
+ .nullish()
+ .describe('Replacement ISO 8601 deadline, or null to clear it.'),
+ status: zod
+ .enum(['open', 'in_progress', 'completed', 'canceled'])
+ .describe(
+ '\* `open` - Open\n\* `in_progress` - In progress\n\* `completed` - Completed\n\* `canceled` - Canceled'
+ )
+ .optional()
+ .describe(
+ 'Replacement task status.\n\n\* `open` - Open\n\* `in_progress` - In progress\n\* `completed` - Completed\n\* `canceled` - Canceled'
+ ),
+ archived: zod.boolean().optional().describe('Archive tasks when true, or restore them when false.'),
+ })
+ .describe('Changes to apply to every selected task.'),
})
/**
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index f30f2bbe3363..dbc9815580c3 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -28924,6 +28924,54 @@ export namespace Schemas {
readonly results: readonly CustomerTaskActivity[];
}
+ export interface CustomerTaskBulkPatch {
+ /**
+ * UUID of a visible account, or null to remove the account link.
+ * @nullable
+ */
+ account_id?: string | null;
+ /**
+ * Replacement assignee ID, or null to unassign.
+ * @nullable
+ */
+ assigned_to_id?: number | null;
+ /**
+ * Replacement ISO 8601 deadline, or null to clear it.
+ * @nullable
+ */
+ due_at?: string | null;
+ /** Replacement task status.
+ *
+ * * `open` - Open
+ * * `in_progress` - In progress
+ * * `completed` - Completed
+ * * `canceled` - Canceled */
+ status?: CustomerTaskStatusEnum;
+ /** Archive tasks when true, or restore them when false. */
+ archived?: boolean;
+ }
+
+ export interface CustomerTaskBulkUpdate {
+ /**
+ * UUIDs of up to 100 tasks to update together.
+ * @minItems 1
+ * @maxItems 100
+ */
+ task_ids: string[];
+ /** Changes to apply to every selected task. */
+ updates: CustomerTaskBulkPatch;
+ }
+
+ export interface CustomerTaskBulkUpdateError {
+ /** Reason the batch could not be updated. */
+ readonly detail: string;
+ }
+
+ export interface CustomerTaskBulkUpdateResult {
+ /** Number of tasks changed by this batch. */
+ readonly updated_count: number;
+ }
+
export interface CustomerTaskCreate {
/**
* UUID of a visible account, or null for an accountless task.
@@ -28982,16 +29030,6 @@ export namespace Schemas {
* @nullable
*/
account_id?: string | null;
- /**
- * Replacement task name.
- * @maxLength 400
- */
- name: string;
- /**
- * Replacement description, or null to clear it.
- * @nullable
- */
- description?: string | null;
/**
* Replacement assignee ID, or null to unassign.
* @nullable
@@ -29009,6 +29047,16 @@ export namespace Schemas {
* * `completed` - Completed
* * `canceled` - Canceled */
status?: CustomerTaskStatusEnum;
+ /**
+ * Replacement task name.
+ * @maxLength 400
+ */
+ name: string;
+ /**
+ * Replacement description, or null to clear it.
+ * @nullable
+ */
+ description?: string | null;
}
export type DashboardFilters = { [key: string]: unknown };
@@ -85228,16 +85276,6 @@ export namespace Schemas {
* @nullable
*/
account_id?: string | null;
- /**
- * Replacement task name.
- * @maxLength 400
- */
- name?: string;
- /**
- * Replacement description, or null to clear it.
- * @nullable
- */
- description?: string | null;
/**
* Replacement assignee ID, or null to unassign.
* @nullable
@@ -85255,6 +85293,16 @@ export namespace Schemas {
* * `completed` - Completed
* * `canceled` - Canceled */
status?: CustomerTaskStatusEnum;
+ /**
+ * Replacement task name.
+ * @maxLength 400
+ */
+ name?: string;
+ /**
+ * Replacement description, or null to clear it.
+ * @nullable
+ */
+ description?: string | null;
}
export interface PatchedDashboardTemplate {
diff --git a/services/mcp/src/generated/customer_analytics/api.ts b/services/mcp/src/generated/customer_analytics/api.ts
index 88d690899767..4d9f646c5786 100644
--- a/services/mcp/src/generated/customer_analytics/api.ts
+++ b/services/mcp/src/generated/customer_analytics/api.ts
@@ -1073,8 +1073,6 @@ export const customerTasksPartialUpdateBodyNameMax = 400
export const CustomerTasksPartialUpdateBody = () => zod.object({
account_id: zod.string().nullish().describe('UUID of a visible account, or null to remove the account link.'),
- name: zod.string().max(customerTasksPartialUpdateBodyNameMax).optional().describe('Replacement task name.'),
- description: zod.string().nullish().describe('Replacement description, or null to clear it.'),
assigned_to_id: zod.number().nullish().describe('Replacement assignee ID, or null to unassign.'),
due_at: zod.iso
.datetime({ offset: true })
@@ -1089,6 +1087,8 @@ export const CustomerTasksPartialUpdateBody = () => zod.object({
.describe(
'Replacement task status.\n\n\* `open` - Open\n\* `in_progress` - In progress\n\* `completed` - Completed\n\* `canceled` - Canceled'
),
+ name: zod.string().max(customerTasksPartialUpdateBodyNameMax).optional().describe('Replacement task name.'),
+ description: zod.string().nullish().describe('Replacement description, or null to clear it.'),
})
export const CustomerTasksActivitiesListParams = () => zod.object({
diff --git a/services/mcp/src/tools/generated/customer_analytics.ts b/services/mcp/src/tools/generated/customer_analytics.ts
index 2e2e963fd28a..9cfea33be911 100644
--- a/services/mcp/src/tools/generated/customer_analytics.ts
+++ b/services/mcp/src/tools/generated/customer_analytics.ts
@@ -1319,12 +1319,6 @@ const customerTasksPartialUpdate = (): ToolBase<
if (params.account_id !== undefined) {
body['account_id'] = params.account_id
}
- if (params.name !== undefined) {
- body['name'] = params.name
- }
- if (params.description !== undefined) {
- body['description'] = params.description
- }
if (params.assigned_to_id !== undefined) {
body['assigned_to_id'] = params.assigned_to_id
}
@@ -1334,6 +1328,12 @@ const customerTasksPartialUpdate = (): ToolBase<
if (params.status !== undefined) {
body['status'] = params.status
}
+ if (params.name !== undefined) {
+ body['name'] = params.name
+ }
+ if (params.description !== undefined) {
+ body['description'] = params.description
+ }
const result = await context.api.request<Schemas.CustomerTask>({
method: 'PATCH',
path: `/api/projects/${encodeURIComponent(String(projectId))}/customer_tasks/${encodeURIComponent(String(params.id))}/`,