# ConnectWise PSA Integration — Implementation Plan

> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.

**Goal:** Integrate ResolutionFlow with ConnectWise PSA so engineers can post session documentation directly to CW tickets, with credential management, ticket linking, search, note posting, and member mapping.

**Architecture:** PSA abstraction layer (`services/psa/`) with abstract `PSAProvider` interface + ConnectWise implementation. Fernet-encrypted credentials stored per-account. 5 incremental slices: Foundation → Ticket Linking → Ticket Search → Update Ticket Modal → Member Mapping.

**Tech Stack:** FastAPI, SQLAlchemy 2.0, httpx (async HTTP client for CW API), cryptography (Fernet), React, TypeScript, Tailwind CSS

**Design doc:** `docs/superpowers/specs/2026-03-14-connectwise-psa-integration-design.md`

**Reference docs:** `docs/connectwise/` — read `CONNECTWISE-API-REFERENCE.md` first, then best-practices files before implementing CW client.

---

## Slice 1: Foundation

### Task 1: PSA abstraction layer — base types and abstract interface

**Files:**
- Create: `backend/app/services/psa/__init__.py`
- Create: `backend/app/services/psa/base.py`
- Create: `backend/app/services/psa/types.py`
- Create: `backend/app/services/psa/exceptions.py`

**Step 1: Create the package**

Create `backend/app/services/psa/__init__.py`:

```python
"""PSA integration abstraction layer."""
```

**Step 2: Create PSA exception types**

Create `backend/app/services/psa/exceptions.py`:

```python
"""Typed exceptions for PSA integration errors."""


class PSAError(Exception):
    """Base exception for all PSA integration errors."""
    def __init__(self, message: str, provider: str = "unknown"):
        self.provider = provider
        super().__init__(message)


class PSAAuthError(PSAError):
    """Invalid or expired credentials."""
    pass


class PSAPermissionError(PSAError):
    """Insufficient permissions on the PSA side."""
    pass


class PSANotFoundError(PSAError):
    """Requested resource (ticket, company, etc.) not found."""
    pass


class PSARateLimitError(PSAError):
    """Rate limit exceeded. retry_after_seconds may be set."""
    def __init__(self, message: str, retry_after_seconds: int | None = None, provider: str = "unknown"):
        self.retry_after_seconds = retry_after_seconds
        super().__init__(message, provider)


class PSAServerError(PSAError):
    """Remote PSA server error (5xx)."""
    pass


class PSATimeoutError(PSAError):
    """Request to PSA timed out."""
    pass


class PSAConnectionError(PSAError):
    """Cannot reach the PSA server."""
    pass
```

**Step 3: Create normalized PSA types**

Create `backend/app/services/psa/types.py`:

```python
"""Provider-agnostic PSA data types."""
from __future__ import annotations

from pydantic import BaseModel


class ConnectionTestResult(BaseModel):
    success: bool
    message: str
    server_version: str | None = None


class PSATicket(BaseModel):
    id: str
    summary: str
    company_name: str | None = None
    company_id: str | None = None
    board_name: str | None = None
    board_id: int | None = None
    status_name: str | None = None
    status_id: int | None = None
    priority_name: str | None = None
    priority_id: int | None = None
    closed: bool = False


class PSANote(BaseModel):
    id: str
    text: str
    note_type: str
    created_at: str | None = None


class PSAStatus(BaseModel):
    id: int
    name: str
    is_closed: bool = False


class PSACompany(BaseModel):
    id: str
    name: str
    status: str | None = None


class PSAMember(BaseModel):
    id: str
    identifier: str  # CW login username
    name: str
    email: str | None = None


class PSAConfiguration(BaseModel):
    id: str
    name: str
    type: str | None = None
    company_name: str | None = None


class NoteType:
    INTERNAL_ANALYSIS = "internal_analysis"
    RESOLUTION = "resolution"
    DESCRIPTION = "description"
```

**Step 4: Create abstract PSAProvider interface**

Create `backend/app/services/psa/base.py`:

```python
"""Abstract base class for PSA provider implementations."""
from __future__ import annotations

from abc import ABC, abstractmethod

from .types import (
    ConnectionTestResult,
    PSATicket,
    PSANote,
    PSAStatus,
    PSACompany,
    PSAMember,
    PSAConfiguration,
)


class PSAProvider(ABC):
    """Abstract base for PSA integrations (ConnectWise, Autotask, etc.)."""

    @abstractmethod
    async def test_connection(self) -> ConnectionTestResult:
        ...

    @abstractmethod
    async def get_ticket(self, ticket_id: str) -> PSATicket:
        ...

    @abstractmethod
    async def search_tickets(self, query: str, **filters) -> list[PSATicket]:
        ...

    @abstractmethod
    async def post_note(
        self,
        ticket_id: str,
        text: str,
        note_type: str,
        member_id: str | None = None,
    ) -> PSANote:
        ...

    @abstractmethod
    async def update_ticket_status(
        self,
        ticket_id: str,
        status_id: int,
    ) -> PSATicket:
        ...

    @abstractmethod
    async def get_ticket_statuses(self, board_id: int) -> list[PSAStatus]:
        ...

    @abstractmethod
    async def list_companies(self, **filters) -> list[PSACompany]:
        ...

    @abstractmethod
    async def get_company(self, company_id: str) -> PSACompany:
        ...

    @abstractmethod
    async def list_members(self) -> list[PSAMember]:
        ...

    @abstractmethod
    async def get_ticket_configurations(self, ticket_id: str) -> list[PSAConfiguration]:
        ...
```

