# Price reduced

Source: https://help.ruuster.com/idx/recipe-price-reduced

> A /price-reduced page with the homes in your market area whose price dropped in the last 7 days, rendered on your server.

A page at `/price-reduced` with the homes in your market area whose price dropped in the last 7 days.
`priceReduction=7d` asks for them; `0d` (today), `1d`, `2d`, `3d`, `14d`, `30d` and `90d` are the
other windows. Each card shows its price-change badge.

## What the visitor sees

<figure class="idx-shot"><img src="/idx-docs/screens/ours/listing-grid-1440.png" alt="Listing grid with the disclaimers under it, on a desktop (1440 px wide)" width="1440" height="900" loading="lazy" decoding="async"><figcaption>Price-reduced homes in the card grid.</figcaption></figure>

<figure class="idx-shot"><img src="/idx-docs/screens/ours/listing-grid-375.png" alt="Listing grid with the disclaimers under it, on a phone (375 px wide)" width="375" height="1403" loading="lazy" decoding="async"><figcaption>Price-reduced homes in the card grid.</figcaption></figure>

The markup is `static/html/listing-grid.html` in `@ruuster/idx-recipes`. The [HTML and CSS recipe](https://help.ruuster.com/idx/recipe-html-css) shows how to fill it and which stylesheet and script to load.

## What the page calls

| When | Request | Key | Cached |
|---|---|---|---|
| Each page view | `GET /v1/listings` with `priceReduction=7d` and your market area | secret key, on your server | 5 minutes by Next.js |

cURL:

```bash
curl -s -G "https://idx.ruuster.com/v1/listings" \
  --data-urlencode 'where={"label":"Atlanta, GA","value":"Atlanta","source":"crm-system","data":{"state":"GA","city":"Atlanta"},"city":"Atlanta","state":"GA"}' \
  --data-urlencode status=active \
  --data-urlencode priceReduction=7d \
  --data-urlencode limit=24 \
  --data-urlencode pageHref=/price-reduced \
  -H "Authorization: Bearer $IDX_SECRET_KEY"
```

TypeScript:

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

const idx = createClient({ secretKey: process.env.IDX_SECRET_KEY });

const r = await idx.search({
  where: {
    label: "Atlanta, GA",
    value: "Atlanta",
    source: "crm-system",
    data: {
      state: "GA",
      city: "Atlanta",
    },
    city: "Atlanta",
    state: "GA",
  },
  status: "active",
  priceReduction: "7d",
  limit: 24,
  pageHref: "/price-reduced",
});
if (!r.ok) throw new Error(`${r.error.code}: ${r.error.message}`);
console.log(r.data);
```

Python:

```python
import os

import requests

res = requests.get(
    "https://idx.ruuster.com/v1/listings",
    params={
        "where": "{\"label\":\"Atlanta, GA\",\"value\":\"Atlanta\",\"source\":\"crm-system\",\"data\":{\"state\":\"GA\",\"city\":\"Atlanta\"},\"city\":\"Atlanta\",\"state\":\"GA\"}",
        "status": "active",
        "priceReduction": "7d",
        "limit": "24",
        "pageHref": "/price-reduced",
    },
    headers={"Authorization": "Bearer " + os.environ["IDX_SECRET_KEY"]},
    timeout=30,
)
body = res.json()
if not body["ok"]:
    raise RuntimeError(body["error"]["code"] + ": " + body["error"]["message"])
print(body["data"])
```

PHP:

```php
<?php

$query = http_build_query([
    'where' => '{"label":"Atlanta, GA","value":"Atlanta","source":"crm-system","data":{"state":"GA","city":"Atlanta"},"city":"Atlanta","state":"GA"}',
    'status' => 'active',
    'priceReduction' => '7d',
    'limit' => '24',
    'pageHref' => '/price-reduced',
], '', '&', PHP_QUERY_RFC3986);
$ch = curl_init('https://idx.ruuster.com/v1/listings' . '?' . $query);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('IDX_SECRET_KEY')],
    CURLOPT_TIMEOUT => 30,
]);
$body = json_decode(curl_exec($ch), true);
curl_close($ch);
if (!$body['ok']) {
    throw new RuntimeException($body['error']['code'] . ': ' . $body['error']['message']);
}
print_r($body['data']);
```

## Steps

1. Add `lib/idx.ts`, `lib/site.ts` and `components/results.tsx` from the
   [recipes overview](https://help.ruuster.com/idx/recipes), and `lib/area-query.ts` and
   `lib/results.ts` from the [search page recipe](https://help.ruuster.com/idx/recipe-search-page).
2. Make your whole market the last entry of `content/areas.ts` (`MARKET_AREA`).
3. Create `app/price-reduced/page.tsx` with the code below.
4. Open `http://localhost:3000/price-reduced`.

