dashboard/app/lib/work/entry_sheet.dart
bashynx 820aca7d92 Settings sync between the dashboard and the app
- Dashboard (settingsync.py): the plugins' settings go into a synced
  settings.db, one row per setting (the row id is the setting's key, so the
  phone and the dashboard edit the same row; the later change wins) plus each
  field as the plugin declares it. Fields marked "local" (addresses, paths on
  one machine) and the plugins' on / off stay out. Values set on another
  device are checked as the Settings page does before they're saved; a
  refused one is written back with the dashboard's value.
- App 1.1.7: a Settings page (the gear on every tab) built from those fields,
  synced both ways. Food targets, the cycle, the work day and the body profile
  read the synced values; with a dashboard that doesn't sync settings yet,
  they still come from its Health summaries.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 16:30:00 +02:00

432 lines
16 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Booking time (the web page's entry form as a bottom sheet): what it was for — one picker for the
// whole tree + the recent ones as chips —, the day, start and end (an end at or before the start
// = the next day), billable (the tree's default + where it comes from), the rate and amount it
// comes to on that day, a note. Delete = tap twice. The last thing booked is remembered.
import 'package:flutter/material.dart';
import '../app/sync_service.dart';
import '../app/theme.dart';
import 'work_model.dart';
Color hexColor(String hex) => Color(int.parse('ff${hex.substring(1)}', radix: 16));
String hhmm(int minutes) => '${two(minutes ~/ 60 % 24)}:${two(minutes % 60)}';
const _dow = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
const _mon = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
String dayLabel(DateTime d) => '${_dow[d.weekday - 1]} ${d.day} ${_mon[d.month - 1]}${d.year != DateTime.now().year ? ' ${d.year}' : ''}';
/// A new entry at [day] from [startMin] (default: now, rounded down to 15 minutes), or [entry] to edit.
Future<void> openEntry(
BuildContext context,
SyncService sync, {
WorkEntry? entry,
DateTime? day,
int? startMin,
int? endMin,
String? node,
String note = '',
WorkSettings? s,
}) => showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: card,
builder: (_) => EntrySheet(sync: sync, entry: entry, day: day, startMin: startMin, endMin: endMin, node: node, note: note, s: s ?? WorkSettings.of(sync.store)),
);
class EntrySheet extends StatefulWidget {
const EntrySheet({
super.key,
required this.sync,
this.entry,
this.day,
this.startMin,
this.endMin,
this.node,
this.note = '',
required this.s,
});
final SyncService sync;
final WorkEntry? entry;
final DateTime? day;
final int? startMin, endMin;
final String? node; // a guess (an Activity block's customer); the last one booked otherwise
final String note; // a calendar event's title, an Activity block's items
final WorkSettings s;
@override
State<EntrySheet> createState() => _EntrySheetState();
}
class _EntrySheetState extends State<EntrySheet> {
late Tree t = Tree(widget.sync.store, widget.s);
late EntryForm f;
late final note = TextEditingController(text: f.note);
bool billableTouched = false, armed = false;
String? error, errorField;
@override
void initState() {
super.initState();
final e = widget.entry;
if (e != null) {
final d0 = dayOf(e.s);
f = EntryForm(
id: e.id,
node: e.node,
day: d0,
startMin: e.s.difference(d0).inMinutes,
endMin: e.e.difference(dayOf(e.e)).inMinutes,
endDay: e.e.difference(d0).inDays > 1 ? dayOf(e.e) : null,
billable: e.billable,
note: e.note,
);
billableTouched = true; // an entry's own billable stays as it is
} else {
final now = DateTime.now();
final start = widget.startMin ?? (now.hour * 60 + now.minute) ~/ 15 * 15;
var last = widget.node != null && t.nodes.containsKey(widget.node) ? widget.node : widget.sync.store.metaText('work_last');
if (last != null && (!t.nodes.containsKey(last) || t.archived(last))) last = null;
last ??= recent(widget.sync.store, t, 1).firstOrNull;
f = EntryForm(
node: last,
day: widget.day ?? dayOf(now),
startMin: start,
endMin: widget.endMin ?? start + widget.s.defaultMinutes,
billable: t.billable(last).$1,
note: widget.note,
);
}
}
void _pick(String nid) => setState(() {
f.node = nid;
if (!billableTouched) f.billable = t.billable(nid).$1;
if (errorField == 'node_id') error = errorField = null;
});
Future<void> _chooseNode() async {
final nid = await showModalBottomSheet<String>(
context: context,
isScrollControlled: true,
backgroundColor: card,
builder: (_) => NodePicker(tree: t, recent: recent(widget.sync.store, t), current: f.node),
);
if (nid != null) _pick(nid);
}
Future<void> _time(bool start) async {
final m = start ? f.startMin : f.endMin;
final p = await showTimePicker(
context: context,
initialTime: TimeOfDay(hour: m ~/ 60 % 24, minute: m % 60),
builder: (c, child) => MediaQuery(data: MediaQuery.of(c).copyWith(alwaysUse24HourFormat: true), child: child!),
);
if (p == null) return;
setState(() {
final v = p.hour * 60 + p.minute;
if (start) {
final dur = f.endMin - f.startMin; // moving the start keeps the length
f.startMin = v;
if (f.endDay == null) f.endMin = v + (dur > 0 ? dur : widget.s.defaultMinutes);
} else {
f.endMin = v;
}
});
}
Future<void> _date() async {
final p = await showDatePicker(context: context, initialDate: f.day, firstDate: DateTime(2000), lastDate: DateTime(2100));
if (p != null) setState(() => f.day = dayOf(p));
}
void _save() {
f.note = note.text; // an end past 24:00 (start + length, the + chips) is the next day's time: span() adds it to the day
try {
final id = saveEntry(widget.sync.store, t, f);
widget.sync.store.setMetaText('work_last', f.node);
widget.sync.changed();
Navigator.pop(context, id);
} on Invalid catch (e) {
setState(() {
error = e.message;
errorField = e.field;
});
}
}
void _delete() {
if (!armed) {
setState(() => armed = true);
return;
}
deleteEntry(widget.sync.store, f.id!);
widget.sync.changed();
Navigator.pop(context);
}
@override
Widget build(BuildContext context) {
final (a, b) = f.span();
final dur = b.difference(a).inMinutes;
final nid = f.node;
final (rate, rsrc) = t.rate(nid, fmtDay(f.day));
final cur = t.currency(nid);
final (defB, bsrc) = t.billable(nid);
final rec = recent(widget.sync.store, t).where((i) => i != nid).take(4).toList();
return Padding(
padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
child: SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(16, 14, 16, 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: [
Text(
f.id == null ? 'Book time' : 'Edit entry',
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent),
),
const SizedBox(height: 10),
if (t.isEmpty)
const Padding(
padding: EdgeInsets.only(bottom: 8),
child: Text('No customers yet — add one under ⋮ ▸ Customers first.', style: TextStyle(color: bad)),
),
// what for
InkWell(
borderRadius: BorderRadius.circular(10),
onTap: t.isEmpty ? null : _chooseNode,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
decoration: BoxDecoration(
color: card2,
borderRadius: BorderRadius.circular(10),
border: errorField == 'node_id' ? Border.all(color: bad) : null,
),
child: Row(
children: [
Icon(Icons.circle, size: 12, color: nid == null ? muted : hexColor(t.colour(nid))),
const SizedBox(width: 10),
Expanded(
child: Text(
nid == null ? 'What did you work on?' : t.path(nid),
style: TextStyle(fontSize: 15.5, color: nid == null ? muted : Colors.white),
),
),
const Icon(Icons.unfold_more, color: muted),
],
),
),
),
if (rec.isNotEmpty) ...[
const SizedBox(height: 6),
Wrap(
spacing: 6,
runSpacing: 4,
children: [
for (final r in rec)
ActionChip(
avatar: Icon(Icons.circle, size: 10, color: hexColor(t.colour(r))),
label: Text(t.nodes[r]!.name),
onPressed: () => _pick(r),
),
],
),
],
const SizedBox(height: 12),
// when
Row(
children: [
Expanded(flex: 5, child: _field(Icons.event, dayLabel(f.day), _date)),
const SizedBox(width: 6),
Expanded(flex: 3, child: _field(null, hhmm(f.startMin), () => _time(true))),
const Padding(
padding: EdgeInsets.symmetric(horizontal: 4),
child: Text('–', style: TextStyle(color: muted)),
),
Expanded(flex: 3, child: _field(null, hhmm(f.endMin), () => _time(false), bad: errorField == 'end')),
],
),
const SizedBox(height: 4),
Text(
[hm(dur > 0 ? dur : 0), if (!dayOf(b).isAtSameMomentAs(f.day) && dur > 0) 'ends ${dayLabel(dayOf(b))}'].join(' · '),
style: const TextStyle(color: muted),
),
const SizedBox(height: 4),
Wrap(
spacing: 6,
children: [
for (final m in const [15, 30, 60, 120])
ActionChip(label: Text(m < 60 ? '+$m min' : '+${m ~/ 60} h'), onPressed: () => setState(() => f.endMin += m)),
],
),
const SizedBox(height: 6),
// billable + money
SwitchListTile(
contentPadding: EdgeInsets.zero,
title: const Text('Billable'),
subtitle: Text(
nid == null ? '' : 'Default: ${defB ? 'billable' : 'not billable'}${bsrc != null ? ' (from ${bsrc.name})' : ''}',
style: const TextStyle(color: muted),
),
value: f.billable,
onChanged: (v) => setState(() {
f.billable = v;
billableTouched = true;
}),
),
if (nid != null && f.billable)
Text(
'${num0(rate)} $cur/h${rsrc != null ? ' from ${rsrc.name}' : ' (default)'} = ${money(dur > 0 ? dur / 60 * rate : 0, cur)}',
style: const TextStyle(color: muted),
),
const SizedBox(height: 10),
TextField(
controller: note,
minLines: 1,
maxLines: 5,
decoration: const InputDecoration(labelText: 'Note', border: OutlineInputBorder()),
),
if (error != null)
Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(error!, style: const TextStyle(color: bad)),
),
const SizedBox(height: 12),
Row(
children: [
if (f.id != null)
TextButton.icon(
onPressed: _delete,
icon: Icon(Icons.delete_outline, color: armed ? bad : muted),
label: Text(armed ? 'Tap again to delete' : 'Delete', style: TextStyle(color: armed ? bad : muted)),
),
const Spacer(),
TextButton(onPressed: () => Navigator.pop(context), child: const Text('Cancel')),
const SizedBox(width: 6),
FilledButton(onPressed: t.isEmpty ? null : _save, child: const Text('Save')),
],
),
],
),
),
);
}
Widget _field(IconData? icon, String text, VoidCallback onTap, {bool bad = false}) => InkWell(
borderRadius: BorderRadius.circular(10),
onTap: onTap,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 12),
decoration: BoxDecoration(
color: card2,
borderRadius: BorderRadius.circular(10),
border: bad ? Border.all(color: const Color(0xFFFF9A9A)) : null,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (icon != null) ...[Icon(icon, size: 16, color: muted), const SizedBox(width: 6)],
Flexible(
child: Text(text, overflow: TextOverflow.ellipsis, style: const TextStyle(fontSize: 15.5)),
),
],
),
),
);
}
/// The whole tree to pick from (the form's picker): a search box, the recent ones, then every live
/// node indented under its parent. Archived ones only when searching (or the current one).
class NodePicker extends StatefulWidget {
const NodePicker({super.key, required this.tree, required this.recent, this.current, this.only});
final Tree tree;
final List<String> recent;
final String? current;
final bool Function(Node)? only; // e.g. parents allowed for a kind
@override
State<NodePicker> createState() => _NodePickerState();
}
class _NodePickerState extends State<NodePicker> {
String q = '';
@override
Widget build(BuildContext context) {
final t = widget.tree;
final words = q.toLowerCase().split(RegExp(r'\s+')).where((w) => w.isNotEmpty).toList();
final rows = [
for (final (n, d) in t.walk(archived: true))
if ((widget.only?.call(n) ?? true) &&
(words.isEmpty ? (!t.archived(n.id) || n.id == widget.current) : words.every(t.path(n.id).toLowerCase().contains)))
(n, d),
];
return SizedBox(
height: MediaQuery.of(context).size.height * .75,
child: Padding(
padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
child: Column(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(12, 12, 12, 6),
child: TextField(
autofocus: false,
decoration: const InputDecoration(
prefixIcon: Icon(Icons.search),
hintText: 'Customer, project, task…',
border: OutlineInputBorder(),
),
onChanged: (v) => setState(() => q = v),
),
),
if (words.isEmpty && widget.recent.isNotEmpty && widget.only == null)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: Wrap(
spacing: 6,
children: [
for (final r in widget.recent)
ActionChip(
avatar: Icon(Icons.history, size: 15, color: hexColor(t.colour(r))),
label: Text(t.nodes[r]!.name),
onPressed: () => Navigator.pop(context, r),
),
],
),
),
Expanded(
child: rows.isEmpty
? const Center(
child: Text('Nothing matches', style: TextStyle(color: muted)),
)
: ListView(
children: [
for (final (n, d) in rows)
ListTile(
dense: true,
selected: n.id == widget.current,
contentPadding: EdgeInsets.only(left: 16.0 + (words.isEmpty ? d * 18 : 0), right: 12),
leading: Icon(
n.kind == 'task'
? Icons.check_box_outline_blank
: n.kind == 'project'
? Icons.folder_outlined
: Icons.business,
size: 18,
color: hexColor(t.colour(n.id)),
),
title: Text(
words.isEmpty ? n.name : t.path(n.id),
style: TextStyle(fontSize: 15, color: t.archived(n.id) ? muted : null),
),
subtitle: t.archived(n.id) ? const Text('archived', style: TextStyle(color: muted)) : null,
onTap: () => Navigator.pop(context, n.id),
),
],
),
),
],
),
),
);
}
}