**Step 5: Run tests to verify no import errors**

Run: `cd backend && python -c "from app.services.psa.base import PSAProvider; print('OK')"`
Expected: `OK`

**Step 6: Commit**

```bash
git add backend/app/services/psa/
git commit -m "feat(psa): add PSA abstraction layer — base types, exceptions, abstract interface"
```

---

### Task 2: Credential encryption utilities

**Files:**
- Create: `backend/app/services/psa/encryption.py`
- Create: `backend/tests/test_psa_encryption.py`

**Step 1: Write the failing test**

Create `backend/tests/test_psa_encryption.py`:

```python
"""Tests for PSA credential encryption/decryption."""
import pytest
from app.services.psa.encryption import encrypt_credentials, decrypt_credentials


class TestCredentialEncryption:
    def test_round_trip(self):
        """Encrypt then decrypt returns original credentials."""
        creds = {
            "public_key": "abc123",
            "private_key": "secret456",
            "client_id": "my-client-id",
        }
        encrypted = encrypt_credentials(creds)

        # Encrypted should be a non-empty string, different from input
        assert isinstance(encrypted, str)
        assert len(encrypted) > 0
        assert "secret456" not in encrypted

        decrypted = decrypt_credentials(encrypted)
        assert decrypted == creds

    def test_different_inputs_produce_different_outputs(self):
        creds1 = {"public_key": "key1", "private_key": "priv1", "client_id": "cid1"}
        creds2 = {"public_key": "key2", "private_key": "priv2", "client_id": "cid2"}

        enc1 = encrypt_credentials(creds1)
        enc2 = encrypt_credentials(creds2)
        assert enc1 != enc2

    def test_tampered_ciphertext_raises(self):
        creds = {"public_key": "k", "private_key": "p", "client_id": "c"}
        encrypted = encrypt_credentials(creds)
        tampered = encrypted[:-5] + "XXXXX"
        with pytest.raises(Exception):
            decrypt_credentials(tampered)

    def test_mask_private_key(self):
        from app.services.psa.encryption import mask_credential
        assert mask_credential("abcdefghij") == "••••••ghij"
        assert mask_credential("abc") == "••••••abc"
        assert mask_credential("") == "••••••"
        assert mask_credential(None) == "••••••"
```

**Step 2: Run test to verify it fails**

Run: `cd backend && python -m pytest tests/test_psa_encryption.py -v`
Expected: FAIL (module not found)

**Step 3: Implement encryption utilities**

Create `backend/app/services/psa/encryption.py`:

```python
"""Fernet-based credential encryption for PSA connections.

Uses the application SECRET_KEY to derive a Fernet encryption key via HKDF.
Credentials are stored as a single encrypted JSON blob.
"""
from __future__ import annotations

import json
import base64

from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.hkdf import HKDF

from app.core.config import settings


def _get_fernet() -> Fernet:
    """Derive a Fernet key from the application SECRET_KEY."""
    hkdf = HKDF(
        algorithm=hashes.SHA256(),
        length=32,
        salt=b"resolutionflow-psa-credentials",
        info=b"psa-credential-encryption",
    )
    key = hkdf.derive(settings.SECRET_KEY.encode())
    fernet_key = base64.urlsafe_b64encode(key)
    return Fernet(fernet_key)


def encrypt_credentials(credentials: dict) -> str:
    """Encrypt a credentials dict to a Fernet token string."""
    f = _get_fernet()
    plaintext = json.dumps(credentials).encode()
    return f.encrypt(plaintext).decode()


def decrypt_credentials(encrypted: str) -> dict:
    """Decrypt a Fernet token string back to a credentials dict."""
    f = _get_fernet()
    plaintext = f.decrypt(encrypted.encode())
    return json.loads(plaintext)


def mask_credential(value: str | None, visible_suffix: int = 4) -> str:
    """Return a masked version of a credential for display.
    e.g., 'abcdefghij' → '••••••ghij'
    """
    if not value:
        return "••••••"
    if len(value) <= visible_suffix:
        return "••••••" + value
    return "••••••" + value[-visible_suffix:]
```

**Step 4: Run test to verify it passes**

Run: `cd backend && python -m pytest tests/test_psa_encryption.py -v`
Expected: PASS (4 tests)

**Step 5: Commit**

```bash
git add backend/app/services/psa/encryption.py backend/tests/test_psa_encryption.py
git commit -m "feat(psa): add Fernet credential encryption with HKDF key derivation"
```

---

### Task 3: PsaConnection model and migration

**Files:**
- Create: `backend/app/models/psa_connection.py`
- Modify: `backend/app/models/__init__.py`
- Modify: `backend/alembic/env.py`
- Create: `backend/alembic/versions/058_add_psa_connections.py`

**Step 1: Create the model**

Create `backend/app/models/psa_connection.py`:

