# Platform: saved searches for signed-in buyers and agents

Source: https://help.ruuster.com/idx/guide-platform-saved-searches

> For Ruuster Platform brokerages. Signed-in buyers save and manage their own searches on your website, and signed-in agents set up searches for their clients from your website or your internal agent portal, all saved straight into Ruuster.

If your brokerage is on the Ruuster Platform, the saved searches made on your own website and in your
own agent portal live in Ruuster, next to the ones made in the Ruuster app. Your agents see them on
the client's page, and alerts go out the way your brokerage already sends them.

Three flows use the same endpoints:

- **A buyer on your website** saves the search they are looking at, and pauses, edits or deletes
  their saved searches.
- **An agent on your website** picks one or more of their clients and sets up a search for them.
- **An agent in your internal portal** (any other front end your brokerage runs) does the same.

Every call goes from your **server**, with your **secret key**, plus a **session** for the person who
is signed in. The browser never holds the key or the session.

## Sessions: who is acting

Each call acts as one signed-in person, a buyer or an agent. You never send a user id or a role: the
session carries both, and nothing in the query or the body can change them.

1. The person signs in on your site or portal. Your sign-in hand-off with Ruuster gives your server a
   short-lived **sign-in token** for that person. It works once and lasts about a minute.
2. Your server exchanges it for a session:

   ```ts
   import { createClient } from "@ruuster/idx";

   const idx = createClient({ secretKey: process.env.IDX_SECRET_KEY });
   const r = await idx.platform.session.exchange({ signInToken });
   if (r.ok) {
     // r.data.session: keep it on your server (an HttpOnly cookie or your own server session).
     // r.data.user.role: "client" for a buyer, "agent" for an agent.
   }
   ```

3. Send the session with every call. It lasts 12 hours. `idx.platform.session.refresh(session)` gives
   you a fresh one for another 12 hours, for up to 30 days after sign-in.
4. When the person signs out, call `idx.platform.session.signOut(session)`.

The sign-in hand-off is part of setting up your Platform website: your Ruuster contact switches it on
for your brokerage and gives you the sign-in link your site uses. Your website and your portal each
run the same exchange, and each signed-in person gets a session of their own.

## A buyer saves a search on your website

Your search page already has the search as GET /v1/listings parameters. Save it as is: locations are
the `where` objects /v1/suggest returned, plus `zip`, `city`, `state`, `near` with `radiusMiles`,
`polygon` and `bbox`, and the price, beds, baths, square feet, year built, HOA, type, status,
new construction and keyword filters.

```ts
// app/api/searches/save/route.ts (your server)
export async function POST(req: Request) {
  const session = await readSessionCookie(req); // your own helper
  const { name, criteria, requestId } = await req.json();
  const r = await idx.platform.searches.buyer.create(session, { name, criteria }, { idempotencyKey: requestId });
  return Response.json(r.ok ? { ok: true } : { ok: false }, { status: r.ok ? 200 : r.status });
}
```

Every create needs an **Idempotency-Key**: a new id for each search the person means to save, sent
again unchanged if you retry. A retry with the same key answers the search already made instead of
making a second one.

A buyer's search starts with alerts once a day by email. They can choose another `clientUpdates`
value (`instant`, `daily`, `weekly` and the others listed below) and `clientNotifications`
(`email`, `sms`, `push`).

The buyer's list and the changes:

```ts
const page = await idx.platform.searches.buyer.list(session); // 10 at a time, newest first
// page.data.items[i]: { id, name, criteria, paused, clientUpdates, ... }; page.data.nextOffset for the next page
await idx.platform.searches.buyer.update(session, searchId, { name: "Austin, weekly", clientUpdates: ["weekly"] });
await idx.platform.searches.buyer.pause(session, searchId);
await idx.platform.searches.buyer.resume(session, searchId);
await idx.platform.searches.buyer.delete(session, searchId);
```

An update changes only the fields you send. Send `criteria` to replace the search's location and
filters in full; leave it out to keep them as they are, including filters set in the Ruuster app
(listed in `unmappedFilters`).

The recipes package has the pieces for this page: `SaveSearchButton` and `MySavedSearches` from
`@ruuster/idx-recipes`. Each posts to your own route, which adds the session.

## An agent sets up a search for clients

On your website or in your portal, a signed-in agent picks one or more clients (up to 40) and sets up
one search for each of them:

```ts
const r = await idx.platform.searches.agent.create(
  session,
  {
    name: "Austin homes under 600k",
    criteria: { city: "Austin", state: "TX", priceMax: 600000, bedsMin: 3 },
    clients: [{ id: clientId }, { id: leadId, userType: "unregistered-client" }],
    clientUpdates: ["daily"],
    agentUpdates: ["daily"],
    agentNotifications: ["email"],
  },
  { idempotencyKey: requestId },
);
// r.data.searches: one { clientId, searchId } per client, in the order sent.
```

`userType` is `client` for a registered client (the default) and `unregistered-client` for a lead.
Agents can also set `ccEmails` (up to 10 addresses), `emailSubject` (up to 60 characters) and
`isAutoSendSaveSearch` (send the client a first email right away).

