Merge pull request #746 from Django-CRM/dev

feat(tickets): implement bulk update and delete actions for tickets
This commit is contained in:
Ashwin Kumar 2026-08-12 08:06:51 +05:30 committed by GitHub
commit 799bb12102
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
14 changed files with 1809 additions and 89 deletions

View file

@ -1,5 +1,7 @@
"""Bulk update / bulk delete endpoints for the Cases module."""
import uuid
from django.core.exceptions import ValidationError
from django.db import transaction
from rest_framework import status
@ -7,6 +9,7 @@ from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from cases.access import has_case_write_access, is_org_admin
from cases.models import Case
from common.models import Activity, Profile, Tags
from common.permissions import HasOrgContext
@ -14,18 +17,69 @@ from common.permissions import HasOrgContext
ALLOWED_FIELDS = {"status", "priority", "case_type", "closed_on"}
ALLOWED_M2M = {"assigned_to": Profile, "tags": Tags}
# Scalar fields whose value must be one of the model's declared choices. A raw
# `setattr` + `save()` skips both DRF's ChoiceField and the model's `clean_fields`,
# so without this an authenticated caller could persist an off-enum status.
_CHOICE_FIELDS = ("status", "priority", "case_type")
def _valid_ids(raw):
"""Keep only the well-formed UUIDs from a client-supplied `ids` list.
Case PKs are UUIDs, so `Case.objects.filter(pk__in=ids)` raises a
ValidationError (a 500) the moment the queryset is evaluated on a value
like "not-a-uuid". That evaluation happens in the bulk loops, outside any
try/except, so a single malformed id in the request body would crash the
whole call. A malformed id names no real case, so drop it here: this
matches how a well-formed-but-nonexistent or other-org id already produces
no result row rather than an error.
"""
ids = []
for value in raw if isinstance(raw, (list, tuple)) else []:
try:
ids.append(str(uuid.UUID(str(value))))
except (ValueError, TypeError, AttributeError):
continue
return ids
def _close_gate_outcome(case_id, exc):
"""Map a `Case.clean()` ValidationError to a per-record outcome.
Keyed on the message dict's field name, not its text, so wording changes do
not move a ticket into the wrong bucket. `status` is the approval error,
`closed_on` is the missing-date error, anything else is a generic invalid.
"""
detail = (
exc.message_dict if hasattr(exc, "message_dict") else {"error": exc.messages}
)
if "status" in detail:
return {
"id": case_id,
"status": "approval_required",
"detail": detail["status"],
}
if "closed_on" in detail:
return {"id": case_id, "status": "closed_on_required"}
return {"id": case_id, "status": "invalid", "detail": detail}
class BulkUpdateCasesView(APIView):
permission_classes = (IsAuthenticated, HasOrgContext)
def post(self, request):
ids = request.data.get("ids") or []
ids = _valid_ids(request.data.get("ids"))
fields = request.data.get("fields") or {}
if not ids:
return Response(
{"error": True, "errors": "ids required"},
status=status.HTTP_400_BAD_REQUEST,
)
if not fields:
return Response(
{"error": True, "errors": "fields required"},
status=status.HTTP_400_BAD_REQUEST,
)
unknown = set(fields) - ALLOWED_FIELDS - set(ALLOWED_M2M)
if unknown:
@ -34,47 +88,91 @@ class BulkUpdateCasesView(APIView):
status=status.HTTP_400_BAD_REQUEST,
)
for field_name in _CHOICE_FIELDS:
if field_name not in fields:
continue
value = fields[field_name]
model_field = Case._meta.get_field(field_name)
valid_values = {choice for choice, _ in model_field.choices}
# `value in valid_values` would raise TypeError (500) on an
# unhashable payload like `{"status": ["Closed"]}`, so gate the
# membership test on a string first: a list/dict/number is simply
# an invalid value and gets the clean 400.
if isinstance(value, str) and value in valid_values:
continue
if value is None and model_field.null:
continue
return Response(
{"error": True, "errors": f"Invalid value for '{field_name}'"},
status=status.HTTP_400_BAD_REQUEST,
)
# `closed_on` is a scalar date, not a choice field, so it skips the loop
# above. A non-string payload would setattr onto the model and blow up at
# `save()` as a DB error (500). Reject it here with the same clean 400.
if "closed_on" in fields:
closed_on = fields["closed_on"]
if closed_on is not None and not isinstance(closed_on, str):
return Response(
{"error": True, "errors": "Invalid value for 'closed_on'"},
status=status.HTTP_400_BAD_REQUEST,
)
scalar_updates = {k: v for k, v in fields.items() if k in ALLOWED_FIELDS}
m2m_updates = {k: v for k, v in fields.items() if k in ALLOWED_M2M}
org = request.profile.org
qs = Case.objects.filter(pk__in=ids, org=org)
try:
with transaction.atomic():
updated_count = 0
for case in qs:
changed = False
results = []
updated_count = 0
for case in Case.objects.filter(pk__in=ids, org=org):
# Per-case authorization, mirroring the single-case PUT path
# (`CaseDetailView.put` calls `assert_case_write_access`). Without
# this any org member could edit, reassign or close any case in
# the org. Cases the caller may not write are reported as
# `no_access` rather than silently skipped, so the caller can see
# which of their selected tickets were denied.
if not has_case_write_access(request.profile, case):
results.append({"id": str(case.pk), "status": "no_access"})
continue
try:
# A savepoint per case, so a blocked close rolls back only
# itself and the rest of the batch still commits.
with transaction.atomic():
for k, v in scalar_updates.items():
setattr(case, k, v)
changed = True
if changed:
if scalar_updates:
# `Case.clean()` carries the close-transition guard: a
# `closed_on` is required and, where a pre_close
# ApprovalRule matches, a recorded approval is too. A
# raw `save()` skips it, which is how the bulk path
# let a case be closed with no approval; the
# single-case path runs the same rule through the
# serializer.
case.clean()
case.save()
for m2m_field, model in ALLOWED_M2M.items():
if m2m_field in m2m_updates:
related_ids = m2m_updates[m2m_field] or []
related = list(
model.objects.filter(pk__in=related_ids, org=org)
)
getattr(case, m2m_field).set(related)
changed = True
if changed:
updated_count += 1
except ValidationError as exc:
return Response(
{
"error": True,
"errors": (
exc.message_dict
if hasattr(exc, "message_dict")
else exc.messages
),
},
status=status.HTTP_400_BAD_REQUEST,
)
if m2m_field not in m2m_updates:
continue
related_ids = m2m_updates[m2m_field] or []
related = list(
model.objects.filter(pk__in=related_ids, org=org)
)
manager = getattr(case, m2m_field)
if m2m_field == "tags":
# Append: bulk-tagging must not wipe a ticket's
# other tags. Reassign (`assigned_to`) still
# replaces.
manager.add(*related)
else:
manager.set(related)
except ValidationError as exc:
results.append(_close_gate_outcome(str(case.pk), exc))
continue
results.append({"id": str(case.pk), "status": "updated"})
updated_count += 1
return Response(
{"error": False, "updated": updated_count},
{"error": False, "updated": updated_count, "results": results},
status=status.HTTP_200_OK,
)
@ -83,34 +181,50 @@ class BulkDeleteCasesView(APIView):
permission_classes = (IsAuthenticated, HasOrgContext)
def post(self, request):
ids = request.data.get("ids") or []
ids = _valid_ids(request.data.get("ids"))
if not ids:
return Response(
{"error": True, "errors": "ids required"},
status=status.HTTP_400_BAD_REQUEST,
)
org = request.profile.org
# Snapshot the cases so we can emit Activity rows after the bulk update
# ; queryset.update() bypasses signals.
qs = Case.objects.filter(pk__in=ids, org=org, is_active=True)
target_cases = list(qs.values("id", "name"))
deleted_count = qs.update(is_active=False)
if target_cases:
admin = is_org_admin(request.profile)
results = []
deletable = []
# Deleting is admin-or-creator only (`assert_case_delete_access`); an
# assignee may work a ticket but not erase it.
for row in Case.objects.filter(pk__in=ids, org=org, is_active=True).values(
"id", "name", "created_by_id"
):
if admin or row["created_by_id"] == request.profile.user_id:
deletable.append(row)
else:
results.append({"id": str(row["id"]), "status": "no_access"})
deleted_count = 0
if deletable:
deleted_count = Case.objects.filter(
id__in=[row["id"] for row in deletable]
).update(is_active=False)
# queryset.update() bypasses signals, so emit Activity rows here.
Activity.objects.bulk_create(
[
Activity(
user=request.profile,
action="DELETE",
entity_type="Case",
entity_id=case["id"],
entity_name=(case["name"] or "")[:255],
entity_id=row["id"],
entity_name=(row["name"] or "")[:255],
metadata={"bulk": True},
org_id=org.id,
)
for case in target_cases
for row in deletable
]
)
for row in deletable:
results.append({"id": str(row["id"]), "status": "deleted"})
return Response(
{"error": False, "deleted": deleted_count},
{"error": False, "deleted": deleted_count, "results": results},
status=status.HTTP_200_OK,
)

