- 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>
807 lines
29 KiB
Dart
807 lines
29 KiB
Dart
// 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 '../app/prefs.dart';
|
||
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';
|
||
|
||
/// The dashboard's Settings ▸ Work (synced: prefs.dart); its defaults until they've come.
|
||
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;
|
||
|
||
static WorkSettings of(SyncStore store) {
|
||
final p = Prefs(store);
|
||
return WorkSettings(currency: p.get<String>('workload.currency', 'EUR'), defaultRate: p.number('workload.default_rate', 0).toDouble(),
|
||
dayStart: p.number('workload.day_start', 7).round(), dayEnd: p.number('workload.day_end', 19).round(),
|
||
defaultMinutes: p.number('workload.default_minutes', 60).round(), weekTarget: p.number('workload.week_target', 40).toDouble());
|
||
}
|
||
}
|
||
|
||
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;
|
||
}
|