Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,22 @@ If you load in sample data, be sure to index for arches-search-extension:
```bash
python manage.py arches_search reindex_database
```

## Featured search items

The Featured Items tab on the search landing page is populated from the `FeaturedSearchItem` model, which is edited in the Django admin. Each item points at a saved search. The picker only lists saved searches whose creator has Django's "Staff status" (`is_staff`) flag set, so a search saved by an ordinary user cannot be featured. On save the linked search also has to have `terms` or `groups` in its query definition, otherwise the form rejects it as not a runnable query.

`presentation` is a JSON object that controls how the card is drawn:

```json
{
"icon": "pi-palette",
"color": "#0d9488",
"label": "Pigments and Colourants",
"description": "Reference pigments, dyes, and colourant samples."
}
```

`icon` and `color` are required and are validated on save. `icon` is a bare PrimeIcons suffix (`pi-palette`, not `pi pi-palette`) and sets the glyph on the card. `color` is a `#rrggbb` hex value and sets the background of the tile behind the glyph.

`label` and `description` are optional. If you leave them out the card falls back to the name and description of the saved search. Any other keys are ignored.
54 changes: 54 additions & 0 deletions arches_rascolls/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import re

from django import forms
from django.contrib import admin
from django.db import models
from django.forms import Textarea

from arches_rascolls.models import FeaturedSearchItem


class FeaturedSearchItemForm(forms.ModelForm):
class Meta:
model = FeaturedSearchItem
fields = "__all__"
exclude = ["featuredsearchitemid", "created_at"]

def clean_presentation(self):
data = self.cleaned_data["presentation"]
if not isinstance(data, dict):
raise forms.ValidationError(
"presentation must be a JSON object, e.g. {'icon': 'pi-palette', 'color': '#0d9488'}"
)
if not re.fullmatch(r"pi-[a-z0-9-]+", data.get("icon", "")):
raise forms.ValidationError(
"icon must be a bare PrimeIcon suffix, e.g. 'pi-palette'"
)
if not re.fullmatch(r"#[0-9a-fA-F]{6}", data.get("color", "")):
raise forms.ValidationError("color must be a #rrggbb hex value")
return data

def clean(self):
cleaned = super().clean()
query_definition = (
cleaned.get("saved_search") and cleaned["saved_search"].query_definition
)
if query_definition is not None and not (
{"terms", "groups"} & query_definition.keys()
):
raise forms.ValidationError(
"linked saved search has no terms/groups — it isn't a runnable dynamic query"
)
return cleaned


@admin.register(FeaturedSearchItem)
class FeaturedSearchItemAdmin(admin.ModelAdmin):
form = FeaturedSearchItemForm
list_display = ["display_label", "saved_search", "sort_order", "is_active"]
list_editable = ["sort_order", "is_active"]
autocomplete_fields = ["saved_search"]
readonly_fields = ["featuredsearchitemid", "created_at"]
formfield_overrides = {
models.JSONField: {"widget": Textarea(attrs={"rows": 20, "cols": 80})},
}
46 changes: 46 additions & 0 deletions arches_rascolls/migrations/0011_featured_search_item.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import uuid

import django.db.models.deletion
from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
("arches_rascolls", "0010_plugin_visibility"),
("arches_search", "0021_daterangesearch_end_value_index"),
]

operations = [
migrations.CreateModel(
name="FeaturedSearchItem",
fields=[
(
"featuredsearchitemid",
models.UUIDField(
default=uuid.uuid4,
primary_key=True,
serialize=False,
),
),
("presentation", models.JSONField(default=dict)),
Comment thread
chrabyrd marked this conversation as resolved.
Resolved
("sort_order", models.PositiveIntegerField(default=0)),
("is_active", models.BooleanField(default=True)),
("created_at", models.DateTimeField(auto_now_add=True)),
Comment on lines +26 to +29

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's make these non-nullable

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

these should be implicitly non-nullable? but happy to add the explicitness 👍

(
"saved_search",
models.ForeignKey(
limit_choices_to={"creator__is_staff": True},
on_delete=django.db.models.deletion.CASCADE,
related_name="featured_items",
to="arches_search.savedsearch",
),
),
],
options={
"db_table": "arches_rascolls_featured_search_items",
"managed": True,
"ordering": ["sort_order", "featuredsearchitemid"],
},
),
]
30 changes: 30 additions & 0 deletions arches_rascolls/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import uuid

from django.db import models


class FeaturedSearchItem(models.Model):
featuredsearchitemid = models.UUIDField(primary_key=True, default=uuid.uuid4)
saved_search = models.ForeignKey(
"arches_search.SavedSearch",
on_delete=models.CASCADE,
related_name="featured_items",
limit_choices_to={"creator__is_staff": True},
)
presentation = models.JSONField(default=dict, null=False)
sort_order = models.PositiveIntegerField(default=0, null=False)
is_active = models.BooleanField(default=True, null=False)
created_at = models.DateTimeField(auto_now_add=True, null=False)

class Meta:
managed = True
db_table = "arches_rascolls_featured_search_items"
ordering = ["sort_order", "featuredsearchitemid"]

@property
def display_label(self):
return self.presentation.get("label") or self.saved_search.name

@property
def display_description(self):
return self.presentation.get("description") or self.saved_search.description
43 changes: 43 additions & 0 deletions arches_rascolls/src/arches_rascolls/SearchLanding/api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { generateArchesURL } from "@/arches_vue_components/application";
import { fetchSearchDefinitionCounts } from "@/arches_search/SearchLanding/api.ts";
import {
buildRequestQuery,
buildRequestTerms,
parseSearchDefinition,
} from "@/arches_search/SimpleSearch/utils/search-definition.ts";

import type { FeaturedItem } from "@/arches_rascolls/SearchLanding/types.ts";

export async function fetchFeaturedItems(): Promise<FeaturedItem[]> {
const response = await fetch(
generateArchesURL("arches_rascolls:api-featured-items"),
);
if (!response.ok) {
throw new Error(response.statusText);
}
const data = await response.json();
return data.results;
}

export async function fetchFeaturedItemCounts(
items: FeaturedItem[],
): Promise<Record<string, number | null>> {
return await fetchSearchDefinitionCounts(
items.map((item) => {
const searchDefinition = parseSearchDefinition(
item.search_definition,
);
return {
id: item.id,
body: {
terms: buildRequestTerms(searchDefinition.terms),
query: buildRequestQuery(
Object.values(searchDefinition.queries),
),
graphIds: searchDefinition.graphIds,
mapFilter: searchDefinition.mapFilter,
},
};
}),
);
}
Loading
Loading