View file

@ -2,6 +2,8 @@
import pytest
from cases.approvals import ApprovalRule
from cases.models import Case
from conftest import rls_org
@ -65,6 +67,237 @@ class TestBulkUpdateCases:
)
assert response.status_code == 400
def test_bulk_update_rejects_off_enum_status(self, admin_client, case_a):
response = admin_client.post(
"/api/cases/bulk/update/",
{"ids": [str(case_a.pk)], "fields": {"status": "Hacked"}},
content_type="application/json",
)
assert response.status_code == 400
case_a.refresh_from_db()
assert case_a.status == "New"
def test_bulk_update_rejects_nonstring_choice_value(self, admin_client, case_a):
# A crafted unhashable payload must be a clean 400, not a 500 from
# `value in valid_values` raising TypeError on a list.
response = admin_client.post(
"/api/cases/bulk/update/",
{"ids": [str(case_a.pk)], "fields": {"status": ["Closed"]}},
content_type="application/json",
)
assert response.status_code == 400
case_a.refresh_from_db()
assert case_a.status == "New"
def test_bulk_update_rejects_nonstring_closed_on(self, admin_client, case_a):
# `closed_on` is a scalar date; a non-string payload must 400 here rather
# than reach `save()` and surface as a 500 DB error.
response = admin_client.post(
"/api/cases/bulk/update/",
{
"ids": [str(case_a.pk)],
"fields": {"status": "Closed", "closed_on": ["2026-05-09"]},
},
content_type="application/json",
)
assert response.status_code == 400
case_a.refresh_from_db()
assert case_a.status == "New"
def test_bulk_update_malformed_id_is_not_500(self, admin_client):
# A malformed UUID in `ids` must not crash the query. It names no real
# case, so it drops out and the request reads as "no valid ids" (400),
# never a 500 from `pk__in` raising ValidationError.
response = admin_client.post(
"/api/cases/bulk/update/",
{"ids": ["not-a-uuid"], "fields": {"status": "Pending"}},
content_type="application/json",
)
assert response.status_code == 400
def test_bulk_update_drops_malformed_id_keeps_valid(self, admin_client, case_a):
# A mix of one good and one malformed id processes the good one and
# silently ignores the garbage, matching how a nonexistent id behaves.
response = admin_client.post(
"/api/cases/bulk/update/",
{
"ids": [str(case_a.pk), "not-a-uuid"],
"fields": {"priority": "Urgent"},
},
content_type="application/json",
)
assert response.status_code == 200
assert response.json()["updated"] == 1
case_a.refresh_from_db()
assert case_a.priority == "Urgent"
@pytest.mark.django_db
class TestBulkUpdateCasesAuthz:
"""A regular member may only bulk-edit cases they may write."""
def test_non_writer_cannot_modify(self, user_client, case_a):
# `case_a` was created by admin_user; the regular member is neither its
# creator nor an assignee, so it must be left untouched.
response = user_client.post(
"/api/cases/bulk/update/",
{"ids": [str(case_a.pk)], "fields": {"priority": "Urgent"}},
content_type="application/json",
)
assert response.status_code == 200
assert response.json()["updated"] == 0
case_a.refresh_from_db()
assert case_a.priority == "High"
def test_creator_can_modify_own_case(self, user_client, regular_user, org_a):
case = Case.objects.create(
name="My own case",
status="New",
priority="Low",
created_by=regular_user,
org=org_a,
)
response = user_client.post(
"/api/cases/bulk/update/",
{"ids": [str(case.pk)], "fields": {"priority": "Urgent"}},
content_type="application/json",
)
assert response.status_code == 200
assert response.json()["updated"] == 1
case.refresh_from_db()
assert case.priority == "Urgent"
@pytest.mark.django_db
class TestBulkUpdateCasesCloseGate:
"""Closing through the bulk path runs the same guard as the single case."""
def test_close_requires_closed_on(self, admin_client, case_a):
# Per-record outcomes mean a blocked close is now a 200 with a
# `closed_on_required` outcome for this ticket, not a request-level
# 400: see `TestBulkUpdatePerRecord.test_close_missing_date`.
response = admin_client.post(
"/api/cases/bulk/update/",
{"ids": [str(case_a.pk)], "fields": {"status": "Closed"}},
content_type="application/json",
)
assert response.status_code == 200
body = response.json()
assert body["updated"] == 0
assert body["results"][0]["status"] == "closed_on_required"
case_a.refresh_from_db()
assert case_a.status == "New"
def test_close_requires_approval_when_rule_matches(
self, admin_client, case_a, org_a
):
# A rule with no match filters applies to every case in the org. Per-
# record outcomes mean this is now a 200 with an `approval_required`
# outcome, not a request-level 400: see
# `TestBulkUpdatePerRecord.test_close_blocked_is_partial`.
ApprovalRule.objects.create(
name="Close gate",
org=org_a,
trigger_event="pre_close",
is_active=True,
)
response = admin_client.post(
"/api/cases/bulk/update/",
{
"ids": [str(case_a.pk)],
"fields": {"status": "Closed", "closed_on": "2026-05-09"},
},
content_type="application/json",
)
assert response.status_code == 200
body = response.json()
assert body["updated"] == 0
assert body["results"][0]["status"] == "approval_required"
case_a.refresh_from_db()
assert case_a.status == "New"
@pytest.mark.django_db
class TestBulkUpdatePerRecord:
def test_mixed_access_reports_both(self, user_client, regular_user, org_a, case_a):
# `case_a` was created by admin_user, so the regular member cannot write
# it. A case they own can be written.
mine = Case.objects.create(
name="Mine",
status="New",
priority="Low",
created_by=regular_user,
org=org_a,
)
response = user_client.post(
"/api/cases/bulk/update/",
{"ids": [str(mine.pk), str(case_a.pk)], "fields": {"priority": "Urgent"}},
content_type="application/json",
)
assert response.status_code == 200
body = response.json()
assert body["updated"] == 1
by_id = {r["id"]: r["status"] for r in body["results"]}
assert by_id[str(mine.pk)] == "updated"
assert by_id[str(case_a.pk)] == "no_access"
def test_close_blocked_is_partial(
self, admin_client, org_a, case_a, case_b_same_org
):
ApprovalRule.objects.create(
name="Close gate", org=org_a, trigger_event="pre_close", is_active=True
)
# A rule with no match filters applies to every case, so both closes are
# gated; both come back approval_required and neither is closed.
response = admin_client.post(
"/api/cases/bulk/update/",
{
"ids": [str(case_a.pk), str(case_b_same_org.pk)],
"fields": {"status": "Closed", "closed_on": "2026-05-09"},
},
content_type="application/json",
)
assert response.status_code == 200
body = response.json()
assert body["updated"] == 0
assert {r["status"] for r in body["results"]} == {"approval_required"}
case_a.refresh_from_db()
assert case_a.status == "New"
def test_close_missing_date(self, admin_client, case_a):
response = admin_client.post(
"/api/cases/bulk/update/",
{"ids": [str(case_a.pk)], "fields": {"status": "Closed"}},
content_type="application/json",
)
assert response.status_code == 200
body = response.json()
assert body["results"][0]["status"] == "closed_on_required"
assert body["updated"] == 0
def test_tags_append_not_replace(self, admin_client, org_a, case_a):
from common.models import Tags
keep = Tags.objects.create(name="keep", org=org_a)
add = Tags.objects.create(name="add", org=org_a)
case_a.tags.add(keep)
response = admin_client.post(
"/api/cases/bulk/update/",
{"ids": [str(case_a.pk)], "fields": {"tags": [str(add.pk)]}},
content_type="application/json",
)
assert response.status_code == 200
case_a.refresh_from_db()
assert set(case_a.tags.values_list("name", flat=True)) == {"keep", "add"}
def test_empty_fields_rejected(self, admin_client, case_a):
response = admin_client.post(
"/api/cases/bulk/update/",
{"ids": [str(case_a.pk)], "fields": {}},
content_type="application/json",
)
assert response.status_code == 400
@pytest.mark.django_db
class TestBulkDeleteCases:
@ -102,3 +335,74 @@ class TestBulkDeleteCases:
content_type="application/json",
)
assert response.status_code == 400
def test_bulk_delete_malformed_id_is_not_500(self, admin_client):
# Same malformed-id guard as bulk update: a bad UUID must 400, never
# 500 from the queryset raising ValidationError on `pk__in`.
response = admin_client.post(
"/api/cases/bulk/delete/",
{"ids": ["not-a-uuid"]},
content_type="application/json",
)
assert response.status_code == 400
@pytest.mark.django_db
class TestBulkDeleteCasesAuthz:
"""Deleting is admin-or-creator only; an assignee is not enough."""
def test_non_creator_cannot_delete(self, user_client, case_a):
response = user_client.post(
"/api/cases/bulk/delete/",
{"ids": [str(case_a.pk)]},
content_type="application/json",
)
assert response.status_code == 200
assert response.json()["deleted"] == 0
case_a.refresh_from_db()
assert case_a.is_active is True
def test_creator_can_delete_own_case(self, user_client, regular_user, org_a):
case = Case.objects.create(
name="My own case",
status="New",
priority="Low",
created_by=regular_user,
org=org_a,
)
response = user_client.post(
"/api/cases/bulk/delete/",
{"ids": [str(case.pk)]},
content_type="application/json",
)
assert response.status_code == 200
assert response.json()["deleted"] == 1
case.refresh_from_db()
assert case.is_active is False
@pytest.mark.django_db
class TestBulkDeletePerRecord:
def test_reports_deleted_and_no_access(
self, user_client, regular_user, org_a, case_a
):
mine = Case.objects.create(
name="Mine",
status="New",
priority="Low",
created_by=regular_user,
org=org_a,
)
response = user_client.post(
"/api/cases/bulk/delete/",
{"ids": [str(mine.pk), str(case_a.pk)]},
content_type="application/json",
)
assert response.status_code == 200
body = response.json()
assert body["deleted"] == 1
by_id = {r["id"]: r["status"] for r in body["results"]}
assert by_id[str(mine.pk)] == "deleted"
assert by_id[str(case_a.pk)] == "no_access"
case_a.refresh_from_db()
assert case_a.is_active is True