```python
"""PSA connection model — one per account."""
import uuid
from datetime import datetime, timezone
from typing import Optional

from sqlalchemy import String, DateTime, Boolean, Text, ForeignKey
from sqlalchemy.orm import Mapped, mapped_column, relationship
from sqlalchemy.dialects.postgresql import UUID

from app.core.database import Base


class PsaConnection(Base):
    __tablename__ = "psa_connections"

    id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True), primary_key=True, default=uuid.uuid4
    )
    account_id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True),
        ForeignKey("accounts.id", ondelete="CASCADE"),
        nullable=False,
        unique=True,
        index=True,
    )
    provider: Mapped[str] = mapped_column(String(50), nullable=False)
    display_name: Mapped[str] = mapped_column(String(100), nullable=False)
    site_url: Mapped[str] = mapped_column(String(255), nullable=False)
    company_id: Mapped[str] = mapped_column(String(100), nullable=False)
    credentials_encrypted: Mapped[str] = mapped_column(Text, nullable=False)
    is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
    last_validated_at: Mapped[Optional[datetime]] = mapped_column(
        DateTime(timezone=True), nullable=True
    )
    created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True),
        nullable=False,
        default=lambda: datetime.now(timezone.utc),
    )
    updated_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True),
        nullable=False,
        default=lambda: datetime.now(timezone.utc),
        onupdate=lambda: datetime.now(timezone.utc),
    )

    # Relationships
    account = relationship("Account", back_populates="psa_connection")
```

**Step 2: Register in `__init__.py`**

Add to `backend/app/models/__init__.py`:

```python
from app.models.psa_connection import PsaConnection
```

**Step 3: Import in `alembic/env.py`**

Add to `backend/alembic/env.py` after the existing model imports:

```python
from app.models.psa_connection import PsaConnection  # noqa: F401
```

**Step 4: Add back_populates to Account model**

Find the Account model and add:

```python
psa_connection = relationship("PsaConnection", back_populates="account", uselist=False)
```

**Step 5: Write migration manually**

Create `backend/alembic/versions/058_add_psa_connections.py`:

```python
"""Add psa_connections table.

Revision ID: 058
Revises: 057
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

revision = "058"
down_revision = "057"
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.create_table(
        "psa_connections",
        sa.Column("id", postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column("account_id", postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column("provider", sa.String(50), nullable=False),
        sa.Column("display_name", sa.String(100), nullable=False),
        sa.Column("site_url", sa.String(255), nullable=False),
        sa.Column("company_id", sa.String(100), nullable=False),
        sa.Column("credentials_encrypted", sa.Text(), nullable=False),
        sa.Column("is_active", sa.Boolean(), nullable=False, server_default=sa.text("true")),
        sa.Column("last_validated_at", sa.DateTime(timezone=True), nullable=True),
        sa.Column("created_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
        sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
        sa.PrimaryKeyConstraint("id"),
        sa.ForeignKeyConstraint(["account_id"], ["accounts.id"], ondelete="CASCADE"),
        sa.UniqueConstraint("account_id"),
    )
    op.create_index("ix_psa_connections_account_id", "psa_connections", ["account_id"])


def downgrade() -> None:
    op.drop_index("ix_psa_connections_account_id")
    op.drop_table("psa_connections")
```

**Step 6: Verify migration chain**

IMPORTANT: Check that migration 057's `revision` and `down_revision` values match. Open `backend/alembic/versions/057_add_script_templates.py` and verify the `revision` value — the 058 migration's `down_revision` must match it exactly. The 057 migration may use a hash-style revision ID instead of `"057"`.

Run: `cd backend && python -c "from alembic.config import Config; from alembic import command; command.check(Config('alembic.ini'))" 2>&1 || echo "Check alembic heads"`

If the revision IDs don't match, update `058`'s `down_revision` accordingly.

**Step 7: Run migration**

Run: `docker exec resolutionflow_backend alembic upgrade head`
Expected: SUCCESS

**Step 8: Commit**

```bash
git add backend/app/models/psa_connection.py backend/app/models/__init__.py backend/alembic/env.py backend/alembic/versions/058_add_psa_connections.py
git commit -m "feat(psa): add PsaConnection model and migration 058"
```

---

### Task 4: ConnectWise HTTP client

**Files:**
- Create: `backend/app/services/psa/connectwise/__init__.py`
- Create: `backend/app/services/psa/connectwise/client.py`

**IMPORTANT:** Before implementing, read these reference docs:
- `docs/connectwise/best-practices/PSA-API-Requests.md` — HTTP methods, response codes, condition query syntax
- `docs/connectwise/best-practices/PSA-Cloud-URL-Formatting.md` — Dynamic base URL construction
- `docs/connectwise/best-practices/PSA-Pagination.md` — Pagination patterns
- `docs/connectwise/best-practices/PSA-Versioning.md` — Pin API version via Accept header
- `docs/connectwise/CONNECTWISE-API-REFERENCE.md` — Auth patterns, endpoint map

**Step 1: Create package**

Create `backend/app/services/psa/connectwise/__init__.py`:

```python
"""ConnectWise PSA provider implementation."""
```

**Step 2: Create the HTTP client**

Create `backend/app/services/psa/connectwise/client.py`:

