Skip to content

Commit 3370f51

Browse files
authored
Track restored and unreviewed suggestions in user/translations API (#4649)
- Include translations unapproved or unrejected within the date range, and return `unapproved_date` and `unrejected_date`. - Add `include=restored`, listing translations by other users that the user unrejected, based on ActionLog rather than the latest `unrejected_user`. - Add a `restored` flag to each result. - Use "unrejected" and "unapproved" consistently, without hyphen
1 parent 0f90554 commit 3370f51

7 files changed

Lines changed: 215 additions & 25 deletions

File tree

‎documentation/docs/dev/api.md‎

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -154,10 +154,16 @@ Optional query parameters:
154154
| `end_date` | Last day of the range, inclusive (`YYYY-MM-DD`). Defaults to today |
155155
| `project` | Project slug |
156156
| `locale` | Locale code |
157+
| `include` | Use `restored` to also list translations the user restored (see below) |
157158

158159
The date range can span at most 30 days. A translation is included if it was created,
159-
approved or rejected within the range, and results are sorted by the most recent of these
160-
dates.
160+
approved, unapproved, rejected or unrejected within the range, and results are sorted by
161+
the most recent of these dates.
162+
163+
With `include=restored`, the list also includes translations by other users that the user
164+
unrejected, for example by uploading a matching suggestion through
165+
[`POST /api/v2/upload/suggestions/`](#post-apiv2uploadsuggestions). This lets a client
166+
follow the review status of suggestions it restored, as well as those it created.
161167

162168
An example may look like this:
163169

@@ -180,7 +186,10 @@ $ curl -H "Authorization: Bearer <token>" \
180186
"status": "rejected",
181187
"date": "2026-10-02T09:12:44.123456Z",
182188
"approved_date": null,
189+
"unapproved_date": null,
183190
"rejected_date": "2026-10-03T15:01:02.654321Z",
191+
"unrejected_date": null,
192+
"restored": false,
184193
"entity": "new-tab",
185194
"resource": "browser/tabs.ftl",
186195
"format": "fluent",
@@ -207,6 +216,14 @@ value is empty. `value` and `properties` hold the complete message content, usin
207216
defined by moz-l10n. `properties` contains message properties such as Fluent attributes,
208217
and is `null` if there are none. `format` is the format of the resource.
209218
`status` is one of `approved`, `rejected`, `pretranslated`, `fuzzy` or `unreviewed`.
219+
`approved_date`, `unapproved_date`, `rejected_date` and `unrejected_date` record review
220+
actions. Approving a translation clears `unapproved_date` and `rejected_date`, and
221+
rejecting it clears `approved_date`. Other dates are kept regardless of the current
222+
status: for example, an unrejected translation keeps its `rejected_date`. The most recent
223+
of the four is the latest review action: a translation with status `unreviewed` and both
224+
dates set was rejected on `rejected_date`, then unrejected on `unrejected_date`. Use
225+
`status` for the current state.
226+
`restored` is `true` if the translation is by another user and the user unrejected it.
210227
`entity` is the string identifier as shown in the context of the translate view (e.g. the
211228
Fluent message ID). Multi-part identifiers, such as nested keys, are shown from the
212229
innermost part, separated by `•`. It's `null` for gettext strings without a context. `url` links to
@@ -423,7 +440,7 @@ A successful request returns a summary of the import:
423440

424441
- `created`: number of suggestions added.
425442
- `restored`: number of rejected translations matching the upload that were
426-
un-rejected, becoming pending suggestions again.
443+
unrejected, becoming pending suggestions again.
427444
- `unchanged`: number of uploaded translations that match existing unrejected
428445
translations, in any review state, ignored.
429446
- `failed_checks`: strings left untouched, because the uploaded translation has errors.
@@ -445,7 +462,7 @@ as a suggestion, unless the string already has an unrejected translation with th
445462
value, whether approved, pretranslated or unreviewed. The fuzzy flag of the uploaded
446463
file is ignored: the translation is stored as a plain suggestion.
447464

448-
A rejected translation matching the upload is un-rejected instead of being suggested
465+
A rejected translation matching the upload is unrejected instead of being suggested
449466
again, so a translation rejected by mistake can be re-proposed. Its original author and
450467
date are kept, and it becomes a pending suggestion, awaiting review like any other.
451468

‎pontoon/api/serializers.py‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -396,8 +396,22 @@ class UserTranslationSerializer(serializers.Serializer):
396396
choices=["approved", "fuzzy", "pretranslated", "rejected", "unreviewed"]
397397
)
398398
date = serializers.DateTimeField()
399-
approved_date = serializers.DateTimeField(allow_null=True)
400-
rejected_date = serializers.DateTimeField(allow_null=True)
399+
approved_date = serializers.DateTimeField(
400+
allow_null=True, help_text="Date of the approval, cleared on rejection."
401+
)
402+
unapproved_date = serializers.DateTimeField(
403+
allow_null=True, help_text="Date of the unapproval, cleared on approval."
404+
)
405+
rejected_date = serializers.DateTimeField(
406+
allow_null=True, help_text="Date of the rejection, cleared on approval."
407+
)
408+
unrejected_date = serializers.DateTimeField(
409+
allow_null=True, help_text="Date of the latest unrejection."
410+
)
411+
restored = serializers.BooleanField(
412+
help_text="Whether the translation is by another user and the user "
413+
"unrejected it."
414+
)
401415
entity = serializers.SerializerMethodField()
402416
resource = serializers.CharField(source="entity.resource.path")
403417
format = serializers.ChoiceField(
@@ -664,7 +678,7 @@ class UploadSuggestionsResponseSerializer(serializers.Serializer):
664678
)
665679
restored = serializers.IntegerField(
666680
help_text="Number of rejected translations matching the upload that were "
667-
"un-rejected, becoming pending suggestions again."
681+
"unrejected, becoming pending suggestions again."
668682
)
669683
unchanged = serializers.IntegerField(
670684
help_text="Number of uploaded translations that the string already has as an "

‎pontoon/api/tests/test_views.py‎

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -336,6 +336,114 @@ def test_user_translations_change_date(member, user_b, user_translations_url):
336336
]
337337

338338

339+
@pytest.mark.django_db
340+
def test_user_translations_unreviewed_change_date(
341+
member, user_b, user_translations_url
342+
):
343+
today = now()
344+
old = today - timedelta(days=400)
345+
unrejected = TranslationFactory(
346+
user=user_b,
347+
date=old,
348+
rejected_date=old,
349+
unrejected_date=today - timedelta(days=1),
350+
)
351+
unapproved = TranslationFactory(
352+
user=user_b,
353+
date=old,
354+
approved_date=old,
355+
unapproved_date=today,
356+
)
357+
358+
response = member.client.get(user_translations_url, HTTP_ACCEPT="application/json")
359+
360+
results = response.data["results"]
361+
assert [t["translation_pk"] for t in results] == [unapproved.pk, unrejected.pk]
362+
assert results[0]["status"] == "unreviewed"
363+
assert results[0]["approved_date"] is not None
364+
assert results[0]["unapproved_date"] is not None
365+
assert results[1]["status"] == "unreviewed"
366+
assert results[1]["rejected_date"] is not None
367+
assert results[1]["unrejected_date"] is not None
368+
assert [t["restored"] for t in results] == [False, False]
369+
370+
371+
@pytest.mark.django_db
372+
def test_user_translations_include_restored(
373+
member, user_b, user_c, user_translations_url
374+
):
375+
today = now()
376+
old = today - timedelta(days=400)
377+
378+
def unrejected_by(performer, date, **kwargs):
379+
kwargs = {"user": user_c, "date": old, **kwargs}
380+
translation = TranslationFactory(
381+
unrejected_user=performer, unrejected_date=date, **kwargs
382+
)
383+
ActionLog.objects.create(
384+
action_type=ActionLog.ActionType.TRANSLATION_UNREJECTED,
385+
performed_by=performer,
386+
translation=translation,
387+
)
388+
return translation
389+
390+
own = TranslationFactory(user=user_b, date=today - timedelta(days=2))
391+
own_unrejected = unrejected_by(user_b, today - timedelta(days=5), user=user_b)
392+
restored = unrejected_by(user_b, today - timedelta(days=1))
393+
rejected_again = unrejected_by(
394+
user_b,
395+
today - timedelta(days=3),
396+
rejected=True,
397+
rejected_user=user_c,
398+
rejected_date=today,
399+
)
400+
# Restored outside the date range
401+
unrejected_by(user_b, old)
402+
# Restored by another user
403+
unrejected_by(member.user, today)
404+
# Restored by the user, then rejected and restored again by another user
405+
restored_twice = unrejected_by(user_b, today - timedelta(days=4))
406+
restored_twice.unrejected_user = member.user
407+
restored_twice.save()
408+
ActionLog.objects.create(
409+
action_type=ActionLog.ActionType.TRANSLATION_UNREJECTED,
410+
performed_by=member.user,
411+
translation=restored_twice,
412+
)
413+
414+
def get_results(**params):
415+
response = member.client.get(
416+
user_translations_url, params, HTTP_ACCEPT="application/json"
417+
)
418+
assert response.status_code == 200
419+
return response.data["results"]
420+
421+
results = get_results()
422+
assert [t["translation_pk"] for t in results] == [own.pk, own_unrejected.pk]
423+
assert [t["restored"] for t in results] == [False, False]
424+
425+
results = get_results(include="restored")
426+
assert [t["translation_pk"] for t in results] == [
427+
rejected_again.pk,
428+
restored.pk,
429+
own.pk,
430+
restored_twice.pk,
431+
own_unrejected.pk,
432+
]
433+
assert [t["restored"] for t in results] == [True, True, False, True, False]
434+
assert results[0]["status"] == "rejected"
435+
436+
437+
@pytest.mark.django_db
438+
def test_user_translations_invalid_include(member, user_translations_url):
439+
response = member.client.get(
440+
user_translations_url, {"include": "other"}, HTTP_ACCEPT="application/json"
441+
)
442+
443+
assert response.status_code == 400
444+
assert "include" in response.data
445+
446+
339447
@pytest.mark.django_db
340448
@pytest.mark.parametrize(
341449
"params",
@@ -458,6 +566,7 @@ def test_schema_documents_user_translations():
458566
"end_date",
459567
"project",
460568
"locale",
569+
"include",
461570
"page",
462571
"page_size",
463572
}

‎pontoon/api/views.py‎

Lines changed: 59 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,14 @@
1212
from django.core.exceptions import ValidationError as DjangoValidationError
1313
from django.core.files.uploadedfile import UploadedFile
1414
from django.db import IntegrityError, transaction
15-
from django.db.models import Prefetch, Q
15+
from django.db.models import (
16+
BooleanField,
17+
Exists,
18+
ExpressionWrapper,
19+
OuterRef,
20+
Prefetch,
21+
Q,
22+
)
1623
from django.db.models.functions import Greatest
1724
from django.http import Http404
1825
from django.shortcuts import get_object_or_404, redirect
@@ -181,10 +188,10 @@ def get(self, request, date, slug):
181188

182189
@extend_schema(
183190
description=(
184-
"List translations submitted by a user, and created, approved or rejected "
185-
"within the date range, most recently changed first. Defaults to the last "
186-
f"{USER_TRANSLATIONS_DEFAULT_DAYS} days; the date range can span at most "
187-
f"{USER_TRANSLATIONS_MAX_DAYS} days."
191+
"List translations submitted by a user, and created, approved, unapproved, "
192+
"rejected or unrejected within the date range, most recently changed "
193+
f"first. Defaults to the last {USER_TRANSLATIONS_DEFAULT_DAYS} days; the date "
194+
f"range can span at most {USER_TRANSLATIONS_MAX_DAYS} days."
188195
),
189196
parameters=[
190197
OpenApiParameter(
@@ -202,6 +209,15 @@ def get(self, request, date, slug):
202209
),
203210
OpenApiParameter("project", str, description="Project slug"),
204211
OpenApiParameter("locale", str, description="Locale code"),
212+
OpenApiParameter(
213+
"include",
214+
str,
215+
enum=["restored"],
216+
description=(
217+
"Use `restored` to also list translations by other users that the "
218+
"user unrejected, e.g. by uploading a matching suggestion."
219+
),
220+
),
205221
],
206222
)
207223
class UserTranslationListView(generics.ListAPIView):
@@ -247,12 +263,33 @@ def get_queryset(self):
247263
}
248264
)
249265

