feat: add the catering login to settings, with an Android-only fetch

The credential **fields** appear on every platform; the **fetch button** only
where it can work. That split is the point, not an oversight: the panel sends
no CORS headers so a browser cannot call it, but the desktop app is where a
password is most likely to be typed, and the credential syncs — so hiding the
fields on web would mean the phone could only ever be set up by typing on the
phone. On web the button is replaced by a line saying why, and noting the
login still reaches the phone from there.

The section says the password is stored and synced in plain text rather than
implying otherwise.

The button disables itself while a fetch is in flight, so an impatient
double-tap cannot pay a second login plus three requests against a third
party. The result line says dishes were added to the **food bank** and that
the user still logs them when eaten — the wording carries the
delivered-is-not-eaten rule to the one place a user actually reads.

`settings_screen.dart` was already at 247 of its 250-line budget, so the
section owns its own leading divider and the fetch handler lives beside it;
the screen spends one line on it.

678 Dart tests.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QQpCiPaSbyRpwsLkH3dgsX
This commit is contained in:
Krzysztof Rudnicki 2026-08-23 08:33:52 +02:00
parent 3d82ddefd4
commit 5c9c1ff160
4 changed files with 318 additions and 1 deletions

View File

@ -0,0 +1,185 @@
/// The catering-panel credential section of the settings screen.
///
/// Its own file because `settings_screen.dart` sits at the repo's 250-line
/// ceiling.
///
/// Two things about this section are deliberate:
///
/// * **The fields show on every platform, the fetch button only on Android.**
/// The panel sends no CORS headers, so a browser cannot call it -- but the
/// desktop app is where the user is most likely to be typing a password, and
/// the credential syncs, so hiding the fields there would mean the phone
/// could only ever be set up by typing on the phone.
/// * **The password is stored and synced in plaintext**, and the section says
/// so rather than implying otherwise. The rest of the synced state is not
/// encrypted either.
library;
import 'package:diet_guard_app/services/kuchnia_client.dart';
import 'package:diet_guard_app/services/kuchnia_credential_service.dart';
import 'package:diet_guard_app/services/kuchnia_import.dart';
import 'package:diet_guard_app/ui/theme.dart';
import 'package:flutter/material.dart';
/// Fetches today's delivery and reports what was banked.
///
/// Deliberately says "banked", not "logged": a delivered meal is not an eaten
/// meal, so the dishes land in the food bank and the user still taps to log
/// each one. Top-level so the settings screen can pass it without growing.
Future<String> fetchTodaysDelivery() async {
final result = await refreshDelivery(DateTime.now());
if (!result.ok) return result.reason!;
if (result.dishes.isEmpty) return 'No delivery found for today.';
final count = result.dishes.length;
return '$count ${count == 1 ? 'dish' : 'dishes'} added to your food bank. '
'Log them from the meal screen when you eat them.';
}
/// Credential fields plus, on Android, a "fetch today's delivery" action.
class KuchniaSettingsSection extends StatefulWidget {
/// Creates the section.
///
/// [canFetch] defaults to [kuchniaFetchSupported] -- false on web, where the
/// button is replaced by a one-line explanation rather than silently
/// vanishing. [onFetch] defaults to the real fetch. Both are injectable so a
/// widget test can drive the section without a network or a platform check.
const KuchniaSettingsSection({
this.canFetch,
this.onFetch,
super.key,
});
/// Whether this platform can reach the catering panel; null means ask.
final bool? canFetch;
/// Fetches today's delivery and returns a status line; null means the real
/// one.
final Future<String> Function()? onFetch;
@override
State<KuchniaSettingsSection> createState() => _KuchniaSettingsSectionState();
}
class _KuchniaSettingsSectionState extends State<KuchniaSettingsSection> {
late final TextEditingController _username = TextEditingController(
text: KuchniaCredentialService.username,
);
late final TextEditingController _password = TextEditingController(
text: KuchniaCredentialService.password,
);
bool _obscured = true;
bool _busy = false;
String? _status;
@override
void dispose() {
_username.dispose();
_password.dispose();
super.dispose();
}
Future<void> _save() async {
if (!KuchniaCredentialService.isInitialized) return;
await KuchniaCredentialService.instance.save(
_username.text,
_password.text,
);
if (!mounted) return;
setState(() => _status = 'Saved. It will sync to your other devices.');
}
Future<void> _fetch() async {
setState(() {
_busy = true;
_status = null;
});
final message = await (widget.onFetch ?? fetchTodaysDelivery)();
if (!mounted) return;
setState(() {
_busy = false;
_status = message;
});
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final canFetch = widget.canFetch ?? kuchniaFetchSupported;
// The section owns its own leading divider so the settings screen needs a
// single line for it -- that file sits on the repo's 250-line ceiling.
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(height: 24),
const Divider(),
const SizedBox(height: 8),
Text('Kuchnia Wikinga', style: theme.textTheme.titleMedium),
const SizedBox(height: 4),
Text(
"Your catering panel login, so this device can look up the day's "
'delivered dishes and their macros. Stored and synced in plain '
'text, like the rest of your synced data.',
style: theme.textTheme.bodySmall,
),
const SizedBox(height: 12),
ConstrainedBox(
constraints: const BoxConstraints(maxWidth: AppWidth.field),
child: TextField(
controller: _username,
keyboardType: TextInputType.emailAddress,
autocorrect: false,
decoration: const InputDecoration(labelText: 'Panel e-mail'),
onSubmitted: (_) => _save(),
),
),
const SizedBox(height: 12),
ConstrainedBox(
constraints: const BoxConstraints(maxWidth: AppWidth.field),
child: TextField(
controller: _password,
obscureText: _obscured,
autocorrect: false,
enableSuggestions: false,
decoration: InputDecoration(
labelText: 'Panel password',
suffixIcon: IconButton(
icon: Icon(_obscured ? Icons.visibility : Icons.visibility_off),
tooltip: _obscured ? 'Show password' : 'Hide password',
onPressed: () => setState(() => _obscured = !_obscured),
),
),
onSubmitted: (_) => _save(),
),
),
const SizedBox(height: 12),
Wrap(
spacing: 8,
runSpacing: 8,
children: [
FilledButton(onPressed: _save, child: const Text('Save login')),
if (canFetch)
OutlinedButton.icon(
onPressed: _busy ? null : _fetch,
icon: const Icon(Icons.restaurant),
label: Text(
_busy ? 'Fetching…' : "Fetch today's delivery",
),
),
],
),
if (!canFetch) ...[
const SizedBox(height: 8),
Text(
'Android only — the catering panel blocks browser requests. Your '
'login still syncs to your phone from here.',
style: theme.textTheme.bodySmall,
),
],
if (_status != null) ...[
const SizedBox(height: 8),
Text(_status!, style: theme.textTheme.bodyMedium),
],
],
);
}
}

