diff --git a/src/country_workspace/admin/transformer.py b/src/country_workspace/admin/transformer.py index ae25a947e..0653466b9 100644 --- a/src/country_workspace/admin/transformer.py +++ b/src/country_workspace/admin/transformer.py @@ -48,7 +48,7 @@ def clean_record(self) -> dict: @admin.register(Transformer) class TransformerAdmin(BaseModelAdmin): readonly_fields = ("created_at", "last_modified", "created_by") - list_display = ("name", "office", "created_by", "created_at", "last_modified") + list_display = ("name", "engine", "office", "created_by", "created_at", "last_modified") list_filter = ( ("office", AutoCompleteFilter), ("created_by", AutoCompleteFilter), @@ -61,6 +61,7 @@ def get_fields(self, request: HttpRequest, obj: Transformer | None = None) -> tu "name", "description", "office", + "engine", ) tail_fields = ( "created_by", @@ -113,6 +114,7 @@ def edit_and_verify(self, request: HttpRequest, pk: str) -> HttpResponse: name=obj.name, description=obj.description, office=obj.office, + engine=obj.engine, value_transformations=code, ) try: diff --git a/src/country_workspace/migrations/0043_transformer_engine.py b/src/country_workspace/migrations/0043_transformer_engine.py new file mode 100644 index 000000000..c9763eb0d --- /dev/null +++ b/src/country_workspace/migrations/0043_transformer_engine.py @@ -0,0 +1,20 @@ +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("country_workspace", "0042_alter_transformer_value_transformations"), + ] + + operations = [ + migrations.AddField( + model_name="transformer", + name="engine", + field=models.CharField( + choices=[("JAVASCRIPT", "JavaScript"), ("STEFICON", "Steficon Python")], + default="JAVASCRIPT", + help_text="Formula engine used to transform records.", + max_length=20, + ), + ), + ] diff --git a/src/country_workspace/models/transformer.py b/src/country_workspace/models/transformer.py index 9e522728e..d3dd5f506 100644 --- a/src/country_workspace/models/transformer.py +++ b/src/country_workspace/models/transformer.py @@ -1,17 +1,23 @@ import logging from typing import Any from django.conf import settings +from django.core.exceptions import ValidationError from django.db import models from django.utils.translation import gettext_lazy as _ from country_workspace.models.base import BaseModel from country_workspace.utils.js_executor import JavaScriptExecutor -from country_workspace.validators.mapping import ValueTransformationRulesValidator +from country_workspace.utils.steficon_executor import SteficonExecutor +from country_workspace.validators.mapping import SteficonTransformationRulesValidator, ValueTransformationRulesValidator logger = logging.getLogger(__name__) class Transformer(BaseModel): + class Engine(models.TextChoices): + JAVASCRIPT = "JAVASCRIPT", _("JavaScript") + STEFICON = "STEFICON", _("Steficon Python") + name = models.CharField(max_length=255) description = models.CharField(max_length=255, blank=True) office = models.ForeignKey( @@ -20,13 +26,19 @@ class Transformer(BaseModel): related_name="transformers", help_text=_("Business Area (Office) this transformer belongs to"), ) + engine = models.CharField( + max_length=20, + choices=Engine.choices, + default=Engine.JAVASCRIPT, + help_text=_("Formula engine used to transform records."), + ) value_transformations = models.TextField( blank=True, default="", - validators=[ValueTransformationRulesValidator()], help_text=_( - "Value transformation rules (JavaScript). " - "Example: `function transform(record) { record['sex'] = 'Male'; return record; }`" + "Value transformation formula." + " JavaScript example: `function transform(record) { record['sex'] = 'Male'; return record; }`." + " Steficon example: `result.value = context['record']; result.value['sex'] = 'MALE'`." ), ) created_at = models.DateTimeField(auto_now_add=True) @@ -42,13 +54,34 @@ class Meta: def __str__(self) -> str: return self.name + def clean(self) -> None: + super().clean() + code = self.value_transformations or "" + if not code.strip(): + return + + if self.engine == self.Engine.STEFICON: + try: + SteficonTransformationRulesValidator()(code) + except ValidationError as exc: + raise ValidationError({"value_transformations": exc.messages}) from exc + return + + try: + ValueTransformationRulesValidator()(code) + except ValidationError as exc: + raise ValidationError({"value_transformations": exc.messages}) from exc + def apply(self, data: dict[str, Any]) -> dict[str, Any]: """Apply value transformations to the data dictionary.""" if not self.value_transformations: return data try: - executor = JavaScriptExecutor(data, self.value_transformations) + if self.engine == self.Engine.STEFICON: + executor = SteficonExecutor(data, self.value_transformations) + else: + executor = JavaScriptExecutor(data, self.value_transformations) return executor.execute() except Exception: logger.exception("Error applying value transformations") diff --git a/src/country_workspace/utils/steficon_executor.py b/src/country_workspace/utils/steficon_executor.py new file mode 100644 index 000000000..be94c66e6 --- /dev/null +++ b/src/country_workspace/utils/steficon_executor.py @@ -0,0 +1,93 @@ +from __future__ import annotations + +from builtins import __build_class__ # noqa: A004 +import datetime +from dataclasses import dataclass, field +from decimal import Decimal +import traceback +from typing import Any + + +class SteficonValidationError(Exception): + pass + + +@dataclass +class SteficonResult: + value: Any = 0 + extra: dict[str, Any] = field(default_factory=dict) + + +class SteficonExecutor: + """Execute Steficon-style Python formula code. + + Formula receives: + - context: dict with "record" + - result: object exposing "value" and "extra" + """ + + FORBIDDEN_TOKENS = ( + "__import__", + "import ", + "\nimport ", + " from ", + " delete", + " save", + " eval", + " exec", + ) + + def __init__(self, data: dict[str, Any], code: str) -> None: + self.data = data + self.code = code + + def execute(self) -> dict[str, Any]: + result = SteficonResult(value=dict(self.data)) + context = {"record": dict(self.data)} + gl = self._globals() + locals_: dict[str, Any] = { + "context": context, + "result": result, + } + exec(self.code, gl, locals_) # noqa: S102 + + if isinstance(result.value, dict): + return result.value + if isinstance(context.get("record"), dict): + return context["record"] + raise SteficonValidationError("Steficon formula must produce a dict in result.value or context['record']") + + @classmethod + def validate(cls, code: str) -> None: + if any(token in code for token in cls.FORBIDDEN_TOKENS): + raise SteficonValidationError("Steficon formula contains forbidden statements") + try: + compile(code, "", mode="exec") + except SyntaxError as exc: + tb = traceback.format_exc(limit=-1) + message = tb.split('", ')[-1] + raise SteficonValidationError(message) from exc + + @staticmethod + def _globals() -> dict[str, Any]: + return { + "__builtins__": { + "__build_class__": __build_class__, + "__name__": __name__, + "date": datetime.date, + "datetime": datetime.datetime, + "timedelta": datetime.timedelta, + "Decimal": Decimal, + "complex": complex, + "dict": dict, + "float": float, + "frozenset": frozenset, + "int": int, + "list": list, + "memoryview": memoryview, + "range": range, + "set": set, + "str": str, + "tuple": tuple, + } + } diff --git a/src/country_workspace/validators/mapping.py b/src/country_workspace/validators/mapping.py index 4a5db5077..48236a541 100644 --- a/src/country_workspace/validators/mapping.py +++ b/src/country_workspace/validators/mapping.py @@ -3,6 +3,7 @@ from django.utils.translation import gettext_lazy as _ from country_workspace.utils.js_executor import JavaScriptExecutor +from country_workspace.utils.steficon_executor import SteficonExecutor, SteficonValidationError @deconstructible @@ -48,3 +49,19 @@ def __call__(self, value: str) -> None: _("Invalid JavaScript code. Must contain a function definition."), code="invalid_js", ) + + +@deconstructible +class SteficonTransformationRulesValidator: + """Validate Steficon-style Python formula code.""" + + def __call__(self, value: str) -> None: + if not value.strip(): + return + try: + SteficonExecutor.validate(value) + except SteficonValidationError as exc: + raise ValidationError( + _("Invalid Steficon formula. %(error)s") % {"error": str(exc)}, + code="invalid_steficon", + ) from exc diff --git a/src/country_workspace/workspaces/admin/transformer.py b/src/country_workspace/workspaces/admin/transformer.py index f4412454d..a979fd44a 100644 --- a/src/country_workspace/workspaces/admin/transformer.py +++ b/src/country_workspace/workspaces/admin/transformer.py @@ -1,24 +1,80 @@ -from django.contrib import admin +from admin_extra_buttons.decorators import button +from django import forms +from django.contrib import admin, messages from django.core.cache import cache from django.db.models import QuerySet from django.forms import ModelForm -from django.http import HttpRequest +from django.http import HttpRequest, HttpResponse, HttpResponseRedirect +from django.shortcuts import render +from django.urls import reverse +from django.utils.translation import gettext_lazy as _ +from strategy_field.utils import fqn +from country_workspace.models import AsyncJob, Batch from country_workspace.state import state from country_workspace.workspaces.models import CountryTransformer from country_workspace.workspaces.options import WorkspaceModelAdmin from country_workspace.workspaces.sites import workspace +class RunTransformerForm(forms.Form): + class ApplyToOptions(forms.TextChoices): + HOUSEHOLDS = "households", _("Households only") + INDIVIDUALS = "individuals", _("Individuals only") + BOTH = "both", _("Households and Individuals") + + batch = forms.ModelChoiceField( + queryset=Batch.objects.none(), + label=_("Batch"), + help_text=_("Select an existing batch to update records before pushing to HOPE."), + ) + apply_to = forms.ChoiceField( + label=_("Apply formula to"), + choices=ApplyToOptions.choices, + help_text=_("Choose which record type should be updated by this formula."), + ) + + def __init__(self, *args: object, **kwargs: object) -> None: + office = kwargs.pop("office", None) + program = kwargs.pop("program", None) + super().__init__(*args, **kwargs) + + qs = Batch.objects.order_by("-import_date") + if office: + qs = qs.filter(country_office=office) + if program: + qs = qs.filter(program=program) + self.fields["batch"].queryset = qs.select_related("program") + + if not program: + self.fields["apply_to"].choices = [ + (self.ApplyToOptions.INDIVIDUALS, self.ApplyToOptions.INDIVIDUALS.label), + (self.ApplyToOptions.BOTH, self.ApplyToOptions.BOTH.label), + ] + return + + if program.is_master_detail: + self.fields["apply_to"].choices = [ + (self.ApplyToOptions.HOUSEHOLDS, self.ApplyToOptions.HOUSEHOLDS.label), + (self.ApplyToOptions.INDIVIDUALS, self.ApplyToOptions.INDIVIDUALS.label), + (self.ApplyToOptions.BOTH, self.ApplyToOptions.BOTH.label), + ] + else: + self.fields["apply_to"].choices = [ + (self.ApplyToOptions.INDIVIDUALS, self.ApplyToOptions.INDIVIDUALS.label), + ] + + @admin.register(CountryTransformer, site=workspace) class CountryTransformerAdmin(WorkspaceModelAdmin): - list_display = ("name", "description", "created_by", "created_at") + list_display = ("name", "engine", "description", "created_by", "created_at") search_fields = ("name", "description") readonly_fields = ("office", "created_at", "last_modified", "created_by") fields = ( "name", "description", "office", + "engine", "value_transformations", "created_by", "created_at", @@ -63,6 +119,72 @@ def delete_queryset(self, request: HttpRequest, queryset: QuerySet[CountryTransf super().delete_queryset(request, queryset) self._invalidate_transformer_cache() + @button( + label="Run Formula on Existing Records", + change_form=True, + html_attrs={"title": "Run this formula in Country Workspace without rule commits"}, + ) + def run_on_existing_records(self, request: HttpRequest, pk: str) -> HttpResponse: + obj = self.get_object(request, pk) + if not obj: + return HttpResponse("Transformer not found", status=404) + + if request.method == "POST" and "apply" in request.POST: + form = RunTransformerForm(request.POST, office=state.tenant, program=state.program) + if form.is_valid(): + batch = form.cleaned_data["batch"] + apply_to = form.cleaned_data["apply_to"] + if not request.user.has_perm("country_workspace.reprocess_batch", batch.program): # type: ignore[attr-defined] + self.message_user( + request, + _("You do not have permission to run formulas on this batch."), + messages.ERROR, + ) + return HttpResponseRedirect(self.get_change_url(request, obj)) + + config: dict[str, int] = {"batch_id": batch.pk} + if batch.program.is_master_detail and apply_to in ( + RunTransformerForm.ApplyToOptions.HOUSEHOLDS, + RunTransformerForm.ApplyToOptions.BOTH, + ): + config["household_transformer_id"] = obj.pk + if apply_to in ( + RunTransformerForm.ApplyToOptions.INDIVIDUALS, + RunTransformerForm.ApplyToOptions.BOTH, + ): + config["individual_transformer_id"] = obj.pk + + job = AsyncJob.objects.create( + description=f"Run formula '{obj.name}' on batch {batch.name}", + type=AsyncJob.JobType.TASK, + owner=request.user, + action=fqn("country_workspace.workspaces.admin.batch.reprocessing.reprocess_batch"), + program=batch.program, + batch=batch, + config=config, + ) + job.queue() + + self.message_user( + request, + _("Formula execution has been scheduled for the selected batch."), + messages.SUCCESS, + ) + return HttpResponseRedirect(reverse("workspace:workspaces_countrybatch_changelist")) + + self.message_user(request, _("Please correct the errors below."), messages.ERROR) + else: + form = RunTransformerForm(office=state.tenant, program=state.program) + + context = self.get_common_context( + request, + pk=pk, + title=_("Run Formula on Existing Records"), + form=form, + transformer=obj, + ) + return render(request, "workspace/admin_extra_buttons/run_transformer_form.html", context) + def _invalidate_transformer_cache(self) -> None: """Invalidate cache keys related to transformers.""" if state.tenant: diff --git a/src/country_workspace/workspaces/templates/workspace/admin_extra_buttons/run_transformer_form.html b/src/country_workspace/workspaces/templates/workspace/admin_extra_buttons/run_transformer_form.html new file mode 100644 index 000000000..c5439be26 --- /dev/null +++ b/src/country_workspace/workspaces/templates/workspace/admin_extra_buttons/run_transformer_form.html @@ -0,0 +1,69 @@ +{% extends 'workspace/_base.html' %} +{% load i18n %} +{% block breadcrumbs %} +{% endblock breadcrumbs %} +{% block content %} +
+
+
+