266+
include = self.request.query_params.get("include")
267+
if include not in (None, "", "restored"):
268+
raise ValidationError(
269+
{"include": ["The only supported value is restored."]}
270+
)
271+
# ActionLog keeps every unrejection, while unrejected_user only tracks the
272+
# latest one.
273+
unrejected_by_user = ActionLog.objects.filter(
274+
performed_by=user,
275+
action_type=ActionLog.ActionType.TRANSLATION_UNREJECTED,
276+
)
277+
users = Q(user=user)
278+
if include == "restored":
279+
# A subquery here would make Postgres scan the whole translation table.
280+
restored_ids = list(
281+
unrejected_by_user.values_list("translation_id", flat=True)
282+
)
283+
users |= Q(pk__in=restored_ids)
284+
250285
visible_projects = Project.objects.visible_for(self.request.user)
251286
qs = Translation.objects.filter(
287+
users,
252288
Q(date__gte=start, date__lt=end)
253289
| Q(approved_date__gte=start, approved_date__lt=end)
254-
| Q(rejected_date__gte=start, rejected_date__lt=end),
255-
user=user,
290+
| Q(unapproved_date__gte=start, unapproved_date__lt=end)
291+
| Q(rejected_date__gte=start, rejected_date__lt=end)
292+
| Q(unrejected_date__gte=start, unrejected_date__lt=end),
256293
entity__resource__project__in=visible_projects,
257294
)
258295