View File

@ -14,6 +14,7 @@ import 'package:crdt_sync/crdt_sync.dart';
import 'package:diet_guard_app/models/meal_schedule.dart';
import 'package:diet_guard_app/models/slot.dart';
import 'package:diet_guard_app/screens/github_mirror_screen.dart';
import 'package:diet_guard_app/screens/settings_kuchnia.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
import 'package:diet_guard_app/services/due_slot_check.dart';
import 'package:diet_guard_app/services/firebase_backend.dart';
@ -185,6 +186,7 @@ class _SettingsScreenState extends State<SettingsScreen>
const Divider(),
const SizedBox(height: 8),
..._mealScheduleSection(context),
const KuchniaSettingsSection(),
const SizedBox(height: 24),
const Divider(),
ListTile(

View File

@ -2,7 +2,7 @@ name: diet_guard_app
description: "Companion phone app for diet_guard: log meals on the go."
publish_to: 'none'
version: 1.0.62+1
version: 1.0.63+1
environment:
sdk: ^3.12.2

View File

@ -0,0 +1,130 @@
/// The catering credential section of the settings screen.
///
/// The behaviour that needs pinning is the platform split, because it is the
/// one thing a reader would plausibly "simplify" the wrong way: the credential
/// **fields** show everywhere (the desktop app is where a password is most
/// likely to be typed, and it syncs from there to the phone), while the
/// **fetch button** is Android-only, because the panel sends no CORS headers
/// and a browser cannot call it at all.
library;
import 'dart:async';
import 'package:diet_guard_app/screens/settings_kuchnia.dart';
import 'package:diet_guard_app/services/document_store.dart';
import 'package:diet_guard_app/services/kuchnia_credential_service.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
/// In-memory store, so these tests need no plugin channel.
class _MemoryStore implements DocumentStore {
final Map<String, String> documents = {};
@override
Future<String?> read(String name) async => documents[name];
@override
Future<void> write(String name, String contents) async {
documents[name] = contents;
}
}
Widget _host({required bool canFetch, Future<String> Function()? onFetch}) =>
MaterialApp(
home: Scaffold(
body: SingleChildScrollView(
child: KuchniaSettingsSection(canFetch: canFetch, onFetch: onFetch),
),
),
);
void main() {
setUp(() => KuchniaCredentialService.resetForTesting(store: _MemoryStore()));
tearDown(KuchniaCredentialService.resetForTesting);
testWidgets('shows both credential fields on every platform', (tester) async {
await tester.pumpWidget(_host(canFetch: false));
expect(find.text('Panel e-mail'), findsOneWidget);
expect(find.text('Panel password'), findsOneWidget);
});
testWidgets('offers the fetch button only where it can work', (tester) async {
await tester.pumpWidget(_host(canFetch: true));
expect(find.text("Fetch today's delivery"), findsOneWidget);
await tester.pumpWidget(_host(canFetch: false));
await tester.pumpAndSettle();
expect(find.text("Fetch today's delivery"), findsNothing);
});
testWidgets('explains the missing button rather than hiding it silently', (
tester,
) async {
await tester.pumpWidget(_host(canFetch: false));
expect(
find.textContaining('Android only'),
findsOneWidget,
reason: 'a browser user needs to know why there is no fetch button, and '
'that entering the login here still helps their phone',
);
});
testWidgets('saving persists the credential', (tester) async {
await tester.pumpWidget(_host(canFetch: true));
await tester.enterText(find.byType(TextField).first, 'me@example.com');
await tester.enterText(find.byType(TextField).last, 'hunter2');
await tester.tap(find.text('Save login'));
await tester.pumpAndSettle();
expect(KuchniaCredentialService.username, 'me@example.com');
expect(KuchniaCredentialService.password, 'hunter2');
expect(find.textContaining('Saved'), findsOneWidget);
});
testWidgets('the password is obscured until revealed', (tester) async {
await tester.pumpWidget(_host(canFetch: true));
TextField passwordField() =>
tester.widget<TextField>(find.byType(TextField).last);
expect(passwordField().obscureText, isTrue);
await tester.tap(find.byTooltip('Show password'));
await tester.pumpAndSettle();
expect(passwordField().obscureText, isFalse);
});
testWidgets('a fetch shows its result', (tester) async {
await tester.pumpWidget(
_host(canFetch: true, onFetch: () async => '3 dishes added'),
);
await tester.tap(find.text("Fetch today's delivery"));
await tester.pumpAndSettle();
expect(find.text('3 dishes added'), findsOneWidget);
});
testWidgets('a failed fetch shows the reason, not a crash', (tester) async {
await tester.pumpWidget(
_host(canFetch: true, onFetch: () async => 'catering login rejected'),
);
await tester.tap(find.text("Fetch today's delivery"));
await tester.pumpAndSettle();
expect(find.text('catering login rejected'), findsOneWidget);
});
testWidgets('the fetch button is disabled while a fetch is in flight', (
tester,
) async {
// Otherwise an impatient double-tap pays a second login plus three
// requests against a third party.
final gate = Completer<String>();
await tester.pumpWidget(_host(canFetch: true, onFetch: () => gate.future));
await tester.tap(find.text("Fetch today's delivery"));
await tester.pump();
expect(find.text('Fetching…'), findsOneWidget);
final button = tester.widget<OutlinedButton>(find.byType(OutlinedButton));
expect(button.onPressed, isNull);
gate.complete('done');
await tester.pumpAndSettle();
});
}