```python
"""Low-level HTTP client for ConnectWise PSA REST API.

Handles auth headers, base URL resolution (cloud vs on-premise),
pagination, retry with backoff, and error mapping.
"""
from __future__ import annotations

import base64
import logging
from typing import Any

import httpx

from app.services.psa.exceptions import (
    PSAAuthError,
    PSANotFoundError,
    PSAPermissionError,
    PSARateLimitError,
    PSAServerError,
    PSATimeoutError,
    PSAConnectionError,
)

logger = logging.getLogger(__name__)

# Pinned CW API version per best-practices/PSA-Versioning.md
CW_API_VERSION = "2025.16"
CW_ACCEPT_HEADER = f"application/vnd.connectwise.com+json; version={CW_API_VERSION}"

# Known CW cloud domains (for SSRF prevention)
CW_ALLOWED_DOMAINS = {
    "myconnectwise.net",
    "connectwisedev.com",
}

REQUEST_TIMEOUT = 30.0
MAX_RETRIES = 2
MAX_PAGE_SIZE = 1000


def _validate_site_url(site_url: str) -> None:
    """Validate site_url is a known CW domain (SSRF prevention)."""
    import ipaddress
    import socket
    from urllib.parse import urlparse

    # Ensure scheme
    url = site_url if "://" in site_url else f"https://{site_url}"
    parsed = urlparse(url)
    hostname = parsed.hostname or ""

    # Check against allowed domains
    if not any(hostname.endswith(f".{domain}") or hostname == domain for domain in CW_ALLOWED_DOMAINS):
        raise PSAConnectionError(
            f"Invalid ConnectWise site URL: {hostname}. Must be a *.myconnectwise.net or *.connectwisedev.com domain.",
            provider="connectwise",
        )

    # Resolve and check for private IPs
    try:
        addrs = socket.getaddrinfo(hostname, None)
        for _, _, _, _, sockaddr in addrs:
            ip = ipaddress.ip_address(sockaddr[0])
            if ip.is_private or ip.is_loopback or ip.is_link_local:
                raise PSAConnectionError(
                    f"Site URL resolves to a private/internal address: {sockaddr[0]}",
                    provider="connectwise",
                )
    except socket.gaierror:
        raise PSAConnectionError(
            f"Cannot resolve hostname: {hostname}",
            provider="connectwise",
        )


class ConnectWiseClient:
    """Async HTTP client for the ConnectWise PSA API."""

    def __init__(
        self,
        site_url: str,
        company_id: str,
        public_key: str,
        private_key: str,
        client_id: str,
    ):
        self.site_url = site_url.rstrip("/")
        self.company_id = company_id
        self.client_id = client_id

        # Auth: Base64(companyId+publicKey:privateKey)
        auth_string = f"{company_id}+{public_key}:{private_key}"
        self._auth_b64 = base64.b64encode(auth_string.encode()).decode()

        # Base URL resolved lazily on first request
        self._base_url: str | None = None

    async def _resolve_base_url(self) -> str:
        """Resolve the CW API base URL using /login/companyinfo/{companyId}.

        Cloud environments return a versioned codebase (e.g., v2025_3/) requiring
        an 'api-' prefix on the hostname. On-premise returns v4_6_release/ with
        no prefix needed.
        """
        if self._base_url:
            return self._base_url

        _validate_site_url(self.site_url)

        info_url = f"https://{self.site_url}/login/companyinfo/{self.company_id}"

        async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT) as client:
            try:
                resp = await client.get(info_url)
                resp.raise_for_status()
            except httpx.TimeoutException:
                raise PSATimeoutError("Timed out resolving CW base URL", provider="connectwise")
            except httpx.HTTPError as e:
                raise PSAConnectionError(f"Failed to resolve CW base URL: {e}", provider="connectwise")

        data = resp.json()
        codebase = data.get("Codebase", "v4_6_release/")
        site_url = data.get("SiteUrl", self.site_url)

        # Cloud codebase (e.g., v2025_3/) requires api- prefix
        if codebase != "v4_6_release/":
            if not site_url.startswith("api-"):
                site_url = f"api-{site_url}"

        self._base_url = f"https://{site_url}/{codebase}apis/3.0"
        logger.info("Resolved CW base URL: %s", self._base_url)
        return self._base_url

    def _headers(self) -> dict[str, str]:
        return {
            "Authorization": f"Basic {self._auth_b64}",
            "clientId": self.client_id,
            "Accept": CW_ACCEPT_HEADER,
            "Content-Type": "application/json",
        }

    async def _request(
        self,
        method: str,
        path: str,
        *,
        params: dict[str, Any] | None = None,
        json_body: Any = None,
        retries: int = MAX_RETRIES,
    ) -> Any:
        """Make an authenticated request to the CW API with retry and error mapping."""
        base_url = await self._resolve_base_url()
        url = f"{base_url}/{path.lstrip('/')}"

        async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT) as client:
            for attempt in range(retries + 1):
                try:
                    resp = await client.request(
                        method,
                        url,
                        headers=self._headers(),
                        params=params,
                        json=json_body,
                    )
                except httpx.TimeoutException:
                    if attempt < retries:
                        continue
                    raise PSATimeoutError("ConnectWise request timed out", provider="connectwise")
                except httpx.ConnectError:
                    raise PSAConnectionError("Cannot reach ConnectWise server", provider="connectwise")

                # Rate limit — retry with backoff
                if resp.status_code == 429:
                    if attempt < retries:
                        import asyncio
                        retry_after = int(resp.headers.get("Retry-After", "5"))
                        await asyncio.sleep(retry_after)
                        continue
                    raise PSARateLimitError(
                        "ConnectWise rate limit exceeded",
                        retry_after_seconds=int(resp.headers.get("Retry-After", "60")),
                        provider="connectwise",
                    )

                # Map error codes
                if resp.status_code == 401:
                    raise PSAAuthError("Invalid credentials. Check your API keys.", provider="connectwise")
                if resp.status_code == 403:
                    raise PSAPermissionError(
                        "Insufficient permissions. Check the API member's security role.",
                        provider="connectwise",
                    )
                if resp.status_code == 404:
                    raise PSANotFoundError("Resource not found.", provider="connectwise")
                if resp.status_code >= 500:
                    if attempt < retries:
                        continue
                    raise PSAServerError("ConnectWise is experiencing issues. Try again.", provider="connectwise")

                resp.raise_for_status()
                if resp.status_code == 204:
                    return None
                return resp.json()

    async def get(self, path: str, params: dict[str, Any] | None = None) -> Any:
        return await self._request("GET", path, params=params)

    async def post(self, path: str, json_body: Any = None) -> Any:
        return await self._request("POST", path, json_body=json_body)

    async def patch(self, path: str, json_body: Any = None) -> Any:
        """CW PATCH uses JSON Patch array format: [{"op": "replace", "path": "field", "value": ...}]"""
        return await self._request("PATCH", path, json_body=json_body)

    async def delete(self, path: str) -> Any:
        return await self._request("DELETE", path)

    async def get_paginated(
        self,
        path: str,
        params: dict[str, Any] | None = None,
        max_pages: int = 10,
    ) -> list[Any]:
        """Fetch all pages of a paginated CW endpoint."""
        params = dict(params or {})
        params.setdefault("pageSize", MAX_PAGE_SIZE)
        all_results: list[Any] = []

        for page in range(1, max_pages + 1):
            params["page"] = page
            results = await self.get(path, params=params)
            if not results:
                break
            all_results.extend(results)
            if len(results) < params["pageSize"]:
                break

        return all_results
```

