Make Starred and Saved-for-later pre-configured system tags

UserArticleState.is_starred/is_saved_for_later/starred_at are gone —
starring and saving now add/remove an ArticleTag against a per-user
"Starred" / "Saved for later" Tag, created lazily on first use and marked
Tag.is_system=True. is_read/is_hidden stay on UserArticleState since
they're genuine reading state, not categorization, which is what made
these two candidates for unifying into the general tag mechanism.

System tags are excluded from the Manage Tags page and from delete_tag
(get_object_or_404 now requires is_system=False, so attempting to delete
one 404s) and from the subscription-tag autocomplete, since they
categorize articles, not feeds. The star/save icons are still exactly
where they were — this only changes what powers them.

apps.rules.engine's star action now does get_system_tag + ArticleTag.
get_or_create instead of setting a boolean field. A data migration
converts every existing is_starred=True/is_saved_for_later=True row into
its ArticleTag equivalent before the fields are dropped — verified by
seeding the pre-removal schema directly (including a row with both flags
set) and confirming the migration produces the right tags.

apps.articles.queries.with_user_state gained one more query (tag lookup
for the current page's articles) to stay in the same "fixed number of
queries regardless of article count" shape it already had.

Verified end to end against a running dev server: toggling star/saved,
the starred/saved filters, the sidebar's Favourites count, and that the
Starred tag doesn't appear on the Manage Tags page.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
ksmithandClaude Sonnet 5 committed 2026-10-30 21:36:44 -06:00
1 parent 0e132e9ab9
commit 753ae9efc7
15 files changed
+267 -82

No files matched your search

+10 -5
View File
@@ -1,6 +1,6 @@
from django.contrib import admin from django.contrib import admin
from .models import Article, ArticleTag, Tag, UserArticleState from .models import Article, ArticleTag, SubscriptionTag, Tag, UserArticleState
@admin.register(Article) @admin.register(Article)
@@ -12,16 +12,21 @@ class ArticleAdmin(admin.ModelAdmin):
@admin.register(UserArticleState) @admin.register(UserArticleState)
class UserArticleStateAdmin(admin.ModelAdmin): class UserArticleStateAdmin(admin.ModelAdmin):
list_display = ["user", "article", "is_read", "is_starred", "is_saved_for_later", "is_hidden"] list_display = ["user", "article", "is_read", "is_hidden"]
list_filter = ["is_read", "is_starred", "is_saved_for_later", "is_hidden"] list_filter = ["is_read", "is_hidden"]
@admin.register(Tag) @admin.register(Tag)
class TagAdmin(admin.ModelAdmin): class TagAdmin(admin.ModelAdmin):
list_display = ["name", "user", "color"] list_display = ["name", "user", "color", "is_system"]
list_filter = ["user"] list_filter = ["user", "is_system"]
@admin.register(ArticleTag) @admin.register(ArticleTag)
class ArticleTagAdmin(admin.ModelAdmin): class ArticleTagAdmin(admin.ModelAdmin):
list_display = ["user", "article", "tag"] list_display = ["user", "article", "tag"]
@admin.register(SubscriptionTag)
class SubscriptionTagAdmin(admin.ModelAdmin):
list_display = ["user", "subscription", "tag"]
@@ -0,0 +1,65 @@
from django.db import migrations, models
STARRED_TAG_NAME = "Starred"
SAVED_TAG_NAME = "Saved for later"
def migrate_star_and_saved_to_tags(apps, schema_editor):
UserArticleState = apps.get_model("articles", "UserArticleState")
Tag = apps.get_model("articles", "Tag")
ArticleTag = apps.get_model("articles", "ArticleTag")
tag_cache: dict[tuple[int, str], object] = {}
def system_tag(user_id, name):
key = (user_id, name)
if key not in tag_cache:
tag, _ = Tag.objects.get_or_create(
user_id=user_id, name=name, defaults={"is_system": True}
)
tag_cache[key] = tag
return tag_cache[key]
for state in UserArticleState.objects.filter(is_starred=True):
tag = system_tag(state.user_id, STARRED_TAG_NAME)
ArticleTag.objects.get_or_create(user_id=state.user_id, article=state.article, tag=tag)
for state in UserArticleState.objects.filter(is_saved_for_later=True):
tag = system_tag(state.user_id, SAVED_TAG_NAME)
ArticleTag.objects.get_or_create(user_id=state.user_id, article=state.article, tag=tag)
def noop_reverse(apps, schema_editor):
pass
class Migration(migrations.Migration):
dependencies = [
("articles", "0003_migrate_folders_to_tags"),
]
operations = [
migrations.AddField(
model_name="tag",
name="is_system",
field=models.BooleanField(default=False),
),
migrations.RunPython(migrate_star_and_saved_to_tags, noop_reverse),
migrations.RemoveIndex(
model_name="userarticlestate",
name="articles_us_user_id_cb0761_idx",
),
migrations.RemoveField(
model_name="userarticlestate",
name="is_starred",
),
migrations.RemoveField(
model_name="userarticlestate",
name="is_saved_for_later",
),
migrations.RemoveField(
model_name="userarticlestate",
name="starred_at",
),
]
+20 -7
View File
@@ -33,11 +33,15 @@ class Article(models.Model):
class UserArticleState(models.Model): class UserArticleState(models.Model):
"""Per-user read/star/save/hide state for an Article. """Per-user read/hide state for an Article.
Starred and saved-for-later are ArticleTags against pre-configured
system tags instead of fields here (see Tag.is_system) — read/hidden
stay here since they're genuine reading state, not categorization.
Rows are created lazily, only on first interaction — a row with no Rows are created lazily, only on first interaction — a row with no
explicit True flags is equivalent to "no row exists" (unread, not explicit True flags is equivalent to "no row exists" (unread). Never
starred). Never bulk-create one of these per subscriber on ingest. bulk-create one of these per subscriber on ingest.
""" """
user = models.ForeignKey( user = models.ForeignKey(
@@ -46,30 +50,34 @@ class UserArticleState(models.Model):
article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name="user_states") article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name="user_states")
is_read = models.BooleanField(default=False) is_read = models.BooleanField(default=False)
is_starred = models.BooleanField(default=False)
is_saved_for_later = models.BooleanField(default=False)
is_hidden = models.BooleanField(default=False) is_hidden = models.BooleanField(default=False)
read_at = models.DateTimeField(null=True, blank=True) read_at = models.DateTimeField(null=True, blank=True)
starred_at = models.DateTimeField(null=True, blank=True)
class Meta: class Meta:
unique_together = [("user", "article")] unique_together = [("user", "article")]
indexes = [ indexes = [
models.Index(fields=["user", "is_read"]), models.Index(fields=["user", "is_read"]),
models.Index(fields=["user", "is_starred"]),
] ]
def __str__(self): def __str__(self):
return f"{self.user}: {self.article}" return f"{self.user}: {self.article}"
# Pre-configured per-user tags backing the star/save-for-later icons —
# created lazily on first use (see get_system_tag), same as any other tag,
# just under a name the app itself controls rather than the user.
STARRED_TAG_NAME = "Starred"
SAVED_TAG_NAME = "Saved for later"
class Tag(models.Model): class Tag(models.Model):
user = models.ForeignKey( user = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="tags" settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="tags"
) )
name = models.CharField(max_length=100) name = models.CharField(max_length=100)
color = models.CharField(max_length=7, blank=True) color = models.CharField(max_length=7, blank=True)
is_system = models.BooleanField(default=False)
class Meta: class Meta:
unique_together = [("user", "name")] unique_together = [("user", "name")]
@@ -79,6 +87,11 @@ class Tag(models.Model):
return self.name return self.name
def get_system_tag(user, name):
tag, _ = Tag.objects.get_or_create(user=user, name=name, defaults={"is_system": True})
return tag
class ArticleTag(models.Model): class ArticleTag(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name="article_tags") article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name="article_tags")
+20 -7
View File
@@ -1,12 +1,14 @@
from django.db.models import Count from django.db.models import Count
from .models import Article, UserArticleState from .models import SAVED_TAG_NAME, STARRED_TAG_NAME, Article, ArticleTag, UserArticleState
def with_user_state(articles, user): def with_user_state(articles, user):
"""Annotates an iterable of Article instances with is_read/is_starred/ """Annotates an iterable of Article instances with is_read/is_starred/
is_saved_for_later booleans for the given user, in two queries total is_saved_for_later booleans for the given user, in two queries total
regardless of how many articles there are (no N+1). regardless of how many articles there are (no N+1). Starred/saved come
from ArticleTag against the pre-configured system tags, not a field on
UserArticleState — see Tag.is_system.
Accepts either a queryset or a plain list (search backends return Accepts either a queryset or a plain list (search backends return
plain lists already ordered by relevance), materializing it either plain lists already ordered by relevance), materializing it either
@@ -16,17 +18,28 @@ def with_user_state(articles, user):
if not articles: if not articles:
return articles return articles
article_ids = [a.pk for a in articles]
states = { states = {
state.article_id: state state.article_id: state
for state in UserArticleState.objects.filter( for state in UserArticleState.objects.filter(user=user, article_id__in=article_ids)
user=user, article_id__in=[a.pk for a in articles]
)
} }
starred_ids = set()
saved_ids = set()
tag_rows = ArticleTag.objects.filter(
user=user,
article_id__in=article_ids,
tag__is_system=True,
tag__name__in=[STARRED_TAG_NAME, SAVED_TAG_NAME],
).values_list("article_id", "tag__name")
for article_id, tag_name in tag_rows:
(starred_ids if tag_name == STARRED_TAG_NAME else saved_ids).add(article_id)
for article in articles: for article in articles:
state = states.get(article.pk) state = states.get(article.pk)
article.is_read = state.is_read if state else False article.is_read = state.is_read if state else False
article.is_starred = state.is_starred if state else False article.is_starred = article.pk in starred_ids
article.is_saved_for_later = state.is_saved_for_later if state else False article.is_saved_for_later = article.pk in saved_ids
return articles return articles
+11 -5
View File
@@ -4,12 +4,18 @@ from django.contrib.auth import get_user_model
from apps.feeds.models import Feed, Subscription from apps.feeds.models import Feed, Subscription
from apps.rules.models import FilterRule from apps.rules.models import FilterRule
from .models import Article, SubscriptionTag, Tag, UserArticleState from .models import STARRED_TAG_NAME, Article, ArticleTag, SubscriptionTag, Tag, UserArticleState
from .tasks import apply_filter_rules_for_feed from .tasks import apply_filter_rules_for_feed
User = get_user_model() User = get_user_model()
def is_starred(user, article):
return ArticleTag.objects.filter(
user=user, article=article, tag__is_system=True, tag__name=STARRED_TAG_NAME
).exists()
@pytest.fixture @pytest.fixture
def feed(db): def feed(db):
return Feed.objects.create(feed_url="https://example.com/feed.xml", title="Example Feed") return Feed.objects.create(feed_url="https://example.com/feed.xml", title="Example Feed")
@@ -40,7 +46,7 @@ def test_dispatch_applies_rules_only_for_subscribers_with_matching_rules(feed, a
apply_filter_rules_for_feed(feed.id, [article.pk]) apply_filter_rules_for_feed(feed.id, [article.pk])
assert UserArticleState.objects.get(user=alice, article=article).is_starred is True assert is_starred(alice, article) is True
# Bob has no rules, so he should get no state row at all. # Bob has no rules, so he should get no state row at all.
assert not UserArticleState.objects.filter(user=bob, article=article).exists() assert not UserArticleState.objects.filter(user=bob, article=article).exists()
@@ -67,7 +73,7 @@ def test_feed_scoped_rule_does_not_apply_to_other_feeds(alice):
apply_filter_rules_for_feed(feed_a.id, [article_a.pk]) apply_filter_rules_for_feed(feed_a.id, [article_a.pk])
apply_filter_rules_for_feed(feed_b.id, [article_b.pk]) apply_filter_rules_for_feed(feed_b.id, [article_b.pk])
assert UserArticleState.objects.get(user=alice, article=article_a).is_starred is True assert is_starred(alice, article_a) is True
assert not UserArticleState.objects.filter(user=alice, article=article_b).exists() assert not UserArticleState.objects.filter(user=alice, article=article_b).exists()
@@ -96,7 +102,7 @@ def test_tag_scoped_rule_only_applies_to_feeds_carrying_that_tag(alice, feed):
apply_filter_rules_for_feed(feed.id, [tagged_article.pk]) apply_filter_rules_for_feed(feed.id, [tagged_article.pk])
apply_filter_rules_for_feed(other_feed.id, [untagged_article.pk]) apply_filter_rules_for_feed(other_feed.id, [untagged_article.pk])
assert UserArticleState.objects.get(user=alice, article=tagged_article).is_starred is True assert is_starred(alice, tagged_article) is True
assert not UserArticleState.objects.filter(user=alice, article=untagged_article).exists() assert not UserArticleState.objects.filter(user=alice, article=untagged_article).exists()
@@ -120,7 +126,7 @@ def test_rule_scoped_to_one_tag_still_applies_to_a_feed_with_multiple_tags(alice
apply_filter_rules_for_feed(feed.id, [article.pk]) apply_filter_rules_for_feed(feed.id, [article.pk])
assert UserArticleState.objects.get(user=alice, article=article).is_starred is True assert is_starred(alice, article) is True
@pytest.mark.django_db @pytest.mark.django_db
+4 -2
View File
@@ -23,14 +23,16 @@ def tag_list(request):
tag.save() tag.save()
return redirect("articles:tag_list") return redirect("articles:tag_list")
tags = Tag.objects.filter(user=request.user) # Starred/Saved for later are pre-configured tags (see Tag.is_system) —
# managed only via the star/save icons, not this page.
tags = Tag.objects.filter(user=request.user, is_system=False)
return render(request, "articles/tags.html", {"tags": tags, "form": form}) return render(request, "articles/tags.html", {"tags": tags, "form": form})
@login_required @login_required
@require_POST @require_POST
def delete_tag(request, tag_id): def delete_tag(request, tag_id):
tag = get_object_or_404(Tag, user=request.user, pk=tag_id) tag = get_object_or_404(Tag, user=request.user, pk=tag_id, is_system=False)
tag.delete() tag.delete()
return redirect("articles:tag_list") return redirect("articles:tag_list")
+6 -4
View File
@@ -1,4 +1,4 @@
from apps.articles.models import SubscriptionTag, Tag, UserArticleState from apps.articles.models import STARRED_TAG_NAME, ArticleTag, SubscriptionTag, Tag
from apps.articles.queries import unread_counts_by_feed from apps.articles.queries import unread_counts_by_feed
from apps.feeds.models import Subscription from apps.feeds.models import Subscription
@@ -17,7 +17,9 @@ def sidebar(request):
return {} return {}
unread_counts = unread_counts_by_feed(user) unread_counts = unread_counts_by_feed(user)
tags = list(Tag.objects.filter(user=user)) # System tags (Starred/Saved for later) categorize articles, not feeds
# — they get their own pinned nav items above, not a feed-tag group.
tags = list(Tag.objects.filter(user=user, is_system=False))
tag_rows = ( tag_rows = (
SubscriptionTag.objects.filter(user=user) SubscriptionTag.objects.filter(user=user)
@@ -45,7 +47,7 @@ def sidebar(request):
{"tag": tag, "subscriptions": feeds_by_tag.get(tag.pk, [])} for tag in tags {"tag": tag, "subscriptions": feeds_by_tag.get(tag.pk, [])} for tag in tags
], ],
"sidebar_untagged": untagged, "sidebar_untagged": untagged,
"sidebar_starred_count": UserArticleState.objects.filter( "sidebar_starred_count": ArticleTag.objects.filter(
user=user, is_starred=True user=user, tag__user=user, tag__name=STARRED_TAG_NAME, tag__is_system=True
).count(), ).count(),
} }
+6 -4
View File
@@ -177,10 +177,12 @@ def test_refetching_updated_content_does_not_reset_user_state():
fetch_and_ingest(feed) fetch_and_ingest(feed)
feed.save() feed.save()
from apps.articles.models import STARRED_TAG_NAME, ArticleTag, get_system_tag
article = Article.objects.get(feed=feed) article = Article.objects.get(feed=feed)
state = UserArticleState.objects.create( state = UserArticleState.objects.create(user=user, article=article, is_read=True)
user=user, article=article, is_read=True, is_starred=True starred_tag = get_system_tag(user, STARRED_TAG_NAME)
) ArticleTag.objects.create(user=user, article=article, tag=starred_tag)
updated_xml = GOOD_FEED_XML.replace("First post", "First post (edited)") updated_xml = GOOD_FEED_XML.replace("First post", "First post (edited)")
responses.add(responses.GET, FEED_URL, body=updated_xml, status=200) responses.add(responses.GET, FEED_URL, body=updated_xml, status=200)
@@ -193,4 +195,4 @@ def test_refetching_updated_content_does_not_reset_user_state():
state.refresh_from_db() state.refresh_from_db()
assert state.is_read is True assert state.is_read is True
assert state.is_starred is True assert ArticleTag.objects.filter(user=user, article=article, tag=starred_tag).exists()
+5 -1
View File
@@ -97,7 +97,11 @@ def subscription_tags_partial(request, subscription_id):
tags = Tag.objects.filter( tags = Tag.objects.filter(
subscription_tags__subscription=subscription, subscription_tags__user=request.user subscription_tags__subscription=subscription, subscription_tags__user=request.user
) )
all_user_tags = Tag.objects.filter(user=request.user).exclude(pk__in=[t.pk for t in tags]) # Starred/Saved for later categorize articles, not feeds — don't
# suggest them here (see Tag.is_system).
all_user_tags = Tag.objects.filter(user=request.user, is_system=False).exclude(
pk__in=[t.pk for t in tags]
)
return render( return render(
request, request,
"feeds/_subscription_tags.html", "feeds/_subscription_tags.html",
+18 -8
View File
@@ -2,7 +2,7 @@ import pytest
from django.contrib.auth import get_user_model from django.contrib.auth import get_user_model
from django.urls import reverse from django.urls import reverse
from apps.articles.models import Article, UserArticleState from apps.articles.models import STARRED_TAG_NAME, Article, ArticleTag, UserArticleState
from apps.feeds.models import Feed, Subscription from apps.feeds.models import Feed, Subscription
User = get_user_model() User = get_user_model()
@@ -91,14 +91,20 @@ def test_toggle_star_flips_state_and_persists(client, alice, alices_article):
response = client.post(url) response = client.post(url)
assert response.status_code == 200 assert response.status_code == 200
state = UserArticleState.objects.get(user=alice, article=alices_article) assert ArticleTag.objects.filter(
assert state.is_starred is True user=alice,
assert state.starred_at is not None article=alices_article,
tag__is_system=True,
tag__name=STARRED_TAG_NAME,
).exists()
client.post(url) client.post(url)
state.refresh_from_db() assert not ArticleTag.objects.filter(
assert state.is_starred is False user=alice,
assert state.starred_at is None article=alices_article,
tag__is_system=True,
tag__name=STARRED_TAG_NAME,
).exists()
@pytest.mark.django_db @pytest.mark.django_db
@@ -118,7 +124,11 @@ def test_user_cannot_toggle_state_on_another_users_article(client, alice, bob, a
@pytest.mark.django_db @pytest.mark.django_db
def test_stream_remembers_last_selected_filter(client, alice, alices_article): def test_stream_remembers_last_selected_filter(client, alice, alices_article):
UserArticleState.objects.create(user=alice, article=alices_article, is_starred=True) from apps.articles.models import get_system_tag
ArticleTag.objects.create(
user=alice, article=alices_article, tag=get_system_tag(alice, STARRED_TAG_NAME)
)
client.login(username="alice", password="pw-alice-123") client.login(username="alice", password="pw-alice-123")
response = client.get(reverse("reader:stream"), {"filter": "starred"}) response = client.get(reverse("reader:stream"), {"filter": "starred"})
+61 -21
View File
@@ -8,7 +8,15 @@ from django.urls import reverse
from django.utils import timezone from django.utils import timezone
from django.views.decorators.http import require_POST from django.views.decorators.http import require_POST
from apps.articles.models import Article, Tag, UserArticleState from apps.articles.models import (
SAVED_TAG_NAME,
STARRED_TAG_NAME,
Article,
ArticleTag,
Tag,
UserArticleState,
get_system_tag,
)
from apps.articles.queries import with_user_state from apps.articles.queries import with_user_state
from apps.feeds.models import Feed from apps.feeds.models import Feed
@@ -37,6 +45,20 @@ def _get_or_create_state(user, article):
return state return state
def _article_tag_flags(user, article):
"""is_starred/is_saved_for_later for a single article — the toggle
views' equivalent of with_user_state's bulk version."""
tag_names = set(
ArticleTag.objects.filter(
user=user,
article=article,
tag__is_system=True,
tag__name__in=[STARRED_TAG_NAME, SAVED_TAG_NAME],
).values_list("tag__name", flat=True)
)
return STARRED_TAG_NAME in tag_names, SAVED_TAG_NAME in tag_names
def _apply_scope(request, queryset): def _apply_scope(request, queryset):
"""Narrows an already-base-scoped Article queryset by the optional """Narrows an already-base-scoped Article queryset by the optional
?tag=/?feed= params the sidebar links use. feed_id alone is enough to ?tag=/?feed= params the sidebar links use. feed_id alone is enough to
@@ -111,10 +133,18 @@ def stream(request):
if active_filter == "unread": if active_filter == "unread":
queryset = queryset.exclude(user_states__user=request.user, user_states__is_read=True) queryset = queryset.exclude(user_states__user=request.user, user_states__is_read=True)
elif active_filter == "starred": elif active_filter == "starred":
queryset = queryset.filter(user_states__user=request.user, user_states__is_starred=True) queryset = queryset.filter(
article_tags__user=request.user,
article_tags__tag__user=request.user,
article_tags__tag__name=STARRED_TAG_NAME,
article_tags__tag__is_system=True,
)
elif active_filter == "saved": elif active_filter == "saved":
queryset = queryset.filter( queryset = queryset.filter(
user_states__user=request.user, user_states__is_saved_for_later=True article_tags__user=request.user,
article_tags__tag__user=request.user,
article_tags__tag__name=SAVED_TAG_NAME,
article_tags__tag__is_system=True,
) )
queryset, active_tag, active_feed = _apply_scope(request, queryset) queryset, active_tag, active_feed = _apply_scope(request, queryset)
@@ -188,8 +218,7 @@ def _load_article_and_mark_read(user, article_id):
state.save(update_fields=["is_read", "read_at"]) state.save(update_fields=["is_read", "read_at"])
article.is_read = state.is_read article.is_read = state.is_read
article.is_starred = state.is_starred article.is_starred, article.is_saved_for_later = _article_tag_flags(user, article)
article.is_saved_for_later = state.is_saved_for_later
return article return article
@@ -212,38 +241,49 @@ def article_inline(request, article_id):
@login_required @login_required
@require_POST @require_POST
def toggle_read(request, article_id): def toggle_read(request, article_id):
return _toggle(request, article_id, "is_read", "read_at") article = _owned_article(request.user, article_id)
state = _get_or_create_state(request.user, article)
state.is_read = not state.is_read
state.read_at = timezone.now() if state.is_read else None
state.save(update_fields=["is_read", "read_at"])
article.is_read = state.is_read
article.is_starred, article.is_saved_for_later = _article_tag_flags(request.user, article)
return render(request, "reader/_article_actions.html", {"article": article})
@login_required @login_required
@require_POST @require_POST
def toggle_star(request, article_id): def toggle_star(request, article_id):
return _toggle(request, article_id, "is_starred", "starred_at") return _toggle_system_tag(request, article_id, STARRED_TAG_NAME)
@login_required @login_required
@require_POST @require_POST
def toggle_saved(request, article_id): def toggle_saved(request, article_id):
return _toggle(request, article_id, "is_saved_for_later", None) return _toggle_system_tag(request, article_id, SAVED_TAG_NAME)
def _toggle(request, article_id, flag_field, timestamp_field): def _owned_article(user, article_id):
try: try:
article = _base_queryset(request.user).get(pk=article_id) return _base_queryset(user).get(pk=article_id)
except Article.DoesNotExist: except Article.DoesNotExist:
raise Http404 raise Http404
state = _get_or_create_state(request.user, article)
new_value = not getattr(state, flag_field)
setattr(state, flag_field, new_value)
update_fields = [flag_field]
if timestamp_field:
setattr(state, timestamp_field, timezone.now() if new_value else None)
update_fields.append(timestamp_field)
state.save(update_fields=update_fields)
article.is_read = state.is_read def _toggle_system_tag(request, article_id, tag_name):
article.is_starred = state.is_starred article = _owned_article(request.user, article_id)
article.is_saved_for_later = state.is_saved_for_later
tag = get_system_tag(request.user, tag_name)
existing = ArticleTag.objects.filter(user=request.user, article=article, tag=tag)
if existing.exists():
existing.delete()
else:
ArticleTag.objects.create(user=request.user, article=article, tag=tag)
state = UserArticleState.objects.filter(user=request.user, article=article).first()
article.is_read = state.is_read if state else False
article.is_starred, article.is_saved_for_later = _article_tag_flags(request.user, article)
return render(request, "reader/_article_actions.html", {"article": article}) return render(request, "reader/_article_actions.html", {"article": article})
+10 -4
View File
@@ -12,7 +12,14 @@ import re
from django.utils import timezone from django.utils import timezone
from apps.articles.models import Article, ArticleTag, Tag, UserArticleState from apps.articles.models import (
STARRED_TAG_NAME,
Article,
ArticleTag,
Tag,
UserArticleState,
get_system_tag,
)
from .models import FilterRule from .models import FilterRule
@@ -75,9 +82,8 @@ def apply_rule_action(rule: FilterRule, user, article: Article, state: UserArtic
return True return True
if rule.action == FilterRule.ACTION_STAR: if rule.action == FilterRule.ACTION_STAR:
state.is_starred = True tag = get_system_tag(user, STARRED_TAG_NAME)
state.starred_at = state.starred_at or now ArticleTag.objects.get_or_create(user=user, article=article, tag=tag)
state.save(update_fields=["is_starred", "starred_at"])
return False return False
if rule.action == FilterRule.ACTION_MARK_READ: if rule.action == FilterRule.ACTION_MARK_READ:
+17 -7
View File
@@ -1,7 +1,13 @@
import pytest import pytest
from django.contrib.auth import get_user_model from django.contrib.auth import get_user_model
from apps.articles.models import Article, ArticleTag, Tag, UserArticleState from apps.articles.models import (
STARRED_TAG_NAME,
Article,
ArticleTag,
Tag,
UserArticleState,
)
from apps.feeds.models import Feed from apps.feeds.models import Feed
from .engine import evaluate_rules_for_article, rule_matches from .engine import evaluate_rules_for_article, rule_matches
@@ -10,6 +16,12 @@ from .models import FilterRule
User = get_user_model() User = get_user_model()
def is_starred(user, article):
return ArticleTag.objects.filter(
user=user, article=article, tag__is_system=True, tag__name=STARRED_TAG_NAME
).exists()
@pytest.fixture @pytest.fixture
def user(db): def user(db):
return User.objects.create_user("alice", password="pw-alice-123") return User.objects.create_user("alice", password="pw-alice-123")
@@ -98,9 +110,8 @@ class TestApplyRuleAction:
rules = [make_rule(user, action=FilterRule.ACTION_STAR)] rules = [make_rule(user, action=FilterRule.ACTION_STAR)]
evaluate_rules_for_article(user, article, rules) evaluate_rules_for_article(user, article, rules)
assert is_starred(user, article) is True
state = UserArticleState.objects.get(user=user, article=article) state = UserArticleState.objects.get(user=user, article=article)
assert state.is_starred is True
assert state.starred_at is not None
assert state.is_read is False assert state.is_read is False
def test_mark_read_action(self, user, article): def test_mark_read_action(self, user, article):
@@ -143,8 +154,7 @@ class TestRulePriorityAndShortCircuit:
evaluate_rules_for_article(user, article, [tag_rule, star_rule]) evaluate_rules_for_article(user, article, [tag_rule, star_rule])
state = UserArticleState.objects.get(user=user, article=article) assert is_starred(user, article) is True
assert state.is_starred is True
assert Tag.objects.filter(user=user, name="early-tag").exists() assert Tag.objects.filter(user=user, name="early-tag").exists()
def test_hide_short_circuits_later_rules(self, user, article): def test_hide_short_circuits_later_rules(self, user, article):
@@ -156,7 +166,7 @@ class TestRulePriorityAndShortCircuit:
state = UserArticleState.objects.get(user=user, article=article) state = UserArticleState.objects.get(user=user, article=article)
assert state.is_hidden is True assert state.is_hidden is True
# The star rule never ran because hide short-circuited first. # The star rule never ran because hide short-circuited first.
assert state.is_starred is False assert is_starred(user, article) is False
def test_non_hide_actions_stack_across_multiple_rules(self, user, article): def test_non_hide_actions_stack_across_multiple_rules(self, user, article):
star_rule = make_rule(user, priority=1, action=FilterRule.ACTION_STAR) star_rule = make_rule(user, priority=1, action=FilterRule.ACTION_STAR)
@@ -164,6 +174,6 @@ class TestRulePriorityAndShortCircuit:
evaluate_rules_for_article(user, article, [star_rule, read_rule]) evaluate_rules_for_article(user, article, [star_rule, read_rule])
assert is_starred(user, article) is True
state = UserArticleState.objects.get(user=user, article=article) state = UserArticleState.objects.get(user=user, article=article)
assert state.is_starred is True
assert state.is_read is True assert state.is_read is True
+10 -5
View File
@@ -2,7 +2,7 @@ import pytest
from django.contrib.auth import get_user_model from django.contrib.auth import get_user_model
from django.urls import reverse from django.urls import reverse
from apps.articles.models import Article, UserArticleState from apps.articles.models import STARRED_TAG_NAME, Article, ArticleTag, UserArticleState
from apps.feeds.models import Feed, Subscription from apps.feeds.models import Feed, Subscription
from .models import FilterRule from .models import FilterRule
@@ -11,6 +11,12 @@ from .tasks import reapply_rules_for_user_backlog
User = get_user_model() User = get_user_model()
def is_starred(user, article):
return ArticleTag.objects.filter(
user=user, article=article, tag__is_system=True, tag__name=STARRED_TAG_NAME
).exists()
@pytest.fixture @pytest.fixture
def alice(db): def alice(db):
return User.objects.create_user("alice", password="pw-alice-123") return User.objects.create_user("alice", password="pw-alice-123")
@@ -110,7 +116,7 @@ def test_reapply_rule_view_applies_to_unread_backlog(client, alice, feed):
response = client.post(reverse("rules:reapply_rule", args=[rule.pk])) response = client.post(reverse("rules:reapply_rule", args=[rule.pk]))
assert response.status_code == 302 assert response.status_code == 302
assert UserArticleState.objects.get(user=alice, article=article).is_starred is True assert is_starred(alice, article) is True
@pytest.mark.django_db @pytest.mark.django_db
@@ -129,8 +135,7 @@ def test_reapply_skips_already_read_articles(alice, feed):
count = reapply_rules_for_user_backlog(rule.pk) count = reapply_rules_for_user_backlog(rule.pk)
assert count == 0 assert count == 0
state = UserArticleState.objects.get(user=alice, article=article) assert is_starred(alice, article) is False
assert state.is_starred is False
@pytest.mark.django_db @pytest.mark.django_db
@@ -153,5 +158,5 @@ def test_reapply_respects_feed_scope(alice):
reapply_rules_for_user_backlog(rule.pk) reapply_rules_for_user_backlog(rule.pk)
assert UserArticleState.objects.get(user=alice, article=article_a).is_starred is True assert is_starred(alice, article_a) is True
assert not UserArticleState.objects.filter(user=alice, article=article_b).exists() assert not UserArticleState.objects.filter(user=alice, article=article_b).exists()
+4 -2
View File
@@ -2,7 +2,7 @@ import pytest
from django.contrib.auth import get_user_model from django.contrib.auth import get_user_model
from django.urls import reverse from django.urls import reverse
from apps.articles.models import Article, UserArticleState from apps.articles.models import STARRED_TAG_NAME, Article, ArticleTag, get_system_tag
from apps.feeds.models import Feed, Subscription from apps.feeds.models import Feed, Subscription
User = get_user_model() User = get_user_model()
@@ -48,7 +48,9 @@ def test_search_view_with_no_query_shows_no_results_block(client, alice):
def test_search_results_carry_user_state(client, alice, feed): def test_search_results_carry_user_state(client, alice, feed):
Subscription.objects.create(user=alice, feed=feed) Subscription.objects.create(user=alice, feed=feed)
article = Article.objects.create(feed=feed, guid="g1", title="Django 5 release notes") article = Article.objects.create(feed=feed, guid="g1", title="Django 5 release notes")
UserArticleState.objects.create(user=alice, article=article, is_starred=True) ArticleTag.objects.create(
user=alice, article=article, tag=get_system_tag(alice, STARRED_TAG_NAME)
)
client.login(username="alice", password="pw-alice-123") client.login(username="alice", password="pw-alice-123")
response = client.get(reverse("search:search"), {"q": "Django"}) response = client.get(reverse("search:search"), {"q": "Django"})