dashPi: a self-hosted home dashboard, its sync server and phone app
The dashboard (Raspberry Pi 3.5" screen + web pages), the end-to-end encrypted sync mailbox (PHP + SQLite) and the Android companion app (Flutter), with docs, clean-install checks and screenshots made from demo data. Built mostly with an AI coding assistant; not yet reviewed line by line by a human (see README and SECURITY.md). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
fb3c01cdd7
333 changed files with 45151 additions and 0 deletions
406
app/lib/work/customers_page.dart
Normal file
406
app/lib/work/customers_page.dart
Normal file
|
|
@ -0,0 +1,406 @@
|
|||
// 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, this.s = const WorkSettings()});
|
||||
final SyncService sync;
|
||||
final WorkSettings s;
|
||||
@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, s: widget.s, 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.s = const WorkSettings(), this.nodeId, this.kind = 'client', this.parent});
|
||||
final SyncService sync;
|
||||
final WorkSettings s;
|
||||
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')),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
432
app/lib/work/entry_sheet.dart
Normal file
432
app/lib/work/entry_sheet.dart
Normal file
|
|
@ -0,0 +1,432 @@
|
|||
// 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 = const WorkSettings(),
|
||||
}) => 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),
|
||||
);
|
||||
|
||||
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),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
239
app/lib/work/report_page.dart
Normal file
239
app/lib/work/report_page.dart
Normal file
|
|
@ -0,0 +1,239 @@
|
|||
// Report (the web's /work/report): a range — this / last week, month, year, or any days — and
|
||||
// optionally one customer; the totals, the tree with hours / billable / money per node, and every
|
||||
// entry (tap = edit). "Copy CSV" puts the entries on the clipboard in the Pi's CSV columns.
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../app/sync_service.dart';
|
||||
import '../app/theme.dart';
|
||||
import 'entry_sheet.dart';
|
||||
import 'work_model.dart';
|
||||
|
||||
class ReportPage extends StatefulWidget {
|
||||
const ReportPage({super.key, required this.sync, this.s = const WorkSettings()});
|
||||
final SyncService sync;
|
||||
final WorkSettings s;
|
||||
@override
|
||||
State<ReportPage> createState() => _ReportPageState();
|
||||
}
|
||||
|
||||
class _ReportPageState extends State<ReportPage> {
|
||||
String preset = 'month';
|
||||
late (DateTime, DateTime) range = presetRange('month')!;
|
||||
String? client;
|
||||
|
||||
String _amounts(Agg a) =>
|
||||
(a.amounts.entries.toList()..sort((x, y) => x.key.compareTo(y.key))).map((e) => money(e.value, e.key)).join(' · ');
|
||||
|
||||
Future<void> _custom() async {
|
||||
final p = await showDateRangePicker(
|
||||
context: context,
|
||||
firstDate: DateTime(2000),
|
||||
lastDate: DateTime(2100),
|
||||
initialDateRange: DateTimeRange(start: range.$1, end: range.$2),
|
||||
);
|
||||
if (p != null) {
|
||||
setState(() {
|
||||
preset = 'custom';
|
||||
range = (dayOf(p.start), dayOf(p.end));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => ListenableBuilder(
|
||||
listenable: widget.sync,
|
||||
builder: (context, _) {
|
||||
final store = widget.sync.store;
|
||||
final t = Tree(store, widget.s);
|
||||
final r = report(store, t, range.$1, range.$2, client: client);
|
||||
final clients = [
|
||||
for (final (n, d) in t.walk(archived: true))
|
||||
if (n.kind == 'client') (n, d),
|
||||
];
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Report'),
|
||||
actions: [
|
||||
IconButton(
|
||||
tooltip: 'Copy as CSV',
|
||||
icon: const Icon(Icons.copy_all),
|
||||
onPressed: r.items.isEmpty
|
||||
? null
|
||||
: () async {
|
||||
await Clipboard.setData(ClipboardData(text: reportCsv(r, t)));
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('${r.items.length} entries copied as CSV')));
|
||||
}
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
body: ListView(
|
||||
padding: const EdgeInsets.fromLTRB(12, 6, 12, 24),
|
||||
children: [
|
||||
Wrap(
|
||||
spacing: 6,
|
||||
runSpacing: 4,
|
||||
children: [
|
||||
for (final (k, label) in presets)
|
||||
ChoiceChip(
|
||||
label: Text(label),
|
||||
selected: preset == k,
|
||||
onSelected: (_) => setState(() {
|
||||
preset = k;
|
||||
range = presetRange(k)!;
|
||||
}),
|
||||
),
|
||||
ChoiceChip(
|
||||
label: Text(preset == 'custom' ? '${dayLabel(range.$1)} – ${dayLabel(range.$2)}' : 'Days…'),
|
||||
selected: preset == 'custom',
|
||||
onSelected: (_) => _custom(),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
DropdownButtonFormField<String?>(
|
||||
initialValue: client,
|
||||
isExpanded: true,
|
||||
decoration: const InputDecoration(labelText: 'Customer', border: OutlineInputBorder(), isDense: true),
|
||||
items: [
|
||||
const DropdownMenuItem(value: null, child: Text('Everyone')),
|
||||
for (final (n, d) in clients) DropdownMenuItem(value: n.id, child: Text('${' ' * d}${n.name}')),
|
||||
],
|
||||
onChanged: (v) => setState(() => client = v),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(14),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('${dayLabel(range.$1)} – ${dayLabel(range.$2)}', style: const TextStyle(color: muted)),
|
||||
const SizedBox(height: 4),
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.end,
|
||||
children: [
|
||||
Text(hm(r.total.m), style: const TextStyle(fontSize: 26, fontWeight: FontWeight.bold)),
|
||||
const SizedBox(width: 8),
|
||||
Text('${(r.total.m / 60).toStringAsFixed(2)} h', style: const TextStyle(color: muted)),
|
||||
const Spacer(),
|
||||
Text(_amounts(r.total), style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600)),
|
||||
],
|
||||
),
|
||||
Text.rich(
|
||||
TextSpan(
|
||||
children: [
|
||||
TextSpan(
|
||||
text: '${hm(r.total.bm)} billable',
|
||||
style: const TextStyle(color: good),
|
||||
),
|
||||
TextSpan(
|
||||
text: ' · ${hm(r.total.m - r.total.bm)} not billable',
|
||||
style: const TextStyle(color: muted),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
if (r.rows.isEmpty)
|
||||
const Padding(
|
||||
padding: EdgeInsets.all(24),
|
||||
child: Center(
|
||||
child: Text('Nothing booked in this range', style: TextStyle(color: muted)),
|
||||
),
|
||||
),
|
||||
if (r.rows.isNotEmpty) ...[
|
||||
const SizedBox(height: 10),
|
||||
Card(
|
||||
child: Column(
|
||||
children: [
|
||||
for (final row in r.rows)
|
||||
ListTile(
|
||||
dense: true,
|
||||
contentPadding: EdgeInsets.only(left: 12.0 + row.depth * 18, right: 12),
|
||||
leading: Icon(Icons.circle, size: 11, color: hexColor(t.colour(row.node.id))),
|
||||
minLeadingWidth: 10,
|
||||
title: Text(row.node.name, style: TextStyle(fontWeight: row.depth == 0 ? FontWeight.bold : null)),
|
||||
subtitle: Text(
|
||||
'${hm(row.agg.bm)} billable${row.agg.m > row.agg.bm ? ' · ${hm(row.agg.m - row.agg.bm)} not' : ''}',
|
||||
style: const TextStyle(color: muted, fontSize: 12),
|
||||
),
|
||||
trailing: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
crossAxisAlignment: CrossAxisAlignment.end,
|
||||
children: [
|
||||
Text(hm(row.agg.m), style: const TextStyle(fontWeight: FontWeight.w600)),
|
||||
if (row.agg.amounts.isNotEmpty) Text(_amounts(row.agg), style: const TextStyle(fontSize: 12, color: muted)),
|
||||
],
|
||||
),
|
||||
onTap: row.node.kind == 'client' ? () => setState(() => client = row.node.id) : null,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
Text(
|
||||
'Entries (${r.items.length})',
|
||||
style: const TextStyle(color: muted, fontWeight: FontWeight.w600),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
..._entries(t, r),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
List<Widget> _entries(Tree t, Report r) {
|
||||
final out = <Widget>[];
|
||||
String? lastDay;
|
||||
for (final i in r.items) {
|
||||
final e = i.e, d = e.start.substring(0, 10);
|
||||
if (d != lastDay) {
|
||||
out.add(
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(4, 10, 4, 2),
|
||||
child: Text(
|
||||
dayLabel(dayOf(e.s)),
|
||||
style: const TextStyle(color: accent, fontWeight: FontWeight.w600),
|
||||
),
|
||||
),
|
||||
);
|
||||
lastDay = d;
|
||||
}
|
||||
out.add(
|
||||
Card(
|
||||
margin: const EdgeInsets.only(bottom: 4),
|
||||
child: ListTile(
|
||||
dense: true,
|
||||
leading: Container(width: 4, height: 36, color: hexColor(t.colour(e.node))),
|
||||
minLeadingWidth: 4,
|
||||
title: Text(t.path(e.node)),
|
||||
subtitle: Text(
|
||||
['${e.start.substring(11)}–${e.end.substring(11)}', if (e.note.isNotEmpty) e.note.split('\n').first].join(' · '),
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: const TextStyle(color: muted),
|
||||
),
|
||||
trailing: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
crossAxisAlignment: CrossAxisAlignment.end,
|
||||
children: [
|
||||
Text(hm(e.minutes), style: const TextStyle(fontWeight: FontWeight.w600)),
|
||||
Text(e.billable ? money(i.amount, i.currency) : 'not billable', style: const TextStyle(fontSize: 12, color: muted)),
|
||||
],
|
||||
),
|
||||
onTap: () => openEntry(context, widget.sync, entry: e, s: widget.s),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
799
app/lib/work/work_model.dart
Normal file
799
app/lib/work/work_model.dart
Normal file
|
|
@ -0,0 +1,799 @@
|
|||
// The workload tracker — a port of the dashboard's plugins/workload: db.py (the tree, inheritance,
|
||||
// rate history, what an entry is) and views.py (week totals, the report). Keep them in step.
|
||||
//
|
||||
// Synced rows (workload.db, ids = the Pi's _uid; references are those ids):
|
||||
// "workload.node" {kind client|project|task, parent_id, name, colour, billable 0/1/null, currency,
|
||||
// notes, archived 0/1, created}
|
||||
// "workload.rate" {node_id, since 'YYYY-MM-DD' | '0000-01-01' = always, rate} id = '<node id>:<since>'
|
||||
// "workload.entry" {node_id, start, end 'YYYY-MM-DD HH:MM' local, billable 0/1, note, created, updated}
|
||||
import 'dart:convert';
|
||||
|
||||
import '../sync/store.dart';
|
||||
|
||||
const kinds = ['client', 'project', 'task'];
|
||||
const parentsOf = {
|
||||
'client': [null, 'client'],
|
||||
'project': ['client'],
|
||||
'task': ['client', 'project'],
|
||||
};
|
||||
const palette = ['#ffb33a', '#5cc8ff', '#7fd6a3', '#ff6b7a', '#c792ea', '#ff9d5c', '#82aaff', '#f78c6c', '#c3e88d', '#89ddff'];
|
||||
const epoch = '0000-01-01'; // a rate "since" this applies to all work
|
||||
const tNode = 'workload.node', tRate = 'workload.rate', tEntry = 'workload.entry';
|
||||
|
||||
/// Until settings sync: the dashboard's Settings ▸ Work defaults.
|
||||
class WorkSettings {
|
||||
const WorkSettings({
|
||||
this.currency = 'EUR',
|
||||
this.defaultRate = 0,
|
||||
this.dayStart = 7,
|
||||
this.dayEnd = 19,
|
||||
this.defaultMinutes = 60,
|
||||
this.weekTarget = 40,
|
||||
});
|
||||
final String currency;
|
||||
final double defaultRate;
|
||||
final int dayStart, dayEnd, defaultMinutes;
|
||||
final double weekTarget;
|
||||
}
|
||||
|
||||
class Invalid implements Exception {
|
||||
Invalid(this.field, this.message);
|
||||
final String field, message;
|
||||
@override
|
||||
String toString() => message;
|
||||
}
|
||||
|
||||
// ---- times -------------------------------------------------------------------------------
|
||||
|
||||
String two(int n) => n.toString().padLeft(2, '0');
|
||||
String fmtDay(DateTime d) => '${d.year}-${two(d.month)}-${two(d.day)}';
|
||||
String fmtMin(DateTime d) => '${fmtDay(d)} ${two(d.hour)}:${two(d.minute)}';
|
||||
String fmtSec(DateTime d) => '${fmtMin(d)}:${two(d.second)}';
|
||||
// Wall-clock time, like the Pi (naive datetimes): every date here is a UTC DateTime holding the local
|
||||
// fields, so a day is always 24 h and a week 7 × 24 h — summer time never shifts a block or a week number.
|
||||
DateTime parseMin(String s) => DateTime.parse('${s.replaceFirst(' ', 'T')}Z');
|
||||
DateTime dayOf(DateTime d) => DateTime.utc(d.year, d.month, d.day);
|
||||
|
||||
/// Monday 00:00 of the week [offset] weeks from this one (views.week_start).
|
||||
DateTime weekStart(int offset, [DateTime? now]) {
|
||||
final t = dayOf(now ?? DateTime.now());
|
||||
return DateTime.utc(t.year, t.month, t.day - (t.weekday - 1) + 7 * offset);
|
||||
}
|
||||
|
||||
/// The ISO week number of a week's Monday (Python's isocalendar()[1]).
|
||||
int isoWeek(DateTime monday) {
|
||||
final thu = DateTime.utc(monday.year, monday.month, monday.day + 3);
|
||||
return thu.difference(DateTime.utc(thu.year, 1, 1)).inDays ~/ 7 + 1;
|
||||
}
|
||||
|
||||
/// 90 → '1:30' (views.hm).
|
||||
String hm(num minutes) {
|
||||
final m = minutes.round();
|
||||
return '${m ~/ 60}:${two(m % 60)}';
|
||||
}
|
||||
|
||||
/// 1234.5 → '1 234.50 EUR' (views.money).
|
||||
String money(double amount, String currency) {
|
||||
final s = amount.toStringAsFixed(2), dot = s.indexOf('.');
|
||||
final neg = s.startsWith('-');
|
||||
final digits = s.substring(neg ? 1 : 0, dot);
|
||||
final b = StringBuffer(neg ? '-' : '');
|
||||
for (var i = 0; i < digits.length; i++) {
|
||||
if (i > 0 && (digits.length - i) % 3 == 0) b.write(' ');
|
||||
b.write(digits[i]);
|
||||
}
|
||||
return '$b${s.substring(dot)} $currency';
|
||||
}
|
||||
|
||||
/// A rate as the Pi's f"{rate:g}" would print it (20.0 → '20', 22.5 → '22.5').
|
||||
String num0(double v) => v == v.roundToDouble() ? v.round().toString() : v.toString();
|
||||
|
||||
// ---- rows --------------------------------------------------------------------------------
|
||||
|
||||
class Node {
|
||||
Node(this.r);
|
||||
final Map<String, dynamic> r;
|
||||
String get id => r['_u'] as String;
|
||||
String get kind => r['kind'] as String;
|
||||
String? get parent => r['parent_id'] as String?;
|
||||
String get name => r['name'] as String? ?? '?';
|
||||
String? get colour => r['colour'] as String?;
|
||||
int? get billable => (r['billable'] as num?)?.toInt();
|
||||
String? get currency => r['currency'] as String?;
|
||||
String get notes => r['notes'] as String? ?? '';
|
||||
bool get archived => (r['archived'] as num? ?? 0) != 0;
|
||||
bool get isSub => kind == 'client' && parent != null;
|
||||
}
|
||||
|
||||
class Rate {
|
||||
Rate(this.since, this.rate);
|
||||
final String since;
|
||||
final double rate;
|
||||
}
|
||||
|
||||
class WorkEntry {
|
||||
WorkEntry(this.r) : s = parseMin(r['start'] as String), e = parseMin(r['end'] as String);
|
||||
final Map<String, dynamic> r;
|
||||
final DateTime s, e;
|
||||
String get id => r['_u'] as String;
|
||||
String get node => r['node_id'] as String;
|
||||
String get start => r['start'] as String;
|
||||
String get end => r['end'] as String;
|
||||
bool get billable => (r['billable'] as num? ?? 0) != 0;
|
||||
String get note => r['note'] as String? ?? '';
|
||||
double get minutes => e.difference(s).inSeconds / 60;
|
||||
}
|
||||
|
||||
// ---- the tree ----------------------------------------------------------------------------
|
||||
|
||||
/// All nodes + rates in memory (db.Tree): inheritance, paths, the picker list.
|
||||
class Tree {
|
||||
Tree(SyncStore store, [this.s = const WorkSettings()]) {
|
||||
final ns = store.rows(tNode).map(Node.new).toList()..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));
|
||||
for (final n in ns) {
|
||||
nodes[n.id] = n;
|
||||
}
|
||||
for (final r in store.rows(tRate)) {
|
||||
final nid = r['node_id'] as String?;
|
||||
if (nid == null) continue;
|
||||
rates.putIfAbsent(nid, () => []).add(Rate(r['since'] as String, (r['rate'] as num).toDouble()));
|
||||
}
|
||||
for (final l in rates.values) {
|
||||
l.sort((a, b) => a.since.compareTo(b.since));
|
||||
}
|
||||
for (final n in nodes.values) {
|
||||
// a parent that isn't here (yet) → shown at the top until it arrives
|
||||
children.putIfAbsent(nodes.containsKey(n.parent) ? n.parent : null, () => []).add(n.id);
|
||||
}
|
||||
}
|
||||
|
||||
final WorkSettings s;
|
||||
final nodes = <String, Node>{};
|
||||
final rates = <String, List<Rate>>{};
|
||||
final children = <String?, List<String>>{};
|
||||
|
||||
bool get isEmpty => nodes.isEmpty;
|
||||
|
||||
/// The node and its ancestors, nearest first.
|
||||
List<Node> chain(String? nid) {
|
||||
final out = <Node>[], seen = <String>{};
|
||||
while (nid != null && nodes.containsKey(nid) && seen.add(nid)) {
|
||||
out.add(nodes[nid]!);
|
||||
nid = nodes[nid]!.parent;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
String path(String nid, [String sep = ' › ']) => chain(nid).reversed.map((n) => n.name).join(sep);
|
||||
|
||||
/// The top-level customer a node belongs to.
|
||||
Node? clientOf(String nid) {
|
||||
final c = chain(nid);
|
||||
return c.isEmpty ? null : c.last;
|
||||
}
|
||||
|
||||
(T, Node?) _inherit<T>(String? nid, T? Function(Node) key, T def) {
|
||||
for (final n in chain(nid)) {
|
||||
final v = key(n);
|
||||
if (v != null) return (v, n);
|
||||
}
|
||||
return (def, null);
|
||||
}
|
||||
|
||||
String colour(String? nid) => _inherit(nid, (n) => n.colour, palette[0]).$1;
|
||||
String currency(String? nid) => _inherit(nid, (n) => n.currency, s.currency).$1;
|
||||
|
||||
/// (default billable for new entries, the node it comes from or null = default yes).
|
||||
(bool, Node?) billable(String? nid) {
|
||||
final (v, src) = _inherit(nid, (n) => n.billable, 1);
|
||||
return (v != 0, src);
|
||||
}
|
||||
|
||||
/// (hourly rate on [day] 'YYYY-MM-DD', the node it comes from or null = the default rate):
|
||||
/// the nearest node with a rate in force that day wins.
|
||||
(double, Node?) rate(String? nid, String day) {
|
||||
for (final n in chain(nid)) {
|
||||
Rate? best;
|
||||
for (final r in rates[n.id] ?? const <Rate>[]) {
|
||||
if (r.since.compareTo(day) <= 0) best = r;
|
||||
}
|
||||
if (best != null) return (best.rate, n);
|
||||
}
|
||||
return (s.defaultRate, null);
|
||||
}
|
||||
|
||||
bool archived(String nid) => chain(nid).any((n) => n.archived);
|
||||
|
||||
/// Depth-first (node, depth): under each node its sub-customers, then projects, then tasks.
|
||||
Iterable<(Node, int)> walk({String? parent, int depth = 0, bool archived = false}) sync* {
|
||||
const order = {'client': 0, 'project': 1, 'task': 2};
|
||||
final kids = [...?children[parent]]
|
||||
..sort((a, b) {
|
||||
final x = nodes[a]!, y = nodes[b]!;
|
||||
final k = order[x.kind]!.compareTo(order[y.kind]!);
|
||||
return k != 0 ? k : x.name.toLowerCase().compareTo(y.name.toLowerCase());
|
||||
});
|
||||
for (final i in kids) {
|
||||
final n = nodes[i]!;
|
||||
if (n.archived && !archived) continue;
|
||||
yield (n, depth);
|
||||
yield* walk(parent: i, depth: depth + 1, archived: archived);
|
||||
}
|
||||
}
|
||||
|
||||
Set<String> subtree(String nid) {
|
||||
final out = <String>{}, todo = [nid];
|
||||
while (todo.isNotEmpty) {
|
||||
final i = todo.removeLast();
|
||||
if (out.add(i)) todo.addAll(children[i] ?? const []);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/// One entry → (minutes, amount, currency); unbillable work is worth 0 (views._amount).
|
||||
(double, double, String) amount(WorkEntry e) {
|
||||
final cur = currency(e.node);
|
||||
if (!e.billable) return (e.minutes, 0, cur);
|
||||
return (e.minutes, e.minutes / 60 * rate(e.node, e.start.substring(0, 10)).$1, cur);
|
||||
}
|
||||
|
||||
/// "A sub-customer" / "A project" … for labels.
|
||||
static String kindLabel(Node n) => n.isSub ? 'Sub-customer' : const {'client': 'Customer', 'project': 'Project', 'task': 'Task'}[n.kind]!;
|
||||
}
|
||||
|
||||
// ---- entries -----------------------------------------------------------------------------
|
||||
|
||||
/// Entries overlapping [start, end) (entries_between); [keep] = node ids to keep.
|
||||
List<WorkEntry> entriesBetween(SyncStore store, DateTime start, DateTime end, {Set<String>? keep}) {
|
||||
final out = [
|
||||
for (final r in store.rows(
|
||||
tEntry,
|
||||
where: "json_extract(data, '\$.start') < ? AND json_extract(data, '\$.end') > ?",
|
||||
args: [fmtMin(end), fmtMin(start)],
|
||||
))
|
||||
WorkEntry(r),
|
||||
]..sort((a, b) => a.start.compareTo(b.start));
|
||||
return keep == null ? out : out.where((e) => keep.contains(e.node)).toList();
|
||||
}
|
||||
|
||||
/// The last few distinct nodes worked on (the form's chips), live ones only (db.recent).
|
||||
List<String> recent(SyncStore store, Tree t, [int n = 5]) {
|
||||
final last = <String, String>{};
|
||||
for (final r in store.rows(tEntry)) {
|
||||
final nid = r['node_id'] as String?, u = r['updated'] as String? ?? '';
|
||||
if (nid != null && u.compareTo(last[nid] ?? '') > 0) last[nid] = u;
|
||||
}
|
||||
final ids = last.keys.toList()..sort((a, b) => last[b]!.compareTo(last[a]!));
|
||||
return ids.where((i) => t.nodes.containsKey(i) && !t.archived(i)).take(n).toList();
|
||||
}
|
||||
|
||||
/// What the entry form submits (db.clean_entry): times as picked; an end at or before the start
|
||||
/// on the same day means it ends the next day (23:00 – 01:00).
|
||||
class EntryForm {
|
||||
EntryForm({
|
||||
this.id,
|
||||
this.node,
|
||||
required this.day,
|
||||
required this.startMin,
|
||||
required this.endMin,
|
||||
this.endDay,
|
||||
required this.billable,
|
||||
this.note = '',
|
||||
});
|
||||
String? id, node;
|
||||
DateTime day; // the start's day
|
||||
int startMin, endMin; // minutes after midnight
|
||||
DateTime? endDay; // only when it was set on purpose (else: same day, or the next one)
|
||||
bool billable;
|
||||
String note;
|
||||
|
||||
(DateTime, DateTime) span() {
|
||||
final a = day.add(Duration(minutes: startMin));
|
||||
var b = (endDay ?? day).add(Duration(minutes: endMin));
|
||||
if (!b.isAfter(a) && endDay == null) b = b.add(const Duration(days: 1));
|
||||
return (a, b);
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, dynamic> cleanEntry(EntryForm f, Tree t) {
|
||||
if (f.node == null || !t.nodes.containsKey(f.node)) throw Invalid('node_id', 'Choose what you worked on.');
|
||||
final (a, b) = f.span();
|
||||
if (!b.isAfter(a)) throw Invalid('end', 'The end must be after the start.');
|
||||
if (b.difference(a).inSeconds > 24 * 3600) throw Invalid('end', 'At most 24 hours in one entry.');
|
||||
final note = f.note.trim();
|
||||
return {
|
||||
'node_id': f.node,
|
||||
'start': fmtMin(a),
|
||||
'end': fmtMin(b),
|
||||
'billable': f.billable ? 1 : 0,
|
||||
'note': note.length > 2000 ? note.substring(0, 2000) : note,
|
||||
};
|
||||
}
|
||||
|
||||
/// Create or update an entry → its id.
|
||||
String saveEntry(SyncStore store, Tree t, EntryForm f) {
|
||||
final v = cleanEntry(f, t), now = fmtSec(DateTime.now());
|
||||
if (f.id == null) {
|
||||
final id = SyncStore.randomId();
|
||||
store.put(tEntry, id, {...v, 'created': now, 'updated': now});
|
||||
return id;
|
||||
}
|
||||
final old = store.row(tEntry, f.id!);
|
||||
if (old == null) throw Invalid('node_id', 'This entry was deleted meanwhile.');
|
||||
store.put(tEntry, f.id!, {...old, ...v, 'updated': now});
|
||||
return f.id!;
|
||||
}
|
||||
|
||||
void deleteEntry(SyncStore store, String id) => store.delete(tEntry, id);
|
||||
|
||||
// ---- nodes -------------------------------------------------------------------------------
|
||||
|
||||
class NodeForm {
|
||||
NodeForm({
|
||||
this.id,
|
||||
required this.kind,
|
||||
this.parent,
|
||||
this.name = '',
|
||||
this.colour,
|
||||
this.billable,
|
||||
this.currency = '',
|
||||
this.notes = '',
|
||||
this.archived = false,
|
||||
List<(String, String)>? rates,
|
||||
}) : rates = rates ?? [];
|
||||
String? id, parent, colour;
|
||||
String kind, name, currency, notes;
|
||||
int? billable; // null = inherit
|
||||
bool archived;
|
||||
List<(String, String)> rates; // (since '' = always, rate as typed)
|
||||
|
||||
factory NodeForm.of(Tree t, Node n) => NodeForm(
|
||||
id: n.id,
|
||||
kind: n.kind,
|
||||
parent: n.parent,
|
||||
name: n.name,
|
||||
colour: n.colour,
|
||||
billable: n.billable,
|
||||
currency: n.currency ?? '',
|
||||
notes: n.notes,
|
||||
archived: n.archived,
|
||||
rates: [for (final r in t.rates[n.id] ?? const <Rate>[]) (r.since == epoch ? '' : r.since, num0(r.rate))],
|
||||
);
|
||||
}
|
||||
|
||||
/// db._clean_node + _save_rates → (row, rates {since: rate}).
|
||||
(Map<String, dynamic>, Map<String, double>) cleanNode(NodeForm f, Tree t) {
|
||||
final name = f.name.trim();
|
||||
if (name.isEmpty) throw Invalid('name', 'Give it a name.');
|
||||
if (name.length > 80) throw Invalid('name', 'At most 80 characters.');
|
||||
final kind = f.id == null ? f.kind : t.nodes[f.id]!.kind;
|
||||
if (!kinds.contains(kind)) throw Invalid('kind', 'Unknown kind.');
|
||||
final parent = f.parent;
|
||||
if (parent != null && !t.nodes.containsKey(parent)) throw Invalid('parent_id', 'That parent no longer exists.');
|
||||
final pkind = parent == null ? null : t.nodes[parent]!.kind;
|
||||
if (!parentsOf[kind]!.contains(pkind)) {
|
||||
throw Invalid(
|
||||
'parent_id',
|
||||
const {
|
||||
'client': 'A sub-customer goes under a customer.',
|
||||
'project': 'A project goes under a customer.',
|
||||
'task': 'A task goes under a customer or a project.',
|
||||
}[kind]!,
|
||||
);
|
||||
}
|
||||
if (f.id != null && parent != null && t.subtree(f.id!).contains(parent)) throw Invalid('parent_id', "It can't go under itself.");
|
||||
var colour = f.colour;
|
||||
if (colour != null && !RegExp(r'^#[0-9a-fA-F]{6}$').hasMatch(colour)) throw Invalid('colour', 'A colour like #ffb33a.');
|
||||
if (kind == 'client' && parent == null && colour == null) {
|
||||
// customers always have one
|
||||
final used = {
|
||||
for (final n in t.nodes.values)
|
||||
if (n.parent == null && n.id != f.id) n.colour,
|
||||
};
|
||||
colour = palette.firstWhere((c) => !used.contains(c), orElse: () => palette[used.length % palette.length]);
|
||||
}
|
||||
final currency = f.currency.trim().toUpperCase();
|
||||
if (currency.isNotEmpty && !RegExp(r'^[A-Z]{3}$').hasMatch(currency)) throw Invalid('currency', 'A 3-letter code like EUR or RON.');
|
||||
final rates = <String, double>{};
|
||||
for (var i = 0; i < f.rates.length; i++) {
|
||||
final (sinceRaw, rateRaw) = f.rates[i];
|
||||
final raw = rateRaw.trim().replaceAll(',', '.');
|
||||
if (raw.isEmpty) continue;
|
||||
final rate = double.tryParse(raw);
|
||||
if (rate == null) throw Invalid('rates.$i.rate', 'The rate must be a number.');
|
||||
if (rate < 0 || rate > 100000) throw Invalid('rates.$i.rate', 'Between 0 and 100000.');
|
||||
final since = sinceRaw.trim().isEmpty ? epoch : sinceRaw.trim();
|
||||
if (since != epoch && (DateTime.tryParse(since) == null || !RegExp(r'^\d{4}-\d\d-\d\d$').hasMatch(since))) {
|
||||
throw Invalid('rates.$i.since', 'A date, or empty for always.');
|
||||
}
|
||||
if (rates.containsKey(since)) throw Invalid('rates.$i.since', 'Two rates from the same day.');
|
||||
rates[since] = rate;
|
||||
}
|
||||
final notes = f.notes.length > 4000 ? f.notes.substring(0, 4000) : f.notes;
|
||||
return (
|
||||
{
|
||||
'kind': kind,
|
||||
'parent_id': parent,
|
||||
'name': name,
|
||||
'colour': colour,
|
||||
'billable': f.billable,
|
||||
'currency': currency.isEmpty ? null : currency,
|
||||
'notes': notes,
|
||||
'archived': f.archived ? 1 : 0,
|
||||
},
|
||||
rates,
|
||||
);
|
||||
}
|
||||
|
||||
/// Create (no id) or update a node and replace its rate history → its id.
|
||||
String saveNode(SyncStore store, Tree t, NodeForm f) {
|
||||
final (v, rates) = cleanNode(f, t);
|
||||
final String id;
|
||||
if (f.id == null) {
|
||||
id = SyncStore.randomId();
|
||||
store.put(tNode, id, {...v, 'created': fmtSec(DateTime.now())});
|
||||
} else {
|
||||
id = f.id!;
|
||||
final old = store.row(tNode, id);
|
||||
if (old == null) throw Invalid('name', 'It was deleted meanwhile.');
|
||||
store.put(tNode, id, {...old, ...v});
|
||||
}
|
||||
// rates: ids are '<node>:<since>' (the Pi's key) — unchanged rows aren't touched
|
||||
final have = {for (final r in t.rates[id] ?? const <Rate>[]) r.since: r.rate};
|
||||
for (final since in have.keys) {
|
||||
if (!rates.containsKey(since)) store.delete(tRate, '$id:$since');
|
||||
}
|
||||
for (final MapEntry(key: since, value: rate) in rates.entries) {
|
||||
if (have[since] != rate) store.put(tRate, '$id:$since', {'node_id': id, 'since': since, 'rate': rate});
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
/// Delete a node and everything under it — only when no time is booked there (archive it
|
||||
/// instead). → false when refused.
|
||||
bool deleteNode(SyncStore store, Tree t, String nid) {
|
||||
final ids = t.subtree(nid);
|
||||
if (store.rows(tEntry).any((r) => ids.contains(r['node_id']))) return false;
|
||||
final order = ids.toList()..sort((a, b) => t.chain(b).length.compareTo(t.chain(a).length)); // leaves first
|
||||
for (final i in order) {
|
||||
for (final r in t.rates[i] ?? const <Rate>[]) {
|
||||
store.delete(tRate, '$i:${r.since}');
|
||||
}
|
||||
store.delete(tNode, i);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// node id → minutes ever booked directly on it.
|
||||
Map<String, double> bookedMinutes(SyncStore store) {
|
||||
final out = <String, double>{};
|
||||
for (final r in store.rows(tEntry)) {
|
||||
final e = WorkEntry(r);
|
||||
out[e.node] = (out[e.node] ?? 0) + e.minutes;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---- the week ----------------------------------------------------------------------------
|
||||
|
||||
class Block {
|
||||
Block(this.e, this.a, this.b, this.contBefore, this.contAfter);
|
||||
final WorkEntry e;
|
||||
final double a, b; // minutes after the day's midnight
|
||||
final bool contBefore, contAfter;
|
||||
int lane = 0, lanes = 1;
|
||||
}
|
||||
|
||||
class DayCol {
|
||||
DayCol(this.day, this.blocks, this.minutes, this.billableMinutes);
|
||||
final DateTime day;
|
||||
final List<Block> blocks;
|
||||
final double minutes, billableMinutes;
|
||||
}
|
||||
|
||||
class CustomerWeek {
|
||||
CustomerWeek(this.node, this.minutes, this.amounts, this.rate);
|
||||
final Node node;
|
||||
final double minutes;
|
||||
final Map<String, double> amounts;
|
||||
final String rate;
|
||||
}
|
||||
|
||||
class WeekView {
|
||||
WeekView(this.monday, this.days, this.minutes, this.billableMinutes, this.amounts, this.customers);
|
||||
final DateTime monday;
|
||||
final List<DayCol> days;
|
||||
final double minutes, billableMinutes;
|
||||
final Map<String, double> amounts;
|
||||
final List<CustomerWeek> customers;
|
||||
}
|
||||
|
||||
/// Overlap layout: lane + lanes per cluster of overlapping blocks (views._lanes).
|
||||
void lanes(List<Block> items) {
|
||||
final cluster = <Block>[];
|
||||
double? end;
|
||||
void flush() {
|
||||
final n = cluster.fold(0, (m, i) => i.lane > m ? i.lane : m) + 1;
|
||||
for (final i in cluster) {
|
||||
i.lanes = n;
|
||||
}
|
||||
}
|
||||
|
||||
items.sort((x, y) => x.a != y.a ? x.a.compareTo(y.a) : y.b.compareTo(x.b));
|
||||
for (final it in items) {
|
||||
if (cluster.isNotEmpty && it.a >= end!) {
|
||||
flush();
|
||||
cluster.clear();
|
||||
end = null;
|
||||
}
|
||||
final used = {
|
||||
for (final c in cluster)
|
||||
if (c.b > it.a) c.lane,
|
||||
};
|
||||
var l = 0;
|
||||
while (used.contains(l)) {
|
||||
l++;
|
||||
}
|
||||
it.lane = l;
|
||||
cluster.add(it);
|
||||
end = end == null ? it.b : (it.b > end ? it.b : end);
|
||||
}
|
||||
if (cluster.isNotEmpty) flush();
|
||||
}
|
||||
|
||||
WeekView week(SyncStore store, Tree t, int offset, [DateTime? now]) {
|
||||
final ws = weekStart(offset, now), we = DateTime.utc(ws.year, ws.month, ws.day + 7);
|
||||
final entries = entriesBetween(store, ws, we);
|
||||
final days = <DayCol>[];
|
||||
var tot = 0.0, totB = 0.0;
|
||||
for (var d = 0; d < 7; d++) {
|
||||
final d0 = DateTime.utc(ws.year, ws.month, ws.day + d), d1 = DateTime.utc(ws.year, ws.month, ws.day + d + 1);
|
||||
final blocks = <Block>[];
|
||||
var m = 0.0, bm = 0.0;
|
||||
for (final e in entries) {
|
||||
final a = e.s.isAfter(d0) ? e.s : d0, b = e.e.isBefore(d1) ? e.e : d1;
|
||||
if (!b.isAfter(a)) continue;
|
||||
final am = a.difference(d0).inSeconds / 60, bmin = b.difference(d0).inSeconds / 60;
|
||||
m += bmin - am;
|
||||
if (e.billable) bm += bmin - am;
|
||||
blocks.add(Block(e, am, bmin, e.s.isBefore(d0), e.e.isAfter(d1)));
|
||||
}
|
||||
lanes(blocks);
|
||||
days.add(DayCol(d0, blocks, m, bm));
|
||||
tot += m;
|
||||
totB += bm;
|
||||
}
|
||||
final amounts = <String, double>{};
|
||||
final per = <String, (double, Map<String, double>)>{};
|
||||
for (final e in entries) {
|
||||
// money by the entry's own date + rate
|
||||
final (minutes, amt, cur) = t.amount(e);
|
||||
if (e.billable) amounts[cur] = (amounts[cur] ?? 0) + amt;
|
||||
final top = t.clientOf(e.node);
|
||||
if (top != null) {
|
||||
final p = per[top.id] ?? (0.0, <String, double>{});
|
||||
if (e.billable) p.$2[cur] = (p.$2[cur] ?? 0) + amt;
|
||||
per[top.id] = (p.$1 + minutes, p.$2);
|
||||
}
|
||||
}
|
||||
final todayIso = fmtDay(now ?? DateTime.now());
|
||||
final customers = [
|
||||
for (final (n, _) in t.walk())
|
||||
if (n.parent == null)
|
||||
CustomerWeek(n, per[n.id]?.$1 ?? 0, per[n.id]?.$2 ?? {}, '${num0(t.rate(n.id, todayIso).$1)} ${t.currency(n.id)}/h'),
|
||||
]..sort((a, b) => b.minutes.compareTo(a.minutes));
|
||||
return WeekView(ws, days, tot, totB, amounts, customers);
|
||||
}
|
||||
|
||||
// ---- the report --------------------------------------------------------------------------
|
||||
|
||||
const presets = [
|
||||
('week', 'This week'),
|
||||
('lastweek', 'Last week'),
|
||||
('month', 'This month'),
|
||||
('lastmonth', 'Last month'),
|
||||
('year', 'This year'),
|
||||
('lastyear', 'Last year'),
|
||||
];
|
||||
|
||||
/// (from, to) inclusive days of a preset (views.preset_range), or null.
|
||||
(DateTime, DateTime)? presetRange(String name, [DateTime? now]) {
|
||||
final t = dayOf(now ?? DateTime.now());
|
||||
final mon = DateTime.utc(t.year, t.month, t.day - (t.weekday - 1));
|
||||
switch (name) {
|
||||
case 'week':
|
||||
return (mon, DateTime.utc(mon.year, mon.month, mon.day + 6));
|
||||
case 'lastweek':
|
||||
return (DateTime.utc(mon.year, mon.month, mon.day - 7), DateTime.utc(mon.year, mon.month, mon.day - 1));
|
||||
case 'month':
|
||||
return (DateTime.utc(t.year, t.month, 1), DateTime.utc(t.year, t.month + 1, 0));
|
||||
case 'lastmonth':
|
||||
return (DateTime.utc(t.year, t.month - 1, 1), DateTime.utc(t.year, t.month, 0));
|
||||
case 'year':
|
||||
return (DateTime.utc(t.year, 1, 1), DateTime.utc(t.year, 12, 31));
|
||||
case 'lastyear':
|
||||
return (DateTime.utc(t.year - 1, 1, 1), DateTime.utc(t.year - 1, 12, 31));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
class Agg {
|
||||
double m = 0, bm = 0;
|
||||
final amounts = <String, double>{};
|
||||
void add(double minutes, bool billable, double amt, String cur) {
|
||||
m += minutes;
|
||||
if (billable) {
|
||||
bm += minutes;
|
||||
amounts[cur] = (amounts[cur] ?? 0) + amt;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class ReportRow {
|
||||
ReportRow(this.node, this.depth, this.agg);
|
||||
final Node node;
|
||||
final int depth;
|
||||
final Agg agg;
|
||||
}
|
||||
|
||||
class ReportItem {
|
||||
ReportItem(this.e, this.rate, this.amount, this.currency);
|
||||
final WorkEntry e;
|
||||
final double rate, amount;
|
||||
final String currency;
|
||||
}
|
||||
|
||||
class Report {
|
||||
Report(this.rows, this.items, this.total);
|
||||
final List<ReportRow> rows;
|
||||
final List<ReportItem> items;
|
||||
final Agg total;
|
||||
}
|
||||
|
||||
/// Hours + money in [from, to] (inclusive days) as a tree; [client] limits it to one node's
|
||||
/// subtree. Entries count on the day they start (views.report).
|
||||
Report report(SyncStore store, Tree t, DateTime from, DateTime to, {String? client}) {
|
||||
final keep = client != null && t.nodes.containsKey(client) ? t.subtree(client) : null;
|
||||
final start = dayOf(from), end = DateTime.utc(to.year, to.month, to.day + 1);
|
||||
final rows = entriesBetween(
|
||||
store,
|
||||
start.subtract(const Duration(days: 1)),
|
||||
end,
|
||||
keep: keep,
|
||||
).where((e) => !e.s.isBefore(start) && e.s.isBefore(end)).toList();
|
||||
final agg = <String, Agg>{}, total = Agg(), items = <ReportItem>[];
|
||||
for (final e in rows) {
|
||||
final (minutes, amt, cur) = t.amount(e);
|
||||
for (final n in t.chain(e.node)) {
|
||||
agg.putIfAbsent(n.id, Agg.new).add(minutes, e.billable, amt, cur);
|
||||
}
|
||||
total.add(minutes, e.billable, amt, cur);
|
||||
items.add(ReportItem(e, e.billable ? t.rate(e.node, e.start.substring(0, 10)).$1 : 0, amt, cur));
|
||||
}
|
||||
return Report(
|
||||
[
|
||||
for (final (n, d) in t.walk(archived: true))
|
||||
if (agg[n.id] != null) ReportRow(n, d, agg[n.id]!),
|
||||
],
|
||||
items,
|
||||
total,
|
||||
);
|
||||
}
|
||||
|
||||
/// The report's entries as CSV (the Pi's /work/report.csv).
|
||||
String reportCsv(Report r, Tree t) {
|
||||
String q(String s) => RegExp(r'[",\n\r]').hasMatch(s) ? '"${s.replaceAll('"', '""')}"' : s;
|
||||
final b = StringBuffer('date,start,end,hours,customer / project / task,billable,rate,amount,currency,note\r\n');
|
||||
for (final i in r.items) {
|
||||
final e = i.e;
|
||||
b.write(
|
||||
[
|
||||
e.start.substring(0, 10),
|
||||
e.start.substring(11),
|
||||
e.end.substring(11),
|
||||
(e.minutes / 60).toStringAsFixed(2),
|
||||
q(t.path(e.node)),
|
||||
e.billable ? 'yes' : 'no',
|
||||
e.billable ? num0(i.rate) : '',
|
||||
e.billable ? i.amount.toStringAsFixed(2) : '',
|
||||
i.currency,
|
||||
q(e.note),
|
||||
].join(','),
|
||||
);
|
||||
b.write('\r\n');
|
||||
}
|
||||
return b.toString();
|
||||
}
|
||||
|
||||
// ---- what the Pi adds to the week (plugins/workload/phone.py) -----------------------------
|
||||
// "workload.cal" — the calendar's timed events (drawn faintly behind; tap = book them);
|
||||
// "workload.act" — Activity's blocks for the lane beside the bookings (tap = book with the customer guessed).
|
||||
const tCal = 'workload.cal', tAct = 'workload.act';
|
||||
|
||||
class Ghost {
|
||||
Ghost(this.title, this.calendar, this.colour, this.a, this.b, this.s, this.e);
|
||||
final String title, calendar, colour;
|
||||
final double a, b; // minutes after the day's midnight
|
||||
final DateTime s, e; // the part inside this day
|
||||
}
|
||||
|
||||
class ActBlock {
|
||||
ActBlock(this.r) : a = (r['a'] as num).toDouble(), b = (r['b'] as num).toDouble();
|
||||
final Map<String, dynamic> r;
|
||||
final double a, b;
|
||||
String get day => r['day'] as String;
|
||||
String get start => r['start'] as String;
|
||||
String get end => r['end'] as String;
|
||||
String get colour => r['colour'] as String? ?? '#8b929e';
|
||||
String get path => r['path'] as String? ?? '';
|
||||
String get name => r['name'] as String? ?? '';
|
||||
String get what => r['what'] as String? ?? '';
|
||||
String get dur => r['dur'] as String? ?? '';
|
||||
List<String> get names => ((jsonDecodeSafe(r['names'] as String?) as List?) ?? const []).cast<String>();
|
||||
}
|
||||
|
||||
Object? jsonDecodeSafe(String? s) {
|
||||
if (s == null || s.isEmpty) return null;
|
||||
try {
|
||||
return jsonDecode(s);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// The calendar events inside each day of the week from [monday] (all-day ones aren't sent).
|
||||
List<List<Ghost>> ghosts(SyncStore store, DateTime monday) {
|
||||
final end = DateTime.utc(monday.year, monday.month, monday.day + 7);
|
||||
final rows = store.rows(
|
||||
tCal,
|
||||
where: "json_extract(data, '\$.start') < ? AND json_extract(data, '\$.end') > ?",
|
||||
args: [fmtMin(end), fmtMin(monday)],
|
||||
);
|
||||
return [
|
||||
for (var d = 0; d < 7; d++)
|
||||
() {
|
||||
final d0 = DateTime.utc(monday.year, monday.month, monday.day + d),
|
||||
d1 = DateTime.utc(monday.year, monday.month, monday.day + d + 1);
|
||||
final out = <Ghost>[];
|
||||
for (final r in rows) {
|
||||
final s = parseMin(r['start'] as String), e = parseMin(r['end'] as String);
|
||||
final a = s.isAfter(d0) ? s : d0, b = e.isBefore(d1) ? e : d1;
|
||||
if (!b.isAfter(a)) continue;
|
||||
out.add(
|
||||
Ghost(
|
||||
r['title'] as String? ?? '',
|
||||
r['calendar'] as String? ?? '',
|
||||
r['colour'] as String? ?? '#8b929e',
|
||||
a.difference(d0).inSeconds / 60,
|
||||
b.difference(d0).inSeconds / 60,
|
||||
a,
|
||||
b,
|
||||
),
|
||||
);
|
||||
}
|
||||
out.sort((x, y) => x.a.compareTo(y.a));
|
||||
return out;
|
||||
}(),
|
||||
];
|
||||
}
|
||||
|
||||
/// Activity's blocks per day of the week from [monday].
|
||||
List<List<ActBlock>> actBlocks(SyncStore store, DateTime monday) {
|
||||
final days = [for (var d = 0; d < 7; d++) fmtDay(DateTime.utc(monday.year, monday.month, monday.day + d))];
|
||||
final rows = store.rows(tAct, where: "json_extract(data, '\$.day') BETWEEN ? AND ?", args: [days.first, days.last]);
|
||||
return [for (final d in days) (rows.where((r) => r['day'] == d).map(ActBlock.new).toList()..sort((x, y) => x.a.compareTo(y.a)))];
|
||||
}
|
||||
|
||||
/// The customer / project an Activity block is probably for: the first of its category names
|
||||
/// (nearest first: "Rocket", "Acme", "Customer", "Work") that's a live node's name (views._guess).
|
||||
String? guessNode(Tree t, List<String> names) {
|
||||
final byName = <String, String>{};
|
||||
for (final (n, _) in t.walk()) {
|
||||
byName.putIfAbsent(n.name.trim().toLowerCase(), () => n.id);
|
||||
}
|
||||
for (final x in names) {
|
||||
final id = byName[x.trim().toLowerCase()];
|
||||
if (id != null) return id;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
1054
app/lib/work/work_page.dart
Normal file
1054
app/lib/work/work_page.dart
Normal file
File diff suppressed because it is too large
Load diff
Loading…
Add table
Add a link
Reference in a new issue