@@ -273,7 +310,20 @@ def get_queryset(self):
273310
),
274311
)
275312
)
276-
.annotate(last_change=Greatest("date", "approved_date", "rejected_date"))
313+
.annotate(
314+
last_change=Greatest(
315+
"date",
316+
"approved_date",
317+
"unapproved_date",
318+
"rejected_date",
319+
"unrejected_date",
320+
),
321+
restored=ExpressionWrapper(
322+
Exists(unrejected_by_user.filter(translation=OuterRef("pk")))
323+
& ~Q(user=user),
324+
output_field=BooleanField(),
325+
),
326+
)
277327
.order_by("-last_change", "-pk")
278328
)
279329

@@ -1088,7 +1138,7 @@ class UploadSuggestionsView(UploadView):
10881138
"replaced or rejected: every uploaded translation is stored as a "
10891139
"suggestion, unless the string already has an unrejected translation "
10901140
"with the same value, in any review state. A rejected translation "
1091-
"matching the upload is un-rejected instead, becoming a pending "
1141+
"matching the upload is unrejected instead, becoming a pending "
10921142
"suggestion again. "
10931143
"Keys not found in Pontoon are ignored, and the fuzzy flag of the "
10941144
"uploaded file is ignored as well, as a suggestion is unreviewed by "