**Step 3: Run build verification**

Run: `cd backend && python -c "from app.services.psa.connectwise.client import ConnectWiseClient; print('OK')"`
Expected: `OK`

**Step 4: Commit**

```bash
git add backend/app/services/psa/connectwise/
git commit -m "feat(psa): add ConnectWise HTTP client with auth, URL resolution, pagination, retry"
```

---

### Task 5: ConnectWise provider — test_connection

**Files:**
- Create: `backend/app/services/psa/connectwise/provider.py`
- Create: `backend/app/services/psa/registry.py`
- Create: `backend/tests/test_psa_connection.py`

**Step 1: Create the provider (test_connection only)**

Create `backend/app/services/psa/connectwise/provider.py`:

```python
"""ConnectWise implementation of PSAProvider."""
from __future__ import annotations

from app.services.psa.base import PSAProvider
from app.services.psa.types import (
    ConnectionTestResult,
    PSATicket,
    PSANote,
    PSAStatus,
    PSACompany,
    PSAMember,
    PSAConfiguration,
)
from .client import ConnectWiseClient


class ConnectWiseProvider(PSAProvider):
    """ConnectWise PSA provider implementation."""

    def __init__(self, client: ConnectWiseClient):
        self.client = client

    async def test_connection(self) -> ConnectionTestResult:
        """Test the CW connection by fetching system info."""
        try:
            info = await self.client.get("/system/info")
            return ConnectionTestResult(
                success=True,
                message="Connected successfully.",
                server_version=info.get("version", None),
            )
        except Exception as e:
            return ConnectionTestResult(
                success=False,
                message=str(e),
                server_version=None,
            )

    # ── Stubs for Phase A slices 2-5 ─────────────────────────────────

    async def get_ticket(self, ticket_id: str) -> PSATicket:
        raise NotImplementedError("Implemented in Slice 2")

    async def search_tickets(self, query: str, **filters) -> list[PSATicket]:
        raise NotImplementedError("Implemented in Slice 3")

    async def post_note(self, ticket_id: str, text: str, note_type: str, member_id: str | None = None) -> PSANote:
        raise NotImplementedError("Implemented in Slice 4")

    async def update_ticket_status(self, ticket_id: str, status_id: int) -> PSATicket:
        raise NotImplementedError("Implemented in Slice 4")

    async def get_ticket_statuses(self, board_id: int) -> list[PSAStatus]:
        raise NotImplementedError("Implemented in Slice 3")

    async def list_companies(self, **filters) -> list[PSACompany]:
        raise NotImplementedError("Implemented in Slice 3")

    async def get_company(self, company_id: str) -> PSACompany:
        raise NotImplementedError("Implemented in Slice 3")

    async def list_members(self) -> list[PSAMember]:
        raise NotImplementedError("Implemented in Slice 5")

    async def get_ticket_configurations(self, ticket_id: str) -> list[PSAConfiguration]:
        raise NotImplementedError("Implemented in Slice 3")
```

**Step 2: Create the provider registry**

Create `backend/app/services/psa/registry.py`:

```python
"""Factory for instantiating PSA providers from stored connection data."""
from __future__ import annotations

from uuid import UUID

from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.models.psa_connection import PsaConnection
from app.services.psa.base import PSAProvider
from app.services.psa.encryption import decrypt_credentials
from app.services.psa.exceptions import PSAConnectionError


async def get_provider_for_account(account_id: UUID, db: AsyncSession) -> PSAProvider:
    """Look up account's PSA connection, decrypt credentials, instantiate provider."""
    result = await db.execute(
        select(PsaConnection).where(
            PsaConnection.account_id == account_id,
            PsaConnection.is_active.is_(True),
        )
    )
    connection = result.scalar_one_or_none()

    if not connection:
        raise PSAConnectionError(
            "No active PSA connection configured for this account.",
            provider="unknown",
        )

    if connection.provider == "connectwise":
        from app.services.psa.connectwise.client import ConnectWiseClient
        from app.services.psa.connectwise.provider import ConnectWiseProvider

        creds = decrypt_credentials(connection.credentials_encrypted)
        client = ConnectWiseClient(
            site_url=connection.site_url,
            company_id=connection.company_id,
            public_key=creds["public_key"],
            private_key=creds["private_key"],
            client_id=creds["client_id"],
        )
        return ConnectWiseProvider(client)

    raise PSAConnectionError(
        f"Unsupported PSA provider: {connection.provider}",
        provider=connection.provider,
    )
```

