dashboard/app/lib/work/customers_page.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

406 lines
16 KiB
Dart

// Customers (the web's Settings ▸ Work): the tree — customers, sub-customers, projects, tasks —
// with this month's hours and the rate in force today; tap one = its editor: name, where it sits,
// colour (customers always have one; below them "same as above" = inherit), billable (inherit /
// yes / no), currency, the rate history (from a day, or always), notes, archived. Nodes with time
// booked can't be deleted (archive them); a node's + adds a sub-customer / project / task under it.
import 'package:flutter/material.dart';
import '../app/sync_service.dart';
import '../app/theme.dart';
import 'entry_sheet.dart' show NodePicker, hexColor;
import 'work_model.dart';
IconData kindIcon(Node n) => n.kind == 'task'
? Icons.check_box_outline_blank
: n.kind == 'project'
? Icons.folder_outlined
: Icons.business;
class CustomersPage extends StatefulWidget {
const CustomersPage({super.key, required this.sync});
final SyncService sync;
WorkSettings get s => WorkSettings.of(sync.store); // the dashboard's, synced
@override
State<CustomersPage> createState() => _CustomersPageState();
}
class _CustomersPageState extends State<CustomersPage> {
bool showArchived = false;
void _edit({String? id, String kind = 'client', String? parent}) => Navigator.push(
context,
MaterialPageRoute(
builder: (_) => NodeEditor(sync: widget.sync, nodeId: id, kind: kind, parent: parent),
),
);
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: widget.sync,
builder: (context, _) {
final store = widget.sync.store;
final t = Tree(store, widget.s);
final now = DateTime.now(), first = DateTime.utc(now.year, now.month);
final month = <String, double>{};
for (final e in entriesBetween(store, first, now.add(const Duration(days: 1)))) {
for (final n in t.chain(e.node)) {
month[n.id] = (month[n.id] ?? 0) + e.minutes;
}
}
final todayIso = fmtDay(now);
final archivedCount = t.nodes.values.where((n) => n.archived).length;
final rows = t.walk(archived: showArchived).toList();
return Scaffold(
appBar: AppBar(
title: const Text('Customers'),
actions: [
if (archivedCount > 0)
TextButton(
onPressed: () => setState(() => showArchived = !showArchived),
child: Text(showArchived ? 'Hide archived' : 'Archived ($archivedCount)'),
),
],
),
floatingActionButton: FloatingActionButton.extended(
onPressed: () => _edit(),
icon: const Icon(Icons.add),
label: const Text('Customer'),
),
body: rows.isEmpty
? const Center(
child: Text('No customers yet', style: TextStyle(color: muted)),
)
: ListView(
padding: const EdgeInsets.only(bottom: 90),
children: [
for (final (n, d) in rows)
ListTile(
contentPadding: EdgeInsets.only(left: 16.0 + d * 20, right: 8),
leading: Icon(kindIcon(n), color: hexColor(t.colour(n.id))),
title: Text(n.name, style: TextStyle(color: t.archived(n.id) ? muted : null)),
subtitle: Text(
[
Tree.kindLabel(n),
'${num0(t.rate(n.id, todayIso).$1)} ${t.currency(n.id)}/h${t.rates[n.id]?.isNotEmpty == true ? '' : ' (inherited)'}',
if (!t.billable(n.id).$1) 'not billable',
if (month[n.id] != null) '${hm(month[n.id]!)} this month',
if (t.archived(n.id)) 'archived',
].join(' · '),
style: const TextStyle(color: muted, fontSize: 12.5),
),
trailing: n.kind == 'task' ? null : _addMenu(n),
onTap: () => _edit(id: n.id),
),
],
),
);
},
);
Widget _addMenu(Node n) => PopupMenuButton<String>(
icon: const Icon(Icons.add, color: muted),
tooltip: 'Add under ${n.name}',
color: card2,
onSelected: (k) => _edit(kind: k == 'sub' ? 'client' : k, parent: n.id),
itemBuilder: (_) => [
if (n.kind == 'client') const PopupMenuItem(value: 'sub', child: Text('Sub-customer')),
if (n.kind == 'client') const PopupMenuItem(value: 'project', child: Text('Project')),
const PopupMenuItem(value: 'task', child: Text('Task')),
],
);
}
/// One node's editor (new when [nodeId] is null: a [kind] under [parent]).
class NodeEditor extends StatefulWidget {
const NodeEditor({super.key, required this.sync, this.nodeId, this.kind = 'client', this.parent});
final SyncService sync;
WorkSettings get s => WorkSettings.of(sync.store); // the dashboard's, synced
final String? nodeId, kind, parent;
@override
State<NodeEditor> createState() => _NodeEditorState();
}
class _NodeEditorState extends State<NodeEditor> {
late Tree t = Tree(widget.sync.store, widget.s);
late NodeForm f = widget.nodeId != null && t.nodes.containsKey(widget.nodeId)
? NodeForm.of(t, t.nodes[widget.nodeId]!)
: NodeForm(kind: widget.kind ?? 'client', parent: widget.parent);
late final name = TextEditingController(text: f.name),
currency = TextEditingController(text: f.currency),
notes = TextEditingController(text: f.notes);
late final rateCtl = [for (final r in f.rates) TextEditingController(text: r.$2)];
late final sinceList = [for (final r in f.rates) r.$1];
String? error, errorField;
bool armed = false;
bool get isNew => f.id == null;
bool get topLevel => f.kind == 'client' && f.parent == null;
void _save() {
f
..name = name.text
..currency = currency.text
..notes = notes.text
..rates = [for (var i = 0; i < rateCtl.length; i++) (sinceList[i], rateCtl[i].text)];
try {
saveNode(widget.sync.store, t, f);
widget.sync.changed();
Navigator.pop(context);
} on Invalid catch (e) {
setState(() {
error = e.message;
errorField = e.field;
});
}
}
void _delete() {
if (!armed) {
setState(() => armed = true);
return;
}
if (!deleteNode(widget.sync.store, t, f.id!)) {
setState(() {
armed = false;
error = 'Time is booked on it — archive it instead.';
});
return;
}
widget.sync.changed();
Navigator.pop(context);
}
Future<void> _parent() async {
final allowed = parentsOf[f.kind]!;
final mine = f.id == null ? <String>{} : t.subtree(f.id!);
final nid = await showModalBottomSheet<String>(
context: context,
isScrollControlled: true,
backgroundColor: card,
builder: (_) =>
NodePicker(tree: t, recent: const [], current: f.parent, only: (n) => allowed.contains(n.kind) && !mine.contains(n.id)),
);
if (nid != null) setState(() => f.parent = nid);
}
Future<void> _since(int i) async {
final cur = DateTime.tryParse(sinceList[i]);
final p = await showDatePicker(
context: context,
initialDate: cur ?? DateTime.now(),
firstDate: DateTime(2000),
lastDate: DateTime(2100),
helpText: 'Rate from this day',
);
if (p != null) setState(() => sinceList[i] = fmtDay(p));
}
@override
Widget build(BuildContext context) {
final todayIso = fmtDay(DateTime.now());
final parentId = f.parent;
final (pRate, pRsrc) = parentId != null ? t.rate(parentId, todayIso) : (widget.s.defaultRate, null);
final (pBill, pBsrc) = parentId != null ? t.billable(parentId) : (true, null);
final pCur = parentId != null ? t.currency(parentId) : widget.s.currency;
final booked = f.id == null ? 0.0 : t.subtree(f.id!).fold(0.0, (m, i) => m + (bookedMinutes(widget.sync.store)[i] ?? 0));
final kindName = f.kind == 'client'
? (topLevel ? 'Customer' : 'Sub-customer')
: f.kind == 'project'
? 'Project'
: 'Task';
return Scaffold(
appBar: AppBar(
title: Text(isNew ? 'New ${kindName.toLowerCase()}' : kindName),
actions: [TextButton(onPressed: _save, child: const Text('Save'))],
),
body: ListView(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 32),
children: [
TextField(
controller: name,
autofocus: isNew,
textCapitalization: TextCapitalization.sentences,
decoration: InputDecoration(
labelText: 'Name',
border: const OutlineInputBorder(),
errorText: errorField == 'name' ? error : null,
),
),
const SizedBox(height: 12),
// where it sits (customers are top level; a sub-customer can move under another customer)
if (!topLevel || !isNew)
ListTile(
contentPadding: EdgeInsets.zero,
title: const Text('Under'),
subtitle: Text(
parentId == null ? '— top level (a customer)' : t.path(parentId),
style: TextStyle(color: errorField == 'parent_id' ? bad : muted),
),
trailing: f.kind == 'client' && parentId != null
? TextButton(onPressed: () => setState(() => f.parent = null), child: const Text('Make top level'))
: null,
onTap: _parent,
),
if (errorField == 'parent_id') Text(error!, style: const TextStyle(color: bad)),
const SizedBox(height: 6),
const Text('Colour', style: TextStyle(color: muted)),
const SizedBox(height: 6),
Wrap(
spacing: 8,
runSpacing: 8,
children: [
if (!topLevel)
ChoiceChip(
label: const Text('Same as above'),
avatar: Icon(Icons.circle, size: 14, color: hexColor(t.colour(parentId))),
selected: f.colour == null,
onSelected: (_) => setState(() => f.colour = null),
),
for (final c in [
if (f.colour != null && !palette.contains(f.colour)) f.colour!,
...palette,
]) // a custom one (set on the web) first
GestureDetector(
onTap: () => setState(() => f.colour = c),
child: Container(
width: 32,
height: 32,
decoration: BoxDecoration(
color: hexColor(c),
shape: BoxShape.circle,
border: Border.all(color: f.colour == c ? Colors.white : Colors.transparent, width: 2.5),
),
),
),
],
),
const SizedBox(height: 16),
const Text('New entries are', style: TextStyle(color: muted)),
const SizedBox(height: 6),
SegmentedButton<int?>(
segments: [
ButtonSegment(value: null, label: Text(pBill ? 'Inherit (billable)' : 'Inherit (not)')),
const ButtonSegment(value: 1, label: Text('Billable')),
const ButtonSegment(value: 0, label: Text('Not billable')),
],
selected: {f.billable},
showSelectedIcon: false,
onSelectionChanged: (v) => setState(() => f.billable = v.first),
),
if (f.billable == null)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Text(pBsrc != null ? 'from ${pBsrc.name}' : 'the default', style: const TextStyle(color: muted, fontSize: 12.5)),
),
const SizedBox(height: 16),
TextField(
controller: currency,
maxLength: 3,
textCapitalization: TextCapitalization.characters,
decoration: InputDecoration(
labelText: 'Currency',
hintText: '$pCur (inherited)',
border: const OutlineInputBorder(),
errorText: errorField == 'currency' ? error : null,
counterText: '',
),
),
const SizedBox(height: 16),
Row(
children: [
const Expanded(
child: Text('Hourly rate', style: TextStyle(color: muted)),
),
TextButton.icon(
onPressed: () => setState(() {
rateCtl.add(TextEditingController());
sinceList.add(rateCtl.length == 1 ? '' : todayIso);
}),
icon: const Icon(Icons.add),
label: Text(rateCtl.isEmpty ? 'Own rate' : 'New rate from a day'),
),
],
),
if (rateCtl.isEmpty)
Text('${num0(pRate)} $pCur/h — ${pRsrc != null ? 'from ${pRsrc.name}' : 'the default'}', style: const TextStyle(color: muted)),
for (var i = 0; i < rateCtl.length; i++)
Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Row(
children: [
Expanded(
child: OutlinedButton(
onPressed: () => _since(i),
onLongPress: () => setState(() => sinceList[i] = ''),
child: Text(sinceList[i].isEmpty ? 'Always' : 'From ${sinceList[i]}'),
),
),
const SizedBox(width: 8),
SizedBox(
width: 110,
child: TextField(
controller: rateCtl[i],
keyboardType: const TextInputType.numberWithOptions(decimal: true),
decoration: InputDecoration(
isDense: true,
border: const OutlineInputBorder(),
suffixText: '/h',
errorText: errorField == 'rates.$i.rate' || errorField == 'rates.$i.since' ? '!' : null,
),
),
),
IconButton(
onPressed: () => setState(() {
rateCtl.removeAt(i);
sinceList.removeAt(i);
}),
icon: const Icon(Icons.close, color: muted),
),
],
),
),
if (errorField?.startsWith('rates.') == true) Text(error!, style: const TextStyle(color: bad)),
if (rateCtl.isNotEmpty)
const Text(
'A rate counts from its day on; earlier work keeps the rate it had. Long-press a day = always.',
style: TextStyle(color: muted, fontSize: 12),
),
const SizedBox(height: 16),
TextField(
controller: notes,
minLines: 2,
maxLines: 8,
decoration: const InputDecoration(labelText: 'Notes', border: OutlineInputBorder()),
),
const SizedBox(height: 8),
SwitchListTile(
contentPadding: EdgeInsets.zero,
title: const Text('Archived'),
subtitle: const Text('Hidden from the picker; its time stays in reports', style: TextStyle(color: muted)),
value: f.archived,
onChanged: (v) => setState(() => f.archived = v),
),
if (error != null && errorField == null) Text(error!, style: const TextStyle(color: bad)),
const SizedBox(height: 12),
Row(
children: [
if (!isNew)
booked > 0
? Text('${hm(booked)} booked — archive instead of deleting', style: const TextStyle(color: muted, fontSize: 12.5))
: TextButton.icon(
onPressed: _delete,
icon: Icon(Icons.delete_outline, color: armed ? bad : muted),
label: Text(
armed ? 'Tap again to delete (with everything under it)' : 'Delete',
style: TextStyle(color: armed ? bad : muted),
),
),
const Spacer(),
FilledButton(onPressed: _save, child: const Text('Save')),
],
),
],
),
);
}
}