‎pontoon/sync/tests/test_upload.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1064,7 +1064,7 @@ def test_upload_suggestions_updates_latest_translation(
10641064
def test_upload_suggestions_restores_rejected_translation(
10651065
project_locale_a, resource, po_translation, uploader, admin
10661066
):
1067-
"""A rejected translation matching the upload is un-rejected, not duplicated."""
1067+
"""A rejected translation matching the upload is unrejected, not duplicated."""
10681068
author = po_translation.user
10691069
date = po_translation.date
10701070
po_translation.string = "new translation"
@@ -1300,7 +1300,7 @@ def test_upload_suggestions_conflicts_with_concurrent_rejection_of_approved(
13001300
def test_upload_suggestions_conflicts_with_concurrent_unrejection(
13011301
monkeypatch, project_locale_a, resource, po_translation, uploader, admin
13021302
):
1303-
"""A rejected translation un-rejected mid-import is not restored a second time."""
1303+
"""A rejected translation unrejected mid-import is not restored a second time."""
13041304
po_translation.string = "new translation"
13051305
po_translation.value = ["new translation"]
13061306
po_translation.save()
@@ -1309,7 +1309,7 @@ def test_upload_suggestions_conflicts_with_concurrent_unrejection(
13091309
_review_during_import(monkeypatch, lambda: po_translation.unreject(admin))
13101310
_import_conflicts(import_uploaded_suggestions, project_locale_a, resource, uploader)
13111311

1312-
# The import is rolled back, which also undoes the un-rejection made inside it.
1312+
# The import is rolled back, which also undoes the unrejection made inside it.
13131313
po_translation.refresh_from_db()
13141314

13151315
assert po_translation.rejected

‎pontoon/sync/upload.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -681,7 +681,7 @@ class SuggestionUploadResult:
681681
Summary of an uploaded suggestion file import:
682682
- `created`: number of suggestions added
683683
- `restored`: number of rejected translations matching the upload that were
684-
un-rejected, becoming pending suggestions again
684+
unrejected, becoming pending suggestions again
685685
- `unchanged`: number of uploaded translations that the string already has as an
686686
unrejected translation, in any review state
687687
- `failed_checks`: keys of the strings left untouched because the uploaded
@@ -711,7 +711,7 @@ def import_uploaded_suggestions(
711711
with the same value, whether approved, pretranslated or unreviewed. The fuzzy flag
712712
of the uploaded file is ignored: the translation is stored as a plain suggestion.
713713
714-
A rejected translation matching the upload is un-rejected instead of suggested
714+
A rejected translation matching the upload is unrejected instead of suggested
715715
again, so that a translation rejected by mistake can be re-proposed.
716716
717717
Uploaded translations reported with errors are left out, as the editor rejects them

0 commit comments

Comments
 (0)