**Step 3: Commit**

```bash
git add backend/app/services/psa/connectwise/provider.py backend/app/services/psa/registry.py
git commit -m "feat(psa): add ConnectWiseProvider with test_connection + provider registry"
```

---

### Task 6: Pydantic schemas for PSA connections

**Files:**
- Create: `backend/app/schemas/psa_connection.py`
- Modify: `backend/app/schemas/__init__.py`

**Step 1: Create schemas**

Create `backend/app/schemas/psa_connection.py`:

```python
"""Pydantic schemas for PSA connection management."""
from __future__ import annotations

from datetime import datetime
from uuid import UUID

from pydantic import BaseModel, Field


class PsaConnectionCreate(BaseModel):
    provider: str = Field(default="connectwise", pattern="^(connectwise|autotask)$")
    display_name: str = Field(min_length=1, max_length=100)
    site_url: str = Field(min_length=1, max_length=255)
    company_id: str = Field(min_length=1, max_length=100)
    public_key: str = Field(min_length=1)
    private_key: str = Field(min_length=1)
    client_id: str = Field(min_length=1)


class PsaConnectionUpdate(BaseModel):
    display_name: str | None = None
    site_url: str | None = None
    company_id: str | None = None
    public_key: str | None = None
    private_key: str | None = None
    client_id: str | None = None


class PsaConnectionResponse(BaseModel):
    id: UUID
    account_id: UUID
    provider: str
    display_name: str
    site_url: str
    company_id: str
    is_active: bool
    last_validated_at: datetime | None
    created_at: datetime
    updated_at: datetime
    # Redacted credential hints (never expose full keys)
    public_key_hint: str  # e.g., "••••••abc1"
    private_key_hint: str

    model_config = {"from_attributes": True}


class PsaConnectionTestResponse(BaseModel):
    success: bool
    message: str
    server_version: str | None = None
```

**Step 2: Register in schemas __init__**

Add to `backend/app/schemas/__init__.py`:

```python
from app.schemas.psa_connection import (
    PsaConnectionCreate,
    PsaConnectionUpdate,
    PsaConnectionResponse,
    PsaConnectionTestResponse,
)
```

**Step 3: Commit**

```bash
git add backend/app/schemas/psa_connection.py backend/app/schemas/__init__.py
git commit -m "feat(psa): add Pydantic schemas for PSA connection CRUD"
```

---

### Task 7: PSA connection API endpoints

**Files:**
- Create: `backend/app/api/endpoints/integrations.py`
- Modify: `backend/app/api/router.py`
- Create: `backend/tests/test_psa_connections.py`

**Step 1: Write tests**

Create `backend/tests/test_psa_connections.py`:

```python
"""Integration tests for PSA connection CRUD endpoints."""
import pytest
from httpx import AsyncClient

pytestmark = pytest.mark.anyio


class TestPsaConnectionCRUD:
    """Tests for /integrations/psa/connections endpoints."""

    async def test_get_connection_empty(self, client: AsyncClient, auth_headers: dict):
        """GET returns null when no connection exists."""
        resp = await client.get("/api/v1/integrations/psa/connections", headers=auth_headers)
        assert resp.status_code == 200
        assert resp.json() is None

    async def test_create_connection_requires_owner(self, client: AsyncClient, auth_headers: dict):
        """Non-owner users cannot create connections."""
        # Default test user is an engineer, not owner
        resp = await client.post(
            "/api/v1/integrations/psa/connections",
            headers=auth_headers,
            json={
                "provider": "connectwise",
                "display_name": "Test CW",
                "site_url": "na.myconnectwise.net",
                "company_id": "testco",
                "public_key": "pub123",
                "private_key": "priv456",
                "client_id": "cid789",
            },
        )
        # Should be 403 because test user is not an owner
        assert resp.status_code == 403

    async def test_delete_nonexistent_returns_404(self, client: AsyncClient, auth_headers: dict):
        """DELETE on nonexistent connection returns 404."""
        import uuid
        resp = await client.delete(
            f"/api/v1/integrations/psa/connections/{uuid.uuid4()}",
            headers=auth_headers,
        )
        # Either 403 (not owner) or 404 — both are acceptable
        assert resp.status_code in (403, 404)
```

Note: Full CRUD tests with owner-role fixtures will be added when we have a test helper for creating owner-role users. These initial tests verify the endpoints exist and RBAC is enforced.

**Step 2: Create the endpoints**

Create `backend/app/api/endpoints/integrations.py`:

```python
"""PSA integration management endpoints."""
from __future__ import annotations

from typing import Annotated
from uuid import UUID

from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.core.database import get_db
from app.api.deps import require_account_owner, get_current_active_user
from app.models.user import User
from app.models.psa_connection import PsaConnection
from app.schemas.psa_connection import (
    PsaConnectionCreate,
    PsaConnectionUpdate,
    PsaConnectionResponse,
    PsaConnectionTestResponse,
)
from app.services.psa.encryption import encrypt_credentials, decrypt_credentials, mask_credential

router = APIRouter(prefix="/integrations/psa", tags=["integrations"])


def _to_response(conn: PsaConnection) -> PsaConnectionResponse:
    """Convert a PsaConnection model to a response with redacted credentials."""
    creds = decrypt_credentials(conn.credentials_encrypted)
    return PsaConnectionResponse(
        id=conn.id,
        account_id=conn.account_id,
        provider=conn.provider,
        display_name=conn.display_name,
        site_url=conn.site_url,
        company_id=conn.company_id,
        is_active=conn.is_active,
        last_validated_at=conn.last_validated_at,
        created_at=conn.created_at,
        updated_at=conn.updated_at,
        public_key_hint=mask_credential(creds.get("public_key")),
        private_key_hint=mask_credential(creds.get("private_key")),
    )


@router.get("/connections", response_model=PsaConnectionResponse | None)
async def get_connection(
    current_user: Annotated[User, Depends(get_current_active_user)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Get the account's PSA connection (redacted credentials). Any authenticated user can view."""
    if not current_user.account_id:
        return None
    result = await db.execute(
        select(PsaConnection).where(PsaConnection.account_id == current_user.account_id)
    )
    conn = result.scalar_one_or_none()
    if not conn:
        return None
    return _to_response(conn)


@router.post("/connections", response_model=PsaConnectionResponse, status_code=status.HTTP_201_CREATED)
async def create_connection(
    data: PsaConnectionCreate,
    current_user: Annotated[User, Depends(require_account_owner)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Create a new PSA connection for the account. Tests connection before saving."""
    if not current_user.account_id:
        raise HTTPException(status_code=400, detail="User has no account")

    # Check for existing connection
    existing = await db.execute(
        select(PsaConnection).where(PsaConnection.account_id == current_user.account_id)
    )
    if existing.scalar_one_or_none():
        raise HTTPException(status_code=409, detail="Account already has a PSA connection")

    # Test connection before saving
    from app.services.psa.connectwise.client import ConnectWiseClient
    from app.services.psa.connectwise.provider import ConnectWiseProvider

    client = ConnectWiseClient(
        site_url=data.site_url,
        company_id=data.company_id,
        public_key=data.public_key,
        private_key=data.private_key,
        client_id=data.client_id,
    )
    provider = ConnectWiseProvider(client)
    test_result = await provider.test_connection()

    if not test_result.success:
        raise HTTPException(status_code=422, detail=f"Connection test failed: {test_result.message}")

    # Encrypt and save
    from datetime import datetime, timezone

    encrypted = encrypt_credentials({
        "public_key": data.public_key,
        "private_key": data.private_key,
        "client_id": data.client_id,
    })

    conn = PsaConnection(
        account_id=current_user.account_id,
        provider=data.provider,
        display_name=data.display_name,
        site_url=data.site_url,
        company_id=data.company_id,
        credentials_encrypted=encrypted,
        last_validated_at=datetime.now(timezone.utc),
    )
    db.add(conn)
    await db.commit()
    await db.refresh(conn)

    return _to_response(conn)


@router.put("/connections/{connection_id}", response_model=PsaConnectionResponse)
async def update_connection(
    connection_id: UUID,
    data: PsaConnectionUpdate,
    current_user: Annotated[User, Depends(require_account_owner)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Update PSA connection. Re-tests if credentials change."""
    result = await db.execute(
        select(PsaConnection).where(
            PsaConnection.id == connection_id,
            PsaConnection.account_id == current_user.account_id,
        )
    )
    conn = result.scalar_one_or_none()
    if not conn:
        raise HTTPException(status_code=404, detail="Connection not found")

    # Decrypt existing creds to merge with updates
    creds = decrypt_credentials(conn.credentials_encrypted)
    credentials_changed = False

    if data.display_name is not None:
        conn.display_name = data.display_name
    if data.site_url is not None:
        conn.site_url = data.site_url
        credentials_changed = True
    if data.company_id is not None:
        conn.company_id = data.company_id
        credentials_changed = True
    if data.public_key is not None:
        creds["public_key"] = data.public_key
        credentials_changed = True
    if data.private_key is not None:
        creds["private_key"] = data.private_key
        credentials_changed = True
    if data.client_id is not None:
        creds["client_id"] = data.client_id
        credentials_changed = True

    # Re-test if credentials changed
    if credentials_changed:
        from app.services.psa.connectwise.client import ConnectWiseClient
        from app.services.psa.connectwise.provider import ConnectWiseProvider

        client = ConnectWiseClient(
            site_url=conn.site_url,
            company_id=conn.company_id,
            public_key=creds["public_key"],
            private_key=creds["private_key"],
            client_id=creds["client_id"],
        )
        provider = ConnectWiseProvider(client)
        test_result = await provider.test_connection()

        if not test_result.success:
            raise HTTPException(status_code=422, detail=f"Connection test failed: {test_result.message}")

        from datetime import datetime, timezone
        conn.last_validated_at = datetime.now(timezone.utc)
        conn.credentials_encrypted = encrypt_credentials(creds)

    await db.commit()
    await db.refresh(conn)
    return _to_response(conn)


@router.delete("/connections/{connection_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_connection(
    connection_id: UUID,
    current_user: Annotated[User, Depends(require_account_owner)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Delete a PSA connection."""
    result = await db.execute(
        select(PsaConnection).where(
            PsaConnection.id == connection_id,
            PsaConnection.account_id == current_user.account_id,
        )
    )
    conn = result.scalar_one_or_none()
    if not conn:
        raise HTTPException(status_code=404, detail="Connection not found")

    await db.delete(conn)
    await db.commit()


@router.post("/connections/{connection_id}/test", response_model=PsaConnectionTestResponse)
async def test_connection(
    connection_id: UUID,
    current_user: Annotated[User, Depends(require_account_owner)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Test an existing PSA connection."""
    result = await db.execute(
        select(PsaConnection).where(
            PsaConnection.id == connection_id,
            PsaConnection.account_id == current_user.account_id,
        )
    )
    conn = result.scalar_one_or_none()
    if not conn:
        raise HTTPException(status_code=404, detail="Connection not found")

    from app.services.psa.registry import get_provider_for_account
    provider = await get_provider_for_account(current_user.account_id, db)
    test_result = await provider.test_connection()

    if test_result.success:
        from datetime import datetime, timezone
        conn.last_validated_at = datetime.now(timezone.utc)
        await db.commit()

    return PsaConnectionTestResponse(
        success=test_result.success,
        message=test_result.message,
        server_version=test_result.server_version,
    )
```