+ {% translate 'Run Formula on Existing Records' %} +

+
+

+ {% blocktranslate with transformer_name=transformer.name %} + Formula: {{ transformer_name }} + {% endblocktranslate %} +

+

+ {% translate "This executes the selected formula directly in Country Workspace and updates existing records before they are pushed to HOPE." %} +

+

+ {% translate "No admin rule creation, rule commits, or custom code execution is required." %} +

+
+ {% csrf_token %} + {% if form.errors %} +
+

+ {% translate "Please correct the errors below." %} +

+
+ {% endif %} +
+ {% for field in form %} +
+
+ + {{ field }} + {% if field.help_text %} +

+ {{ field.help_text }} +

+ {% endif %} + {% if field.errors %} +
    + {% for error in field.errors %} +
  • + {{ error }} +
  • + {% endfor %} +
+ {% endif %} +
+
+ {% endfor %} +
+
+ + + +
+
+
+
+
+
+{% endblock content %} diff --git a/tests/models/test_m_transformer.py b/tests/models/test_m_transformer.py index a58cb889a..dba74d549 100644 --- a/tests/models/test_m_transformer.py +++ b/tests/models/test_m_transformer.py @@ -105,3 +105,47 @@ def test_apply_handles_null_return(transformer): result = t.apply(data) assert result is None + + +def test_apply_steficon_transformer_returns_updated_record(transformer): + t = transformer( + engine="STEFICON", + value_transformations=( + "result.value = context['record']\nif result.value.get('sex') == 'M':\n result.value['sex'] = 'MALE'\n" + ), + ) + data = {"sex": "M", "name": "A"} + + result = t.apply(data) + assert result == {"sex": "MALE", "name": "A"} + + +def test_apply_steficon_transformer_context_record_fallback(transformer): + t = transformer( + engine="STEFICON", + value_transformations="context['record']['status'] = 'ACTIVE'", + ) + data = {"status": "PENDING"} + + result = t.apply(data) + assert result == {"status": "ACTIVE"} + + +def test_apply_steficon_transformer_handles_invalid_output(transformer, caplog): + t = transformer( + engine="STEFICON", + value_transformations="result.value = 1", + ) + data = {"foo": "bar"} + + with caplog.at_level("ERROR"): + result = t.apply(data) + + assert result == data + assert "Error applying value transformations" in caplog.text + + +def test_transformer_full_clean_invalid_steficon_formula(transformer): + t = transformer.build(engine="STEFICON", value_transformations="import os") + with pytest.raises(ValidationError): + t.full_clean() diff --git a/tests/utils/test_steficon_executor.py b/tests/utils/test_steficon_executor.py new file mode 100644 index 000000000..bc0cbc795 --- /dev/null +++ b/tests/utils/test_steficon_executor.py @@ -0,0 +1,29 @@ +import pytest + +from country_workspace.utils.steficon_executor import SteficonExecutor, SteficonValidationError + + +def test_validate_accepts_valid_formula(): + SteficonExecutor.validate("result.value = context['record']") + + +@pytest.mark.parametrize("code", ["import os", "__import__('os')", "exec('x=1')", "eval('1+1')"]) +def test_validate_rejects_forbidden_tokens(code): + with pytest.raises(SteficonValidationError): + SteficonExecutor.validate(code) + + +def test_execute_uses_result_value_dict(): + data = {"sex": "M"} + code = "result.value = context['record']; result.value['sex'] = 'MALE'" + executor = SteficonExecutor(data=data, code=code) + result = executor.execute() + assert result == {"sex": "MALE"} + + +def test_execute_falls_back_to_context_record(): + data = {"status": "PENDING"} + code = "context['record']['status'] = 'ACTIVE'" + executor = SteficonExecutor(data=data, code=code) + result = executor.execute() + assert result == {"status": "ACTIVE"} diff --git a/tests/workspace/admin/test_transformer.py b/tests/workspace/admin/test_transformer.py index 047500210..5c932d7ef 100644 --- a/tests/workspace/admin/test_transformer.py +++ b/tests/workspace/admin/test_transformer.py @@ -3,9 +3,10 @@ import pytest from django.contrib.auth.models import User from django.http import HttpRequest +from django.http.response import HttpResponse from country_workspace.state import state -from country_workspace.workspaces.admin.transformer import CountryTransformerAdmin +from country_workspace.workspaces.admin.transformer import CountryTransformerAdmin, RunTransformerForm from country_workspace.workspaces.models import CountryTransformer @@ -111,3 +112,170 @@ def test_invalidate_transformer_cache_no_tenant(self, mock_cache, transformer_ad state.tenant = None transformer_admin._invalidate_transformer_cache() mock_cache.delete.assert_not_called() + + +class TestRunTransformerForm: + def _build_mock_queryset(self) -> MagicMock: + qs = MagicMock() + qs.filter.return_value = qs + qs.select_related.return_value = qs + qs.all.return_value = qs + return qs + + @patch("country_workspace.workspaces.admin.transformer.Batch.objects") + def test_choices_without_program(self, mock_batch_objects): + qs = self._build_mock_queryset() + mock_batch_objects.order_by.return_value = qs + + form = RunTransformerForm() + + choices = [choice[0] for choice in form.fields["apply_to"].choices] + assert choices == [ + RunTransformerForm.ApplyToOptions.INDIVIDUALS, + RunTransformerForm.ApplyToOptions.BOTH, + ] + + @patch("country_workspace.workspaces.admin.transformer.Batch.objects") + def test_choices_master_detail_program(self, mock_batch_objects): + qs = self._build_mock_queryset() + mock_batch_objects.order_by.return_value = qs + program = MagicMock(is_master_detail=True) + + form = RunTransformerForm(program=program) + + choices = [choice[0] for choice in form.fields["apply_to"].choices] + assert choices == [ + RunTransformerForm.ApplyToOptions.HOUSEHOLDS, + RunTransformerForm.ApplyToOptions.INDIVIDUALS, + RunTransformerForm.ApplyToOptions.BOTH, + ] + + @patch("country_workspace.workspaces.admin.transformer.Batch.objects") + def test_choices_non_master_detail_program(self, mock_batch_objects): + qs = self._build_mock_queryset() + mock_batch_objects.order_by.return_value = qs + program = MagicMock(is_master_detail=False) + + form = RunTransformerForm(program=program) + + choices = [choice[0] for choice in form.fields["apply_to"].choices] + assert choices == [RunTransformerForm.ApplyToOptions.INDIVIDUALS] + + +class TestRunOnExistingRecords: + def _build_request(self, method: str = "GET", post_data: dict | None = None, has_perm: bool = True) -> MagicMock: + request = MagicMock(spec=HttpRequest) + request.method = method + request.POST = post_data or {} + request.user = MagicMock(spec=User) + request.user.has_perm.return_value = has_perm + return request + + def test_returns_404_when_transformer_not_found(self, transformer_admin): + request = self._build_request() + with patch.object(transformer_admin, "get_object", return_value=None): + response = transformer_admin.run_on_existing_records(request, "123") + assert response.status_code == 404 + + def test_get_renders_form(self, transformer_admin): + request = self._build_request("GET") + transformer = MagicMock(pk=1, name="T1") + state.tenant = MagicMock() + state.program = MagicMock() + + with ( + patch.object(transformer_admin, "get_object", return_value=transformer), + patch( + "country_workspace.workspaces.admin.transformer.render", return_value=HttpResponse("ok") + ) as mock_render, + ): + response = transformer_admin.run_on_existing_records(request, "1") + + assert response.status_code == 200 + mock_render.assert_called_once() + + def test_post_invalid_form_shows_error(self, transformer_admin): + request = self._build_request("POST", {"apply": "yes"}) + transformer = MagicMock(pk=1, name="T1") + state.tenant = MagicMock() + state.program = MagicMock() + + mock_form = MagicMock() + mock_form.is_valid.return_value = False + + with ( + patch.object(transformer_admin, "get_object", return_value=transformer), + patch("country_workspace.workspaces.admin.transformer.RunTransformerForm", return_value=mock_form), + patch.object(transformer_admin, "message_user") as mock_message_user, + patch("country_workspace.workspaces.admin.transformer.render", return_value=HttpResponse("ok")), + ): + transformer_admin.run_on_existing_records(request, "1") + + mock_message_user.assert_called() + assert "Please correct the errors below." in mock_message_user.call_args.args[1] + + def test_post_valid_without_permission_redirects_to_change(self, transformer_admin): + request = self._build_request("POST", {"apply": "yes"}, has_perm=False) + transformer = MagicMock(pk=1, name="T1") + program = MagicMock(is_master_detail=True) + batch = MagicMock(pk=10, name="Batch 1", program=program) + state.tenant = MagicMock() + state.program = MagicMock() + + mock_form = MagicMock() + mock_form.is_valid.return_value = True + mock_form.cleaned_data = { + "batch": batch, + "apply_to": RunTransformerForm.ApplyToOptions.BOTH, + } + + with ( + patch.object(transformer_admin, "get_object", return_value=transformer), + patch("country_workspace.workspaces.admin.transformer.RunTransformerForm", return_value=mock_form), + patch.object(transformer_admin, "get_change_url", return_value="/change/") as mock_get_change_url, + patch.object(transformer_admin, "message_user") as mock_message_user, + ): + response = transformer_admin.run_on_existing_records(request, "1") + + assert response.status_code == 302 + assert response.url == "/change/" + mock_get_change_url.assert_called_once_with(request, transformer) + assert "do not have permission" in mock_message_user.call_args.args[1] + + def test_post_valid_schedules_job_for_both_in_master_detail(self, transformer_admin): + request = self._build_request("POST", {"apply": "yes"}, has_perm=True) + transformer = MagicMock(pk=99, name="Eligibility Rule") + program = MagicMock(is_master_detail=True) + batch = MagicMock(pk=10, name="Batch 1", program=program) + state.tenant = MagicMock() + state.program = MagicMock() + + mock_form = MagicMock() + mock_form.is_valid.return_value = True + mock_form.cleaned_data = { + "batch": batch, + "apply_to": RunTransformerForm.ApplyToOptions.BOTH, + } + job = MagicMock() + + with ( + patch.object(transformer_admin, "get_object", return_value=transformer), + patch("country_workspace.workspaces.admin.transformer.RunTransformerForm", return_value=mock_form), + patch( + "country_workspace.workspaces.admin.transformer.AsyncJob.objects.create", return_value=job + ) as mock_create, + patch("country_workspace.workspaces.admin.transformer.reverse", return_value="/batch/"), + patch.object(transformer_admin, "message_user") as mock_message_user, + ): + response = transformer_admin.run_on_existing_records(request, "99") + + assert response.status_code == 302 + assert response.url == "/batch/" + mock_create.assert_called_once() + assert mock_create.call_args.kwargs["config"] == { + "batch_id": 10, + "household_transformer_id": 99, + "individual_transformer_id": 99, + } + job.queue.assert_called_once() + assert "scheduled" in mock_message_user.call_args.args[1].lower()