View file

@ -0,0 +1,21 @@
export const M2M_FIELDS = new Set(['assigned_to', 'tags']);
/**
* Turn the bulk form into { ids, fields }. `field` names which field to set;
* `value` is repeatable, so an m2m field arrives as an array and a scalar as a
* single string. A Close also carries `closed_on`.
* @param {FormData} formData
*/
export function parseBulkForm(formData) {
const ids = formData.getAll('ids').map(String);
const field = String(formData.get('field') ?? '');
const values = formData.getAll('value').map(String);
/** @type {Record<string, any>} */
const fields = {};
if (field) {
fields[field] = M2M_FIELDS.has(field) ? values : (values[0] ?? '');
}
const closedOn = formData.get('closed_on');
if (closedOn) fields.closed_on = String(closedOn);
return { ids, fields };
}

View file

@ -0,0 +1,26 @@
import { describe, it, expect } from 'vitest';
import { summarizeBulk } from '$lib/server/v2/tickets.js';
describe('summarizeBulk', () => {
it('counts each outcome status', () => {
const s = summarizeBulk([
{ id: '1', status: 'updated' },
{ id: '2', status: 'updated' },
{ id: '3', status: 'no_access' },
{ id: '4', status: 'approval_required' },
{ id: '5', status: 'closed_on_required' },
{ id: '6', status: 'invalid' }
]);
expect(s.updated).toBe(2);
expect(s.no_access).toBe(1);
expect(s.approval_required).toBe(1);
expect(s.closed_on_required).toBe(1);
expect(s.invalid).toBe(1);
});
it('handles an empty list', () => {
const s = summarizeBulk([]);
expect(s.updated).toBe(0);
expect(s.no_access).toBe(0);
});
});

View file