## The code

<p class="code-title"><code>app/price-reduced/page.tsx</code></p>

```tsx
// /price-reduced: homes in your market area whose price dropped in the last 7 days.
import { notFound } from "next/navigation";
import { Results } from "@/components/results";
import { MARKET_AREA } from "@/content/areas";
import { idx } from "@/lib/idx";
import { PAGE_SIZE, visitorQuery, type CardQuery } from "@/lib/area-query";
import { failureAction, resultsMetadata } from "@/lib/results";

export const revalidate = 300;

type Props = { searchParams: Record<string, string | string[] | undefined> };

function query(searchParams: Props["searchParams"]): CardQuery {
  return { ...visitorQuery(searchParams), where: MARKET_AREA.where, status: "active", priceReduction: "7d", limit: PAGE_SIZE, pageHref: "/price-reduced" };
}

export async function generateMetadata({ searchParams }: Props) {
  const r = await idx.search(query(searchParams));
  return r.ok ? resultsMetadata(r.data.head, `Price reduced in ${MARKET_AREA.name}`) : {};
}

export default async function PriceReduced({ searchParams }: Props) {
  const r = await idx.search(query(searchParams));
  if (!r.ok) {
    if (failureAction(r) === "not_found") notFound();
    throw new Error(`Listings API ${r.status} ${r.error.code}`);
  }
  return (
    <main>
      <h1>{`Price reduced in ${MARKET_AREA.name}`}</h1>
      <p>Homes whose price dropped in the last 7 days.</p>
      <Results r={r} basePath="/price-reduced" searchParams={searchParams} listName="Price reduced" emptyText="No prices dropped in the last 7 days." />
    </main>
  );
}
```

## Forms and your CRM

The page carries no forms. Each card leads to its listing page, where your tour form is
([Registration, tour and contact forms](https://help.ruuster.com/idx/recipe-forms)).

## Rules this page follows

**MUST**

- Show the current price from the API on each card, and every board's disclaimer.
- Re-render at least every 5 minutes, so the list follows price changes.

**NEVER**

- Show an old price or a percentage the API did not answer.

## Test it

```sh
curl -s http://localhost:3000/price-reduced | grep -o 'href="[^"]*/homes/[^"]*"' | sort -u | wc -l
```

The count matches the cards on the page. Open a card: its listing page shows the same price.

## Build it with AI

Use the open houses prompt with one change: ask for `priceReduction=7d` on a page at `/price-reduced`
instead of `openHousePeriod=this_weekend` on `/open-houses`.

```text
Read RUUSTER_IDX.md first and follow its MUST and NEVER rules. Ask me if it doesn't cover something.

Build an "Open houses this weekend" page at /open-houses that follows <https://help.ruuster.com/idx/recipe-open-houses>. Call GET /v1/listings with openHousePeriod=this_weekend and my market area's where object on the server with my secret key, and revalidate the page every 5 minutes. Show each open house time in the listing's own time zone, and keep the MLS disclaimers under the results.

Use these environment variables: IDX_SECRET_KEY (server only), SITE_ORIGIN and SITE_NAME. Never paste a secret key into a chat, and never put IDX_SECRET_KEY in browser code, a URL or a log. No key goes in any page: my pages call my own /api/idx route, made with createListingsRoute from @ruuster/idx/route, which adds my secret key on the server (on a site with no server, the widgets call the API with no key from my approved website address).

Fair housing: describe homes, places and amenities only. Never describe the people who live in an area or who a home or area suits, and never rank schools as a reason to buy.

When you are done, show me what the page says when no open houses are scheduled.
```

On a site without React, such as PHP, Python, Ruby on Rails, Go or plain HTML, [Build without React: HTML, CSS and JavaScript](https://help.ruuster.com/idx/recipe-html-css) gives you the same markup, the stylesheet and the script for every widget.
