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.
This commit is contained in:
parent
f132d17d0c
commit
c11ced7894
14 changed files with 1464 additions and 65 deletions
|
|
@ -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"):
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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<string, string>} */ (init?.headers).Authorization).toBe('Bearer tok');
|
||||
const headers = /** @type {Record<string, string>} */ (init?.headers ?? {});
|
||||
expect(headers.Authorization).toBe('Bearer tok');
|
||||
});
|
||||
|
||||
it('passes the upstream filename through rather than inventing one', async () => {
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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 @@
|
|||
</label>
|
||||
</div>
|
||||
<p class="v2-sub" style="font-size:11.5px;margin:-6px 0 16px">
|
||||
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.
|
||||
</p>
|
||||
|
||||
<label class="v2-field">
|
||||
|
|
|
|||
|
|
@ -421,9 +421,14 @@ class ApiConfig {
|
|||
static String get products => '$apiBaseUrl/invoices/products/';
|
||||
static String product(String id) => '$apiBaseUrl/invoices/products/$id/';
|
||||
|
||||
/// PDF templates. This list never carries the raw HTML or CSS: only the
|
||||
/// admin-only editor endpoint does, and this app does not call it.
|
||||
/// PDF templates. Neither of these carries the raw HTML or CSS: only the
|
||||
/// admin-only editor endpoint does, and this app does not call it. That is
|
||||
/// what lets the phone edit a template at all. The fields it writes are the
|
||||
/// ordinary ones, the detail PUT is partial, so a save from here leaves the
|
||||
/// markup exactly as the web editor left it.
|
||||
static String get invoiceTemplates => '$apiBaseUrl/invoices/templates/';
|
||||
static String invoiceTemplate(String id) =>
|
||||
'$apiBaseUrl/invoices/templates/$id/';
|
||||
|
||||
/// Reports. Both are admin-only and answer 403 to everyone else.
|
||||
static String get invoiceReportDashboard =>
|
||||
|
|
|
|||
|
|
@ -7,9 +7,12 @@
|
|||
/// markup, a PDF setting becomes stored XSS. Only `InvoiceTemplateEditorView`
|
||||
/// returns them, it is admin-only, and this app does not call it.
|
||||
///
|
||||
/// So the catalogue is what mobile shows: names, colours, which one is the
|
||||
/// default, and booleans describing the markup rather than the markup. The
|
||||
/// editor stays on the web, where a two-pane HTML editor belongs anyway.
|
||||
/// That absence is what makes the phone's editor safe rather than what stops
|
||||
/// it. Every other field on a template is ordinary form input, all of it is on
|
||||
/// the list response, and `PUT /invoices/templates/<id>/` is partial. So the
|
||||
/// phone can pre-fill from the row it already has, write the ordinary fields
|
||||
/// back, and never name the two markup fields in either direction. A save from
|
||||
/// here leaves whatever the web editor last stored untouched.
|
||||
class InvoiceTemplate {
|
||||
const InvoiceTemplate({
|
||||
required this.id,
|
||||
|
|
@ -20,6 +23,9 @@ class InvoiceTemplate {
|
|||
this.hasLogo = false,
|
||||
this.hasCustomHtml = false,
|
||||
this.hasCustomCss = false,
|
||||
this.defaultNotes = '',
|
||||
this.defaultTerms = '',
|
||||
this.footerText = '',
|
||||
this.usedOnInvoices = 0,
|
||||
this.updatedBy,
|
||||
});
|
||||
|
|
@ -35,9 +41,18 @@ class InvoiceTemplate {
|
|||
final bool hasCustomHtml;
|
||||
final bool hasCustomCss;
|
||||
|
||||
/// The boilerplate a new invoice starts from. Plain text, editable here.
|
||||
final String defaultNotes;
|
||||
final String defaultTerms;
|
||||
final String footerText;
|
||||
|
||||
final int usedOnInvoices;
|
||||
final String? updatedBy;
|
||||
|
||||
/// The model defaults, used when a form has nothing to pre-fill from.
|
||||
static const String defaultPrimaryColor = '#3B82F6';
|
||||
static const String defaultSecondaryColor = '#1E40AF';
|
||||
|
||||
factory InvoiceTemplate.fromJson(Map<String, dynamic> json) {
|
||||
return InvoiceTemplate(
|
||||
id: json['id']?.toString() ?? '',
|
||||
|
|
@ -48,8 +63,74 @@ class InvoiceTemplate {
|
|||
hasLogo: json['has_logo'] as bool? ?? false,
|
||||
hasCustomHtml: json['has_custom_html'] as bool? ?? false,
|
||||
hasCustomCss: json['has_custom_css'] as bool? ?? false,
|
||||
defaultNotes: json['default_notes'] as String? ?? '',
|
||||
defaultTerms: json['default_terms'] as String? ?? '',
|
||||
footerText: json['footer_text'] as String? ?? '',
|
||||
usedOnInvoices: json['used_on_invoices'] as int? ?? 0,
|
||||
updatedBy: json['updated_by'] as String?,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// What the form screen submits.
|
||||
///
|
||||
/// A separate type from [InvoiceTemplate] because the two carry different
|
||||
/// things: the model holds what a template *is*, including the read-only
|
||||
/// `has_custom_html` and `used_on_invoices` the list computes, while this holds
|
||||
/// only the fields a person may write. Sending a model back would mean deciding
|
||||
/// per field whether it is writable at the call site, which is how a read-only
|
||||
/// field ends up in a payload.
|
||||
class InvoiceTemplateDraft {
|
||||
const InvoiceTemplateDraft({
|
||||
required this.name,
|
||||
required this.primaryColor,
|
||||
required this.secondaryColor,
|
||||
this.defaultNotes = '',
|
||||
this.defaultTerms = '',
|
||||
this.footerText = '',
|
||||
this.isDefault,
|
||||
});
|
||||
|
||||
final String name;
|
||||
final String primaryColor;
|
||||
final String secondaryColor;
|
||||
final String defaultNotes;
|
||||
final String defaultTerms;
|
||||
final String footerText;
|
||||
|
||||
/// Null on an edit, where this field is deliberately not the form's to write.
|
||||
///
|
||||
/// `is_default` is a singleton: the model clears the flag on every other
|
||||
/// template in the org inside a transaction. Carrying an off switch through
|
||||
/// an unrelated save would demote the org's current default and leave it with
|
||||
/// none, so the list owns it and both edit forms leave it out. The web's edit
|
||||
/// form does the same, for the same reason.
|
||||
final bool? isDefault;
|
||||
|
||||
/// `#RRGGBB`, the only form the API accepts. Matches the regex in
|
||||
/// `_validate_hex_color` and the one in the web's `templates.js`.
|
||||
static final RegExp hexColor = RegExp(r'^#[0-9a-fA-F]{6}$');
|
||||
|
||||
static bool isHexColor(String value) => hexColor.hasMatch(value.trim());
|
||||
|
||||
Map<String, dynamic> toPayload() {
|
||||
return <String, dynamic>{
|
||||
'name': name.trim(),
|
||||
'primary_color': primaryColor,
|
||||
'secondary_color': secondaryColor,
|
||||
'default_notes': defaultNotes,
|
||||
'default_terms': defaultTerms,
|
||||
'footer_text': footerText,
|
||||
if (isDefault != null) 'is_default': isDefault,
|
||||
};
|
||||
}
|
||||
|
||||
/// The same payload as multipart fields, for the calls that carry a logo.
|
||||
///
|
||||
/// `http.MultipartRequest.fields` is `Map<String, String>`, so `is_default`
|
||||
/// arrives as "true" or "false". DRF's `BooleanField` reads both, and it is
|
||||
/// the same spelling the web sends through `FormData`.
|
||||
Map<String, String> toMultipartFields() {
|
||||
return toPayload().map((key, value) => MapEntry(key, '$value'));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -251,26 +251,109 @@ final productsProvider = AsyncNotifierProvider<ProductsNotifier, List<Product>>(
|
|||
);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// PDF templates, read-only
|
||||
// PDF templates
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// The catalogue only. There is no create, update or delete here on purpose:
|
||||
/// a template's body is raw HTML and CSS that renders into a PDF server-side,
|
||||
/// editing it is admin-only, and a two-pane markup editor is not a phone
|
||||
/// screen. Mobile shows which templates exist and which is the default.
|
||||
final invoiceTemplatesProvider = FutureProvider<List<InvoiceTemplate>>((
|
||||
ref,
|
||||
) async {
|
||||
final response = await ApiService().get(
|
||||
'${ApiConfig.invoiceTemplates}?limit=50',
|
||||
);
|
||||
if (!response.success || response.data == null) {
|
||||
throw Exception(response.message ?? 'Failed to load templates');
|
||||
/// The template catalogue and the three writes the phone owns.
|
||||
///
|
||||
/// **The markup is not among them.** `template_html` / `template_css` stay on
|
||||
/// the admin-only editor route, which this app never calls, so neither field is
|
||||
/// read here and neither is ever sent. The detail PUT is `partial=True`, so a
|
||||
/// field a payload omits is left alone: an edit from the phone changes the
|
||||
/// ordinary fields and leaves the markup as the web editor stored it. That is
|
||||
/// the whole reason a form on a phone is safe here, and it is the one property
|
||||
/// a change to this file must not break.
|
||||
///
|
||||
/// Every write is admin-only server-side (`_forbid_non_admin_template`). The
|
||||
/// screen hides the controls from everyone else, which is a UX hint; a member
|
||||
/// who reaches them anyway gets the 403's own message.
|
||||
class InvoiceTemplatesNotifier extends AsyncNotifier<List<InvoiceTemplate>> {
|
||||
final ApiService _api = ApiService();
|
||||
|
||||
@override
|
||||
Future<List<InvoiceTemplate>> build() => _fetch();
|
||||
|
||||
Future<void> refresh() async {
|
||||
state = const AsyncValue.loading();
|
||||
state = await AsyncValue.guard(_fetch);
|
||||
}
|
||||
return _rows(
|
||||
response.data!,
|
||||
).map(InvoiceTemplate.fromJson).toList(growable: false);
|
||||
});
|
||||
|
||||
Future<List<InvoiceTemplate>> _fetch() async {
|
||||
final response = await _api.get('${ApiConfig.invoiceTemplates}?limit=50');
|
||||
if (!response.success || response.data == null) {
|
||||
throw Exception(response.message ?? 'Failed to load templates');
|
||||
}
|
||||
return _rows(
|
||||
response.data!,
|
||||
).map(InvoiceTemplate.fromJson).toList(growable: false);
|
||||
}
|
||||
|
||||
/// Returns null on success, the server's message otherwise.
|
||||
///
|
||||
/// [logoPath] uploads the logo in the same request. It has to be multipart
|
||||
/// because `logo` is an ImageField, and the ordinary fields ride along as
|
||||
/// form fields rather than being sent in a second call: a JSON create
|
||||
/// followed by a multipart update would leave a template with no logo behind
|
||||
/// whenever the second call failed.
|
||||
Future<String?> createTemplate(
|
||||
InvoiceTemplateDraft draft, {
|
||||
String? logoPath,
|
||||
}) async {
|
||||
final response = logoPath == null
|
||||
? await _api.post(ApiConfig.invoiceTemplates, draft.toPayload())
|
||||
: await _api.postMultipart(
|
||||
ApiConfig.invoiceTemplates,
|
||||
fileField: 'logo',
|
||||
filePath: logoPath,
|
||||
fields: draft.toMultipartFields(),
|
||||
);
|
||||
if (!response.success) return _message(response);
|
||||
await refresh();
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Save an edit. The draft carries a null `isDefault` on this path, so the
|
||||
/// payload omits the key and the org's default is left where it is.
|
||||
Future<String?> updateTemplate(
|
||||
String id,
|
||||
InvoiceTemplateDraft draft, {
|
||||
String? logoPath,
|
||||
}) async {
|
||||
final url = ApiConfig.invoiceTemplate(id);
|
||||
final response = logoPath == null
|
||||
? await _api.put(url, draft.toPayload())
|
||||
: await _api.postMultipart(
|
||||
url,
|
||||
fileField: 'logo',
|
||||
filePath: logoPath,
|
||||
fields: draft.toMultipartFields(),
|
||||
method: 'PUT',
|
||||
);
|
||||
if (!response.success) return _message(response);
|
||||
await refresh();
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Make one template the org default.
|
||||
///
|
||||
/// A swap rather than a toggle: the model clears `is_default` on every other
|
||||
/// template in the org inside a transaction, so there is no call that turns
|
||||
/// the flag off. Untoggling would leave the org without a default, which is
|
||||
/// why neither client offers it.
|
||||
Future<String?> setDefault(String id) async {
|
||||
final response = await _api.put(ApiConfig.invoiceTemplate(id), const {
|
||||
'is_default': true,
|
||||
});
|
||||
if (!response.success) return _message(response);
|
||||
await refresh();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
final invoiceTemplatesProvider =
|
||||
AsyncNotifierProvider<InvoiceTemplatesNotifier, List<InvoiceTemplate>>(
|
||||
InvoiceTemplatesNotifier.new,
|
||||
);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Reports
|
||||
|
|
|
|||
|
|
@ -67,6 +67,7 @@ import '../screens/invoices/invoice_detail_screen.dart';
|
|||
import '../screens/invoices/estimates_list_screen.dart';
|
||||
import '../screens/invoices/recurring_list_screen.dart';
|
||||
import '../screens/invoices/products_list_screen.dart';
|
||||
import '../screens/invoices/invoice_template_form_screen.dart';
|
||||
import '../screens/invoices/invoice_templates_screen.dart';
|
||||
import '../screens/invoices/invoice_reports_screen.dart';
|
||||
import '../screens/invoices/new_invoice_screen.dart';
|
||||
|
|
@ -189,8 +190,13 @@ class AppRoutes {
|
|||
static const String recurring = '/invoices/recurring';
|
||||
static const String products = '/invoices/products';
|
||||
static const String invoiceTemplates = '/invoices/templates';
|
||||
static const String invoiceTemplateNew = '/invoices/templates/new';
|
||||
static const String invoiceTemplateEdit = '/invoices/templates/:id/edit';
|
||||
static const String invoiceReports = '/invoices/reports';
|
||||
|
||||
static String invoiceTemplateEditFor(String id) =>
|
||||
'/invoices/templates/$id/edit';
|
||||
|
||||
// Knowledge base
|
||||
static const String solutions = '/solutions';
|
||||
static const String solutionNew = '/solutions/new';
|
||||
|
|
@ -508,6 +514,19 @@ final appRouterProvider = Provider<GoRouter>((ref) {
|
|||
parentNavigatorKey: _rootNavigatorKey,
|
||||
builder: (context, state) => const InvoiceTemplatesScreen(),
|
||||
),
|
||||
GoRoute(
|
||||
path: AppRoutes.invoiceTemplateNew,
|
||||
name: 'invoiceTemplateNew',
|
||||
parentNavigatorKey: _rootNavigatorKey,
|
||||
builder: (context, state) => const InvoiceTemplateFormScreen(),
|
||||
),
|
||||
GoRoute(
|
||||
path: AppRoutes.invoiceTemplateEdit,
|
||||
name: 'invoiceTemplateEdit',
|
||||
parentNavigatorKey: _rootNavigatorKey,
|
||||
builder: (context, state) =>
|
||||
InvoiceTemplateFormScreen(templateId: state.pathParameters['id']),
|
||||
),
|
||||
GoRoute(
|
||||
path: AppRoutes.invoiceReports,
|
||||
name: 'invoiceReports',
|
||||
|
|
|
|||
603
mobile/lib/screens/invoices/invoice_template_form_screen.dart
Normal file
603
mobile/lib/screens/invoices/invoice_template_form_screen.dart
Normal file
|
|
@ -0,0 +1,603 @@
|
|||
import 'package:file_picker/file_picker.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:lucide_icons_flutter/lucide_icons.dart';
|
||||
|
||||
import '../../core/theme/theme.dart';
|
||||
import '../../data/models/invoice_template.dart';
|
||||
import '../../providers/invoice_extras_provider.dart';
|
||||
import '../../services/attachment_upload.dart';
|
||||
import '../../widgets/forms/unsaved_changes.dart';
|
||||
|
||||
/// Create or edit a PDF template. One screen for both, the way the documents,
|
||||
/// accounts and contacts forms already work here.
|
||||
///
|
||||
/// **What this form does not touch.** `template_html` and `template_css` are
|
||||
/// org-authored markup that WeasyPrint renders into a PDF server-side. They are
|
||||
/// not read here, not shown here and not sent here, so they stay exactly as the
|
||||
/// web editor left them: `PUT /invoices/templates/<id>/` is partial, and a key
|
||||
/// a payload omits is a key the serializer never sees. That is what makes a
|
||||
/// template form on a phone safe, and it is why the screen says where the
|
||||
/// layout is edited rather than pretending the layout is all there is.
|
||||
///
|
||||
/// The seven fields it does own are ordinary form input, which is what made
|
||||
/// this worth building: a name, two brand colours, a logo, and the boilerplate
|
||||
/// text every new invoice starts from.
|
||||
///
|
||||
/// `is_default` appears on create and not on edit. It is a singleton the model
|
||||
/// swaps inside a transaction, so an off switch riding along with an unrelated
|
||||
/// save would demote the org's current default and leave it with none. The list
|
||||
/// screen owns it. The web's two forms split it the same way.
|
||||
///
|
||||
/// Every write is admin-only server-side. The list hides the way in from
|
||||
/// everyone else, and this screen shows the 403's own message to anyone who
|
||||
/// arrives at the route directly.
|
||||
class InvoiceTemplateFormScreen extends ConsumerStatefulWidget {
|
||||
const InvoiceTemplateFormScreen({super.key, this.templateId});
|
||||
|
||||
/// Null creates. An id edits, and is resolved against the catalogue rather
|
||||
/// than fetched: every field this form writes is already on the list row, so
|
||||
/// there is nothing a detail call would add.
|
||||
final String? templateId;
|
||||
|
||||
bool get isEdit => templateId != null;
|
||||
|
||||
@override
|
||||
ConsumerState<InvoiceTemplateFormScreen> createState() =>
|
||||
_InvoiceTemplateFormScreenState();
|
||||
}
|
||||
|
||||
class _InvoiceTemplateFormScreenState
|
||||
extends ConsumerState<InvoiceTemplateFormScreen> {
|
||||
final _name = TextEditingController();
|
||||
final _primary = TextEditingController(
|
||||
text: InvoiceTemplate.defaultPrimaryColor,
|
||||
);
|
||||
final _secondary = TextEditingController(
|
||||
text: InvoiceTemplate.defaultSecondaryColor,
|
||||
);
|
||||
final _notes = TextEditingController();
|
||||
final _terms = TextEditingController();
|
||||
final _footer = TextEditingController();
|
||||
|
||||
bool _isDefault = false;
|
||||
PlatformFile? _logo;
|
||||
bool _hadLogo = false;
|
||||
|
||||
bool _prefilled = false;
|
||||
bool _dirty = false;
|
||||
bool _saving = false;
|
||||
String? _error;
|
||||
String? _nameError;
|
||||
String? _primaryError;
|
||||
String? _secondaryError;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
for (final c in [_name, _primary, _secondary, _notes, _terms, _footer]) {
|
||||
c.addListener(_markDirty);
|
||||
}
|
||||
}
|
||||
|
||||
/// A form that opens already dirty prompts on the way out of a screen nobody
|
||||
/// edited, so the prefill below clears the flag after filling the fields.
|
||||
void _markDirty() {
|
||||
if (!_dirty) _dirty = true;
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
for (final c in [_name, _primary, _secondary, _notes, _terms, _footer]) {
|
||||
c.dispose();
|
||||
}
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _prefill(InvoiceTemplate t) {
|
||||
_name.text = t.name;
|
||||
_primary.text = t.primaryColor ?? InvoiceTemplate.defaultPrimaryColor;
|
||||
_secondary.text = t.secondaryColor ?? InvoiceTemplate.defaultSecondaryColor;
|
||||
_notes.text = t.defaultNotes;
|
||||
_terms.text = t.defaultTerms;
|
||||
_footer.text = t.footerText;
|
||||
_hadLogo = t.hasLogo;
|
||||
_prefilled = true;
|
||||
_dirty = false;
|
||||
}
|
||||
|
||||
InvoiceTemplate? _find(List<InvoiceTemplate>? all) {
|
||||
if (all == null) return null;
|
||||
for (final t in all) {
|
||||
if (t.id == widget.templateId) return t;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
Future<void> _pickLogo() async {
|
||||
// Reuses the attachment picker for its path and size checks, narrowed to
|
||||
// images because `logo` is an ImageField: Pillow refuses anything else
|
||||
// server-side, and a 400 after an upload is a poor way to learn that.
|
||||
final result = await selectAttachment(
|
||||
pickFile: () async {
|
||||
final picked = await FilePicker.pickFiles(
|
||||
type: FileType.image,
|
||||
withReadStream: false,
|
||||
);
|
||||
if (picked == null || picked.files.isEmpty) return null;
|
||||
return picked.files.first;
|
||||
},
|
||||
);
|
||||
if (result.cancelled || !mounted) return;
|
||||
if (result.error != null) {
|
||||
setState(() => _error = result.error);
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
_logo = result.file;
|
||||
_dirty = true;
|
||||
_error = null;
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _save() async {
|
||||
final name = _name.text.trim();
|
||||
final primary = _primary.text.trim();
|
||||
final secondary = _secondary.text.trim();
|
||||
|
||||
setState(() {
|
||||
_nameError = name.isEmpty ? 'Give the template a name' : null;
|
||||
// Mirrors `_validate_hex_color` in the serializer. Both colours are
|
||||
// substituted into the PDF stylesheet, so a value a renderer cannot parse
|
||||
// prints every invoice in the org with a broken accent. The server
|
||||
// refuses it too; this saves the round trip.
|
||||
_primaryError = InvoiceTemplateDraft.isHexColor(primary)
|
||||
? null
|
||||
: 'Use a six digit hex colour, for example #3B82F6';
|
||||
_secondaryError = InvoiceTemplateDraft.isHexColor(secondary)
|
||||
? null
|
||||
: 'Use a six digit hex colour, for example #1E40AF';
|
||||
// The button sits below the fields on a 390px screen, so a tap that only
|
||||
// lights an `errorText` several hundred pixels up the form reads as a
|
||||
// tap that did nothing. This puts a line where the thumb already is.
|
||||
_error =
|
||||
_nameError == null && _primaryError == null && _secondaryError == null
|
||||
? null
|
||||
: 'Check the highlighted fields above.';
|
||||
});
|
||||
if (_error != null) return;
|
||||
|
||||
final draft = InvoiceTemplateDraft(
|
||||
name: name,
|
||||
primaryColor: primary,
|
||||
secondaryColor: secondary,
|
||||
defaultNotes: _notes.text.trim(),
|
||||
defaultTerms: _terms.text.trim(),
|
||||
footerText: _footer.text.trim(),
|
||||
// Null on an edit: the list owns the default, and sending `false` here
|
||||
// would demote whichever template currently holds it.
|
||||
isDefault: widget.isEdit ? null : _isDefault,
|
||||
);
|
||||
|
||||
setState(() {
|
||||
_saving = true;
|
||||
_error = null;
|
||||
});
|
||||
|
||||
final notifier = ref.read(invoiceTemplatesProvider.notifier);
|
||||
final error = widget.isEdit
|
||||
? await notifier.updateTemplate(
|
||||
widget.templateId!,
|
||||
draft,
|
||||
logoPath: _logo?.path,
|
||||
)
|
||||
: await notifier.createTemplate(draft, logoPath: _logo?.path);
|
||||
|
||||
if (_logo != null) await clearAttachmentPickerCache();
|
||||
if (!mounted) return;
|
||||
setState(() => _saving = false);
|
||||
|
||||
if (error != null) {
|
||||
setState(() => _error = error);
|
||||
return;
|
||||
}
|
||||
_dirty = false;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(widget.isEdit ? 'Template saved' : 'Template created'),
|
||||
),
|
||||
);
|
||||
context.pop();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final async = ref.watch(invoiceTemplatesProvider);
|
||||
|
||||
if (widget.isEdit && !_prefilled) {
|
||||
final existing = _find(async.value);
|
||||
if (existing != null) {
|
||||
_prefill(existing);
|
||||
} else if (async.isLoading) {
|
||||
return _shell(const Center(child: CircularProgressIndicator()));
|
||||
} else {
|
||||
return _shell(
|
||||
Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Text(
|
||||
'That template is no longer in the catalogue.',
|
||||
textAlign: TextAlign.center,
|
||||
style: AppTypography.body.copyWith(
|
||||
color: AppColors.textSecondary,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return UnsavedChangesGuard(
|
||||
hasUnsavedChanges: () => _dirty,
|
||||
isSaving: _saving,
|
||||
child: _shell(
|
||||
ListView(
|
||||
padding: const EdgeInsets.only(bottom: 32),
|
||||
children: [
|
||||
_card('Name', [
|
||||
TextField(
|
||||
controller: _name,
|
||||
textCapitalization: TextCapitalization.sentences,
|
||||
maxLength: 100,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Template name',
|
||||
border: const OutlineInputBorder(),
|
||||
errorText: _nameError,
|
||||
),
|
||||
),
|
||||
]),
|
||||
_card('Brand colours', [
|
||||
_ColourField(
|
||||
label: 'Primary',
|
||||
controller: _primary,
|
||||
errorText: _primaryError,
|
||||
onPicked: (hex) => setState(() {
|
||||
_primary.text = hex;
|
||||
_primaryError = null;
|
||||
}),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
_ColourField(
|
||||
label: 'Secondary',
|
||||
controller: _secondary,
|
||||
errorText: _secondaryError,
|
||||
onPicked: (hex) => setState(() {
|
||||
_secondary.text = hex;
|
||||
_secondaryError = null;
|
||||
}),
|
||||
),
|
||||
]),
|
||||
_card('Logo', [_logoRow()]),
|
||||
_card('Boilerplate', [
|
||||
TextField(
|
||||
controller: _notes,
|
||||
textCapitalization: TextCapitalization.sentences,
|
||||
minLines: 2,
|
||||
maxLines: 4,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Default notes',
|
||||
hintText: 'Thanks for your business.',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: _terms,
|
||||
textCapitalization: TextCapitalization.sentences,
|
||||
minLines: 2,
|
||||
maxLines: 4,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Default terms',
|
||||
hintText: 'Payment due within 30 days.',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: _footer,
|
||||
textCapitalization: TextCapitalization.sentences,
|
||||
minLines: 1,
|
||||
maxLines: 3,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Footer text',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'New invoices start from these. Changing them here does not '
|
||||
'rewrite invoices already raised.',
|
||||
style: AppTypography.caption.copyWith(
|
||||
color: AppColors.textSecondary,
|
||||
),
|
||||
),
|
||||
]),
|
||||
if (!widget.isEdit)
|
||||
_card('Default template', [
|
||||
// Its own Material, because `_card` paints a background: a
|
||||
// ListTile draws its splash on the nearest Material ancestor,
|
||||
// so without this the switch has no touch feedback at all.
|
||||
// Flutter asserts on the arrangement, which is how the 390px
|
||||
// render test caught it.
|
||||
Material(
|
||||
color: AppColors.surface,
|
||||
child: SwitchListTile(
|
||||
contentPadding: EdgeInsets.zero,
|
||||
value: _isDefault,
|
||||
onChanged: (v) => setState(() {
|
||||
_isDefault = v;
|
||||
_dirty = true;
|
||||
}),
|
||||
title: const Text('Use this for new invoices'),
|
||||
subtitle: const Text(
|
||||
'Only one template can be the default. Turning this on '
|
||||
'replaces whichever holds it now.',
|
||||
),
|
||||
),
|
||||
),
|
||||
]),
|
||||
_card('Layout', [
|
||||
Text(
|
||||
'The PDF layout is HTML and CSS, and it is edited on the web. '
|
||||
'Saving here changes the fields above and leaves the layout '
|
||||
'as it is.',
|
||||
style: AppTypography.caption.copyWith(
|
||||
color: AppColors.textSecondary,
|
||||
),
|
||||
),
|
||||
]),
|
||||
if (_error != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 16, 16, 0),
|
||||
child: Text(
|
||||
_error!,
|
||||
style: AppTypography.caption.copyWith(
|
||||
color: AppColors.danger600,
|
||||
),
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 20, 16, 0),
|
||||
child: SizedBox(
|
||||
height: 48,
|
||||
child: FilledButton(
|
||||
onPressed: _saving ? null : _save,
|
||||
child: Text(
|
||||
_saving
|
||||
? 'Saving...'
|
||||
: widget.isEdit
|
||||
? 'Save template'
|
||||
: 'Create template',
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _shell(Widget body) {
|
||||
return Scaffold(
|
||||
backgroundColor: AppColors.surfaceDim,
|
||||
appBar: AppBar(
|
||||
title: Text(widget.isEdit ? 'Edit template' : 'New template'),
|
||||
backgroundColor: AppColors.surface,
|
||||
elevation: 0,
|
||||
scrolledUnderElevation: 1,
|
||||
leading: IconButton(
|
||||
icon: const Icon(LucideIcons.chevronLeft),
|
||||
tooltip: 'Back',
|
||||
onPressed: _saving
|
||||
? null
|
||||
: () => leaveForm(context, hasUnsavedChanges: _dirty),
|
||||
),
|
||||
),
|
||||
body: body,
|
||||
);
|
||||
}
|
||||
|
||||
Widget _logoRow() {
|
||||
final picked = _logo;
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
picked != null
|
||||
? picked.name
|
||||
: _hadLogo
|
||||
? 'A logo is already set. Choosing one replaces it.'
|
||||
: 'No logo. Invoices print with the org name instead.',
|
||||
style: AppTypography.caption.copyWith(color: AppColors.textSecondary),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
SizedBox(
|
||||
height: 44,
|
||||
child: OutlinedButton.icon(
|
||||
onPressed: _saving ? null : _pickLogo,
|
||||
icon: const Icon(LucideIcons.image, size: 18),
|
||||
label: Text(
|
||||
picked != null || _hadLogo ? 'Replace logo' : 'Add logo',
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _card(String title, List<Widget> children) {
|
||||
return Container(
|
||||
margin: const EdgeInsets.only(top: 8),
|
||||
color: AppColors.surface,
|
||||
padding: const EdgeInsets.fromLTRB(16, 14, 16, 16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
title,
|
||||
style: AppTypography.caption.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
color: AppColors.textSecondary,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
...children,
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A hex colour, picked from swatches or typed.
|
||||
///
|
||||
/// Swatches first because this is a phone: typing `#3B82F6` on a soft keyboard
|
||||
/// to change a brand colour is the kind of thing that gets a feature called
|
||||
/// unusable. The field stays editable for an exact brand value the palette does
|
||||
/// not carry, and both routes end at the same `#RRGGBB` string the API takes.
|
||||
class _ColourField extends StatelessWidget {
|
||||
const _ColourField({
|
||||
required this.label,
|
||||
required this.controller,
|
||||
required this.onPicked,
|
||||
this.errorText,
|
||||
});
|
||||
|
||||
final String label;
|
||||
final TextEditingController controller;
|
||||
final ValueChanged<String> onPicked;
|
||||
final String? errorText;
|
||||
|
||||
/// The app palette, plus the neutrals an invoice actually tends to use.
|
||||
static const List<String> presets = [
|
||||
'#3B82F6',
|
||||
'#1E40AF',
|
||||
'#16A34A',
|
||||
'#F97316',
|
||||
'#DC2626',
|
||||
'#7C3AED',
|
||||
'#0F172A',
|
||||
'#4B5563',
|
||||
];
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// The whole field rebuilds on every keystroke, swatches included. With only
|
||||
// the input inside the builder, typing a hex by hand changed the preview
|
||||
// and left the matching swatch unringed until something else rebuilt.
|
||||
return ListenableBuilder(
|
||||
listenable: controller,
|
||||
builder: (context, _) {
|
||||
final typed = controller.text.trim().toUpperCase();
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
TextField(
|
||||
controller: controller,
|
||||
autocorrect: false,
|
||||
decoration: InputDecoration(
|
||||
labelText: label,
|
||||
border: const OutlineInputBorder(),
|
||||
errorText: errorText,
|
||||
prefixIcon: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(12, 10, 8, 10),
|
||||
child: Container(
|
||||
width: 22,
|
||||
decoration: BoxDecoration(
|
||||
color: swatchColor(typed) ?? AppColors.gray200,
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
border: Border.all(color: AppColors.gray300),
|
||||
),
|
||||
),
|
||||
),
|
||||
prefixIconConstraints: const BoxConstraints(minWidth: 0),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
for (final hex in presets)
|
||||
_Swatch(
|
||||
hex: hex,
|
||||
selected: typed == hex,
|
||||
onTap: () => onPicked(hex),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _Swatch extends StatelessWidget {
|
||||
const _Swatch({
|
||||
required this.hex,
|
||||
required this.selected,
|
||||
required this.onTap,
|
||||
});
|
||||
|
||||
final String hex;
|
||||
final bool selected;
|
||||
final VoidCallback onTap;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Semantics(
|
||||
selected: selected,
|
||||
button: true,
|
||||
label: hex,
|
||||
child: InkWell(
|
||||
onTap: onTap,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
// 44 square, the minimum comfortable tap target, rather than sizing
|
||||
// the box to the swatch it draws.
|
||||
child: SizedBox(
|
||||
width: 44,
|
||||
height: 44,
|
||||
child: Center(
|
||||
child: Container(
|
||||
width: 30,
|
||||
height: 30,
|
||||
decoration: BoxDecoration(
|
||||
color: swatchColor(hex) ?? AppColors.gray200,
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
border: Border.all(
|
||||
color: selected ? AppColors.textPrimary : AppColors.gray300,
|
||||
width: selected ? 2.5 : 1,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// `#RRGGBB` to a colour, or null for anything else.
|
||||
///
|
||||
/// Null rather than a throw or a guessed colour: the value is org-authored free
|
||||
/// text that reaches here mid-typing, so "not a colour yet" is the ordinary
|
||||
/// case and not an error worth a crash.
|
||||
Color? swatchColor(String? hex) {
|
||||
final value = (hex ?? '').replaceAll('#', '').trim();
|
||||
if (value.length != 6) return null;
|
||||
final parsed = int.tryParse(value, radix: 16);
|
||||
return parsed == null ? null : Color(0xFF000000 | parsed);
|
||||
}
|
||||
|
|
@ -1,30 +1,56 @@
|
|||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:lucide_icons_flutter/lucide_icons.dart';
|
||||
|
||||
import '../../core/theme/theme.dart';
|
||||
import '../../data/models/invoice_template.dart';
|
||||
import '../../providers/auth_provider.dart';
|
||||
import '../../providers/invoice_extras_provider.dart';
|
||||
import '../../routes/app_router.dart';
|
||||
import '../../widgets/common/badge.dart';
|
||||
import 'invoice_shell.dart';
|
||||
import 'invoice_template_form_screen.dart' show swatchColor;
|
||||
|
||||
/// PDF templates, read-only by design.
|
||||
/// PDF templates: the catalogue, and the writes an admin can make from a phone.
|
||||
///
|
||||
/// The web has three pages here: a list, a create form and an editor. Only the
|
||||
/// list is on mobile, and that is a decision rather than a gap. A template's
|
||||
/// body is raw HTML and CSS that WeasyPrint renders server-side, so the editor
|
||||
/// is admin-only and the markup never leaves the editor endpoint. Shipping a
|
||||
/// markup editor to a phone would mean pulling that markup onto the device to
|
||||
/// no benefit, and a two-pane HTML editor is not a 390px screen either.
|
||||
/// Reading is open to every member, since knowing which template an invoice
|
||||
/// will print in is useful to whoever raised it. Creating, editing and
|
||||
/// re-pointing the default are admin-only, which the API enforces
|
||||
/// (`_forbid_non_admin_template`); the controls below are hidden from everyone
|
||||
/// else as a courtesy, not as the check.
|
||||
///
|
||||
/// What is useful on a phone is knowing which template an invoice will come
|
||||
/// out in and which is the default, so that is what this shows.
|
||||
/// **The layout itself is still edited on the web.** A template's body is
|
||||
/// org-authored HTML and CSS that WeasyPrint renders server-side, it never
|
||||
/// leaves the admin-only editor route, and a two-pane markup editor is not a
|
||||
/// 390px screen. Everything else about a template is ordinary form input, so
|
||||
/// that is what the form screen owns, and a save from here leaves the markup
|
||||
/// untouched.
|
||||
class InvoiceTemplatesScreen extends ConsumerWidget {
|
||||
const InvoiceTemplatesScreen({super.key});
|
||||
|
||||
Future<void> _setDefault(
|
||||
BuildContext context,
|
||||
WidgetRef ref,
|
||||
InvoiceTemplate template,
|
||||
) async {
|
||||
final error = await ref
|
||||
.read(invoiceTemplatesProvider.notifier)
|
||||
.setDefault(template.id);
|
||||
if (!context.mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
error ?? '${template.name} is now the default for new invoices',
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final async = ref.watch(invoiceTemplatesProvider);
|
||||
final isAdmin = ref.watch(isOrgAdminProvider);
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: AppColors.surfaceDim,
|
||||
|
|
@ -33,33 +59,52 @@ class InvoiceTemplatesScreen extends ConsumerWidget {
|
|||
backgroundColor: AppColors.surface,
|
||||
elevation: 0,
|
||||
scrolledUnderElevation: 1,
|
||||
actions: [
|
||||
if (isAdmin)
|
||||
IconButton(
|
||||
icon: const Icon(LucideIcons.plus),
|
||||
tooltip: 'New template',
|
||||
onPressed: () => context.push(AppRoutes.invoiceTemplateNew),
|
||||
),
|
||||
],
|
||||
),
|
||||
body: async.when(
|
||||
loading: () => const Center(child: CircularProgressIndicator()),
|
||||
error: (_, _) => InvoiceErrorState(
|
||||
message: 'Could not load templates',
|
||||
onRetry: () => ref.invalidate(invoiceTemplatesProvider),
|
||||
onRetry: () => ref.read(invoiceTemplatesProvider.notifier).refresh(),
|
||||
),
|
||||
data: (templates) {
|
||||
if (templates.isEmpty) {
|
||||
return const InvoiceEmptyState(
|
||||
return InvoiceEmptyState(
|
||||
icon: LucideIcons.layoutTemplate,
|
||||
message: 'No templates yet',
|
||||
detail: 'Invoices use the built-in layout until one is added.',
|
||||
detail: isAdmin
|
||||
? 'Invoices use the built-in layout until one is added.'
|
||||
: 'Invoices use the built-in layout. An administrator adds '
|
||||
'these.',
|
||||
);
|
||||
}
|
||||
return RefreshIndicator(
|
||||
onRefresh: () async => ref.invalidate(invoiceTemplatesProvider),
|
||||
onRefresh: () =>
|
||||
ref.read(invoiceTemplatesProvider.notifier).refresh(),
|
||||
child: ListView(
|
||||
padding: const EdgeInsets.only(bottom: 96),
|
||||
children: [
|
||||
for (final t in templates) _TemplateCard(template: t),
|
||||
for (final t in templates)
|
||||
_TemplateCard(
|
||||
template: t,
|
||||
canManage: isAdmin,
|
||||
onEdit: () =>
|
||||
context.push(AppRoutes.invoiceTemplateEditFor(t.id)),
|
||||
onSetDefault: () => _setDefault(context, ref, t),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 16, 16, 0),
|
||||
child: Text(
|
||||
'Templates are edited on the web. The layout is HTML and '
|
||||
'CSS that renders into the PDF, and only an administrator '
|
||||
'can change it.',
|
||||
'A template\'s PDF layout is HTML and CSS, and it is '
|
||||
'edited on the web. The name, colours, logo and '
|
||||
'boilerplate are editable here.',
|
||||
style: AppTypography.caption.copyWith(
|
||||
color: AppColors.textSecondary,
|
||||
),
|
||||
|
|
@ -75,22 +120,21 @@ class InvoiceTemplatesScreen extends ConsumerWidget {
|
|||
}
|
||||
|
||||
class _TemplateCard extends StatelessWidget {
|
||||
const _TemplateCard({required this.template});
|
||||
const _TemplateCard({
|
||||
required this.template,
|
||||
required this.canManage,
|
||||
required this.onEdit,
|
||||
required this.onSetDefault,
|
||||
});
|
||||
|
||||
final InvoiceTemplate template;
|
||||
|
||||
/// `#RRGGBB` to a swatch, falling back to grey rather than throwing on
|
||||
/// anything unexpected: the value is org-authored free text.
|
||||
Color? _swatch(String? hex) {
|
||||
final value = hex?.replaceAll('#', '').trim() ?? '';
|
||||
if (value.length != 6) return null;
|
||||
final parsed = int.tryParse(value, radix: 16);
|
||||
return parsed == null ? null : Color(0xFF000000 | parsed);
|
||||
}
|
||||
final bool canManage;
|
||||
final VoidCallback onEdit;
|
||||
final VoidCallback onSetDefault;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final primary = _swatch(template.primaryColor);
|
||||
final primary = swatchColor(template.primaryColor);
|
||||
|
||||
return Container(
|
||||
color: AppColors.surface,
|
||||
|
|
@ -123,6 +167,12 @@ class _TemplateCard extends StatelessWidget {
|
|||
),
|
||||
),
|
||||
),
|
||||
if (canManage)
|
||||
IconButton(
|
||||
icon: const Icon(LucideIcons.pencil, size: 18),
|
||||
tooltip: 'Edit template',
|
||||
onPressed: onEdit,
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
|
|
@ -159,6 +209,20 @@ class _TemplateCard extends StatelessWidget {
|
|||
),
|
||||
],
|
||||
),
|
||||
// Making a template the default is a swap, not a toggle: the model
|
||||
// clears the flag on every other row in one transaction. So the one
|
||||
// already holding it gets no control, because there is nothing to
|
||||
// offer that would not leave the org without a default.
|
||||
if (canManage && !template.isDefault) ...[
|
||||
const SizedBox(height: 8),
|
||||
SizedBox(
|
||||
height: 44,
|
||||
child: OutlinedButton(
|
||||
onPressed: onSetDefault,
|
||||
child: const Text('Use for new invoices'),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
|
|
|
|||
|
|
@ -27,6 +27,9 @@ import 'package:bottle_crm/providers/settings_provider.dart';
|
|||
import 'package:bottle_crm/providers/timesheet_provider.dart';
|
||||
import 'package:bottle_crm/screens/invoices/estimates_list_screen.dart';
|
||||
import 'package:bottle_crm/screens/invoices/invoices_list_screen.dart';
|
||||
import 'package:bottle_crm/data/models/invoice_template.dart';
|
||||
import 'package:bottle_crm/screens/invoices/invoice_template_form_screen.dart';
|
||||
import 'package:bottle_crm/screens/invoices/invoice_templates_screen.dart';
|
||||
import 'package:bottle_crm/screens/invoices/new_invoice_screen.dart';
|
||||
import 'package:bottle_crm/screens/invoices/new_recurring_screen.dart';
|
||||
import 'package:bottle_crm/screens/invoices/products_list_screen.dart';
|
||||
|
|
@ -523,6 +526,24 @@ void main() {
|
|||
child: routed(const ProductsListScreen()),
|
||||
);
|
||||
|
||||
/// Both answers matter: reading the catalogue is open to any member, and
|
||||
/// every write on a template is admin-only.
|
||||
Widget templatesApp({required bool isAdmin}) => ProviderScope(
|
||||
overrides: [
|
||||
invoiceTemplatesProvider.overrideWith(_FakeTemplates.new),
|
||||
isOrgAdminProvider.overrideWithValue(isAdmin),
|
||||
],
|
||||
child: routed(const InvoiceTemplatesScreen()),
|
||||
);
|
||||
|
||||
/// The form over the same catalogue. [templateId] null creates; an id edits,
|
||||
/// and the fixture is what it pre-fills from, since the form reads the list
|
||||
/// row rather than making a detail call.
|
||||
Widget templateFormApp({String? templateId}) => ProviderScope(
|
||||
overrides: [invoiceTemplatesProvider.overrideWith(_FakeTemplates.new)],
|
||||
child: routed(InvoiceTemplateFormScreen(templateId: templateId)),
|
||||
);
|
||||
|
||||
Future<void> pump(
|
||||
WidgetTester tester,
|
||||
Widget app, {
|
||||
|
|
@ -533,6 +554,36 @@ void main() {
|
|||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
/// Scroll a long form until [target] is built, or give up.
|
||||
///
|
||||
/// A `ListView` builds only what is near the viewport, so on a 390x844 phone
|
||||
/// a card below the fold is not merely off-screen, it is absent from the
|
||||
/// tree. That makes a bare `findsNothing` on it worthless: it passes for a
|
||||
/// field that exists and one that does not. Giving up quietly is right, since
|
||||
/// the tests that assert absence want to reach the bottom and find nothing.
|
||||
///
|
||||
/// Dragging rather than `scrollUntilVisible`: every `TextField` on the form
|
||||
/// carries a `Scrollable` of its own, so the implicit scrollable lookup is
|
||||
/// ambiguous here. `find.byType(ListView)` is not.
|
||||
/// [step] is negative to go down the form and positive to come back up.
|
||||
Future<void> scrollForm(
|
||||
WidgetTester tester,
|
||||
Finder target, {
|
||||
double step = -320,
|
||||
}) async {
|
||||
for (var i = 0; i < 10 && target.evaluate().isEmpty; i++) {
|
||||
await tester.drag(find.byType(ListView), Offset(0, step));
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> submitForm(WidgetTester tester, String label) async {
|
||||
final button = find.widgetWithText(FilledButton, label);
|
||||
await scrollForm(tester, button);
|
||||
await tester.tap(button);
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
group('timesheet at 390px', () {
|
||||
testWidgets('renders a week without overflowing', (tester) async {
|
||||
await pump(tester, timesheetApp());
|
||||
|
|
@ -818,6 +869,159 @@ void main() {
|
|||
});
|
||||
});
|
||||
|
||||
group('invoice templates at 390px', () {
|
||||
testWidgets('the catalogue renders without overflowing', (tester) async {
|
||||
await pump(tester, templatesApp(isAdmin: true));
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
|
||||
testWidgets('the catalogue fits with the system font scaled up', (
|
||||
tester,
|
||||
) async {
|
||||
await pump(tester, templatesApp(isAdmin: true), textScale: 1.5);
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
|
||||
testWidgets('a member sees the catalogue and no write control', (
|
||||
tester,
|
||||
) async {
|
||||
// Every template write answers 403 to a member, so drawing one would be
|
||||
// drawing a guaranteed failure. The read stays open: knowing which
|
||||
// template an invoice prints in is useful to whoever raised it.
|
||||
await pump(tester, templatesApp(isAdmin: false));
|
||||
|
||||
expect(find.text('House style'), findsOneWidget);
|
||||
expect(find.byTooltip('New template'), findsNothing);
|
||||
expect(find.byTooltip('Edit template'), findsNothing);
|
||||
expect(
|
||||
find.widgetWithText(OutlinedButton, 'Use for new invoices'),
|
||||
findsNothing,
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('an admin gets a way in on every row', (tester) async {
|
||||
await pump(tester, templatesApp(isAdmin: true));
|
||||
|
||||
expect(find.byTooltip('New template'), findsOneWidget);
|
||||
expect(find.byTooltip('Edit template'), findsNWidgets(2));
|
||||
});
|
||||
|
||||
testWidgets('the template already holding the default is not offered it', (
|
||||
tester,
|
||||
) async {
|
||||
// Setting the default is a swap the model performs in one transaction,
|
||||
// so there is no call that turns the flag off. Offering it on the row
|
||||
// that holds it would be offering to leave the org without a default.
|
||||
await pump(tester, templatesApp(isAdmin: true));
|
||||
|
||||
expect(
|
||||
find.widgetWithText(OutlinedButton, 'Use for new invoices'),
|
||||
findsOneWidget,
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('the form renders without overflowing', (tester) async {
|
||||
await pump(tester, templateFormApp());
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
|
||||
testWidgets('the form fits with the system font scaled up', (tester) async {
|
||||
await pump(tester, templateFormApp(), textScale: 1.5);
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
|
||||
testWidgets('editing pre-fills from the catalogue row', (tester) async {
|
||||
await pump(tester, templateFormApp(templateId: 't1'));
|
||||
|
||||
expect(find.text('House style'), findsOneWidget);
|
||||
expect(find.text('#3B82F6'), findsOneWidget);
|
||||
|
||||
await scrollForm(tester, find.text('Thanks, as ever.'));
|
||||
expect(find.text('Thanks, as ever.'), findsOneWidget);
|
||||
expect(find.text('Settle within 14 days.'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('the form says where the layout is edited instead', (
|
||||
tester,
|
||||
) async {
|
||||
// `template_html` and `template_css` stay on the admin-only editor
|
||||
// route: the phone neither reads nor writes them, which is why a save
|
||||
// from here cannot blank the layout the web editor stored. Saying
|
||||
// nothing about that would read as "this form is the whole template".
|
||||
await pump(tester, templateFormApp(templateId: 't1'));
|
||||
await scrollForm(tester, find.textContaining('edited on the web'));
|
||||
|
||||
expect(find.textContaining('edited on the web'), findsOneWidget);
|
||||
expect(find.widgetWithText(TextField, 'Custom HTML'), findsNothing);
|
||||
expect(find.widgetWithText(TextField, 'Custom CSS'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('the default switch is on create only', (tester) async {
|
||||
// Carrying an off switch through an unrelated edit would demote the
|
||||
// org's current default and leave it with none, so the edit form does
|
||||
// not own the field at all. The web splits its two forms the same way.
|
||||
await pump(tester, templateFormApp());
|
||||
await scrollForm(tester, find.text('Use this for new invoices'));
|
||||
expect(find.text('Use this for new invoices'), findsOneWidget);
|
||||
|
||||
await pump(tester, templateFormApp(templateId: 't1'));
|
||||
await scrollForm(tester, find.text('Use this for new invoices'));
|
||||
expect(find.text('Use this for new invoices'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('a name is refused where the thumb already is', (tester) async {
|
||||
// The submit button is below the fold on a phone, so lighting only the
|
||||
// name field's own error, several hundred pixels up, reads as a tap that
|
||||
// did nothing. Both halves have to be there: the line by the button, and
|
||||
// the field it points at.
|
||||
await pump(tester, templateFormApp());
|
||||
await submitForm(tester, 'Create template');
|
||||
expect(find.text('Check the highlighted fields above.'), findsOneWidget);
|
||||
|
||||
await scrollForm(
|
||||
tester,
|
||||
find.text('Give the template a name'),
|
||||
step: 320,
|
||||
);
|
||||
expect(find.text('Give the template a name'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('a colour that is not hex is refused the same way', (
|
||||
tester,
|
||||
) async {
|
||||
// The serializer refuses it too, which is the check that counts. This is
|
||||
// the round trip saved, and the reason the swatches are there.
|
||||
await pump(tester, templateFormApp());
|
||||
await tester.enterText(
|
||||
find.widgetWithText(TextField, 'Template name'),
|
||||
'Brand',
|
||||
);
|
||||
await tester.enterText(find.widgetWithText(TextField, 'Primary'), 'red');
|
||||
await submitForm(tester, 'Create template');
|
||||
expect(find.text('Check the highlighted fields above.'), findsOneWidget);
|
||||
|
||||
await scrollForm(
|
||||
tester,
|
||||
find.textContaining('six digit hex colour'),
|
||||
step: 320,
|
||||
);
|
||||
expect(find.textContaining('six digit hex colour'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('tapping a swatch fills the field with its hex', (
|
||||
tester,
|
||||
) async {
|
||||
// Typing `#3B82F6` on a soft keyboard to change a brand colour is what
|
||||
// the swatches exist to avoid, so the tap has to land in the field the
|
||||
// payload reads.
|
||||
await pump(tester, templateFormApp());
|
||||
await tester.tap(find.bySemanticsLabel('#16A34A').first);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('#16A34A'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
group('the new invoice form at 390px', () {
|
||||
testWidgets('renders without overflowing', (tester) async {
|
||||
await pump(tester, newInvoiceApp());
|
||||
|
|
@ -3112,6 +3316,37 @@ class _FakeProducts extends ProductsNotifier {
|
|||
];
|
||||
}
|
||||
|
||||
/// The org default plus one alternative, so the row that holds the flag and
|
||||
/// the row that could take it are both on screen.
|
||||
class _FakeTemplates extends InvoiceTemplatesNotifier {
|
||||
@override
|
||||
Future<List<InvoiceTemplate>> build() async => [
|
||||
InvoiceTemplate.fromJson({
|
||||
'id': 't1',
|
||||
'name': 'House style',
|
||||
'is_default': true,
|
||||
'primary_color': '#3B82F6',
|
||||
'secondary_color': '#1E40AF',
|
||||
'has_logo': true,
|
||||
'has_custom_html': true,
|
||||
// Deliberately not the field hints, which say "Thanks for your
|
||||
// business." and "Payment due within 30 days.": a fixture that matches
|
||||
// its own placeholder cannot tell a pre-filled field from an empty one.
|
||||
'default_notes': 'Thanks, as ever.',
|
||||
'default_terms': 'Settle within 14 days.',
|
||||
'footer_text': 'Questions? Ask for Dana.',
|
||||
'used_on_invoices': 4,
|
||||
}),
|
||||
InvoiceTemplate.fromJson({
|
||||
'id': 't2',
|
||||
'name': 'Minimal, for the quarterly retainer statements',
|
||||
'is_default': false,
|
||||
'primary_color': '#4B5563',
|
||||
'used_on_invoices': 0,
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
/// Monday has one stopped entry, Tuesday a running one, Wednesday nothing.
|
||||
class _FakeTimesheet extends TimesheetNotifier {
|
||||
@override
|
||||
|
|
|
|||
|
|
@ -389,6 +389,157 @@ void main() {
|
|||
isNot(contains('script')),
|
||||
);
|
||||
});
|
||||
|
||||
test('the editable text fields come off the list row', () async {
|
||||
// The form pre-fills from the catalogue rather than a detail call, which
|
||||
// only works while the list serializer carries these three.
|
||||
client.body = '''
|
||||
{"count": 1, "results": [
|
||||
{"id": "t1", "name": "House style", "default_notes": "Thanks.",
|
||||
"default_terms": "Net 30", "footer_text": "Ask for Dana"}
|
||||
]}''';
|
||||
|
||||
final t = (await readTemplates()).single;
|
||||
|
||||
expect(t.defaultNotes, 'Thanks.');
|
||||
expect(t.defaultTerms, 'Net 30');
|
||||
expect(t.footerText, 'Ask for Dana');
|
||||
});
|
||||
|
||||
group('the draft a form submits', () {
|
||||
const draft = InvoiceTemplateDraft(
|
||||
name: ' House style ',
|
||||
primaryColor: '#3B82F6',
|
||||
secondaryColor: '#1E40AF',
|
||||
defaultNotes: 'Thanks.',
|
||||
);
|
||||
|
||||
test('never names either markup field', () {
|
||||
// The whole reason a template form on a phone is safe: the PUT is
|
||||
// partial, so a key the payload omits is a key the serializer never
|
||||
// sees, and the web editor's markup survives a save from here.
|
||||
final payload = draft.toPayload();
|
||||
|
||||
expect(payload.containsKey('template_html'), isFalse);
|
||||
expect(payload.containsKey('template_css'), isFalse);
|
||||
});
|
||||
|
||||
test('trims the name and keeps the rest verbatim', () {
|
||||
final payload = draft.toPayload();
|
||||
|
||||
expect(payload['name'], 'House style');
|
||||
expect(payload['primary_color'], '#3B82F6');
|
||||
expect(payload['default_notes'], 'Thanks.');
|
||||
});
|
||||
|
||||
test('omits is_default when the form does not own it', () {
|
||||
// An edit sends null, and an absent key is what leaves the org's
|
||||
// current default where it is. Sending `false` would demote it.
|
||||
expect(draft.toPayload().containsKey('is_default'), isFalse);
|
||||
});
|
||||
|
||||
test('sends is_default when the create form does own it', () {
|
||||
const creating = InvoiceTemplateDraft(
|
||||
name: 'New',
|
||||
primaryColor: '#3B82F6',
|
||||
secondaryColor: '#1E40AF',
|
||||
isDefault: false,
|
||||
);
|
||||
|
||||
expect(creating.toPayload()['is_default'], isFalse);
|
||||
});
|
||||
|
||||
test('spells booleans out for a multipart body', () {
|
||||
const creating = InvoiceTemplateDraft(
|
||||
name: 'New',
|
||||
primaryColor: '#3B82F6',
|
||||
secondaryColor: '#1E40AF',
|
||||
isDefault: true,
|
||||
);
|
||||
|
||||
expect(creating.toMultipartFields()['is_default'], 'true');
|
||||
});
|
||||
});
|
||||
|
||||
group('the hex colour rule', () {
|
||||
// Mirrors `_validate_hex_color` in the serializer, which is the check
|
||||
// that counts. Both directions, since a rule that only ever says yes is
|
||||
// the shape that has bitten this codebase before.
|
||||
test('accepts six hex digits in either case', () {
|
||||
expect(InvoiceTemplateDraft.isHexColor('#3B82F6'), isTrue);
|
||||
expect(InvoiceTemplateDraft.isHexColor('#a1b2c3'), isTrue);
|
||||
expect(InvoiceTemplateDraft.isHexColor(' #000000 '), isTrue);
|
||||
});
|
||||
|
||||
test('refuses a colour name, a short form and a missing hash', () {
|
||||
expect(InvoiceTemplateDraft.isHexColor('purple'), isFalse);
|
||||
expect(InvoiceTemplateDraft.isHexColor('#abc'), isFalse);
|
||||
expect(InvoiceTemplateDraft.isHexColor('3B82F6'), isFalse);
|
||||
expect(InvoiceTemplateDraft.isHexColor(''), isFalse);
|
||||
});
|
||||
|
||||
test('refuses something that would break the PDF stylesheet', () {
|
||||
// `pdf.py` substitutes this straight into the CSS, so the seven
|
||||
// characters the column allows are seven characters of stylesheet.
|
||||
expect(InvoiceTemplateDraft.isHexColor('}a{b:c'), isFalse);
|
||||
});
|
||||
});
|
||||
|
||||
group('the writes', () {
|
||||
const feed =
|
||||
'{"count": 1, "results": [{"id": "t1", "name": "House style"}]}';
|
||||
const draft = InvoiceTemplateDraft(
|
||||
name: 'House style',
|
||||
primaryColor: '#3B82F6',
|
||||
secondaryColor: '#1E40AF',
|
||||
);
|
||||
|
||||
Future<InvoiceTemplatesNotifier> notifier() async {
|
||||
client.body = feed;
|
||||
await readTemplates();
|
||||
return container.read(invoiceTemplatesProvider.notifier);
|
||||
}
|
||||
|
||||
test('an edit PUTs to the template it names', () async {
|
||||
final n = await notifier();
|
||||
client.sent.clear();
|
||||
|
||||
expect(await n.updateTemplate('t1', draft), isNull);
|
||||
|
||||
final write = client.sent.first;
|
||||
expect(write.method, 'PUT');
|
||||
expect(write.url.path, endsWith('/invoices/templates/t1/'));
|
||||
});
|
||||
|
||||
test('setting the default sends only that flag', () async {
|
||||
// A swap, not a field write: the model clears `is_default` on every
|
||||
// other row. Sending anything else here would carry stale values from
|
||||
// whenever the list was last loaded.
|
||||
final n = await notifier();
|
||||
client.sent.clear();
|
||||
|
||||
expect(await n.setDefault('t1'), isNull);
|
||||
|
||||
final write = client.sent.first as http.Request;
|
||||
expect(jsonDecode(write.body), {'is_default': true});
|
||||
});
|
||||
|
||||
test(
|
||||
'a refused write returns the server message and does not throw',
|
||||
() async {
|
||||
final n = await notifier();
|
||||
client.status = 403;
|
||||
client.body =
|
||||
'{"error": true, "message": "Only an administrator can change '
|
||||
'invoice templates."}';
|
||||
|
||||
expect(
|
||||
await n.createTemplate(draft),
|
||||
contains('Only an administrator'),
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
group('reports', () {
|
||||
|
|
|
|||
|
|
@ -74,6 +74,56 @@ void main() {
|
|||
});
|
||||
});
|
||||
|
||||
group('the template form routes', () {
|
||||
test('sit under the catalogue, two segments past /invoices', () {
|
||||
// Same reasoning as `recurring/new`: `:id` matches one segment, so
|
||||
// neither of these can be mistaken for an invoice id. That is why they
|
||||
// are absent from `siblings` rather than an oversight.
|
||||
for (final path in [
|
||||
AppRoutes.invoiceTemplateNew,
|
||||
AppRoutes.invoiceTemplateEdit,
|
||||
]) {
|
||||
expect(
|
||||
path,
|
||||
startsWith('${AppRoutes.invoiceTemplates}/'),
|
||||
reason: path,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('the create and edit paths cannot match each other', () {
|
||||
// `/invoices/templates/new` is two segments and
|
||||
// `/invoices/templates/:id/edit` is three, so declaration order between
|
||||
// the two does not matter. If the edit path ever loses its `/edit` tail,
|
||||
// it would swallow `new` as an id and this fails.
|
||||
expect(
|
||||
AppRoutes.invoiceTemplateNew.split('/'),
|
||||
isNot(hasLength(AppRoutes.invoiceTemplateEdit.split('/').length)),
|
||||
);
|
||||
expect(AppRoutes.invoiceTemplateEdit, endsWith('/edit'));
|
||||
});
|
||||
|
||||
test('the helper builds the path the route declares', () {
|
||||
// A hand-built string here is how a link goes to a 404 that nothing
|
||||
// catches, since go_router answers an unmatched path at runtime.
|
||||
expect(
|
||||
AppRoutes.invoiceTemplateEditFor('abc-123'),
|
||||
AppRoutes.invoiceTemplateEdit.replaceFirst(':id', 'abc-123'),
|
||||
);
|
||||
});
|
||||
|
||||
test('both are in the real router', () {
|
||||
final container = ProviderContainer();
|
||||
addTearDown(container.dispose);
|
||||
final order = _invoicePaths(
|
||||
container.read(appRouterProvider).configuration.routes,
|
||||
);
|
||||
|
||||
expect(order, contains(AppRoutes.invoiceTemplateNew));
|
||||
expect(order, contains(AppRoutes.invoiceTemplateEdit));
|
||||
});
|
||||
});
|
||||
|
||||
group('the detail route', () {
|
||||
test('takes a single :id segment', () {
|
||||
expect(AppRoutes.invoiceDetail, '${AppRoutes.invoices}/:id');
|
||||
|
|
|
|||
Loading…
Reference in a new issue