@ -520,6 +520,54 @@ export async function replyToTicket({ cookies }, id, reply) {
);
}
/**
* Bulk-update tickets. `fields` is a subset of
* { status, priority, case_type, closed_on, assigned_to: string[], tags: string[] }.
* The backend enforces per-case write access and the close gate, so this only
* forwards; it never gates.
* @param {{ cookies: any }} evt
* @param {string[]} ids
* @param {Record<string, any>} fields
*/
export async function bulkUpdateTickets({ cookies }, ids, fields) {
return await apiRequest(
'/cases/bulk/update/',
{ method: 'POST', body: { ids, fields } },
{ cookies }
);
}
/**
* Bulk soft-delete tickets. Backend deletes only those the caller may delete
* (admin or creator) and reports the rest as no_access.
* @param {{ cookies: any }} evt
* @param {string[]} ids
*/
export async function bulkDeleteTickets({ cookies }, ids) {
return await apiRequest('/cases/bulk/delete/', { method: 'POST', body: { ids } }, { cookies });
}
/**
* Count a bulk `results` array by outcome status, for the summary banner.
* Each entry also carries an `id` and, on some outcomes, a `detail`; only
* `status` is read here.
* @param {Array<{status: string, [key: string]: any}>} results
*/
export function summarizeBulk(results) {
const out = {
updated: 0,
deleted: 0,
no_access: 0,
approval_required: 0,
closed_on_required: 0,
invalid: 0
};
for (const r of results ?? []) {
if (r.status in out) out[r.status] += 1;
}
return out;
}
/**
* `CaseDetailView.get` answers 404 for another org's ticket. Deliberately not
* 403, which would confirm the id exists, and 403 for a ticket inside the org

View file

@ -0,0 +1,153 @@
<script>
import { enhance } from '$app/forms';
import { CASE_STATUSES, CASE_PRIORITIES, CASE_TYPES } from '$lib/v2/enums.js';
/**
* @type {{
* ids: string[],
* people: {id:string,name:string}[],
* tags: {id:string,name:string}[],
* onclear: () => void,
* ondone: () => void
* }}
*/
let { ids, people, tags, onclear, ondone } = $props();
// Which action the agent picked in the menu. '' means the menu is showing.
let action = $state('');
// The status select's live value, so the Close date field can appear the
// moment "Closed" is picked, before Apply is pressed. Starts blank so
// Apply cannot fire on an unmade choice.
let statusValue = $state('');
// Delete is a two-click confirm, armed by the first click. Kept separate
// from `action` so leaving and re-entering the delete branch through Back
// does not skip the confirm on the next attempt.
let armed = $state(false);
// Today, for the Close date default. yyyy-mm-dd.
const today = new Date().toISOString().slice(0, 10);
const ACTIONS = [
{ key: 'assigned_to', label: 'Reassign' },
{ key: 'priority', label: 'Set priority' },
{ key: 'status', label: 'Set status' },
{ key: 'case_type', label: 'Set type' },
{ key: 'tags', label: 'Add tags' },
{ key: 'delete', label: 'Delete' }
];
function reset() {
action = '';
armed = false;
ondone();
}
</script>
<div class="v2-bulkbar" role="region" aria-label="Bulk actions">
<span class="v2-num">{ids.length} selected</span>
<button type="button" class="v2-btn" onclick={onclear}>Clear</button>
{#if action === ''}
<select class="v2-input" bind:value={action} aria-label="Choose a bulk action">
<option value="">Actions</option>
{#each ACTIONS as a (a.key)}
<option value={a.key}>{a.label}</option>
{/each}
</select>
{:else if action === 'delete'}
<form
method="POST"
action="?/bulkDelete"
use:enhance={() =>
async ({ update }) => {
await update({ reset: false });
reset();
}}
>
{#each ids as id (id)}<input type="hidden" name="ids" value={id} />{/each}
{#if !armed}
<button type="button" class="v2-btn" onclick={() => (armed = true)}>
Delete {ids.length}
</button>
{:else}
<button type="submit" class="v2-btn v2-btn-primary">Confirm</button>
<button type="button" class="v2-btn" onclick={() => (armed = false)}>Cancel</button>
{/if}
<button type="button" class="v2-btn" onclick={() => ((action = ''), (armed = false))}>
Back
</button>
</form>
{:else}
<form
method="POST"
action="?/bulkUpdate"
use:enhance={() =>
async ({ update }) => {
await update({ reset: false });
reset();
}}
>
{#each ids as id (id)}<input type="hidden" name="ids" value={id} />{/each}
<input type="hidden" name="field" value={action} />
{#if action === 'assigned_to'}
<select class="v2-input" name="value" required>
<option value="">Choose a person</option>
{#each people as p (p.id)}<option value={p.id}>{p.name}</option>{/each}
</select>
{:else if action === 'tags'}
<select class="v2-input" name="value" multiple required>
{#each tags as t (t.id)}<option value={t.id}>{t.name}</option>{/each}
</select>
{:else if action === 'priority'}
<select class="v2-input" name="value" required>
<option value="">Choose a priority</option>
{#each CASE_PRIORITIES as v (v)}<option value={v}>{v}</option>{/each}
</select>
{:else if action === 'case_type'}
<select class="v2-input" name="value" required>
<option value="">Choose a type</option>
{#each CASE_TYPES as v (v)}<option value={v}>{v}</option>{/each}
</select>
{:else if action === 'status'}
<select class="v2-input" name="value" bind:value={statusValue} required>
<option value="">Choose a status</option>
{#each CASE_STATUSES as v (v)}<option value={v}>{v}</option>{/each}
</select>
{#if statusValue === 'Closed'}
<input class="v2-input" type="date" name="closed_on" value={today} required />
{/if}
{/if}
<button type="submit" class="v2-btn v2-btn-primary">Apply</button>
<button type="button" class="v2-btn" onclick={() => (action = '')}>Back</button>
</form>
{/if}
</div>
<style>
.v2-bulkbar {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
padding: 10px 12px;
border: 1px solid var(--v2-line);
border-radius: 10px;
background: var(--v2-card);
}
/* Phone: dock above the tab bar, full width, comfortable tap targets. */
@media (max-width: 768px) {
.v2-bulkbar {
position: fixed;
left: 8px;
right: 8px;
bottom: calc(var(--v2-tabbar-h, 56px) + 8px);
z-index: 40;
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.12);
}
.v2-bulkbar :global(.v2-btn),
.v2-bulkbar .v2-input {
min-height: 44px;
}
}
</style>

View file

@ -1,7 +1,16 @@
import { listTickets, OPEN_STATUSES, FILTER_FIELDS } from '$lib/server/v2/tickets.js';
import { fail } from '@sveltejs/kit';
import {
listTickets,
OPEN_STATUSES,
FILTER_FIELDS,
bulkUpdateTickets,
bulkDeleteTickets,
summarizeBulk
} from '$lib/server/v2/tickets.js';
import { readFilters, buildFilterQuery } from '$lib/server/v2/filter-params.js';
import { getOrgPeopleAndTeams, resolveMe } from '$lib/server/v2/org-people.js';
import { getTags } from '$lib/server/v2/tags.js';
import { parseBulkForm } from '$lib/server/v2/bulk-form.js';
/**
* Only filters the API actually applies are forwarded. A parameter that
@ -56,3 +65,18 @@ export async function load({ cookies, url, locals }) {
meId: resolveMe(orgPeople.people, /** @type {any} */ (locals).user?.email)
};
}
export const actions = {
bulkUpdate: async ({ request, cookies }) => {
const { ids, fields } = parseBulkForm(await request.formData());
if (ids.length === 0) return fail(400, { message: 'Select at least one ticket.' });
const res = await bulkUpdateTickets({ cookies }, ids, fields);
return { ok: true, kind: 'update', summary: summarizeBulk(res.results) };
},
bulkDelete: async ({ request, cookies }) => {
const ids = (await request.formData()).getAll('ids').map(String);
if (ids.length === 0) return fail(400, { message: 'Select at least one ticket.' });
const res = await bulkDeleteTickets({ cookies }, ids);
return { ok: true, kind: 'delete', summary: summarizeBulk(res.results) };
}
};

View file

@ -1,12 +1,15 @@
<script>
import { resolve } from '$app/paths';
import { page } from '$app/state';
import { invalidateAll } from '$app/navigation';
import { SvelteSet } from 'svelte/reactivity';
import PageHeader from '$lib/v2/components/PageHeader.svelte';
import SectionTabs from '$lib/v2/components/SectionTabs.svelte';
import FilterBar from '$lib/v2/components/FilterBar.svelte';
import Pill from '$lib/v2/components/Pill.svelte';
import Avatar from '$lib/v2/components/Avatar.svelte';
import EmptyState from '$lib/v2/components/EmptyState.svelte';
import BulkActionBar from '$lib/v2/components/BulkActionBar.svelte';
import { count, shortAge } from '$lib/v2/format.js';
import { PRIORITY_TONE, CASE_STATUS_TONE } from '$lib/v2/enums.js';
import { Plus, LifeBuoy } from '@lucide/svelte';
@ -17,6 +20,40 @@
let tickets = $derived(data.tickets);
let totals = $derived(data.totals);
// Bulk selection: loaded rows only, never the whole filtered set. SvelteSet
// is reactive on mutation, so add/delete/clear below re-render without
// reassigning the whole set.
let selected = new SvelteSet();
let banner = $state('');
/** @param {string} id */
function toggle(id) {
if (selected.has(id)) selected.delete(id);
else selected.add(id);
}
function toggleAll() {
if (selected.size === tickets.length) {
selected.clear();
} else {
selected.clear();
for (const t of tickets) selected.add(t.id);
}
}
/**
* @param {'update'|'delete'} kind
* @param {Record<string, number>} s
*/
function summaryText(kind, s) {
const parts = [
`${kind === 'delete' ? s.deleted : s.updated} ${kind === 'delete' ? 'deleted' : 'updated'}`
];
if (s.no_access) parts.push(`${s.no_access} skipped (no access)`);
if (s.approval_required) parts.push(`${s.approval_required} need approval`);
if (s.closed_on_required) parts.push(`${s.closed_on_required} missing close date`);
if (s.invalid) parts.push(`${s.invalid} invalid`);
return parts.join(' · ');
}
/**
* How the first-reply clock stands.
*
@ -97,6 +134,25 @@
which one you are on. -->
<SectionTabs set="tickets" />
{#if banner}
<p class="v2-sub" style="font-size:12px;margin:8px 0 0">{banner}</p>
{/if}
{#if selected.size > 0}
<BulkActionBar
ids={[...selected]}
people={data.people}
tags={data.tags}
onclear={() => selected.clear()}
ondone={async () => {
// The form action returned; show its summary, refresh, clear selection.
const r = page.form;
if (r?.ok) banner = summaryText(r.kind, r.summary);
selected.clear();
await invalidateAll();
}}
/>
{/if}
<FilterBar
page="tickets"
url={page.url}
@ -129,6 +185,14 @@
<table class="v2-table">
<thead>
<tr>
<th style="width:34px">
<input
type="checkbox"
aria-label="Select all loaded"
checked={tickets.length > 0 && selected.size === tickets.length}
onchange={toggleAll}
/>
</th>
<th>Subject</th>
<th>Priority</th>
<th>Status</th>
@ -143,6 +207,14 @@
{#each tickets as t (t.id)}
{@const p = responsePressure(t)}
<tr>
<td data-m="lead">
<input
type="checkbox"
aria-label="Select ticket"
checked={selected.has(t.id)}
onchange={() => toggle(t.id)}
/>
</td>
<td data-m="title">
<a class="v2-row-link" href={resolve(`/tickets/${t.id}`)}>
<span class="v2-table-primary">{t.name}</span>

View file

@ -0,0 +1,47 @@
import { describe, it, expect } from 'vitest';
import { parseBulkForm } from '$lib/server/v2/bulk-form.js';
function fd(entries) {
const f = new FormData();
for (const [k, v] of entries) f.append(k, v);
return f;
}
describe('parseBulkForm', () => {
it('reads ids and a scalar field', () => {
const { ids, fields } = parseBulkForm(
fd([
['ids', 'a'],
['ids', 'b'],
['field', 'priority'],
['value', 'Urgent']
])
);
expect(ids).toEqual(['a', 'b']);
expect(fields).toEqual({ priority: 'Urgent' });
});
it('reads a Close with a date', () => {
const { fields } = parseBulkForm(
fd([
['ids', 'a'],
['field', 'status'],
['value', 'Closed'],
['closed_on', '2026-05-09']
])
);
expect(fields).toEqual({ status: 'Closed', closed_on: '2026-05-09' });
});
it('reads a multi-value m2m field', () => {
const { fields } = parseBulkForm(
fd([
['ids', 'a'],
['field', 'tags'],
['value', 't1'],
['value', 't2']
])
);
expect(fields).toEqual({ tags: ['t1', 't2'] });
});
});

View file

@ -10,7 +10,7 @@ class ApiConfig {
// ==========================================================================
/// Development API URL
static const String _developmentUrl = 'https://pc-8000.rcdev.in';
static const String _developmentUrl = 'https://pc-8004.rcdev.in';
/// Production API URL
static const String _productionUrl = 'https://api.bottlecrm.io';
@ -249,6 +249,15 @@ class ApiConfig {
/// Tickets (support tickets) management
static String get tickets => '$apiBaseUrl/cases/';
/// Bulk-update selected tickets: POST `{ids, fields}`. Backend answers a
/// per-record results envelope (`{error, updated, results}`), not a single
/// ticket, so callers must not treat this like `updateTicket`.
static String get casesBulkUpdate => '$apiBaseUrl/cases/bulk/update/';
/// Bulk-delete selected tickets: POST `{ids}`. Same per-record envelope
/// shape as [casesBulkUpdate], with `deleted` in place of `updated`.
static String get casesBulkDelete => '$apiBaseUrl/cases/bulk/delete/';
/// BottleCRM product support tickets opened by the signed-in user.
static String get supportTickets => '$apiBaseUrl/support/';

View file

@ -548,6 +548,44 @@ class TicketsNotifier extends AsyncNotifier<TicketsListData> {
}
}
/// Bulk-update the given tickets in one call. `fields` is applied
/// server-side: `tags` appends to each ticket's existing tags, `assigned_to`
/// replaces them, and every other field is a plain overwrite.
///
/// Returns the raw `{error, updated, results}` envelope untouched. This
/// layer does not summarize it or refresh local state; the caller (the
/// bulk-actions UI) does both, since it also owns the current selection.
Future<ApiResponse<Map<String, dynamic>>> bulkUpdate(
List<String> ids,
Map<String, dynamic> fields,
) async {
try {
return await _apiService.post(ApiConfig.casesBulkUpdate, {
'ids': ids,
'fields': fields,
});
} catch (e) {
return ApiResponse(success: false, message: e.toString(), statusCode: 0);
}
}
/// Bulk-delete the given tickets in one call. Per-record authorization
/// (admin or creator) is enforced server-side, so a caller with no rights
/// on some of the ids gets those reported as failures in `results` rather
/// than the whole request being refused.
///
/// Returns the raw `{error, deleted, results}` envelope untouched, same as
/// [bulkUpdate].
Future<ApiResponse<Map<String, dynamic>>> bulkDelete(
List<String> ids,
) async {
try {
return await _apiService.post(ApiConfig.casesBulkDelete, {'ids': ids});
} catch (e) {
return ApiResponse(success: false, message: e.toString(), statusCode: 0);
}
}
Future<ApiResponse<Map<String, dynamic>>> deleteTicket(String id) async {
try {
final response = await _apiService.delete(ApiConfig.ticketDetail(id));

View file

@ -12,6 +12,7 @@ import '../../data/models/ticket.dart';
import '../../providers/lookup_provider.dart';
import '../../providers/tickets_provider.dart';
import '../../routes/app_router.dart';
import '../../services/api_service.dart';
import '../../widgets/cards/ticket_card.dart';
import '../../widgets/common/common.dart';
import '../../widgets/forms/multi_select_sheet.dart';
@ -33,6 +34,25 @@ class _TicketsListScreenState extends ConsumerState<TicketsListScreen> {
TicketListFilters _filters = const TicketListFilters();
Timer? _searchDebounce;
// Selection mode, toggled from the app bar. `_selected` only ever holds ids
// of rows currently loaded in the list, there is no whole-filter selection.
bool _selectMode = false;
final Set<String> _selected = {};
// The six bulk actions, key first (matches the field name the backend
// reads, `delete` is handled separately) then the label shown in the sheet.
// Same keys and order as the web bulk bar's ACTIONS in
// frontend/src/lib/v2/components/BulkActionBar.svelte, so a screenshot from
// either client describes the same menu.
static const List<(String key, String label)> _bulkActionOptions = [
('assigned_to', 'Reassign'),
('priority', 'Set priority'),
('status', 'Set status'),
('case_type', 'Set type'),
('tags', 'Add tags'),
('delete', 'Delete'),
];
@override
void initState() {
super.initState();
@ -124,28 +144,41 @@ class _TicketsListScreenState extends ConsumerState<TicketsListScreen> {
backgroundColor: AppColors.surface,
elevation: 0,
scrolledUnderElevation: 1,
actions: [
IconButton(
tooltip: 'Analytics',
icon: const Icon(LucideIcons.barChart3),
onPressed: () => context.push(AppRoutes.ticketAnalytics),
),
IconButton(
tooltip: 'Approvals',
icon: const Icon(LucideIcons.shieldCheck),
onPressed: () => context.push(AppRoutes.approvalsInbox),
),
IconButton(
tooltip: 'Knowledge base',
icon: const Icon(LucideIcons.bookOpen),
onPressed: () => context.push(AppRoutes.solutions),
),
IconButton(
tooltip: 'New ticket',
icon: const Icon(LucideIcons.plus),
onPressed: () => context.push(AppRoutes.ticketCreate),
),
],
actions: _selectMode
? [
IconButton(
tooltip: 'Cancel selection',
icon: const Icon(LucideIcons.x),
onPressed: _exitSelectMode,
),
]
: [
IconButton(
tooltip: 'Select tickets',
icon: const Icon(LucideIcons.checkSquare),
onPressed: _enterSelectMode,
),
IconButton(
tooltip: 'Analytics',
icon: const Icon(LucideIcons.barChart3),
onPressed: () => context.push(AppRoutes.ticketAnalytics),
),
IconButton(
tooltip: 'Approvals',
icon: const Icon(LucideIcons.shieldCheck),
onPressed: () => context.push(AppRoutes.approvalsInbox),
),
IconButton(
tooltip: 'Knowledge base',
icon: const Icon(LucideIcons.bookOpen),
onPressed: () => context.push(AppRoutes.solutions),
),
IconButton(
tooltip: 'New ticket',
icon: const Icon(LucideIcons.plus),
onPressed: () => context.push(AppRoutes.ticketCreate),
),
],
),
body: Column(
children: [
@ -160,6 +193,7 @@ class _TicketsListScreenState extends ConsumerState<TicketsListScreen> {
Expanded(child: _buildList(ticketsAsync, tickets)),
],
),
bottomNavigationBar: _selected.isEmpty ? null : _buildBulkBar(),
);
}
@ -299,15 +333,466 @@ class _TicketsListScreenState extends ConsumerState<TicketsListScreen> {
);
}
final ticketItem = tickets[index];
return TicketCard(
ticketItem: ticketItem,
onTap: () => context.push('/tickets/${ticketItem.id}'),
);
return _buildTicketRow(ticketItem);
},
),
);
}
/// A single row in the list. Gates the card's tap: in selection mode a tap
/// toggles the row instead of pushing the detail screen, and a checkbox
/// badge overlays its top-left corner to show the selected state.
///
/// The badge is a `Positioned` overlay in a `Stack`, not a leading column in
/// a `Row`, on purpose: TicketCard's own footer row (type, priority,
/// timestamp, assignee) already sits close to its overflow point at a
/// 390px phone width, and a Row that gives the card less than its full
/// width pushes that row over. TicketCard is out of scope for this change,
/// so the fix is to never narrow it: a `Positioned` child does not affect
/// how much space the `Stack` gives its non-positioned child.
Widget _buildTicketRow(Ticket ticketItem) {
final card = TicketCard(
ticketItem: ticketItem,
onTap: _selectMode
? () => _toggleSelected(ticketItem.id)
: () => context.push('/tickets/${ticketItem.id}'),
);
if (!_selectMode) return card;
final isSelected = _selected.contains(ticketItem.id);
return Stack(
children: [
card,
Positioned(
top: 6,
left: 6,
child: Container(
decoration: BoxDecoration(
color: AppColors.surface,
shape: BoxShape.circle,
border: Border.all(color: AppColors.border),
),
child: Checkbox(
value: isSelected,
onChanged: (_) => _toggleSelected(ticketItem.id),
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
visualDensity: VisualDensity.compact,
),
),
),
],
);
}
// ---------------------------------------------------------------------
// Selection mode
// ---------------------------------------------------------------------
void _enterSelectMode() {
setState(() => _selectMode = true);
}
void _exitSelectMode() {
setState(() {
_selectMode = false;
_selected.clear();
});
}
void _toggleSelected(String id) {
setState(() {
if (_selected.contains(id)) {
_selected.remove(id);
} else {
_selected.add(id);
}
});
}
/// Flat bar per DESIGN_SYSTEM.md: no elevation, a top border instead of a
/// shadow. Mirrors the Container-plus-SafeArea shape already used for
/// `deal_detail_screen.dart`'s sticky bottom bar.
Widget _buildBulkBar() {
return Container(
decoration: BoxDecoration(
color: AppColors.surface,
border: Border(top: BorderSide(color: AppColors.border)),
),
child: SafeArea(
child: Padding(
padding: const EdgeInsets.fromLTRB(16, 10, 12, 10),
child: Row(
children: [
Expanded(
child: Text(
'${_selected.length} selected',
style: AppTypography.label,
),
),
TextButton(
// Themed buttons carry an infinite minimum width, which a Row
// does not bound. Without this the row fails to lay out and
// the bar paints nothing. See AppLayout.buttonMinSizeInRow
// (already relied on by multi_select_sheet.dart).
style: TextButton.styleFrom(
minimumSize: AppLayout.buttonMinSizeInRow,
),
onPressed: () => setState(_selected.clear),
child: const Text('Clear'),
),
const SizedBox(width: 4),
FilledButton(
style: FilledButton.styleFrom(
minimumSize: AppLayout.buttonMinSizeInRow,
),
onPressed: _openActionsSheet,
child: const Text('Actions'),
),
],
),
),
),
);
}
Future<void> _openActionsSheet() async {
final action = await showModalBottomSheet<String>(
context: context,
backgroundColor: AppColors.surface,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
),
builder: (_) => SafeArea(
child: SingleChildScrollView(
// A short viewport (a phone in landscape, or a small split-screen
// window) can be shorter than six rows plus the handle and title.
// `showModalBottomSheet` without `isScrollControlled` already caps
// this sheet at 9/16 of the screen height, so scrolling here is the
// fallback for whatever doesn't fit inside that cap, not the
// primary way anyone reads a 6-item menu.
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
margin: const EdgeInsets.only(top: 8),
width: 32,
height: 4,
decoration: BoxDecoration(
color: AppColors.gray300,
borderRadius: BorderRadius.circular(2),
),
),
Padding(
padding: const EdgeInsets.all(12),
child: Text('Actions', style: AppTypography.label),
),
for (final option in _bulkActionOptions)
InkWell(
onTap: () => Navigator.pop(context, option.$1),
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 12,
),
child: Text(
option.$2,
style: AppTypography.body.copyWith(
color: option.$1 == 'delete'
? AppColors.danger600
: AppColors.textPrimary,
fontWeight: option.$1 == 'delete'
? FontWeight.w600
: FontWeight.normal,
),
),
),
),
const SizedBox(height: 12),
],
),
),
),
);
if (!mounted || action == null) return;
await _runBulkAction(action);
}
Future<void> _runBulkAction(String key) async {
switch (key) {
case 'assigned_to':
await _bulkReassign();
case 'priority':
await _bulkPickAndApply<TicketPriority>(
'Set priority',
TicketPriority.values,
(p) => p.value,
(p) => p.label,
'priority',
colorOf: (p) => p.color,
);
case 'status':
await _bulkSetStatus();
case 'case_type':
await _bulkPickAndApply<TicketType>(
'Set type',
TicketType.values,
(t) => t.value,
(t) => t.label,
'case_type',
);
case 'tags':
await _bulkAddTags();
case 'delete':
await _bulkDeleteConfirm();
}
}
/// Single-choice scalar field (priority, case type). Reuses the same
/// `_SimpleFilterSheet` / `_FilterRow` shape the existing filter pickers
/// use above: tapping a row applies immediately, there is no separate
/// Apply button, matching `_pickPriority` and `_pickCaseType`.
Future<void> _bulkPickAndApply<T>(
String title,
List<T> options,
String Function(T) valueOf,
String Function(T) labelOf,
String field, {
Color? Function(T)? colorOf,
}) async {
final picked = await showModalBottomSheet<T>(
context: context,
backgroundColor: AppColors.surface,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
),
builder: (_) => _SimpleFilterSheet(
title: title,
rows: [
for (final option in options)
_FilterRow(
label: labelOf(option),
isSelected: false,
color: colorOf?.call(option),
onTap: () => Navigator.pop(context, option),
),
],
),
);
if (picked == null) return;
await _applyBulkUpdate({field: valueOf(picked)});
}
/// Status is a scalar too, except Closed also needs `closed_on`. The date
/// picker defaults to today; the backend requires the key for a close and
/// gates it on any pre_close approval rule regardless of what is sent here.
Future<void> _bulkSetStatus() async {
final picked = await showModalBottomSheet<TicketStatus>(
context: context,
backgroundColor: AppColors.surface,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
),
builder: (_) => _SimpleFilterSheet(
title: 'Set status',
rows: [
for (final status in TicketStatus.values)
_FilterRow(
label: status.label,
isSelected: false,
onTap: () => Navigator.pop(context, status),
),
],
),
);
if (picked == null) return;
if (picked != TicketStatus.closed) {
await _applyBulkUpdate({'status': picked.value});
return;
}
if (!mounted) return;
final now = DateTime.now();
final date = await showDatePicker(
context: context,
initialDate: now,
firstDate: DateTime(2000),
lastDate: now.add(const Duration(days: 1)),
);
if (date == null) return;
await _applyBulkUpdate({'status': 'Closed', 'closed_on': _isoDate(date)});
}
String _isoDate(DateTime d) =>
'${d.year.toString().padLeft(4, '0')}-'
'${d.month.toString().padLeft(2, '0')}-'
'${d.day.toString().padLeft(2, '0')}';
/// `assigned_to` is many-to-many on the backend (it replaces the set), but
/// the picker here offers one person at a time, same as the web bulk bar's
/// single-select Reassign dropdown. The field still carries a list.
Future<void> _bulkReassign() async {
final users = ref.read(usersProvider);
final picked = await showModalBottomSheet<UserLookup>(
context: context,
backgroundColor: AppColors.surface,
isScrollControlled: true,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
),
builder: (_) => DraggableScrollableSheet(
initialChildSize: 0.6,
minChildSize: 0.3,
maxChildSize: 0.9,
expand: false,
builder: (ctx, controller) => Column(
children: [
Container(
margin: const EdgeInsets.only(top: 12),
width: 40,
height: 4,
decoration: BoxDecoration(
color: AppColors.gray300,
borderRadius: BorderRadius.circular(2),
),
),
Padding(
padding: const EdgeInsets.all(16),
child: Text('Reassign to', style: AppTypography.h3),
),
Expanded(
child: ListView.builder(
controller: controller,
itemCount: users.length,
itemBuilder: (_, i) {
final u = users[i];
return ListTile(
leading: UserAvatar(
name: u.displayName,
size: AvatarSize.xs,
),
title: Text(u.displayName),
onTap: () => Navigator.pop(context, u),
);
},
),
),
],
),
),
);
if (picked == null) return;
await _applyBulkUpdate({
'assigned_to': [picked.id],
});
}
/// `tags` is many-to-many and appends server-side, so a multi-select is
/// correct here (unlike Reassign, which replaces). Reuses the same
/// MultiSelectSheet the filter bar's tag picker already uses.
Future<void> _bulkAddTags() async {
final tags = ref.read(tagsProvider);
final result = await MultiSelectSheet.show<TagLookup>(
context: context,
title: 'Add tags',
items: tags,
initialSelection: const [],
labelOf: (t) => t.name,
searchText: (t) => t.name,
);
if (result == null || result.isEmpty) return;
await _applyBulkUpdate({'tags': result.map((t) => t.id).toList()});
}
Future<void> _bulkDeleteConfirm() async {
final ids = _selected.toList();
final confirmed = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: const Text('Delete tickets?'),
content: Text(
'Permanently delete ${ids.length} '
'ticket${ids.length == 1 ? '' : 's'}. This cannot be undone.',
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: const Text('Cancel'),
),
TextButton(
onPressed: () => Navigator.pop(context, true),
child: Text('Delete', style: TextStyle(color: AppColors.danger600)),
),
],
),
);
if (confirmed != true) return;
final response = await ref.read(ticketsProvider.notifier).bulkDelete(ids);
await _finishBulkAction(response, isDelete: true);
}
Future<void> _applyBulkUpdate(Map<String, dynamic> fields) async {
final ids = _selected.toList();
if (ids.isEmpty) return;
final response = await ref
.read(ticketsProvider.notifier)
.bulkUpdate(ids, fields);
await _finishBulkAction(response, isDelete: false);
}
Future<void> _finishBulkAction(
ApiResponse<Map<String, dynamic>> response, {
required bool isDelete,
}) async {
if (!mounted) return;
final text = response.success
? _bulkSummary(
(response.data?['results'] as List<dynamic>?) ?? const [],
isDelete: isDelete,
)
: (response.message ?? 'Bulk ${isDelete ? 'delete' : 'update'} failed');
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(text)));
setState(() {
_selected.clear();
_selectMode = false;
});
ref.read(ticketsProvider.notifier).refresh(filters: _filters);
}
/// Tallies `results` rows (`{'id':..., 'status':...}`) into the same
/// wording the web bulk bar shows. Mirrors `summarizeBulk` and
/// `summaryText` in frontend/src/lib/server/v2/tickets.js and
/// frontend/src/routes/(app)/tickets/+page.svelte: one headline count, then
/// a part per nonzero bucket, joined with " · ".
String _bulkSummary(List<dynamic> results, {required bool isDelete}) {
var updated = 0;
var deleted = 0;
var noAccess = 0;
var approvalRequired = 0;
var closedOnRequired = 0;
var invalid = 0;
for (final row in results) {
if (row is! Map) continue;
switch (row['status']) {
case 'updated':
updated++;
case 'deleted':
deleted++;
case 'no_access':
noAccess++;
case 'approval_required':
approvalRequired++;
case 'closed_on_required':
closedOnRequired++;
case 'invalid':
invalid++;
}
}
final parts = <String>[isDelete ? '$deleted deleted' : '$updated updated'];
if (noAccess > 0) parts.add('$noAccess skipped (no access)');
if (approvalRequired > 0) parts.add('$approvalRequired need approval');
if (closedOnRequired > 0) parts.add('$closedOnRequired missing close date');
if (invalid > 0) parts.add('$invalid invalid');
return parts.join(' · ');
}
Widget _buildSearchBar() {
return Container(
color: AppColors.surfaceDim,
@ -834,25 +1319,30 @@ class _SimpleFilterSheet extends StatelessWidget {
@override
Widget build(BuildContext context) {
return SafeArea(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
margin: const EdgeInsets.only(top: 8),
width: 32,
height: 4,
decoration: BoxDecoration(
color: AppColors.gray300,
borderRadius: BorderRadius.circular(2),
// Scrolls only if a short viewport (or the bulk-action lists this sheet
// now also serves, e.g. all six TicketStatus rows) doesn't fit under
// the 9/16-screen cap `showModalBottomSheet` applies by default.
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
margin: const EdgeInsets.only(top: 8),
width: 32,
height: 4,
decoration: BoxDecoration(
color: AppColors.gray300,
borderRadius: BorderRadius.circular(2),
),
),
),
Padding(
padding: const EdgeInsets.all(12),
child: Text(title, style: AppTypography.label),
),
...rows,
const SizedBox(height: 12),
],
Padding(
padding: const EdgeInsets.all(12),
child: Text(title, style: AppTypography.label),
),
...rows,
const SizedBox(height: 12),
],
),
),
);
}

View file

@ -0,0 +1,105 @@
import 'dart:convert';
import 'package:bottle_crm/config/api_config.dart';
import 'package:bottle_crm/providers/tickets_provider.dart';
import 'package:bottle_crm/services/api_service.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
/// Bulk ticket actions: mobile data layer only (the UI bulk bar is a later
/// task). Both methods must POST the raw request the backend expects and hand
/// the response envelope back untouched, so the UI task can summarize
/// `{error, updated/deleted, results}` for itself.
class RecordingClient extends http.BaseClient {
http.BaseRequest? request;
List<int>? requestBody;
Map<String, dynamic> responseBody = const {
'cases': [],
'cases_count': 0,
'offset': null,
};
int statusCode = 200;
@override
Future<http.StreamedResponse> send(http.BaseRequest incoming) async {
request = incoming;
requestBody = await incoming.finalize().toBytes();
return http.StreamedResponse(
Stream.value(utf8.encode(jsonEncode(responseBody))),
statusCode,
headers: {'content-type': 'application/json'},
request: incoming,
);
}
}
void main() {
late RecordingClient client;
late ProviderContainer container;
setUp(() async {
client = RecordingClient();
ApiService().setClientForTesting(client);
container = ProviderContainer();
// Let the list's own initial fetch (the provider's build()) settle
// before issuing a bulk call, so that GET cannot race the POST below on
// the shared RecordingClient.
await container.read(ticketsProvider.future);
});
tearDown(() {
container.dispose();
ApiService().clearAuth();
ApiService().setRefreshCallback(null);
ApiService().setClientForTesting(http.Client());
});
test('bulkUpdate posts ids and fields to the bulk update endpoint', () async {
client.responseBody = {
'error': false,
'updated': 2,
'results': [
{'id': 'a', 'success': true},
{'id': 'b', 'success': true},
],
};
final response = await container
.read(ticketsProvider.notifier)
.bulkUpdate(['a', 'b'], {'priority': 'Urgent'});
expect(client.request!.method, 'POST');
expect(client.request!.url.toString(), ApiConfig.casesBulkUpdate);
expect(jsonDecode(utf8.decode(client.requestBody!)), {
'ids': ['a', 'b'],
'fields': {'priority': 'Urgent'},
});
// The envelope comes back untouched: the UI task summarizes it, this
// layer does not.
expect(response.success, isTrue);
expect(response.data, client.responseBody);
});
test('bulkDelete posts ids to the bulk delete endpoint', () async {
client.responseBody = {
'error': false,
'deleted': 1,
'results': [
{'id': 'a', 'success': true},
],
};
final response = await container
.read(ticketsProvider.notifier)
.bulkDelete(['a']);
expect(client.request!.method, 'POST');
expect(client.request!.url.toString(), ApiConfig.casesBulkDelete);
expect(jsonDecode(utf8.decode(client.requestBody!)), {
'ids': ['a'],
});
expect(response.success, isTrue);
expect(response.data, client.responseBody);
});
}

View file

@ -0,0 +1,269 @@
import 'package:bottle_crm/core/theme/theme.dart';
import 'package:bottle_crm/data/models/ticket.dart';
import 'package:bottle_crm/providers/lookup_provider.dart';
import 'package:bottle_crm/providers/tickets_provider.dart';
import 'package:bottle_crm/screens/tickets/tickets_list_screen.dart';
import 'package:bottle_crm/services/api_service.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
/// Selection mode and the bulk action sheet on the tickets list, the mobile
/// counterpart to the web bulk bar (`frontend/src/lib/v2/components/BulkActionBar.svelte`).
///
/// The harness mirrors `test/screens/tasks/tasks_list_screen_test.dart` and
/// `test/screens/deals/deals_list_screen_test.dart`: a fake `TicketsNotifier`
/// subclass overrides `build` with canned data and records the bulk calls, so
/// the widget pumps with no live backend.
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('TicketsListScreen selection mode', () {
testWidgets('the app-bar toggle enters selection mode with a checkbox '
'per row', (tester) async {
final notifier = _FakeTicketsNotifier(
TicketsListData(
tickets: [_ticket(id: 't1', name: 'Login broken')],
totalCount: 1,
hasMore: false,
),
);
await tester.pumpWidget(_testApp(notifier));
await tester.pumpAndSettle();
expect(find.byType(Checkbox), findsNothing);
await tester.tap(find.byTooltip('Select tickets'));
await tester.pumpAndSettle();
expect(find.byType(Checkbox), findsOneWidget);
});
testWidgets('selecting a card and opening Actions lists all six bulk '
'actions', (tester) async {
final notifier = _FakeTicketsNotifier(
TicketsListData(
tickets: [_ticket(id: 't1', name: 'Login broken')],
totalCount: 1,
hasMore: false,
),
);
await tester.pumpWidget(_testApp(notifier));
await tester.pumpAndSettle();
await tester.tap(find.byTooltip('Select tickets'));
await tester.pumpAndSettle();
await tester.tap(find.byType(Checkbox).first);
await tester.pumpAndSettle();
expect(find.text('1 selected'), findsOneWidget);
await tester.tap(find.text('Actions'));
await tester.pumpAndSettle();
for (final label in [
'Reassign',
'Set priority',
'Set status',
'Set type',
'Add tags',
'Delete',
]) {
expect(find.text(label), findsOneWidget, reason: label);
}
});
testWidgets(
'Set priority, then Urgent, calls bulkUpdate with the selected id and '
'a scalar field, not a list',
(tester) async {
final notifier = _FakeTicketsNotifier(
TicketsListData(
tickets: [_ticket(id: 't1', name: 'Login broken')],
totalCount: 1,
hasMore: false,
),
);
await tester.pumpWidget(_testApp(notifier));
await tester.pumpAndSettle();
await tester.tap(find.byTooltip('Select tickets'));
await tester.pumpAndSettle();
await tester.tap(find.byType(Checkbox).first);
await tester.pumpAndSettle();
await tester.tap(find.text('Actions'));
await tester.pumpAndSettle();
await tester.tap(find.text('Set priority'));
await tester.pumpAndSettle();
await tester.tap(find.text('Urgent'));
await tester.pumpAndSettle();
expect(notifier.bulkUpdateCalls, hasLength(1));
expect(notifier.bulkUpdateCalls.single.ids, ['t1']);
expect(notifier.bulkUpdateCalls.single.fields, {'priority': 'Urgent'});
// The bar clears and the SnackBar reports the same wording the web
// bulk bar's summaryText() produces for one clean update.
expect(find.text('1 updated'), findsOneWidget);
expect(find.text('1 selected'), findsNothing);
},
);
});
group('TicketsListScreen bulk bar and sheet at phone and tablet widths', () {
// An iPhone-ish logical viewport, the narrow end of what ships today.
// Mirrors test/screens/phone_viewport_test.dart's usePhone helper: a
// screen isn't done until it holds up at 390px, checked by rendering
// rather than by reading the layout code.
void useSize(WidgetTester tester, Size logicalSize) {
tester.view.devicePixelRatio = 1.0;
tester.view.physicalSize = logicalSize;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
}
// Selects two of three loaded tickets and opens the actions sheet, so
// both the bottom bar and the sheet are on screen together, the state
// Step 5 of the brief would otherwise check by hand on a device.
Future<void> pumpWithSelectionAndSheet(
WidgetTester tester,
Size size,
) async {
useSize(tester, size);
final notifier = _FakeTicketsNotifier(
TicketsListData(
tickets: [
_ticket(id: 't1', name: 'Login broken for the whole billing team'),
_ticket(id: 't2', name: 'Export stuck at ninety percent'),
_ticket(id: 't3', name: 'Password reset email never arrives'),
],
totalCount: 3,
hasMore: false,
),
);
await tester.pumpWidget(_testApp(notifier));
await tester.pumpAndSettle();
await tester.tap(find.byTooltip('Select tickets'));
await tester.pumpAndSettle();
await tester.tap(find.byType(Checkbox).at(0));
await tester.pumpAndSettle();
await tester.tap(find.byType(Checkbox).at(1));
await tester.pumpAndSettle();
await tester.tap(find.text('Actions'));
await tester.pumpAndSettle();
}
testWidgets('the bulk bar and the actions sheet fit at 390px', (
tester,
) async {
await pumpWithSelectionAndSheet(tester, const Size(390, 844));
expect(tester.takeException(), isNull);
expect(find.text('2 selected'), findsOneWidget);
expect(find.text('Reassign'), findsOneWidget);
});
testWidgets('the bulk bar and the actions sheet fit at a tablet width', (
tester,
) async {
await pumpWithSelectionAndSheet(tester, const Size(800, 1100));
expect(tester.takeException(), isNull);
expect(find.text('2 selected'), findsOneWidget);
expect(find.text('Reassign'), findsOneWidget);
});
});
}
Widget _testApp(_FakeTicketsNotifier notifier) {
return ProviderScope(
overrides: [
ticketsProvider.overrideWith(() => notifier),
usersProvider.overrideWithValue(const []),
tagsProvider.overrideWithValue(const []),
accountOptionsProvider.overrideWithValue(const []),
],
child: MaterialApp(theme: AppTheme.light, home: const TicketsListScreen()),
);
}
Ticket _ticket({required String id, required String name}) {
return Ticket(
id: id,
name: name,
status: TicketStatus.newStatus,
priority: TicketPriority.normal,
ticketType: TicketType.question,
createdAt: DateTime(2026, 5, 1),
);
}
/// Records the ids and fields shape passed to `bulkUpdate` as a plain class
/// rather than a Dart record: a record's `==` compares `List`/`Map` fields by
/// identity, not by content, which would make an `expect(..., [...])` on the
/// call list fail even for a matching call. Asserting `.ids` and `.fields`
/// directly (each a bare List/Map) gets `flutter_test`'s deep equality.
class _BulkUpdateCall {
final List<String> ids;
final Map<String, dynamic> fields;
const _BulkUpdateCall(this.ids, this.fields);
}
class _FakeTicketsNotifier extends TicketsNotifier {
_FakeTicketsNotifier(this.initialData);
final TicketsListData initialData;
final List<_BulkUpdateCall> bulkUpdateCalls = [];
final List<List<String>> bulkDeleteCalls = [];
@override
Future<TicketsListData> build() async => initialData;
@override
Future<void> refresh({
TicketListFilters filters = const TicketListFilters(),
}) async {}
@override
Future<void> loadMore({
TicketListFilters filters = const TicketListFilters(),
}) async {}
@override
Future<ApiResponse<Map<String, dynamic>>> bulkUpdate(
List<String> ids,
Map<String, dynamic> fields,
) async {
bulkUpdateCalls.add(_BulkUpdateCall(ids, fields));
return ApiResponse(
success: true,
statusCode: 200,
data: {
'updated': ids.length,
'results': [
for (final id in ids) {'id': id, 'status': 'updated'},
],
},
);
}
@override
Future<ApiResponse<Map<String, dynamic>>> bulkDelete(List<String> ids) async {
bulkDeleteCalls.add(ids);
return ApiResponse(
success: true,
statusCode: 200,
data: {
'deleted': ids.length,
'results': [
for (final id in ids) {'id': id, 'status': 'deleted'},
],
},
);
}
}