feat(gallery): tag→gallery nav from modal chips (#5) + OR/exclude tag scope (#6a)
CI / lint (push) Successful in 2s
CI / frontend-build (push) Successful in 19s
CI / backend-lint-and-test (push) Successful in 26s
CI / integration (push) Successful in 3m19s

Cluster A, milestone #97. #5: clicking an image-modal tag chip's body now
closes the modal and opens the gallery filtered for that one tag (fresh
filter); ✕/kebab stay as the explicit remove/rename controls.

#6a (backend of OR/exclude filtering): gallery_service._apply_scope gains a
structured tag model — tag_or_groups (AND-of-OR: one EXISTS(tag_id IN group)
per group) + tag_exclude (NOT EXISTS(tag_id IN exclude)) — layered additively
on the existing tag_ids AND path so cursors/facets/deep-links are untouched.
Threaded through scroll/timeline/jump_cursor/facets/similar + facets common
dict; _require_single_filter rejects post_id combined with OR/exclude. API
parses tag_or (repeatable → one OR-group each) + tag_not (csv exclude).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XCUHUGQLrBrkgyk1t49kpX
This commit is contained in:
2026-06-23 01:11:42 -04:00
parent 7c94d99b9f
commit 23fab983a0
6 changed files with 258 additions and 20 deletions
+23 -7
View File
@@ -37,16 +37,30 @@ def _parse_filters():
"""Parse the composable gallery filters from query args, returning """Parse the composable gallery filters from query args, returning
``(filters_dict, sort)``. Raises ValueError (→ 400) on malformed ids/dates. ``(filters_dict, sort)``. Raises ValueError (→ 400) on malformed ids/dates.
`tag_id` accepts a single id or a comma-separated list (AND); `media` is The structured tag filter (#6) is AND-of-OR plus exclusions:
image|video; `sort` is newest|oldest; `platform` selects one platform - `tag_id` accepts a single id or a comma-separated list — all ANDed
(or the UNSOURCED_PLATFORM sentinel); `untagged`/`no_artist` are boolean (the include common case; back-compat).
flags; `date_from`/`date_to` are inclusive calendar-day bounds (date_to is - `tag_or` is REPEATABLE; each instance is a comma-separated OR-group, and
widened by a day so the whole day is covered by the service's half-open the image must match at least one tag from EACH group (groups ANDed).
`< date_to`).""" - `tag_not` is a comma-separated exclude list (image must carry none).
`media` is image|video; `sort` is newest|oldest; `platform` selects one
platform (or the UNSOURCED_PLATFORM sentinel); `untagged`/`no_artist` are
boolean flags; `date_from`/`date_to` are inclusive calendar-day bounds
(date_to is widened by a day so the whole day is covered by the service's
half-open `< date_to`)."""
tag_raw = request.args.get("tag_id") tag_raw = request.args.get("tag_id")
tag_ids = ( tag_ids = (
[int(x) for x in tag_raw.split(",") if x.strip()] if tag_raw else None [int(x) for x in tag_raw.split(",") if x.strip()] if tag_raw else None
) or None ) or None
tag_or_groups = [
grp for raw in request.args.getlist("tag_or")
if (grp := [int(x) for x in raw.split(",") if x.strip()])
] or None
not_raw = request.args.get("tag_not")
tag_exclude = (
[int(x) for x in not_raw.split(",") if x.strip()] if not_raw else None
) or None
post_id_raw = request.args.get("post_id") post_id_raw = request.args.get("post_id")
post_id = int(post_id_raw) if post_id_raw else None post_id = int(post_id_raw) if post_id_raw else None
artist_id_raw = request.args.get("artist_id") artist_id_raw = request.args.get("artist_id")
@@ -64,7 +78,9 @@ def _parse_filters():
date_to += timedelta(days=1) # inclusive of the date_to calendar day date_to += timedelta(days=1) # inclusive of the date_to calendar day
filters = { filters = {
"tag_ids": tag_ids, "post_id": post_id, "artist_id": artist_id, "tag_ids": tag_ids, "post_id": post_id, "artist_id": artist_id,
"media_type": media_type, "platform": platform, "media_type": media_type,
"tag_or_groups": tag_or_groups, "tag_exclude": tag_exclude,
"platform": platform,
"untagged": untagged, "no_artist": no_artist, "untagged": untagged, "no_artist": no_artist,
"date_from": date_from, "date_to": date_to, "date_from": date_from, "date_to": date_to,
} }
+64 -11
View File
@@ -136,11 +136,15 @@ def image_url(path: str) -> str:
return f"/images/{quote(rel, safe='/')}" return f"/images/{quote(rel, safe='/')}"
def _require_single_filter(tag_ids, post_id, artist_id) -> None: def _require_single_filter(
tag_ids, post_id, artist_id, tag_or_groups=None, tag_exclude=None,
) -> None:
"""post_id is the post-detail view — it can't combine with the """post_id is the post-detail view — it can't combine with the
composable filters. tag_ids + artist_id (+ media_type) compose freely composable filters. tag_ids / tag_or_groups / tag_exclude + artist_id
(AND).""" (+ media_type) compose freely (AND)."""
if post_id is not None and (tag_ids or artist_id is not None): if post_id is not None and (
tag_ids or artist_id is not None or tag_or_groups or tag_exclude
):
raise ValueError( raise ValueError(
"post_id cannot be combined with tag or artist filters" "post_id cannot be combined with tag or artist filters"
) )
@@ -148,6 +152,7 @@ def _require_single_filter(tag_ids, post_id, artist_id) -> None:
def _apply_scope( def _apply_scope(
stmt, *, tag_ids, post_id, artist_id, media_type, stmt, *, tag_ids, post_id, artist_id, media_type,
tag_or_groups=None, tag_exclude=None,
platform=None, untagged=False, no_artist=False, platform=None, untagged=False, no_artist=False,
date_from=None, date_to=None, date_from=None, date_to=None,
): ):
@@ -158,7 +163,14 @@ def _apply_scope(
be present on `stmt` (the artist/platform paths alias Post/Source inside be present on `stmt` (the artist/platform paths alias Post/Source inside
their own EXISTS). their own EXISTS).
- tag_ids: image must carry ALL of them — one correlated EXISTS per tag. Tag filtering is one structured model (#6): AND-of-OR plus exclusions.
- tag_ids: image must carry ALL of them — one correlated EXISTS per tag
(the AND-of-singletons "include" common case; light editor + back-compat).
- tag_or_groups: list of OR-groups; the image must carry AT LEAST ONE tag
from EACH group — one EXISTS(tag_id IN group) per group, AND'd across
groups. (advanced editor)
- tag_exclude: image must carry NONE of these — a single NOT EXISTS(tag_id
IN exclude). (light "exclude" chips + advanced NOT)
- post_id / artist_id: provenance EXISTS (post_id is exclusive, guarded - post_id / artist_id: provenance EXISTS (post_id is exclusive, guarded
by _require_single_filter). by _require_single_filter).
- media_type: 'image' | 'video' narrows by mime prefix. - media_type: 'image' | 'video' narrows by mime prefix.
@@ -175,6 +187,22 @@ def _apply_scope(
image_tag.c.tag_id == tid, image_tag.c.tag_id == tid,
) )
) )
for group in tag_or_groups or []:
if not group:
continue # an empty OR-group would match nothing; treat as absent
stmt = stmt.where(
exists().where(
image_tag.c.image_record_id == ImageRecord.id,
image_tag.c.tag_id.in_(group),
)
)
if tag_exclude:
stmt = stmt.where(
~exists().where(
image_tag.c.image_record_id == ImageRecord.id,
image_tag.c.tag_id.in_(tag_exclude),
)
)
prov = _provenance_clause(post_id, artist_id) prov = _provenance_clause(post_id, artist_id)
if prov is not None: if prov is not None:
stmt = stmt.where(prov) stmt = stmt.where(prov)
@@ -296,6 +324,8 @@ class GalleryService:
artist_id: int | None = None, artist_id: int | None = None,
media_type: str | None = None, media_type: str | None = None,
sort: str = "newest", sort: str = "newest",
tag_or_groups: list[list[int]] | None = None,
tag_exclude: list[int] | None = None,
platform: str | None = None, platform: str | None = None,
untagged: bool = False, untagged: bool = False,
no_artist: bool = False, no_artist: bool = False,
@@ -304,7 +334,9 @@ class GalleryService:
) -> GalleryPage: ) -> GalleryPage:
if limit < 1 or limit > 200: if limit < 1 or limit > 200:
raise ValueError("limit must be between 1 and 200") raise ValueError("limit must be between 1 and 200")
_require_single_filter(tag_ids, post_id, artist_id) _require_single_filter(
tag_ids, post_id, artist_id, tag_or_groups, tag_exclude,
)
eff = _effective_date_col() eff = _effective_date_col()
stmt = select(ImageRecord, Post.post_date, eff.label("eff")) stmt = select(ImageRecord, Post.post_date, eff.label("eff"))
@@ -312,6 +344,7 @@ class GalleryService:
stmt = _apply_scope( stmt = _apply_scope(
stmt, tag_ids=tag_ids, post_id=post_id, stmt, tag_ids=tag_ids, post_id=post_id,
artist_id=artist_id, media_type=media_type, artist_id=artist_id, media_type=media_type,
tag_or_groups=tag_or_groups, tag_exclude=tag_exclude,
platform=platform, untagged=untagged, no_artist=no_artist, platform=platform, untagged=untagged, no_artist=no_artist,
date_from=date_from, date_to=date_to, date_from=date_from, date_to=date_to,
) )
@@ -359,6 +392,8 @@ class GalleryService:
post_id: int | None = None, post_id: int | None = None,
artist_id: int | None = None, artist_id: int | None = None,
media_type: str | None = None, media_type: str | None = None,
tag_or_groups: list[list[int]] | None = None,
tag_exclude: list[int] | None = None,
platform: str | None = None, platform: str | None = None,
untagged: bool = False, untagged: bool = False,
no_artist: bool = False, no_artist: bool = False,
@@ -372,10 +407,13 @@ class GalleryService:
year_col, month_col, func.count(ImageRecord.id).label("cnt") year_col, month_col, func.count(ImageRecord.id).label("cnt")
) )
stmt = _outer_join_primary_post(stmt) stmt = _outer_join_primary_post(stmt)
_require_single_filter(tag_ids, post_id, artist_id) _require_single_filter(
tag_ids, post_id, artist_id, tag_or_groups, tag_exclude,
)
stmt = _apply_scope( stmt = _apply_scope(
stmt, tag_ids=tag_ids, post_id=post_id, stmt, tag_ids=tag_ids, post_id=post_id,
artist_id=artist_id, media_type=media_type, artist_id=artist_id, media_type=media_type,
tag_or_groups=tag_or_groups, tag_exclude=tag_exclude,
platform=platform, untagged=untagged, no_artist=no_artist, platform=platform, untagged=untagged, no_artist=no_artist,
date_from=date_from, date_to=date_to, date_from=date_from, date_to=date_to,
) )
@@ -387,6 +425,8 @@ class GalleryService:
self, year: int, month: int, tag_ids: list[int] | None = None, self, year: int, month: int, tag_ids: list[int] | None = None,
post_id: int | None = None, artist_id: int | None = None, post_id: int | None = None, artist_id: int | None = None,
media_type: str | None = None, sort: str = "newest", media_type: str | None = None, sort: str = "newest",
tag_or_groups: list[list[int]] | None = None,
tag_exclude: list[int] | None = None,
platform: str | None = None, untagged: bool = False, platform: str | None = None, untagged: bool = False,
no_artist: bool = False, date_from: datetime | None = None, no_artist: bool = False, date_from: datetime | None = None,
date_to: datetime | None = None, date_to: datetime | None = None,
@@ -403,10 +443,13 @@ class GalleryService:
extract("month", eff) == month, extract("month", eff) == month,
) )
stmt = _outer_join_primary_post(stmt) stmt = _outer_join_primary_post(stmt)
_require_single_filter(tag_ids, post_id, artist_id) _require_single_filter(
tag_ids, post_id, artist_id, tag_or_groups, tag_exclude,
)
stmt = _apply_scope( stmt = _apply_scope(
stmt, tag_ids=tag_ids, post_id=post_id, stmt, tag_ids=tag_ids, post_id=post_id,
artist_id=artist_id, media_type=media_type, artist_id=artist_id, media_type=media_type,
tag_or_groups=tag_or_groups, tag_exclude=tag_exclude,
platform=platform, untagged=untagged, no_artist=no_artist, platform=platform, untagged=untagged, no_artist=no_artist,
date_from=date_from, date_to=date_to, date_from=date_from, date_to=date_to,
) )
@@ -427,7 +470,10 @@ class GalleryService:
async def facets( async def facets(
self, *, tag_ids: list[int] | None = None, self, *, tag_ids: list[int] | None = None,
post_id: int | None = None, artist_id: int | None = None, post_id: int | None = None, artist_id: int | None = None,
media_type: str | None = None, platform: str | None = None, media_type: str | None = None,
tag_or_groups: list[list[int]] | None = None,
tag_exclude: list[int] | None = None,
platform: str | None = None,
untagged: bool = False, no_artist: bool = False, untagged: bool = False, no_artist: bool = False,
date_from: datetime | None = None, date_to: datetime | None = None, date_from: datetime | None = None, date_to: datetime | None = None,
) -> GalleryFacets: ) -> GalleryFacets:
@@ -437,10 +483,13 @@ class GalleryService:
No outer join is needed — every clause is a correlated EXISTS or a No outer join is needed — every clause is a correlated EXISTS or a
column predicate on ImageRecord. column predicate on ImageRecord.
""" """
_require_single_filter(tag_ids, post_id, artist_id) _require_single_filter(
tag_ids, post_id, artist_id, tag_or_groups, tag_exclude,
)
common = { common = {
"tag_ids": tag_ids, "post_id": post_id, "tag_ids": tag_ids, "post_id": post_id,
"artist_id": artist_id, "media_type": media_type, "artist_id": artist_id, "media_type": media_type,
"tag_or_groups": tag_or_groups, "tag_exclude": tag_exclude,
} }
# total — the full active filter (the headline result count). # total — the full active filter (the headline result count).
@@ -515,7 +564,10 @@ class GalleryService:
async def similar( async def similar(
self, image_id: int, limit: int = 100, *, self, image_id: int, limit: int = 100, *,
tag_ids: list[int] | None = None, artist_id: int | None = None, tag_ids: list[int] | None = None, artist_id: int | None = None,
media_type: str | None = None, platform: str | None = None, media_type: str | None = None,
tag_or_groups: list[list[int]] | None = None,
tag_exclude: list[int] | None = None,
platform: str | None = None,
untagged: bool = False, no_artist: bool = False, untagged: bool = False, no_artist: bool = False,
date_from: datetime | None = None, date_to: datetime | None = None, date_from: datetime | None = None, date_to: datetime | None = None,
) -> list[GalleryImage] | None: ) -> list[GalleryImage] | None:
@@ -547,6 +599,7 @@ class GalleryService:
stmt = _apply_scope( stmt = _apply_scope(
stmt, tag_ids=tag_ids, post_id=None, stmt, tag_ids=tag_ids, post_id=None,
artist_id=artist_id, media_type=media_type, artist_id=artist_id, media_type=media_type,
tag_or_groups=tag_or_groups, tag_exclude=tag_exclude,
platform=platform, untagged=untagged, no_artist=no_artist, platform=platform, untagged=untagged, no_artist=no_artist,
date_from=date_from, date_to=date_to, date_from=date_from, date_to=date_to,
) )
+12 -1
View File
@@ -3,6 +3,10 @@
<v-chip <v-chip
size="small" closable size="small" closable
:color="store.colorFor(tag.kind)" variant="tonal" :color="store.colorFor(tag.kind)" variant="tonal"
class="fc-tag-chip__nav"
role="link"
:title="`Browse images tagged “${tag.name}”`"
@click="$emit('navigate', tag)"
@click:close="$emit('remove', tag.id)" @click:close="$emit('remove', tag.id)"
> >
<v-icon start size="x-small">{{ iconFor(tag.kind) }}</v-icon> <v-icon start size="x-small">{{ iconFor(tag.kind) }}</v-icon>
@@ -30,7 +34,7 @@ import { useTagStore } from '../../stores/tags.js'
import KebabMenu from '../common/KebabMenu.vue' import KebabMenu from '../common/KebabMenu.vue'
const props = defineProps({ tag: { type: Object, required: true } }) const props = defineProps({ tag: { type: Object, required: true } })
defineEmits(['remove', 'rename', 'set-fandom']) defineEmits(['remove', 'rename', 'set-fandom', 'navigate'])
const store = useTagStore() const store = useTagStore()
@@ -53,6 +57,13 @@ function iconFor (k) { return KIND_ICONS[k] || 'mdi-tag' }
<style scoped> <style scoped>
.fc-tag-chip { display: inline-flex; align-items: center; gap: 1px; } .fc-tag-chip { display: inline-flex; align-items: center; gap: 1px; }
/* The chip body navigates to the filtered gallery (#5); signal it's clickable.
The close ✕ (remove) and the sibling kebab stay as the explicit controls. */
.fc-tag-chip__nav { cursor: pointer; }
.fc-tag-chip__nav:focus-visible {
outline: 2px solid rgb(var(--v-theme-accent));
outline-offset: 1px;
}
.fc-tag-chip__kebab { opacity: 0.7; } .fc-tag-chip__kebab { opacity: 0.7; }
.fc-tag-chip:hover .fc-tag-chip__kebab { opacity: 1; } .fc-tag-chip:hover .fc-tag-chip__kebab { opacity: 1; }
.fc-tag-chip__fandom { opacity: 0.7; font-size: 0.85em; } .fc-tag-chip__fandom { opacity: 0.7; font-size: 0.85em; }
@@ -6,6 +6,7 @@
v-for="tag in modal.current?.tags || []" v-for="tag in modal.current?.tags || []"
:key="tag.id" :tag="tag" :key="tag.id" :tag="tag"
@remove="onRemove" @rename="openRename" @set-fandom="openSetFandom" @remove="onRemove" @rename="openRename" @set-fandom="openSetFandom"
@navigate="onNavigate"
/> />
<span v-if="!modal.current?.tags?.length" class="text-caption">No tags yet.</span> <span v-if="!modal.current?.tags?.length" class="text-caption">No tags yet.</span>
</div> </div>
@@ -51,6 +52,7 @@
<script setup> <script setup>
import { ref } from 'vue' import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useModalStore } from '../../stores/modal.js' import { useModalStore } from '../../stores/modal.js'
import { useSuggestionsStore } from '../../stores/suggestions.js' import { useSuggestionsStore } from '../../stores/suggestions.js'
import TagChip from './TagChip.vue' import TagChip from './TagChip.vue'
@@ -61,9 +63,18 @@ import FandomSetDialog from './FandomSetDialog.vue'
const modal = useModalStore() const modal = useModalStore()
const suggestions = useSuggestionsStore() const suggestions = useSuggestionsStore()
const router = useRouter()
const errorMsg = ref(null) const errorMsg = ref(null)
const tagInputRef = ref(null) const tagInputRef = ref(null)
// #5: clicking a tag chip's body leaves the modal and opens the gallery
// filtered for that single tag (a fresh filter — the obvious "show me more
// like this tag" move). Rename/set-fandom (kebab) and remove (✕) stay put.
async function onNavigate(tag) {
await modal.close()
router.push({ name: 'gallery', query: { tag_id: String(tag.id) } })
}
// Return focus to the tag input after a suggestion is accepted (from the // Return focus to the tag input after a suggestion is accepted (from the
// Suggestions panel or the autocomplete dropdown) so the operator can keep // Suggestions panel or the autocomplete dropdown) so the operator can keep
// typing the next tag without re-clicking the field (operator-asked 2026-06-08). // typing the next tag without re-clicking the field (operator-asked 2026-06-08).
+61 -1
View File
@@ -2,7 +2,8 @@ from datetime import UTC, datetime, timedelta
import pytest import pytest
from backend.app.models import ImageRecord from backend.app.models import ImageRecord, Tag, TagKind
from backend.app.models.tag import image_tag
pytestmark = pytest.mark.integration pytestmark = pytest.mark.integration
@@ -114,3 +115,62 @@ async def test_scroll_date_from_param(client, db):
resp = await client.get("/api/gallery/scroll?date_from=2099-01-01&limit=10") resp = await client.get("/api/gallery/scroll?date_from=2099-01-01&limit=10")
assert resp.status_code == 200 assert resp.status_code == 200
assert (await resp.get_json())["images"] == [] assert (await resp.get_json())["images"] == []
async def _seed_tagged(db):
"""3 images: [0]→a, [1]→b, [2]→x. Returns (records, {a,b,x} tag ids)."""
records = []
base = datetime.now(UTC)
for i in range(3):
r = ImageRecord(
path=f"/images/t/{i}.jpg", sha256=f"t{i:063d}",
size_bytes=1, mime="image/jpeg", width=1, height=1,
origin="imported_filesystem", integrity_status="unknown",
)
r.created_at = base - timedelta(minutes=i)
r.effective_date = r.created_at
db.add(r)
records.append(r)
a = Tag(name="apia", kind=TagKind.general)
b = Tag(name="apib", kind=TagKind.general)
x = Tag(name="apix", kind=TagKind.general)
db.add_all([a, b, x])
await db.flush()
await db.execute(image_tag.insert().values([
{"image_record_id": records[0].id, "tag_id": a.id, "source": "manual"},
{"image_record_id": records[1].id, "tag_id": b.id, "source": "manual"},
{"image_record_id": records[2].id, "tag_id": x.id, "source": "manual"},
]))
await db.commit()
return records, {"a": a.id, "b": b.id, "x": x.id}
@pytest.mark.asyncio
async def test_scroll_tag_or_param(client, db):
# ?tag_or=a,b is one OR-group → images carrying a OR b (not x-only).
records, ids = await _seed_tagged(db)
resp = await client.get(f"/api/gallery/scroll?tag_or={ids['a']},{ids['b']}&limit=10")
assert resp.status_code == 200
got = {i["id"] for i in (await resp.get_json())["images"]}
assert got == {records[0].id, records[1].id}
@pytest.mark.asyncio
async def test_scroll_tag_not_param(client, db):
# ?tag_not=x excludes the x-tagged image.
records, ids = await _seed_tagged(db)
resp = await client.get(f"/api/gallery/scroll?tag_not={ids['x']}&limit=10")
assert resp.status_code == 200
got = {i["id"] for i in (await resp.get_json())["images"]}
assert got == {records[0].id, records[1].id}
@pytest.mark.asyncio
async def test_scroll_repeated_tag_or_groups_anded(client, db):
# Two ?tag_or= groups AND together: (a) AND (b) → no single image has both.
records, ids = await _seed_tagged(db)
resp = await client.get(
f"/api/gallery/scroll?tag_or={ids['a']}&tag_or={ids['b']}&limit=10"
)
assert resp.status_code == 200
assert (await resp.get_json())["images"] == []
+87
View File
@@ -305,6 +305,93 @@ async def test_scroll_multi_tag_and(db):
assert {i.id for i in just_a.images} == {images[0].id, images[1].id} assert {i.id for i in just_a.images} == {images[0].id, images[1].id}
@pytest.mark.asyncio
async def test_scroll_tag_or_group(db):
# #6: one OR-group — match images carrying AT LEAST ONE of the group's tags.
images = await _seed_images(db, 3)
a = Tag(name="ora", kind=TagKind.general)
b = Tag(name="orb", kind=TagKind.general)
db.add_all([a, b])
await db.flush()
await db.execute(image_tag.insert().values([
{"image_record_id": images[0].id, "tag_id": a.id, "source": "manual"},
{"image_record_id": images[1].id, "tag_id": b.id, "source": "manual"},
# images[2] carries neither.
]))
svc = GalleryService(db)
page = await svc.scroll(cursor=None, limit=10, tag_or_groups=[[a.id, b.id]])
assert {i.id for i in page.images} == {images[0].id, images[1].id}
@pytest.mark.asyncio
async def test_scroll_tag_or_groups_anded(db):
# Two OR-groups AND together: image must satisfy (a OR b) AND (c).
images = await _seed_images(db, 3)
a = Tag(name="aaa", kind=TagKind.general)
b = Tag(name="bbb", kind=TagKind.general)
c = Tag(name="ccc", kind=TagKind.general)
db.add_all([a, b, c])
await db.flush()
await db.execute(image_tag.insert().values([
{"image_record_id": images[0].id, "tag_id": a.id, "source": "manual"},
{"image_record_id": images[0].id, "tag_id": c.id, "source": "manual"},
{"image_record_id": images[1].id, "tag_id": b.id, "source": "manual"},
{"image_record_id": images[2].id, "tag_id": a.id, "source": "manual"},
]))
svc = GalleryService(db)
page = await svc.scroll(
cursor=None, limit=10, tag_or_groups=[[a.id, b.id], [c.id]],
)
# Only images[0] has both an (a-or-b) tag AND c.
assert [i.id for i in page.images] == [images[0].id]
@pytest.mark.asyncio
async def test_scroll_tag_exclude(db):
# #6: exclude — drop images carrying ANY excluded tag.
images = await _seed_images(db, 3)
x = Tag(name="xxx", kind=TagKind.general)
db.add(x)
await db.flush()
await db.execute(image_tag.insert().values(
image_record_id=images[0].id, tag_id=x.id, source="manual",
))
svc = GalleryService(db)
page = await svc.scroll(cursor=None, limit=10, tag_exclude=[x.id])
assert {i.id for i in page.images} == {images[1].id, images[2].id}
@pytest.mark.asyncio
async def test_scroll_or_and_exclude_compose(db):
# The structured model composes: (a OR b) AND NOT x.
images = await _seed_images(db, 3)
a = Tag(name="ca", kind=TagKind.general)
b = Tag(name="cb", kind=TagKind.general)
x = Tag(name="cx", kind=TagKind.general)
db.add_all([a, b, x])
await db.flush()
await db.execute(image_tag.insert().values([
{"image_record_id": images[0].id, "tag_id": a.id, "source": "manual"},
{"image_record_id": images[0].id, "tag_id": x.id, "source": "manual"},
{"image_record_id": images[1].id, "tag_id": b.id, "source": "manual"},
]))
svc = GalleryService(db)
page = await svc.scroll(
cursor=None, limit=10, tag_or_groups=[[a.id, b.id]], tag_exclude=[x.id],
)
# images[0] matches the OR-group but is excluded by x; images[1] survives.
assert [i.id for i in page.images] == [images[1].id]
@pytest.mark.asyncio
async def test_require_single_filter_rejects_post_id_with_or_or_exclude(db):
svc = GalleryService(db)
with pytest.raises(ValueError, match="post_id cannot be combined"):
await svc.scroll(cursor=None, limit=10, post_id=5, tag_or_groups=[[1]])
with pytest.raises(ValueError, match="post_id cannot be combined"):
await svc.scroll(cursor=None, limit=10, post_id=5, tag_exclude=[1])
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_scroll_media_filter(db): async def test_scroll_media_filter(db):
imgs = await _seed_images(db, 2) # image/jpeg imgs = await _seed_images(db, 2) # image/jpeg