Merge pull request #731 from Django-CRM/dev

Dev
This commit is contained in:
Ashwin Kumar 2026-08-04 16:09:19 +05:30 committed by GitHub
commit e7f4e300ba
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
116 changed files with 8302 additions and 5160 deletions

View file

@ -123,6 +123,10 @@ jobs:
working-directory: frontend
run: pnpm check
- name: Run tests
working-directory: frontend
run: pnpm test
- name: Build
working-directory: frontend
run: pnpm build

View file

@ -29,8 +29,10 @@ your data.
self-hosted CRM alternative to Salesforce, HubSpot and Pipedrive.
- **Multi-tenant by design**: PostgreSQL Row-Level Security enforces tenant isolation in the
database, not just in application code. Run it for a single company or as a SaaS for many.
- **AI agents built in (MCP)**: connect Claude, Cursor, Codex, Gemini or any MCP client and let
it search, create and update records *as you*, inheriting your role, org and permissions.
- **Agent-ready REST API**: point Claude, Cursor, Codex, Gemini or any agent at the API with a
personal access token and let it search, create and update records *as you*, inheriting your
role, org and permissions. An OpenAPI schema ships with it, so the agent can discover the
endpoints itself.
- **Web, native mobile and API**: one Django REST backend behind a Svelte 5 web app and a
Flutter app for iOS and Android.
- **A stack you can actually hack on**: Django 6 / DRF and Svelte 5, not a bespoke in-house
@ -47,7 +49,7 @@ your data.
| **Data ownership** | Total. It is your database | Vendor-controlled | Total |
| **Multi-tenancy** | Database-level RLS | Not applicable | Uncommon |
| **Native mobile app** | Yes, Flutter, iOS + Android | Yes | Uncommon |
| **AI agent access** | Built-in MCP server | Proprietary add-ons | Uncommon |
| **AI agent access** | Full REST API, per-user tokens | Proprietary add-ons | Uncommon |
| **Stack** | Django REST + SvelteKit | Closed source | Varies |
| **License** | MIT | Proprietary | Varies, often GPL/AGPL |

View file

@ -41,7 +41,7 @@ class GetProfileAndOrg:
request.profile = None
request.org = None
# Personal Access Token (agent / MCP). Resolve here so org context is
# Personal Access Token (script / agent). Resolve here so org context is
# set before RequireOrgContext runs (DRF auth runs too late for that).
# MUST come before the JWT branch so a PAT bearer is never handed to
# the JWT decoder.
@ -94,7 +94,7 @@ class GetProfileAndOrg:
request.profile = pat.profile
request.org = pat.org
request.META["org"] = str(pat.org.id)
request.META["mcp_token_id"] = str(pat.id)
request.META["pat_token_id"] = str(pat.id)
request._pat = pat
def _process_jwt_auth(self, request):

View file

@ -45,12 +45,16 @@ class SetOrgContext:
# Set org context before processing request
self._set_org_context(request)
response = self.get_response(request)
# Reset context after request
self._reset_org_context()
return response
# The reset MUST run even when the view raises. `app.current_org` is
# set at SESSION scope, so it outlives the statement and the
# transaction; it is cleared only because we clear it. Without the
# finally, an exception anywhere downstream hands the connection back
# still carrying this tenant's org id, and the next request to reuse
# that connection inherits it. That is a cross-tenant read.
try:
return self.get_response(request)
finally:
self._reset_org_context()
def _set_org_context(self, request):
"""
@ -188,12 +192,14 @@ class RequireOrgContext:
# Set org context
self._set_org_context(request)
response = self.get_response(request)
# Reset context
self._reset_org_context()
return response
# See SetOrgContext.__call__: the reset is in a finally because
# `app.current_org` is SESSION-scoped and survives an exception. On a
# pooled or otherwise reused connection, skipping it leaks this
# tenant's context to whoever borrows the connection next.
try:
return self.get_response(request)
finally:
self._reset_org_context()
def _is_exempt(self, path):
"""Check if path is exempt from org context requirement."""

View file

@ -853,7 +853,7 @@ def generate_pat_raw():
class PersonalAccessToken(BaseOrgModel):
"""
Per-user token for programmatic/agent (MCP) access.
Per-user token for programmatic REST API access (scripts, agents).
The agent authenticates AS `profile` and inherits that user's role,
org and RLS scope. The raw token is shown ONCE at creation and only

View file

@ -1,74 +1,29 @@
"""In-app notification dispatcher.
Single call site used by every producer (watchers, mentions, escalations,
future apps). Writes a `Notification` row, then best-effort publishes the
new row's id on a Redis pub/sub channel so the SSE consumer can fan it out
to any open browser tabs for that recipient.
future apps). Writes a `Notification` row. That row is the whole delivery
mechanism: clients poll ``GET /api/notifications/?since=<iso>`` and pick it up
on their next tick.
Channel naming: ``notif:<org_id>:<profile_id>``. See
``docs/cases/tier2/in-app-notifications.md`` "Cross-org leak".
This module used to also publish each new row's id on a Redis pub/sub channel
(``notif:<org_id>:<profile_id>``) to fan out to an SSE consumer. The SSE
stream was removed on 2026-08-03, which left the publish with no subscriber:
it opened a Redis connection per notification for nobody. Removed with it. If
a live transport ever comes back, it should be websockets via Channels rather
than the hand-rolled stream that was here, and it can reintroduce a fan-out
then.
"""
from __future__ import annotations
import logging
import threading
from typing import Any, Optional
from django.conf import settings
from common.models import Notification, Profile
logger = logging.getLogger(__name__)
_redis_client = None
_redis_lock = threading.Lock()
def _get_redis():
"""Lazy redis-py client keyed off CELERY_BROKER_URL.
Returns None if redis is unavailable (e.g. test environments). Callers
must treat publish as best-effort.
"""
global _redis_client
if _redis_client is not None:
return _redis_client
with _redis_lock:
if _redis_client is not None:
return _redis_client
try:
import redis # type: ignore
except ImportError: # pragma: no cover
logger.warning("redis-py not installed; notification fan-out disabled")
return None
url = getattr(settings, "CELERY_BROKER_URL", None) or "redis://localhost:6379/0"
try:
client = redis.Redis.from_url(url, socket_timeout=1, socket_connect_timeout=1)
except Exception as exc: # pragma: no cover - defensive
logger.warning("Could not build redis client for notifications: %s", exc)
return None
_redis_client = client
return client
def channel_for(org_id, profile_id) -> str:
return f"notif:{org_id}:{profile_id}"
def _publish(channel: str, payload: str) -> None:
client = _get_redis()
if client is None:
return
try:
client.publish(channel, payload)
except Exception as exc:
# Publish failure must never break the originating request. The
# row is already persisted and the user sees it on next poll/load.
logger.warning("notifications publish failed on %s: %s", channel, exc)
def create(
recipient: Profile,
verb: str,
@ -79,7 +34,7 @@ def create(
link: str = "",
data: Optional[dict] = None,
) -> Optional[Notification]:
"""Write a Notification row and publish it on the recipient's channel.
"""Write a Notification row for the recipient.
Returns the Notification, or ``None`` when delivery was skipped because
the recipient is inactive.
@ -110,5 +65,4 @@ def create(
link=link,
data=data or {},
)
_publish(channel_for(recipient.org_id, recipient.id), str(notif.id))
return notif

View file

@ -69,7 +69,7 @@ class PATAuthentication(BaseAuthentication):
request.profile = profile
request.org = pat.org
request.META["org"] = str(pat.org.id)
request.META["mcp_token_id"] = str(pat.id)
request.META["pat_token_id"] = str(pat.id)
now = timezone.now()
if pat.last_used_at is None or (now - pat.last_used_at).total_seconds() > 60:
@ -87,5 +87,5 @@ class PATAuthenticationScheme(OpenApiAuthenticationExtension):
return {
"type": "http",
"scheme": "bearer",
"description": "Personal access token (bcrm_pat_…) for agent/MCP access",
"description": "Personal access token (bcrm_pat_…) for script and agent access",
}

View file

@ -118,7 +118,7 @@ ORG_SCOPED_TABLES = [
# Approval workflows (Tier 3 approvals).
"approval_rule",
"approval",
# MCP / programmatic access
# Programmatic API access
# NOTE: personal_access_token is intentionally NOT RLS-protected. It is an
# auth-bootstrap table (looked up by token_hash before any tenant context
# exists), mirroring the Org table. Isolation for token management is enforced

View file

@ -0,0 +1,62 @@
"""Connection-pool hooks that keep RLS context from leaking between tenants.
**Why this module exists.** `app.current_org` is set with
``set_config(<var>, <org>, false)``, i.e. **SESSION** scope. That is deliberate:
Django runs in autocommit, so a transaction-local (`true`) setting would vanish
before the next statement in the same request. The cost is that the value
outlives the statement, the transaction, and the request. It is cleared only
because something explicitly clears it.
Without pooling that was survivable: ``CONN_MAX_AGE=0`` closed the backend at
the end of every request, taking the session state with it. With a pool, the
same backend is handed to the next borrower still carrying the previous
tenant's org id, and every RLS policy on the database happily scopes that
borrower's queries to the wrong tenant. psycopg_pool does **not** clean session
state on its own: ``ConnectionPool._reset_connection`` only rolls back an open
transaction. A `SET`/`set_config` survives a rollback when it was made at
session scope outside that transaction.
So the reset below is not a tidiness measure. It is the thing standing between
a pooled deployment and a cross-tenant read.
**This module must not import Django.** ``crm/settings.py`` imports it while
building ``DATABASES``, long before the app registry is ready. It takes a raw
psycopg connection and speaks SQL.
IMPORTANT: this module cannot be exercised by the default test suite, which
runs on SQLite (``crm/test_settings.py``) and has no ``set_config`` at all.
See ``common/tests/test_pool_rls_isolation.py``, which is marked
``postgres_only`` and needs a non-superuser role to mean anything, since a
superuser bypasses RLS entirely.
"""
from . import CONTEXT_VARIABLE
# Set to the empty string rather than RESET/DISCARD. The isolation policies
# generated by `get_enable_policy_sql` compare against
# `NULLIF(current_setting(<var>, true), '')`, so empty and unset both fail
# closed to zero rows. Assigning '' keeps the GUC defined, which means
# `current_setting(<var>, true)` never raises for later readers.
CLEAR_CONTEXT_SQL = f"SELECT set_config('{CONTEXT_VARIABLE}', '', false)"
def reset_rls_context(conn):
"""psycopg_pool ``reset`` callback: clear tenant context before reuse.
Contract, from ``ConnectionPool._reset_connection``: if this function
raises, or leaves the connection in any transaction status other than
IDLE, the pool logs a warning and **discards the connection**. A reset that
silently dirties every connection turns the pool into an expensive way of
opening one connection per request, which looks like pooling doing nothing
rather than like an error. Hence the explicit commit below.
The connection arrives IDLE (the pool rolls back an open transaction before
calling us). Under autocommit the statement stands alone and we stay IDLE.
Without autocommit the statement opens a transaction, so we must commit to
return to IDLE. Commit, not rollback: a session-scoped `set_config` made
inside a transaction is *reverted* by a rollback, which would leave the
stale org id in place and defeat the entire point.
"""
conn.execute(CLEAR_CONTEXT_SQL)
if not conn.autocommit:
conn.commit()

View file

@ -210,3 +210,69 @@ class TestDelete(NotificationAPIBase):
r = self.client.delete(f"/api/notifications/{n.id}/")
assert r.status_code == 404
assert Notification.objects.filter(pk=n.id).exists()
class TestPollingRoundTrip(NotificationAPIBase):
"""The exact loop `notifications.svelte.js` runs, now that SSE is gone.
The client keeps a high-water mark: the newest `created_at` it has
ingested, replayed as `?since=`. Two properties have to hold or the bell
either misses notifications or re-toasts the same one forever.
"""
def _poll(self, since=None):
qs = {"limit": "20"}
if since:
qs["since"] = since
return self.client.get("/api/notifications/?" + urlencode(qs)).json()
def test_high_water_mark_does_not_replay_or_skip(self):
first = Notification.objects.create(
org=self.org_a, recipient=self.profile_a, verb="first"
)
initial = self._poll()
assert [r["verb"] for r in initial["results"]] == ["first"]
mark = initial["results"][0]["created_at"]
# 1. Replaying the mark must be empty, not the same row again. The
# filter is `created_at__gt`, strictly greater, so the boundary row
# is excluded. With `gte` the client re-toasts it every poll.
assert self._poll(mark)["results"] == [], (
"the boundary row came back: the client would re-toast it on "
"every single poll"
)
# 2. A newer row must arrive, without dragging the older one back.
Notification.objects.filter(pk=first.pk).update(
created_at=timezone.now() - timedelta(minutes=5)
)
Notification.objects.create(
org=self.org_a, recipient=self.profile_a, verb="second"
)
after = self._poll(mark)
assert [r["verb"] for r in after["results"]] == ["second"]
# And the new mark still terminates.
assert self._poll(after["results"][0]["created_at"])["results"] == []
def test_poll_reports_global_unread_not_the_since_window(self):
"""The client refreshes the badge straight from the poll response.
If `unread_count` were scoped to the `since` window it would read 0 on
every quiet poll and the badge would clear itself while unread
notifications were still sitting there.
"""
for verb in ("one", "two", "three"):
Notification.objects.create(
org=self.org_a, recipient=self.profile_a, verb=verb
)
mark = self._poll()["results"][0]["created_at"]
quiet = self._poll(mark)
assert quiet["results"] == []
assert quiet["count"] == 0, "count is since-scoped, as documented"
assert quiet["unread_count"] == 3, (
"unread_count must stay global or the bell badge zeroes itself "
"on the first quiet poll"
)

View file

@ -1,192 +0,0 @@
"""Tests for the Server-Sent Events notification stream.
Covers:
- Pure-function helpers (`_format_sse`, `_format_keepalive`).
- The async generator `_stream_events` with an injected stub pubsub
(no real Redis required).
- The auth gate on the view.
"""
import asyncio
import json
from django.test import TestCase, TransactionTestCase
from rest_framework.test import APIClient
from common.models import Notification, Org, Profile, User
from common.views import notification_views
from common.views.notification_views import (
_format_keepalive,
_format_sse,
_stream_events,
)
class TestFormatHelpers:
def test_format_sse_event_shape(self):
out = _format_sse("notification", {"id": "abc", "verb": "v"})
assert out.startswith(b"event: notification\n")
assert b"data: " in out
assert out.endswith(b"\n\n")
data_line = [l for l in out.split(b"\n") if l.startswith(b"data: ")][0]
payload = json.loads(data_line[len(b"data: "):])
assert payload == {"id": "abc", "verb": "v"}
def test_format_keepalive_is_comment(self):
# SSE comment lines start with ':'
assert _format_keepalive() == b": keepalive\n\n"
class _StubPubSub:
"""Duck-typed redis.asyncio pubsub.
Pulls messages from a list; once exhausted, returns None forever.
"""
def __init__(self, messages=None):
self._messages = list(messages or [])
self.subscribed = []
self.unsubscribed = []
self.closed = False
async def subscribe(self, channel):
self.subscribed.append(channel)
async def unsubscribe(self, channel):
self.unsubscribed.append(channel)
async def close(self):
self.closed = True
async def get_message(self, ignore_subscribe_messages=False):
if self._messages:
return self._messages.pop(0)
return None
class TestStreamEvents(TransactionTestCase):
"""Uses TransactionTestCase because the SSE generator's `sync_to_async`
DB hit opens a separate SQLite connection, incompatible with the
transaction-wrapped TestCase isolation."""
def setUp(self):
self.org = Org.objects.create(name="O")
self.user = User.objects.create_user(email="u@test.com", password="x")
self.profile = Profile.objects.create(
user=self.user, org=self.org, role="USER", is_active=True
)
self.other_user = User.objects.create_user(email="x@test.com", password="x")
self.other_profile = Profile.objects.create(
user=self.other_user, org=self.org, role="USER", is_active=True
)
def test_first_frame_is_keepalive(self):
async def runner():
pubsub = _StubPubSub()
gen = _stream_events("notif:o:p", recipient_id=self.profile.id, pubsub=pubsub)
first = await asyncio.wait_for(gen.__anext__(), timeout=1)
await gen.aclose()
return first
first = asyncio.run(runner())
assert first == b": keepalive\n\n"
def test_emits_notification_for_pubsub_message(self):
notif = Notification.objects.create(
org=self.org,
recipient=self.profile,
verb="case.commented",
data={"comment_excerpt": "hi"},
link="/cases/abc",
)
async def runner():
pubsub = _StubPubSub([{"data": str(notif.id).encode("utf-8")}])
gen = _stream_events(
"notif:o:p", recipient_id=self.profile.id, pubsub=pubsub
)
first = await asyncio.wait_for(gen.__anext__(), timeout=1)
second = await asyncio.wait_for(gen.__anext__(), timeout=2)
await gen.aclose()
return first, second
first, second = asyncio.run(runner())
assert first == b": keepalive\n\n"
assert second.startswith(b"event: notification\n")
data_line = [l for l in second.split(b"\n") if l.startswith(b"data: ")][0]
payload = json.loads(data_line[len(b"data: "):])
assert payload["id"] == str(notif.id)
assert payload["verb"] == "case.commented"
assert payload["link"] == "/cases/abc"
assert payload["data"] == {"comment_excerpt": "hi"}
def test_stream_self_terminates_at_deadline(self):
"""The stream must end on its own once MAX_STREAM_SECONDS elapses, so a
long-open browser tab cannot pin a worker thread / DB connection
forever (the connection-exhaustion regression)."""
async def runner():
pubsub = _StubPubSub() # no messages -> keepalive-only loop
gen = _stream_events(
"notif:o:p", recipient_id=self.profile.id, pubsub=pubsub
)
first = await asyncio.wait_for(gen.__anext__(), timeout=1)
stopped = False
try:
# Deadline already passed -> next pull should end the stream.
await asyncio.wait_for(gen.__anext__(), timeout=2)
except StopAsyncIteration:
stopped = True
await gen.aclose()
return first, stopped
original = notification_views.MAX_STREAM_SECONDS
notification_views.MAX_STREAM_SECONDS = 0
try:
first, stopped = asyncio.run(runner())
finally:
notification_views.MAX_STREAM_SECONDS = original
assert first == b": keepalive\n\n"
assert stopped, "stream did not terminate at its deadline"
def test_drops_message_for_other_recipient(self):
n_other = Notification.objects.create(
org=self.org, recipient=self.other_profile, verb="other"
)
n_mine = Notification.objects.create(
org=self.org, recipient=self.profile, verb="mine"
)
async def runner():
pubsub = _StubPubSub(
[
{"data": str(n_other.id).encode("utf-8")},
{"data": str(n_mine.id).encode("utf-8")},
]
)
gen = _stream_events(
"notif:o:p", recipient_id=self.profile.id, pubsub=pubsub
)
await asyncio.wait_for(gen.__anext__(), timeout=1) # discard initial keepalive
second = await asyncio.wait_for(gen.__anext__(), timeout=2)
await gen.aclose()
return second
second = asyncio.run(runner())
assert second.startswith(b"event: notification\n")
data_line = [l for l in second.split(b"\n") if l.startswith(b"data: ")][0]
payload = json.loads(data_line[len(b"data: "):])
# Should be MINE, never the other recipient's row
assert payload["id"] == str(n_mine.id)
assert payload["verb"] == "mine"
class TestStreamAuth(TestCase):
def test_unauthenticated_rejected(self):
anon = APIClient()
r = anon.get("/api/notifications/stream/")
try:
assert r.status_code in (401, 403)
finally:
close = getattr(r, "close", None)
if close:
close()

View file

@ -4,7 +4,6 @@ API-level coverage lives in `test_notification_api.py` once that lands.
"""
from datetime import timedelta
from unittest.mock import patch
from django.test import TestCase
from django.utils import timezone
@ -112,68 +111,58 @@ class TestNotificationModel(NotificationModelBase):
class TestDispatcher(NotificationModelBase):
def test_create_writes_row_and_publishes(self):
with patch("common.notifications._publish") as pub:
n = notifications.create(
self.profile_a,
"case.commented",
actor=self.actor_profile,
link="/cases/123",
data={"comment_excerpt": "hello"},
)
def test_create_writes_the_row(self):
n = notifications.create(
self.profile_a,
"case.commented",
actor=self.actor_profile,
link="/cases/123",
data={"comment_excerpt": "hello"},
)
assert n is not None
assert n.org_id == self.org_a.id
assert n.recipient_id == self.profile_a.id
assert n.actor_id == self.actor_profile.id
assert n.link == "/cases/123"
assert n.data == {"comment_excerpt": "hello"}
pub.assert_called_once()
channel, payload = pub.call_args[0]
assert channel == f"notif:{self.org_a.id}:{self.profile_a.id}"
assert payload == str(n.id)
def test_create_skips_inactive_recipient(self):
self.profile_a.is_active = False
self.profile_a.save()
with patch("common.notifications._publish") as pub:
n = notifications.create(self.profile_a, "case.commented")
n = notifications.create(self.profile_a, "case.commented")
assert n is None
pub.assert_not_called()
assert not Notification.objects.filter(recipient=self.profile_a).exists()
def test_create_with_entity_denormalizes_type_id_name(self):
account = Account.objects.create(name="Acme Corp", org=self.org_a)
with patch("common.notifications._publish"):
n = notifications.create(
self.profile_a,
"account.assigned",
entity=account,
)
n = notifications.create(
self.profile_a,
"account.assigned",
entity=account,
)
assert n.entity_type == "Account"
assert n.entity_id == account.pk
assert n.entity_name == "Acme Corp"
def test_create_entity_name_override(self):
account = Account.objects.create(name="Acme Corp", org=self.org_a)
with patch("common.notifications._publish"):
n = notifications.create(
self.profile_a,
"account.assigned",
entity=account,
entity_name="Custom Label",
)
n = notifications.create(
self.profile_a,
"account.assigned",
entity=account,
entity_name="Custom Label",
)
assert n.entity_name == "Custom Label"
def test_create_does_not_raise_when_redis_publish_fails(self):
# Simulate redis being totally broken.
with patch("common.notifications._get_redis") as gr:
gr.return_value = type(
"_BrokenClient",
(),
{"publish": lambda self, *a, **kw: (_ for _ in ()).throw(RuntimeError("boom"))},
)()
# Should NOT raise. Publish is best-effort.
n = notifications.create(self.profile_a, "case.commented")
def test_create_needs_no_broker(self):
"""The row IS the delivery mechanism.
`create()` used to publish on Redis for the SSE stream to fan out.
That stream is gone, so notification delivery must not depend on a
broker being reachable at all: clients pick the row up on their next
`?since=` poll. Nothing is patched here on purpose.
"""
n = notifications.create(self.profile_a, "case.commented")
assert n is not None
assert Notification.objects.filter(pk=n.pk).exists()

View file

@ -0,0 +1,164 @@
"""Proof that connection pooling cannot leak RLS context between tenants.
``app.current_org`` is a SESSION-scoped GUC (``set_config(..., false)``). It
survives the statement, the transaction, and the request. psycopg_pool does not
clear session state when a connection is returned: ``_reset_connection`` only
rolls back an open transaction. So a pool WITHOUT
``common.rls.pool.reset_rls_context`` hands the next borrower a backend still
scoped to the previous tenant, and every RLS policy on the database obediently
serves that borrower the wrong tenant's rows.
These tests build their own single-connection ``ConnectionPool`` rather than
driving Django's. Two reasons:
* ``max_size=1`` makes the second checkout provably the *same* backend. With
the default pool size the next checkout may land on a connection that was
never dirtied, and the test passes for the wrong reason. The assertions on
``pg_backend_pid()`` below exist to make that failure mode impossible.
* The default suite runs on SQLite (``crm/test_settings.py``), which has no
``set_config`` at all, so nothing here can be expressed through Django's
``connection``. Connection params are read from the same environment
variables ``crm/settings.py`` uses, so this runs against whatever PostgreSQL
the developer already has configured, and skips when there isn't one.
Note that these tests do NOT need a non-superuser role. They assert that the
session variable is cleared, which is upstream of RLS enforcement and therefore
observable even on a superuser dev database where RLS is inert. A companion
check that RLS then actually hides rows does need a non-superuser role; see
`RLS_SETUP.md`.
"""
import os
import pytest
psycopg = pytest.importorskip("psycopg")
psycopg_pool = pytest.importorskip("psycopg_pool")
from common.rls.pool import reset_rls_context # noqa: E402
ORG_A = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
ORG_B = "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"
def _conn_kwargs():
"""Mirror the connection params crm/settings.py builds from the env."""
return {
"dbname": os.environ.get("DBNAME", "crm_db"),
"user": os.environ.get("DBUSER", "postgres"),
"password": os.environ.get("DBPASSWORD", "postgres"),
"host": os.environ.get("DBHOST", "localhost"),
"port": os.environ.get("DBPORT", "5432"),
"autocommit": True,
}
@pytest.fixture(scope="module", autouse=True)
def _require_postgres():
try:
with psycopg.connect(**_conn_kwargs(), connect_timeout=3):
pass
except Exception as exc: # pragma: no cover - environment dependent
pytest.skip(f"PostgreSQL not reachable for pool isolation tests: {exc}")
def _single_connection_pool(reset):
return psycopg_pool.ConnectionPool(
kwargs=_conn_kwargs(),
min_size=1,
max_size=1,
reset=reset,
open=True,
timeout=10,
)
def _dirty(pool, org_id):
"""Borrow, set tenant context, hand the connection back. Returns the pid."""
with pool.connection() as conn:
pid = conn.execute("SELECT pg_backend_pid()").fetchone()[0]
conn.execute("SELECT set_config('app.current_org', %s, false)", [org_id])
return pid
def _observe(pool):
"""Borrow and report (pid, whatever app.current_org this borrower sees)."""
with pool.connection() as conn:
pid = conn.execute("SELECT pg_backend_pid()").fetchone()[0]
seen = conn.execute(
"SELECT current_setting('app.current_org', true)"
).fetchone()[0]
return pid, seen
def test_reset_clears_tenant_context_before_the_next_borrower_sees_it():
"""The guard. Tenant A's org id must not survive into tenant B's checkout."""
pool = _single_connection_pool(reset=reset_rls_context)
try:
pid_a = _dirty(pool, ORG_A)
pid_b, seen = _observe(pool)
finally:
pool.close()
assert pid_a == pid_b, (
"test is inconclusive: the second checkout got a different backend, "
"so nothing was proven about context surviving reuse"
)
assert seen in ("", None), (
f"cross-tenant leak: the next borrower of backend {pid_b} sees "
f"app.current_org={seen!r}, which RLS would resolve to another "
f"tenant's rows"
)
def test_without_the_reset_hook_the_context_does_leak():
"""Characterization, not a pinned bug.
This asserts what a pool configured WITHOUT ``reset`` actually does, so the
reason ``reset_rls_context`` is wired into DATABASES OPTIONS is recorded as
an executable fact rather than a comment. If psycopg_pool ever starts
clearing session state on its own, this test fails and the settings comment
should be revisited. It is not asserting desired behaviour of our code.
"""
pool = _single_connection_pool(reset=None)
try:
pid_a = _dirty(pool, ORG_A)
pid_b, seen = _observe(pool)
finally:
pool.close()
assert pid_a == pid_b, "inconclusive: different backend"
assert seen == ORG_A, (
"psycopg_pool appears to clear session state by itself now; if so the "
"reset hook may no longer be load-bearing. Verify before relying on it."
)
def test_reset_leaves_the_connection_idle_so_the_pool_keeps_reusing_it():
"""The silent-failure mode.
``ConnectionPool._reset_connection`` discards any connection the reset
callback leaves in a non-IDLE transaction status. A reset that opens a
transaction and forgets to commit therefore destroys and reopens a
connection on every single checkout: correctness is preserved, but the pool
silently stops pooling. That looks like a performance mystery, not an
error, so it is asserted here.
"""
pool = _single_connection_pool(reset=reset_rls_context)
try:
pids = set()
for _ in range(15):
pids.add(_dirty(pool, ORG_B))
stats = pool.get_stats()
finally:
pool.close()
assert len(pids) == 1, (
f"the pool churned through {len(pids)} backends over 15 checkouts: the "
f"reset callback is leaving connections non-IDLE and they are being "
f"discarded"
)
assert stats.get("connections_num", 0) <= 2, (
f"pool opened {stats.get('connections_num')} connections for a "
f"max_size=1 pool, which means connections are being discarded"
)

View file

@ -0,0 +1,108 @@
"""The RLS context reset must survive an exception in the view.
`app.current_org` is set with ``set_config(..., false)``, i.e. SESSION scope.
It outlives the statement, the transaction, and the failed request. The only
thing that clears it is the middleware's own reset call.
Before pooling, `CONN_MAX_AGE=0` closed the connection at the end of every
request, so a skipped reset was invisible. Once connections are reused (a
psycopg pool, persistent connections, or a session-mode external pooler), a
skipped reset hands the next borrower a connection still scoped to the
previous tenant, and RLS happily serves them that tenant's rows.
These tests run on SQLite because they assert the *control flow*, that reset is
called on the exception path, not the SQL. The end-to-end proof that a returned
connection carries no context lives in ``test_pool_rls_isolation.py`` and needs
a real PostgreSQL with a non-superuser role.
"""
import pytest
from common.middleware.rls_context import RequireOrgContext, SetOrgContext
class _Boom(Exception):
pass
class _FakeOrg:
id = "11111111-1111-1111-1111-111111111111"
class _FakeRequest:
def __init__(self, path="/api/leads/"):
self.path = path
self.org = _FakeOrg()
def _instrument(middleware_cls, get_response):
"""Build the middleware with set/reset replaced by call recorders."""
calls = []
mw = middleware_cls(get_response)
mw._set_org_context = lambda request: calls.append("set")
mw._reset_org_context = lambda: calls.append("reset")
return mw, calls
@pytest.mark.parametrize("middleware_cls", [SetOrgContext, RequireOrgContext])
def test_reset_runs_on_the_happy_path(middleware_cls):
mw, calls = _instrument(middleware_cls, lambda request: "response")
assert mw(_FakeRequest()) == "response"
assert calls == ["set", "reset"]
@pytest.mark.parametrize("middleware_cls", [SetOrgContext, RequireOrgContext])
def test_reset_runs_when_the_view_raises(middleware_cls):
"""The regression this file exists for.
Without the try/finally the middleware returned early on the exception and
`app.current_org` stayed set on the connection.
"""
def boom(request):
raise _Boom("view exploded")
mw, calls = _instrument(middleware_cls, boom)
with pytest.raises(_Boom):
mw(_FakeRequest())
assert calls == ["set", "reset"], (
"org context was not cleared after the view raised: the connection "
"goes back to the pool still scoped to this tenant"
)
@pytest.mark.parametrize("middleware_cls", [SetOrgContext, RequireOrgContext])
def test_the_exception_still_propagates(middleware_cls):
"""The finally must not swallow the error into a silent 200."""
def boom(request):
raise _Boom("view exploded")
mw, _ = _instrument(middleware_cls, boom)
with pytest.raises(_Boom, match="view exploded"):
mw(_FakeRequest())
def test_require_org_context_resets_after_an_exempt_path_raises():
"""Exempt paths skip the 403 check but still run set/reset around the view.
`/api/public/invoice/` is anonymous, so `_set_org_context` returns early
and leaves the context empty. The reset still has to run: an exempt request
can be handled on a connection a previous tenant's request left dirty, and
clearing on the way out is what stops that spreading further.
"""
def boom(request):
raise _Boom("public view exploded")
mw, calls = _instrument(RequireOrgContext, boom)
request = _FakeRequest(path="/api/public/invoice/abc123/")
with pytest.raises(_Boom):
mw(request)
assert calls == ["set", "reset"]

View file

@ -21,7 +21,6 @@ from common.views.notification_views import (
NotificationListView,
NotificationReadAllView,
NotificationReadView,
NotificationStreamView,
)
from common.views.org_settings_views import OrgSettingsView
from common.views.organization_views import (
@ -101,7 +100,7 @@ urlpatterns = [
),
path("org/<str:pk>/", OrgUpdateView.as_view()),
path("profile/", ProfileView.as_view()),
# Personal Access Tokens (MCP server), a user manages ONLY their own
# Personal Access Tokens (REST API), a user manages ONLY their own
path(
"profile/tokens/",
PersonalAccessTokenListCreateView.as_view(),
@ -145,11 +144,6 @@ urlpatterns = [
),
# In-app notifications (per-recipient feed)
path("notifications/", NotificationListView.as_view(), name="notifications_list"),
path(
"notifications/stream/",
NotificationStreamView.as_view(),
name="notifications_stream",
),
path(
"notifications/read-all/",
NotificationReadAllView.as_view(),

View file

@ -2,52 +2,41 @@
URL surface (mounted at /api/notifications/):
GET /: list, optional ?unread=true&limit=20&since=<iso>
GET /stream/: SSE event stream (one event per new notification)
POST /<id>/read/: mark a single notification read
POST /read-all/: mark all (or all-before-iso) read
DELETE /<id>/: hard-delete a notification
Delivery is by polling: the client passes `?since=<iso>` on an interval and
receives whatever arrived after that timestamp. There was previously an SSE
stream at `/stream/`, removed 2026-08-03. It was the only async code in the
project, so it forced the whole deployment onto ASGI, where every in-flight
request takes its own database connection with no ceiling. That model caused
two production connection-exhaustion incidents. It was also silently broken:
its payload fetch ran on a connection with no `app.current_org` set, so under
a correctly configured non-superuser role every RLS policy matched zero rows
and the stream emitted keepalives and nothing else.
Polling costs far less than it appears to. At a 45s interval and a ~50ms
request, average concurrency is one request per ~900 open tabs, each borrowing
a pooled connection briefly and returning it.
Rules:
- All queries filter by `recipient=request.profile`. RLS adds an org
isolation safety net at the DB layer.
- Mark-read is idempotent (re-marking does not move read_at backwards).
"""
import asyncio
import json
import logging
import time
from asgiref.sync import sync_to_async
from django.http import StreamingHttpResponse
from django.shortcuts import get_object_or_404
from django.utils import timezone
from django.utils.dateparse import parse_datetime
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from rest_framework.renderers import BaseRenderer
from rest_framework.response import Response
from rest_framework.views import APIView
from common import notifications as notif_mod
from common.models import Notification
from common.serializer import NotificationSerializer
logger = logging.getLogger(__name__)
KEEPALIVE_SECONDS = 15
# Upper bound on a single SSE connection's lifetime. The browser's EventSource
# transparently reconnects when the server closes the stream, so capping this
# is invisible to the user but critical for the server: under ASGI the *entire*
# stream runs inside one request (one `ThreadSensitiveContext`), so an
# unbounded `while True` stream pins a worker thread, and any DB/redis
# connection bound to it. For as long as the tab stays open (hours). Left
# unbounded this is what slowly exhausts a shared Postgres cluster and leaves
# workers undrainable on deploy. 5 minutes bounds the leak window and lets
# workers recycle.
MAX_STREAM_SECONDS = 300
DEFAULT_LIMIT = 20
MAX_LIMIT = 100
@ -65,7 +54,19 @@ def _parse_int(raw, default, *, lo=1, hi=MAX_LIMIT):
class NotificationListView(APIView):
"""GET /api/notifications/"""
"""GET /api/notifications/
Also the delivery endpoint the client polls with ``?since=<iso>``.
Note the two counts have different scopes, and the polling client depends
on the difference:
* ``count`` is the size of the *filtered* queryset, so under ``?since=``
it is "how many arrived since", not the feed total.
* ``unread_count`` is always computed over the recipient's whole feed,
deliberately unfiltered, so a poll can refresh the bell badge without a
second request.
"""
permission_classes = (IsAuthenticated,)
@ -133,210 +134,3 @@ class NotificationDetailView(APIView):
notif = get_object_or_404(_user_qs(request), pk=pk)
notif.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
# --- SSE stream ---------------------------------------------------------
def _format_sse(event: str, data: dict) -> bytes:
"""Encode one Server-Sent Events frame."""
return f"event: {event}\ndata: {json.dumps(data)}\n\n".encode("utf-8")
def _format_keepalive() -> bytes:
# Comment lines (starting with ':') are silently ignored by the EventSource
# client but defeat reverse-proxy buffering on idle connections.
return b": keepalive\n\n"
async def _aget_serialized(notif_id, recipient_id):
"""Fetch a notification by id, scoped to recipient. Returns dict or None."""
@sync_to_async
def fetch():
from django.db import connection
try:
notif = Notification.objects.filter(
pk=notif_id, recipient_id=recipient_id
).first()
if notif is None:
return None
return NotificationSerializer(notif).data
finally:
# This runs in asgiref's shared thread-sensitive executor, outside
# Django's request/response cycle, so `close_old_connections`
# never fires for it. Without this explicit close the connection
# dangles open (the SSE tests need TransactionTestCase precisely
# because of it). Close it so each fetch reclaims its connection.
connection.close()
return await fetch()
async def _aclose_redis(obj):
"""Close a redis.asyncio client/pubsub across versions (aclose vs close)."""
if obj is None:
return
closer = getattr(obj, "aclose", None) or getattr(obj, "close", None)
if closer is None:
return
try:
result = closer()
if asyncio.iscoroutine(result):
await result
except Exception: # pragma: no cover - best effort
pass
async def _open_pubsub(channel: str):
"""Open a redis.asyncio pubsub subscribed to ``channel``.
Returns ``(client, pubsub)``. Both are ``None`` if Redis is unreachable;
the stream then runs in keepalive-only mode (the frontend's polling-since
path provides backfill). The caller owns closing BOTH the pubsub and the
underlying client connection pool, closing only the pubsub leaks the
client's pooled connections, one per dropped SSE stream.
"""
try:
import redis.asyncio as aioredis # type: ignore
except ImportError: # pragma: no cover
return None, None
from django.conf import settings
url = getattr(settings, "CELERY_BROKER_URL", None) or "redis://localhost:6379/0"
client = None
try:
client = aioredis.from_url(url)
pubsub = client.pubsub()
await pubsub.subscribe(channel)
return client, pubsub
except Exception as exc:
logger.warning("SSE redis subscribe failed (%s); keepalive-only mode", exc)
await _aclose_redis(client)
return None, None
async def _stream_events(channel: str, recipient_id, *, pubsub=None):
"""Async generator yielding SSE-formatted bytes for the recipient's channel.
Pass ``pubsub`` to inject a stub for tests. When omitted the generator
opens its own redis.asyncio pubsub via :func:`_open_pubsub`.
"""
owns_pubsub = pubsub is None
client = None
if owns_pubsub:
client, pubsub = await _open_pubsub(channel)
deadline = time.monotonic() + MAX_STREAM_SECONDS
try:
# Initial comment so the client confirms the stream opened.
yield _format_keepalive()
while True:
# Bounded lifetime: end the stream so the worker thread and its
# DB/redis connections are released. EventSource reconnects.
if time.monotonic() >= deadline:
return
if pubsub is None:
await asyncio.sleep(KEEPALIVE_SECONDS)
yield _format_keepalive()
continue
try:
msg = await asyncio.wait_for(
pubsub.get_message(ignore_subscribe_messages=True),
timeout=KEEPALIVE_SECONDS,
)
except asyncio.TimeoutError:
yield _format_keepalive()
continue
if msg is None:
await asyncio.sleep(0.5)
continue
data = msg.get("data")
if isinstance(data, bytes):
data = data.decode("utf-8", errors="replace")
payload = await _aget_serialized(data, recipient_id)
if payload is None:
continue
yield _format_sse("notification", payload)
finally:
if owns_pubsub:
if pubsub is not None:
try:
await pubsub.unsubscribe(channel)
except Exception: # pragma: no cover - best effort
pass
await _aclose_redis(pubsub)
# Close the underlying client pool too, not just the pubsub.
await _aclose_redis(client)
def _drive_async_gen(agen):
"""Yield from an async generator using a dedicated event loop.
DRF's APIView dispatch is sync, so we can't expose an `async def` handler
directly (Django would mark the view async via `view_is_async`, then DRF's
sync dispatch returns a Response that the async wrapper tries to await).
StreamingHttpResponse accepts a sync iterable, so we bridge here.
"""
loop = asyncio.new_event_loop()
try:
while True:
try:
yield loop.run_until_complete(agen.__anext__())
except StopAsyncIteration:
return
finally:
try:
loop.run_until_complete(agen.aclose())
finally:
loop.close()
class _EventStreamRenderer(BaseRenderer):
"""Advertises text/event-stream for DRF content negotiation.
Never actually invoked: the view returns a StreamingHttpResponse directly.
Without this, an EventSource sending `Accept: text/event-stream` is
rejected by DRF's content negotiation with HTTP 406 (no matching renderer).
"""
media_type = "text/event-stream"
format = "sse"
def render(self, data, accepted_media_type=None, renderer_context=None):
return b""
class NotificationStreamView(APIView):
"""GET /api/notifications/stream/
Long-lived Server-Sent Events response. Requires an ASGI server in
production, under WSGI this view ties up one worker per connected user.
"""
permission_classes = (IsAuthenticated,)
renderer_classes = (_EventStreamRenderer,)
def get(self, request, *args, **kwargs):
org_id = request.profile.org_id
profile_id = request.profile.id
channel = notif_mod.channel_for(org_id, profile_id)
# Release THIS request thread's DB connection before streaming begins.
# Under ASGI the entire stream runs inside one request's
# ThreadSensitiveContext, so the connection opened by auth/middleware
# would otherwise stay checked out for the full (possibly hours-long)
# stream, one leaked Postgres connection per open browser tab, which
# is what exhausts the shared cluster. The stream's own reads go
# through a separate executor (see `_aget_serialized`) and close
# themselves, so dropping this one is safe.
from django.db import connection
connection.close()
response = StreamingHttpResponse(
_drive_async_gen(_stream_events(channel, profile_id)),
content_type="text/event-stream",
)
response["Cache-Control"] = "no-cache, no-transform"
response["X-Accel-Buffering"] = "no" # disable nginx buffering
return response

View file

@ -1,4 +1,8 @@
"""Personal Access Token CRUD for the BottleCRM MCP server.
"""Personal Access Token CRUD for programmatic REST API access.
Tokens authenticate scripts, integrations and AI agents against the API under
``/api/`` with an ``Authorization: Bearer bcrm_pat_...`` header. A token acts
AS its owning profile and inherits that user's role, org and RLS scope.
A user manages ONLY their own tokens. Both list and revoke are filtered by
``org=request.profile.org`` AND ``profile=request.profile`` so another user's
@ -33,7 +37,7 @@ from common.serializer import (
class PersonalAccessTokenListCreateView(APIView):
permission_classes = (IsAuthenticated, HasOrgContext)
@extend_schema(tags=["MCP / Tokens"], operation_id="pat_list")
@extend_schema(tags=["API Tokens"], operation_id="pat_list")
def get(self, request):
qs = PersonalAccessToken.objects.filter(
org=request.profile.org, profile=request.profile
@ -47,7 +51,7 @@ class PersonalAccessTokenListCreateView(APIView):
)
@extend_schema(
tags=["MCP / Tokens"],
tags=["API Tokens"],
operation_id="pat_create",
request=PersonalAccessTokenCreateSerializer,
)
@ -72,7 +76,7 @@ class PersonalAccessTokenListCreateView(APIView):
class PersonalAccessTokenDetailView(APIView):
permission_classes = (IsAuthenticated, HasOrgContext)
@extend_schema(tags=["MCP / Tokens"], operation_id="pat_revoke")
@extend_schema(tags=["API Tokens"], operation_id="pat_revoke")
def delete(self, request, pk):
pat = get_object_or_404(
PersonalAccessToken,
@ -112,7 +116,7 @@ class OrgAccessTokenListView(APIView):
permission_classes = (IsAuthenticated, HasOrgContext, IsOrgAdmin)
@extend_schema(tags=["MCP / Tokens"], operation_id="org_pat_list")
@extend_schema(tags=["API Tokens"], operation_id="org_pat_list")
def get(self, request):
now = timezone.now()
qs = (
@ -164,7 +168,7 @@ class OrgAccessTokenDetailView(APIView):
permission_classes = (IsAuthenticated, HasOrgContext, IsOrgAdmin)
@extend_schema(tags=["MCP / Tokens"], operation_id="org_pat_revoke")
@extend_schema(tags=["API Tokens"], operation_id="org_pat_revoke")
def delete(self, request, pk):
pat = get_object_or_404(
PersonalAccessToken, pk=pk, org=request.profile.org

View file

@ -1,21 +1,24 @@
"""ASGI entrypoint for Django-CRM.
Mirror of `wsgi.py` for ASGI servers (uvicorn, hypercorn, daphne). Required
for the in-app notifications SSE stream. Async views serving long-lived
connections will hold a worker hostage when run under WSGI.
Mirror of `wsgi.py` for ASGI servers (uvicorn, hypercorn, daphne). Kept so
existing ASGI deployments keep working, but **nothing in this project requires
it any more**. It existed for the in-app notifications SSE stream, which was
the only async view here; that was replaced by polling on 2026-08-03.
It also optionally mounts the BottleCRM **MCP server** at ``/mcp`` so AI agents
can connect over HTTP with no local install (each request authenticates with
its own ``Authorization: Bearer <pat>`` header). The mount is best-effort: if
the optional ``bcrm-mcp`` dependency is not installed, or ``BCRM_MCP_ENABLED``
is false, this module serves Django alone. Exactly as before.
Prefer WSGI in production:
Production deploy must run an ASGI server pointing at this module:
gunicorn crm.wsgi:application --bind 0.0.0.0:8000 --workers 3 --threads 4
uvicorn crm.asgi:application --host 0.0.0.0 --port 8000
Not merely for simplicity. Under ASGI each in-flight request gets its own
thread-sensitive executor and its own thread-local database connection, with
no ceiling, which is what exhausted PostgreSQL twice in this project's
history. Under WSGI the ceiling is `workers x threads`, a number you choose.
If you do serve this module, enable pooling (`DB_POOL_ENABLED=true`, see
crm/settings.py) so the connection count is bounded some other way.
`runserver` uses WSGI, so the MCP mount is only active under a real ASGI
server; dev workflows for the Django app itself are unchanged.
Agents and scripts reach the CRM through the REST API under `/api/`,
authenticated with a personal access token (`Authorization: Bearer
bcrm_pat_...`). See docs/integrations/ai-agents.md.
"""
import os
@ -29,99 +32,4 @@ sys.path.append(PROJECT_DIR)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "crm.settings")
django_application = get_asgi_application()
def _mcp_disabled():
return os.environ.get("BCRM_MCP_ENABLED", "true").strip().lower() in (
"0",
"false",
"no",
"off",
)
def _build_application():
"""Return the ASGI app: Django alone, or Django with the MCP server at /mcp.
Falls back to the plain Django app whenever the MCP server can't or
shouldn't be mounted, so an incomplete install never takes the site down.
"""
if _mcp_disabled():
return django_application
try:
from bcrm_mcp.auth import extract_bearer_token
from bcrm_mcp.server import build_http_app
except ImportError:
# Optional `mcp` extra not installed: serve Django only.
return django_application
# The CRM REST root the MCP tools call. Mounted in-process, so this is a
# loopback to this very server; override via env for a different internal
# address.
base_url = os.environ.get("BCRM_BASE_URL", "http://127.0.0.1:8000")
# MCP streamable endpoint lives at exactly "/mcp". We dispatch by prefix
# ourselves rather than using Starlette's Mount, which (in the vendored
# starlette) only matches "/mcp/…" and lets a slashless "/mcp" fall through
# to Django, users configure ".../mcp" without a trailing slash.
mcp_app = build_http_app(base_url, path="/mcp")
def _bearer_token(scope):
for name, value in scope.get("headers", []):
if name == b"authorization":
return extract_bearer_token(
{"authorization": value.decode("latin-1")}
)
return None
async def application(scope, receive, send):
kind = scope.get("type")
# Drive ONLY the MCP app's lifespan (it starts the MCP session
# manager). Django needs no lifespan, so it never sees this scope.
if kind == "lifespan":
await mcp_app(scope, receive, send)
return
if kind in ("http", "websocket"):
path = scope.get("path", "")
if path == "/mcp" or path.startswith("/mcp/"):
# Edge auth: reject anything without a well-formed bearer token
# BEFORE it reaches the MCP layer, so initialize/list-tools are
# unreachable unauthenticated, not just tool calls. (The token's
# validity is still checked by the backend on each API call.)
if _bearer_token(scope) is None:
await _unauthorized(scope, send)
return
await mcp_app(scope, receive, send)
return
await django_application(scope, receive, send)
return application
async def _unauthorized(scope, send):
"""Send a 401 (http) or reject the connection (websocket) for /mcp requests
that carry no usable bearer token."""
if scope.get("type") == "websocket":
await send({"type": "websocket.close", "code": 1008})
return
body = (
b'{"error":"unauthorized","detail":"Missing or malformed Authorization '
b'header. Send: Authorization: Bearer <bcrm_pat_...>"}'
)
await send(
{
"type": "http.response.start",
"status": 401,
"headers": [
(b"content-type", b"application/json"),
(b"www-authenticate", b"Bearer"),
(b"content-length", str(len(body)).encode("ascii")),
],
}
)
await send({"type": "http.response.body", "body": body})
application = _build_application()
application = get_asgi_application()

View file

@ -94,6 +94,29 @@ WSGI_APPLICATION = "crm.wsgi.application"
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
# Connection pooling (psycopg 3 + psycopg_pool, wired by Django's postgresql
# backend). Off by default so an existing deployment does not silently change
# its connection behaviour on upgrade; set DB_POOL_ENABLED=true to turn it on.
#
# Two things make this more than a performance knob here:
#
# 1. Every ASGI request gets its own thread-sensitive executor and therefore
# its own connection, with no ceiling. That is how two separate incidents
# exhausted PostgreSQL. `max_size` is the ceiling that was missing.
# 2. RLS context lives in a SESSION-scoped GUC, so a reused connection carries
# the previous tenant's org id unless something clears it. `reset` below is
# that something, and pooling MUST NOT be enabled without it. See
# common/rls/pool.py for the full argument.
#
# Sizing: the pool is per PROCESS, not per host. Real peak connections are
# roughly DB_POOL_MAX_SIZE x (uvicorn workers + celery prefork children), and
# docker-compose.yml runs `celery -A crm worker` with no --concurrency, so each
# worker forks one child per CPU. Multiply before comparing to PostgreSQL's
# max_connections (default 100).
DB_POOL_ENABLED = os.environ.get("DB_POOL_ENABLED", "False").lower() == "true"
DB_POOL_MIN_SIZE = int(os.environ.get("DB_POOL_MIN_SIZE", "2"))
DB_POOL_MAX_SIZE = int(os.environ.get("DB_POOL_MAX_SIZE", "10"))
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
@ -102,9 +125,29 @@ DATABASES = {
"PASSWORD": os.environ.get("DBPASSWORD", "postgres"),
"HOST": os.environ.get("DBHOST", "localhost"),
"PORT": os.environ.get("DBPORT", "5432"),
# Django raises ImproperlyConfigured if this is non-zero alongside a
# pool ("Pooling doesn't support persistent connections"). Keep it 0.
"CONN_MAX_AGE": 0,
"CONN_HEALTH_CHECKS": DB_POOL_ENABLED,
}
}
if DB_POOL_ENABLED:
# Imported lazily and locally: common/rls/pool.py deliberately imports no
# Django, but keeping the import inside the branch means a non-pooled
# deployment never touches it at all.
from common.rls.pool import reset_rls_context
DATABASES["default"]["OPTIONS"] = {
"pool": {
"min_size": DB_POOL_MIN_SIZE,
"max_size": DB_POOL_MAX_SIZE,
# Load-bearing for tenant isolation, not a tidy-up. Removing this
# key turns pooling into a cross-tenant data leak.
"reset": reset_rls_context,
}
}
# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators

View file

@ -49,7 +49,12 @@ dependencies = [
"djangorestframework-simplejwt>=5.5.1",
"drf-spectacular>=0.30.0",
"django-ses>=4.7.2",
"psycopg2-binary>=2.9.12",
# psycopg 3, not psycopg2. The `pool` extra is required: Django refuses
# pool options under psycopg2 (ImproperlyConfigured, "Database pooling
# requires psycopg >= 3"), and DATABASES["default"]["OPTIONS"]["pool"] in
# crm/settings.py depends on it. No application code imports the driver
# directly, so the swap is confined to this line.
"psycopg[binary,pool]>=3.2.10",
"whitenoise>=6.12.0",
"sentry-sdk>=2.66.1",
"django-storages>=1.14.6",
@ -72,15 +77,6 @@ dependencies = [
"uvicorn[standard]>=0.51.0",
]
[project.optional-dependencies]
# Hosted MCP server, mounted at /mcp by crm.asgi (opt-in: install with
# `uv sync --extra mcp`). Pulls in fastmcp + starlette. The core app does not
# depend on it, so the default install stays lean.
mcp = ["bcrm-mcp"]
[tool.uv.sources]
bcrm-mcp = { path = "../mcp_server", editable = true }
[project.urls]
Homepage = "https://github.com/django-crm/Django-CRM"
Repository = "https://github.com/django-crm/Django-CRM"

File diff suppressed because it is too large Load diff

View file

@ -160,7 +160,6 @@ Interactive versions of the same schema are served by a running backend at
| `/api/macros/{id}/render/` | POST |
| `/api/notifications/` | GET |
| `/api/notifications/read-all/` | POST |
| `/api/notifications/stream/` | GET |
| `/api/notifications/{id}/` | DELETE |
| `/api/notifications/{id}/read/` | POST |
| `/api/opportunities/` | GET, POST |

View file

@ -35,7 +35,7 @@ filter here is the only tenant boundary, not a belt over RLS's braces):
"tokens": [
{
"id": "<uuid>",
"name": "laptop mcp",
"name": "reporting script",
"token_prefix": "bcrm_pat_abc1",
"scopes": [],
"expires_at": null,
@ -56,7 +56,7 @@ filter here is the only tenant boundary, not a belt over RLS's braces):
`POST /api/profile/tokens/` (same view, `:49-69`) creates a token for the caller:
```json
{"name": "laptop mcp", "scopes": [], "expires_at": null}
{"name": "reporting script", "scopes": [], "expires_at": null}
```
`name` is required (non-empty, at most 255 characters); `scopes`, if present, must be a list of
@ -68,7 +68,7 @@ strings (at most 32); `expires_at` is optional, but if present must be in the fu
{
"error": false,
"id": "<uuid>",
"name": "laptop mcp",
"name": "reporting script",
"token_prefix": "bcrm_pat_abc1",
"scopes": [],
"expires_at": null,
@ -106,7 +106,7 @@ endpoint is never the thing that has to be loosened to support oversight:
"tokens": [
{
"id": "<uuid>",
"name": "laptop mcp",
"name": "reporting script",
"token_prefix": "bcrm_pat_abc1",
"scopes": [],
"expires_at": null,

View file

@ -143,7 +143,7 @@ one transaction for the same reason the refresh endpoint's does.
## Personal access tokens
Personal access tokens (`bcrm_pat_…`, `PersonalAccessToken` in `backend/common/models.py`) are
for agents and scripts, the MCP server integration in particular, that need to authenticate as a
for agents and scripts that need to authenticate as a
specific user without going through the JWT/OAuth flow on every call. A token is generated once
(`PersonalAccessToken.generate(profile, name, ...)`), shown to the caller exactly once, and stored
only as a SHA-256 hash (`token_hash`); the plaintext is not recoverable from the database

View file

@ -23,7 +23,7 @@ that it forgot to.
**But read this before running anything:** as of this writing, none of `black`, `isort`, or `ruff`
is declared as a dependency anywhere in `backend/pyproject.toml`, not in `[project.dependencies]`,
not in the `dev` or `docs` groups under `[dependency-groups]`, not in the `mcp` extra, and not
not in the `dev` or `docs` groups under `[dependency-groups]`, and not
pulled in transitively (`backend/uv.lock` has no entry for any of the three). `uv sync` on a fresh
clone will not install any of them, and `uv run black .` fails on a fresh clone with `error: Failed
to spawn: 'black' / Caused by: No such file or directory`. The same is true of `isort` and `ruff`.

View file

@ -48,13 +48,11 @@ removing a dependency (for example, to pick up a transitive security fix) use `u
instead; it re-resolves and rewrites `uv.lock` in place.
`backend/pyproject.toml` currently declares two dependency groups: `dev` (`pytest`,
`pytest-django`, `pytest-cov`) and `docs` (`mkdocs-material`), plus one optional extra, `mcp`, for
the hosted MCP server (`uv sync --extra mcp`, not installed by default). `dev` is treated as a
`pytest-django`, `pytest-cov`) and `docs` (`mkdocs-material`). `dev` is treated as a
default group by `uv`, so `uv sync` on its own installs it; a plain `uv sync --group docs` installs
`docs` **in addition to** `dev`, not instead of it: that's why CI's `docs-build` job, which runs
exactly `uv sync --frozen --group docs`, is able to run `uv run pytest ...` in the very next step
(see [Pull requests](pull-requests.md#what-ci-runs)). `mcp` is the one group/extra that stays out
unless you ask for it explicitly with `--extra mcp`. See [Code style](code-style.md) before reaching
(see [Pull requests](pull-requests.md#what-ci-runs)). See [Code style](code-style.md) before reaching
for `uv add black` or similar. It is not as simple as it sounds in this repository.
## Frontend

View file

@ -14,8 +14,6 @@ Django-CRM/
├── docker/ # Docker-specific config: docker/postgres/init-rls-user.sql (creates the
│ # non-superuser RLS role) and docker/backend/entrypoint.sh. That's the
│ # whole directory, no Redis config lives here
├── mcp_server/ # The hosted MCP server (backend's optional `mcp` extra). See
│ # Integrations → MCP server
├── mkdocs.yml # Docs site config and nav
├── docker-compose.yml # Full local stack. See Self-hosting → Docker
├── CONTRIBUTING.md # The short version of this Contributing section

View file

@ -0,0 +1,91 @@
# AI agents
An AI agent talks to BottleCRM the same way any other program does: over the REST API under
`/api/`, authenticated with a personal access token. There is no separate agent protocol, no
agent-specific endpoint, and no service account. The agent is a normal API client, so RLS, RBAC
and field validation apply to it exactly as they apply to the web app and the mobile app.
This is a deliberate choice. BottleCRM previously shipped a Model Context Protocol (MCP) server at
`/mcp`, a thin proxy that re-issued each tool call as an HTTP request to this same API. It covered
eight entities out of the full product and added no capability the API did not already have, so it
was removed. Point your agent at the API directly and it can reach everything.
## Give the agent a token
Mint a personal access token in the CRM at **Settings → API tokens** (`/settings/api-tokens`), or
via `POST /api/profile/tokens/`. The raw value is shown exactly once, at creation. Only a SHA-256
hash is stored, so a lost token cannot be recovered, only replaced.
Every request carries it as a bearer token:
```bash
curl -H "Authorization: Bearer bcrm_pat_..." \
https://api.bottlecrm.io/api/leads/
```
See [Tokens and API keys](../api/tokens-and-api-keys.md#personal-access-tokens) for the full
lifecycle: creation, expiry, validation and revocation.
## Let the agent discover the API
The backend publishes an OpenAPI 3 schema generated by drf-spectacular. Feed it to the agent and
it can work out the endpoints, request bodies, enums and required fields on its own, without you
hand-maintaining a tool registry that drifts from the real URLconf:
| What | Where |
| --- | --- |
| Machine-readable schema | `GET /schema/` |
| Interactive browser docs | `/swagger-ui/` |
| ReDoc rendering | `/api/schema/redoc/` |
| Hand-written endpoint list | [Endpoint index](../api/endpoint-index.md) |
Request and response shapes, pagination, filtering and error envelopes are described in
[API conventions](../api/conventions.md) and [Errors](../api/errors.md).
## Permissions
**The agent is exactly as privileged as the token it holds, no more and no less.**
`PATAuthentication` (`backend/common/pat_auth.py`) resolves the token to its owning `Profile` and
sets `request.profile` and `request.org` from it, the same code path every other PAT-authenticated
request goes through. The agent inherits that user's role, org and RLS scope.
A token does carry a `scopes` field, but **nothing enforces it yet**. There is currently no way to
issue an agent a token narrower than its owner's own access. Treat every token you configure into
an agent as equivalent to handing that agent your login for as long as the token is valid, and
give it to a profile whose role matches the job you want done.
A token stops working the moment its owning profile or org is deactivated: `resolve_valid_pat`
rejects it with "Token owner or org is inactive". That makes a deactivated user's token dormant
rather than live, though it is still worth revoking on offboarding, because reactivating the
account revives the token.
## Revoking
To cut off an agent immediately, revoke its token. Which endpoint you use depends on your role:
- **Any role, own token**: `DELETE /api/profile/tokens/{id}/`. Self-service, scoped to your own
tokens. Another user's token id returns 404 rather than being revoked.
- **Admins, any token in the org**: `DELETE /api/org/tokens/{id}/`, backed by the org-wide
oversight list at `GET /api/org/tokens/`. This is what the **Settings → API tokens** page calls.
A non-admin who opens that page sees "Admins only", not a token list.
Revoke is idempotent: a second call on an already-revoked token is a no-op 200.
## Practical notes
A few API details that commonly trip up a first agent integration:
- **Comments are not a sub-action.** Every module routes them at `comment/<id>/`, for example
`POST /api/leads/comment/<id>/`, not `/api/leads/<id>/add_comment/`.
- **Converting a lead is a status change**, not an action endpoint:
`PATCH /api/leads/<id>/` with `{"status": "converted"}`.
- **Solutions live under the cases app** at `/api/cases/solutions/`, not at a top-level
`/api/solutions/`.
- **`InvoiceDetailView` implements only `get` and `put`.** A `PATCH` or `DELETE` against
`/api/invoices/<id>/` returns 405. Use a full `PUT`, or `POST /api/invoices/<id>/send/` to send
one. See [Invoices and estimates](../api/invoices.md).
- **Sending an invoice emails a customer.** If you let an agent call it, put a confirmation step in
front of it. The API will not ask twice.
Worked examples in two languages: [Python](python-sample.md) and
[JavaScript](javascript-sample.md).

View file

@ -5,7 +5,7 @@ replies onto the same case automatically. This is the **only** webhook in the pr
in one direction only: BottleCRM *receives* mail through it. Nothing in this codebase posts a
webhook out to a URL you configure. There is no equivalent "notify my system when a case closes"
hook. If you need BottleCRM to push events elsewhere, you're integrating through the
[MCP server](mcp-server.md) or polling the REST API; nothing here does that for you.
[REST API](../api/conventions.md) by polling; nothing here does that for you.
## How inbound email becomes a ticket

View file

@ -1,204 +0,0 @@
# MCP server
`bcrm-mcp` is a [Model Context Protocol](https://modelcontextprotocol.io) server that lets an AI
agent (Claude Desktop, Cursor, Codex CLI, Gemini CLI, or any other MCP client) read and write CRM
data. It lives in its own top-level package, `mcp_server/`, next to `backend/` and `frontend/`,
not inside the Django project, and it is a thin HTTP client of the CRM's own REST API: it has no
database connection of its own and does not import Django (`mcp_server/src/bcrm_mcp/client.py`
depends only on `httpx`). Every tool call becomes one authenticated request to `/api/...`, and the
backend enforces RLS, RBAC and field validation exactly as it would for any other caller.
Source and further detail: [`mcp_server/README.md`](https://github.com/django-crm/Django-CRM/blob/master/mcp_server/README.md)
in the repository.
## What it does
The server exposes eight tools an agent can call. Search/list, get, create, update, delete, a
generic non-CRUD action runner, a schema-describe helper, and an action-discovery helper: over
eight CRM entities: leads, contacts, accounts, opportunities, tasks, cases, invoices and
solutions. It does not add any capability the REST API doesn't already have; it's a uniform,
agent-friendly surface over the same endpoints documented in [API reference](../api/conventions.md).
## Installing
There are two things you can install, depending on how you want to run it.
**The standalone package**, for running the server as a local subprocess your MCP client launches
(the `stdio` transport, the default):
```bash
cd mcp_server
uv sync
```
`uv sync` creates `mcp_server/.venv/` from `mcp_server/pyproject.toml` + `uv.lock`. The package
requires Python 3.11+ and pulls in `fastmcp`, `httpx` and `pydantic`, nothing from the Django
project.
**The `mcp` extra on the backend**, for mounting the server inside the Django app so it's reachable
over HTTP without a local install at all:
```bash
cd backend
uv sync --extra mcp
```
This is declared in `backend/pyproject.toml` as `[project.optional-dependencies] mcp =
["bcrm-mcp"]`, with `bcrm-mcp` resolved via `[tool.uv.sources]` as an editable path dependency on
`../mcp_server`. It is opt-in specifically so the core backend install stays lean, a plain `uv
sync` in `backend/` never pulls in `fastmcp` or `starlette` at all. If the extra isn't installed,
`backend/crm/asgi.py` catches the resulting `ImportError` and serves Django alone; an incomplete or
skipped MCP install never takes the rest of the site down.
## Hosted at /mcp
`backend/crm/asgi.py` optionally mounts the MCP server at exactly `/mcp` on the same process that
serves the rest of the API, no separate deployment. This only activates when three things are all
true: the `mcp` extra is installed, `BCRM_MCP_ENABLED` is not set to a falsy value (`0`, `false`,
`no` or `off`: anything else, including unset, leaves it enabled), and the app is served under
**ASGI**, not WSGI:
```bash
# from backend/
uv sync --extra mcp
BCRM_BASE_URL=http://127.0.0.1:8000 \
uv run uvicorn crm.asgi:application --host 0.0.0.0 --port 8000
# MCP is now live at http://<host>:8000/mcp
```
`manage.py runserver` uses WSGI, so the mount is inactive under the ordinary local dev server.
This is purely an ASGI-server concern and doesn't change any other local workflow.
`BCRM_BASE_URL` is the loopback address the mounted tools call to reach the CRM API; it defaults
to `http://127.0.0.1:8000`, which is correct when MCP and Django share the same process, as they
do here.
The mount dispatches by path prefix rather than Starlette's `Mount` (which only matches
`/mcp/…` with a trailing segment and would let a bare `/mcp` fall through to Django). Both `/mcp`
and `/mcp/...` are routed to the MCP app, everything else goes to Django as before.
## Authenticating
The server has two transports, and they authenticate differently:
- **`stdio`** (default, used when your MCP client launches `bcrm-mcp` as a local subprocess), the
whole process acts as one user. It reads a single token from `BCRM_TOKEN` at startup and reuses
one `CrmClient` for every call. `Settings.from_env()` refuses to start without it.
- **`http`** (the `/mcp` mount above, or a standalone server run with `BCRM_TRANSPORT=http`), a
long-lived, multi-user server. There is no server-side token at all; `Settings.from_env()`
actively rejects a `BCRM_TOKEN` set alongside `BCRM_TRANSPORT=http`, because a shared token would
collapse every caller into one identity. Instead **every request carries its own
`Authorization: Bearer <bcrm_pat_…>` header**, and `ClientResolver.get()`
(`mcp_server/src/bcrm_mcp/server.py`) builds a fresh, uncached `CrmClient` from that header on
every single call, never reused across requests, so one caller's identity can never leak into
the next caller's response.
For the `/mcp` mount specifically, `crm/asgi.py` enforces this at the edge: any request to `/mcp`
or `/mcp/...` with no well-formed bearer token gets a `401` before it reaches the MCP layer at
all, even `initialize` and tool listing are unreachable without a token, not just the tool calls
that touch data. The token's actual validity (not expired, not revoked, owning profile and org
still active) is then re-checked by the backend on every API call the tool makes, the same way any
other PAT-authenticated request is checked. See
[Tokens and API keys](../api/tokens-and-api-keys.md#personal-access-tokens) for how a PAT is
minted, validated and revoked.
In both transports, the token is a normal BottleCRM personal access token
(`bcrm_pat_…`). There is nothing MCP-specific about it.
## Available tools
| Tool | Kind | Description |
| --- | --- | --- |
| `crm_search` | read-only | List/search records of an entity. Takes `query`, `filters`, `limit`, `offset`. `limit` is capped at **50** regardless of what's requested (`MAX_LIMIT` in `mcp_server/src/bcrm_mcp/tools.py`). |
| `crm_get` | read-only | Fetch one record's full detail by `id`. |
| `crm_create` | write | Create a record from a `data` object, validated server-side exactly as `POST` to the underlying endpoint would be. |
| `crm_update` | write | Partially update a record (PATCH semantics) from a `data` object. **Returns an error for `invoices`**. See below. |
| `crm_delete` | destructive | Delete a record. Refuses to run unless called with `confirm=true`. **Also returns an error for `invoices`**. See below. |
| `crm_action` | write | `POST` a non-CRUD action to `/api/<entity>/<id>/<action>/`. Most of the actions `entities.py` lists don't resolve to a real route today. See below before relying on this. |
| `crm_describe` | read-only | Return an entity's fields, types, enums and which are required, derived from the live OpenAPI schema at `/schema/`. |
| `list_actions` | read-only | Return the allowed non-CRUD actions for every entity, exactly as `entities.py` declares them. See below for which of those are actually reachable. |
CRUD tools take an `entity` argument. `resolve_path` (`mcp_server/src/bcrm_mcp/entities.py`) maps
each to its real API path and the non-CRUD actions `entities.py` declares as allowed for it:
| Entity | API path | Non-CRUD actions declared |
| --- | --- | --- |
| `leads` | `/api/leads/` | `convert`, `add_comment` |
| `contacts` | `/api/contacts/` | `add_comment` |
| `accounts` | `/api/accounts/` | `add_comment` |
| `opportunities` | `/api/opportunities/` | `add_comment` |
| `tasks` | `/api/tasks/` |. |
| `cases` | `/api/cases/` | `add_comment` |
| `invoices` | `/api/invoices/` | `send` |
| `solutions` | `/api/cases/solutions/` |. |
Solutions are served under the cases app, not at a top-level `/api/solutions/`: `crm_search(entity="solutions", ...)` resolves to `/api/cases/solutions/` correctly, but it's worth knowing if you're
cross-referencing the [Endpoint index](../api/endpoint-index.md).
**Most of the actions in that table don't work, and neither does `crm_update`/`crm_delete` on
invoices. This is a real bug in `entities.py`, not a doc gap, and it isn't fixed here.**
`crm_action` builds `POST /api/<entity>/<id>/<action>/` (`tools.py`). Checked against the real
Django URLconfs (`leads/urls.py`, `contacts/urls.py`, `accounts/urls.py`, `opportunity/urls.py`,
`cases/urls.py`, `invoices/api_urls.py`):
- **`convert` on `leads`**, no such route exists anywhere in `leads/urls.py`. Converting a lead
is done by setting its status, not by calling an action:
`crm_update(entity="leads", id=..., data={"status": "converted"})`.
- **`add_comment`** on `leads`, `contacts`, `accounts`, `opportunities` and `cases`, none of these
resolve either. Every one of those apps routes comments at `comment/<id>/`
(e.g. `POST /api/leads/comment/<id>/`), not `<id>/add_comment/`, and Django's `<str:pk>` URL
converter doesn't match a `/` inside the segment, so `<id>/add_comment/` matches nothing. No tool
in this MCP server currently reaches the `comment/<id>/` routes at all.
- **`send` on `invoices`** is the only one that actually resolves;
`POST /api/invoices/<id>/send/` is a real route (`invoices/api_urls.py`).
Calling `crm_action` with any of the non-working entries returns a `CrmError` carrying the
backend's `404`. The MCP layer doesn't pre-validate that the action exists before posting.
Separately, `InvoiceDetailView` (`backend/invoices/api_views.py`) implements only `get` and `put`(
no `patch`, no `delete`), so `crm_update` (which sends `PATCH`) and `crm_delete` (which sends
`DELETE`) both come back as a `CrmError` carrying a `405` for `invoices`, regardless of the
`data`/`confirm` you pass. To change an invoice, use `crm_action(entity="invoices",
action="send", confirm=true)` for sending it, or a full `PUT` via the REST API directly (see
[Invoices and estimates](../api/invoices.md)) for anything else. There is no MCP tool that
partially updates or deletes an invoice today.
## Permissions
**The agent is exactly as privileged as the PAT it's given, no more and no less.** `PATAuthentication`
resolves the token to the owning `Profile` and sets `request.profile`/`request.org` from it
(`backend/common/pat_auth.py`), the same code path any other PAT-authenticated request goes
through. There is no separate MCP identity, no elevated service account, and no way for the MCP
layer itself to grant a permission the token's owner doesn't already have. A PAT does carry a
`scopes` field, but nothing in the request-handling code enforces it yet (see
[Tokens and API keys](../api/tokens-and-api-keys.md#personal-access-tokens)), so today there is no
way to hand an agent a narrower token than its owner's own full role and org access. Treat every
PAT you configure into an MCP client as equivalent to handing that agent your own login for as
long as the token is valid.
A few narrower guards live in the MCP layer itself, on top of (not instead of) backend
enforcement:
- `crm_search` caps `limit` at 50 no matter what the agent asks for, so a single call can't pull an
unbounded result set.
- `crm_delete` refuses to run without `confirm=true`.
- `crm_action` refuses an outward-facing action, currently just `send` (emailing a customer an
invoice), without `confirm=true` too, mirroring the delete guard so a model can't trigger a
real-world side effect off a misread instruction.
Beyond that, the MCP server does no authorization of its own: it forwards each tool call to the
CRM API verbatim and surfaces whatever the API returns, success or error (`CrmClient._request`
raises `CrmError` whenever `resp.status_code >= 400`, carrying the DRF error body. A `3xx`
response isn't treated as an error by this check and instead falls through to `resp.json()`,
which would raise its own decode error if that response body isn't JSON).
RLS, role checks and per-object ownership rules are all enforced exactly once, in the backend, the
same as for the web app or the mobile app.
To cut off an agent immediately, revoke its PAT. There are two ways to do that, and which one
applies depends on your role. An admin can revoke any token in the org from the CRM at
**Settings → API tokens** (`/settings/api-tokens`); that page's revoke action calls the
admin-only `DELETE /api/org/tokens/{id}/`, and the whole page is gated on that same admin-only
oversight list (`GET /api/org/tokens/`): a non-admin who opens it sees "Admins only", not a token
list, and can't reach any revoke control there at all. Any role can instead call
`DELETE /api/profile/tokens/{id}/` directly against their **own** token, a separate, self-service
endpoint that no UI on this settings page currently calls, which is the option to use if the PAT
you need to revoke is yours and you aren't an admin.

View file

@ -39,12 +39,10 @@ itself, so they aren't in the table below:
own. See [Production deployment](../self-hosting/production-deploy.md#required-settings) and
[Security hardening](../self-hosting/security-hardening.md#secrets) for what `ENV_TYPE=prod`
actually requires and why it shouldn't be set casually.
- **`BCRM_MCP_ENABLED`** and **`BCRM_BASE_URL`** are two different knobs, both read in
`backend/crm/asgi.py`, not `crm/settings.py`. Only `BCRM_MCP_ENABLED` (default `"true"`) gates
whether the optional MCP server is mounted at `/mcp` at all, anything in `0`/`false`/`no`/`off`
disables it, anything else (including unset) leaves it enabled. `BCRM_BASE_URL` (default
`http://127.0.0.1:8000`) has no bearing on whether the mount happens; it's the REST API root the
mounted MCP tools call once it's live. See [MCP server](../integrations/mcp-server.md) for both.
- **`BCRM_MCP_ENABLED`** and **`BCRM_BASE_URL`** are no longer read anywhere. They gated the
MCP server that used to be mounted at `/mcp`, which has been removed in favour of the REST API.
Both are safe to delete from an existing deployment's environment. See
[AI agents](../integrations/ai-agents.md) for how an agent connects now.
## Reference
@ -66,6 +64,20 @@ itself, so they aren't in the table below:
| `DBHOST` | `localhost` | No | PostgreSQL host. |
| `DBPORT` | `5432` | No | PostgreSQL port. |
### Connection pooling
Pooling uses psycopg 3's `psycopg_pool` through Django's PostgreSQL backend. It is **off by default**, so upgrading does not silently change an existing deployment's connection behaviour. Turning it on also enables `CONN_HEALTH_CHECKS`; `CONN_MAX_AGE` is pinned to `0`, because Django raises `ImproperlyConfigured` ("Pooling doesn't support persistent connections") if a pool is configured alongside persistent connections.
| Variable | Default | Required | Purpose |
| --- | --- | --- | --- |
| `DB_POOL_ENABLED` | `False` | No | `"true"` (case-insensitive) puts a `psycopg_pool.ConnectionPool` in front of the default database and installs the RLS reset callback described below. Anything else leaves the connection behaviour unchanged. |
| `DB_POOL_MIN_SIZE` | `2` | No | Connections the pool keeps open per process even when idle. |
| `DB_POOL_MAX_SIZE` | `10` | No | Ceiling on concurrent connections per process. This is the limit that was missing when the API exhausted PostgreSQL: under ASGI every in-flight request otherwise takes its own connection with no upper bound. |
**Size this against `max_connections`, and remember the pool is per process, not per host.** Peak usage is roughly `DB_POOL_MAX_SIZE × (uvicorn workers + Celery prefork children)`, plus `DB_POOL_MIN_SIZE` held idle by each of those processes. `docker-compose.yml` runs `celery -A crm worker` with no `--concurrency`, so each worker forks one child per CPU. On an 8-core host with 3 uvicorn workers and the defaults, that is `10 × (3 + 8) = 110` connections at peak against PostgreSQL's default `max_connections` of 100.
**Why the reset callback matters.** RLS context lives in `app.current_org`, a session-scoped setting that outlives the transaction and the request. `psycopg_pool` does not clear session state when a connection is returned; it only rolls back an open transaction. A pool without `common.rls.pool.reset_rls_context` therefore hands the next borrower a connection still scoped to the previous tenant. Enabling `DB_POOL_ENABLED` wires that callback in automatically, and `common/tests/test_pool_rls_isolation.py` proves both that it clears the context and that it leaves the connection in the `IDLE` state `psycopg_pool` requires. Do not configure a pool by hand without it.
### Email
| Variable | Default | Required | Purpose |

View file

@ -74,7 +74,7 @@ query the actual resource. See
### Personal access token
`bcrm_pat_…` (`PersonalAccessToken`, `backend/common/models.py`): a token a signed-in user creates
for themselves (`POST /api/profile/tokens/`) to authenticate scripts, the MCP server, or other
for themselves (`POST /api/profile/tokens/`) to authenticate scripts, AI agents, or other
programmatic access without a browser session. It authenticates as the profile that created it and
inherits that profile's role and org in full; its `scopes` field is stored but not enforced.
Deactivating the owning profile invalidates the token immediately; `resolve_valid_pat` checks

View file

@ -38,21 +38,62 @@ cd backend
uv run gunicorn crm.wsgi:application --bind 0.0.0.0:8000
```
There is one documented exception to WSGI, in the codebase's own words. `backend/crm/asgi.py`
carries this docstring:
**WSGI is the recommended path, and there is no longer a reason to prefer ASGI.** Earlier
releases required an ASGI server (`uvicorn crm.asgi:application`) because the in-app notifications
endpoint was a Server-Sent Events stream, and a long-lived async view holds a worker hostage under
WSGI. That stream was removed on 2026-08-03 in favour of polling, and it was the only async code
in the project, so nothing needs ASGI now. `backend/crm/asgi.py` still exists and still works if
you prefer it, but it buys you nothing.
> Production deploy must run an ASGI server pointing at this module:
> `uvicorn crm.asgi:application --host 0.0.0.0 --port 8000`
Prefer WSGI for a concrete reason beyond simplicity: **it bounds your database connections by
construction.** Under ASGI, Django runs each request in its own thread-sensitive executor with its
own thread-local connection and no ceiling, so concurrent requests translate one-to-one into
PostgreSQL backends. That is what caused two connection-exhaustion incidents in this project's
history. Under Gunicorn, peak connections are `workers × threads`, a number you set on the command
line:
The reason given is the in-app notifications SSE (server-sent events) stream: it's an async view
serving a long-lived connection, and running it under WSGI (Gunicorn) "will hold a worker
hostage" for the life of each connection. `crm/asgi.py` also optionally mounts the BottleCRM MCP
server at `/mcp` when the `mcp` extra is installed and `BCRM_MCP_ENABLED` isn't set to a falsy
value. `uvicorn[standard]>=0.51.0` is a listed dependency alongside Gunicorn for exactly this
path. In short: if you need the SSE notification stream (or the MCP mount) to work correctly
under concurrent load, serve via `uvicorn crm.asgi:application`, not Gunicorn/WSGI; if you don't,
Gunicorn against `crm.wsgi:application` is what this project bundles as its production WSGI
dependency.
```bash
cd backend
uv run gunicorn crm.wsgi:application --bind 0.0.0.0:8000 --workers 3 --threads 4
```
That example tops out at 12 database connections per host, plus whatever Celery uses. See
[Database connections](#database-connections) below for pooling, which you may still want if you
run many Gunicorn workers or a large thread count.
`uvicorn[standard]>=0.51.0` remains a dependency so the ASGI path keeps working for anyone already
deployed that way. If you serve under ASGI, read the next section before going live: bounding
connections there is not optional.
## Database connections
Under ASGI, Django runs each request in its own thread-sensitive executor, and each of those gets
its own thread-local database connection. Nothing caps that. A burst of concurrent requests
becomes a burst of PostgreSQL backends, and `max_connections` (default `100`) is reached long
before the application itself is under strain. This project has hit that in production.
Set `DB_POOL_ENABLED=true` to put a bounded `psycopg_pool` pool in front of the database.
`DB_POOL_MAX_SIZE` (default `10`) is the ceiling per process. Size it deliberately: the pool is
per process, so peak usage is roughly `DB_POOL_MAX_SIZE × (uvicorn workers + Celery prefork
children)`. See [Environment variables](../reference/environment-variables.md#connection-pooling)
for the arithmetic and a worked example.
Two things to know before enabling it:
- **The pool requires psycopg 3.** That is what this project depends on
(`psycopg[binary,pool]`); Django raises `ImproperlyConfigured` if pool options are set under
psycopg2. Nothing to do unless you have pinned the driver yourself.
- **Do not hand-roll the pool configuration.** Tenant isolation depends on `app.current_org`, a
session-scoped PostgreSQL setting that survives the transaction and the request. `psycopg_pool`
does not clear session state when a connection is returned, so a pool without the project's
`reset` callback serves one tenant's data to the next borrower of that connection. Setting
`DB_POOL_ENABLED=true` wires the callback in for you. Writing your own `OPTIONS["pool"]` block
without it is a cross-tenant data leak.
An external pooler is a reasonable alternative, with one hard constraint: it must run in
**session** mode. Transaction-mode pooling (PgBouncer's default) does not keep session settings
across statements, which silently breaks the RLS context this application relies on for tenant
isolation.
## Static files

View file

@ -11,15 +11,17 @@
"check": "svelte-kit sync && svelte-check --tsconfig ./jsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./jsconfig.json --watch",
"format": "prettier --write .",
"lint": "prettier --check . && eslint ."
"lint": "prettier --check . && eslint .",
"test": "vitest run",
"test:watch": "vitest"
},
"devDependencies": {
"@eslint/compat": "^2.1.0",
"@eslint/js": "^10.0.1",
"@internationalized/date": "^3.12.2",
"@lucide/svelte": "^1.27.0",
"@internationalized/date": "^3.12.3",
"@lucide/svelte": "^1.28.0",
"@sveltejs/adapter-node": "^5.5.7",
"@sveltejs/kit": "^2.70.1",
"@sveltejs/kit": "^2.70.2",
"@sveltejs/vite-plugin-svelte": "^7.2.0",
"@tailwindcss/typography": "^0.5.20",
"@tailwindcss/vite": "^4.3.3",
@ -28,26 +30,27 @@
"eslint": "^10.8.0",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-svelte": "^3.22.0",
"globals": "^17.7.0",
"globals": "^17.9.0",
"mode-watcher": "^1.1.0",
"prettier": "^3.9.6",
"prettier-plugin-svelte": "^4.1.1",
"prettier-plugin-tailwindcss": "^0.8.1",
"svelte": "^5.56.8",
"svelte-check": "^4.7.3",
"svelte-check": "^4.7.4",
"svelte-sonner": "^1.1.1",
"tailwindcss": "^4.3.3",
"typescript": "^6.0.3",
"vite": "^8.1.5"
"vite": "^8.2.0",
"vitest": "^4.1.10"
},
"dependencies": {
"@sentry/sveltekit": "^10.68.0",
"axios": "^1.18.1",
"@sentry/sveltekit": "^10.69.0",
"axios": "^1.19.0",
"clsx": "^2.1.1",
"libphonenumber-js": "^1.13.9",
"svelte-dnd-action": "^0.9.74",
"libphonenumber-js": "^1.13.10",
"svelte-dnd-action": "^0.9.77",
"tailwind-merge": "^3.6.0",
"tailwind-variants": "^3.2.2",
"tailwind-variants": "^3.3.0",
"tw-animate-css": "^1.4.0"
}
}

File diff suppressed because it is too large Load diff

View file

@ -2,3 +2,8 @@ allowBuilds:
'@sentry/cli': true
onlyBuiltDependencies:
- '@sentry/cli'
overrides:
# GHSA-rgw5-rvv9-x895 (high): DoS via unbounded intermediate arrays.
# Only reachable through dev tooling (eslint, @sentry/vite-plugin), but the
# transitive parents still ask for a vulnerable range, so force the patch.
'brace-expansion@>=4.0.0 <5.0.9': '^5.0.9'

View file

@ -8,12 +8,12 @@
let open = $state(false);
$effect(() => {
notifications.startStream();
return () => notifications.stopStream();
notifications.start();
return () => notifications.stop();
});
// Refresh on first open in case the stream missed any messages while
// we were initialising.
// Opening the panel is an explicit "show me now", so don't make the user
// wait out the poll interval.
$effect(() => {
if (open) notifications.fetch();
});

View file

@ -12,11 +12,27 @@
* so fold the flat fields into that array here and trim the seconds. Holidays
* already arrive as `{ id, date, name }`.
*
* Read-only page: "Edit hours" / "Add holiday" are deferred builders (the
* backend has admin PUT/POST/DELETE endpoints, but no form is wired yet), so
* there is no write path here.
* WRITE PATHS, AND WHO MAY USE THEM
* `updateBusinessHours` runs the fold above backwards: `unfoldDays` turns the
* page's `days` array back into the fourteen flat fields, Monday-first, null
* for a closed day. It PUTs the calendar's OWN url, `/business-hours/calendar/
* <id>/`, not the collection path this module's read uses; `BusinessCalendarView.put`
* is `partial=True` and admin-only, and `is_default` is read-only on
* `BusinessCalendarSerializer`, so it is never part of the outgoing body.
* `addHoliday` and `removeHoliday` write the holiday sub-resource,
* `/business-hours/calendar/<id>/holidays/` and its `<hid>/` detail, also
* admin-only. A holiday add is idempotent on date: posting a date already on
* the calendar returns the existing row with 200, not 201, and creates
* nothing new; that is a normal outcome, not a failure to surface. A holiday
* removal is a hard delete, the row is gone and the day counts as working
* time again immediately. All three fail with 403 and
* `{"error": "Only admins can update business hours."}` for a non-admin;
* `can_edit` below only decides whether the edit controls are offered, since
* the backend re-derives admin status from the request's own profile and is
* what actually refuses.
*/
import { apiRequest } from '$lib/api-helpers.js';
import { viewerRole } from './organization.js';
/** Monday-first weekday label ↔ the model's field prefix. */
const WEEKDAYS = [
@ -36,7 +52,7 @@ function toHm(value) {
/**
* @param {{ cookies: import('@sveltejs/kit').Cookies }} event
* @returns {Promise<{ calendar: any }>}
* @returns {Promise<{ calendar: any, can_edit: boolean }>}
*/
export async function getBusinessHours({ cookies }) {
const cal = await apiRequest('/business-hours/calendar/', {}, { cookies });
@ -56,6 +72,109 @@ export async function getBusinessHours({ cookies }) {
name: h.name,
date: h.date
}))
}
},
// A display hint decoded from the JWT `role` claim, deciding only whether
// the page offers "Edit hours" / "Add holiday". `BusinessCalendarView.put`
// and the holiday views re-derive admin status from `request.profile`
// server-side, and that is what actually refuses a non-admin's write.
can_edit: viewerRole(cookies) === 'ADMIN'
};
}
/**
* Fold the page's `days` array back into the model's fourteen flat fields.
*
* `getBusinessHours` above turns `monday_open` and the rest into
* `days: [{ day, open, close }]` with "HH:MM" times; this is that in
* reverse. A closed day is both fields null. One field null and the other
* set stores a half-open day that the SLA clock reads as nonsense.
* `BusinessCalendarSerializer.validate()` is the real backstop: it already
* refuses a half-open day with a 400 (`(open_val is None) != (close_val is
* None)`). This client-side check exists only to name the day in the
* message, instead of surfacing the serializer's generic per-field error.
*
* @param {{ day: string, open: string | null, close: string | null }[]} days
*/
function unfoldDays(days) {
/** @type {Record<string, string | null>} */
const flat = {};
for (const [label, key] of WEEKDAYS) {
const entry = days.find((d) => d.day === label);
const open = entry?.open || null;
const close = entry?.close || null;
if (Boolean(open) !== Boolean(close)) {
throw new Error(`${label} needs both an opening and a closing time, or neither.`);
}
flat[`${key}_open`] = open;
flat[`${key}_close`] = close;
}
return flat;
}
/**
* Save the week plus the calendar's name and timezone.
*
* PUTs the calendar's own detail url, not the collection path
* `getBusinessHours` reads from; `calendar.id` survives that read's reshape,
* so the caller always has it. `is_default` is read-only on
* `BusinessCalendarSerializer` and is deliberately never part of the body.
*
* @param {{ cookies: import('@sveltejs/kit').Cookies }} event
* @param {string} calendarId
* @param {{ day: string, open: string | null, close: string | null }[]} days
* @param {{ name: string, timezone: string, [key: string]: unknown }} meta caller may pass
* extra fields (e.g. `is_default`, read off the loaded calendar); only
* `name` and `timezone` are ever read out of it
*/
export async function updateBusinessHours({ cookies }, calendarId, days, meta) {
if (!calendarId) throw new Error('Which calendar? No calendar id was given.');
const body = { ...unfoldDays(days), name: meta.name, timezone: meta.timezone };
return await apiRequest(
`/business-hours/calendar/${calendarId}/`,
{ method: 'PUT', body },
{ cookies }
);
}
/**
* Add a holiday to a calendar.
*
* `POST /business-hours/calendar/<id>/holidays/` is idempotent on `date`:
* adding a date already on this calendar returns the existing row with
* HTTP 200, not 201, and creates no duplicate. That is a normal outcome, not
* an error, so callers should not treat it as one and this module does not
* pre-check for an existing date on the client.
*
* @param {{ cookies: import('@sveltejs/kit').Cookies }} event
* @param {string} calendarId
* @param {{ date: string, name: string }} values
*/
export async function addHoliday({ cookies }, calendarId, values) {
if (!values?.date) throw new Error('A holiday needs a date.');
const body = { date: values.date, name: values.name };
return await apiRequest(
`/business-hours/calendar/${calendarId}/holidays/`,
{ method: 'POST', body },
{ cookies }
);
}
/**
* Remove a holiday.
*
* `BusinessHolidayDetailView.delete` is a hard delete: the row is gone, not
* flagged off, and the day it named counts as working time again as soon as
* the request succeeds.
*
* @param {{ cookies: import('@sveltejs/kit').Cookies }} event
* @param {string} calendarId
* @param {string} holidayId
*/
export async function removeHoliday({ cookies }, calendarId, holidayId) {
if (!holidayId) throw new Error('Which holiday? No holiday id was given.');
return await apiRequest(
`/business-hours/calendar/${calendarId}/holidays/${holidayId}/`,
{ method: 'DELETE' },
{ cookies }
);
}

View file

@ -0,0 +1,104 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
const apiRequest = vi.fn();
vi.mock('$lib/api-helpers.js', () => ({ apiRequest: (...a) => apiRequest(...a) }));
const { updateBusinessHours, addHoliday, removeHoliday } =
await import('$lib/server/v2/business-hours.js');
const event = /** @type {any} */ ({ cookies: { get: () => 'token' } });
const week = [
{ day: 'Monday', open: '09:00', close: '17:00' },
{ day: 'Tuesday', open: '09:00', close: '17:00' },
{ day: 'Wednesday', open: '09:00', close: '17:00' },
{ day: 'Thursday', open: '09:00', close: '17:00' },
{ day: 'Friday', open: '09:00', close: '17:00' },
{ day: 'Saturday', open: null, close: null },
{ day: 'Sunday', open: null, close: null }
];
describe('updateBusinessHours', () => {
beforeEach(() => {
apiRequest.mockReset();
});
it('unfolds the days array back into the fourteen flat fields', async () => {
apiRequest.mockResolvedValue({});
await updateBusinessHours(event, 'cal1', week, { name: 'Support', timezone: 'Asia/Kolkata' });
const [endpoint, options] = apiRequest.mock.calls[0];
// The detail URL, not the collection path the read uses.
expect(endpoint).toBe('/business-hours/calendar/cal1/');
expect(options.method).toBe('PUT');
expect(options.body.monday_open).toBe('09:00');
expect(options.body.friday_close).toBe('17:00');
// A closed day is both fields null, never one of them.
expect(options.body.saturday_open).toBeNull();
expect(options.body.saturday_close).toBeNull();
expect(options.body.name).toBe('Support');
expect(options.body.timezone).toBe('Asia/Kolkata');
});
it('never sends is_default, which the serializer marks read-only', async () => {
apiRequest.mockResolvedValue({});
await updateBusinessHours(event, 'cal1', week, {
name: 'Support',
timezone: 'UTC',
is_default: false
});
expect(apiRequest.mock.calls[0][1].body.is_default).toBeUndefined();
});
it('rejects a day with an open but no close, naming the day', async () => {
const broken = week.map((d) => (d.day === 'Wednesday' ? { ...d, close: null } : d));
await expect(
updateBusinessHours(event, 'cal1', broken, { name: 'S', timezone: 'UTC' })
).rejects.toThrow(/Wednesday/);
expect(apiRequest).not.toHaveBeenCalled();
});
it('refuses an empty calendar id before making a request', async () => {
await expect(
updateBusinessHours(event, '', week, { name: 'S', timezone: 'UTC' })
).rejects.toThrow(/calendar/i);
expect(apiRequest).not.toHaveBeenCalled();
});
});
describe('addHoliday', () => {
beforeEach(() => {
apiRequest.mockReset();
});
it('POSTs date and name to the calendar sub-resource', async () => {
apiRequest.mockResolvedValue({ id: 'h1', date: '2026-12-25', name: 'Christmas' });
await addHoliday(event, 'cal1', { date: '2026-12-25', name: 'Christmas' });
const [endpoint, options] = apiRequest.mock.calls[0];
expect(endpoint).toBe('/business-hours/calendar/cal1/holidays/');
expect(options.method).toBe('POST');
expect(options.body).toEqual({ date: '2026-12-25', name: 'Christmas' });
});
it('rejects a missing date before making a request', async () => {
await expect(addHoliday(event, 'cal1', { date: '', name: 'X' })).rejects.toThrow(/date/i);
expect(apiRequest).not.toHaveBeenCalled();
});
});
describe('removeHoliday', () => {
beforeEach(() => {
apiRequest.mockReset();
});
it('DELETEs the holiday under its calendar', async () => {
apiRequest.mockResolvedValue(null);
await removeHoliday(event, 'cal1', 'h1');
const [endpoint, options] = apiRequest.mock.calls[0];
expect(endpoint).toBe('/business-hours/calendar/cal1/holidays/h1/');
expect(options.method).toBe('DELETE');
});
});

View file

@ -8,15 +8,26 @@
* `totals` block { count, active, models_extended, required_with_gaps } for the
* stat cards. Both are org-scoped server-side; the page never counts records.
*
* Read-only page: "New field" is a deferred builder, and the rows have no
* inline edit/toggle controls. No write path here. The page groups by
* target_model and orders by display_order itself.
* Create, edit, turn off and turn back on are all wired below. `key`,
* `target_model` and `field_type` are only ever sent on create: values live in
* each record's `custom_fields` JSON keyed by `key` (see the module docstring
* in `backend/common/custom_fields.py`), so changing `key` orphans them,
* changing `target_model` leaves them on the old entity, and changing
* `field_type` reinterprets values written under the old one.
* `CustomFieldDefinitionSerializer.validate()` freezes all three server-side
* too; this module just avoids offering the doomed edit in the first place.
* "Turn off" is `DELETE /custom-fields/<id>/`, a soft delete
* (`CustomFieldDefinitionDetailView.delete` flips `is_active`, never removes
* the row or the values on records that already carry it). "Turn on" is the
* same `updateCustomField` PUT with only `is_active: true`, since the
* detail view has no separate reactivate endpoint.
*/
import { apiRequest } from '$lib/api-helpers.js';
import { viewerRole } from './organization.js';
/**
* @param {{ cookies: import('@sveltejs/kit').Cookies }} event
* @returns {Promise<{ fields: any[], totals: any }>}
* @returns {Promise<{ fields: any[], totals: any, can_edit: boolean }>}
*/
export async function getCustomFields({ cookies }) {
const resp = await apiRequest('/custom-fields/', {}, { cookies });
@ -27,6 +38,113 @@ export async function getCustomFields({ cookies }) {
active: 0,
models_extended: 0,
required_with_gaps: 0
}
},
can_edit: viewerRole(cookies) === 'ADMIN'
};
}
/** The fields the serializer accepts on create. `org` is set from the JWT
* server-side and `records_missing_value` is computed, so neither appears. */
const CREATE_FIELDS = [
'target_model',
'key',
'label',
'field_type',
'is_required',
'is_filterable',
'display_order',
'is_active'
];
/** Edit omits the three fields `CustomFieldDefinitionSerializer.validate()`
* freezes after creation. Values live in each record's `custom_fields` JSON
* keyed by `key` (see `backend/common/custom_fields.py`): changing `key`
* orphans them, changing `target_model` leaves them on the old entity, and
* changing `field_type` reinterprets values written under the old one. The
* backend refuses all three with a 400; not offering them is better than
* teaching it through a failed save. */
const FROZEN_AFTER_CREATE = ['key', 'target_model', 'field_type'];
const UPDATE_FIELDS = CREATE_FIELDS.filter((f) => !FROZEN_AFTER_CREATE.includes(f));
/** "Very High" to "very-high". Only ever applied to a NEW dropdown option: an
* existing option's value is stored on every record that uses it and must
* survive a relabel untouched. */
function slugifyOptionValue(label) {
return label
.toLowerCase()
.trim()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '');
}
/**
* Shape the request body from an allow-list.
*
* @param {string[]} allowed
* @param {{ [key: string]: any }} values
*/
function buildBody(allowed, values) {
/** @type {Record<string, any>} */
const body = {};
for (const field of allowed) {
if (values[field] === undefined) continue;
body[field] = values[field];
}
if (body.display_order !== undefined) body.display_order = Number(body.display_order) || 0;
for (const flag of ['is_required', 'is_filterable', 'is_active']) {
if (body[flag] !== undefined) body[flag] = Boolean(body[flag]);
}
// `options` is only legal on a dropdown. `validate_definition_options`
// rejects a non-empty options list on any other type, so this is not
// defensive noise: sending it turns a valid text field into a 400.
if (values.field_type === 'dropdown') {
const rows = (values.options ?? [])
.map((/** @type {any} */ o) => ({
value: o.value ? String(o.value) : slugifyOptionValue(String(o.label ?? '')),
label: String(o.label ?? '').trim()
}))
.filter((/** @type {any} */ o) => o.label && o.value);
if (!rows.length) {
throw new Error('A dropdown needs at least one option.');
}
const seen = new Set();
for (const row of rows) {
if (seen.has(row.value)) {
throw new Error(`Two options would both be stored as "${row.value}". Rename one.`);
}
seen.add(row.value);
}
body.options = rows;
}
return body;
}
/** @param {{ cookies: import('@sveltejs/kit').Cookies }} event */
export async function createCustomField({ cookies }, values) {
const body = buildBody(CREATE_FIELDS, values);
return await apiRequest('/custom-fields/', { method: 'POST', body }, { cookies });
}
/** @param {{ cookies: import('@sveltejs/kit').Cookies }} event */
export async function updateCustomField({ cookies }, id, values) {
if (!id) throw new Error('Which field? No field id was given.');
const body = buildBody(UPDATE_FIELDS, values);
return await apiRequest(`/custom-fields/${id}/`, { method: 'PUT', body }, { cookies });
}
/**
* Turn a field off.
*
* `CustomFieldDefinitionDetailView.delete` is a soft delete: it flips
* `is_active` and leaves every stored value readable. The UI says "Turn off"
* for that reason; calling it Delete would promise something the backend does
* not do.
*
* @param {{ cookies: import('@sveltejs/kit').Cookies }} event
*/
export async function deactivateCustomField({ cookies }, id) {
if (!id) throw new Error('Which field? No field id was given.');
return await apiRequest(`/custom-fields/${id}/`, { method: 'DELETE' }, { cookies });
}

View file

@ -0,0 +1,174 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
const apiRequest = vi.fn();
vi.mock('$lib/api-helpers.js', () => ({ apiRequest: (...a) => apiRequest(...a) }));
const { createCustomField, updateCustomField, deactivateCustomField } =
await import('$lib/server/v2/custom-fields.js');
const event = /** @type {any} */ ({ cookies: { get: () => 'token' } });
const base = {
target_model: 'Case',
key: 'severity',
label: 'Severity',
field_type: 'text',
is_required: false,
is_filterable: true,
display_order: 3
};
describe('createCustomField', () => {
beforeEach(() => {
apiRequest.mockReset();
});
it('POSTs the definition to /custom-fields/', async () => {
apiRequest.mockResolvedValue({ id: 'cf1', ...base });
const result = await createCustomField(event, base);
const [endpoint, options] = apiRequest.mock.calls[0];
expect(endpoint).toBe('/custom-fields/');
expect(options.method).toBe('POST');
expect(options.body.key).toBe('severity');
expect(options.body.target_model).toBe('Case');
expect(options.body.display_order).toBe(3);
expect(result.id).toBe('cf1');
});
it('omits options entirely for a non-dropdown field', async () => {
// `validate_definition_options` rejects a non-empty `options` on any type
// other than dropdown, so sending [] or null on a text field is not
// harmless noise, it is the difference between 201 and 400.
apiRequest.mockResolvedValue({});
await createCustomField(event, {
...base,
field_type: 'text',
options: [{ value: 'a', label: 'A' }]
});
expect(apiRequest.mock.calls[0][1].body.options).toBeUndefined();
});
it('sends dropdown options as {value,label} pairs', async () => {
apiRequest.mockResolvedValue({});
await createCustomField(event, {
...base,
field_type: 'dropdown',
options: [
{ value: '', label: 'Very High' },
{ value: 'low', label: 'Low' }
]
});
// A blank value is a new row; the label is slugified into one. An
// existing value is preserved verbatim, because the stored values on
// every record reference it.
expect(apiRequest.mock.calls[0][1].body.options).toEqual([
{ value: 'very-high', label: 'Very High' },
{ value: 'low', label: 'Low' }
]);
});
it('rejects a dropdown with no options before making a request', async () => {
await expect(
createCustomField(event, { ...base, field_type: 'dropdown', options: [] })
).rejects.toThrow(/at least one option/i);
expect(apiRequest).not.toHaveBeenCalled();
});
it('never forwards a client-supplied org', async () => {
apiRequest.mockResolvedValue({});
await createCustomField(event, { ...base, org: 'attacker-org' });
expect(apiRequest.mock.calls[0][1].body.org).toBeUndefined();
});
});
describe('updateCustomField', () => {
beforeEach(() => {
apiRequest.mockReset();
});
it('PUTs to the detail endpoint without key, target_model or field_type', async () => {
// Values live on each record keyed by `key`, and every stored value for a
// field was written and checked against its `field_type`.
// `CustomFieldDefinitionSerializer.validate()` freezes all three
// server-side (a differing value in the PUT body is a 400); this layer is
// what refuses to send any of them in the first place. `field_type` here
// changes to `number`, not `dropdown`, on purpose: a `dropdown` value
// would route through the options-shaping branch, which is a different
// behaviour covered below.
apiRequest.mockResolvedValue({});
await updateCustomField(event, 'cf1', {
...base,
key: 'renamed',
target_model: 'Lead',
field_type: 'number'
});
const [endpoint, options] = apiRequest.mock.calls[0];
expect(endpoint).toBe('/custom-fields/cf1/');
expect(options.method).toBe('PUT');
expect(options.body.key).toBeUndefined();
expect(options.body.target_model).toBeUndefined();
expect(options.body.field_type).toBeUndefined();
expect(options.body.label).toBe('Severity');
});
it('still attaches options when editing an existing dropdown field', async () => {
// `field_type` never reaches the outgoing body (it's frozen), but the
// caller still has to say "this definition is a dropdown" so `buildBody`
// knows to shape and attach `options`. Losing that signal on edit would
// silently drop a dropdown's choices from every save.
apiRequest.mockResolvedValue({});
await updateCustomField(event, 'cf1', {
...base,
field_type: 'dropdown',
options: [{ value: 'low', label: 'Low' }]
});
const [, options] = apiRequest.mock.calls[0];
expect(options.body.field_type).toBeUndefined();
expect(options.body.options).toEqual([{ value: 'low', label: 'Low' }]);
});
it('supports a minimal reactivation body of just is_active', async () => {
// The "Turn on" control posts only an id; its action calls this with
// `{ is_active: true }` and nothing else, deliberately bypassing the
// full-form field reader so a field the form never submitted can't read
// back as an empty string and blank something out (see the `activate`
// action's comment in +page.server.js).
apiRequest.mockResolvedValue({});
await updateCustomField(event, 'cf1', { is_active: true });
const [, options] = apiRequest.mock.calls[0];
expect(options.body).toEqual({ is_active: true });
});
});
describe('deactivateCustomField', () => {
beforeEach(() => {
apiRequest.mockReset();
});
it('DELETEs the detail endpoint', async () => {
apiRequest.mockResolvedValue({ error: false, message: 'Custom field deactivated' });
await deactivateCustomField(event, 'cf1');
const [endpoint, options] = apiRequest.mock.calls[0];
expect(endpoint).toBe('/custom-fields/cf1/');
expect(options.method).toBe('DELETE');
});
it('refuses an empty id before making a request', async () => {
await expect(deactivateCustomField(event, '')).rejects.toThrow(/which/i);
expect(apiRequest).not.toHaveBeenCalled();
});
});

View file

@ -49,6 +49,7 @@
*/
import { apiRequest } from '$lib/api-helpers.js';
import { env } from '$env/dynamic/public';
import { getOrgPeopleAndTeams } from './org-people.js';
const API_BASE_URL = `${env.PUBLIC_DJANGO_API_URL}/api`;
@ -173,32 +174,6 @@ export async function listDocuments({ cookies }) {
return { results, totals: computeTotals(results) };
}
/**
* In-org people and teams for the share pickers.
* `/users/get-teams-and-users/` filters both to `request.profile.org`, so the
* picker can only ever offer in-org targets, the same boundary the upload/edit
* view enforces when it filters `shared_to`/`teams` by org, surfaced early as
* UX.
*
* @param {import('@sveltejs/kit').Cookies} cookies
*/
async function shareOptions(cookies) {
try {
const resp = await apiRequest('/users/get-teams-and-users/', {}, { cookies });
const people = (resp?.profiles ?? []).map((/** @type {any} */ p) => ({
id: p.id,
name: personName(p)
}));
const teams = (resp?.teams ?? []).map((/** @type {any} */ t) => ({
id: t.id,
name: t.name
}));
return { people, teams };
} catch {
return { people: [], teams: [] };
}
}
/**
* The share pickers for the upload form.
*
@ -212,7 +187,7 @@ async function shareOptions(cookies) {
* @param {{ cookies: import('@sveltejs/kit').Cookies }} event
*/
export async function getUploadOptions({ cookies }) {
const { people, teams } = await shareOptions(cookies);
const { people, teams } = await getOrgPeopleAndTeams(cookies);
return { people, teams };
}
@ -233,7 +208,7 @@ export async function getDocumentForEdit({ cookies }, id) {
if (!doc.can_write) return { can_edit: false };
const { people, teams } = await shareOptions(cookies);
const { people, teams } = await getOrgPeopleAndTeams(cookies);
return {
can_edit: true,
people,

View file

@ -3,19 +3,27 @@
*
* Server-only. Reads `GET /cases/escalation-policies/`, at most one row per
* priority. Each row carries the policy's two halves (first_response /
* resolution action + target), the team to notify, and. The reason the page
* exists; `breaches_last_30d`, a server-side count of SLA breaches per
* resolution action + target), the team to notify, and the reason the page
* exists: `breaches_last_30d`, a server-side count of SLA breaches per
* priority over the last 30 days. That count is condition-based, not sourced
* from the escalation event log, so it still surfaces breaches under a dead
* policy (off, or reassigning to nobody), which is the page's whole point.
*
* Read-only page: "Edit policy" is a deferred builder, so there is no write
* path to wire here. The backend returns targets as full profile objects
* (`user_details.name`) and the team as a full team object; the page only wants
* `{ id, name }`, so flatten to that here rather than teach the component the
* backend's nesting.
* The backend returns targets as full profile objects (`user_details.name`)
* and the team as a full team object; the page only wants `{ id, name }`, so
* flatten to that here rather than teach the component the backend's nesting.
* The same flattened shape is what the edit form uses to preselect a target.
*
* Create, edit, turn off, turn on and delete are wired below. The picker
* lists (`people`, `teams`) are NOT fetched here: `settings.js`'s
* `getSettingsHub` calls `getEscalationPolicies` and reads only `.policies`
* off it, so a picker fetch in this function would be a redundant request on
* every settings-hub load. The route's `load` fetches `getOrgPeopleAndTeams`
* itself, in parallel with this.
*/
import { apiRequest } from '$lib/api-helpers.js';
import { ESCALATION_PRIORITIES } from '$lib/v2/enums.js';
import { viewerRole } from './organization.js';
/** Profile → the `{ id, name }` the card renders, or null when unset. */
function shapeTarget(target) {
@ -31,7 +39,7 @@ function shapeTeam(team) {
/**
* @param {{ cookies: import('@sveltejs/kit').Cookies }} event
* @returns {Promise<{ policies: any[] }>}
* @returns {Promise<{ policies: any[], can_edit: boolean }>}
*/
export async function getEscalationPolicies({ cookies }) {
const { policies } = await apiRequest('/cases/escalation-policies/', {}, { cookies });
@ -46,6 +54,75 @@ export async function getEscalationPolicies({ cookies }) {
resolution_target: shapeTarget(p.resolution_target),
notify_team: shapeTeam(p.notify_team),
breaches_last_30d: p.breaches_last_30d ?? { first_response: 0, resolution: 0 }
}))
})),
// A display hint: POST/PUT/DELETE on `/cases/escalation-policies/` each
// start with `_is_admin(request.profile)` server-side and 403 regardless
// of what this says. This only decides whether the page offers the
// controls.
can_edit: viewerRole(cookies) === 'ADMIN'
};
}
export const CREATE_FIELDS = [
'priority',
'first_response_action',
'resolution_action',
'first_response_target_id',
'resolution_target_id',
'notify_team_id',
'is_active'
];
/** `priority` is the natural key and is frozen after create. It is not merely
* unwise to change: `EscalationPolicyDetailView.put` deletes the key from the
* body before the serializer sees it, so a PUT carrying a new priority
* returns 200 and changes nothing. Omitting it here means the page never
* offers a control whose success is a lie. */
export const UPDATE_FIELDS = CREATE_FIELDS.filter((f) => f !== 'priority');
/** @param {string[]} allowed @param {{ [key: string]: any }} values */
function buildBody(allowed, values) {
/** @type {Record<string, any>} */
const body = {};
for (const field of allowed) {
if (values[field] === undefined) continue;
body[field] = values[field];
}
for (const nullable of ['first_response_target_id', 'resolution_target_id', 'notify_team_id']) {
if (body[nullable] === '') body[nullable] = null;
}
if (body.is_active !== undefined) body.is_active = Boolean(body.is_active);
return body;
}
/** @param {{ cookies: import('@sveltejs/kit').Cookies }} event */
export async function createEscalationPolicy({ cookies }, values) {
const body = buildBody(CREATE_FIELDS, values);
if (!ESCALATION_PRIORITIES.includes(body.priority)) {
throw new Error('Pick a priority for the policy.');
}
return await apiRequest('/cases/escalation-policies/', { method: 'POST', body }, { cookies });
}
/** @param {{ cookies: import('@sveltejs/kit').Cookies }} event */
export async function updateEscalationPolicy({ cookies }, id, values) {
if (!id) throw new Error('Which policy? No policy id was given.');
const body = buildBody(UPDATE_FIELDS, values);
return await apiRequest(
`/cases/escalation-policies/${id}/`,
{ method: 'PUT', body },
{ cookies }
);
}
/**
* Delete a policy, permanently. `EscalationPolicyDetailView.delete` calls
* `obj.delete()`. The priority it covered then escalates to nobody, which is
* what the confirm line has to say.
*
* @param {{ cookies: import('@sveltejs/kit').Cookies }} event
*/
export async function deleteEscalationPolicy({ cookies }, id) {
if (!id) throw new Error('Which policy? No policy id was given.');
return await apiRequest(`/cases/escalation-policies/${id}/`, { method: 'DELETE' }, { cookies });
}

View file

@ -0,0 +1,190 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
const apiRequest = vi.fn();
vi.mock('$lib/api-helpers.js', () => ({ apiRequest: (...a) => apiRequest(...a) }));
const {
createEscalationPolicy,
updateEscalationPolicy,
deleteEscalationPolicy,
UPDATE_FIELDS
} = await import('./escalation.js');
const cookies = /** @type {any} */ ({ get: () => 'token' });
const event = /** @type {any} */ ({ cookies });
const base = {
priority: 'Urgent',
first_response_action: 'notify',
resolution_action: 'reassign',
first_response_target_id: 'p1',
resolution_target_id: 'p2',
notify_team_id: 't1',
is_active: true
};
describe('UPDATE_FIELDS', () => {
it('excludes priority, the frozen natural key', () => {
expect(UPDATE_FIELDS).not.toContain('priority');
});
});
describe('createEscalationPolicy', () => {
beforeEach(() => {
apiRequest.mockReset();
});
it('includes priority on create, along with the rest of the allow-list, and drops a hostile org', async () => {
apiRequest.mockResolvedValue({});
await createEscalationPolicy(event, {
...base,
org: 'ATTACKER-ORG',
created_by: 'ATTACKER'
});
const [url, opts] = apiRequest.mock.calls[0];
expect(url).toBe('/cases/escalation-policies/');
expect(opts.method).toBe('POST');
expect(opts.body.priority).toBe('Urgent');
expect(Object.keys(opts.body).sort()).toEqual([
'first_response_action',
'first_response_target_id',
'is_active',
'notify_team_id',
'priority',
'resolution_action',
'resolution_target_id'
]);
expect(opts.body.org).toBeUndefined();
expect(opts.body.created_by).toBeUndefined();
});
it('sends null, not an empty string, for an unselected first_response_target_id', async () => {
apiRequest.mockResolvedValue({});
await createEscalationPolicy(event, { ...base, first_response_target_id: '' });
const { body } = apiRequest.mock.calls[0][1];
expect(body.first_response_target_id).toBeNull();
});
it('sends null, not an empty string, for an unselected resolution_target_id', async () => {
apiRequest.mockResolvedValue({});
await createEscalationPolicy(event, { ...base, resolution_target_id: '' });
const { body } = apiRequest.mock.calls[0][1];
expect(body.resolution_target_id).toBeNull();
});
it('sends null, not an empty string, for an unselected notify_team_id', async () => {
apiRequest.mockResolvedValue({});
await createEscalationPolicy(event, { ...base, notify_team_id: '' });
const { body } = apiRequest.mock.calls[0][1];
expect(body.notify_team_id).toBeNull();
});
it('coerces is_active to a boolean', async () => {
apiRequest.mockResolvedValue({});
await createEscalationPolicy(event, { ...base, is_active: 'true' });
const { body } = apiRequest.mock.calls[0][1];
expect(body.is_active).toBe(true);
expect(typeof body.is_active).toBe('boolean');
});
it('rejects a priority outside the four choices before the round trip', async () => {
await expect(createEscalationPolicy(event, { ...base, priority: 'Critical' })).rejects.toThrow(
/priority/i
);
expect(apiRequest).not.toHaveBeenCalled();
});
it('rejects a missing priority before the round trip', async () => {
await expect(createEscalationPolicy(event, { ...base, priority: '' })).rejects.toThrow(
/priority/i
);
expect(apiRequest).not.toHaveBeenCalled();
});
});
describe('updateEscalationPolicy', () => {
beforeEach(() => {
apiRequest.mockReset();
});
it('PUTs to the detail endpoint', async () => {
apiRequest.mockResolvedValue({});
await updateEscalationPolicy(event, 'e1', base);
const [url, opts] = apiRequest.mock.calls[0];
expect(url).toBe('/cases/escalation-policies/e1/');
expect(opts.method).toBe('PUT');
});
it('never sends priority, even when the caller passes one', async () => {
apiRequest.mockResolvedValue({});
await updateEscalationPolicy(event, 'e1', base);
const { body } = apiRequest.mock.calls[0][1];
expect(body.priority).toBeUndefined();
expect(Object.keys(body)).not.toContain('priority');
});
it('sends only what it is given, with no org/created_by', async () => {
apiRequest.mockResolvedValue({});
await updateEscalationPolicy(event, 'e1', {
...base,
org: 'ATTACKER-ORG',
created_by: 'ATTACKER'
});
const { body } = apiRequest.mock.calls[0][1];
expect(Object.keys(body).sort()).toEqual([
'first_response_action',
'first_response_target_id',
'is_active',
'notify_team_id',
'resolution_action',
'resolution_target_id'
]);
expect(body.org).toBeUndefined();
expect(body.created_by).toBeUndefined();
});
it('sends exactly one key for a minimal { is_active: true } body (the turn-on path)', async () => {
apiRequest.mockResolvedValue({});
await updateEscalationPolicy(event, 'e1', { is_active: true });
const { body } = apiRequest.mock.calls[0][1];
expect(body).toEqual({ is_active: true });
});
it('sends exactly one key for a minimal { is_active: false } body (the turn-off path)', async () => {
apiRequest.mockResolvedValue({});
await updateEscalationPolicy(event, 'e1', { is_active: false });
const { body } = apiRequest.mock.calls[0][1];
expect(body).toEqual({ is_active: false });
});
it('sends null, not an empty string, for an unselected target on update', async () => {
apiRequest.mockResolvedValue({});
await updateEscalationPolicy(event, 'e1', { ...base, first_response_target_id: '' });
const { body } = apiRequest.mock.calls[0][1];
expect(body.first_response_target_id).toBeNull();
});
it('throws when the id is missing', async () => {
await expect(updateEscalationPolicy(event, '', base)).rejects.toThrow(/which policy/i);
expect(apiRequest).not.toHaveBeenCalled();
});
});
describe('deleteEscalationPolicy', () => {
beforeEach(() => {
apiRequest.mockReset();
});
it('DELETEs the detail endpoint', async () => {
apiRequest.mockResolvedValue({});
await deleteEscalationPolicy(event, 'e1');
const [url, opts] = apiRequest.mock.calls[0];
expect(url).toBe('/cases/escalation-policies/e1/');
expect(opts.method).toBe('DELETE');
});
it('throws when the id is missing', async () => {
await expect(deleteEscalationPolicy(event, '')).rejects.toThrow(/which policy/i);
expect(apiRequest).not.toHaveBeenCalled();
});
});

View file

@ -34,6 +34,7 @@
* fields already in the payload, never a second aggregate query.
*/
import { apiRequest } from '$lib/api-helpers.js';
import { getOrgPeopleAndTeams } from './org-people.js';
/** The two goal kinds the backend accepts (common/utils.py GOAL_TYPES). */
export const GOAL_TYPES = ['REVENUE', 'DEALS_CLOSED'];
@ -191,31 +192,6 @@ export async function listGoals({ cookies }) {
};
}
/**
* In-org people and teams for the create/edit pickers.
* `/users/get-teams-and-users/` filters both to `request.profile.org`, so the
* picker can only ever offer in-org targets. The same boundary the serializer
* now enforces, surfaced early as UX.
*
* @param {import('@sveltejs/kit').Cookies} cookies
*/
async function targetOptions(cookies) {
try {
const resp = await apiRequest('/users/get-teams-and-users/', {}, { cookies });
const people = (resp?.profiles ?? []).map((/** @type {any} */ p) => ({
id: p.id,
name: personName(p)
}));
const teams = (resp?.teams ?? []).map((/** @type {any} */ t) => ({
id: t.id,
name: t.name
}));
return { people, teams };
} catch {
return { people: [], teams: [] };
}
}
/**
* What the create form needs. `can_edit` gates the whole route: creating a goal
* is admin-only server-side, and a non-admin who reaches `/goals/new` gets
@ -225,7 +201,7 @@ async function targetOptions(cookies) {
*/
export async function getGoalFormOptions({ cookies }) {
if (viewerRole(cookies) !== 'ADMIN') return { can_edit: false };
const { people, teams } = await targetOptions(cookies);
const { people, teams } = await getOrgPeopleAndTeams(cookies);
return { can_edit: true, people, teams };
}
@ -242,7 +218,7 @@ export async function getGoalForEdit({ cookies }, id) {
const [raw, { people, teams }] = await Promise.all([
apiRequest(`/opportunities/goals/${id}/`, {}, { cookies }),
targetOptions(cookies)
getOrgPeopleAndTeams(cookies)
]);
const target = raw.assigned_to

View file

@ -12,14 +12,22 @@
* came from the provider. Anything holding it can forge tickets into this org.
* The backend already strips it for non-admins, but this layer drops it for
* everyone: it is never needed to render the page, so it never reaches the
* browser, admin or not. Rotation is an explicit action elsewhere, not a field
* on a page you can browse to.
* browser, admin or not. `topic_arn` embeds the AWS account id and is held to
* the same bar. Rotation and a one-time reveal on create are an explicit,
* separate feature this task does not build, not a field on a page you can
* browse to.
*
* Read-only page: "Add address" / "Edit" are deferred builders, so there is no
* write path here. The backend returns `default_assignee` as a full profile
* object (name under `user_details.name`); the page wants `{ id, name }`.
* The rule extends to the write side, below: `CREATE_FIELDS` and
* `UPDATE_FIELDS` exclude both fields too, on purpose, not by oversight. See
* the comment above `CREATE_FIELDS` for why omitting them is strictly better
* than any form could do.
*
* Create, edit, turn off, turn on and delete are wired below. The backend
* returns `default_assignee` as a full profile object (name under
* `user_details.name`); the page wants `{ id, name }`.
*/
import { apiRequest } from '$lib/api-helpers.js';
import { viewerRole } from './organization.js';
/** Profile → the `{ id, name }` the card reads, or null. */
function shapeAssignee(p) {
@ -29,7 +37,7 @@ function shapeAssignee(p) {
/**
* @param {{ cookies: import('@sveltejs/kit').Cookies }} event
* @returns {Promise<{ mailboxes: any[], totals: any }>}
* @returns {Promise<{ mailboxes: any[], totals: any, can_edit: boolean }>}
*/
export async function getMailboxes({ cookies }) {
const { mailboxes, totals } = await apiRequest('/cases/mailboxes/', {}, { cookies });
@ -48,6 +56,82 @@ export async function getMailboxes({ cookies }) {
cases_last_30d: m.cases_last_30d ?? 0,
last_received_at: m.last_received_at ?? null
})),
totals: totals ?? { count: 0, active: 0, cases_last_30d: 0 }
totals: totals ?? { count: 0, active: 0, cases_last_30d: 0 },
// A display hint: POST/PUT/DELETE on `/cases/mailboxes/` each start with
// `_is_admin(request.profile)` server-side and 403 regardless of what this
// says. This only decides whether the page offers the controls. GET itself
// is not role-gated, so a member can still see this list.
can_edit: viewerRole(cookies) === 'ADMIN'
};
}
/** No `webhook_secret`, no `topic_arn`. `InboundMailboxListCreateView.post`
* generates a `secrets.token_urlsafe(32)` secret when the body carries none,
* which is a better secret than a pasted one, and `put` is `partial=True`,
* so omitting the key leaves the live credential untouched. A form field for
* either would mean the credential travels to a browser and back on every
* edit, and an empty one would blank it. */
const CREATE_FIELDS = [
'address',
'provider',
'default_priority',
'default_case_type',
'default_assignee_id',
'is_active'
];
/** `address` is the mailbox's identity and its uniqueness key. It is not
* frozen by the backend (`validate_address` only checks duplicates on
* create, and `put` is partial), so an edit may change it. It stays in the
* update allow-list for that reason, with a hint on the form saying mail to
* the old address stops becoming tickets. */
const UPDATE_FIELDS = CREATE_FIELDS;
/** @param {string[]} allowed @param {{ [key: string]: any }} values */
function buildBody(allowed, values) {
/** @type {Record<string, any>} */
const body = {};
for (const field of allowed) {
if (values[field] === undefined) continue;
body[field] = values[field];
}
// Two nullable fields whose "none selected" option is an empty `<option>`
// value. `''` fails the ChoiceField and the PK lookup alike; `null` is what
// clears them, and both are `allow_null=True` on the serializer.
for (const nullable of ['default_case_type', 'default_assignee_id']) {
if (body[nullable] === '') body[nullable] = null;
}
if (body.is_active !== undefined) body.is_active = Boolean(body.is_active);
if (body.address !== undefined) {
body.address = String(body.address).trim().toLowerCase();
}
return body;
}
/** @param {{ cookies: import('@sveltejs/kit').Cookies }} event */
export async function createMailbox({ cookies }, values) {
const body = buildBody(CREATE_FIELDS, values);
if (!body.address) throw new Error('A mailbox needs an address.');
return await apiRequest('/cases/mailboxes/', { method: 'POST', body }, { cookies });
}
/** @param {{ cookies: import('@sveltejs/kit').Cookies }} event */
export async function updateMailbox({ cookies }, id, values) {
if (!id) throw new Error('Which mailbox? No mailbox id was given.');
const body = buildBody(UPDATE_FIELDS, values);
return await apiRequest(`/cases/mailboxes/${id}/`, { method: 'PUT', body }, { cookies });
}
/**
* Delete a mailbox, permanently.
*
* `InboundMailboxDetailView.delete` calls `obj.delete()`. Hard delete, and it
* takes the row's `webhook_secret` with it, so mail already in flight from the
* provider stops verifying the moment this runs, not just stops opening tickets.
*
* @param {{ cookies: import('@sveltejs/kit').Cookies }} event
*/
export async function deleteMailbox({ cookies }, id) {
if (!id) throw new Error('Which mailbox? No mailbox id was given.');
return await apiRequest(`/cases/mailboxes/${id}/`, { method: 'DELETE' }, { cookies });
}

View file

@ -0,0 +1,197 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
const apiRequest = vi.fn();
vi.mock('$lib/api-helpers.js', () => ({ apiRequest: (...a) => apiRequest(...a) }));
const { createMailbox, updateMailbox, deleteMailbox } = await import('./inbound-email.js');
const cookies = /** @type {any} */ ({ get: () => 'token' });
const event = /** @type {any} */ ({ cookies });
const base = {
address: 'Support@Example.io',
provider: 'ses',
default_priority: 'Normal',
default_case_type: 'Question',
default_assignee_id: 'p1',
is_active: true
};
describe('createMailbox', () => {
beforeEach(() => {
apiRequest.mockReset();
});
it('sends only allow-listed keys on create and drops a hostile org', async () => {
apiRequest.mockResolvedValue({});
await createMailbox(event, {
...base,
org: 'ATTACKER-ORG',
created_by: 'ATTACKER'
});
const [url, opts] = apiRequest.mock.calls[0];
expect(url).toBe('/cases/mailboxes/');
expect(opts.method).toBe('POST');
expect(Object.keys(opts.body).sort()).toEqual([
'address',
'default_assignee_id',
'default_case_type',
'default_priority',
'is_active',
'provider'
]);
expect(opts.body.org).toBeUndefined();
expect(opts.body.created_by).toBeUndefined();
});
it('never sends a webhook_secret or topic_arn, even when handed one', async () => {
apiRequest.mockResolvedValue({});
await createMailbox(event, {
...base,
webhook_secret: 'ATTACKER-CHOSEN',
topic_arn: 'arn:aws:sns:us-east-1:999999999999:x'
});
const [, opts] = apiRequest.mock.calls[0];
expect(opts.body.webhook_secret).toBeUndefined();
expect(opts.body.topic_arn).toBeUndefined();
});
it('trims and lowercases the address before sending', async () => {
apiRequest.mockResolvedValue({});
await createMailbox(event, { ...base, address: ' Support@Example.IO ' });
const { body } = apiRequest.mock.calls[0][1];
expect(body.address).toBe('support@example.io');
});
it('sends null, not an empty string, for an unselected default_case_type', async () => {
apiRequest.mockResolvedValue({});
await createMailbox(event, { ...base, default_case_type: '' });
const { body } = apiRequest.mock.calls[0][1];
expect(body.default_case_type).toBeNull();
});
it('sends null, not an empty string, for an unselected default_assignee_id', async () => {
apiRequest.mockResolvedValue({});
await createMailbox(event, { ...base, default_assignee_id: '' });
const { body } = apiRequest.mock.calls[0][1];
expect(body.default_assignee_id).toBeNull();
});
it('coerces is_active to a boolean', async () => {
apiRequest.mockResolvedValue({});
await createMailbox(event, { ...base, is_active: 'true' });
const { body } = apiRequest.mock.calls[0][1];
expect(body.is_active).toBe(true);
expect(typeof body.is_active).toBe('boolean');
});
it('refuses a mailbox with no address before making a request', async () => {
await expect(createMailbox(event, { ...base, address: '' })).rejects.toThrow(
/needs an address/i
);
expect(apiRequest).not.toHaveBeenCalled();
});
it('refuses a mailbox whose address is only whitespace before making a request', async () => {
await expect(createMailbox(event, { ...base, address: ' ' })).rejects.toThrow(
/needs an address/i
);
expect(apiRequest).not.toHaveBeenCalled();
});
});
describe('updateMailbox', () => {
beforeEach(() => {
apiRequest.mockReset();
});
it('PUTs to the detail endpoint', async () => {
apiRequest.mockResolvedValue({});
await updateMailbox(event, 'm1', base);
const [url, opts] = apiRequest.mock.calls[0];
expect(url).toBe('/cases/mailboxes/m1/');
expect(opts.method).toBe('PUT');
});
it('sends only what it is given, with no org/created_by', async () => {
apiRequest.mockResolvedValue({});
await updateMailbox(event, 'm1', {
...base,
org: 'ATTACKER-ORG',
created_by: 'ATTACKER'
});
const { body } = apiRequest.mock.calls[0][1];
expect(Object.keys(body).sort()).toEqual([
'address',
'default_assignee_id',
'default_case_type',
'default_priority',
'is_active',
'provider'
]);
expect(body.org).toBeUndefined();
expect(body.created_by).toBeUndefined();
});
it('never sends a webhook_secret or topic_arn, even when handed one', async () => {
apiRequest.mockResolvedValue({});
await updateMailbox(event, 'm1', {
...base,
webhook_secret: 'ATTACKER-CHOSEN',
topic_arn: 'arn:aws:sns:us-east-1:999999999999:x'
});
const { body } = apiRequest.mock.calls[0][1];
expect(body.webhook_secret).toBeUndefined();
expect(body.topic_arn).toBeUndefined();
});
it('sends exactly one key for a minimal { is_active: true } body (the turn-on path)', async () => {
apiRequest.mockResolvedValue({});
await updateMailbox(event, 'm1', { is_active: true });
const { body } = apiRequest.mock.calls[0][1];
expect(body).toEqual({ is_active: true });
});
it('sends exactly one key for a minimal { is_active: false } body (the turn-off path)', async () => {
apiRequest.mockResolvedValue({});
await updateMailbox(event, 'm1', { is_active: false });
const { body } = apiRequest.mock.calls[0][1];
expect(body).toEqual({ is_active: false });
});
it('does not require an address, since a turn-on/off submits none', async () => {
apiRequest.mockResolvedValue({});
await expect(updateMailbox(event, 'm1', { is_active: true })).resolves.toBeDefined();
});
it('trims and lowercases an address when one is submitted', async () => {
apiRequest.mockResolvedValue({});
await updateMailbox(event, 'm1', { address: ' New@Example.IO ' });
const { body } = apiRequest.mock.calls[0][1];
expect(body.address).toBe('new@example.io');
});
it('throws when the id is missing', async () => {
await expect(updateMailbox(event, '', base)).rejects.toThrow(/which mailbox/i);
expect(apiRequest).not.toHaveBeenCalled();
});
});
describe('deleteMailbox', () => {
beforeEach(() => {
apiRequest.mockReset();
});
it('DELETEs the detail endpoint', async () => {
apiRequest.mockResolvedValue({});
await deleteMailbox(event, 'm1');
const [url, opts] = apiRequest.mock.calls[0];
expect(url).toBe('/cases/mailboxes/m1/');
expect(opts.method).toBe('DELETE');
});
it('throws when the id is missing', async () => {
await expect(deleteMailbox(event, '')).rejects.toThrow(/which mailbox/i);
expect(apiRequest).not.toHaveBeenCalled();
});
});

View file

@ -456,3 +456,82 @@ async function fetchDetail(cookies, id) {
throw err;
}
}
/**
* Create a lead.
*
* Mirrors `updateLead`, with one deliberate difference: update sends only the
* fields the form submitted, because the API treats absent as "leave alone".
* Create has nothing to leave alone, so every editable field is sent and an
* empty one is sent as null, which is how the serializer records "no value".
*
* `org` and `created_by` are never sent. The backend derives both from the
* JWT, and accepting them from a form body is how a tenant boundary gets
* crossed. The loop below only ever reads keys named in EDITABLE_FIELDS, so an
* extra key in `values` cannot reach the request.
*
* @param {{ cookies: import('@sveltejs/kit').Cookies }} event
* @param {Record<string, any>} values
* @returns {Promise<any>} the `LeadListView.post` response body. Confirmed against the
* running backend: on success this is `{ error: false, message: "Lead Created Successfully" }`,
* with no `id` field. Unlike `createDeal`'s response, which does carry one
* (`OpportunityListView.post` adds it deliberately), a caller here cannot read `.id` off the
* result to open the record it just created. `+page.server.js` accounts for this and falls
* back to the list rather than assuming an id that is not there.
*/
export async function createLead({ cookies }, values) {
/** @type {Record<string, any>} */
const body = {};
for (const field of EDITABLE_FIELDS) {
const value = values[field];
body[field] = value === '' || value === undefined ? null : value;
}
if (values.opportunity_amount !== undefined) {
const amount = values.opportunity_amount;
body.opportunity_amount = amount === '' || amount == null ? null : Number(amount);
}
// Single-select owner, sent as the list the API expects. Empty means
// unassigned, which is a real state, so it is sent rather than skipped.
body.assigned_to = values.assigned_to ? [values.assigned_to] : [];
return await apiRequest('/leads/', { method: 'POST', body }, { cookies });
}
/**
* Who the session actually is, rather than who a form claims to be. The owner
* select defaults to this. Empty on failure: an unassigned lead is a better
* outcome than a wrongly assigned one, and the select is right there.
*
* Exported for `macros.js`, which needs the same "who am I" resolution to
* compare against a macro's `owner.id`; a second copy of this call would be
* the same mistake `viewerRole` made before phase 1 consolidated it.
*
* @param {import('@sveltejs/kit').Cookies} cookies
*/
// Despite the name `user_obj`, `ProfileView.get` serializes `request.profile`
// (a Profile, not a User) through `ProfileSerializer`, so `user_obj.id` below
// is the Profile's own id. The payload key is a holdover from the API's
// naming, not a description of what it returns.
export async function myProfileId(cookies) {
try {
const response = await apiRequest('/profile/', {}, { cookies });
return response.user_obj?.id ?? '';
} catch {
return '';
}
}
/**
* Everything the create form needs to render its selects, in one call.
*
* @param {{ cookies: import('@sveltejs/kit').Cookies }} event
*/
export async function getLeadFormOptions({ cookies }) {
const [owners, mine] = await Promise.all([listOwners(cookies), myProfileId(cookies)]);
return {
owners,
defaults: { assigned_to: mine, status: 'assigned' }
};
}

View file

@ -0,0 +1,56 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
const apiRequest = vi.fn();
vi.mock('$lib/api-helpers.js', () => ({ apiRequest: (...a) => apiRequest(...a) }));
const { createLead } = await import('$lib/server/v2/leads.js');
// Cast rather than shaping a full Cookies mock: createLead only ever calls
// `cookies.get`, and `apiRequest` itself is mocked above, so nothing here
// touches `getAll`/`set`/`delete`/`serialize`. Without the cast svelte-check
// flags this object against SvelteKit's full `Cookies` type on every call site
// below, which is noise for a shape the test deliberately keeps minimal.
const event = /** @type {any} */ ({ cookies: { get: () => 'token' } });
describe('createLead', () => {
beforeEach(() => {
apiRequest.mockReset();
});
it('POSTs to /leads/ and returns the created lead', async () => {
apiRequest.mockResolvedValue({ id: 'abc', first_name: 'Ada' });
const result = await createLead(event, { first_name: 'Ada', last_name: 'Lovelace' });
expect(apiRequest).toHaveBeenCalledOnce();
const [endpoint, options] = apiRequest.mock.calls[0];
expect(endpoint).toBe('/leads/');
expect(options.method).toBe('POST');
expect(options.body.first_name).toBe('Ada');
expect(result.id).toBe('abc');
});
it('sends an empty field as null rather than an empty string', async () => {
apiRequest.mockResolvedValue({ id: 'abc' });
await createLead(event, { first_name: 'Ada', job_title: '' });
expect(apiRequest.mock.calls[0][1].body.job_title).toBeNull();
});
it('coerces opportunity_amount to a number', async () => {
apiRequest.mockResolvedValue({ id: 'abc' });
await createLead(event, { first_name: 'Ada', opportunity_amount: '4200.50' });
expect(apiRequest.mock.calls[0][1].body.opportunity_amount).toBe(4200.5);
});
it('wraps a single owner id in a list, matching the API contract', async () => {
apiRequest.mockResolvedValue({ id: 'abc' });
await createLead(event, { first_name: 'Ada', assigned_to: 'profile-1' });
expect(apiRequest.mock.calls[0][1].body.assigned_to).toEqual(['profile-1']);
});
it('never forwards a client-supplied org, which the backend derives from the JWT', async () => {
apiRequest.mockResolvedValue({ id: 'abc' });
await createLead(event, { first_name: 'Ada', org: 'attacker-org', created_by: 'someone' });
const body = apiRequest.mock.calls[0][1].body;
expect(body.org).toBeUndefined();
expect(body.created_by).toBeUndefined();
});
});

View file

@ -7,9 +7,24 @@
* the reference card. Visibility is decided by the API from the JWT, a member
* never sees another member's personal macros, so nothing here filters rows.
*
* This page is read-only: it lists and explains macros; the only mutating
* control ("New macro") is a builder that is not wired yet. There is no write
* path here.
* WRITE PATHS, AND WHO MAY USE THEM
* This page's permission model is unlike the rest of settings. Every
* signed-in member may create, edit and delete their own `personal` macros;
* only an admin may do any of that to an `org`-scope macro.
* `_resolve_scope_and_owner` enforces the scope rule server-side and turns a
* non-admin's org-scope attempt into 403, so `owner` is never sent from
* here: it is derived from `request.profile` on the way in, and a client
* that could name one could file a macro as somebody else. Editing someone
* else's personal macro answers 404, not 403, on purpose
* (`MacroDetailView._get_writable`), so the id space cannot be used to
* discover which rows are other people's private macros; callers of
* `updateMacro`/`deleteMacro` have to carry that distinction through to
* their error copy rather than "fixing" it into a uniform 403.
*
* Delete is soft for an org macro (`is_active` flips to false, the row stays
* and stays counted) and a hard delete for a personal one. Both go through
* `deleteMacro`, one endpoint; which happens is decided by the row's own
* scope server-side, never by anything this module sends.
*
* The one reshape is `owner`: the API returns it as a Profile id plus a
* separate `owner_name` (the owner's email; `User` has no display name), while
@ -20,10 +35,12 @@
* the renderer actually expands.
*/
import { apiRequest } from '$lib/api-helpers.js';
import { viewerRole } from './organization.js';
import { myProfileId } from './leads.js';
/**
* @param {{ cookies: import('@sveltejs/kit').Cookies }} event
* @returns {Promise<{ macros: any[], totals: any, placeholders: any[] }>}
* @returns {Promise<{ macros: any[], totals: any, placeholders: any[], can_create_org: boolean, my_profile_id: string }>}
*/
export async function getMacros({ cookies }) {
const resp = await apiRequest('/macros/', {}, { cookies });
@ -40,6 +57,108 @@ export async function getMacros({ cookies }) {
inactive: 0,
with_unknown_placeholders: 0
},
placeholders: resp.placeholders ?? []
placeholders: resp.placeholders ?? [],
// A display hint, not the authorization: `_resolve_scope_and_owner`
// re-derives admin status from `request.profile` server-side, and that
// is what actually decides whether an org-scope write succeeds. This
// only decides whether the scope select offers "Everyone in the org".
can_create_org: viewerRole(cookies) === 'ADMIN',
// So the page can tell its own personal macros apart from a stranger's.
// The API already keeps a stranger's personal macros out of `results`
// entirely, so this is only ever compared against rows the viewer could
// already see.
my_profile_id: await myProfileId(cookies)
};
}
/** The fields `MacroSerializer` accepts on create or update. `owner` is
* derived server-side by `_resolve_scope_and_owner` from `request.profile`,
* never from the body, so it can never appear here. `org` is a JWT claim
* for the same reason. */
const WRITABLE_FIELDS = ['title', 'body', 'scope', 'is_active'];
/**
* Shape the request body from the allow-list.
*
* The three checks below are a fast fail for an obviously bad form, not the
* authority: `MacroSerializer` requires both `title` and `body`, and
* `_resolve_scope_and_owner` rejects any scope outside these two, so the
* server re-validates everything here regardless of what this lets through.
*
* @param {{ [key: string]: any }} values
*/
function buildBody(values) {
/** @type {Record<string, any>} */
const body = {};
for (const field of WRITABLE_FIELDS) {
if (values[field] === undefined) continue;
body[field] = values[field];
}
body.title = String(body.title ?? '').trim();
body.body = String(body.body ?? '').trim();
if (!body.title) throw new Error('A macro needs a title.');
if (!body.body) throw new Error('A macro needs a body.');
if (body.scope !== 'org' && body.scope !== 'personal') {
throw new Error("scope must be 'org' or 'personal'.");
}
if (body.is_active !== undefined) body.is_active = Boolean(body.is_active);
return body;
}
/** @param {{ cookies: import('@sveltejs/kit').Cookies }} event */
export async function createMacro({ cookies }, values) {
const body = buildBody(values);
return await apiRequest('/macros/', { method: 'POST', body }, { cookies });
}
/**
* PATCH, not PUT: `MacroDetailView.put` runs the serializer with
* `partial=False` and `MacroSerializer` requires both `title` and `body`, so
* a PUT missing either 400s. `patch` is the partial verb and is what this
* form, which always submits both fields anyway, should be using regardless.
*
* @param {{ cookies: import('@sveltejs/kit').Cookies }} event
*/
export async function updateMacro({ cookies }, id, values) {
if (!id) throw new Error('Which macro? No macro id was given.');
const body = buildBody(values);
return await apiRequest(`/macros/${id}/`, { method: 'PATCH', body }, { cookies });
}
/**
* Delete is soft for an org macro (`MacroDetailView.delete` flips
* `is_active` and leaves the row in place) and a hard delete for a personal
* one. Both happen behind this one call; which one is decided by the row's
* own scope server-side, not by anything sent here.
*
* @param {{ cookies: import('@sveltejs/kit').Cookies }} event
*/
export async function deleteMacro({ cookies }, id) {
if (!id) throw new Error('Which macro? No macro id was given.');
return await apiRequest(`/macros/${id}/`, { method: 'DELETE' }, { cookies });
}
/**
* Turn a macro back on.
*
* A dedicated action, not a reuse of `updateMacro`: `buildBody` above
* unconditionally requires both `title` and `body` to be non-empty (a fast
* client-side fail for the create/edit form, which always submits both), so
* calling `updateMacro(event, id, { is_active: true })` would throw before a
* request was even made. This bypasses `buildBody` and sends exactly
* `{ is_active: true }`. PATCH, partial, so the rest of the row is untouched.
* `_get_writable` still enforces the same admin-only-for-org /
* owner-only-for-personal rule as any other write to this row.
*
* @param {{ cookies: import('@sveltejs/kit').Cookies }} event
*/
export async function activateMacro({ cookies }, id) {
if (!id) throw new Error('Which macro? No macro id was given.');
return await apiRequest(
`/macros/${id}/`,
{ method: 'PATCH', body: { is_active: true } },
{ cookies }
);
}

View file

@ -0,0 +1,233 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
const apiRequest = vi.fn();
vi.mock('$lib/api-helpers.js', () => ({ apiRequest: (...a) => apiRequest(...a) }));
const { getMacros, createMacro, updateMacro, deleteMacro, activateMacro } =
await import('$lib/server/v2/macros.js');
const event = /** @type {any} */ ({ cookies: { get: () => 'token' } });
/**
* `getMacros`'s `can_create_org` comes from `viewerRole`, which decodes the
* `role` claim out of the `jwt_access` cookie directly (no network call), so
* a plain `{ get: () => 'token' }` mock (as `event` above) can't drive it: a
* `'token'` has no `.` to split, `viewerRole` catches that and returns null.
* This builds a JWT-shaped string with a real base64url payload so the
* decode path actually runs, matching how `organization.js`'s `viewerRole`
* reads a real access token.
*
* @param {string} role
*/
function eventWithRole(role) {
const payload = Buffer.from(JSON.stringify({ role }), 'utf-8').toString('base64url');
const token = `h.${payload}.s`;
return /** @type {any} */ ({
cookies: { get: (/** @type {string} */ name) => (name === 'jwt_access' ? token : null) }
});
}
describe('getMacros', () => {
beforeEach(() => {
apiRequest.mockReset();
});
it('can_create_org is true for an ADMIN token and false for a non-admin one', async () => {
// The page's whole permission model rests on this one boolean: it is
// what decides whether the scope select offers "Everyone in the org" and
// whether `canWrite` treats an org macro as editable. `_resolve_scope_and_owner`
// re-derives admin status independently server-side, but a display hint
// that is wired backwards is still worth catching here.
apiRequest.mockImplementation(async (/** @type {string} */ url) => {
if (url === '/macros/') return { results: [], totals: {}, placeholders: [] };
if (url === '/profile/') return { user_obj: { id: 'profile-1' } };
throw new Error(`unexpected url: ${url}`);
});
const admin = await getMacros(eventWithRole('ADMIN'));
expect(admin.can_create_org).toBe(true);
const member = await getMacros(eventWithRole('USER'));
expect(member.can_create_org).toBe(false);
});
it('my_profile_id is the id the page compares a macro owner against', async () => {
// `canWrite` in the page does `m.owner?.id === data.my_profile_id` for a
// personal macro. `getMacros` reshapes `owner` from the raw profile id
// the API sends into `{ id, name }`; this proves that reshape keeps the
// id in the same identity space `myProfileId` resolves, so a viewer's
// own personal macro actually compares equal rather than silently never
// matching.
apiRequest.mockImplementation(async (/** @type {string} */ url) => {
if (url === '/macros/') {
return {
results: [
{
id: 'm1',
scope: 'personal',
owner: 'profile-77',
owner_name: 'a@example.com',
is_active: true,
usage_count: 0,
unknown_placeholders: []
},
{
id: 'm2',
scope: 'org',
owner: null,
is_active: true,
usage_count: 0,
unknown_placeholders: []
}
],
totals: {},
placeholders: []
};
}
if (url === '/profile/') return { user_obj: { id: 'profile-77' } };
throw new Error(`unexpected url: ${url}`);
});
const data = await getMacros(eventWithRole('USER'));
expect(data.my_profile_id).toBe('profile-77');
const mine = data.macros.find((/** @type {any} */ m) => m.id === 'm1');
expect(mine.owner.id).toBe(data.my_profile_id);
});
it('my_profile_id falls back to an empty string, never a value that could collide with an owner id', async () => {
apiRequest.mockImplementation(async (/** @type {string} */ url) => {
if (url === '/macros/') return { results: [], totals: {}, placeholders: [] };
if (url === '/profile/') throw new Error('502');
throw new Error(`unexpected url: ${url}`);
});
const data = await getMacros(eventWithRole('USER'));
expect(data.my_profile_id).toBe('');
});
});
describe('createMacro', () => {
beforeEach(() => {
apiRequest.mockReset();
});
it('POSTs title, body, scope and is_active to /macros/', async () => {
apiRequest.mockResolvedValue({ id: 'm1' });
await createMacro(event, {
title: ' Ask for logs ',
body: 'Could you attach the log file?',
scope: 'personal',
is_active: true
});
const [endpoint, options] = apiRequest.mock.calls[0];
expect(endpoint).toBe('/macros/');
expect(options.method).toBe('POST');
expect(options.body).toEqual({
title: 'Ask for logs',
body: 'Could you attach the log file?',
scope: 'personal',
is_active: true
});
});
it('never forwards owner or org, which the backend derives from the token', async () => {
// `_resolve_scope_and_owner` sets owner from `request.profile`. A client
// that could name an owner could file a macro as somebody else.
apiRequest.mockResolvedValue({});
await createMacro(event, {
title: 't',
body: 'b',
scope: 'personal',
owner: 'someone-else',
org: 'attacker-org'
});
const body = apiRequest.mock.calls[0][1].body;
expect(body.owner).toBeUndefined();
expect(body.org).toBeUndefined();
});
it('rejects an unknown scope before making a request', async () => {
await expect(createMacro(event, { title: 't', body: 'b', scope: 'global' })).rejects.toThrow(
/scope/i
);
expect(apiRequest).not.toHaveBeenCalled();
});
it('rejects an empty title or body before making a request', async () => {
await expect(createMacro(event, { title: ' ', body: 'b', scope: 'org' })).rejects.toThrow(
/title/i
);
await expect(createMacro(event, { title: 't', body: ' ', scope: 'org' })).rejects.toThrow(
/body/i
);
expect(apiRequest).not.toHaveBeenCalled();
});
});
describe('updateMacro', () => {
beforeEach(() => {
apiRequest.mockReset();
});
it('PATCHes rather than PUTs, because PUT is not partial', async () => {
// `MacroDetailView.put` runs the serializer with `partial=False` and
// `MacroSerializer` requires title and body, so a PUT missing either
// returns 400. PATCH is the partial verb.
apiRequest.mockResolvedValue({});
await updateMacro(event, 'm1', { title: 'New title', body: 'b', scope: 'personal' });
const [endpoint, options] = apiRequest.mock.calls[0];
expect(endpoint).toBe('/macros/m1/');
expect(options.method).toBe('PATCH');
expect(options.body.title).toBe('New title');
});
});
describe('deleteMacro', () => {
beforeEach(() => {
apiRequest.mockReset();
});
it('DELETEs the detail endpoint', async () => {
apiRequest.mockResolvedValue(null);
await deleteMacro(event, 'm1');
const [endpoint, options] = apiRequest.mock.calls[0];
expect(endpoint).toBe('/macros/m1/');
expect(options.method).toBe('DELETE');
});
it('refuses an empty id before making a request', async () => {
await expect(deleteMacro(event, '')).rejects.toThrow(/which/i);
expect(apiRequest).not.toHaveBeenCalled();
});
});
describe('activateMacro', () => {
beforeEach(() => {
apiRequest.mockReset();
});
it('PATCHes the detail endpoint with only { is_active: true }', async () => {
// The "Turn on" control must never resend `title`/`body`/`scope`: a
// blank `title` slipping through here would blank a live macro's title.
apiRequest.mockResolvedValue({});
await activateMacro(event, 'm1');
const [endpoint, options] = apiRequest.mock.calls[0];
expect(endpoint).toBe('/macros/m1/');
expect(options.method).toBe('PATCH');
expect(options.body).toEqual({ is_active: true });
});
it('refuses an empty id before making a request', async () => {
await expect(activateMacro(event, '')).rejects.toThrow(/which/i);
expect(apiRequest).not.toHaveBeenCalled();
});
});

View file

@ -0,0 +1,54 @@
/**
* The in-org people and teams every picker needs.
*
* Server-only. `GET /users/get-teams-and-users/` filters profiles to
* `is_active=True, org=request.profile.org` and teams to the same org, so a
* picker built from this can only ever offer an active, in-org target.
*
* That is UX, not the boundary. Every consumer's own write path re-checks the
* id against the caller's org, and they do it in three different ways, so do
* not read one mechanism into all of them: the four `cases` settings
* serializers scope their relational querysets to the caller's org in
* `__init__` and reject a foreign id with a 400; `SalesGoalCreateSerializer`
* raises a 400 from `validate_assigned_to` / `validate_team`; the document
* views filter `Profile.objects.filter(id__in=..., org=..., is_active=True)`
* inline and silently drop a foreign id rather than failing. All three close
* the hole. None of them depend on what this list offered.
*
* This exists because four modules had grown their own private copy of the
* same fetch. `documents.js` and `goals.js` were byte-identical in behaviour
* and now import this. `deals.js` and `leads.js` keep theirs: they label a
* person by email rather than name, and changing what their owner select
* displays is not a refactor.
*
* A failed fetch resolves to empty lists rather than throwing. The pickers
* are one part of a settings page, and taking the whole page down to a 500
* because an optional list did not load is worse than rendering it with
* nothing to choose.
*/
import { apiRequest } from '$lib/api-helpers.js';
/** A profile as the pickers label it. */
function personName(profile) {
const d = profile?.user_details ?? {};
return d.name || d.email || 'Unnamed';
}
/**
* @param {import('@sveltejs/kit').Cookies} cookies
* @returns {Promise<{ people: { id: string, name: string }[], teams: { id: string, name: string }[] }>}
*/
export async function getOrgPeopleAndTeams(cookies) {
try {
const resp = await apiRequest('/users/get-teams-and-users/', {}, { cookies });
return {
people: (resp?.profiles ?? []).map((/** @type {any} */ p) => ({
id: p.id,
name: personName(p)
})),
teams: (resp?.teams ?? []).map((/** @type {any} */ t) => ({ id: t.id, name: t.name }))
};
} catch {
return { people: [], teams: [] };
}
}

View file

@ -0,0 +1,62 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
// Local mock plus a thin wrapper, matching every other test in this
// directory (business-hours.test.js, tags.test.js, etc). Destructuring
// `apiRequest` straight off `await import('$lib/api-helpers.js')` types it
// against the real module's declared signature, which has no
// `mockReset`/`mockResolvedValue`, and fails `svelte-check`.
const apiRequest = vi.fn();
vi.mock('$lib/api-helpers.js', () => ({ apiRequest: (...a) => apiRequest(...a) }));
const { getOrgPeopleAndTeams } = await import('./org-people.js');
const cookies = /** @type {any} */ ({});
describe('getOrgPeopleAndTeams', () => {
beforeEach(() => {
apiRequest.mockReset();
});
it('labels a person by name when there is one', async () => {
apiRequest.mockResolvedValue({
profiles: [{ id: 'p1', user_details: { name: 'Ada Lovelace', email: 'ada@x.io' } }],
teams: []
});
const { people } = await getOrgPeopleAndTeams(cookies);
expect(people).toEqual([{ id: 'p1', name: 'Ada Lovelace' }]);
});
it('falls back to the email, then to Unnamed', async () => {
apiRequest.mockResolvedValue({
profiles: [
{ id: 'p1', user_details: { email: 'ada@x.io' } },
{ id: 'p2', user_details: {} },
{ id: 'p3' }
],
teams: []
});
const { people } = await getOrgPeopleAndTeams(cookies);
expect(people.map((p) => p.name)).toEqual(['ada@x.io', 'Unnamed', 'Unnamed']);
});
it('flattens teams to id and name', async () => {
apiRequest.mockResolvedValue({
profiles: [],
teams: [{ id: 't1', name: 'Support', description: 'ignored', users: [1, 2] }]
});
const { teams } = await getOrgPeopleAndTeams(cookies);
expect(teams).toEqual([{ id: 't1', name: 'Support' }]);
});
it('returns empty lists rather than throwing when the fetch fails', async () => {
apiRequest.mockImplementation(() => {
throw new Error('boom');
});
await expect(getOrgPeopleAndTeams(cookies)).resolves.toEqual({ people: [], teams: [] });
});
it('survives a response missing both keys', async () => {
apiRequest.mockResolvedValue({});
await expect(getOrgPeopleAndTeams(cookies)).resolves.toEqual({ people: [], teams: [] });
});
});

View file

@ -9,17 +9,69 @@
* computed server-side from the reopen audit trail (REOPENED activities + the
* out-of-window flag the signal writes on late replies).
*
* Read-only page: "Edit policy" is a deferred builder (no form on the page yet),
* so there is no write path to wire here. The whole flat response is the page's
* `policy` object.
* `updateReopenPolicy` below is the write path: `PUT /cases/reopen-policy/`,
* admin-only, `partial=True` on the backend but sent as all four fields at
* once. The page's own `+page.server.js` action turns a rejected save into a
* message the user reads.
*/
import { apiRequest } from '$lib/api-helpers.js';
import { viewerRole } from './organization.js';
import { REOPEN_TO_STATUSES } from '$lib/v2/enums.js';
/**
* @param {{ cookies: import('@sveltejs/kit').Cookies }} event
* @returns {Promise<{ policy: any }>}
* @returns {Promise<{ policy: any, can_edit: boolean }>}
*/
export async function getReopenPolicy({ cookies }) {
const policy = await apiRequest('/cases/reopen-policy/', {}, { cookies });
return { policy };
return { policy, can_edit: viewerRole(cookies) === 'ADMIN' };
}
/** The four fields the serializer accepts. Everything else in the GET
* response is a computed metric and is not writable. */
const EDITABLE_FIELDS = [
'is_enabled',
'reopen_window_days',
'reopen_to_status',
'notify_assigned'
];
/**
* Update the org's reopen policy.
*
* `ReopenPolicyView.put` is admin-only and `partial=True`, so this could send
* a subset. It sends all four anyway: the form edits all four at once, and a
* partial body would make "unchecked" indistinguishable from "not submitted"
* for the two booleans.
*
* The two guards below are fast fails for an obvious mistake, not security
* controls. `validate_reopen_window_days` and `validate_reopen_to_status` on
* the serializer are the real authority and run regardless of what reaches
* them.
*
* @param {{ cookies: import('@sveltejs/kit').Cookies }} event
* @param {{ [key: string]: any }} values callers may pass extra keys (a
* computed metric read back off the page, a hostile `org`); the allow-list
* loop below is what stops them reaching the API.
* @returns {Promise<any>} the updated policy, the four fields only.
*/
export async function updateReopenPolicy({ cookies }, values) {
const days = Number(values.reopen_window_days);
if (!Number.isInteger(days) || days < 1 || days > 365) {
throw new Error('The reopen window must be a whole number of days between 1 and 365.');
}
if (!REOPEN_TO_STATUSES.includes(values.reopen_to_status)) {
throw new Error('A reopened ticket has to come back as New, Assigned or Pending.');
}
/** @type {Record<string, any>} */
const body = {};
for (const field of EDITABLE_FIELDS) {
body[field] = values[field];
}
body.reopen_window_days = days;
body.is_enabled = Boolean(values.is_enabled);
body.notify_assigned = Boolean(values.notify_assigned);
return await apiRequest('/cases/reopen-policy/', { method: 'PUT', body }, { cookies });
}

View file

@ -0,0 +1,78 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
const apiRequest = vi.fn();
vi.mock('$lib/api-helpers.js', () => ({ apiRequest: (...a) => apiRequest(...a) }));
const { updateReopenPolicy } = await import('$lib/server/v2/reopen.js');
// Cast rather than shaping a full Cookies mock, matching tags.test.js: the
// function under test only reads `cookies.get`, and `apiRequest` is mocked.
const event = /** @type {any} */ ({ cookies: { get: () => 'token' } });
describe('updateReopenPolicy', () => {
beforeEach(() => {
apiRequest.mockReset();
});
it('PUTs the four policy fields to the singleton endpoint', async () => {
apiRequest.mockResolvedValue({ is_enabled: true, reopen_window_days: 14 });
await updateReopenPolicy(event, {
is_enabled: true,
reopen_window_days: 14,
reopen_to_status: 'Assigned',
notify_assigned: false
});
const [endpoint, options] = apiRequest.mock.calls[0];
expect(endpoint).toBe('/cases/reopen-policy/');
expect(options.method).toBe('PUT');
expect(options.body).toEqual({
is_enabled: true,
reopen_window_days: 14,
reopen_to_status: 'Assigned',
notify_assigned: false
});
});
it('never forwards a computed metric or a client-supplied org', async () => {
apiRequest.mockResolvedValue({});
await updateReopenPolicy(event, {
is_enabled: true,
reopen_window_days: 7,
reopen_to_status: 'New',
notify_assigned: true,
reopened_last_30d: 999,
org: 'attacker-org'
});
const body = apiRequest.mock.calls[0][1].body;
expect(body.reopened_last_30d).toBeUndefined();
expect(body.org).toBeUndefined();
});
it('rejects a window outside 1 to 365 before making a request', async () => {
await expect(
updateReopenPolicy(event, {
is_enabled: true,
reopen_window_days: 0,
reopen_to_status: 'New',
notify_assigned: true
})
).rejects.toThrow(/between 1 and 365/i);
expect(apiRequest).not.toHaveBeenCalled();
});
it('rejects a terminal reopen_to_status before making a request', async () => {
await expect(
updateReopenPolicy(event, {
is_enabled: true,
reopen_window_days: 7,
reopen_to_status: 'Closed',
notify_assigned: true
})
).rejects.toThrow(/New, Assigned or Pending/i);
expect(apiRequest).not.toHaveBeenCalled();
});
});

View file

@ -9,13 +9,17 @@
* page can name who is next). The response also carries org totals, including
* `unrouted_last_30d` (cases no rule matched).
*
* Read-only page: "New rule" / drag-to-reorder are deferred builders, so there
* is no write path to wire. The backend returns `target_assignees` as full
* profile objects (name under `user_details.name`, plus `is_active`, which the
* page flags on) and `target_team` as a full team object; the page wants
* `{ id, name, is_active }` / `{ id, name }`, so flatten here.
* Create, edit, turn off, turn on and delete are wired below. Drag-to-reorder
* is still a deferred builder, so `priority_order` is a plain number field on
* the form rather than something a drag sets. The backend returns
* `target_assignees` as full profile objects (name under `user_details.name`,
* plus `is_active`, which the page flags on) and `target_team` as a full team
* object; the page wants `{ id, name, is_active }` / `{ id, name }`, so
* flatten here.
*/
import { apiRequest } from '$lib/api-helpers.js';
import { viewerRole } from './organization.js';
import { CONDITION_FIELD_LABEL, CONDITION_OP_LABEL, ROUTING_STRATEGY_NAME } from '$lib/v2/enums.js';
/** Profile → the `{ id, name, is_active }` the rule card reads. */
function shapeAssignee(p) {
@ -30,7 +34,7 @@ function shapeTeam(team) {
/**
* @param {{ cookies: import('@sveltejs/kit').Cookies }} event
* @returns {Promise<{ rules: any[], totals: any }>}
* @returns {Promise<{ rules: any[], totals: any, can_edit: boolean }>}
*/
export async function getRoutingRules({ cookies }) {
const { rules, totals } = await apiRequest('/cases/routing-rules/', {}, { cookies });
@ -48,6 +52,250 @@ export async function getRoutingRules({ cookies }) {
state: r.state ?? null,
matched_last_30d: r.matched_last_30d ?? 0
})),
totals: totals ?? { count: 0, active: 0, unrouted_last_30d: 0 }
totals: totals ?? { count: 0, active: 0, unrouted_last_30d: 0 },
// A display hint: POST/PUT/DELETE on `/cases/routing-rules/` each start
// with `_is_admin(request.profile)` server-side and 403 regardless of
// what this says. This only decides whether the page offers the controls.
can_edit: viewerRole(cookies) === 'ADMIN'
};
}
/** Everything a create may set. `org` is the JWT's, never the body's. */
const CREATE_FIELDS = [
'name',
'priority_order',
'is_active',
'conditions',
'strategy',
'stop_processing',
'target_assignee_ids',
'target_team_id'
];
/** Nothing is frozen after creation on this resource, so an edit may set the
* same fields a create may. `RoutingRuleDetailView.put` builds its serializer
* with `partial=True`, so an omitted key is left untouched rather than
* blanked, which is what lets the turn-on action below send a single key. */
const UPDATE_FIELDS = CREATE_FIELDS;
/** The fields and operators `RoutingRuleSerializer.validate_conditions`
* accepts, derived from the label maps the page renders its selects from.
* Derived rather than restated: a `.svelte` file cannot import from
* `$lib/server/`, so the page cannot share this module's list, and two
* hand-maintained copies of the same set drift. Keying off the labels
* means adding a field in one place adds it to both. */
export const CONDITION_FIELDS = Object.keys(CONDITION_FIELD_LABEL);
export const CONDITION_OPS = Object.keys(CONDITION_OP_LABEL);
/**
* Read the repeating condition rows back off a submitted form.
*
* One indexed name per row (`condition_field_0`, `condition_op_0`,
* `condition_value_0`, then `_1`, and so on), read by index. This lives here
* rather than in the route's `+page.server.js` so the parse and the clean can
* be tested together: the harness covers `$lib/server/` modules and cannot
* import a route module at all.
*
* The indexing is the whole point, and it replaced three parallel `getAll`
* arrays that were paired POSITIONALLY. A `<select>` whose value matches no
* option has `selectedIndex === -1`, and such a select contributes NO entry to
* `FormData`. With parallel arrays one missing `condition_field` therefore
* shifted every later row's operator and value up by one, rewriting conditions
* the admin never touched into ones that match nothing, or dropping the last
* row entirely and widening the rule. The page also renders an unmatched
* stored field as its own option so the select has something to match, but
* these two fixes are not redundant: that one keeps a known value editable,
* this one means no future unmatched value can corrupt its neighbours.
*
* Indices come from the submitted keys rather than from a hidden count field,
* so a row that submits only two of its three inputs still holds its place,
* and a missing count cannot silently collapse every condition into "matches
* every ticket".
*
* @param {FormData} form
* @returns {{ field: string, op: string, value: string }[]}
*/
export function readConditionRows(form) {
/** @type {Map<number, { field: string, op: string, value: string }>} */
const rows = new Map();
for (const key of form.keys()) {
const match = /^condition_(field|op|value)_(\d+)$/.exec(key);
if (!match) continue;
const index = Number(match[2]);
let row = rows.get(index);
if (!row) {
row = { field: '', op: 'eq', value: '' };
rows.set(index, row);
}
const part = /** @type {'field' | 'op' | 'value'} */ (match[1]);
const raw = form.get(key);
if (raw !== null) row[part] = raw.toString();
}
return [...rows.entries()].sort((a, b) => a[0] - b[0]).map(([, row]) => row);
}
/**
* Clean the repeating condition rows into what the backend validates.
*
* A row the admin added and left blank is dropped, not rejected: an empty row
* is how the editor represents "I am about to type here", and failing the save
* for it would be hostile. A row with a field but no operator gets `eq`, the
* backend's own default. `value` is always sent even when empty, including as
* an empty array for `in`, because `validate_conditions` requires the KEY to
* be present and only checks `"value" not in cond`.
*
* `in` gets an array; every other op keeps the plain string it always has.
* `cases/routing.py`'s evaluator does
* `if not isinstance(value, (list, tuple)): return False` for `in`, and does
* it silently: the unknown-op and unknown-field branches next to it both log
* a warning, this one does not. `validate_conditions` never checks the
* value's type, only that the key exists, so a string here would save
* cleanly (200) and then match nothing, forever, with no signal anywhere
* pointing at why. A comma-separated string is split and trimmed; a value
* that already arrives as an array (a condition this editor did not
* originate) is kept as one, each entry trimmed the same way.
*/
function cleanConditions(rows) {
return (rows ?? [])
.map((r) => {
const op = String(r?.op ?? 'eq').trim() || 'eq';
const raw = r?.value;
let value;
if (op === 'in') {
const parts = Array.isArray(raw)
? raw.map((v) => String(v).trim())
: String(raw ?? '')
.split(',')
.map((v) => v.trim());
value = parts.filter(Boolean);
} else {
value = raw === undefined || raw === null ? '' : String(raw);
}
return { field: String(r?.field ?? '').trim(), op, value };
})
.filter((r) => r.field)
.map((r) => {
if (!(CONDITION_FIELDS.includes(r.field) || r.field.startsWith('custom_fields.'))) {
throw new Error(`"${r.field}" is not a field a rule can match on.`);
}
if (!CONDITION_OPS.includes(r.op)) {
throw new Error(`"${r.op}" is not an operator a rule can use.`);
}
return r;
});
}
/** @param {string[]} allowed @param {{ [key: string]: any }} values */
function buildBody(allowed, values) {
/** @type {Record<string, any>} */
const body = {};
for (const field of allowed) {
if (values[field] === undefined) continue;
body[field] = values[field];
}
if (body.priority_order !== undefined) body.priority_order = Number(body.priority_order) || 0;
for (const flag of ['is_active', 'stop_processing']) {
if (body[flag] !== undefined) body[flag] = Boolean(body[flag]);
}
if (body.conditions !== undefined) body.conditions = cleanConditions(body.conditions);
// `by_team` routes to a team and nothing else; the other three route to
// people. Sending the half that does not apply is not rejected by the
// backend, it is simply stored, and a later strategy switch would then
// resurrect a stale target nobody chose. Send only the half in play.
if (body.strategy === 'by_team') {
delete body.target_assignee_ids;
} else if (body.strategy !== undefined) {
delete body.target_team_id;
}
// An empty string from an unselected `<select>` is not null. The field is
// `allow_null=True`, so null clears it; `''` is a 400.
if (body.target_team_id === '') body.target_team_id = null;
if (body.target_assignee_ids !== undefined) {
const ids = (body.target_assignee_ids ?? []).filter(Boolean);
// An empty multi-select omits the key rather than sending `[]`, because
// `[]` disarms the backend's own guard. `RoutingRuleSerializer.validate`
// reads `assignees = attrs.get("target_assignees")` and only raises when
// `assignees is None and self.instance is None`; `[]` is not `None`, so a
// create with a condition and nobody selected returns 201. With
// `stop_processing` on by default, `cases/routing.py` then hits
// `if not pool: decision.reason = "empty_pool"` followed by
// `if rule.stop_processing: return decision`, so every matching ticket is
// left unassigned by a rule that also stops any lower rule from assigning
// it. Omitting the key lets the serializer answer with its own message.
//
// Omitting it is only half the answer, and only on create. `put` is
// `partial=True`, so on an edit the omission leaves the stored assignees
// in place, and the backend has no update-path guard to speak up
// (`self.instance is None` is false there). An admin who deselected
// everyone would get a success, a closed panel, and the old list back,
// with nothing saying the change was dropped. `updateRoutingRule` refuses
// that request outright instead: see the guard below it.
if (ids.length === 0) delete body.target_assignee_ids;
else body.target_assignee_ids = ids;
}
return body;
}
/** @param {{ cookies: import('@sveltejs/kit').Cookies }} event */
export async function createRoutingRule({ cookies }, values) {
const body = buildBody(CREATE_FIELDS, values);
if (!body.name) throw new Error('A rule needs a name.');
return await apiRequest('/cases/routing-rules/', { method: 'POST', body }, { cookies });
}
/** The strategies that route to people rather than to a team, which is every
* strategy except `by_team`. Derived from the same map the page labels its
* select from, rather than restated, for the reason `CONDITION_FIELDS` is
* derived: two hand-maintained copies of one set drift. It matches
* `RoutingRuleSerializer.validate`'s `("round_robin", "least_busy",
* "direct")`. All four strategies are exercised against the guard below, so
* a change to that map which no longer splits the same way fails there. */
const PEOPLE_STRATEGIES = Object.keys(ROUTING_STRATEGY_NAME).filter((s) => s !== 'by_team');
/** @param {{ cookies: import('@sveltejs/kit').Cookies }} event */
export async function updateRoutingRule({ cookies }, id, values) {
if (!id) throw new Error('Which rule? No rule id was given.');
const body = buildBody(UPDATE_FIELDS, values);
// The one rule the backend enforces on create and cannot enforce on edit.
// `RoutingRuleSerializer.validate` guards a people strategy with no
// assignees behind `self.instance is None`, so on a PUT it never fires, and
// `buildBody` above has just dropped the empty list so `partial=True` will
// leave the stored assignees alone. Sending it would answer 200 and change
// nothing the admin asked to change, which is a silent no-op on a control
// they just operated. Refuse instead, and say which constraint refused.
//
// Both conditions are required. `body.strategy` alone is not enough: a
// partial update that names a strategy without touching the assignee
// picker (or the turn-on path, which sends `{ is_active: true }` and
// nothing else) must still go through untouched. And an empty list under
// `by_team` cannot reach here at all, because `buildBody` deletes the
// assignee key outright for that strategy before the emptiness check.
const submittedAssignees = values?.target_assignee_ids !== undefined;
if (
submittedAssignees &&
body.target_assignee_ids === undefined &&
PEOPLE_STRATEGIES.includes(body.strategy)
) {
const name = ROUTING_STRATEGY_NAME[body.strategy].toLowerCase();
throw new Error(`A ${name} rule needs at least one assignee.`);
}
return await apiRequest(`/cases/routing-rules/${id}/`, { method: 'PUT', body }, { cookies });
}
/**
* Delete a rule, permanently.
*
* `RoutingRuleDetailView.delete` calls `obj.delete()`. Unlike
* `/custom-fields/<id>/`, there is no soft-delete hiding behind this verb, so
* the control that calls it has to say so.
*
* @param {{ cookies: import('@sveltejs/kit').Cookies }} event
*/
export async function deleteRoutingRule({ cookies }, id) {
if (!id) throw new Error('Which rule? No rule id was given.');
return await apiRequest(`/cases/routing-rules/${id}/`, { method: 'DELETE' }, { cookies });
}

View file

@ -0,0 +1,537 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
const apiRequest = vi.fn();
vi.mock('$lib/api-helpers.js', () => ({ apiRequest: (...a) => apiRequest(...a) }));
const {
createRoutingRule,
updateRoutingRule,
deleteRoutingRule,
readConditionRows,
CONDITION_FIELDS,
CONDITION_OPS
} = await import('./routing.js');
const cookies = /** @type {any} */ ({ get: () => 'token' });
const event = /** @type {any} */ ({ cookies });
const base = {
name: 'Urgent to Ada',
priority_order: '5',
is_active: true,
stop_processing: true,
strategy: 'direct',
target_assignee_ids: ['p1'],
target_team_id: '',
conditions: [{ field: 'priority', op: 'eq', value: 'Urgent' }]
};
describe('createRoutingRule', () => {
beforeEach(() => {
apiRequest.mockReset();
});
it('sends only allow-listed keys on create', async () => {
apiRequest.mockResolvedValue({});
await createRoutingRule(event, {
...base,
org: 'ATTACKER-ORG',
created_by: 'ATTACKER'
});
const [url, opts] = apiRequest.mock.calls[0];
expect(url).toBe('/cases/routing-rules/');
expect(opts.method).toBe('POST');
expect(Object.keys(opts.body).sort()).toEqual([
'conditions',
'is_active',
'name',
'priority_order',
'stop_processing',
'strategy',
'target_assignee_ids'
]);
expect(opts.body.priority_order).toBe(5);
expect(opts.body.org).toBeUndefined();
expect(opts.body.created_by).toBeUndefined();
});
it('coerces priority_order to a number', async () => {
apiRequest.mockResolvedValue({});
await createRoutingRule(event, { ...base, priority_order: '12' });
expect(apiRequest.mock.calls[0][1].body.priority_order).toBe(12);
expect(typeof apiRequest.mock.calls[0][1].body.priority_order).toBe('number');
});
it('falls back to 0 for a non-numeric priority_order', async () => {
apiRequest.mockResolvedValue({});
await createRoutingRule(event, { ...base, priority_order: 'not-a-number' });
expect(apiRequest.mock.calls[0][1].body.priority_order).toBe(0);
});
it('coerces is_active and stop_processing to booleans', async () => {
apiRequest.mockResolvedValue({});
await createRoutingRule(event, {
...base,
is_active: 'true',
stop_processing: ''
});
const { body } = apiRequest.mock.calls[0][1];
expect(body.is_active).toBe(true);
expect(typeof body.is_active).toBe('boolean');
expect(body.stop_processing).toBe(false);
expect(typeof body.stop_processing).toBe('boolean');
});
it('drops condition rows with a blank field', async () => {
apiRequest.mockResolvedValue({});
await createRoutingRule(event, {
...base,
conditions: [
{ field: '', op: 'eq', value: 'ignored' },
{ field: ' ', op: 'eq', value: 'also ignored' },
{ field: 'priority', op: 'eq', value: 'Urgent' }
]
});
const { body } = apiRequest.mock.calls[0][1];
expect(body.conditions).toEqual([{ field: 'priority', op: 'eq', value: 'Urgent' }]);
});
it('still sends a value key when a row has a field but no value key', async () => {
apiRequest.mockResolvedValue({});
await createRoutingRule(event, {
...base,
conditions: [{ field: 'priority', op: 'eq' }]
});
const { body } = apiRequest.mock.calls[0][1];
expect(body.conditions).toEqual([{ field: 'priority', op: 'eq', value: '' }]);
});
it('defaults a condition row missing an operator to eq', async () => {
apiRequest.mockResolvedValue({});
await createRoutingRule(event, {
...base,
conditions: [{ field: 'priority', op: '', value: 'Urgent' }]
});
const { body } = apiRequest.mock.calls[0][1];
expect(body.conditions).toEqual([{ field: 'priority', op: 'eq', value: 'Urgent' }]);
});
it('splits an "in" condition value on commas into a trimmed array', async () => {
// `cases/routing.py`'s evaluator requires a list/tuple for `in` and
// silently returns False for every ticket otherwise. A comma-separated
// string is the only way one text input can express a list.
apiRequest.mockResolvedValue({});
await createRoutingRule(event, {
...base,
conditions: [{ field: 'priority', op: 'in', value: 'Urgent, High ,Medium' }]
});
const { body } = apiRequest.mock.calls[0][1];
expect(body.conditions).toEqual([
{ field: 'priority', op: 'in', value: ['Urgent', 'High', 'Medium'] }
]);
});
it('keeps an already-array "in" condition value as an array', async () => {
// A rule whose `in` condition was seeded or created directly through the
// API (not through this editor) already carries an array. Editing an
// unrelated field on that same rule must not turn it into a string.
apiRequest.mockResolvedValue({});
await createRoutingRule(event, {
...base,
conditions: [{ field: 'priority', op: 'in', value: ['Urgent', 'High'] }]
});
const { body } = apiRequest.mock.calls[0][1];
expect(body.conditions).toEqual([{ field: 'priority', op: 'in', value: ['Urgent', 'High'] }]);
});
it('turns an empty "in" condition value into an empty array, and still sends the key', async () => {
apiRequest.mockResolvedValue({});
await createRoutingRule(event, {
...base,
conditions: [{ field: 'priority', op: 'in' }]
});
const { body } = apiRequest.mock.calls[0][1];
expect(body.conditions).toEqual([{ field: 'priority', op: 'in', value: [] }]);
});
it('does not split an "eq" condition value that contains a comma', async () => {
// A tag or account name can legitimately contain a comma. Only `in`
// means "list"; every other operator's value is a literal string.
apiRequest.mockResolvedValue({});
await createRoutingRule(event, {
...base,
conditions: [{ field: 'tags', op: 'eq', value: 'North America, EMEA' }]
});
const { body } = apiRequest.mock.calls[0][1];
expect(body.conditions).toEqual([{ field: 'tags', op: 'eq', value: 'North America, EMEA' }]);
});
it('rejects a condition field the backend does not accept, before the request', async () => {
await expect(
createRoutingRule(event, {
...base,
conditions: [{ field: 'severity', op: 'eq', value: 'high' }]
})
).rejects.toThrow(/not a field a rule can match on/i);
expect(apiRequest).not.toHaveBeenCalled();
});
it('accepts a custom_fields.-prefixed condition field', async () => {
apiRequest.mockResolvedValue({});
await createRoutingRule(event, {
...base,
conditions: [{ field: 'custom_fields.severity', op: 'eq', value: 'high' }]
});
const { body } = apiRequest.mock.calls[0][1];
expect(body.conditions).toEqual([{ field: 'custom_fields.severity', op: 'eq', value: 'high' }]);
});
it('rejects a condition operator the backend does not accept, before the request', async () => {
await expect(
createRoutingRule(event, {
...base,
conditions: [{ field: 'priority', op: 'startswith', value: 'high' }]
})
).rejects.toThrow(/not an operator a rule can use/i);
expect(apiRequest).not.toHaveBeenCalled();
});
it('drops target_team_id for a non-by_team strategy', async () => {
apiRequest.mockResolvedValue({});
await createRoutingRule(event, { ...base, strategy: 'round_robin', target_team_id: 't1' });
expect(apiRequest.mock.calls[0][1].body.target_team_id).toBeUndefined();
});
it('drops target_assignee_ids and keeps target_team_id for by_team', async () => {
apiRequest.mockResolvedValue({});
await createRoutingRule(event, {
...base,
strategy: 'by_team',
target_team_id: 't1',
target_assignee_ids: ['p1', 'p2']
});
const { body } = apiRequest.mock.calls[0][1];
expect(body.target_assignee_ids).toBeUndefined();
expect(body.target_team_id).toBe('t1');
});
it('turns an empty-string target_team_id into null for by_team', async () => {
apiRequest.mockResolvedValue({});
await createRoutingRule(event, { ...base, strategy: 'by_team', target_team_id: '' });
expect(apiRequest.mock.calls[0][1].body.target_team_id).toBeNull();
});
it('filters falsy entries out of target_assignee_ids', async () => {
apiRequest.mockResolvedValue({});
await createRoutingRule(event, {
...base,
strategy: 'direct',
target_assignee_ids: ['p1', '', null, 'p2']
});
expect(apiRequest.mock.calls[0][1].body.target_assignee_ids).toEqual(['p1', 'p2']);
});
it('omits target_assignee_ids entirely when nobody is selected', async () => {
// `[]` is not `None`, and `RoutingRuleSerializer.validate` only raises
// when `assignees is None and self.instance is None`. Sending `[]` from an
// empty multi-select therefore disarms the backend's own create guard: the
// rule saves 201 with an empty pool, and with `stop_processing` on it eats
// every matching ticket and assigns nobody. Omitting the key is what lets
// the serializer answer.
apiRequest.mockResolvedValue({});
await createRoutingRule(event, { ...base, strategy: 'direct', target_assignee_ids: [] });
const { body } = apiRequest.mock.calls[0][1];
expect('target_assignee_ids' in body).toBe(false);
});
it('omits target_assignee_ids when every selected entry is blank', async () => {
apiRequest.mockResolvedValue({});
await createRoutingRule(event, {
...base,
strategy: 'round_robin',
target_assignee_ids: ['', null, undefined]
});
const { body } = apiRequest.mock.calls[0][1];
expect('target_assignee_ids' in body).toBe(false);
});
it('refuses a rule with no name before making a request', async () => {
await expect(createRoutingRule(event, { ...base, name: '' })).rejects.toThrow(/needs a name/i);
expect(apiRequest).not.toHaveBeenCalled();
});
});
describe('updateRoutingRule', () => {
beforeEach(() => {
apiRequest.mockReset();
});
it('PUTs to the detail endpoint', async () => {
apiRequest.mockResolvedValue({});
await updateRoutingRule(event, 'r1', base);
const [url, opts] = apiRequest.mock.calls[0];
expect(url).toBe('/cases/routing-rules/r1/');
expect(opts.method).toBe('PUT');
});
it('omits nothing and adds nothing outside UPDATE_FIELDS on a full edit', async () => {
apiRequest.mockResolvedValue({});
await updateRoutingRule(event, 'r1', {
...base,
strategy: 'round_robin',
org: 'ATTACKER-ORG',
created_by: 'ATTACKER'
});
const { body } = apiRequest.mock.calls[0][1];
expect(Object.keys(body).sort()).toEqual([
'conditions',
'is_active',
'name',
'priority_order',
'stop_processing',
'strategy',
'target_assignee_ids'
]);
expect(body.org).toBeUndefined();
expect(body.created_by).toBeUndefined();
});
it('sends exactly one key for a minimal { is_active: true } body', async () => {
apiRequest.mockResolvedValue({});
await updateRoutingRule(event, 'r1', { is_active: true });
const { body } = apiRequest.mock.calls[0][1];
expect(body).toEqual({ is_active: true });
});
it('sends exactly one key for a minimal { is_active: false } body', async () => {
apiRequest.mockResolvedValue({});
await updateRoutingRule(event, 'r1', { is_active: false });
const { body } = apiRequest.mock.calls[0][1];
expect(body).toEqual({ is_active: false });
});
it('refuses an edit that leaves a people strategy with no assignee', async () => {
// The backend cannot answer this one. Its guard is behind
// `self.instance is None`, and `put` is `partial=True`, so the request
// would return 200 and leave the stored assignees exactly as they were:
// a success for a change that did not happen, on a control the admin just
// operated. Refused here, before the round trip.
await expect(
updateRoutingRule(event, 'r1', { ...base, strategy: 'direct', target_assignee_ids: [] })
).rejects.toThrow(/direct rule needs at least one assignee/i);
expect(apiRequest).not.toHaveBeenCalled();
});
it('names the strategy that refused, for each people strategy', async () => {
await expect(
updateRoutingRule(event, 'r1', { ...base, strategy: 'round_robin', target_assignee_ids: [] })
).rejects.toThrow(/round robin rule needs at least one assignee/i);
await expect(
updateRoutingRule(event, 'r1', { ...base, strategy: 'least_busy', target_assignee_ids: [] })
).rejects.toThrow(/least busy rule needs at least one assignee/i);
expect(apiRequest).not.toHaveBeenCalled();
});
it('refuses an edit whose assignee entries are all blank', async () => {
await expect(
updateRoutingRule(event, 'r1', {
...base,
strategy: 'direct',
target_assignee_ids: ['', null]
})
).rejects.toThrow(/needs at least one assignee/i);
expect(apiRequest).not.toHaveBeenCalled();
});
it('allows an edit switching to by_team with an empty people list', async () => {
// This path must stay open: switching a rule to by_team is exactly when
// the people multi-select is empty and should be. `buildBody` drops the
// assignee key for `by_team` before the emptiness check, so the guard
// never sees it.
apiRequest.mockResolvedValue({});
await updateRoutingRule(event, 'r1', {
...base,
strategy: 'by_team',
target_team_id: 't1',
target_assignee_ids: []
});
const { body } = apiRequest.mock.calls[0][1];
expect(body.target_team_id).toBe('t1');
expect('target_assignee_ids' in body).toBe(false);
});
it('allows a partial edit that never submitted an assignee list', async () => {
// A caller that names a strategy without touching the picker is asking to
// leave the assignees alone, which `partial=True` does. Only a submitted
// and empty list is a discarded change.
apiRequest.mockResolvedValue({});
await updateRoutingRule(event, 'r1', { name: 'Renamed', strategy: 'direct' });
const { body } = apiRequest.mock.calls[0][1];
expect(body).toEqual({ name: 'Renamed', strategy: 'direct' });
});
it('leaves the turn-on and turn-off paths untouched by the guard', async () => {
apiRequest.mockResolvedValue({});
await updateRoutingRule(event, 'r1', { is_active: true });
await updateRoutingRule(event, 'r1', { is_active: false });
expect(apiRequest).toHaveBeenCalledTimes(2);
});
it('does not refuse a create with the same empty list', async () => {
// Deliberately asymmetric. On create the backend's own guard fires and
// its message is the better one, which is the whole point of omitting the
// key rather than sending `[]`.
apiRequest.mockResolvedValue({});
await createRoutingRule(event, { ...base, strategy: 'direct', target_assignee_ids: [] });
expect(apiRequest).toHaveBeenCalledTimes(1);
});
it('throws when the id is missing', async () => {
await expect(updateRoutingRule(event, '', base)).rejects.toThrow(/which rule/i);
expect(apiRequest).not.toHaveBeenCalled();
});
});
describe('deleteRoutingRule', () => {
beforeEach(() => {
apiRequest.mockReset();
});
it('DELETEs the detail endpoint', async () => {
apiRequest.mockResolvedValue({});
await deleteRoutingRule(event, 'r1');
const [url, opts] = apiRequest.mock.calls[0];
expect(url).toBe('/cases/routing-rules/r1/');
expect(opts.method).toBe('DELETE');
});
it('throws when the id is missing', async () => {
await expect(deleteRoutingRule(event, '')).rejects.toThrow(/which rule/i);
expect(apiRequest).not.toHaveBeenCalled();
});
});
describe('CONDITION_FIELDS and CONDITION_OPS', () => {
// These are derived from `CONDITION_FIELD_LABEL`/`CONDITION_OP_LABEL` in
// `$lib/v2/enums.js` rather than hand-restated, because the page's selects
// read those maps directly (a `.svelte` file cannot import from
// `$lib/server/`) and two hand-maintained copies of the same set drift.
// This pins the derived lists to exactly what
// `RoutingRuleSerializer.validate_conditions` accepts, so an addition to
// the label maps that the backend does not also accept fails here instead
// of shipping a field or operator the page offers and the API 400s.
it('matches the fields RoutingRuleSerializer.validate_conditions accepts', () => {
expect(CONDITION_FIELDS).toEqual([
'priority',
'case_type',
'account',
'tags',
'from_email_domain',
'mailbox_id'
]);
});
it('matches the operators RoutingRuleSerializer.validate_conditions accepts', () => {
expect(CONDITION_OPS).toEqual(['eq', 'in', 'contains', 'regex']);
});
});
describe('readConditionRows', () => {
/**
* One row's three inputs, as the form submits them.
*
* `omit` names a control that submitted nothing, which is what a `<select>`
* with no matching option does: `selectedIndex` is -1 and the browser
* contributes no entry for it at all.
*
* @param {FormData} form
* @param {number} i
* @param {{ field?: string, op?: string, value?: string }} row
*/
function appendRow(form, i, row) {
if (row.field !== undefined) form.append(`condition_field_${i}`, row.field);
if (row.op !== undefined) form.append(`condition_op_${i}`, row.op);
if (row.value !== undefined) form.append(`condition_value_${i}`, row.value);
}
beforeEach(() => {
apiRequest.mockReset();
});
it('pairs each row by its index', () => {
const form = new FormData();
appendRow(form, 0, { field: 'priority', op: 'eq', value: 'Urgent' });
appendRow(form, 1, { field: 'tags', op: 'in', value: 'vip, gold' });
expect(readConditionRows(form)).toEqual([
{ field: 'priority', op: 'eq', value: 'Urgent' },
{ field: 'tags', op: 'in', value: 'vip, gold' }
]);
});
it('does not shift the next row when a row submits no field', () => {
// The defect this indexing replaced: three parallel `getAll` arrays paired
// POSITIONALLY, so one absent `condition_field` moved every later row's
// operator and value up by one. Here row 1 keeps its own op and value.
const form = new FormData();
appendRow(form, 0, { op: 'eq', value: 'EMEA' });
appendRow(form, 1, { field: 'priority', op: 'in', value: 'High, Urgent' });
expect(readConditionRows(form)).toEqual([
{ field: '', op: 'eq', value: 'EMEA' },
{ field: 'priority', op: 'in', value: 'High, Urgent' }
]);
});
it('reads rows in index order however the entries were appended', () => {
const form = new FormData();
appendRow(form, 2, { field: 'account', op: 'eq', value: 'Acme' });
appendRow(form, 0, { field: 'priority', op: 'eq', value: 'Urgent' });
expect(readConditionRows(form).map((r) => r.field)).toEqual(['priority', 'account']);
});
it('ignores form keys that are not indexed condition inputs', () => {
const form = new FormData();
form.append('name', 'Urgent to Ada');
form.append('condition_field', 'priority');
form.append('condition_field_x', 'priority');
appendRow(form, 0, { field: 'tags', op: 'eq', value: 'vip' });
expect(readConditionRows(form)).toEqual([{ field: 'tags', op: 'eq', value: 'vip' }]);
});
it('carries a custom_fields. condition through an edit unchanged', async () => {
// The whole round trip: the page renders a stored `custom_fields.<key>`
// as its own option so the select has something to match, the form
// submits it under an indexed name, and the rule saves with the same two
// conditions it had. Before this, an admin who opened Edit only to rename
// a rule lost the custom-field condition and shifted the other row.
apiRequest.mockResolvedValue({});
const form = new FormData();
appendRow(form, 0, { field: 'custom_fields.region', op: 'eq', value: 'EMEA' });
appendRow(form, 1, { field: 'priority', op: 'in', value: 'High, Urgent' });
await updateRoutingRule(event, 'r1', {
name: 'Renamed, conditions untouched',
strategy: 'direct',
target_assignee_ids: ['p1'],
conditions: readConditionRows(form)
});
const { body } = apiRequest.mock.calls[0][1];
expect(body.conditions).toEqual([
{ field: 'custom_fields.region', op: 'eq', value: 'EMEA' },
{ field: 'priority', op: 'in', value: ['High', 'Urgent'] }
]);
});
it('drops only the row that submitted no field, leaving the rest intact', async () => {
apiRequest.mockResolvedValue({});
const form = new FormData();
appendRow(form, 0, { op: 'eq', value: 'EMEA' });
appendRow(form, 1, { field: 'priority', op: 'in', value: 'High, Urgent' });
await updateRoutingRule(event, 'r1', {
name: 'Renamed',
strategy: 'direct',
target_assignee_ids: ['p1'],
conditions: readConditionRows(form)
});
const { body } = apiRequest.mock.calls[0][1];
expect(body.conditions).toEqual([{ field: 'priority', op: 'in', value: ['High', 'Urgent'] }]);
});
});

View file

@ -8,19 +8,77 @@
* `{ count, active, unused }` for the stat cards. Both are computed server-side
* (the usage counts are org-scoped subqueries, not a client tally over rows).
*
* Read-only page: the only controls ("New tag", the duplicate-merge banner) are
* not wired, deferred, like the other settings builders. No write path here.
* "New tag" is wired: `createTag` below posts the name and the page's action
* calls it. The duplicate-merge banner is still deferred; its "Merge" button
* has no backing endpoint yet, see the comment on it in `+page.svelte`.
*
* CREATE IS ADMIN-ONLY, LIST IS NOT
* `/settings` is deliberately member-readable (see the comment in
* `$lib/v2/components/Sidebar.svelte`), and `TagsListView.get` has no role
* check, so every member reads the full tag list. `TagsListView.post`
* (`backend/common/views/tags_views.py:143-149`) does gate: it 403s anyone
* whose `profile.role` is not `ADMIN`. `can_edit` below mirrors that split so
* the page can hide "New tag" for a member instead of letting them submit a
* form the backend was always going to refuse. It is a display hint only,
* decoded from the JWT and never verified; the backend re-derives the role
* from the same token and is the check that actually matters. `viewerRole` is
* imported from `organization.js`, where it is exported for exactly this
* reuse, rather than redefined here: a role check is exactly the kind of
* thing that should not exist in one more private copy per module.
* `goals.js` and `products.js` still carry their own pre-existing private
* copies of the same decode; not touched here, worth consolidating later.
*/
import { apiRequest } from '$lib/api-helpers.js';
import { viewerRole } from './organization.js';
/**
* @param {{ cookies: import('@sveltejs/kit').Cookies }} event
* @returns {Promise<{ tags: any[], totals: any }>}
* @returns {Promise<{ tags: any[], totals: any, can_edit: boolean }>}
*/
export async function getTags({ cookies }) {
const resp = await apiRequest('/tags/?include_archived=true', {}, { cookies });
return {
tags: resp.tags ?? [],
totals: resp.totals ?? { count: 0, active: 0, unused: 0 }
totals: resp.totals ?? { count: 0, active: 0, unused: 0 },
can_edit: viewerRole(cookies) === 'ADMIN'
};
}
/**
* Create a tag.
*
* Only `name` is sent. `org` comes from the JWT on the backend, and `usage`
* and `totals` are computed, never submitted. The empty-name guard is a fast
* fail for an obvious mistake, not a security control: `TagsListView.post`
* (`backend/common/views/tags_views.py`) runs its own `if not name:` check
* after stripping the param, and that is the real authority. `TagsSerializer`
* is not in this path at all; the view only uses it to shape the response.
*
* `TagsListView.post` wraps its result in an envelope,
* `{ error, message, tag }`, on both the create branch and the reactivation
* branch (an archived tag with the same slug is revived instead of
* duplicated). This unwraps to `.tag` deliberately rather than just fixing
* the doc comment: a function named `createTag` that resolves to the
* envelope is a trap the next caller will fall into blind, exactly like
* `createLead` does today, `LeadListView.post` returns no id at all, so
* `leads/new/+page.server.js`'s `created?.id` is always undefined and every
* lead creation redirects to `/leads` instead of the new record. Not every
* create endpoint in this codebase gives you a record back; the seven
* settings pages that copy this function will want to link to or highlight
* the tag they just made, so this one hands back the real thing.
*
* @param {{ cookies: import('@sveltejs/kit').Cookies }} event
* @param {{ name?: string, [key: string]: any }} values callers may pass extra
* keys (a hostile `org`, say); the index signature lets TypeScript accept
* the object literal without widening what this function actually reads,
* which stays just `name`.
* @returns {Promise<any>} the created (or reactivated) tag record: `{ id, name,
* slug, color, description, is_active, created_at }`.
*/
export async function createTag({ cookies }, values) {
const name = (values.name ?? '').trim();
if (!name) throw new Error('A tag needs a name.');
const resp = await apiRequest('/tags/', { method: 'POST', body: { name } }, { cookies });
return resp.tag ?? resp;
}

View file

@ -0,0 +1,56 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
const apiRequest = vi.fn();
vi.mock('$lib/api-helpers.js', () => ({ apiRequest: (...a) => apiRequest(...a) }));
const { createTag } = await import('$lib/server/v2/tags.js');
// Cast rather than shaping a full Cookies mock, matching leads.test.js:
// createTag only ever calls `cookies.get`, and `apiRequest` itself is mocked
// above, so nothing here touches `getAll`/`set`/`delete`/`serialize`. Without
// the cast svelte-check flags this object against SvelteKit's full `Cookies`
// type on every call site below, which is noise for a shape the test
// deliberately keeps minimal.
const event = /** @type {any} */ ({ cookies: { get: () => 'token' } });
describe('createTag', () => {
beforeEach(() => {
apiRequest.mockReset();
});
it('POSTs the trimmed name to /tags/ and unwraps the tag from the response envelope', async () => {
// The real backend, `TagsListView.post`, never returns a bare tag: it
// wraps its result as `{ error, message, tag }` on both the create
// branch and the reactivation branch. A mock that returned a bare object
// here would let `resp.tag ?? resp`'s fallback mask a broken unwrap.
apiRequest.mockResolvedValue({
error: false,
message: 'Tag Created Successfully',
tag: { id: 't1', name: 'urgent' }
});
const result = await createTag(event, { name: ' urgent ' });
const [endpoint, options] = apiRequest.mock.calls[0];
expect(endpoint).toBe('/tags/');
expect(options.method).toBe('POST');
expect(options.body.name).toBe('urgent');
expect(result.id).toBe('t1');
expect(result.name).toBe('urgent');
});
it('falls back to the raw response when it is not wrapped in a tag envelope', async () => {
apiRequest.mockResolvedValue({ id: 't1', name: 'urgent' });
const result = await createTag(event, { name: 'urgent' });
expect(result.id).toBe('t1');
});
it('rejects an empty name before making a request', async () => {
await expect(createTag(event, { name: ' ' })).rejects.toThrow(/name/i);
expect(apiRequest).not.toHaveBeenCalled();
});
it('never forwards a client-supplied org', async () => {
apiRequest.mockResolvedValue({ tag: { id: 't1' } });
await createTag(event, { name: 'urgent', org: 'attacker-org' });
expect(apiRequest.mock.calls[0][1].body.org).toBeUndefined();
});
});

View file

@ -7,16 +7,23 @@
* Approval rows in state "pending" bound to it). Totals carry `count`, `active`,
* and `pending` (the org's total waiting approvals).
*
* Read-only page: "New rule" is a deferred builder, so there is no write path.
* The backend returns `approvers` as `[{ id, email }]`; the page renders them as
* a sentence (`approvers.join(' or ')`), so flatten to the email strings here.
* `match_team` already arrives as `{ id, name }` or null.
* Create, edit, turn off, turn on and delete are wired below. Delete is not
* what its name says on this resource: it destroys a rule that has never been
* used and turns off one that has, and it answers 2xx either way. See
* `deleteApprovalRule` for how the two are told apart.
*
* The backend
* returns `approvers` as `[{ id, email }]`; that shape is kept as-is rather than
* flattened to bare email strings, because the edit form needs the ids to
* preselect the approver multi-select. The page reads `.email` off each entry
* for the sentence it renders on the row.
*/
import { apiRequest } from '$lib/api-helpers.js';
import { viewerRole } from './organization.js';
/**
* @param {{ cookies: import('@sveltejs/kit').Cookies }} event
* @returns {Promise<{ rules: any[], totals: any }>}
* @returns {Promise<{ rules: any[], totals: any, can_edit: boolean }>}
*/
export async function getApprovalRules({ cookies }) {
const { rules, totals } = await apiRequest('/cases/approval-rules/', {}, { cookies });
@ -26,12 +33,119 @@ export async function getApprovalRules({ cookies }) {
name: r.name,
is_active: r.is_active,
approver_role: r.approver_role,
approvers: (r.approvers ?? []).map((a) => a.email).filter(Boolean),
approvers: (r.approvers ?? []).filter((a) => a && a.id),
match_priority: r.match_priority,
match_case_type: r.match_case_type,
match_team: r.match_team ?? null,
pending_count: r.pending_count ?? 0
})),
totals: totals ?? { count: 0, active: 0, pending: 0 }
totals: totals ?? { count: 0, active: 0, pending: 0 },
// A display hint: POST/PUT/DELETE on `/cases/approval-rules/` each start
// with `_is_admin(request.profile)` server-side and 403 regardless of
// what this says. This only decides whether the page offers the controls.
can_edit: viewerRole(cookies) === 'ADMIN'
};
}
/** Everything a create or edit may set. `org` and `created_by` are the JWT's,
* never the body's, and `trigger_event` is not here: see `TRIGGER_EVENT`
* below. Nothing is frozen after creation on this resource, so an edit may
* set the same fields a create may; `ApprovalRuleDetailView.put` builds its
* serializer with `partial=True`, so an omitted key is left untouched rather
* than blanked, which is what lets the turn-on action send a single key. */
const CREATE_FIELDS = [
'name',
'match_priority',
'match_case_type',
'match_team_id',
'approver_role',
'approver_ids',
'is_active'
];
const UPDATE_FIELDS = CREATE_FIELDS;
/** The only value `trigger_event` accepts. It is set here rather than read
* from the form: a select with one option is a control that cannot be
* wrong, so it should not be a control. If the backend ever gains a second
* trigger, this is the one line that has to change and the field becomes a
* real select. */
const TRIGGER_EVENT = 'pre_close';
/** @param {string[]} allowed @param {{ [key: string]: any }} values */
function buildBody(allowed, values) {
/** @type {Record<string, any>} */
const body = {};
for (const field of allowed) {
if (values[field] === undefined) continue;
body[field] = values[field];
}
// Three nullable fields whose "any" option is an empty `<option>` value.
// `''` fails the ChoiceField and the PK lookup alike; `null` is what clears
// them, and all three are `allow_null=True`.
for (const nullable of ['match_priority', 'match_case_type', 'match_team_id']) {
if (body[nullable] === '') body[nullable] = null;
}
if (body.is_active !== undefined) body.is_active = Boolean(body.is_active);
if (body.approver_ids !== undefined) {
body.approver_ids = (body.approver_ids ?? []).filter(Boolean);
}
return body;
}
/** @param {{ cookies: import('@sveltejs/kit').Cookies }} event */
export async function createApprovalRule({ cookies }, values) {
const body = buildBody(CREATE_FIELDS, values);
if (!body.name) throw new Error('A rule needs a name.');
body.trigger_event = TRIGGER_EVENT;
return await apiRequest('/cases/approval-rules/', { method: 'POST', body }, { cookies });
}
/** @param {{ cookies: import('@sveltejs/kit').Cookies }} event */
export async function updateApprovalRule({ cookies }, id, values) {
if (!id) throw new Error('Which rule? No rule id was given.');
const body = buildBody(UPDATE_FIELDS, values);
return await apiRequest(`/cases/approval-rules/${id}/`, { method: 'PUT', body }, { cookies });
}
/**
* Delete a rule, or turn it off, depending on what the backend decides.
*
* There IS a soft-delete hiding behind this verb, and an earlier version of
* this comment said the opposite. `ApprovalRuleDetailView.delete` branches:
*
* ```python
* if rule.requests.exists():
* rule.is_active = False
* rule.save(update_fields=["is_active", "updated_at"])
* return Response({"id": str(rule.id), "is_active": False}, status=200)
* rule.delete()
* ```
*
* `Approval.rule` is `on_delete=models.PROTECT`, so a rule that has ever gated
* a close cannot be destroyed without taking the approval history with it. The
* view turns it off instead and still answers 2xx, so the caller cannot read
* the outcome off "did it throw".
*
* Two things make the outcome unguessable from the page's own data:
*
* - `rule.requests.exists()` counts approvals in EVERY state. The
* `pending_count` the page already has counts only `state="pending"`, so a
* rule showing zero pending can still have history and still be soft
* disabled.
* - The two branches differ only in their body. `apiRequest` returns the
* parsed body on 200 and `null` on the hard-delete branch's 204, so
* `is_active === false` in the response is the signal, and the absence of a
* body is the other one.
*
* Hence the return shape: the action that calls this reports what happened
* rather than asserting what it hoped for.
*
* @param {{ cookies: import('@sveltejs/kit').Cookies }} event
* @returns {Promise<{ turned_off: boolean }>} `turned_off` is true when the
* rule had history and was disabled rather than destroyed.
*/
export async function deleteApprovalRule({ cookies }, id) {
if (!id) throw new Error('Which rule? No rule id was given.');
const resp = await apiRequest(`/cases/approval-rules/${id}/`, { method: 'DELETE' }, { cookies });
return { turned_off: resp?.is_active === false };
}

View file

@ -0,0 +1,200 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
const apiRequest = vi.fn();
vi.mock('$lib/api-helpers.js', () => ({ apiRequest: (...a) => apiRequest(...a) }));
const { createApprovalRule, updateApprovalRule, deleteApprovalRule } = await import(
'./ticket-approvals.js'
);
const cookies = /** @type {any} */ ({ get: () => 'token' });
const event = /** @type {any} */ ({ cookies });
const base = {
name: 'Urgent close needs a manager',
match_priority: 'Urgent',
match_case_type: 'Incident',
match_team_id: 't1',
approver_role: 'ADMIN',
approver_ids: ['p1', 'p2'],
is_active: true
};
describe('createApprovalRule', () => {
beforeEach(() => {
apiRequest.mockReset();
});
it('sends only allow-listed keys on create and drops a hostile org', async () => {
apiRequest.mockResolvedValue({});
await createApprovalRule(event, {
...base,
org: 'ATTACKER-ORG',
created_by: 'ATTACKER'
});
const [url, opts] = apiRequest.mock.calls[0];
expect(url).toBe('/cases/approval-rules/');
expect(opts.method).toBe('POST');
expect(Object.keys(opts.body).sort()).toEqual([
'approver_ids',
'approver_role',
'is_active',
'match_case_type',
'match_priority',
'match_team_id',
'name',
'trigger_event'
]);
expect(opts.body.org).toBeUndefined();
expect(opts.body.created_by).toBeUndefined();
});
it('always sends trigger_event as pre_close, ignoring any caller-supplied value', async () => {
apiRequest.mockResolvedValue({});
await createApprovalRule(event, { ...base, trigger_event: 'post_close' });
const { body } = apiRequest.mock.calls[0][1];
expect(body.trigger_event).toBe('pre_close');
});
it('sends null, not an empty string, for an unselected match_priority', async () => {
apiRequest.mockResolvedValue({});
await createApprovalRule(event, { ...base, match_priority: '' });
const { body } = apiRequest.mock.calls[0][1];
expect(body.match_priority).toBeNull();
});
it('sends null, not an empty string, for an unselected match_case_type', async () => {
apiRequest.mockResolvedValue({});
await createApprovalRule(event, { ...base, match_case_type: '' });
const { body } = apiRequest.mock.calls[0][1];
expect(body.match_case_type).toBeNull();
});
it('sends null, not an empty string, for an unselected match_team_id', async () => {
apiRequest.mockResolvedValue({});
await createApprovalRule(event, { ...base, match_team_id: '' });
const { body } = apiRequest.mock.calls[0][1];
expect(body.match_team_id).toBeNull();
});
it('filters blank entries out of approver_ids', async () => {
apiRequest.mockResolvedValue({});
await createApprovalRule(event, {
...base,
approver_ids: ['p1', '', null, 'p2']
});
const { body } = apiRequest.mock.calls[0][1];
expect(body.approver_ids).toEqual(['p1', 'p2']);
});
it('coerces is_active to a boolean', async () => {
apiRequest.mockResolvedValue({});
await createApprovalRule(event, { ...base, is_active: 'true' });
const { body } = apiRequest.mock.calls[0][1];
expect(body.is_active).toBe(true);
expect(typeof body.is_active).toBe('boolean');
});
it('refuses a rule with no name before making a request', async () => {
await expect(createApprovalRule(event, { ...base, name: '' })).rejects.toThrow(
/needs a name/i
);
expect(apiRequest).not.toHaveBeenCalled();
});
});
describe('updateApprovalRule', () => {
beforeEach(() => {
apiRequest.mockReset();
});
it('PUTs to the detail endpoint', async () => {
apiRequest.mockResolvedValue({});
await updateApprovalRule(event, 'r1', base);
const [url, opts] = apiRequest.mock.calls[0];
expect(url).toBe('/cases/approval-rules/r1/');
expect(opts.method).toBe('PUT');
});
it('sends only what it is given, with no trigger_event and no org/created_by', async () => {
apiRequest.mockResolvedValue({});
await updateApprovalRule(event, 'r1', {
...base,
org: 'ATTACKER-ORG',
created_by: 'ATTACKER'
});
const { body } = apiRequest.mock.calls[0][1];
expect(Object.keys(body).sort()).toEqual([
'approver_ids',
'approver_role',
'is_active',
'match_case_type',
'match_priority',
'match_team_id',
'name'
]);
expect(body.trigger_event).toBeUndefined();
expect(body.org).toBeUndefined();
expect(body.created_by).toBeUndefined();
});
it('sends exactly one key for a minimal { is_active: true } body (the turn-on path)', async () => {
apiRequest.mockResolvedValue({});
await updateApprovalRule(event, 'r1', { is_active: true });
const { body } = apiRequest.mock.calls[0][1];
expect(body).toEqual({ is_active: true });
});
it('sends exactly one key for a minimal { is_active: false } body (the turn-off path)', async () => {
apiRequest.mockResolvedValue({});
await updateApprovalRule(event, 'r1', { is_active: false });
const { body } = apiRequest.mock.calls[0][1];
expect(body).toEqual({ is_active: false });
});
it('throws when the id is missing', async () => {
await expect(updateApprovalRule(event, '', base)).rejects.toThrow(/which rule/i);
expect(apiRequest).not.toHaveBeenCalled();
});
});
describe('deleteApprovalRule', () => {
beforeEach(() => {
apiRequest.mockReset();
});
it('DELETEs the detail endpoint', async () => {
apiRequest.mockResolvedValue(null);
await deleteApprovalRule(event, 'r1');
const [url, opts] = apiRequest.mock.calls[0];
expect(url).toBe('/cases/approval-rules/r1/');
expect(opts.method).toBe('DELETE');
});
it('reports a real delete when the response carries no body', async () => {
// `ApprovalRuleDetailView.delete` answers 204 on the hard-delete branch,
// and `apiRequest` turns a 204 into `null`.
apiRequest.mockResolvedValue(null);
await expect(deleteApprovalRule(event, 'r1')).resolves.toEqual({ turned_off: false });
});
it('reports a soft disable when the response says is_active is false', async () => {
// The other branch: `rule.requests.exists()` is true, so the view sets
// `is_active = False` and answers 200 with `{ id, is_active: false }`.
// Nothing about the status code distinguishes the two for a caller that
// only checks "did it throw", which is how the page came to promise a
// permanence the backend never delivered.
apiRequest.mockResolvedValue({ id: 'r1', is_active: false });
await expect(deleteApprovalRule(event, 'r1')).resolves.toEqual({ turned_off: true });
});
it('does not read a soft disable out of an unrelated 200 body', async () => {
apiRequest.mockResolvedValue({ id: 'r1' });
await expect(deleteApprovalRule(event, 'r1')).resolves.toEqual({ turned_off: false });
});
it('throws when the id is missing', async () => {
await expect(deleteApprovalRule(event, '')).rejects.toThrow(/which rule/i);
expect(apiRequest).not.toHaveBeenCalled();
});
});

View file

@ -1,16 +1,19 @@
/**
* Weekly timesheet: the wiring behind /v2/timesheet.
*
* Server-only. One backend call, `GET /time-entries/timesheet/`, returns the
* caller's own week grouped into day buckets (every day present, empty or not)
* with week totals, the billable split, and a running-timer count. The page
* reads it verbatim as `data.week`.
* Server-only. `GET /time-entries/timesheet/` returns the caller's own week
* grouped into day buckets (every day present, empty or not) with week
* totals, the billable split, and a running-timer count. The page reads it
* verbatim as `data.week`.
*
* The v2 page is always "your timesheet", it has no profile switcher, so this
* layer never passes a `profile`, which also keeps it clear of the endpoint's
* admin-only "another profile" 403. `TimesheetView` already expands `case` and
* `invoice` to `{id, name}` / `{id, invoice_number}` and names the profile, so
* there is no reshaping here.
*
* `stopTimer` is the one write path here: `POST /time-entries/<id>/stop/`.
* Nothing else on this page is editable.
*/
import { apiRequest } from '$lib/api-helpers.js';
@ -45,3 +48,24 @@ export async function getTimesheet({ cookies }, { start, end } = {}) {
const week = await apiRequest(`/time-entries/timesheet/?${qs.toString()}`, {}, { cookies });
return { week };
}
/**
* Stop a running timer.
*
* The id guard is not defensive noise: an empty id would POST to
* `/time-entries//stop/`, which is a different path, and the failure would
* read as a routing bug rather than a missing argument.
*
* Ownership is the backend's call. The endpoint is org-scoped and checks the
* entry belongs to the caller, so this does not re-check it here and must not
* be read as having done so.
*
* @param {{ cookies: import('@sveltejs/kit').Cookies }} event
* @param {string} entryId
* @returns {Promise<any>} the stopped entry
*/
export async function stopTimer({ cookies }, entryId) {
if (!entryId) throw new Error('Which time entry? No entry id was given.');
return await apiRequest(`/time-entries/${entryId}/stop/`, { method: 'POST' }, { cookies });
}

View file

@ -0,0 +1,34 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
const apiRequest = vi.fn();
vi.mock('$lib/api-helpers.js', () => ({ apiRequest: (...a) => apiRequest(...a) }));
const { stopTimer } = await import('$lib/server/v2/timesheet.js');
// Cast rather than shaping a full Cookies mock, matching leads.test.js and
// tags.test.js: stopTimer only ever calls `cookies.get`, and `apiRequest`
// itself is mocked above, so nothing here touches
// `getAll`/`set`/`delete`/`serialize`. Without the cast svelte-check flags
// this object against SvelteKit's full `Cookies` type on every call site
// below, which is noise for a shape the test deliberately keeps minimal.
const event = /** @type {any} */ ({ cookies: { get: () => 'token' } });
describe('stopTimer', () => {
beforeEach(() => {
apiRequest.mockReset();
});
it('POSTs to the stop endpoint for the given entry', async () => {
apiRequest.mockResolvedValue({ id: 'e1', ended_at: '2026-08-04T10:00:00Z' });
const result = await stopTimer(event, 'e1');
const [endpoint, options] = apiRequest.mock.calls[0];
expect(endpoint).toBe('/time-entries/e1/stop/');
expect(options.method).toBe('POST');
expect(result.ended_at).toBeTruthy();
});
it('refuses a missing entry id rather than posting to a malformed path', async () => {
await expect(stopTimer(event, '')).rejects.toThrow(/entry/i);
expect(apiRequest).not.toHaveBeenCalled();
});
});

View file

@ -4,12 +4,26 @@
* Single source of truth for the bell badge, the panel list, and
* svelte-sonner toasts. Talks to the SvelteKit proxies under
* `/api/notifications/...` (which forward to Django with the JWT cookie).
*
* Delivery is by polling `?since=<iso>`. This replaced an EventSource stream
* on 2026-08-03. The SSE endpoint was the only async code in the backend, so
* it forced the entire deployment onto ASGI, where each in-flight request
* takes its own database connection with no ceiling. It was also silently
* delivering nothing under a correctly configured database role, and the
* `error` handler here was an empty placeholder, so in practice the bell
* already only updated on page load. Polling is strictly better than that and
* costs about one concurrent request per 900 open tabs.
*/
import { toast } from 'svelte-sonner';
const PANEL_LIMIT = 20;
// Delivery latency ceiling. Notifications here are "you were assigned a lead",
// not chat, so tens of seconds is fine and the load is flat and predictable
// rather than proportional to how long tabs stay open.
const POLL_INTERVAL_MS = 45_000;
// Verbs that should fire an in-page toast in addition to bumping the badge.
// Keep this conservative: too noisy and users mute the channel.
// NOTE: `case.*` keys are backend wire-format strings. Do not rename.
@ -22,10 +36,17 @@ class NotificationsStore {
loading = $state(false);
error = $state('');
/** @type {EventSource | null} */
#stream = null;
/** @type {ReturnType<typeof setInterval> | null} */
#timer = null;
/** @type {boolean} */
#started = false;
/** @type {boolean} */
#polling = false;
/** High-water mark: `created_at` of the newest row we have ingested. */
/** @type {string | null} */
#since = null;
/** @type {(() => void) | null} */
#onVisibility = null;
async fetch() {
this.loading = true;
@ -37,6 +58,7 @@ class NotificationsStore {
this.notifications = data.results || [];
this.unread_count = data.unread_count ?? 0;
this.total_count = data.count ?? this.notifications.length;
this.#advanceSince(this.notifications);
} catch (err) {
console.error('notifications fetch failed', err);
this.error = 'Could not load notifications.';
@ -106,35 +128,87 @@ class NotificationsStore {
}
}
startStream() {
start() {
if (this.#started || typeof window === 'undefined') return;
this.#started = true;
this.fetch();
this.#timer = setInterval(() => this.#poll(), POLL_INTERVAL_MS);
// Don't poll a tab nobody is looking at, and catch up immediately when
// the user comes back rather than making them wait out the interval.
this.#onVisibility = () => {
if (document.visibilityState === 'visible') this.#poll();
};
document.addEventListener('visibilitychange', this.#onVisibility);
}
stop() {
if (this.#timer !== null) {
clearInterval(this.#timer);
this.#timer = null;
}
if (this.#onVisibility) {
document.removeEventListener('visibilitychange', this.#onVisibility);
this.#onVisibility = null;
}
this.#started = false;
}
async #poll() {
// Skip while hidden, and never let a slow request stack up behind itself.
if (this.#polling || document.visibilityState === 'hidden') return;
this.#polling = true;
try {
this.#stream = new EventSource('/api/notifications/stream/');
this.#stream.addEventListener('notification', (ev) => {
try {
const row = JSON.parse(/** @type {MessageEvent} */ (ev).data);
this.#ingest(row);
} catch (err) {
console.error('notifications: bad SSE payload', err);
}
});
this.#stream.addEventListener('error', () => {
// Browser will auto-retry; nothing to do unless we want to fall back
// to polling. Leaving this as a placeholder.
});
const qs = new URLSearchParams({ limit: String(PANEL_LIMIT) });
if (this.#since) qs.set('since', this.#since);
const res = await window.fetch(`/api/notifications/?${qs}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
// Oldest first, so the panel ends up newest-first after each unshift
// and the toasts fire in the order things actually happened.
const rows = (data.results || []).slice().reverse();
for (const row of rows) this.#ingest(row);
this.#advanceSince(rows);
// `unread_count` is computed over the whole feed server-side, unlike
// `count`, which is scoped to the `since` window. Trust it over the
// increments #ingest made, so a read on another device converges here.
if (typeof data.unread_count === 'number') this.unread_count = data.unread_count;
} catch (err) {
console.error('notifications: EventSource open failed', err);
// A failed poll is not worth surfacing: the next tick retries, and
// showing an error banner for a transient blip is worse than silence.
console.error('notifications poll failed', err);
} finally {
this.#polling = false;
}
}
stopStream() {
if (this.#stream) {
this.#stream.close();
this.#stream = null;
/**
* Move the high-water mark to the newest `created_at` we have seen.
*
* Compares parsed instants, never the raw strings. DRF omits the
* microseconds component when it is zero, so `...T10:00:00Z` and
* `...T10:00:00.123456Z` differ in length, and under a `Z` suffix the
* shorter one sorts *later* lexicographically ('Z' > '.') while being
* earlier in time. That would advance `since` past a notification and drop
* it. The bug is invisible on the default `TIME_ZONE = "Asia/Kolkata"`
* (a '+' offset happens to sort correctly) and appears only for deployments
* that set `TIME_ZONE = "UTC"`, which is exactly the sort of thing that
* survives every local test and fails in someone else's production.
*
* @param {any[]} rows
*/
#advanceSince(rows) {
let best = this.#since === null ? -Infinity : Date.parse(this.#since);
for (const row of rows) {
if (!row?.created_at) continue;
const t = Date.parse(row.created_at);
if (!Number.isNaN(t) && t > best) {
best = t;
this.#since = row.created_at;
}
}
this.#started = false;
}
/** @param {any} row */

View file

@ -0,0 +1,74 @@
<script>
/**
* A destructive action that takes two clicks.
*
* The first click swaps the button for a confirm and a cancel; the second
* submits. No `window.confirm`: a native dialog blocks the page, cannot be
* styled or explained, and is a dead end for anything driving the browser.
*
* `explain` is the one line of consequence shown while armed. Say what the
* action actually does. "Turn off" and "Delete permanently" are different
* promises and this codebase has both, sometimes behind the same verb on
* the backend.
*/
import { enhance } from '$app/forms';
/** @type {{
* action: string,
* label?: string,
* confirmLabel?: string,
* explain?: string,
* hidden?: Record<string, string>
* }} */
let {
action,
label = 'Delete',
confirmLabel = 'Confirm',
explain = '',
hidden = {}
} = $props();
let armed = $state(false);
let busy = $state(false);
</script>
{#if armed}
<form
class="v2-confirm"
method="POST"
{action}
use:enhance={() => {
busy = true;
return async (/** @type {any} */ { update }) => {
await update();
busy = false;
// Disarm either way. On success the row is gone; on failure the page
// error is what the user needs to read, not a still-armed button.
armed = false;
};
}}
>
{#each Object.entries(hidden) as [name, value] (name)}
<input type="hidden" {name} {value} />
{/each}
{#if explain}
<span class="v2-sub" style="font-size:11.5px">{explain}</span>
{/if}
<button class="v2-btn v2-btn-sm" type="submit" disabled={busy}>{confirmLabel}</button>
<button class="v2-btn v2-btn-sm" type="button" disabled={busy} onclick={() => (armed = false)}>
Cancel
</button>
</form>
{:else}
<button class="v2-btn v2-btn-sm" type="button" onclick={() => (armed = true)}>{label}</button>
{/if}
<style>
.v2-confirm {
display: inline-flex;
align-items: center;
gap: 7px;
flex-wrap: wrap;
justify-content: flex-end;
}
</style>

View file

@ -0,0 +1,112 @@
<script>
/**
* The chrome around a settings form.
*
* Every settings page in v2 is a list with an "add" or "edit" control, and
* every one of those forms needs the same four things: somewhere to put the
* error, a submit that cannot be double-fired, a cancel, and the rule that
* a failed submit leaves the form open so the error stays on screen. That
* rule is the reason this exists as a component rather than as markup
* copied eight times: getting it wrong closes the panel and takes the
* message with it, and it is invisible until someone submits something
* invalid.
*
* The fields are the caller's, passed as a snippet. This component holds no
* opinion about what is being edited and no per-resource state.
*
* Visibility is the caller's too: render this inside an `{#if}`. A panel
* that owned its own `open` flag would need the caller to reach in and set
* it to switch between "add" and "edit this row", which is worse than an
* `{#if}`.
*/
import { enhance } from '$app/forms';
/** @type {{
* title: string,
* action: string,
* error?: string | null,
* submitLabel?: string,
* oncancel: () => void,
* ondone?: () => void,
* fields: import('svelte').Snippet
* }} */
let {
title,
action,
error = null,
submitLabel = 'Save',
oncancel,
ondone,
fields
} = $props();
// Disables submit while a request is in flight so a double-click cannot
// fire two writes.
let busy = $state(false);
</script>
<div class="v2-card v2-sfp">
<form
method="POST"
{action}
use:enhance={() => {
busy = true;
return async (/** @type {any} */ { result, update }) => {
await update();
busy = false;
// Close only on success. A rejected submit has to leave the panel
// open, or the error rendered above the fields is unmounted the
// instant the action returns and nobody ever reads it.
if (result.type === 'success') ondone?.();
};
}}
>
<div class="v2-sfp-head">{title}</div>
{#if error}
<p class="v2-error" style="margin:0 0 12px">{error}</p>
{/if}
<div class="v2-sfp-fields">
{@render fields()}
</div>
<div class="v2-sfp-foot">
<button class="v2-btn v2-btn-primary" type="submit" disabled={busy}>{submitLabel}</button>
<button class="v2-btn" type="button" disabled={busy} onclick={oncancel}>Cancel</button>
</div>
</form>
</div>
<style>
.v2-sfp {
padding: 16px 17px;
margin-bottom: 18px;
}
.v2-sfp-head {
font-weight: 600;
font-size: 13px;
margin-bottom: 13px;
}
/* Two columns on a wide screen, one on a narrow one. A settings form is
mostly short fields (a number, a select, a checkbox) and a single column
of them wastes the width these pages have. A field that needs the full
row opts in with `grid-column: 1 / -1` via the `v2-sfp-wide` class. */
.v2-sfp-fields {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 13px 18px;
align-items: start;
}
.v2-sfp-foot {
display: flex;
gap: 8px;
margin-top: 16px;
}
@media (max-width: 768px) {
.v2-sfp-fields {
grid-template-columns: 1fr;
}
}
</style>

View file

@ -312,6 +312,16 @@ export const ROUTING_STRATEGY_LABEL = {
by_team: 'Anyone on'
};
/** Standalone names for the strategy select. `ROUTING_STRATEGY_LABEL` above
* is a sentence fragment that runs into the target names on the rule card,
* so it cannot double as an option label. */
export const ROUTING_STRATEGY_NAME = {
direct: 'Direct',
round_robin: 'Round robin',
least_busy: 'Least busy',
by_team: 'By team'
};
/** Fields a routing condition can test, in the words the rest of the app uses. */
export const CONDITION_FIELD_LABEL = {
priority: 'Priority',
@ -336,6 +346,12 @@ export const ESCALATION_ACTION_LABEL = {
notify_and_reassign: 'Notify and reassign to'
};
/** cases.EscalationPolicy priorities, worst first. This is the display order
* the escalation page sorts by, not the model's `ordering = ("priority",)`,
* which sorts the CharField alphabetically and puts Low between High and
* Normal. Imported by both the page and `lib/server/v2/escalation.js`. */
export const ESCALATION_PRIORITIES = ['Urgent', 'High', 'Normal', 'Low'];
/** cases.InboundMailbox.PROVIDER_CHOICES, only SES ships today. */
export const MAILBOX_PROVIDER_LABEL = {
ses: 'Amazon SES',
@ -356,6 +372,16 @@ export const FIELD_TYPE_LABEL = {
checkbox: 'Checkbox'
};
/** The statuses a reopened ticket may come back as.
*
* `ReopenPolicySerializer.NON_TERMINAL_STATUSES` in
* `backend/cases/serializer.py` is the authority and rejects anything else.
* Reopening into a terminal status would close the ticket again on arrival,
* so the model's own choice list, which also carries Closed, Rejected and
* Duplicate, is not the list to offer.
*/
export const REOPEN_TO_STATUSES = ['New', 'Assigned', 'Pending'];
/** Plural forms for the target model, for reading in a heading. */
export const TARGET_MODEL_LABEL = {
Account: 'Accounts',

View file

@ -0,0 +1,66 @@
/**
* Keeping a stored target that the picker list cannot offer.
*
* Every people picker on the settings pages is built from
* `getOrgPeopleAndTeams`, and `GetTeamsAndUsersView` filters profiles to
* `is_active=True, org=request.profile.org`. None of the four `cases` settings
* resources filter `is_active` on the write side, so a profile that was a
* legal target when it was chosen stays the stored target after it is
* deactivated. The list the form renders from can no longer represent it.
*
* A `<select>` whose bound value matches no option reports
* `selectedIndex === -1`, and a select with no selected option contributes NO
* entry to `FormData`. The action then reads that absence as `''` and the
* body builder turns `''` into `null`. So an admin who opens an edit form to
* change something unrelated, and saves, silently clears a target they never
* touched. On an escalation policy that means Urgent breaches stop escalating
* to anybody, with no message anywhere.
*
* The fix is to give the select something to match: render the stored value as
* its own option, labelled so the admin can see why it is there. That is what
* these two helpers find. They live in `$lib/v2/` rather than `$lib/server/v2/`
* because a `.svelte` file cannot import from `$lib/server/`, and here they can
* still be unit tested, unlike the markup that consumes them.
*
* "Not in the list" is the test, not "is_active is false": the pages that need
* this do not receive `is_active` on a stored target, and absence from a list
* that only ever contains active in-org profiles means the same thing. The one
* case where it means something else is a failed picker fetch, which
* `getOrgPeopleAndTeams` reports as empty lists; the form is unusable then
* anyway, and keeping the stored value is still the right outcome.
*/
/**
* The stored targets the options list cannot offer.
*
* @param {{ id: string }[]} options what the picker can currently show
* @param {any[]} stored what the record actually points at
* @returns {any[]} the entries of `stored` with no matching option, in order
*/
export function missingOptions(options, stored) {
const known = new Set((options ?? []).map((o) => o?.id).filter(Boolean));
return (stored ?? []).filter((s) => s && s.id && !known.has(s.id));
}
/**
* The single stored target an options list cannot offer, or null.
*
* @param {{ id: string }[]} options
* @param {any} stored a single target object, or null when nothing is set
* @returns {any} the target when it is unrepresentable, null otherwise
*/
export function missingOption(options, stored) {
return missingOptions(options, stored ? [stored] : [])[0] ?? null;
}
/**
* How such an option reads. Not a bare name: the point is that the admin can
* tell the difference between a person they can pick and a person who is only
* there because the record already points at them.
*
* @param {string | null | undefined} name
* @returns {string}
*/
export function inactiveOptionLabel(name) {
return `${name || 'Unnamed'} (no longer active)`;
}

View file

@ -0,0 +1,73 @@
import { describe, it, expect } from 'vitest';
import { missingOption, missingOptions, inactiveOptionLabel } from './pickers.js';
const people = [
{ id: 'p1', name: 'Ada Lovelace' },
{ id: 'p2', name: 'Grace Hopper' }
];
describe('missingOptions', () => {
it('returns the stored entries the options list cannot offer', () => {
const stored = [{ id: 'p1' }, { id: 'gone', email: 'left@x.io' }];
expect(missingOptions(people, stored)).toEqual([{ id: 'gone', email: 'left@x.io' }]);
});
it('returns nothing when every stored entry is in the list', () => {
expect(missingOptions(people, [{ id: 'p1' }, { id: 'p2' }])).toEqual([]);
});
it('keeps the stored order', () => {
const stored = [{ id: 'a' }, { id: 'p1' }, { id: 'b' }];
expect(missingOptions(people, stored).map((s) => s.id)).toEqual(['a', 'b']);
});
it('treats an empty options list as offering nothing', () => {
// What a failed `getOrgPeopleAndTeams` fetch looks like. Keeping the
// stored value is still the right outcome: the form cannot offer an
// alternative, so discarding it would be pure loss.
expect(missingOptions([], [{ id: 'p1' }])).toEqual([{ id: 'p1' }]);
});
it('survives null and undefined on either side', () => {
expect(missingOptions(null, null)).toEqual([]);
expect(missingOptions(undefined, undefined)).toEqual([]);
expect(missingOptions(people, undefined)).toEqual([]);
});
it('ignores stored entries with no id', () => {
expect(missingOptions(people, [null, {}, { id: '' }])).toEqual([]);
});
});
describe('missingOption', () => {
it('returns the stored target when the list cannot offer it', () => {
expect(missingOption(people, { id: 'gone', name: 'Departed' })).toEqual({
id: 'gone',
name: 'Departed'
});
});
it('returns null when the list can offer it', () => {
expect(missingOption(people, { id: 'p1', name: 'Ada Lovelace' })).toBeNull();
});
it('returns null when nothing is stored', () => {
expect(missingOption(people, null)).toBeNull();
expect(missingOption(people, undefined)).toBeNull();
});
});
describe('inactiveOptionLabel', () => {
it('says the target is no longer active', () => {
expect(inactiveOptionLabel('Ada Lovelace')).toBe('Ada Lovelace (no longer active)');
});
it('falls back to Unnamed rather than rendering null', () => {
// Both `shapeTarget` and `shapeAssignee` resolve a missing
// `user_details.name` to null, so a bare interpolation would read
// "null (no longer active)".
expect(inactiveOptionLabel(null)).toBe('Unnamed (no longer active)');
expect(inactiveOptionLabel('')).toBe('Unnamed (no longer active)');
});
});

View file

@ -1002,6 +1002,17 @@ a.v2-setting:hover {
.v2-field {
margin-bottom: 15px;
}
/* `.v2-field` carries a bottom margin for the single-column forms it was
written for (`/leads/new`). Inside the panel the grid's own gap does that
job, and both together double the spacing. */
.v2-sfp-fields .v2-field {
margin-bottom: 0;
}
/* Opt a field out of the panel's two-column grid when it needs the whole
row: a textarea, a checkbox with a sentence next to it, an options list. */
.v2-sfp-wide {
grid-column: 1 / -1;
}
.v2-field > label {
display: block;
font-size: 12.5px;

View file

@ -42,8 +42,11 @@
<span class="v2-num">{totals.unworked_over_a_week}</span> unworked for more than a week
{/snippet}
{#snippet actions()}
<!-- Import stays unwired: /api/leads/import/ does not exist yet. Contacts
and cases both have import/preview/ and import/commit/; leads does not.
Tracked in the phase 2 plan. -->
<button class="v2-btn"><Upload />Import</button>
<button class="v2-btn v2-btn-primary"><Plus />New {singular}</button>
<a class="v2-btn v2-btn-primary" href="/leads/new"><Plus />New {singular}</a>
{/snippet}
</PageHeader>
@ -57,7 +60,7 @@
>
{#snippet icon()}<Target size={21} />{/snippet}
{#snippet actions()}
<button class="v2-btn v2-btn-primary">New {singular}</button>
<a class="v2-btn v2-btn-primary" href="/leads/new">New {singular}</a>
<button class="v2-btn">Import</button>
{/snippet}
</EmptyState>

View file

@ -0,0 +1,32 @@
import { fail, redirect } from '@sveltejs/kit';
import { EDITABLE_FIELDS, createLead, getLeadFormOptions } from '$lib/server/v2/leads.js';
import { readableError } from '$lib/server/v2/form-errors.js';
/** @type {import('./$types').PageServerLoad} */
export async function load(event) {
return await getLeadFormOptions(event);
}
/** @type {import('./$types').Actions} */
export const actions = {
async create(event) {
const form = await event.request.formData();
/** @type {Record<string, any>} */
const values = {};
for (const field of [...EDITABLE_FIELDS, 'assigned_to']) {
if (form.has(field)) values[field] = form.get(field)?.toString().trim() ?? '';
}
/** @type {any} */
let created;
try {
created = await createLead(event, values);
} catch (/** @type {any} */ err) {
// Values go back so a rejected form is not a blank form.
return fail(400, { values, error: readableError(err, 'Could not create the lead.') });
}
redirect(303, created?.id ? `/leads/${created.id}` : '/leads');
}
};

View file

@ -0,0 +1,324 @@
<script>
/**
* Adding a lead.
*
* A brand-new org cannot add its first lead through the web UI without this
* page. `/leads` has always rendered a "New lead" button; nothing was ever
* behind it. See CLAUDE.md, "API Validation & Authorization": the checks
* below are a courtesy that saves a round trip, not the rule. The
* serializer runs again on everything that arrives, and a curl request or a
* stale build reaches it without ever loading this file.
*
* Nothing here binds to `org`, `created_by`, or an assigned-by field. Those
* are server-derived; `createLead` never reads them off the form, and the
* action below only ever forwards keys named in `EDITABLE_FIELDS`.
*/
import { tick, untrack } from 'svelte';
import { enhance } from '$app/forms';
import PageHeader from '$lib/v2/components/PageHeader.svelte';
import {
LEAD_STATUSES,
LEAD_STATUS_LABEL,
LEAD_SOURCES,
LEAD_SOURCE_LABEL,
INDUSTRIES,
industryLabel
} from '$lib/v2/enums.js';
import { money } from '$lib/v2/format.js';
import { TriangleAlert } from '@lucide/svelte';
/** @type {{ data: any, form: any }} */
let { data, form: result } = $props();
// Seeded from the load once, on purpose: a half-typed form must not be
// wiped if the page data revalidates underneath it. untrack() says that
// out loud rather than leaving it as an accident.
let form = $state(
untrack(() => ({
first_name: '',
last_name: '',
company_name: '',
email: '',
assigned_to: data.defaults.assigned_to,
job_title: '',
phone: '',
website: '',
status: data.defaults.status,
source: '',
industry: '',
opportunity_amount: '',
description: '',
// A rejected submit comes back with what was typed. Retyping a dozen
// fields because one collided is how people learn to distrust a create
// page.
...(untrack(() => result?.values) ?? {})
}))
);
let touched = $state(/** @type {Record<string, boolean>} */ ({}));
let submitted = $state(false);
// Disables the submit button while the create action is in flight, so a
// double-click cannot fire two creates.
let busy = $state(false);
let errors = $derived.by(() => {
/** @type {Record<string, string>} */
const e = {};
// Mirrors the edit form's own rule: a lead needs a name to be findable,
// but not both halves of one. Neither half is required by the API
// itself (Lead.first_name/last_name are both nullable), so this is a UX
// floor, not the boundary; an empty lead would otherwise save silently
// and be unfindable in the list a moment later.
if (!form.first_name.trim() && !form.last_name.trim())
e.last_name = 'A lead needs a name to be findable. First or last will do.';
if (form.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email))
e.email = 'That does not look like an email address.';
// The exact regex from `flexible_phone_validator`. Extensions like "x123"
// are rejected by the model, so they are caught here rather than as an
// opaque whole-form refusal after the save.
if (form.phone && !/^[\d\s\-()+.]{7,25}$/.test(form.phone))
e.phone = '7 to 25 characters: digits, spaces, brackets, dots, dashes. No extensions.';
// `createLead` runs `Number(amount)` and the body is JSON-encoded, and
// `JSON.stringify` turns `NaN` into `null`. Without this check, typing
// "abc" would not error, it would silently save as no value at all.
if (form.opportunity_amount !== '') {
const n = Number(form.opportunity_amount);
if (!Number.isFinite(n)) e.opportunity_amount = 'Estimated value has to be a number.';
else if (n < 0) e.opportunity_amount = 'Estimated value cannot be negative.';
}
return e;
});
let valid = $derived(Object.keys(errors).length === 0);
const show = (/** @type {string} */ field) => (touched[field] || submitted) && errors[field];
/**
* On success the action redirects to the new lead, so there is no success
* state to render here.
*
* @type {import('./$types').SubmitFunction}
*/
const check = async ({ cancel }) => {
submitted = true;
if (!valid) {
// Send focus to the first field that needs work rather than only
// colouring it. await tick() matters: on the first submit the
// aria-invalid attributes do not exist until Svelte flushes, so
// querying now finds nothing.
cancel();
await tick();
/** @type {HTMLElement | null} */
const first = document.querySelector('[aria-invalid="true"]');
first?.focus();
return;
}
busy = true;
return async (/** @type {any} */ { update }) => {
await update();
busy = false;
};
};
</script>
<PageHeader title="New lead" center>
{#snippet crumb()}
<a href="/leads">Leads</a> ›
{/snippet}
{#snippet sub()}
A name and a company is enough to start. The rest can wait.
{/snippet}
</PageHeader>
<div class="v2-scroll v2-pad" style="padding-top:18px">
<form class="v2-form" method="POST" action="?/create" use:enhance={check} novalidate>
{#if result?.error}
<div
class="v2-next"
style="background:color-mix(in srgb, var(--v2-rust) 9%, transparent);border-color:color-mix(in srgb, var(--v2-rust) 28%, transparent);margin-bottom:18px"
role="alert"
>
<TriangleAlert size={17} style="color:var(--v2-rust);flex:none" />
<div class="v2-next-body">
<div style="font-weight:600">The server refused this lead</div>
<div class="v2-sub" style="margin-top:2px">{result.error}</div>
</div>
</div>
{/if}
{#if submitted && !valid}
<div
class="v2-next"
style="background:color-mix(in srgb, var(--v2-rust) 9%, transparent);border-color:color-mix(in srgb, var(--v2-rust) 28%, transparent);margin-bottom:18px"
role="alert"
>
<TriangleAlert size={17} style="color:var(--v2-rust);flex:none" />
<div class="v2-next-body">
<div style="font-weight:600">
{Object.keys(errors).length} field{Object.keys(errors).length === 1 ? '' : 's'} still need{Object.keys(
errors
).length === 1
? 's'
: ''} you
</div>
<div class="v2-sub" style="margin-top:2px">Nothing has been saved.</div>
</div>
</div>
{/if}
<div class="v2-field">
<label for="f-first">First name</label>
<input
id="f-first"
name="first_name"
class="v2-input"
bind:value={form.first_name}
onblur={() => (touched.first_name = true)}
/>
</div>
<div class="v2-field">
<label for="f-last">Last name</label>
<input
id="f-last"
name="last_name"
class="v2-input"
bind:value={form.last_name}
onblur={() => (touched.last_name = true)}
aria-invalid={show('last_name') ? 'true' : undefined}
aria-describedby={show('last_name') ? 'e-last' : undefined}
/>
{#if show('last_name')}<p class="v2-error" id="e-last">{errors.last_name}</p>{/if}
</div>
<div class="v2-field">
<label for="f-company">Company</label>
<input id="f-company" name="company_name" class="v2-input" bind:value={form.company_name} />
</div>
<div class="v2-field">
<label for="f-email">Email</label>
<input
id="f-email"
name="email"
class="v2-input"
type="email"
bind:value={form.email}
onblur={() => (touched.email = true)}
aria-invalid={show('email') ? 'true' : undefined}
aria-describedby={show('email') ? 'e-email' : undefined}
/>
{#if show('email')}<p class="v2-error" id="e-email">{errors.email}</p>{/if}
</div>
<div class="v2-field">
<label for="f-owner">Owner</label>
<select id="f-owner" name="assigned_to" class="v2-input" bind:value={form.assigned_to}>
<option value="">Unassigned</option>
{#each data.owners as o (o.id)}
<option value={o.id}>{o.name}</option>
{/each}
</select>
</div>
<div class="v2-field">
<label for="f-jobtitle">Job title</label>
<input id="f-jobtitle" name="job_title" class="v2-input" bind:value={form.job_title} />
</div>
<div class="v2-field">
<label for="f-phone">Phone</label>
<input
id="f-phone"
name="phone"
class="v2-input"
bind:value={form.phone}
onblur={() => (touched.phone = true)}
aria-invalid={show('phone') ? 'true' : undefined}
aria-describedby={show('phone') ? 'e-phone' : undefined}
/>
{#if show('phone')}<p class="v2-error" id="e-phone">{errors.phone}</p>{/if}
</div>
<div class="v2-field">
<label for="f-website">Website</label>
<input id="f-website" name="website" class="v2-input" bind:value={form.website} />
</div>
<div class="v2-field">
<label for="f-status">Status</label>
<select id="f-status" name="status" class="v2-input" bind:value={form.status}>
{#each LEAD_STATUSES.filter((s) => s !== 'converted') as s (s)}
<option value={s}>{LEAD_STATUS_LABEL[s]}</option>
{/each}
</select>
<p class="v2-hint">
Converting is a significant, largely irreversible step: it creates an Account, a Contact and
an Opportunity that nothing undoes if the status changes back, and it requires an email
address that nothing else here does. Set the status here to something else, and convert once
the lead is real.
</p>
</div>
<div class="v2-field">
<label for="f-source">Source</label>
<select id="f-source" name="source" class="v2-input" bind:value={form.source}>
<option value="">Not specified</option>
{#each LEAD_SOURCES as s (s)}
<option value={s}>{LEAD_SOURCE_LABEL[s]}</option>
{/each}
</select>
</div>
<div class="v2-field">
<label for="f-industry">Industry</label>
<select id="f-industry" name="industry" class="v2-input" bind:value={form.industry}>
<option value="">Not specified</option>
{#each INDUSTRIES as ind (ind)}
<option value={ind}>{industryLabel(ind)}</option>
{/each}
</select>
</div>
<div class="v2-field">
<label for="f-amount">Estimated value</label>
<input
id="f-amount"
name="opportunity_amount"
class="v2-input v2-num"
type="number"
step="any"
bind:value={form.opportunity_amount}
onblur={() => (touched.opportunity_amount = true)}
aria-invalid={show('opportunity_amount') ? 'true' : undefined}
aria-describedby={show('opportunity_amount') ? 'e-amount' : 'h-amount'}
/>
{#if show('opportunity_amount')}
<p class="v2-error" id="e-amount">{errors.opportunity_amount}</p>
{:else}
<p class="v2-hint" id="h-amount">
{Number(form.opportunity_amount) > 0
? money(Number(form.opportunity_amount))
: 'What the deal would be worth if it lands.'}
</p>
{/if}
</div>
<div class="v2-field">
<label for="f-notes">Notes</label>
<textarea
id="f-notes"
name="description"
class="v2-input"
rows="4"
bind:value={form.description}></textarea>
</div>
<div class="actions">
<button class="v2-btn v2-btn-primary" type="submit" disabled={busy}>Create lead</button>
<a class="v2-btn" href="/leads">Cancel</a>
</div>
</form>
</div>
<style>
.actions {
display: flex;
align-items: center;
gap: 9px;
margin-top: 22px;
padding-bottom: 40px;
}
</style>

View file

@ -73,7 +73,7 @@
{
href: '/settings/api-tokens',
title: 'API tokens',
body: 'Personal access tokens for scripts, integrations and MCP clients.',
body: 'Personal access tokens for scripts, integrations and AI agents.',
value: data.tokenTotals ? `${data.tokenTotals.live} live` : null,
warn: data.tokenTotals
? data.tokenTotals.orphaned > 0 || data.tokenTotals.unused_90d > 0

View file

@ -1,6 +1,121 @@
import { getBusinessHours } from '$lib/server/v2/business-hours.js';
import { fail } from '@sveltejs/kit';
import {
getBusinessHours,
updateBusinessHours,
addHoliday as addHolidayWrite,
removeHoliday as removeHolidayWrite
} from '$lib/server/v2/business-hours.js';
import { readableError } from '$lib/server/v2/form-errors.js';
/** @type {import('./$types').PageServerLoad} */
export async function load({ cookies }) {
return getBusinessHours({ cookies });
}
/** Monday-first weekday label ↔ the form field prefix each row posts under.
* Kept in one place so the seven names are typed once here, not seven
* times across the read of a form submission. */
const WEEKDAYS = [
['Monday', 'monday'],
['Tuesday', 'tuesday'],
['Wednesday', 'wednesday'],
['Thursday', 'thursday'],
['Friday', 'friday'],
['Saturday', 'saturday'],
['Sunday', 'sunday']
];
/**
* Read the week back out of the form: one `open` and one `close` input per
* day plus a `closed` checkbox, all named by weekday prefix. A checked
* "closed" box wins outright and reports both fields null for that day,
* regardless of whatever the (disabled, and so never actually submitted by
* the browser) time inputs hold.
*
* @param {FormData} form
*/
function readDays(form) {
return WEEKDAYS.map(([label, key]) => {
const closed = form.get(`${key}_closed`) === 'true';
return {
day: label,
open: closed ? null : form.get(`${key}_open`)?.toString() || null,
close: closed ? null : form.get(`${key}_close`)?.toString() || null
};
});
}
/** The one 403 body all three admin-only writes share, turned into a sentence. */
const FORBIDDEN = 'Only admins can update business hours.';
/**
* All three actions below are admin-only, enforced server-side by
* `BusinessCalendarView.put` / `BusinessHolidayListView.post` /
* `BusinessHolidayDetailView.delete`, each re-deriving admin status from
* `request.profile`. `data.can_edit` in the page only hides the controls;
* it is a display hint, never the authorization decision.
*
* @type {import('./$types').Actions}
*/
export const actions = {
async updateHours(event) {
const form = await event.request.formData();
const days = readDays(form);
const meta = {
name: form.get('name')?.toString().trim() ?? '',
timezone: form.get('timezone')?.toString().trim() ?? ''
};
try {
// The calendar id never travels through the form: there is exactly
// one calendar per org, and this read is org-scoped server-side, so
// resolving it here rather than trusting a hidden field means there
// is nothing for a hand-crafted POST to redirect at another org's row.
const { calendar } = await getBusinessHours(event);
await updateBusinessHours(event, calendar.id, days, meta);
} catch (/** @type {any} */ err) {
if (err?.status === 403) {
return fail(403, { updateHours: { error: FORBIDDEN } });
}
return fail(400, {
updateHours: { error: readableError(err, 'Could not save business hours.') }
});
}
return { hoursUpdated: true };
},
async addHoliday(event) {
const form = await event.request.formData();
const date = form.get('date')?.toString() ?? '';
const name = form.get('name')?.toString().trim() ?? '';
try {
const { calendar } = await getBusinessHours(event);
await addHolidayWrite(event, calendar.id, { date, name });
} catch (/** @type {any} */ err) {
if (err?.status === 403) {
return fail(403, { addHoliday: { error: FORBIDDEN } });
}
return fail(400, { addHoliday: { error: readableError(err, 'Could not add the holiday.') } });
}
// Adding a date already on the calendar is idempotent (200, the existing
// row, no duplicate): not an error, so this path is the same "success"
// whether the row was created or already existed.
return { holidayAdded: true };
},
async removeHoliday(event) {
const form = await event.request.formData();
const holidayId = form.get('holiday_id')?.toString() ?? '';
try {
const { calendar } = await getBusinessHours(event);
await removeHolidayWrite(event, calendar.id, holidayId);
} catch (/** @type {any} */ err) {
if (err?.status === 403) {
return fail(403, { removeHoliday: { error: FORBIDDEN } });
}
return fail(400, {
removeHoliday: { error: readableError(err, 'Could not remove the holiday.') }
});
}
return { holidayRemoved: true };
}
};

View file

@ -10,14 +10,22 @@
*
* Closed days and holidays are shown, not omitted. A blank row for Saturday
* reads as missing data; "Closed" reads as a decision.
*
* "Edit hours" and "Add" open the two panels below. `data.can_edit` only
* decides whether those controls are offered: it is a display hint decoded
* from the JWT, never the authorization decision. The backend re-derives
* admin status from `request.profile` on every write and is what actually
* refuses a non-admin.
*/
import PageHeader from '$lib/v2/components/PageHeader.svelte';
import SettingsCrumb from '$lib/v2/components/SettingsCrumb.svelte';
import SettingsFormPanel from '$lib/v2/components/SettingsFormPanel.svelte';
import ConfirmAction from '$lib/v2/components/ConfirmAction.svelte';
import { shortDate, relativeDays } from '$lib/v2/format.js';
import { Plus, Clock } from '@lucide/svelte';
/** @type {{ data: any }} */
let { data } = $props();
/** @type {{ data: any, form: any }} */
let { data, form } = $props();
let calendar = $derived(data.calendar);
@ -31,6 +39,34 @@
let weekly = $derived(calendar.days.reduce((a, d) => a + hours(d), 0));
const todayName = new Intl.DateTimeFormat('en-GB', { weekday: 'long' }).format(new Date());
// `null` when the panel is closed. One panel for the week, so only one
// edit can be in flight at a time.
let editingHours = $state(false);
// The week being edited, seeded from `calendar.days` when the panel opens.
// A day's key is its own name lower-cased ("Monday" → "monday"), the same
// prefix the model's fourteen flat fields use, so no separate label map is
// needed here. `closed` drives both the checkbox and whether the two time
// inputs are disabled; a closed day still carries a sensible default time
// so re-opening it doesn't hand back a blank field.
let hourRows = $state(
/** @type {{ day: string, key: string, open: string, close: string, closed: boolean }[]} */ ([])
);
function openHoursEdit() {
hourRows = calendar.days.map((d) => ({
day: d.day,
key: d.day.toLowerCase(),
open: d.open ?? '09:00',
close: d.close ?? '17:00',
closed: !d.open
}));
editingHours = true;
}
// `null` when the panel is closed.
let addingHoliday = $state(false);
</script>
<PageHeader title="Business hours">
@ -40,7 +76,9 @@
<span class="v2-num">{weekly}</span> hours a week
{/snippet}
{#snippet actions()}
<button class="v2-btn v2-btn-primary">Edit hours</button>
{#if data.can_edit && !editingHours}
<button class="v2-btn v2-btn-primary" onclick={openHoursEdit}>Edit hours</button>
{/if}
{/snippet}
</PageHeader>
@ -49,6 +87,84 @@
<div class="v2-split">
<div>
<div class="v2-label" style="margin-bottom:10px">Open hours</div>
{#if editingHours}
<SettingsFormPanel
title="Edit business hours"
action="?/updateHours"
error={form?.updateHours?.error}
submitLabel="Save hours"
oncancel={() => (editingHours = false)}
ondone={() => (editingHours = false)}
>
{#snippet fields()}
<div class="v2-field">
<label for="bh-name">Name</label>
<input
id="bh-name"
class="v2-input"
name="name"
maxlength="100"
required
value={calendar.name}
/>
</div>
<div class="v2-field">
<label for="bh-timezone">Timezone</label>
<input
id="bh-timezone"
class="v2-input"
name="timezone"
maxlength="64"
required
value={calendar.timezone}
placeholder="America/New_York"
/>
<p class="v2-hint">IANA timezone name.</p>
</div>
<div class="v2-field v2-sfp-wide">
<label for="bh-day-0-open">Week</label>
{#each hourRows as row, i (row.key)}
<div style="display:flex;gap:10px;align-items:center;margin-bottom:8px">
<span style="width:84px;font-size:13px;flex:none">{row.day}</span>
<label
style="display:flex;gap:6px;align-items:center;font-size:12px;font-weight:400;flex:none"
>
<input
type="checkbox"
name="{row.key}_closed"
value="true"
bind:checked={row.closed}
/>
Closed
</label>
<input
id={i === 0 ? 'bh-day-0-open' : undefined}
class="v2-input"
type="time"
name="{row.key}_open"
bind:value={row.open}
disabled={row.closed}
style="width:auto"
/>
<span class="v2-sub">to</span>
<input
class="v2-input"
type="time"
name="{row.key}_close"
bind:value={row.close}
disabled={row.closed}
style="width:auto"
/>
</div>
{/each}
</div>
{/snippet}
</SettingsFormPanel>
{/if}
<div class="v2-card" style="overflow:hidden">
{#each calendar.days as d (d.day)}
<div class="v2-setting" style={d.day === todayName ? 'background:var(--v2-hover)' : ''}>
@ -79,8 +195,50 @@
<div>
<div style="display:flex;align-items:baseline;margin-bottom:10px">
<div class="v2-label">Holidays</div>
<button class="v2-btn v2-btn-sm" style="margin-left:auto"><Plus size={12} />Add</button>
{#if data.can_edit && !addingHoliday}
<button
class="v2-btn v2-btn-sm"
style="margin-left:auto"
onclick={() => (addingHoliday = true)}
>
<Plus size={12} />Add
</button>
{/if}
</div>
{#if addingHoliday}
<SettingsFormPanel
title="Add holiday"
action="?/addHoliday"
error={form?.addHoliday?.error}
submitLabel="Add holiday"
oncancel={() => (addingHoliday = false)}
ondone={() => (addingHoliday = false)}
>
{#snippet fields()}
<div class="v2-field">
<label for="bh-holiday-date">Date</label>
<input id="bh-holiday-date" class="v2-input" type="date" name="date" required />
</div>
<div class="v2-field">
<label for="bh-holiday-name">Name</label>
<input
id="bh-holiday-name"
class="v2-input"
name="name"
maxlength="100"
required
placeholder="Christmas"
/>
</div>
{/snippet}
</SettingsFormPanel>
{/if}
{#if form?.removeHoliday?.error}
<p class="v2-error" style="margin-bottom:12px">{form.removeHoliday.error}</p>
{/if}
<div class="v2-card" style="overflow:hidden">
{#each calendar.holidays as h (h.id)}
<div class="v2-setting">
@ -89,6 +247,15 @@
<span class="v2-sub" style="font-size:11.5px">{relativeDays(h.date)}</span>
</div>
<span class="v2-num" style="font-size:12.5px">{shortDate(h.date)}</span>
{#if data.can_edit}
<ConfirmAction
action="?/removeHoliday"
label="Remove"
confirmLabel="Remove"
explain="Deletes it. The day counts as working time again."
hidden={{ holiday_id: h.id }}
/>
{/if}
</div>
{:else}
<p class="v2-sub" style="padding:14px 16px;font-size:12.5px;margin:0">
@ -105,9 +272,16 @@
<div style="font-weight:600;font-size:13px">What this changes</div>
<p class="v2-sub" style="font-size:12px;margin:4px 0 0">
Response and resolution targets count only the time inside these hours. A ticket
opened at 17:20 on Friday starts its clock at
<span class="v2-num">{calendar.days[0].open}</span> on Monday, so the weekend does not spend
a four-hour target.
opened at 17:20 on Friday
{#if calendar.days[0].open}
starts its clock at <span class="v2-num">{calendar.days[0].open}</span> on Monday,
{:else}
<!-- Monday can be marked closed from this page now, so the
fixed "Monday morning" framing can no longer assume an
open time exists to quote. -->
starts its clock whenever the week next opens,
{/if}
so the weekend does not spend a four-hour target.
</p>
<p class="v2-sub" style="font-size:12px;margin:8px 0 0">
<a href="/tickets/analytics" style="color:inherit">Service analytics</a> is measured on

View file

@ -1,6 +1,119 @@
import { getCustomFields } from '$lib/server/v2/custom-fields.js';
import { fail } from '@sveltejs/kit';
import {
getCustomFields,
createCustomField,
updateCustomField,
deactivateCustomField
} from '$lib/server/v2/custom-fields.js';
import { readableError } from '$lib/server/v2/form-errors.js';
/** @type {import('./$types').PageServerLoad} */
export async function load({ cookies }) {
return getCustomFields({ cookies });
}
/**
* Read the repeated option rows back into `{ value, label }` pairs.
*
* The form renders one hidden `option_value` and one text `option_label` per
* row, so `getAll` returns two parallel arrays. A blank value marks a row the
* admin just added; `createCustomField` slugifies a value for it. A non-blank
* one is an existing option whose value is referenced by every record already
* holding it, and it travels back unchanged.
*
* @param {FormData} form
*/
function readOptions(form) {
const values = form.getAll('option_value').map((v) => v.toString());
const labels = form.getAll('option_label').map((v) => v.toString());
return labels.map((label, i) => ({ value: values[i] ?? '', label }));
}
/** @param {FormData} form */
function readValues(form) {
return {
target_model: form.get('target_model')?.toString() ?? '',
key: form.get('key')?.toString().trim() ?? '',
label: form.get('label')?.toString().trim() ?? '',
field_type: form.get('field_type')?.toString() ?? '',
is_required: form.get('is_required') === 'true',
is_filterable: form.get('is_filterable') === 'true',
display_order: form.get('display_order')?.toString() ?? '0',
options: readOptions(form)
};
}
/** @type {import('./$types').Actions} */
export const actions = {
// Admin-only server-side (`CustomFieldDefinitionListCreateView.post` calls
// `_is_admin` first). `can_edit` only hides the control.
async create(event) {
const form = await event.request.formData();
const values = readValues(form);
try {
await createCustomField(event, values);
} catch (/** @type {any} */ err) {
if (err?.status === 403) {
return fail(403, { create: { error: 'Only an admin can add custom fields.' } });
}
return fail(400, { create: { error: readableError(err, 'Could not add the field.') } });
}
return { created: true };
},
async update(event) {
const form = await event.request.formData();
const id = form.get('id')?.toString() ?? '';
const values = readValues(form);
try {
await updateCustomField(event, id, values);
} catch (/** @type {any} */ err) {
if (err?.status === 403) {
return fail(403, { update: { error: 'Only an admin can change custom fields.' } });
}
return fail(400, { update: { error: readableError(err, 'Could not save the field.') } });
}
return { updated: true };
},
async deactivate(event) {
const form = await event.request.formData();
const id = form.get('id')?.toString() ?? '';
try {
await deactivateCustomField(event, id);
} catch (/** @type {any} */ err) {
if (err?.status === 403) {
return fail(403, { deactivate: { error: 'Only an admin can turn custom fields off.' } });
}
return fail(400, {
deactivate: { error: readableError(err, 'Could not turn the field off.') }
});
}
return { deactivated: true };
},
// A field's own action, not a reuse of `update`. `readValues` builds a full
// field payload from the form, and this control only ever submits an id: if
// it posted through `update`, the missing `label` would read back as `''`
// (FormData has no key for it, `readValues` falls back to an empty string,
// not `undefined`) and `buildBody` would forward that empty string, since
// its allow-list only skips a field that is `undefined`. That would blank
// the label on every reactivation. Calling `updateCustomField` directly with
// only `{ is_active: true }` sidesteps `readValues` entirely, so the PUT
// body is `{ is_active: true }` and nothing else.
async activate(event) {
const form = await event.request.formData();
const id = form.get('id')?.toString() ?? '';
try {
await updateCustomField(event, id, { is_active: true });
} catch (/** @type {any} */ err) {
if (err?.status === 403) {
return fail(403, { activate: { error: 'Only an admin can turn custom fields on.' } });
}
return fail(400, {
activate: { error: readableError(err, 'Could not turn the field on.') }
});
}
return { activated: true };
}
};

View file

@ -12,16 +12,46 @@
* field with 23 records missing a value is a promise the data does not keep,
* and reporting on that field will quietly exclude or mis-bucket those 23.
*/
import { enhance } from '$app/forms';
import PageHeader from '$lib/v2/components/PageHeader.svelte';
import SettingsCrumb from '$lib/v2/components/SettingsCrumb.svelte';
import Pill from '$lib/v2/components/Pill.svelte';
import StatCard from '$lib/v2/components/StatCard.svelte';
import SettingsFormPanel from '$lib/v2/components/SettingsFormPanel.svelte';
import ConfirmAction from '$lib/v2/components/ConfirmAction.svelte';
import { count } from '$lib/v2/format.js';
import { FIELD_TYPE_LABEL, TARGET_MODEL_LABEL } from '$lib/v2/enums.js';
import { Plus, TriangleAlert, Filter } from '@lucide/svelte';
/** @type {{ data: any }} */
let { data } = $props();
/** @type {{ data: any, form: any }} */
let { data, form } = $props();
// `null` when the panel is closed, `'new'` when adding, or the field object
// when editing that row. One panel, two modes, so two rows can never be
// open for edit at once.
let editing = $state(/** @type {any} */ (null));
// The dropdown options being edited, as `{ value, label }` rows. Held here
// rather than read off `editing` so a row can be added or removed before
// submitting. A new row has an empty `value`; the server module slugifies
// one from the label, and never rewrites an existing value.
let optionRows = $state(/** @type {{ value: string, label: string }[]} */ ([]));
// The type currently selected in the form, so the options editor appears
// only for a dropdown. Seeded from the row being edited.
let fieldType = $state('text');
function openCreate() {
editing = 'new';
fieldType = 'text';
optionRows = [];
}
function openEdit(f) {
editing = f;
fieldType = f.field_type;
optionRows = (f.options ?? []).map((o) => ({ value: o.value, label: o.label }));
}
let totals = $derived(data.totals);
@ -49,7 +79,9 @@
<span class="v2-num">{count(totals.models_extended)}</span> record types
{/snippet}
{#snippet actions()}
<button class="v2-btn v2-btn-primary"><Plus />New field</button>
{#if data.can_edit && !editing}
<button class="v2-btn v2-btn-primary" onclick={openCreate}><Plus />New field</button>
{/if}
{/snippet}
</PageHeader>
@ -69,6 +101,178 @@
<div class="v2-scroll">
<div class="v2-pad" style="padding-bottom:32px">
{#if editing}
<SettingsFormPanel
title={editing === 'new' ? 'New custom field' : `Edit ${editing.label}`}
action={editing === 'new' ? '?/create' : '?/update'}
error={editing === 'new' ? form?.create?.error : form?.update?.error}
submitLabel={editing === 'new' ? 'Add field' : 'Save field'}
oncancel={() => (editing = null)}
ondone={() => (editing = null)}
>
{#snippet fields()}
{#if editing !== 'new'}
<input type="hidden" name="id" value={editing.id} />
{/if}
<div class="v2-field">
<label for="f-label">Label</label>
<input
id="f-label"
class="v2-input"
name="label"
maxlength="128"
required
value={editing === 'new' ? '' : editing.label}
/>
</div>
<div class="v2-field">
<label for="f-key">Key</label>
{#if editing === 'new'}
<input
id="f-key"
class="v2-input"
name="key"
maxlength="64"
pattern="[a-z][a-z0-9_]*"
required
placeholder="severity"
/>
<p class="v2-hint">
Lowercase letters, numbers and underscores, starting with a letter. No hyphens.
Cannot be changed later.
</p>
{:else}
<code class="v2-cf-key">{editing.key}</code>
<p class="v2-hint">
Fixed after creation. Every value already stored is filed under this key, and
changing it would leave them all behind.
</p>
{/if}
</div>
<div class="v2-field">
<label for="f-target">On record type</label>
{#if editing === 'new'}
<select id="f-target" class="v2-input" name="target_model" required>
{#each Object.entries(TARGET_MODEL_LABEL) as [value, label] (value)}
<option {value}>{label}</option>
{/each}
</select>
{:else}
<div style="font-size:13px">
{TARGET_MODEL_LABEL[editing.target_model] ?? editing.target_model}
</div>
<p class="v2-hint">Fixed after creation.</p>
{/if}
</div>
<div class="v2-field">
<label for="f-type">Type</label>
{#if editing === 'new'}
<select id="f-type" class="v2-input" name="field_type" bind:value={fieldType}>
{#each Object.entries(FIELD_TYPE_LABEL) as [value, label] (value)}
<option {value}>{label}</option>
{/each}
</select>
{:else}
<!-- No `<select>` here means nothing named `field_type` reaches
the form submit, but `fieldType` (below) still has to drive
whether the choices editor renders and, on submit, whether
`readValues`/`buildBody` attach `options` at all. This
hidden input carries the value through without offering it
as something to change; `UPDATE_FIELDS` drops `field_type`
from the outgoing body regardless of what this holds. -->
<input type="hidden" name="field_type" value={fieldType} />
<div style="font-size:13px">{FIELD_TYPE_LABEL[editing.field_type]}</div>
<p class="v2-hint">
Fixed after creation. Values already stored were written and checked against this
type.
</p>
{/if}
</div>
{#if fieldType === 'dropdown'}
<div class="v2-field v2-sfp-wide">
<label for="f-choices">Choices</label>
{#each optionRows as row, i (i)}
<div style="display:flex;gap:7px;align-items:center;margin-bottom:6px">
<input type="hidden" name="option_value" value={row.value} />
<input
id={i === 0 ? 'f-choices' : undefined}
class="v2-input"
name="option_label"
bind:value={row.label}
required
/>
<button
class="v2-btn v2-btn-sm"
type="button"
onclick={() => (optionRows = optionRows.filter((_, j) => j !== i))}
>
Remove
</button>
</div>
{/each}
<button
class="v2-btn v2-btn-sm"
type="button"
style="align-self:flex-start"
onclick={() => (optionRows = [...optionRows, { value: '', label: '' }])}
>
Add a choice
</button>
<p class="v2-hint">
Renaming a choice keeps the values already stored against it. Removing one leaves
the records that hold it showing a value the list no longer offers.
</p>
</div>
{/if}
<div class="v2-field">
<label for="f-order">Order</label>
<input
id="f-order"
class="v2-input"
type="number"
name="display_order"
min="0"
value={editing === 'new' ? 0 : editing.display_order}
/>
</div>
<div class="v2-field">
<label for="f-required">Required</label>
<label style="display:flex;gap:8px;align-items:center;font-weight:400">
<input
id="f-required"
type="checkbox"
name="is_required"
value="true"
checked={editing !== 'new' && editing.is_required}
/>
Binds new writes only. Records saved before this keep their gap.
</label>
</div>
<div class="v2-field">
<label for="f-filterable">Filterable</label>
<label style="display:flex;gap:8px;align-items:center;font-weight:400">
<input
id="f-filterable"
type="checkbox"
name="is_filterable"
value="true"
checked={editing !== 'new' && editing.is_filterable}
/>
Can be used to narrow a list, not just read on the record.
</label>
</div>
{/snippet}
</SettingsFormPanel>
{/if}
{#if gaps.length}
<div class="v2-cf-banner">
<TriangleAlert size={16} style="color:var(--v2-clay);flex:none;margin-top:1px" />
@ -89,6 +293,13 @@
</div>
{/if}
{#if form?.deactivate?.error}
<p class="v2-error" style="margin-bottom:12px">{form.deactivate.error}</p>
{/if}
{#if form?.activate?.error}
<p class="v2-error" style="margin-bottom:12px">{form.activate.error}</p>
{/if}
<div class="v2-cf-groups">
{#each groups as g (g.model)}
<div>
@ -124,6 +335,35 @@
{:else if f.is_required}
<Pill tone="clay">Required</Pill>
{/if}
{#if data.can_edit}
<div style="display:flex;gap:6px;align-items:center;flex:none">
<button class="v2-btn v2-btn-sm" type="button" onclick={() => openEdit(f)}>
Edit
</button>
{#if f.is_active}
<ConfirmAction
action="?/deactivate"
label="Turn off"
confirmLabel="Turn off"
explain="Stops being collected. Stored values stay."
hidden={{ id: f.id }}
/>
{:else}
<!-- Turning a field back on restores nothing that was
destroyed (the values never left), so unlike "Turn
off" this doesn't need the two-click confirm. A
plain enhanced form posting just the id keeps the
request to `{ is_active: true }`, see the `activate`
action's comment for why that has to be its own
action rather than a bare `update` submit. -->
<form method="POST" action="?/activate" use:enhance>
<input type="hidden" name="id" value={f.id} />
<button class="v2-btn v2-btn-sm" type="submit">Turn on</button>
</form>
{/if}
</div>
{/if}
</div>
{/each}
</div>

View file

@ -1,6 +1,146 @@
import { getEscalationPolicies } from '$lib/server/v2/escalation.js';
import { fail } from '@sveltejs/kit';
import {
getEscalationPolicies,
createEscalationPolicy,
updateEscalationPolicy,
deleteEscalationPolicy
} from '$lib/server/v2/escalation.js';
import { getOrgPeopleAndTeams } from '$lib/server/v2/org-people.js';
import { readableError } from '$lib/server/v2/form-errors.js';
// The policy list and the create/edit form's target picker are two
// independent fetches: `getEscalationPolicies` does not fold
// `getOrgPeopleAndTeams` into its own return, because `getSettingsHub` (the
// settings-hub aggregator) also calls `getEscalationPolicies` and only ever
// reads `.policies` off it. Folding the picker fetch in there would fire an
// extra, unused `/users/get-teams-and-users/` request on every settings-hub
// load. Fetched in parallel here instead, since this is the one place both
// are actually needed.
/** @type {import('./$types').PageServerLoad} */
export async function load({ cookies }) {
return getEscalationPolicies({ cookies });
const [data, options] = await Promise.all([
getEscalationPolicies({ cookies }),
getOrgPeopleAndTeams(cookies)
]);
return { ...data, ...options };
}
/**
* Everything both the create and edit form submit. `is_active` is
* deliberately not read here: only the create form carries that checkbox
* (the row's own Turn off / Turn on control owns that state on an existing
* policy), so reading `form.get('is_active')` here would answer `false` on
* every edit submit, since an absent checkbox and an unchecked one look
* identical to `FormData`. The `create` action below attaches `is_active`
* itself, straight from the one form that renders it.
*
* `priority` is read here too, but it only ever reaches the outgoing body on
* a create: `updateEscalationPolicy` filters through `UPDATE_FIELDS`, which
* excludes it, and the edit form never renders a `priority` input in the
* first place.
*
* @param {FormData} form
*/
function readValues(form) {
return {
priority: form.get('priority')?.toString() ?? '',
first_response_action: form.get('first_response_action')?.toString() ?? '',
resolution_action: form.get('resolution_action')?.toString() ?? '',
first_response_target_id: form.get('first_response_target_id')?.toString() ?? '',
resolution_target_id: form.get('resolution_target_id')?.toString() ?? '',
notify_team_id: form.get('notify_team_id')?.toString() ?? ''
};
}
/** @type {import('./$types').Actions} */
export const actions = {
// Admin-only server-side (`EscalationPolicyListCreateView.post` and
// `EscalationPolicyDetailView.put`/`.delete` each call `_is_admin` first).
// `can_edit` only hides the control.
async create(event) {
const form = await event.request.formData();
const values = { ...readValues(form), is_active: form.get('is_active') === 'true' };
try {
await createEscalationPolicy(event, values);
} catch (/** @type {any} */ err) {
if (err?.status === 403) {
return fail(403, { create: { error: 'Only an admin can change escalation policies.' } });
}
return fail(400, { create: { error: readableError(err, 'Could not add the policy.') } });
}
return { created: true };
},
async update(event) {
const form = await event.request.formData();
const id = form.get('id')?.toString() ?? '';
const values = readValues(form);
try {
await updateEscalationPolicy(event, id, values);
} catch (/** @type {any} */ err) {
if (err?.status === 403) {
return fail(403, { update: { error: 'Only an admin can change escalation policies.' } });
}
return fail(400, { update: { error: readableError(err, 'Could not save the policy.') } });
}
return { updated: true };
},
async deactivate(event) {
const form = await event.request.formData();
const id = form.get('id')?.toString() ?? '';
try {
await updateEscalationPolicy(event, id, { is_active: false });
} catch (/** @type {any} */ err) {
if (err?.status === 403) {
return fail(403, {
deactivate: { error: 'Only an admin can change escalation policies.' }
});
}
return fail(400, {
deactivate: { error: readableError(err, 'Could not turn the policy off.') }
});
}
return { deactivated: true };
},
// A policy's own action, not a reuse of `update`. `readValues` builds a
// full policy payload from the form, and this control only ever submits an
// id: if it posted through `update`, every other field would read back
// empty (`FormData` has no key for it) and `buildBody` would forward that,
// blanking the policy on every reactivation. Calling `updateEscalationPolicy`
// directly with only `{ is_active: true }` sidesteps `readValues` entirely,
// so the PUT body is `{ is_active: true }` and nothing else.
async activate(event) {
const form = await event.request.formData();
const id = form.get('id')?.toString() ?? '';
try {
await updateEscalationPolicy(event, id, { is_active: true });
} catch (/** @type {any} */ err) {
if (err?.status === 403) {
return fail(403, { activate: { error: 'Only an admin can change escalation policies.' } });
}
return fail(400, {
activate: { error: readableError(err, 'Could not turn the policy on.') }
});
}
return { activated: true };
},
// `EscalationPolicyDetailView.delete` is a hard delete. The row control
// that posts here says so before it does, and names what happens next: the
// priority it covered escalates to nobody.
async remove(event) {
const form = await event.request.formData();
const id = form.get('id')?.toString() ?? '';
try {
await deleteEscalationPolicy(event, id);
} catch (/** @type {any} */ err) {
if (err?.status === 403) {
return fail(403, { remove: { error: 'Only an admin can change escalation policies.' } });
}
return fail(400, { remove: { error: readableError(err, 'Could not delete the policy.') } });
}
return { removed: true };
}
};

View file

@ -3,9 +3,9 @@
* What happens when a ticket blows its target.
*
* One EscalationPolicy per priority, enforced by a unique constraint. The
* useful question is not "is there a policy", there always is, but "does
* it do anything", and the model allows three separate ways for the answer
* to be no:
* useful question is not "is there a policy", there always is at most one
* per priority, but "does it do anything", and the model allows three
* separate ways for the answer to be no:
*
* · the action is `reassign` but the target FK is null (SET_NULL empties
* it when a profile is removed, silently)
@ -15,28 +15,50 @@
* All three look identical in v1's form, a row of selects with something
* chosen. Here the breach count sits next to the outcome, so "11 breaches,
* nobody told" is one line rather than two screens.
*
* Only four priorities exist and each may have at most one policy
* (`(org, priority)` unique constraint, enforced again by
* `EscalationPolicySerializer.validate()` on create). So "New policy"
* offers only the priorities with no policy yet, and disappears once all
* four are configured: a disabled button with no explanation is the dead
* end this phase exists to remove, not a control worth keeping around.
*
* `priority` never appears on the edit form. `EscalationPolicyDetailView.put`
* strips the key from the request body before the serializer sees it, so an
* edit that offered it would report success and change nothing.
*/
import { enhance } from '$app/forms';
import PageHeader from '$lib/v2/components/PageHeader.svelte';
import SettingsCrumb from '$lib/v2/components/SettingsCrumb.svelte';
import EmptyState from '$lib/v2/components/EmptyState.svelte';
import Pill from '$lib/v2/components/Pill.svelte';
import SettingsFormPanel from '$lib/v2/components/SettingsFormPanel.svelte';
import ConfirmAction from '$lib/v2/components/ConfirmAction.svelte';
import { count } from '$lib/v2/format.js';
import { ESCALATION_ACTION_LABEL, PRIORITY_TONE } from '$lib/v2/enums.js';
import { TriangleAlert, BellOff } from '@lucide/svelte';
import { ESCALATION_ACTION_LABEL, ESCALATION_PRIORITIES, PRIORITY_TONE } from '$lib/v2/enums.js';
import { missingOption, inactiveOptionLabel } from '$lib/v2/pickers.js';
import { TriangleAlert, BellOff, Plus } from '@lucide/svelte';
/** @type {{ data: any }} */
let { data } = $props();
/** @type {{ data: any, form: any }} */
let { data, form } = $props();
/**
* By severity, not by the model's `ordering = ("priority",)`. That sorts
* the CharField alphabetically and puts Low between High and Normal, which
* reads as a mistake every single time.
*/
const SEVERITY = ['Urgent', 'High', 'Normal', 'Low'];
let policies = $derived(
[...data.policies].sort((a, b) => SEVERITY.indexOf(a.priority) - SEVERITY.indexOf(b.priority))
[...data.policies].sort(
(a, b) => ESCALATION_PRIORITIES.indexOf(a.priority) - ESCALATION_PRIORITIES.indexOf(b.priority)
)
);
/** The priorities with no policy yet: what "New policy" is allowed to offer. */
let availablePriorities = $derived(
ESCALATION_PRIORITIES.filter((p) => !data.policies.some((x) => x.priority === p))
);
let allConfigured = $derived(availablePriorities.length === 0);
/**
* What one half of a policy actually does, and whether that is nothing.
* @returns {{ text: string, dead: boolean }}
@ -71,17 +93,230 @@
0
)
);
// `null` when the panel is closed, `'new'` when adding, or the policy
// object when editing that row. One panel, two modes, so two rows can
// never be open for edit at once.
let editing = $state(/** @type {any} */ (null));
// Mirrors of the four action/target fields, so the "reassigns to nobody"
// hint can react to what is currently picked in the form, before the
// policy is saved, rather than only ever telling the admin from the card
// afterward. `notify_team_id` needs no such mirror: there is no live
// warning tied to it.
let firstResponseAction = $state('notify');
let resolutionAction = $state('notify');
let firstResponseTarget = $state('');
let resolutionTarget = $state('');
function openCreate() {
editing = 'new';
firstResponseAction = 'notify';
resolutionAction = 'notify';
firstResponseTarget = '';
resolutionTarget = '';
}
function openEdit(p) {
editing = p;
firstResponseAction = p.first_response_action;
resolutionAction = p.resolution_action;
firstResponseTarget = p.first_response_target?.id ?? '';
resolutionTarget = p.resolution_target?.id ?? '';
}
/**
* A stored target the picker cannot offer.
*
* `getOrgPeopleAndTeams` only ever returns active profiles, while
* `EscalationPolicy.first_response_target` / `resolution_target` carry
* whoever was chosen, deactivated or not, and `cases/tasks.py` escalates to
* them with no active filter. A select with no matching option submits
* nothing, `readValues` reads that absence as `''`, and `buildBody` turns
* `''` into `null`. So without an option of its own, opening this form to
* change one unrelated field would stop Urgent breaches escalating to
* anybody. It would also hide the "reassigns to nobody" warning at the
* moment it became true, because the binding keeps the stale id when the
* browser deselects.
*/
let missingFirstTarget = $derived(
editing && editing !== 'new' ? missingOption(data.people, editing.first_response_target) : null
);
let missingResolutionTarget = $derived(
editing && editing !== 'new' ? missingOption(data.people, editing.resolution_target) : null
);
</script>
<PageHeader title="Escalation">
{#snippet crumb()}<SettingsCrumb />{/snippet}
{#snippet sub()}
One policy per priority · <span class="v2-num">{count(policies.length)}</span> configured
{#if allConfigured}
One policy per priority · all four are configured
{:else}
One policy per priority · <span class="v2-num">{count(policies.length)}</span> configured
{/if}
{/snippet}
{#snippet actions()}
{#if data.can_edit && !editing && availablePriorities.length > 0}
<button class="v2-btn v2-btn-primary" onclick={openCreate}><Plus />New policy</button>
{/if}
{/snippet}
</PageHeader>
<div class="v2-scroll">
<div class="v2-pad" style="padding-top:18px;padding-bottom:32px">
{#if editing}
<SettingsFormPanel
title={editing === 'new' ? 'New policy' : `Edit ${editing.priority} policy`}
action={editing === 'new' ? '?/create' : '?/update'}
error={editing === 'new' ? form?.create?.error : form?.update?.error}
submitLabel={editing === 'new' ? 'Add policy' : 'Save policy'}
oncancel={() => (editing = null)}
ondone={() => (editing = null)}
>
{#snippet fields()}
{#if editing !== 'new'}
<input type="hidden" name="id" value={editing.id} />
{/if}
<div class="v2-field">
<label for="e-priority">Priority</label>
{#if editing === 'new'}
<select id="e-priority" class="v2-input" name="priority" required>
{#each availablePriorities as p (p)}
<option value={p}>{p}</option>
{/each}
</select>
{:else}
<div style="font-size:13px">{editing.priority}</div>
<p class="v2-hint">Fixed after creation. One policy per priority.</p>
{/if}
</div>
<div class="v2-field">
<label for="e-fr-action">First response action</label>
<select
id="e-fr-action"
class="v2-input"
name="first_response_action"
bind:value={firstResponseAction}
>
{#each Object.entries(ESCALATION_ACTION_LABEL) as [value, label] (value)}
<option {value}>{label}</option>
{/each}
</select>
{#if firstResponseAction === 'reassign' && !firstResponseTarget}
<p class="v2-hint">Reassigns to nobody until a target is picked below.</p>
{/if}
</div>
<div class="v2-field">
<label for="e-fr-target">First response target</label>
<select
id="e-fr-target"
class="v2-input"
name="first_response_target_id"
bind:value={firstResponseTarget}
>
<option value="">Nobody</option>
{#if missingFirstTarget}
<option value={missingFirstTarget.id}>
{inactiveOptionLabel(missingFirstTarget.name)}
</option>
{/if}
{#each data.people as p (p.id)}
<option value={p.id}>{p.name}</option>
{/each}
</select>
{#if missingFirstTarget}
<p class="v2-hint">
This target's account is no longer active. It stays set until you change it, and a
breach reassigned there waits for someone who cannot sign in.
</p>
{/if}
</div>
<div class="v2-field">
<label for="e-res-action">Resolution action</label>
<select
id="e-res-action"
class="v2-input"
name="resolution_action"
bind:value={resolutionAction}
>
{#each Object.entries(ESCALATION_ACTION_LABEL) as [value, label] (value)}
<option {value}>{label}</option>
{/each}
</select>
{#if resolutionAction === 'reassign' && !resolutionTarget}
<p class="v2-hint">Reassigns to nobody until a target is picked below.</p>
{/if}
</div>
<div class="v2-field">
<label for="e-res-target">Resolution target</label>
<select
id="e-res-target"
class="v2-input"
name="resolution_target_id"
bind:value={resolutionTarget}
>
<option value="">Nobody</option>
{#if missingResolutionTarget}
<option value={missingResolutionTarget.id}>
{inactiveOptionLabel(missingResolutionTarget.name)}
</option>
{/if}
{#each data.people as p (p.id)}
<option value={p.id}>{p.name}</option>
{/each}
</select>
{#if missingResolutionTarget}
<p class="v2-hint">
This target's account is no longer active. It stays set until you change it, and a
breach reassigned there waits for someone who cannot sign in.
</p>
{/if}
</div>
<div class="v2-field">
<label for="e-team">Notify team</label>
<select id="e-team" class="v2-input" name="notify_team_id">
<option value="" selected={editing === 'new' || !editing.notify_team}>No team</option>
{#each data.teams as t (t.id)}
<option value={t.id} selected={editing !== 'new' && editing.notify_team?.id === t.id}>
{t.name}
</option>
{/each}
</select>
{#if !data.teams.length}
<p class="v2-hint">No teams in this org yet.</p>
{/if}
</div>
{#if editing === 'new'}
<div class="v2-field">
<label for="e-active">Active</label>
<label style="display:flex;gap:8px;align-items:center;font-weight:400">
<input id="e-active" type="checkbox" name="is_active" value="true" checked />
Starts escalating breaches at this priority as soon as it is saved.
</label>
</div>
{/if}
{/snippet}
</SettingsFormPanel>
{/if}
{#if form?.deactivate?.error}
<p class="v2-error" style="margin-bottom:12px">{form.deactivate.error}</p>
{/if}
{#if form?.activate?.error}
<p class="v2-error" style="margin-bottom:12px">{form.activate.error}</p>
{/if}
{#if form?.remove?.error}
<p class="v2-error" style="margin-bottom:12px">{form.remove.error}</p>
{/if}
{#if policies.length === 0}
<!-- No policy for any priority. Without this the page falls to a header
over a blank column, the each-block renders nothing and the trailing
@ -120,9 +355,42 @@
{@const first = outcome(p, 'first_response')}
{@const res = outcome(p, 'resolution')}
<div class="v2-card" style="padding:15px 16px;opacity:{p.is_active ? 1 : 0.62}">
<div style="display:flex;gap:9px;align-items:center;margin-bottom:12px">
<Pill tone={PRIORITY_TONE[p.priority]}>{p.priority}</Pill>
{#if !p.is_active}<Pill tone="slate">Off</Pill>{/if}
<div
style="display:flex;gap:9px;align-items:center;margin-bottom:12px;justify-content:space-between"
>
<div style="display:flex;gap:9px;align-items:center">
<Pill tone={PRIORITY_TONE[p.priority]}>{p.priority}</Pill>
{#if !p.is_active}<Pill tone="slate">Off</Pill>{/if}
</div>
{#if data.can_edit}
<div style="display:flex;gap:6px;align-items:center;flex:none">
<button class="v2-btn v2-btn-sm" type="button" onclick={() => openEdit(p)}>
Edit
</button>
{#if p.is_active}
<ConfirmAction
action="?/deactivate"
label="Turn off"
confirmLabel="Turn off"
explain="Stops escalating breaches at this priority. It stays in the list, off, until turned back on."
hidden={{ id: p.id }}
/>
{:else}
<form method="POST" action="?/activate" use:enhance>
<input type="hidden" name="id" value={p.id} />
<button class="v2-btn v2-btn-sm" type="submit">Turn on</button>
</form>
{/if}
<ConfirmAction
action="?/remove"
label="Delete"
confirmLabel="Delete"
explain="Deleted permanently. Breaches at this priority will escalate to nobody."
hidden={{ id: p.id }}
/>
</div>
{/if}
</div>
<div class="v2-escalation-halves">
@ -188,7 +456,6 @@
@media (max-width: 768px) {
.v2-escalation-halves {
grid-template-columns: 1fr;
gap: 14px;
}
.v2-escalation-half + .v2-escalation-half {
border-left: 0;

View file

@ -1,6 +1,142 @@
import { getMailboxes } from '$lib/server/v2/inbound-email.js';
import { fail } from '@sveltejs/kit';
import {
getMailboxes,
createMailbox,
updateMailbox,
deleteMailbox
} from '$lib/server/v2/inbound-email.js';
import { getOrgPeopleAndTeams } from '$lib/server/v2/org-people.js';
import { readableError } from '$lib/server/v2/form-errors.js';
// The mailbox list and the create/edit form's assignee picker are two
// independent fetches: `getMailboxes` does not fold `getOrgPeopleAndTeams`
// into its own return, because `getSettingsHub` (the settings-hub aggregator)
// also calls `getMailboxes` and only ever reads `.totals` off it. Folding the
// picker fetch in there would fire an extra, unused
// `/users/get-teams-and-users/` request on every settings-hub load. Fetched
// in parallel here instead, since this is the one place both are actually
// needed. This resource has no team FK, so only `.people` is read below, but
// `getOrgPeopleAndTeams` returns both and spreading both is harmless.
/** @type {import('./$types').PageServerLoad} */
export async function load({ cookies }) {
return getMailboxes({ cookies });
const [data, options] = await Promise.all([
getMailboxes({ cookies }),
getOrgPeopleAndTeams(cookies)
]);
return { ...data, ...options };
}
/**
* Everything both the create and edit form submit. There is no signing-secret
* key read here: no field on either form carries one, and reading one would be
* the first step toward sending it. `is_active` is likewise deliberately not
* read here: only the create form carries that checkbox (the edit form's own
* row control, Turn off / Turn on, owns that state), so reading
* `form.get('is_active')` here would answer `false` on every edit submit,
* since an absent checkbox and an unchecked one look identical to `FormData`.
* The `create` action below attaches `is_active` itself, straight from the
* one form that renders it.
*
* @param {FormData} form
*/
function readValues(form) {
return {
address: form.get('address')?.toString().trim() ?? '',
provider: form.get('provider')?.toString() ?? '',
default_priority: form.get('default_priority')?.toString() ?? '',
default_case_type: form.get('default_case_type')?.toString() ?? '',
default_assignee_id: form.get('default_assignee_id')?.toString() ?? ''
};
}
/** @type {import('./$types').Actions} */
export const actions = {
// Admin-only server-side (`InboundMailboxListCreateView.post` calls
// `_is_admin` first). `can_edit` only hides the control.
async create(event) {
const form = await event.request.formData();
const values = { ...readValues(form), is_active: form.get('is_active') === 'true' };
try {
await createMailbox(event, values);
} catch (/** @type {any} */ err) {
if (err?.status === 403) {
return fail(403, { create: { error: 'Only an admin can change inbound mailboxes.' } });
}
return fail(400, { create: { error: readableError(err, 'Could not add the address.') } });
}
return { created: true };
},
async update(event) {
const form = await event.request.formData();
const id = form.get('id')?.toString() ?? '';
const values = readValues(form);
try {
await updateMailbox(event, id, values);
} catch (/** @type {any} */ err) {
if (err?.status === 403) {
return fail(403, { update: { error: 'Only an admin can change inbound mailboxes.' } });
}
return fail(400, { update: { error: readableError(err, 'Could not save the address.') } });
}
return { updated: true };
},
async deactivate(event) {
const form = await event.request.formData();
const id = form.get('id')?.toString() ?? '';
try {
await updateMailbox(event, id, { is_active: false });
} catch (/** @type {any} */ err) {
if (err?.status === 403) {
return fail(403, { deactivate: { error: 'Only an admin can change inbound mailboxes.' } });
}
return fail(400, {
deactivate: { error: readableError(err, 'Could not turn the address off.') }
});
}
return { deactivated: true };
},
// A row's own action, not a reuse of `update`. `readValues` builds a full
// mailbox payload from the form, and this control only ever submits an id:
// if it posted through `update`, `address` would read back as `''`
// (`FormData` has no key for it) and `createMailbox`/`updateMailbox`'s own
// `buildBody` would forward that, and `validate_address` would reject the
// empty string on its way to blanking the address. Calling `updateMailbox`
// directly with only `{ is_active: true }` sidesteps `readValues` entirely,
// so the PUT body is `{ is_active: true }` and nothing else.
async activate(event) {
const form = await event.request.formData();
const id = form.get('id')?.toString() ?? '';
try {
await updateMailbox(event, id, { is_active: true });
} catch (/** @type {any} */ err) {
if (err?.status === 403) {
return fail(403, { activate: { error: 'Only an admin can change inbound mailboxes.' } });
}
return fail(400, {
activate: { error: readableError(err, 'Could not turn the address on.') }
});
}
return { activated: true };
},
// `InboundMailboxDetailView.delete` is a hard delete. It also destroys the
// row's signing secret, so any delivery already signed against it stops
// verifying, not just stops opening tickets. The row control that posts
// here says so before it does.
async remove(event) {
const form = await event.request.formData();
const id = form.get('id')?.toString() ?? '';
try {
await deleteMailbox(event, id);
} catch (/** @type {any} */ err) {
if (err?.status === 403) {
return fail(403, { remove: { error: 'Only an admin can change inbound mailboxes.' } });
}
return fail(400, { remove: { error: readableError(err, 'Could not delete the address.') } });
}
return { removed: true };
}
};

View file

@ -4,30 +4,70 @@
*
* Two things this page is careful about:
*
* 1. NO SECRETS. InboundMailbox carries `webhook_secret` and
* `imap_password_enc`. The webhook secret is what proves a delivery
* really came from the provider. Anything holding it can forge tickets
* into this org, or read the ones it forges. It is not fetched, not
* rendered, and not masked-but-present in the DOM. Rotation belongs
* behind an explicit action, not on a page you can arrive at by browsing.
* 1. NO SECRETS. InboundMailbox carries a per-address signing secret and a
* provider topic id. The signing secret is what proves a delivery really
* came from the provider. Anything holding it can forge tickets into this
* org, or read the ones it forges. It is not fetched, not rendered, and
* not masked-but-present in the DOM, on this page or on the create/edit
* form below: there is no field for it, not even a disabled one, because
* the server always generates a stronger secret than a pasted one and an
* empty field posted on an edit would blank the org's live credential.
* Rotation and a one-time reveal on create are a deliberate, separate
* feature, not built here; see the card at the foot of the page.
* 2. An inactive mailbox does not bounce. The address keeps accepting mail
* and the webhook stops creating cases, so the sender gets silence rather
* than a delivery failure. That is a materially different thing from
* "off", and a grey pill saying "Off" does not say it.
*/
import { enhance } from '$app/forms';
import PageHeader from '$lib/v2/components/PageHeader.svelte';
import SettingsCrumb from '$lib/v2/components/SettingsCrumb.svelte';
import Pill from '$lib/v2/components/Pill.svelte';
import SettingsFormPanel from '$lib/v2/components/SettingsFormPanel.svelte';
import ConfirmAction from '$lib/v2/components/ConfirmAction.svelte';
import { count, relativeDays } from '$lib/v2/format.js';
import { MAILBOX_PROVIDER_LABEL, PRIORITY_TONE } from '$lib/v2/enums.js';
import { missingOption, inactiveOptionLabel } from '$lib/v2/pickers.js';
import { Plus, MailWarning, KeyRound } from '@lucide/svelte';
/** @type {{ data: any }} */
let { data } = $props();
/** @type {{ data: any, form: any }} */
let { data, form } = $props();
// cases.InboundMailbox.PROVIDER_CHOICES is MAILBOX_PROVIDER_LABEL's key
// order. PRIORITY_CHOICE and CASE_TYPE mirror ticket-approvals' own local
// copies: value and label are the same string for both, and no shared map
// exists to derive them from.
const PROVIDERS = ['ses', 'mailgun', 'postmark', 'imap'];
const PRIORITIES = ['Low', 'Normal', 'High', 'Urgent'];
const CASE_TYPES = ['Question', 'Incident', 'Problem'];
let totals = $derived(data.totals);
let mailboxes = $derived(data.mailboxes);
let silent = $derived(mailboxes.filter((m) => !m.is_active));
// `null` when the panel is closed, `'new'` when adding, or the mailbox
// object when editing that row. One panel, two modes, so two rows can
// never be open for edit at once.
let editing = $state(/** @type {any} */ (null));
function openCreate() {
editing = 'new';
}
function openEdit(m) {
editing = m;
}
// The stored default assignee when the picker cannot offer it, because the
// profile has been deactivated since it was chosen. `getOrgPeopleAndTeams`
// returns active profiles only, `InboundMailbox.default_assignee` keeps
// whoever was set. A select with no matching option submits nothing, which
// `readValues` reads as `''` and `buildBody` sends as `null`, so an edit
// made to change the address or the provider would also quietly move this
// mailbox back to Unassigned.
let missingAssignee = $derived(
editing && editing !== 'new' ? missingOption(data.people, editing.default_assignee) : null
);
</script>
<PageHeader title="Inbound email">
@ -38,12 +78,136 @@
<span class="v2-num">{count(totals.cases_last_30d)}</span> in the last 30 days
{/snippet}
{#snippet actions()}
<button class="v2-btn v2-btn-primary"><Plus />Add address</button>
{#if data.can_edit && !editing}
<button class="v2-btn v2-btn-primary" onclick={openCreate}><Plus />Add address</button>
{/if}
{/snippet}
</PageHeader>
<div class="v2-scroll">
<div class="v2-pad" style="padding-top:18px;padding-bottom:32px">
{#if editing}
<SettingsFormPanel
title={editing === 'new' ? 'New address' : `Edit ${editing.address}`}
action={editing === 'new' ? '?/create' : '?/update'}
error={editing === 'new' ? form?.create?.error : form?.update?.error}
submitLabel={editing === 'new' ? 'Add address' : 'Save address'}
oncancel={() => (editing = null)}
ondone={() => (editing = null)}
>
{#snippet fields()}
{#if editing !== 'new'}
<input type="hidden" name="id" value={editing.id} />
{/if}
<div class="v2-field">
<label for="m-address">Address</label>
<input
id="m-address"
class="v2-input"
type="email"
name="address"
required
value={editing === 'new' ? '' : editing.address}
/>
{#if editing !== 'new'}
<p class="v2-hint">Mail to the old address stops becoming tickets.</p>
{/if}
</div>
<div class="v2-field">
<label for="m-provider">Provider</label>
<select id="m-provider" class="v2-input" name="provider">
{#each PROVIDERS as p (p)}
<option value={p} selected={editing === 'new' ? p === 'ses' : editing.provider === p}>
{MAILBOX_PROVIDER_LABEL[p]}
</option>
{/each}
</select>
<p class="v2-hint">
The signing secret is generated by the server and is not shown here.
</p>
</div>
<div class="v2-field">
<label for="m-priority">Opens as priority</label>
<select id="m-priority" class="v2-input" name="default_priority">
{#each PRIORITIES as p (p)}
<option
value={p}
selected={editing === 'new' ? p === 'Normal' : editing.default_priority === p}
>
{p}
</option>
{/each}
</select>
</div>
<div class="v2-field">
<label for="m-type">Opens as type</label>
<select id="m-type" class="v2-input" name="default_case_type">
<option value="" selected={editing === 'new' || !editing.default_case_type}>
None
</option>
{#each CASE_TYPES as t (t)}
<option value={t} selected={editing !== 'new' && editing.default_case_type === t}>
{t}
</option>
{/each}
</select>
</div>
<div class="v2-field">
<label for="m-assignee">Default assignee</label>
<select id="m-assignee" class="v2-input" name="default_assignee_id">
<option value="" selected={editing === 'new' || !editing.default_assignee}>
Unassigned
</option>
{#if missingAssignee}
<option value={missingAssignee.id} selected>
{inactiveOptionLabel(missingAssignee.name)}
</option>
{/if}
{#each data.people as p (p.id)}
<option
value={p.id}
selected={editing !== 'new' && editing.default_assignee?.id === p.id}
>
{p.name}
</option>
{/each}
</select>
{#if missingAssignee}
<p class="v2-hint">
This assignee's account is no longer active. It stays set until you change it, so
new tickets from this address land on someone who cannot sign in.
</p>
{/if}
</div>
{#if editing === 'new'}
<div class="v2-field">
<label for="m-active">Active</label>
<label style="display:flex;gap:8px;align-items:center;font-weight:400">
<input id="m-active" type="checkbox" name="is_active" value="true" checked />
Starts creating tickets from mail to this address as soon as it is saved.
</label>
</div>
{/if}
{/snippet}
</SettingsFormPanel>
{/if}
{#if form?.deactivate?.error}
<p class="v2-error" style="margin-bottom:12px">{form.deactivate.error}</p>
{/if}
{#if form?.activate?.error}
<p class="v2-error" style="margin-bottom:12px">{form.activate.error}</p>
{/if}
{#if form?.remove?.error}
<p class="v2-error" style="margin-bottom:12px">{form.remove.error}</p>
{/if}
{#if silent.length}
<div class="v2-mbx-banner">
<MailWarning size={17} style="color:var(--v2-clay);flex:none;margin-top:1px" />
@ -98,7 +262,34 @@
</div>
</div>
<button class="v2-btn v2-btn-sm" style="flex:none">Edit</button>
{#if data.can_edit}
<div style="display:flex;gap:6px;align-items:center;flex:none">
<button class="v2-btn v2-btn-sm" type="button" onclick={() => openEdit(m)}>
Edit
</button>
{#if m.is_active}
<ConfirmAction
action="?/deactivate"
label="Turn off"
confirmLabel="Turn off"
explain="Stops opening tickets from this address. It stays in the list, off, until turned back on."
hidden={{ id: m.id }}
/>
{:else}
<form method="POST" action="?/activate" use:enhance>
<input type="hidden" name="id" value={m.id} />
<button class="v2-btn v2-btn-sm" type="submit">Turn on</button>
</form>
{/if}
<ConfirmAction
action="?/remove"
label="Delete"
confirmLabel="Delete"
explain="Deleted permanently. Mail to this address stops becoming tickets, and the signing secret is destroyed."
hidden={{ id: m.id }}
/>
</div>
{/if}
</div>
{/each}
</div>
@ -106,8 +297,9 @@
<!--
The webhook secret is the credential that authenticates deliveries from
the provider. It is not on this page in any form, not shown, not
masked, not sitting in the payload behind a click-to-reveal. See api.js
for the same rule stated at the boundary.
masked, not sitting in the payload behind a click-to-reveal, and there
is no field for it on the form above either. See api.js for the same
rule stated at the boundary.
-->
<div class="v2-card" style="padding:15px 16px;margin-top:20px">
<div style="display:flex;gap:10px;align-items:flex-start">
@ -117,8 +309,8 @@
<p class="v2-sub" style="font-size:12.5px;margin:5px 0 0;line-height:1.5">
Each address has a shared secret that proves a delivery really came from the provider.
Anything holding it can post mail into this organisation as though a customer sent it,
so it is never rendered on a page. Rotating one is an explicit action that shows the
new value once.
so it is never rendered on a page. The server generates it when an address is added and
it is not editable here; rotating one is a separate action this page does not offer yet.
</p>
</div>
</div>

View file

@ -1,6 +1,126 @@
import { getMacros } from '$lib/server/v2/macros.js';
import { fail } from '@sveltejs/kit';
import {
getMacros,
createMacro,
updateMacro,
deleteMacro,
activateMacro
} from '$lib/server/v2/macros.js';
import { readableError } from '$lib/server/v2/form-errors.js';
/** @type {import('./$types').PageServerLoad} */
export async function load({ cookies }) {
return getMacros({ cookies });
}
// `is_active` is deliberately not read here: the create/edit form has no
// control for it (see the page's `fields` snippet), so a macro write from
// this form never carries it. That closes the gap "Turn off"'s two-click
// `ConfirmAction` used to have a sibling: unchecking a box in the edit panel
// and hitting Save used to flip `is_active` with no confirm and none of the
// consequence copy the dedicated action carries. Turning a macro back on now
// only happens through the `activate` action below, which sends nothing but
// the id and `is_active: true`.
/** @param {FormData} form */
function readValues(form) {
return {
title: form.get('title')?.toString() ?? '',
body: form.get('body')?.toString() ?? '',
scope: form.get('scope')?.toString() ?? ''
};
}
/** @type {import('./$types').Actions} */
export const actions = {
// Every signed-in member may create their own personal macro here.
// `can_create_org` only decides whether the form offers `scope=org` at
// all; `_resolve_scope_and_owner` re-derives admin status server-side and
// is what actually turns a non-admin's org-scope attempt into 403.
async create(event) {
const form = await event.request.formData();
const values = readValues(form);
try {
await createMacro(event, values);
} catch (/** @type {any} */ err) {
if (err?.status === 403) {
return fail(403, {
create: { error: 'Only an admin can create a macro shared with everyone.' }
});
}
return fail(400, { create: { error: readableError(err, 'Could not add the macro.') } });
}
return { created: true };
},
async update(event) {
const form = await event.request.formData();
const id = form.get('id')?.toString() ?? '';
const values = readValues(form);
try {
await updateMacro(event, id, values);
} catch (/** @type {any} */ err) {
if (err?.status === 403) {
return fail(403, {
update: { error: 'Only an admin can change a macro shared with everyone.' }
});
}
if (err?.status === 404) {
// A personal macro belonging to someone else answers 404 on purpose:
// a 403 would confirm the row exists. Say the same thing back.
return fail(404, { update: { error: 'That macro is not yours to change.' } });
}
return fail(400, { update: { error: readableError(err, 'Could not save the macro.') } });
}
return { updated: true };
},
async delete(event) {
const form = await event.request.formData();
const id = form.get('id')?.toString() ?? '';
try {
await deleteMacro(event, id);
} catch (/** @type {any} */ err) {
if (err?.status === 403) {
return fail(403, {
delete: { error: 'Only an admin can remove a macro shared with everyone.' }
});
}
if (err?.status === 404) {
// Same reasoning as `update`: the row not being yours reads the same
// as the row not existing, on purpose.
return fail(404, { delete: { error: 'That macro is not yours to remove.' } });
}
return fail(400, { delete: { error: readableError(err, 'Could not remove the macro.') } });
}
return { deleted: true };
},
// A macro's own action, not a reuse of `update`. `readValues` builds a
// full macro payload from the form, and this control only ever submits an
// id: posting through `update` would read `title`/`body` back as `''`
// (FormData has no key for either, `readValues` falls back to an empty
// string) and `buildBody` would then throw ("A macro needs a title.")
// before a request was even made. Calling `activateMacro` sidesteps
// `readValues`/`buildBody` entirely, so the PATCH body is
// `{ is_active: true }` and nothing else.
async activate(event) {
const form = await event.request.formData();
const id = form.get('id')?.toString() ?? '';
try {
await activateMacro(event, id);
} catch (/** @type {any} */ err) {
if (err?.status === 403) {
return fail(403, {
activate: { error: 'Only an admin can turn on a macro shared with everyone.' }
});
}
if (err?.status === 404) {
// Same reasoning as `update`/`delete`: the row not being yours reads
// the same as the row not existing, on purpose.
return fail(404, { activate: { error: 'That macro is not yours to turn on.' } });
}
return fail(400, { activate: { error: readableError(err, 'Could not turn the macro on.') } });
}
return { activated: true };
}
};

View file

@ -15,17 +15,64 @@
* segments and placed in elements, never through {@html}. A canned reply is
* a string a colleague wrote; putting it in the DOM as markup would make the
* macro editor a stored-XSS form.
*
* PERMISSIONS, WHICH ARE NOT ROLE-GATED THE WAY THE REST OF SETTINGS IS
* Every signed-in member may create, edit and delete their own `personal`
* macros; only an admin may do any of that to an `org`-scope one.
* `data.can_create_org` and `data.my_profile_id` are display hints decoded
* server-side from the JWT (see `macros.js`'s `getMacros`), never the
* authorization: the backend re-derives both and is what actually decides
* whether a write succeeds. `canWrite` below mirrors that split so a row
* only offers Edit/Delete when the click would not just come back as an
* error.
*/
import { enhance } from '$app/forms';
import PageHeader from '$lib/v2/components/PageHeader.svelte';
import SettingsCrumb from '$lib/v2/components/SettingsCrumb.svelte';
import Pill from '$lib/v2/components/Pill.svelte';
import StatCard from '$lib/v2/components/StatCard.svelte';
import SettingsFormPanel from '$lib/v2/components/SettingsFormPanel.svelte';
import ConfirmAction from '$lib/v2/components/ConfirmAction.svelte';
import { count, relativeDays } from '$lib/v2/format.js';
import { MACRO_SCOPE_LABEL } from '$lib/v2/enums.js';
import { Plus, TriangleAlert } from '@lucide/svelte';
/** @type {{ data: any }} */
let { data } = $props();
/** @type {{ data: any, form: any }} */
let { data, form } = $props();
// `null` when the panel is closed, `'new'` when adding, or the macro
// object when editing that row. One panel, two modes, so two rows can
// never be open for edit at once.
let editing = $state(/** @type {any} */ (null));
// The scope currently selected in the form. Bound separately from `editing`
// so the select works the same way in both modes: seeded from the row on
// edit, defaulted to 'personal' on create, since every member can make a
// personal macro but not every member can make an org one.
let scope = $state('personal');
function openCreate() {
editing = 'new';
scope = 'personal';
}
function openEdit(m) {
editing = m;
scope = m.scope;
}
/**
* May the signed-in viewer write this row. An org macro is writable only
* by an admin (`data.can_create_org`); a personal macro is writable only
* by its owner, compared by Profile id (`m.owner.id`, from `getMacros`'s
* reshape, against `data.my_profile_id`). This is a display decision, not
* an authorization one: the backend enforces the same split independently
* (403 on someone else's org macro, 404 on someone else's personal one)
* and would refuse the write even if this returned true by mistake.
*/
function canWrite(m) {
return m.scope === 'org' ? data.can_create_org : m.owner?.id === data.my_profile_id;
}
let totals = $derived(data.totals);
let byUse = $derived([...data.macros].sort((a, b) => b.usage_count - a.usage_count));
@ -66,7 +113,9 @@
<span class="v2-num">{count(totals.personal)}</span> yours
{/snippet}
{#snippet actions()}
<button class="v2-btn v2-btn-primary"><Plus />New macro</button>
{#if !editing}
<button class="v2-btn v2-btn-primary" onclick={openCreate}><Plus />New macro</button>
{/if}
{/snippet}
</PageHeader>
@ -86,6 +135,67 @@
<div class="v2-scroll">
<div class="v2-pad" style="padding-bottom:32px">
{#if editing}
<SettingsFormPanel
title={editing === 'new' ? 'New macro' : `Edit ${editing.title}`}
action={editing === 'new' ? '?/create' : '?/update'}
error={editing === 'new' ? form?.create?.error : form?.update?.error}
submitLabel={editing === 'new' ? 'Add macro' : 'Save macro'}
oncancel={() => (editing = null)}
ondone={() => (editing = null)}
>
{#snippet fields()}
{#if editing !== 'new'}
<input type="hidden" name="id" value={editing.id} />
{/if}
<div class="v2-field">
<label for="m-title">Title</label>
<input
id="m-title"
class="v2-input"
name="title"
maxlength="255"
required
value={editing === 'new' ? '' : editing.title}
/>
</div>
<div class="v2-field">
<label for="m-scope">Who sees it</label>
<select id="m-scope" class="v2-input" name="scope" bind:value={scope}>
<option value="personal">Just me</option>
{#if data.can_create_org}
<option value="org">Everyone in the org</option>
{/if}
</select>
{#if !data.can_create_org}
<p class="v2-hint">Only an admin can share a macro with everyone.</p>
{/if}
</div>
<div class="v2-field v2-sfp-wide">
<label for="m-body">Body</label>
<textarea id="m-body" class="v2-input" name="body" rows="5" required
>{editing === 'new' ? '' : editing.body}</textarea
>
<p class="v2-hint">
Placeholders like %customer_name% are substituted when the macro is sent. The seven
supported tokens are listed to the right; anything else goes to the customer exactly
as typed.
</p>
</div>
{/snippet}
</SettingsFormPanel>
{/if}
{#if form?.delete?.error}
<p class="v2-error" style="margin-bottom:12px">{form.delete.error}</p>
{/if}
{#if form?.activate?.error}
<p class="v2-error" style="margin-bottom:12px">{form.activate.error}</p>
{/if}
<div class="v2-split-wide">
<div>
<div class="v2-label" style="margin-bottom:10px">Shared with everyone</div>
@ -172,6 +282,51 @@
{MACRO_SCOPE_LABEL[m.scope]} · {m.owner.name}
</div>
{/if}
{#if canWrite(m)}
<div style="display:flex;gap:6px;align-items:center;justify-content:flex-end;margin-top:10px">
<button class="v2-btn v2-btn-sm" type="button" onclick={() => openEdit(m)}>Edit</button>
{#if !m.is_active}
<!-- Turning a macro back on restores nothing that was destroyed, so
unlike "Turn off"/"Delete" this doesn't need the two-click
confirm. A plain enhanced form posting just the id keeps the
request to `{ is_active: true }`; see `activateMacro`'s
comment for why that has to bypass `updateMacro` rather than
reuse it. Offered for both scopes on purpose: an org row gets
here by "Turn off" (soft), a personal row can only be inactive
from data written before the edit form stopped carrying
`is_active`, and either way `_get_writable` still enforces
admin-only for org / owner-only for personal server-side, so
this can never write a row `canWrite` above disagrees with. -->
<form method="POST" action="?/activate" use:enhance>
<input type="hidden" name="id" value={m.id} />
<button class="v2-btn v2-btn-sm" type="submit">Turn on</button>
</form>
{:else if m.scope === 'org'}
<!-- `MacroDetailView.delete` soft-deletes an org macro: it flips
`is_active` and leaves the row (and its usage count) in place.
"Turn off", not "Delete", says what actually happens. -->
<ConfirmAction
action="?/delete"
label="Turn off"
confirmLabel="Turn off"
explain="Turns it off for everyone. It stops appearing in the picker."
hidden={{ id: m.id }}
/>
{:else}
<!-- A personal macro is hard-deleted, not soft-deactivated: this
button removes the row outright, so once it's gone there is
nothing left to turn back on. -->
<ConfirmAction
action="?/delete"
label="Delete"
confirmLabel="Delete"
explain="Deletes it permanently."
hidden={{ id: m.id }}
/>
{/if}
</div>
{/if}
</div>
{/snippet}

View file

@ -1,6 +1,43 @@
import { getReopenPolicy } from '$lib/server/v2/reopen.js';
import { fail } from '@sveltejs/kit';
import { getReopenPolicy, updateReopenPolicy } from '$lib/server/v2/reopen.js';
import { readableError } from '$lib/server/v2/form-errors.js';
/** @type {import('./$types').PageServerLoad} */
export async function load({ cookies }) {
return getReopenPolicy({ cookies });
}
/** @type {import('./$types').Actions} */
export const actions = {
// Admin-only. `load`'s `can_edit` hides the "Edit policy" control for a
// member, but that is the affordance, not the check. `ReopenPolicyView.put`
// 403s a non-admin regardless of what reaches it; this branch turns that
// into a sentence instead of a raw backend error string.
async update(event) {
const form = await event.request.formData();
// The two booleans are read as "was the checkbox submitted", the normal
// HTML convention: an unchecked box sends nothing at all.
const values = {
is_enabled: form.get('is_enabled') === 'true',
notify_assigned: form.get('notify_assigned') === 'true',
reopen_window_days: form.get('reopen_window_days')?.toString() ?? '',
reopen_to_status: form.get('reopen_to_status')?.toString() ?? ''
};
try {
await updateReopenPolicy(event, values);
} catch (/** @type {any} */ err) {
if (err?.status === 403) {
return fail(403, { update: { error: 'Only an admin can change the reopen policy.' } });
}
return fail(400, {
update: { error: readableError(err, 'Could not save the reopen policy.') }
});
}
// No redirect. The policy is on this page and `load` re-runs after an
// action, so the new values appear where the user is already looking.
return { updated: true };
}
};

View file

@ -15,11 +15,15 @@
import SettingsCrumb from '$lib/v2/components/SettingsCrumb.svelte';
import Pill from '$lib/v2/components/Pill.svelte';
import StatCard from '$lib/v2/components/StatCard.svelte';
import SettingsFormPanel from '$lib/v2/components/SettingsFormPanel.svelte';
import { count } from '$lib/v2/format.js';
import { REOPEN_TO_STATUSES } from '$lib/v2/enums.js';
import { RotateCcw, MailX } from '@lucide/svelte';
/** @type {{ data: any }} */
let { data } = $props();
/** @type {{ data: any, form: any }} */
let { data, form } = $props();
let editing = $state(false);
let p = $derived(data.policy);
</script>
@ -32,7 +36,9 @@
: 'Closed tickets stay closed'}
{/snippet}
{#snippet actions()}
<button class="v2-btn v2-btn-primary">Edit policy</button>
{#if data.can_edit && !editing}
<button class="v2-btn v2-btn-primary" onclick={() => (editing = true)}>Edit policy</button>
{/if}
{/snippet}
</PageHeader>
@ -61,6 +67,74 @@
<div class="v2-scroll">
<div class="v2-pad" style="padding-bottom:32px">
{#if editing}
<SettingsFormPanel
title="Reopen policy"
action="?/update"
error={form?.update?.error}
submitLabel="Save policy"
oncancel={() => (editing = false)}
ondone={() => (editing = false)}
>
{#snippet fields()}
<div class="v2-field v2-sfp-wide">
<label for="f-enabled">Reopen on customer reply</label>
<label style="display:flex;gap:8px;align-items:center;font-weight:400">
<input
id="f-enabled"
type="checkbox"
name="is_enabled"
value="true"
checked={p.is_enabled}
/>
Off means a reply is filed on the closed ticket and nothing else happens.
</label>
</div>
<div class="v2-field">
<label for="f-window">Window, in days</label>
<input
id="f-window"
class="v2-input"
type="number"
name="reopen_window_days"
min="1"
max="365"
required
value={p.reopen_window_days}
/>
<p class="v2-hint">Counted from when the ticket was closed, in calendar days.</p>
</div>
<div class="v2-field">
<label for="f-status">Comes back as</label>
<select id="f-status" class="v2-input" name="reopen_to_status">
{#each REOPEN_TO_STATUSES as status (status)}
<option value={status} selected={status === p.reopen_to_status}>{status}</option>
{/each}
</select>
<p class="v2-hint">
Only these three. A ticket reopened into a closed status would close again on
arrival.
</p>
</div>
<div class="v2-field v2-sfp-wide">
<label for="f-notify">Tell the assignee</label>
<label style="display:flex;gap:8px;align-items:center;font-weight:400">
<input
id="f-notify"
type="checkbox"
name="notify_assigned"
value="true"
checked={p.notify_assigned}
/>
The person the ticket was assigned to when it closed.
</label>
</div>
{/snippet}
</SettingsFormPanel>
{/if}
<div class="v2-split">
<div>
<div class="v2-label" style="margin-bottom:10px">The rule</div>

View file

@ -1,6 +1,145 @@
import { getRoutingRules } from '$lib/server/v2/routing.js';
import { fail } from '@sveltejs/kit';
import {
getRoutingRules,
createRoutingRule,
updateRoutingRule,
deleteRoutingRule,
readConditionRows
} from '$lib/server/v2/routing.js';
import { getOrgPeopleAndTeams } from '$lib/server/v2/org-people.js';
import { readableError } from '$lib/server/v2/form-errors.js';
// The rule list and the create/edit form's people/team pickers are two
// independent fetches: `getRoutingRules` no longer folds `getOrgPeopleAndTeams`
// into its own return, because `getSettingsHub` (the settings-hub aggregator)
// also calls `getRoutingRules` and only ever reads `.totals` off it. Folding
// the picker fetch in there fired an extra, unused `/users/get-teams-and-users/`
// request on every settings-hub load. Fetched in parallel here instead, since
// this is the one place both are actually needed.
/** @type {import('./$types').PageServerLoad} */
export async function load({ cookies }) {
return getRoutingRules({ cookies });
const [data, options] = await Promise.all([
getRoutingRules({ cookies }),
getOrgPeopleAndTeams(cookies)
]);
return { ...data, ...options };
}
/**
* Everything both the create and edit form submit. `is_active` is
* deliberately not read here: only the create form carries that checkbox
* (the edit form's own row control, Turn off / Turn on, owns that state), so
* reading `form.get('is_active')` here would answer `false` on every edit
* submit, since an absent checkbox and an unchecked one look identical to
* `FormData`. The `create` action below attaches `is_active` itself, straight
* from the one form that renders it.
*
* The condition rows are read by `readConditionRows` in `routing.js`, not
* here: the form submits one indexed name per row (`condition_field_0` and so
* on) and the reader pairs them by index, so a control that submits nothing
* cannot shift its neighbours. Keeping it in the module is what makes that
* rule testable, since the harness cannot import a route file.
*
* @param {FormData} form
*/
function readValues(form) {
return {
name: form.get('name')?.toString().trim() ?? '',
priority_order: form.get('priority_order')?.toString() ?? '0',
stop_processing: form.get('stop_processing') === 'true',
strategy: form.get('strategy')?.toString() ?? '',
target_assignee_ids: form.getAll('target_assignee_ids').map((v) => v.toString()),
target_team_id: form.get('target_team_id')?.toString() ?? '',
conditions: readConditionRows(form)
};
}
/** @type {import('./$types').Actions} */
export const actions = {
// Admin-only server-side (`RoutingRuleListCreateView.post` calls
// `_is_admin` first). `can_edit` only hides the control.
async create(event) {
const form = await event.request.formData();
const values = { ...readValues(form), is_active: form.get('is_active') === 'true' };
try {
await createRoutingRule(event, values);
} catch (/** @type {any} */ err) {
if (err?.status === 403) {
return fail(403, { create: { error: 'Only an admin can add routing rules.' } });
}
return fail(400, { create: { error: readableError(err, 'Could not add the rule.') } });
}
return { created: true };
},
async update(event) {
const form = await event.request.formData();
const id = form.get('id')?.toString() ?? '';
const values = readValues(form);
try {
await updateRoutingRule(event, id, values);
} catch (/** @type {any} */ err) {
if (err?.status === 403) {
return fail(403, { update: { error: 'Only an admin can change routing rules.' } });
}
return fail(400, { update: { error: readableError(err, 'Could not save the rule.') } });
}
return { updated: true };
},
async deactivate(event) {
const form = await event.request.formData();
const id = form.get('id')?.toString() ?? '';
try {
await updateRoutingRule(event, id, { is_active: false });
} catch (/** @type {any} */ err) {
if (err?.status === 403) {
return fail(403, { deactivate: { error: 'Only an admin can turn routing rules off.' } });
}
return fail(400, {
deactivate: { error: readableError(err, 'Could not turn the rule off.') }
});
}
return { deactivated: true };
},
// A rule's own action, not a reuse of `update`. `readValues` builds a full
// rule payload from the form, and this control only ever submits an id: if
// it posted through `update`, `name` would read back as `''` (`FormData`
// has no key for it) and `createRoutingRule`/`updateRoutingRule`'s own
// `buildBody` would forward that, blanking the name on every reactivation.
// Calling `updateRoutingRule` directly with only `{ is_active: true }`
// sidesteps `readValues` entirely, so the PUT body is `{ is_active: true }`
// and nothing else.
async activate(event) {
const form = await event.request.formData();
const id = form.get('id')?.toString() ?? '';
try {
await updateRoutingRule(event, id, { is_active: true });
} catch (/** @type {any} */ err) {
if (err?.status === 403) {
return fail(403, { activate: { error: 'Only an admin can turn routing rules on.' } });
}
return fail(400, {
activate: { error: readableError(err, 'Could not turn the rule on.') }
});
}
return { activated: true };
},
// `RoutingRuleDetailView.delete` is a hard delete, unlike `/custom-fields/`.
// The row control that posts here says so before it does.
async remove(event) {
const form = await event.request.formData();
const id = form.get('id')?.toString() ?? '';
try {
await deleteRoutingRule(event, id);
} catch (/** @type {any} */ err) {
if (err?.status === 403) {
return fail(403, { remove: { error: 'Only an admin can delete routing rules.' } });
}
return fail(400, { remove: { error: readableError(err, 'Could not delete the rule.') } });
}
return { removed: true };
}
};

View file

@ -14,23 +14,96 @@
* unconditional, stop-processing rule appears, everything below it is
* dead, and "matched 0 times" on its own looks like a quiet month.
*/
import { enhance } from '$app/forms';
import PageHeader from '$lib/v2/components/PageHeader.svelte';
import SettingsCrumb from '$lib/v2/components/SettingsCrumb.svelte';
import Pill from '$lib/v2/components/Pill.svelte';
import StatCard from '$lib/v2/components/StatCard.svelte';
import SettingsFormPanel from '$lib/v2/components/SettingsFormPanel.svelte';
import ConfirmAction from '$lib/v2/components/ConfirmAction.svelte';
import { count } from '$lib/v2/format.js';
import {
ROUTING_STRATEGY_LABEL,
ROUTING_STRATEGY_NAME,
CONDITION_FIELD_LABEL,
CONDITION_OP_LABEL
} from '$lib/v2/enums.js';
import { missingOptions, inactiveOptionLabel } from '$lib/v2/pickers.js';
import { Plus, GripVertical, TriangleAlert, UserX } from '@lucide/svelte';
/** @type {{ data: any }} */
let { data } = $props();
/** @type {{ data: any, form: any }} */
let { data, form } = $props();
// `null` when the panel is closed, `'new'` when adding, or the rule object
// when editing that row. One panel, two modes, so two rows can never be
// open for edit at once.
let editing = $state(/** @type {any} */ (null));
// The strategy currently selected in the form, so the target picker below
// it (team vs. people) can switch without a round trip. Seeded from the
// rule being edited.
let strategy = $state('direct');
// The repeating condition rows being edited, as `{ field, op, value }`.
// Held here, rather than read off `editing`, so a row can be added or
// removed before submitting.
let conditionRows = $state(
/** @type {{ field: string, op: string, value: string }[]} */ ([])
);
function openCreate() {
editing = 'new';
strategy = 'direct';
conditionRows = [];
}
function openEdit(r) {
editing = r;
strategy = r.strategy;
// Joining an array value into a comma-separated string is the right
// editing representation for a single text input, and it round-trips: on
// save, `routing.js`'s `cleanConditions` splits an `in` row's value back
// on commas. That round trip is lossless for any value made up of
// entries with no comma in them, which is the whole reason this editor
// can stay one text input instead of its own repeating sub-list. Known
// limitation: a value that itself contains a literal comma cannot be
// expressed here, since splitting can't tell that comma apart from a
// separator.
conditionRows = r.conditions.map((c) => ({
field: c.field,
op: c.op,
value: Array.isArray(c.value) ? c.value.join(', ') : String(c.value ?? '')
}));
}
let totals = $derived(data.totals);
// Targets the picker cannot offer, because the profile was deactivated
// after it was chosen. `getOrgPeopleAndTeams` only ever returns active
// profiles, while the rule's M2M keeps them, which is exactly what the
// deactivated-target flag on the card below is about. Without an option of
// their own the multi-select submits nothing for them, so an edit made for
// another reason would quietly rewrite the rotation.
let missingAssignees = $derived(
editing && editing !== 'new' ? missingOptions(data.people, editing.target_assignees) : []
);
/**
* A stored condition field the select cannot show.
*
* `custom_fields.<key>` is a first-class field everywhere else: the backend
* accepts it, `cleanConditions` accepts it, and `when()` below renders it.
* `CONDITION_FIELD_LABEL` only carries the six fixed ones, so without this
* the select would have no matching option, would submit nothing, and the
* row would be dropped or, worse, shift its neighbours.
*/
function unlistedField(field) {
if (!field || field in CONDITION_FIELD_LABEL) return null;
return field.startsWith('custom_fields.')
? `Custom field: ${field.slice('custom_fields.'.length)}`
: field;
}
/**
* Reachability, walked in evaluation order.
*
@ -84,7 +157,9 @@
<span class="v2-num">{count(totals.active)}</span> active rules, run in this order until one matches
{/snippet}
{#snippet actions()}
<button class="v2-btn v2-btn-primary"><Plus />New rule</button>
{#if data.can_edit && !editing}
<button class="v2-btn v2-btn-primary" onclick={openCreate}><Plus />New rule</button>
{/if}
{/snippet}
</PageHeader>
@ -103,6 +178,231 @@
<div class="v2-scroll">
<div class="v2-pad" style="padding-bottom:32px">
{#if editing}
<SettingsFormPanel
title={editing === 'new' ? 'New rule' : `Edit ${editing.name}`}
action={editing === 'new' ? '?/create' : '?/update'}
error={editing === 'new' ? form?.create?.error : form?.update?.error}
submitLabel={editing === 'new' ? 'Add rule' : 'Save rule'}
oncancel={() => (editing = null)}
ondone={() => (editing = null)}
>
{#snippet fields()}
{#if editing !== 'new'}
<input type="hidden" name="id" value={editing.id} />
{/if}
<div class="v2-field">
<label for="r-name">Name</label>
<input
id="r-name"
class="v2-input"
name="name"
maxlength="128"
required
value={editing === 'new' ? '' : editing.name}
/>
</div>
<div class="v2-field">
<label for="r-priority">Priority</label>
<input
id="r-priority"
class="v2-input"
type="number"
name="priority_order"
min="0"
value={editing === 'new' ? 0 : editing.priority_order}
/>
<p class="v2-hint">The engine runs rules low number first and takes the first match.</p>
</div>
<div class="v2-field">
<label for="r-strategy">Then</label>
<select id="r-strategy" class="v2-input" name="strategy" bind:value={strategy}>
{#each Object.entries(ROUTING_STRATEGY_NAME) as [value, label] (value)}
<option {value}>{label}</option>
{/each}
</select>
</div>
{#if strategy === 'by_team'}
<div class="v2-field">
<label for="r-team">Team</label>
<select id="r-team" class="v2-input" name="target_team_id" required>
<option value="" disabled selected={editing === 'new' || !editing.target_team}>
Choose a team
</option>
{#each data.teams as t (t.id)}
<option
value={t.id}
selected={editing !== 'new' && editing.target_team?.id === t.id}
>
{t.name}
</option>
{/each}
</select>
{#if !data.teams.length}
<p class="v2-hint">No teams in this org yet.</p>
{/if}
</div>
{:else}
<div class="v2-field">
<label for="r-people">Who</label>
<select
id="r-people"
class="v2-input"
name="target_assignee_ids"
multiple
style="height:118px"
>
<!-- A target whose profile has been deactivated is not in
`data.people`, so it gets an option of its own. Dropping
it would be a change to who tickets go to, made by an
edit that was about something else. -->
{#each missingAssignees as a (a.id)}
<option value={a.id} selected>{inactiveOptionLabel(a.name)}</option>
{/each}
{#each data.people as p (p.id)}
<option
value={p.id}
selected={editing !== 'new' &&
editing.target_assignees.some((a) => a.id === p.id)}
>
{p.name}
</option>
{/each}
</select>
<p class="v2-hint">
{#if strategy === 'direct'}
Direct uses only the first person selected here; the rest are ignored unless the
strategy changes.
{:else}
Round robin and least busy cycle through everyone listed here.
{/if}
</p>
{#if missingAssignees.length}
<p class="v2-hint">
{missingAssignees.map((a) => a.name).join(', ')}
{missingAssignees.length === 1 ? 'is' : 'are'} deactivated and still in the rotation.
Deselect to take them out.
</p>
{/if}
</div>
{/if}
<div class="v2-field">
<label for="r-stop">Stop processing</label>
<label style="display:flex;gap:8px;align-items:center;font-weight:400">
<input
id="r-stop"
type="checkbox"
name="stop_processing"
value="true"
checked={editing !== 'new' && editing.stop_processing}
/>
A matching rule with this on stops the engine, so later rules never see the ticket.
</label>
</div>
{#if editing === 'new'}
<div class="v2-field">
<label for="r-active">Active</label>
<label style="display:flex;gap:8px;align-items:center;font-weight:400">
<input id="r-active" type="checkbox" name="is_active" value="true" checked />
Starts matching tickets as soon as it is saved.
</label>
</div>
{/if}
<div class="v2-field v2-sfp-wide">
<label for="r-cond-0">Conditions</label>
<!-- One indexed name per row, not three parallel `condition_field`
/ `condition_op` / `condition_value` lists. A select with no
matching option submits no entry at all, so parallel lists
paired by position silently shifted every row after the gap.
Indexed names make a row's three inputs travel together, and
`readConditionRows` in `routing.js` pairs them by index. -->
{#each conditionRows as row, i (i)}
{@const unlisted = unlistedField(row.field)}
<div style="margin-bottom:6px">
<div style="display:flex;gap:7px;align-items:center">
<select
id={i === 0 ? 'r-cond-0' : undefined}
class="v2-input"
name="condition_field_{i}"
bind:value={row.field}
>
<option value="">Choose a field</option>
{#if unlisted}
<!-- A stored `custom_fields.<key>` condition. The label
map carries only the six fixed fields, so without
this option the select would match nothing and the
condition would not survive an unrelated edit. -->
<option value={row.field}>{unlisted}</option>
{/if}
{#each Object.entries(CONDITION_FIELD_LABEL) as [value, label] (value)}
<option {value}>{label}</option>
{/each}
</select>
<select class="v2-input" name="condition_op_{i}" bind:value={row.op}>
{#each Object.entries(CONDITION_OP_LABEL) as [value, label] (value)}
<option {value}>{label}</option>
{/each}
</select>
<input
class="v2-input"
name="condition_value_{i}"
bind:value={row.value}
placeholder="Value"
/>
<button
class="v2-btn v2-btn-sm"
type="button"
onclick={() => (conditionRows = conditionRows.filter((_, j) => j !== i))}
>
Remove
</button>
</div>
{#if row.op === 'in'}
<!-- Only for `in`: `eq`, `contains` and `regex` all take the
value as one plain string, so this hint would be wrong
for them. -->
<p class="v2-hint">
Comma separated. Matches if any one of these values matches.
</p>
{/if}
</div>
{/each}
<button
class="v2-btn v2-btn-sm"
type="button"
style="align-self:flex-start"
onclick={() => (conditionRows = [...conditionRows, { field: '', op: 'eq', value: '' }])}
>
Add a condition
</button>
{#if !conditionRows.some((row) => row.field)}
<p class="v2-error" style="margin-top:8px">
<TriangleAlert size={13} style="flex:none;margin-top:1px" />
<span>With no conditions this rule matches every ticket.</span>
</p>
{/if}
</div>
{/snippet}
</SettingsFormPanel>
{/if}
{#if form?.deactivate?.error}
<p class="v2-error" style="margin-bottom:12px">{form.deactivate.error}</p>
{/if}
{#if form?.activate?.error}
<p class="v2-error" style="margin-bottom:12px">{form.activate.error}</p>
{/if}
{#if form?.remove?.error}
<p class="v2-error" style="margin-bottom:12px">{form.remove.error}</p>
{/if}
<div class="v2-label" style="margin-bottom:10px">In evaluation order</div>
<div style="display:flex;flex-direction:column;gap:9px">
@ -172,6 +472,35 @@
<span class="v2-sub" style="font-size:10.5px;margin-top:4px">falls through</span>
{/if}
</div>
{#if data.can_edit}
<div class="v2-rule-actions">
<button class="v2-btn v2-btn-sm" type="button" onclick={() => openEdit(r)}>
Edit
</button>
{#if r.is_active}
<ConfirmAction
action="?/deactivate"
label="Turn off"
confirmLabel="Turn off"
explain="Stops matching new tickets. It stays in the list, off, until turned back on."
hidden={{ id: r.id }}
/>
{:else}
<form method="POST" action="?/activate" use:enhance>
<input type="hidden" name="id" value={r.id} />
<button class="v2-btn v2-btn-sm" type="submit">Turn on</button>
</form>
{/if}
<ConfirmAction
action="?/remove"
label="Delete"
confirmLabel="Delete"
explain="Deleted permanently. Tickets already routed by it stay where they are."
hidden={{ id: r.id }}
/>
</div>
{/if}
</div>
{/each}
</div>
@ -206,6 +535,12 @@
align-items: flex-end;
text-align: right;
}
.v2-rule-actions {
flex: none;
display: flex;
gap: 6px;
align-items: center;
}
.v2-rule-flag {
display: flex;
gap: 7px;
@ -230,5 +565,17 @@
margin-top: 10px;
padding-left: 30px;
}
/* Same reflow as `.v2-rule-stat` above: a flex:none column becomes its
own full-width row, indented to align under the card's main content
rather than the grip handle. `flex-wrap` is added here (unlike the
stat block) because an armed `ConfirmAction` grows into a button pair
plus a sentence of explain text, which does not fit one line at
390px. */
.v2-rule-actions {
flex-wrap: wrap;
width: 100%;
margin-top: 10px;
padding-left: 30px;
}
}
</style>

View file

@ -1,6 +1,37 @@
import { getTags } from '$lib/server/v2/tags.js';
import { fail } from '@sveltejs/kit';
import { getTags, createTag } from '$lib/server/v2/tags.js';
import { readableError } from '$lib/server/v2/form-errors.js';
/** @type {import('./$types').PageServerLoad} */
export async function load({ cookies }) {
return getTags({ cookies });
}
/** @type {import('./$types').Actions} */
export const actions = {
// Admin-only. `load`'s `can_edit` hides the "New tag" control for a member,
// but that is only the affordance; this check is the one that matters.
// `TagsListView.post` (`backend/common/views/tags_views.py:143-149`) 403s a
// non-admin regardless of what reaches it, so this branch exists to turn
// that response into a message instead of a raw backend error string, not
// to be the authority itself.
async create(event) {
const form = await event.request.formData();
const name = form.get('name')?.toString() ?? '';
try {
await createTag(event, { name });
} catch (/** @type {any} */ err) {
if (err?.status === 403) {
return fail(403, { create: { name, error: 'Only an admin can create tags.' } });
}
return fail(400, {
create: { name, error: readableError(err, 'Could not create the tag.') }
});
}
// No redirect. The list is on this page, and `load` re-runs after an
// action, so the new tag appears where the user is already looking.
return { created: true };
}
};

View file

@ -10,6 +10,7 @@
* collide on the slug, but "Renewal" and "Renewals" slug differently while
* meaning the same thing, and the work splits silently across them.
*/
import { enhance } from '$app/forms';
import PageHeader from '$lib/v2/components/PageHeader.svelte';
import SettingsCrumb from '$lib/v2/components/SettingsCrumb.svelte';
import Pill from '$lib/v2/components/Pill.svelte';
@ -18,8 +19,20 @@
import { count } from '$lib/v2/format.js';
import { Plus, Merge, Tags as TagsIcon } from '@lucide/svelte';
/** @type {{ data: any }} */
let { data } = $props();
/** @type {{ data: any, form: any }} */
let { data, form } = $props();
// The "New tag" disclosure. Open while adding, closed on a successful
// create; a failed one stays open so the error next to the input is
// actually visible instead of vanishing the instant the form action
// returns.
let adding = $state(false);
// Disables the Create button while the submit is in flight, so a
// double-click cannot fire two creates: the second would either duplicate
// the tag or, for a same-named resubmit, come back as "already exists"
// right after the first one succeeded.
let busy = $state(false);
let totals = $derived(data.totals);
@ -62,7 +75,48 @@
<span class="v2-num">{count(totals.active)}</span> in use across accounts, leads, deals and tickets
{/snippet}
{#snippet actions()}
<button class="v2-btn v2-btn-primary"><Plus />New tag</button>
{#if data.can_edit}
{#if adding}
<form
class="v2-tag-add-form"
method="POST"
action="?/create"
use:enhance={() => {
busy = true;
return async (/** @type {any} */ { result, update }) => {
await update();
busy = false;
// Only close on success. A failed submit (the empty-name guard, a
// duplicate name) has to leave the form open, or the error rendered
// below never gets seen: it lives inside this same `{#if adding}`
// block.
if (result.type === 'success') adding = false;
};
}}
>
{#if form?.create?.error}
<p class="v2-error">{form.create.error}</p>
{/if}
<!-- svelte-ignore a11y_autofocus -->
<input
class="v2-input"
name="name"
placeholder="Tag name"
required
autofocus
disabled={busy}
/>
<button class="v2-btn v2-btn-primary" type="submit" disabled={busy}>Create</button>
<button class="v2-btn" type="button" disabled={busy} onclick={() => (adding = false)}>
Cancel
</button>
</form>
{:else}
<button class="v2-btn v2-btn-primary" onclick={() => (adding = true)}
><Plus />New tag</button
>
{/if}
{/if}
{/snippet}
</PageHeader>
@ -93,6 +147,8 @@
one of them misses the other.
</p>
</div>
<!-- Merge stays unwired: /api/tags/<id>/merge/ does not resolve, there
is no backing endpoint yet. Tracked in the phase 2 plan. -->
<button class="v2-btn v2-btn-sm" style="flex:none;align-self:center">Merge</button>
</div>
{/each}
@ -170,4 +226,49 @@
border-radius: var(--v2-radius);
background: var(--v2-card);
}
/* The inline "New tag" disclosure lives in the page header's actions row
(a flex container), alongside the plain Create/Cancel buttons, so it has
to lay out as a single line rather than stack like a full-page form. */
.v2-tag-add-form {
display: flex;
align-items: center;
gap: 7px;
position: relative;
}
.v2-tag-add-form .v2-input {
width: 200px;
}
/* The error sits above the input per the leads/new convention, but there is
no room to grow the header's height for it, so it floats instead of
pushing the row down. `right: 0` plus `white-space: normal` (rather than
the `nowrap` a one-line floating label would default to) let it wrap
within the row's own width instead of running off narrow viewports; a
duplicate-name rejection ("A tag with this name already exists.") is
long enough to hit this in practice. */
.v2-tag-add-form .v2-error {
position: absolute;
bottom: 100%;
left: 0;
right: 0;
margin: 0 0 4px;
white-space: normal;
}
/* Below 768px `.v2-header .v2-actions` goes full width (v2.css), but this
form's own children do not: a 200px input plus two buttons is wider than
a phone screen, and a flex item does not shrink past its content's fixed
width on its own. Confirmed by emulating a 320px viewport: the row
overflowed and clipped "Cancel" before this rule existed. Wrapping the
input onto its own full-width line, with the buttons below it, keeps
everything on screen and touchable instead of cut off. */
@media (max-width: 768px) {
.v2-tag-add-form {
flex-wrap: wrap;
width: 100%;
}
.v2-tag-add-form .v2-input {
width: 100%;
flex: 1 1 100%;
}
}
</style>

View file

@ -1,6 +1,146 @@
import { getApprovalRules } from '$lib/server/v2/ticket-approvals.js';
import { fail } from '@sveltejs/kit';
import {
getApprovalRules,
createApprovalRule,
updateApprovalRule,
deleteApprovalRule
} from '$lib/server/v2/ticket-approvals.js';
import { getOrgPeopleAndTeams } from '$lib/server/v2/org-people.js';
import { readableError } from '$lib/server/v2/form-errors.js';
// The rule list and the create/edit form's approver picker are two independent
// fetches: `getApprovalRules` does not fold `getOrgPeopleAndTeams` into its own
// return, because `getSettingsHub` (the settings-hub aggregator) also calls
// `getApprovalRules` and only ever reads `.totals` off it. Folding the picker
// fetch in there would fire an extra, unused `/users/get-teams-and-users/`
// request on every settings-hub load. Fetched in parallel here instead, since
// this is the one place both are actually needed.
/** @type {import('./$types').PageServerLoad} */
export async function load({ cookies }) {
return getApprovalRules({ cookies });
const [data, options] = await Promise.all([
getApprovalRules({ cookies }),
getOrgPeopleAndTeams(cookies)
]);
return { ...data, ...options };
}
/**
* Everything both the create and edit form submit. `is_active` is
* deliberately not read here: only the create form carries that checkbox
* (the edit form's own row control, Turn off / Turn on, owns that state), so
* reading `form.get('is_active')` here would answer `false` on every edit
* submit, since an absent checkbox and an unchecked one look identical to
* `FormData`. The `create` action below attaches `is_active` itself, straight
* from the one form that renders it. `trigger_event` is never read from the
* form at all: `ticket-approvals.js` sets it, since `pre_close` is the only
* value the backend accepts.
*
* @param {FormData} form
*/
function readValues(form) {
return {
name: form.get('name')?.toString().trim() ?? '',
match_priority: form.get('match_priority')?.toString() ?? '',
match_case_type: form.get('match_case_type')?.toString() ?? '',
match_team_id: form.get('match_team_id')?.toString() ?? '',
approver_role: form.get('approver_role')?.toString() ?? '',
approver_ids: form.getAll('approver_ids').map((v) => v.toString())
};
}
/** @type {import('./$types').Actions} */
export const actions = {
// Admin-only server-side (`ApprovalRuleListCreateView.post` calls
// `_is_admin` first). `can_edit` only hides the control.
async create(event) {
const form = await event.request.formData();
const values = { ...readValues(form), is_active: form.get('is_active') === 'true' };
try {
await createApprovalRule(event, values);
} catch (/** @type {any} */ err) {
if (err?.status === 403) {
return fail(403, { create: { error: 'Only an admin can change approval rules.' } });
}
return fail(400, { create: { error: readableError(err, 'Could not add the rule.') } });
}
return { created: true };
},
async update(event) {
const form = await event.request.formData();
const id = form.get('id')?.toString() ?? '';
const values = readValues(form);
try {
await updateApprovalRule(event, id, values);
} catch (/** @type {any} */ err) {
if (err?.status === 403) {
return fail(403, { update: { error: 'Only an admin can change approval rules.' } });
}
return fail(400, { update: { error: readableError(err, 'Could not save the rule.') } });
}
return { updated: true };
},
async deactivate(event) {
const form = await event.request.formData();
const id = form.get('id')?.toString() ?? '';
try {
await updateApprovalRule(event, id, { is_active: false });
} catch (/** @type {any} */ err) {
if (err?.status === 403) {
return fail(403, { deactivate: { error: 'Only an admin can change approval rules.' } });
}
return fail(400, {
deactivate: { error: readableError(err, 'Could not turn the rule off.') }
});
}
return { deactivated: true };
},
// A rule's own action, not a reuse of `update`. `readValues` builds a full
// rule payload from the form, and this control only ever submits an id: if
// it posted through `update`, `name` would read back as `''` (`FormData`
// has no key for it) and `createApprovalRule`/`updateApprovalRule`'s own
// `buildBody` would forward that, blanking the name on every reactivation.
// Calling `updateApprovalRule` directly with only `{ is_active: true }`
// sidesteps `readValues` entirely, so the PUT body is `{ is_active: true }`
// and nothing else.
async activate(event) {
const form = await event.request.formData();
const id = form.get('id')?.toString() ?? '';
try {
await updateApprovalRule(event, id, { is_active: true });
} catch (/** @type {any} */ err) {
if (err?.status === 403) {
return fail(403, { activate: { error: 'Only an admin can change approval rules.' } });
}
return fail(400, {
activate: { error: readableError(err, 'Could not turn the rule on.') }
});
}
return { activated: true };
},
// `ApprovalRuleDetailView.delete` has two outcomes behind the one verb: a
// rule with no approval history is destroyed, and a rule with any history
// (in any state, not just pending) is turned off instead, because
// `Approval.rule` is `on_delete=PROTECT`. Both answer 2xx, so which one
// happened is read off the response body by `deleteApprovalRule` and
// reported here rather than assumed. The page renders a line saying the
// rule was turned off when that is what happened, so an admin is never told
// "deleted" about a row that is still in the list.
async remove(event) {
const form = await event.request.formData();
const id = form.get('id')?.toString() ?? '';
let outcome;
try {
outcome = await deleteApprovalRule(event, id);
} catch (/** @type {any} */ err) {
if (err?.status === 403) {
return fail(403, { remove: { error: 'Only an admin can change approval rules.' } });
}
return fail(400, { remove: { error: readableError(err, 'Could not delete the rule.') } });
}
return { removed: !outcome.turned_off, remove: { turned_off: outcome.turned_off } };
}
};

View file

@ -18,18 +18,59 @@
* flagged "any admin, including the requester" as a hole; the view has since
* closed it, so the warning is gone.
*/
import { enhance } from '$app/forms';
import PageHeader from '$lib/v2/components/PageHeader.svelte';
import SettingsCrumb from '$lib/v2/components/SettingsCrumb.svelte';
import Pill from '$lib/v2/components/Pill.svelte';
import SettingsFormPanel from '$lib/v2/components/SettingsFormPanel.svelte';
import ConfirmAction from '$lib/v2/components/ConfirmAction.svelte';
import { count } from '$lib/v2/format.js';
import { ROLE_LABEL } from '$lib/v2/enums.js';
import { missingOptions, inactiveOptionLabel } from '$lib/v2/pickers.js';
import { Plus, TriangleAlert, ChevronRight } from '@lucide/svelte';
/** @type {{ data: any }} */
let { data } = $props();
/** @type {{ data: any, form: any }} */
let { data, form } = $props();
// cases.approvals: PRIORITY_CHOICE and CASE_TYPE. Not in `$lib/v2/enums.js`
// because there is no shared label map to derive from: value and label are
// the same string for both, and no other v2 page reads either list.
const MATCH_PRIORITIES = ['Low', 'Normal', 'High', 'Urgent'];
const MATCH_CASE_TYPES = ['Question', 'Incident', 'Problem'];
// `ROLE_LABEL` covers `Profile.role` (ADMIN/USER), not the approver-role
// vocabulary this form offers (ADMIN/MANAGER). MANAGER is not a real
// `Profile.role` value (see the module docstring), so it has no entry in
// that map and would render as `undefined`. Labelled here instead.
function approverRoleLabel(role) {
return role === 'MANAGER' ? 'Manager' : (ROLE_LABEL[role] ?? role);
}
// `null` when the panel is closed, `'new'` when adding, or the rule object
// when editing that row. One panel, two modes, so two rows can never be
// open for edit at once.
let editing = $state(/** @type {any} */ (null));
function openCreate() {
editing = 'new';
}
function openEdit(r) {
editing = r;
}
let totals = $derived(data.totals);
let rules = $derived(data.rules);
// Named approvers the picker cannot offer, because the profile has been
// deactivated since it was named. Without an option of their own the
// multi-select submits nothing for them and an unrelated edit drops them,
// which can widen a rule to "any admin" or, on a MANAGER rule, leave it
// clearable by nobody.
let missingApprovers = $derived(
editing && editing !== 'new' ? missingOptions(data.people, editing.approvers) : []
);
/** MANAGER matches no Profile.role, so an empty approvers list means nobody. */
const clearableByNobody = (r) =>
r.is_active && r.approver_role === 'MANAGER' && !r.approvers.length;
@ -52,12 +93,172 @@
<span class="v2-num">{count(totals.pending)}</span> approvals waiting on them right now
{/snippet}
{#snippet actions()}
<button class="v2-btn v2-btn-primary"><Plus />New rule</button>
{#if data.can_edit && !editing}
<button class="v2-btn v2-btn-primary" onclick={openCreate}><Plus />New rule</button>
{/if}
{/snippet}
</PageHeader>
<div class="v2-scroll">
<div class="v2-pad" style="padding-top:18px;padding-bottom:32px">
{#if editing}
<SettingsFormPanel
title={editing === 'new' ? 'New rule' : `Edit ${editing.name}`}
action={editing === 'new' ? '?/create' : '?/update'}
error={editing === 'new' ? form?.create?.error : form?.update?.error}
submitLabel={editing === 'new' ? 'Add rule' : 'Save rule'}
oncancel={() => (editing = null)}
ondone={() => (editing = null)}
>
{#snippet fields()}
{#if editing !== 'new'}
<input type="hidden" name="id" value={editing.id} />
{/if}
<div class="v2-field">
<label for="a-name">Name</label>
<input
id="a-name"
class="v2-input"
name="name"
maxlength="128"
required
value={editing === 'new' ? '' : editing.name}
/>
</div>
<div class="v2-field">
<label for="a-role">Approver role</label>
<select id="a-role" class="v2-input" name="approver_role">
{#each ['ADMIN', 'MANAGER'] as role (role)}
<option
value={role}
selected={editing === 'new' ? role === 'ADMIN' : editing.approver_role === role}
>
{approverRoleLabel(role)}
</option>
{/each}
</select>
</div>
<div class="v2-field v2-sfp-wide">
<label for="a-approvers">Named approvers</label>
<select
id="a-approvers"
class="v2-input"
name="approver_ids"
multiple
style="height:96px"
>
<!-- A named approver whose profile is no longer active is not in
`data.people`, so it gets an option of its own here. Without
one the browser submits nothing for it and saving an
unrelated field would drop the approver silently. -->
{#each missingApprovers as a (a.id)}
<option value={a.id} selected>{inactiveOptionLabel(a.email)}</option>
{/each}
{#each data.people as p (p.id)}
<option
value={p.id}
selected={editing !== 'new' && editing.approvers.some((a) => a.id === p.id)}
>
{p.name}
</option>
{/each}
</select>
<p class="v2-hint">
Named approvers are in addition to the role above. Leave this empty and anyone with
that role can clear the approval.
</p>
{#if missingApprovers.length}
<p class="v2-hint">
{missingApprovers.length === 1
? 'One approver is'
: `${missingApprovers.length} approvers are`}
no longer active. They stay named until you deselect them, and they cannot clear an approval
while their account is off.
</p>
{/if}
</div>
<div class="v2-field">
<label for="a-priority">Priority</label>
<select id="a-priority" class="v2-input" name="match_priority">
<option value="" selected={editing === 'new' || !editing.match_priority}>Any</option>
{#each MATCH_PRIORITIES as p (p)}
<option value={p} selected={editing !== 'new' && editing.match_priority === p}>
{p}
</option>
{/each}
</select>
</div>
<div class="v2-field">
<label for="a-type">Ticket type</label>
<select id="a-type" class="v2-input" name="match_case_type">
<option value="" selected={editing === 'new' || !editing.match_case_type}>
Any
</option>
{#each MATCH_CASE_TYPES as t (t)}
<option value={t} selected={editing !== 'new' && editing.match_case_type === t}>
{t}
</option>
{/each}
</select>
</div>
<div class="v2-field">
<label for="a-team">Team</label>
<select id="a-team" class="v2-input" name="match_team_id">
<option value="" selected={editing === 'new' || !editing.match_team}>Any team</option>
{#each data.teams as t (t.id)}
<option value={t.id} selected={editing !== 'new' && editing.match_team?.id === t.id}>
{t.name}
</option>
{/each}
</select>
{#if !data.teams.length}
<p class="v2-hint">No teams in this org yet.</p>
{/if}
</div>
{#if editing === 'new'}
<div class="v2-field">
<label for="a-active">Active</label>
<label style="display:flex;gap:8px;align-items:center;font-weight:400">
<input id="a-active" type="checkbox" name="is_active" value="true" checked />
Starts gating matching ticket closes as soon as it is saved.
</label>
</div>
{/if}
{/snippet}
</SettingsFormPanel>
{/if}
{#if form?.deactivate?.error}
<p class="v2-error" style="margin-bottom:12px">{form.deactivate.error}</p>
{/if}
{#if form?.activate?.error}
<p class="v2-error" style="margin-bottom:12px">{form.activate.error}</p>
{/if}
{#if form?.remove?.error}
<p class="v2-error" style="margin-bottom:12px">{form.remove.error}</p>
{/if}
{#if form?.remove?.turned_off}
<!-- What actually happened, not what the button said. The backend
soft-disables a rule that has approval history rather than
destroying it, so the row is still in the list below, off, and
saying nothing here would read as a delete that failed silently. -->
<div class="v2-rule-flag" style="margin-bottom:12px">
<TriangleAlert size={14} style="color:var(--v2-clay);flex:none" />
<span>
That rule had approval history, so it was turned off instead of deleted. The approvals it
already gated have to keep pointing at it. It is still in the list below, marked Off, and
gates nothing.
</span>
</div>
{/if}
<div class="v2-label" style="margin-bottom:10px">Rules</div>
<div style="display:flex;flex-direction:column;gap:9px">
{#each rules as r (r.id)}
@ -76,7 +277,7 @@
<b style="font-weight:600;color:var(--v2-ink)">→</b>
cleared by
{#if r.approvers.length}
{r.approvers.join(' or ')}
{r.approvers.map((a) => a.email).join(' or ')}
{:else}
any {r.approver_role.toLowerCase()}
{/if}
@ -106,6 +307,45 @@
</a>
{/if}
</div>
{#if data.can_edit}
<div style="display:flex;gap:6px;align-items:center;flex:none">
<button class="v2-btn v2-btn-sm" type="button" onclick={() => openEdit(r)}>
Edit
</button>
{#if r.is_active}
<ConfirmAction
action="?/deactivate"
label="Turn off"
confirmLabel="Turn off"
explain="Stops gating new ticket closes. It stays in the list, off, until turned back on."
hidden={{ id: r.id }}
/>
{:else}
<form method="POST" action="?/activate" use:enhance>
<input type="hidden" name="id" value={r.id} />
<button class="v2-btn v2-btn-sm" type="submit">Turn on</button>
</form>
{/if}
<!-- Not "deleted permanently". The backend destroys a rule
only when it has never been used; one with any approval
history, in any state, is turned off instead, because the
approval rows have to keep pointing at it. `pending_count`
cannot predict which happens: it counts only the pending
state, and the backend's check counts every state. So the
line names both outcomes, and the page reports which one
actually happened afterwards. -->
<ConfirmAction
action="?/remove"
label="Delete"
confirmLabel="Delete"
explain={r.pending_count > 0
? `${r.pending_count} approvals are waiting on this rule. A rule that has ever gated a close is turned off rather than deleted, because the record has to be kept.`
: 'A rule that has never gated a close is deleted for good. One with any approval history is turned off instead, because the record has to be kept.'}
hidden={{ id: r.id }}
/>
</div>
{/if}
</div>
</div>
{/each}

View file

@ -1,4 +1,6 @@
import { getTimesheet } from '$lib/server/v2/timesheet.js';
import { fail } from '@sveltejs/kit';
import { getTimesheet, stopTimer } from '$lib/server/v2/timesheet.js';
import { readableError } from '$lib/server/v2/form-errors.js';
/**
* `?start=&end=` (YYYY-MM-DD) pick the week; absent, it defaults to this ISO
@ -11,3 +13,19 @@ export async function load({ cookies, url }) {
const end = url.searchParams.get('end') || undefined;
return await getTimesheet({ cookies }, { start, end });
}
/** @type {import('./$types').Actions} */
export const actions = {
async stop(event) {
const form = await event.request.formData();
const entryId = form.get('entry_id')?.toString() ?? '';
try {
await stopTimer(event, entryId);
} catch (/** @type {any} */ err) {
return fail(400, { error: readableError(err, 'Could not stop the timer.') });
}
return { stopped: true };
}
};

View file

@ -12,17 +12,31 @@
*/
import { onMount } from 'svelte';
import { goto } from '$app/navigation';
import { enhance } from '$app/forms';
import PageHeader from '$lib/v2/components/PageHeader.svelte';
import StatCard from '$lib/v2/components/StatCard.svelte';
import Pill from '$lib/v2/components/Pill.svelte';
import { money, count, shortDate } from '$lib/v2/format.js';
import { ChevronLeft, ChevronRight, Square, Receipt } from '@lucide/svelte';
/** @type {{ data: any }} */
let { data } = $props();
/** @type {{ data: any, form: any }} */
let { data, form } = $props();
let week = $derived(data.week);
// Disables every "Stop timer" button while a stop is in flight. Without
// this, a double-click fires two POSTs; the first stops the timer and the
// second gets a 400 "Timer is already stopped." back, so a successful stop
// reads as a failure.
let busy = $state(false);
const stopping = () => {
busy = true;
return async (/** @type {any} */ { update }) => {
await update();
busy = false;
};
};
/** Minutes elapsed since this page loaded, added to the server's figure. */
let sinceLoad = $state(0);
onMount(() => {
@ -141,17 +155,36 @@
<!-- The one thing on this page that changes while you look at it. -->
<div class="v2-next" style="margin-bottom:16px">
<div class="v2-next-body">
<div class="v2-label" style="color:var(--v2-ember)">Timer running</div>
<div class="v2-label" style="color:var(--v2-ember)">
{week.running_count === 1 ? 'Timer running' : `${week.running_count} timers running`}
</div>
{#if form?.error}
<!-- Stop can fail (ownership check, network). Silent failure here
would repeat the exact bug this page exists to fix: a timer
that keeps accruing time with nothing on screen saying so. -->
<p class="v2-error">{form.error}</p>
{/if}
<div class="v2-next-text">
{#each week.days as d (d.date)}
{#each d.entries.filter((e) => e.is_running) as e (e.id)}
<span class="v2-num">{hm(liveMinutes(e))}</span> on
<a href="/tickets/{e.case.id}" style="color:inherit">{e.case.name}</a>
<div class="v2-running-row">
<span>
<span class="v2-num">{hm(liveMinutes(e))}</span> on
<a href="/tickets/{e.case.id}" style="color:inherit">{e.case.name}</a>
</span>
<!-- One form per entry. A single shared button could not say
which of several running timers it meant. -->
<form method="POST" action="?/stop" use:enhance={stopping}>
<input type="hidden" name="entry_id" value={e.id} />
<button class="v2-btn v2-btn-primary" type="submit" disabled={busy}>
<Square size={13} />Stop timer
</button>
</form>
</div>
{/each}
{/each}
</div>
</div>
<button class="v2-btn v2-btn-primary"><Square size={13} />Stop timer</button>
</div>
{/if}
@ -220,3 +253,12 @@
</p>
</div>
</div>
<style>
.v2-running-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
</style>

View file

@ -1,45 +0,0 @@
/**
* SSE proxy.
*
* The browser cannot send custom headers via EventSource, so we proxy the
* stream through SvelteKit, where we can read the JWT cookie server-side
* and attach it as an Authorization header on the upstream fetch. The
* upstream Response body is piped straight through.
*/
import { env } from '$env/dynamic/public';
const API_BASE_URL = `${env.PUBLIC_DJANGO_API_URL}/api`;
/** @type {import('./$types').RequestHandler} */
export async function GET({ cookies, request }) {
const accessToken = cookies.get('jwt_access');
if (!accessToken) return new Response('Unauthorized', { status: 401 });
const upstream = await fetch(`${API_BASE_URL}/notifications/stream/`, {
method: 'GET',
headers: {
Authorization: `Bearer ${accessToken}`,
Accept: 'text/event-stream'
},
// Abort the upstream when the browser hangs up.
signal: request.signal
});
if (!upstream.ok || !upstream.body) {
return new Response(`Upstream error: ${upstream.status}`, {
status: upstream.status || 502
});
}
// Note: `Connection` is a hop-by-hop header, Node refuses to forward it
// and HTTP keep-alive is the default in HTTP/1.1 anyway. Don't set it.
return new Response(upstream.body, {
status: 200,
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache, no-transform',
'X-Accel-Buffering': 'no'
}
});
}

53
frontend/vitest.config.js Normal file
View file

@ -0,0 +1,53 @@
import { defineConfig } from 'vitest/config';
import path from 'node:path';
/**
* THE CEILING OF THIS HARNESS
*
* This is a bare Vite config, not the app's own `vite.config.js`, so none of
* SvelteKit's virtual modules exist here by default. Two aliases are wired in
* below because `$lib/server/v2/leads.js:26` and `$lib/api-helpers.js:8` both
* import `$env/dynamic/public` at module scope: it is a Vite virtual module
* generated at build/dev time, not a real file, so a plain `node`/vitest run
* cannot resolve it without a stand-in. `$lib` is aliased because
* `path.resolve('./src/lib')` is the only way to reach it outside SvelteKit's
* own resolution.
*
* That is as far as this config goes. It resolves `$lib` and
* `$env/dynamic/public` and nothing else: `$app/forms`, `$app/navigation`,
* `$env/static/*`, and `$env/dynamic/private` are all still unresolvable
* here, and there is no Svelte plugin, so `.svelte` files cannot be compiled
* at all. `include: ['src/**\/*.test.js']` will happily pick up a test placed
* anywhere under `src/`, including next to a route module or a component, but
* importing either from a test run through this config fails with an opaque
* "Failed to resolve import" rather than a clear "not supported here".
*
* This harness therefore covers server modules only (`$lib/server/v2/*.js`
* and similar, functions over `apiRequest` with no SvelteKit runtime
* dependency). Testing a route module (`+page.server.js`, which pulls in
* `$app/forms` via its actions) or a `.svelte` component means moving
* `test: {}` into the app's own `vite.config.js`, where the `sveltekit()`
* plugin already provides `$lib`, `$app/*`, `$env/*` and Svelte compilation
* for free. That is a real tradeoff, not a strict improvement: it also pulls
* `sentrySvelteKit()` and `tailwindcss()` into every test run, which this
* standalone config exists specifically to avoid.
*
* `path.resolve('./src/lib')` below resolves against `process.cwd()`, not
* against this file's location, so `pnpm test` (and `vitest` directly) must
* be run from `frontend/`. Running it from the repo root or from `src/`
* silently resolves `$lib` to the wrong place.
*/
export default defineConfig({
test: {
// Server modules only. They are plain functions over `apiRequest`, so they
// need no DOM, and a node environment keeps the run fast.
environment: 'node',
include: ['src/**/*.test.js']
},
resolve: {
alias: {
$lib: path.resolve('./src/lib'),
'$env/dynamic/public': path.resolve('./test/stubs/env-dynamic-public.js')
}
}
});

View file

@ -1,333 +0,0 @@
# BottleCRM MCP Server (`bcrm-mcp`)
`bcrm-mcp` is a standalone [Model Context Protocol](https://modelcontextprotocol.io)
server that lets an AI agent (Claude Desktop, Cursor, etc.) drive a BottleCRM
instance through its REST API.
It is a **thin HTTP client** of the CRM API. It does *not* import Django, has no
database access of its own, and runs as its own [`uv`](https://docs.astral.sh/uv/)
package. Every request is authenticated with a **Personal Access Token (PAT)**
and the agent acts **as the user who owns that token**: it inherits exactly that
user's role and org. All Row-Level Security, permission checks, and field
validation are enforced by the backend. The MCP server never bypasses tenant
isolation and adds no privileges of its own.
> **Transports.** `bcrm-mcp` runs in two modes, selected by `BCRM_TRANSPORT`:
>
> - **`stdio`** (default), the agent launches `bcrm-mcp` as a local subprocess
> and talks over stdin/stdout. The process acts as a single user, whose token
> is `BCRM_TOKEN`.
> - **`http`**, a hosted, multi-user server (e.g. mounted in the Django app at
> `/mcp`). It holds **no** server-side token; instead **every request
> authenticates with its own `Authorization: Bearer <pat>` header**, so each
> caller acts strictly as their own CRM identity. See
> [HTTP transport](#http-transport-hosted-multi-user) below.
>
> OAuth-based connect is planned for a later phase; today http mode uses a
> personal access token in the request header.
## Requirements
- Python 3.11+
- [`uv`](https://docs.astral.sh/uv/)
- A reachable BottleCRM backend (the community Django-CRM API)
- A BottleCRM Personal Access Token (`bcrm_pat_…`)
## Install & run
```bash
cd mcp_server
uv sync
BCRM_BASE_URL=http://localhost:8000 BCRM_TOKEN=bcrm_pat_… uv run bcrm-mcp
```
`uv sync` creates `.venv/` from `pyproject.toml` + `uv.lock`. `uv run bcrm-mcp`
launches the server over stdio (it will block waiting for an MCP client on
stdin. That is expected; normally your MCP client launches it for you).
### Configuration (environment variables)
| Variable | Required | Description |
| ---------------- | ------------------- | ---------------------------------------------------------------------------------------------------- |
| `BCRM_BASE_URL` | yes | Root URL of the CRM (the host, **not** an `/api/...` path), e.g. `http://localhost:8000`. |
| `BCRM_TRANSPORT` | no (default `stdio`)| `stdio` or `http`. See [HTTP transport](#http-transport-hosted-multi-user). |
| `BCRM_TOKEN` | stdio only | A Personal Access Token, `bcrm_pat_…`, sent as `Authorization: Bearer <token>`. **Required for stdio; must be unset for http** (where the token comes per-request from each caller's header). |
| `BCRM_HOST` | no (default `127.0.0.1`) | http only, bind address when serving standalone. |
| `BCRM_PORT` | no (default `8900`) | http only, bind port when serving standalone. |
| `BCRM_PATH` | no (default `/mcp`) | http only. Route the streamable endpoint is served at when serving standalone. |
In stdio mode, a missing `BCRM_BASE_URL` or `BCRM_TOKEN` exits immediately. In
http mode, a server-side `BCRM_TOKEN` is rejected (it would make every caller
share one identity).
## HTTP transport (hosted, multi-user)
In http mode the server is long-lived and serves many users at once. There is
no server-side token: **each request must carry its own
`Authorization: Bearer <bcrm_pat_…>` header**, and the server builds a fresh,
per-request client from that token, so every caller acts strictly as their own
CRM identity, with their own role and org. A request with no/invalid bearer
token is rejected before any API call is made.
There are two ways to run http mode:
**1. Mounted in the Django app (recommended).** The community backend mounts
this server at `/mcp` from `crm/asgi.py` when the optional `mcp` extra is
installed and the app is served under ASGI (uvicorn). Clients then connect to
`https://<your-api-host>/mcp`: see the hosted client config below.
```bash
# from Django-CRM/backend
uv sync --extra mcp # installs fastmcp + this package (editable)
BCRM_BASE_URL=http://127.0.0.1:8000 \
uv run uvicorn crm.asgi:application --host 0.0.0.0 --port 8000
# MCP is now at http://<host>:8000/mcp
```
Notes:
- The mount is **inactive under `runserver`/WSGI**. It only activates when you
serve `crm.asgi:application` under an ASGI server (uvicorn).
- `BCRM_BASE_URL` is the loopback the in-process tools call (defaults to
`http://127.0.0.1:8000`). Leave `BCRM_TOKEN` **unset**. Http mode takes the
token from each request. Set `BCRM_MCP_ENABLED=false` to disable the mount.
- **Edge auth:** any `/mcp` request without a well-formed `Authorization: Bearer`
header gets a `401` before reaching the MCP layer, even `initialize` and
tool listing require a token (the token's validity is then checked by the
backend on each API call).
**2. Standalone.** Run the server on its own port:
```bash
BCRM_TRANSPORT=http BCRM_BASE_URL=http://localhost:8000 \
BCRM_HOST=0.0.0.0 BCRM_PORT=8900 uv run bcrm-mcp
# streamable endpoint at http://localhost:8900/mcp
```
### Hosted client config (no install)
For clients that support remote MCP servers, point them at the URL and send the
token in a header, nothing to install:
```json
{
"mcpServers": {
"bottlecrm": {
"type": "http",
"url": "https://api.bottlecrm.io/mcp",
"headers": { "Authorization": "Bearer bcrm_pat_…" }
}
}
}
```
## Getting a Personal Access Token
A PAT identifies the user the agent acts as. Anyone holding the token has the
same CRM access as that user, scoped to their org. Treat it like a password.
### Option A: CRM web UI (recommended)
In the CRM go to **Settings → API Tokens**, create a token, and copy the
`bcrm_pat_…` value. **The raw token is shown only once at creation.** You can
revoke it from the same screen at any time. That page also shows ready-to-paste
config for each client below, pre-filled with your API host and token.
### Option B: Django shell (local / dev)
For a quick local token, mint one directly from the backend. This prints the raw
token once:
```bash
cd ../backend && uv run python manage.py shell -c "from common.models import Profile, PersonalAccessToken; p=Profile.objects.filter(role='ADMIN', is_active=True).first(); print(PersonalAccessToken.generate(p,'smoke')[0])"
```
The PAT table is created by the `common` app migrations, if you get a
`relation "personal_access_token" does not exist` error, run
`uv run python manage.py migrate common` first.
## Client configuration
Register `bcrm-mcp` in your AI client and pass `BCRM_BASE_URL` + `BCRM_TOKEN` as
environment variables. **Claude Desktop, Cursor, and Gemini CLI share the
identical `mcpServers` JSON schema**, only the config file differs. **Codex CLI
uses TOML.** Replace `http://localhost:8000` with your API host (e.g.
`https://api.bottlecrm.io`) and paste your `bcrm_pat_…` token.
| Client | Config file | Format |
| -------------- | ---------------------------------------------------------------------- | ------ |
| Claude Desktop | `claude_desktop_config.json` (Settings → Developer → Edit Config) | JSON |
| Cursor | `~/.cursor/mcp.json` (global) or `.cursor/mcp.json` (per project) | JSON |
| Gemini CLI | `~/.gemini/settings.json` | JSON |
| Codex CLI | `~/.codex/config.toml` | TOML |
### JSON clients (Claude Desktop / Cursor / Gemini CLI)
```json
{
"mcpServers": {
"bottlecrm": {
"command": "uvx",
"args": ["bcrm-mcp"],
"env": {
"BCRM_BASE_URL": "http://localhost:8000",
"BCRM_TOKEN": "bcrm_pat_…"
}
}
}
}
```
### Codex CLI (TOML)
```toml
[mcp_servers.bottlecrm]
command = "uvx"
args = ["bcrm-mcp"]
[mcp_servers.bottlecrm.env]
BCRM_BASE_URL = "http://localhost:8000"
BCRM_TOKEN = "bcrm_pat_…"
```
Restart the client after editing its config; it launches `bcrm-mcp` for you and
discovers the tools automatically.
### Until published: run from a local checkout
`bcrm-mcp` is not yet on PyPI, so point the command at this directory instead of
using `uvx`. Use `--directory` with an absolute path so it works regardless of
the client's working directory. For the JSON clients:
```json
{
"mcpServers": {
"bottlecrm": {
"command": "uv",
"args": ["run", "--directory", "/abs/path/to/mcp_server", "bcrm-mcp"],
"env": {
"BCRM_BASE_URL": "http://localhost:8000",
"BCRM_TOKEN": "bcrm_pat_…"
}
}
}
}
```
For Codex, set `command = "uv"` and
`args = ["run", "--directory", "/abs/path/to/mcp_server", "bcrm-mcp"]`.
(Equivalently, from inside `mcp_server` you can just run `uv run bcrm-mcp`.)
## Available tools
The server exposes **8 tools**. CRUD tools take an `entity` argument; supported
entities are: **leads, contacts, accounts, opportunities, tasks, cases,
invoices, solutions**.
| Tool | Kind | Description |
| -------------- | ----------- | --------------------------------------------------------------------------------------------------------------- |
| `crm_search` | read-only | List/search records of an entity. Supports `query`, `filters`, `limit`, `offset`. `limit` is capped at **50**. |
| `crm_get` | read-only | Fetch one record's full detail by `id`. |
| `crm_create` | write | Create a record from a `data` object (validated server-side by the API). |
| `crm_update` | write | Partially update a record (PATCH semantics) from a `data` object. |
| `crm_delete` | destructive | Delete a record. **Requires `confirm=true`**. Refuses to run otherwise. |
| `crm_action` | write | Run a non-CRUD action on a record (see `list_actions`), e.g. `convert`, `add_comment`, `send`. Outward-facing actions (`send`) **require `confirm=true`**. |
| `crm_describe` | read-only | Return an entity's fields, types, enums, and which are required. Derived from the live OpenAPI schema. |
| `list_actions` | read-only | Return the allowed non-CRUD actions for each entity. |
### Entity → actions / API path
| Entity | API path | Non-CRUD actions |
| --------------- | ------------------------- | ------------------------- |
| `leads` | `/api/leads/` | `convert`, `add_comment` |
| `contacts` | `/api/contacts/` | `add_comment` |
| `accounts` | `/api/accounts/` | `add_comment` |
| `opportunities` | `/api/opportunities/` | `add_comment` |
| `tasks` | `/api/tasks/` |. |
| `cases` | `/api/cases/` | `add_comment` |
| `invoices` | `/api/invoices/` | `send` |
| `solutions` | `/api/cases/solutions/` |. |
> Note: solutions are served under the **cases** app at `/api/cases/solutions/`,
> not at a top-level `/api/solutions/`.
>
> `send` is outward-facing (emails a customer), so `crm_action` requires
> `confirm=true` for it. See the security model below.
## Security model
- **The agent acts as the token owner.** A PAT carries no extra privileges; the
agent can do exactly what that user can do, in that user's org, and nothing
more.
- **The backend is the only trust boundary.** All RLS (tenant isolation),
RBAC/permission checks, and input validation happen server-side. The MCP
server forwards requests and surfaces the API's responses and errors verbatim;
it does not re-implement (or relax) any of those checks.
- **Read limits.** `crm_search` caps `limit` at 50 regardless of what the agent
requests, to avoid pulling unbounded result sets.
- **Destructive & outward-facing ops are gated.** `crm_delete` refuses to run
without `confirm=true`, and so do outward-facing actions like
`crm_action(..., action="send")` (which emails a customer), so a model can't
delete a record or send an invoice by accident.
- **Tokens are revocable.** Revoke a PAT from the CRM (Settings → API Tokens) to
immediately cut off an agent. Tokens may also carry an expiry.
- **Never commit a token.** Keep `BCRM_TOKEN` out of source control, logs, and
shared configs. Pass it via environment / your MCP client's `env` block.
## Manual smoke test
To exercise the real HTTP path without the full MCP stdio handshake, run the
plain async tool functions directly against a live backend:
1. Start (or confirm) a backend on `:8000` with the PAT migrations applied:
```bash
cd ../backend
uv run python manage.py migrate common # ensures personal_access_token table exists
uv run python manage.py runserver 8000
```
2. Mint a PAT (Option B above) and copy the printed `bcrm_pat_…`.
3. Run a throwaway script against the live API:
```bash
cd ../mcp_server
BCRM_BASE_URL=http://localhost:8000 BCRM_TOKEN=bcrm_pat_… uv run python - <<'PY'
import asyncio, json, os
from bcrm_mcp.client import CrmClient
from bcrm_mcp import tools
async def main():
client = CrmClient(os.environ["BCRM_BASE_URL"], os.environ["BCRM_TOKEN"])
print(await tools.crm_search(client, "leads", limit=5))
print(json.dumps(await tools.crm_describe(client, "leads"), indent=2))
asyncio.run(main())
PY
```
`crm_search` should return a paginated list payload, and `crm_describe`
should return a non-empty field map for the `Lead` schema component.
## Development
```bash
uv sync
uv run pytest # unit tests (client, tools, entities, server registration)
uv run black . && uv run isort .
```
Layout:
```
mcp_server/
├── src/bcrm_mcp/
│ ├── server.py # FastMCP server, ClientResolver, `bcrm-mcp` entry + build_http_app
│ ├── tools.py # the 8 tool implementations + OpenAPI describe heuristic
│ ├── client.py # async httpx wrapper (CrmClient)
│ ├── entities.py # entity → path / allowed-action registry
│ ├── auth.py # per-request bearer-token extraction (http transport)
│ └── config.py # env-var settings (transport, BCRM_BASE_URL, BCRM_TOKEN, …)
└── tests/
```

View file

@ -1,20 +0,0 @@
[project]
name = "bcrm-mcp"
version = "0.1.0"
description = "BottleCRM MCP server: connect your AI agent to BottleCRM"
requires-python = ">=3.11"
dependencies = ["fastmcp>=3.4.4", "httpx>=0.28.1", "pydantic>=2.13.4"]
[project.scripts]
bcrm-mcp = "bcrm_mcp.server:main"
[dependency-groups]
dev = ["pytest>=9.1.1", "pytest-asyncio>=1.4.0", "respx>=0.23.1"]
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[tool.pytest.ini_options]
asyncio_mode = "auto"
pythonpath = ["src"]

View file

@ -1 +0,0 @@
__version__ = "0.1.0"

View file

@ -1,36 +0,0 @@
"""Per-request authentication for the http transport.
In http mode every MCP request carries the caller's own Personal Access Token
in the ``Authorization`` header. The server builds a fresh CrmClient from THAT
token for each call, so every caller acts strictly as their own CRM identity
(their role, their org). The server holds no shared token in http mode,
caching or reusing a client across requests would collapse all callers into a
single identity and break tenant isolation, so we deliberately never do it.
"""
class AuthError(Exception):
"""Raised when an http-mode request carries no usable bearer token."""
_BEARER = "bearer " # scheme prefix, compared case-insensitively
def extract_bearer_token(headers):
"""Return the PAT from an ``Authorization: Bearer <token>`` header.
``headers`` is the mapping returned by FastMCP's ``get_http_headers`` (keys
already lowercased). Returns the token string, or ``None`` when the header
is absent, not a Bearer scheme, or empty. Never raises, callers decide how
to handle a missing token.
"""
if not headers:
return None
raw = headers.get("authorization") or headers.get("Authorization")
if not raw:
return None
value = raw.strip()
if value[: len(_BEARER)].lower() != _BEARER:
return None
token = value[len(_BEARER) :].strip()
return token or None

Some files were not shown because too many files have changed in this diff Show more