From c11ced7894d2df6b134a39e1fe93ffff1068a353 Mon Sep 17 00:00:00 2001 From: Ashwin Date: Sat, 8 Aug 2026 15:47:13 +0530 Subject: [PATCH] feat: add invoice template form screen and integrate with templates list - Implemented `InvoiceTemplateFormScreen` for creating and editing invoice templates. - Added functionality to pre-fill form fields from existing templates. - Enhanced `InvoiceTemplatesScreen` to allow admins to create new templates and set defaults. - Updated routing to include paths for creating and editing templates. - Added tests for the new template form and its integration with the templates list. - Ensured proper handling of admin-only actions and user permissions. --- backend/invoices/serializer.py | 33 + backend/invoices/tests/test_invoices_api.py | 72 +++ frontend/src/lib/server/v2/files.test.js | 3 +- frontend/src/lib/server/v2/templates.js | 11 +- .../(app)/invoices/templates/new/+page.svelte | 19 +- mobile/lib/config/api_config.dart | 9 +- mobile/lib/data/models/invoice_template.dart | 87 ++- .../providers/invoice_extras_provider.dart | 117 +++- mobile/lib/routes/app_router.dart | 19 + .../invoice_template_form_screen.dart | 603 ++++++++++++++++++ .../invoices/invoice_templates_screen.dart | 120 +++- mobile/test/screens/phone_viewport_test.dart | 235 +++++++ mobile/test/unit/invoice_extras_test.dart | 151 +++++ mobile/test/unit/invoice_routes_test.dart | 50 ++ 14 files changed, 1464 insertions(+), 65 deletions(-) create mode 100644 mobile/lib/screens/invoices/invoice_template_form_screen.dart diff --git a/backend/invoices/serializer.py b/backend/invoices/serializer.py index 8c2b66ad..4bbc6403 100644 --- a/backend/invoices/serializer.py +++ b/backend/invoices/serializer.py @@ -1,3 +1,4 @@ +import re from decimal import Decimal from rest_framework import serializers @@ -218,6 +219,32 @@ class InvoiceTemplateListSerializer(serializers.ModelSerializer): return (user.name or "").strip() or user.email +HEX_COLOR = re.compile(r"^#[0-9a-fA-F]{6}$") + + +def _validate_hex_color(value): + """Refuse anything that is not ``#RRGGBB``. + + Both colour fields are substituted straight into the PDF stylesheet + (``pdf.py`` does ``css_content.replace("#3B82F6", template.primary_color)``), + so a value the browser will not parse does not fail loudly, it silently + prints every invoice in the org with a broken accent colour. The model is + ``max_length=7`` and nothing else, which accepted ``"purple"`` happily. + + All three clients already constrain this: both web forms use + ``input type="color"`` and the phone picks from swatches, so each one can + only ever submit six hex digits. That made this the last field where the + only thing standing between a typo and a broken PDF was a client, which is + the shape ``API Validation & Authorization`` exists to rule out. + """ + value = (value or "").strip() + if not HEX_COLOR.match(value): + raise serializers.ValidationError( + "Use a six digit hex colour, for example #3B82F6." + ) + return value + + class InvoiceTemplateCreateSerializer(serializers.ModelSerializer): """Serializer for creating/updating Invoice Templates""" @@ -236,6 +263,12 @@ class InvoiceTemplateCreateSerializer(serializers.ModelSerializer): "is_default", ) + def validate_primary_color(self, value): + return _validate_hex_color(value) + + def validate_secondary_color(self, value): + return _validate_hex_color(value) + def create(self, validated_data): request = self.context.get("request") if request and hasattr(request, "profile"): diff --git a/backend/invoices/tests/test_invoices_api.py b/backend/invoices/tests/test_invoices_api.py index 474a8f38..51bf786c 100644 --- a/backend/invoices/tests/test_invoices_api.py +++ b/backend/invoices/tests/test_invoices_api.py @@ -2557,6 +2557,78 @@ class TestInvoiceTemplateDetailView: assert response.status_code == 404 +@pytest.mark.django_db +class TestInvoiceTemplateColourValidation: + """``primary_color`` / ``secondary_color`` have to parse as CSS colours. + + ``pdf.py`` substitutes ``primary_color`` into the stylesheet by string + replacement, so a value a renderer cannot parse does not raise, it prints + every invoice in the org with a broken accent. The model carries only + ``max_length=7``, so before this the three clients (two web forms and the + phone) were the only thing refusing ``purple``. + """ + + def test_a_six_digit_hex_is_accepted(self, admin_client): + response = admin_client.post( + "/api/invoices/templates/", + {"name": "Hex", "primary_color": "#a1B2c3", "secondary_color": "#000000"}, + format="json", + ) + assert response.status_code == 201, response.content + assert InvoiceTemplate.objects.get(name="Hex").primary_color == "#a1B2c3" + + def test_a_colour_name_is_refused(self, admin_client): + response = admin_client.post( + "/api/invoices/templates/", + {"name": "Named", "primary_color": "purple"}, + format="json", + ) + assert response.status_code == 400 + assert "primary_color" in response.json()["errors"] + assert not InvoiceTemplate.objects.filter(name="Named").exists() + + def test_a_missing_hash_is_refused(self, admin_client): + response = admin_client.post( + "/api/invoices/templates/", + {"name": "Bare", "primary_color": "3B82F6"}, + format="json", + ) + assert response.status_code == 400 + assert not InvoiceTemplate.objects.filter(name="Bare").exists() + + def test_the_secondary_colour_is_checked_too(self, admin_client): + """Two fields, two validators; one of them was easy to forget.""" + response = admin_client.post( + "/api/invoices/templates/", + {"name": "Second", "primary_color": "#3B82F6", "secondary_color": "}a{b:c"}, + format="json", + ) + assert response.status_code == 400 + assert "secondary_color" in response.json()["errors"] + + def test_an_update_is_checked_as_well_as_a_create(self, admin_client, template): + """The edit form writes these fields, so PUT is the likelier caller.""" + response = admin_client.put( + f"/api/invoices/templates/{template.id}/", + {"primary_color": "red"}, + format="json", + ) + assert response.status_code == 400 + template.refresh_from_db() + assert template.primary_color == "#3B82F6" + + def test_omitting_a_colour_leaves_it_alone(self, admin_client, template): + """PUT is partial. Editing only the name must not demand the colours.""" + response = admin_client.put( + f"/api/invoices/templates/{template.id}/", + {"name": "Renamed"}, + format="json", + ) + assert response.status_code == 200, response.content + template.refresh_from_db() + assert template.primary_color == "#3B82F6" + + @pytest.mark.django_db class TestInvoiceTemplateWriteAuthorization: """Invoice templates are org-wide shared config: how every invoice reaches a diff --git a/frontend/src/lib/server/v2/files.test.js b/frontend/src/lib/server/v2/files.test.js index 97843a5a..37db556f 100644 --- a/frontend/src/lib/server/v2/files.test.js +++ b/frontend/src/lib/server/v2/files.test.js @@ -65,7 +65,8 @@ describe('streamDownload', () => { const [url, init] = fetchSpy.mock.calls[0]; expect(url).toBe('http://api.test/api/attachments/1/download/'); - expect(/** @type {Record} */ (init?.headers).Authorization).toBe('Bearer tok'); + const headers = /** @type {Record} */ (init?.headers ?? {}); + expect(headers.Authorization).toBe('Bearer tok'); }); it('passes the upstream filename through rather than inventing one', async () => { diff --git a/frontend/src/lib/server/v2/templates.js b/frontend/src/lib/server/v2/templates.js index 81ece3d1..03f562a1 100644 --- a/frontend/src/lib/server/v2/templates.js +++ b/frontend/src/lib/server/v2/templates.js @@ -179,10 +179,13 @@ export const UPDATE_FIELDS = [ * control using `can_manage`, but that is a display hint decoded from the JWT; * the backend re-derives the role and is the check that matters. * - * The colour checks below mirror nothing on the server. Neither colour field - * has a format validator; the model is `max_length=7` only, so `"purple"` is - * stored happily and then renders as an invalid CSS colour in the PDF. That is - * a backend gap, flagged rather than worked around. + * The colour checks below now mirror `_validate_hex_color` in + * `InvoiceTemplateCreateSerializer`, which is the check that counts. They used + * to mirror nothing: the model is `max_length=7` and had no format validator, + * so `"purple"` was stored happily and then rendered as an invalid CSS colour + * in the PDF. The serializer closed that when the phone became the third client + * constraining the field. These stay because a client-side message beats a raw + * 400 on a field the user picked from a swatch. * * `is_default` is not a plain field write: the model's `save()` clears the flag * on every other template in the org inside a transaction, so setting it here diff --git a/frontend/src/routes/(app)/invoices/templates/new/+page.svelte b/frontend/src/routes/(app)/invoices/templates/new/+page.svelte index 24bd9b4d..08a9580c 100644 --- a/frontend/src/routes/(app)/invoices/templates/new/+page.svelte +++ b/frontend/src/routes/(app)/invoices/templates/new/+page.svelte @@ -6,20 +6,20 @@ * * SCOPE, ON PURPOSE. No `template_html` / `template_css` input anywhere on * this page, and no `{@html}` anywhere in this app. Both fields are org- - * authored markup that WeasyPrint renders into a PDF server-side; every read - * serializer (list AND detail) strips them, so a value written from a form - * here could never be read back or edited afterwards, a write-once field - * that is invisible from the moment it is saved. See `templates.js` for the - * full reasoning. + * authored markup that WeasyPrint renders into a PDF server-side. A new + * template starts from the built-in layout, and replacing that whole + * document is a deliberate follow-up on an existing template rather than + * part of naming a new one, so the edit page owns those two fields. See + * `templates.js` for the full reasoning, including the older reason this + * page gave, which the editor route made obsolete. * * VALIDATION HERE IS A UX HINT, NOT A RULE. `POST /api/invoices/templates/` * is admin-gated (`_forbid_non_admin_template`) and enforces that * regardless of what this page shows; curl and the mobile client reach the * API without passing through here. The two colour inputs use * `type="color"` so the browser can only ever submit a valid six-digit hex - * value: the server has no format validator on either field (only - * `max_length=7`), so a text input would make the client check the only - * thing standing between "purple" and a broken PDF. + * value, and `_validate_hex_color` in the serializer refuses anything else, + * which is the check that counts. */ import { enhance } from '$app/forms'; import PageHeader from '$lib/v2/components/PageHeader.svelte'; @@ -105,8 +105,7 @@

- Picked, not typed, so the value sent is always a valid six digit hex. The API stores - whatever it is given here with no format check. + Picked, not typed, so the value sent is always a valid six digit hex.