Which clients an agent can reach is the same as in the Ruuster app: their agency's clients, their own
leads, and clients they work with as a collaborator. An admin or owner reaches every client of the
brokerage. A client the agent can't reach answers 404 `client_not_found`, with the ids in
`error.clientIds`, and nothing is created.

The agent's view of a client's searches, and the changes:

```ts
const page = await idx.platform.searches.agent.list(session, clientId);
await idx.platform.searches.agent.update(session, searchId, { agentUpdates: ["none"] });
await idx.platform.searches.agent.pause(session, searchId);
await idx.platform.searches.agent.resume(session, searchId);
await idx.platform.searches.agent.delete(session, searchId);
```

`AgentSearchForm` from `@ruuster/idx-recipes` is a minimal form for this: a box per client, the
search name and how often the clients hear about new homes.

## Your internal portal

Your portal is another front end of the same brokerage, so it uses the same secret key and the same
calls. Its server runs its own sign-in exchange for each agent and keeps that agent's session. A
session from your portal and one from your website are separate: signing out of one leaves the other
signed in.

## The endpoints

| Call | What it does | Who |
| --- | --- | --- |
| `POST /v1/platform/session` | Exchange a sign-in token for a session | Your server |
| `GET /v1/platform/session` | Who the session is for | Any session |
| `POST /v1/platform/session/refresh` | A fresh session for another 12 hours | Any session |
| `DELETE /v1/platform/session` | Sign out | Any session |
| `GET`, `POST /v1/platform/me/searches` | The buyer's searches; save one | Buyer |
| `GET`, `PATCH`, `DELETE /v1/platform/me/searches/{id}` | One of the buyer's searches | Buyer |
| `POST /v1/platform/me/searches/{id}/pause` and `/resume` | Pause or resume it | Buyer |
| `POST /v1/platform/agent/searches` | Set up a search for 1 to 40 clients | Agent |
| `GET /v1/platform/agent/clients/{clientId}/searches` | A client's searches | Agent |
| `GET`, `PATCH`, `DELETE /v1/platform/agent/searches/{id}` | One search | Agent |
| `POST /v1/platform/agent/searches/{id}/pause` and `/resume` | Pause or resume it | Agent |

Send the session as the `X-Idx-Session` header and your secret key as `Authorization: Bearer`. A
create also sends `Idempotency-Key`. The SDK sets all three for you.

Frequencies (`clientUpdates`, `agentUpdates`): `instant`, `daily`, `biweekly`, `weekly`,
`bimonthly`, `monthly`, `quarterly`, `immediate`, or `none` on its own. Channels
(`clientNotifications`, `agentNotifications`): `email`, `sms`, `push`. A lead's search sends email.

## Errors

Answers use the same envelope as every other endpoint. The ones you will see here:

| Status | Code | What to do |
| --- | --- | --- |
| 400 | `invalid_parameter`, `field_not_allowed`, `location_required` | Fix the field named in `error.field` |
| 400 | `idempotency_key_required` | Send an `Idempotency-Key` with the create |
| 401 | `session_required`, `session_invalid`, `session_expired` | Sign the person in again |
| 401 | `signin_token_invalid`, `signin_token_expired`, `signin_token_used` | Start the sign-in again |
| 403 | `role_not_allowed` | A buyer used an agent call, or the other way round |
| 404 | `not_found`, `client_not_found` | The search or client doesn't exist or can't be reached |
| 413 | `payload_too_large` | Keep the request body under 64 KB |
| 429 | `rate_limited` | Up to 60 of these calls a minute per key (10 per 5 seconds); wait for `Retry-After` |
| 409 | `request_in_progress` | Retry shortly with the same `Idempotency-Key` |
| 422 | `filter_not_supported`, `location_not_supported` | That filter or location can't be saved; `error.field` names it |
| 422 | `idempotency_key_reused` | Use a new key for a new search |
| 503 | `source_unavailable` | Retry when `retryable` is true, after `Retry-After` |

## Your MLS's own filters

A saved search can also carry the advanced filters your MLSs offer, written exactly as in a listing
search: `f.<key>` with one value or a list, `f.<key>Min` and `f.<key>Max` for ranges, and
`f.<key>_o` for the operator. The keys are the ones `GET /v1/filters` lists for your account.

```ts
criteria: { city: "Portland", state: "ME", bedsMin: 3, "f.waterfront": true, "f.garageSpacesMin": 2 }
```

Each filter is checked against your account's filter list before the search is saved, the same way a
listing search checks it, so a typo answers 422 `filter_not_supported` with the key in
`error.field` instead of saving a search that quietly matches the wrong homes. A search made in the
Ruuster app with advanced filters reads back with them as `f.` criteria. Send a filter that has its
own parameter (beds, baths, price, square feet) through that parameter: `f.bedroomsMin` answers
"send criteria.bedsMin instead".

Filters a saved search can't carry yet include `boundariesId`, `shape`, `soldPeriod`,
`openHousePeriod`, `priceReduction`, `listedSince`, `daysOnMarketMax`, `ownListings`, `agent`,
`office` and `filterByMls`. Locations from Google place ids can't be saved: use the
`where` objects /v1/suggest returns.