**Step 3: Register in router**

Add to `backend/app/api/router.py`:

```python
from app.api.endpoints import integrations
# ...
api_router.include_router(integrations.router)
```

**Step 4: Run tests**

Run: `cd backend && python -m pytest tests/test_psa_connections.py -v`
Expected: Tests should pass (the RBAC test may need adjustment based on test user role)

**Step 5: Commit**

```bash
git add backend/app/api/endpoints/integrations.py backend/app/api/router.py backend/tests/test_psa_connections.py
git commit -m "feat(psa): add PSA connection CRUD endpoints with encryption and connection testing"
```

---

### Task 8: Frontend — Integrations page (Connection tab)

This task creates the frontend for Slice 1. Due to the size, it's broken into sub-steps but committed as a single unit.

**Files:**
- Create: `frontend/src/types/integrations.ts`
- Modify: `frontend/src/types/index.ts`
- Create: `frontend/src/api/integrations.ts`
- Modify: `frontend/src/api/index.ts`
- Create: `frontend/src/pages/account/IntegrationsPage.tsx`
- Modify: `frontend/src/router.tsx`
- Modify: `frontend/src/pages/account/AccountSettingsPage.tsx` (add link card)

**Sub-step A: Types**

Create `frontend/src/types/integrations.ts` with `PsaConnectionResponse`, `PsaConnectionCreate`, `PsaConnectionUpdate`, `PsaConnectionTestResponse` interfaces matching the backend schemas.

**Sub-step B: API client**

Create `frontend/src/api/integrations.ts` with `integrationsApi` object (connection CRUD + test).

**Sub-step C: IntegrationsPage**

Create `frontend/src/pages/account/IntegrationsPage.tsx`:
- Connection tab (only tab for now — Member Mapping and Post History added in Slices 4-5)
- When no connection: setup form with fields for display name, site URL, company ID, public key, private key, client ID
- When connection exists: status card showing provider, site URL, company ID, redacted keys, last validated timestamp. Actions: Edit, Test, Disconnect
- Connection test shows success/failure inline
- Uses local React state (per lesson #41)
- Glass card styling per design system

**Sub-step D: Routing**

Add route in `frontend/src/router.tsx` under `account` children:
```tsx
{
  path: 'integrations',
  element: (
    <ProtectedRoute requiredRole="owner">
      {page(IntegrationsPage)}
    </ProtectedRoute>
  ),
},
```

Add link card in `AccountSettingsPage.tsx` for "Integrations" pointing to `/account/integrations`.

**Sub-step E: Build and commit**

Run: `cd frontend && npm run build`
Expected: SUCCESS

```bash
git add frontend/src/types/integrations.ts frontend/src/types/index.ts frontend/src/api/integrations.ts frontend/src/api/index.ts frontend/src/pages/account/IntegrationsPage.tsx frontend/src/router.tsx frontend/src/pages/account/AccountSettingsPage.tsx
git commit -m "feat(psa): add Integrations page with connection management UI"
```

---

## Slice 2: Ticket Linking (Outline)

### Task 9: get_ticket in ConnectWise provider
- Implement `get_ticket()` in provider — calls `GET /service/tickets/{id}` with partial response fields
- Map CW response to `PSATicket` model

### Task 10: Session table migration
- Add `psa_ticket_id` (VARCHAR 100, nullable) and `psa_connection_id` (UUID, FK → psa_connections, ON DELETE SET NULL) to sessions
- Migration 059
- Update Session model and SessionResponse schema

### Task 11: Ticket link endpoint
- `PATCH /sessions/{id}/ticket-link` — validates ticket exists in CW before saving
- Add to `sessions.py` endpoints

### Task 12: Frontend — Ticket picker modal + session header indicator
- TicketPickerModal component (manual ID entry + Look Up)
- Session header ticket link indicator (Lucide `Ticket` icon)
- Link/unlink UI

---

## Slice 3: Ticket Search (Outline)

### Task 13: search_tickets, get_ticket_statuses, list_companies in provider
### Task 14: Search and status endpoints
### Task 15: In-memory cache for board statuses and companies
### Task 16: Frontend — Full ticket search in picker modal

---

## Slice 4: Update Ticket Modal (Outline)

### Task 17: PsaPostLog model + migration 060
### Task 18: post_note, update_ticket_status in provider
### Task 19: Preview, post, and post history endpoints
### Task 20: Frontend — Update Ticket modal (split panel, note type, status dropdown)
### Task 21: Frontend — Post history tab in Integrations page

---

## Slice 5: Member Mapping (Outline)

### Task 22: PsaMemberMapping model + migration 061
### Task 23: list_members in provider
### Task 24: Member mapping CRUD + auto-match endpoints
### Task 25: Member attribution on note posts
### Task 26: Frontend — Member Mapping tab in Integrations page
