File size: 25,985 Bytes
3f893e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
"""Site-isolated persistence for the EveryDollar offline clone."""

from __future__ import annotations

import hashlib
import secrets
import time
from datetime import date
from typing import Any

from backend.site_backend_integration import open_site_services


SITE_ID = "everydollar"
backend, auth = open_site_services()

GROUPS = [
    ("Income", 0),
    ("Giving", 1),
    ("Savings", 2),
    ("Housing", 3),
    ("Transportation", 4),
    ("Food", 5),
    ("Lifestyle", 6),
    ("Insurance & Tax", 7),
    ("Debt", 8),
]

SCHEMA = """
CREATE TABLE IF NOT EXISTS everydollar_profiles (
  subject_id TEXT PRIMARY KEY,
  display_name TEXT NOT NULL,
  email TEXT NOT NULL,
  created_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS everydollar_budgets (
  owner_id TEXT NOT NULL,
  month TEXT NOT NULL,
  created_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL,
  PRIMARY KEY(owner_id, month)
);
CREATE TABLE IF NOT EXISTS everydollar_groups (
  group_id TEXT PRIMARY KEY,
  owner_id TEXT NOT NULL,
  month TEXT NOT NULL,
  name TEXT NOT NULL,
  position INTEGER NOT NULL,
  UNIQUE(owner_id, month, name)
);
CREATE TABLE IF NOT EXISTS everydollar_items (
  item_id TEXT PRIMARY KEY,
  owner_id TEXT NOT NULL,
  month TEXT NOT NULL,
  group_id TEXT NOT NULL,
  label TEXT NOT NULL,
  planned_cents INTEGER NOT NULL CHECK(planned_cents >= 0),
  position INTEGER NOT NULL,
  favorite INTEGER NOT NULL DEFAULT 0,
  due_day INTEGER,
  notes TEXT NOT NULL DEFAULT '',
  updated_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS everydollar_transactions (
  transaction_id TEXT PRIMARY KEY,
  owner_id TEXT NOT NULL,
  month TEXT NOT NULL,
  kind TEXT NOT NULL CHECK(kind IN ('expense','income')),
  amount_cents INTEGER NOT NULL CHECK(amount_cents > 0),
  merchant TEXT NOT NULL,
  occurred_on TEXT NOT NULL,
  item_id TEXT,
  account_name TEXT NOT NULL DEFAULT 'Cash',
  created_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS everydollar_goals (
  goal_id TEXT PRIMARY KEY,
  owner_id TEXT NOT NULL,
  label TEXT NOT NULL,
  target_cents INTEGER NOT NULL CHECK(target_cents > 0),
  saved_cents INTEGER NOT NULL CHECK(saved_cents >= 0),
  target_month TEXT NOT NULL,
  updated_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS everydollar_preferences (
  owner_id TEXT PRIMARY KEY,
  reminders INTEGER NOT NULL DEFAULT 1,
  weekly_summary INTEGER NOT NULL DEFAULT 1,
  safe_to_spend INTEGER NOT NULL DEFAULT 0,
  whole_numbers INTEGER NOT NULL DEFAULT 0,
  updated_at INTEGER NOT NULL
);
"""


def initialize() -> None:
    with backend.lifecycle.connection(transaction=True) as connection:
        connection.executescript(SCHEMA)


initialize()


def current_month() -> str:
    return date.today().strftime("%Y-%m")


def new_actor() -> str:
    return "budgeter_" + secrets.token_urlsafe(18)


def ensure_auth_session(token: str | None) -> tuple[str, dict[str, Any]]:
    return auth.ensure_session(token)


def resolve_account(token: str | None) -> dict[str, Any] | None:
    return auth.resolve_session(token)


def _owner(actor_id: str, account: dict[str, Any] | None) -> str:
    return str(account["subject_id"]) if account else actor_id


def register(email: str, display_name: str, password: str) -> dict[str, Any]:
    details = auth.validate_registration_details(
        email=email, display_name=display_name, password=password
    )
    if auth.account_exists(details["email"]):
        raise ValueError("An account already exists for this email.")
    subject = "budgeter_" + hashlib.sha256(details["email"].encode()).hexdigest()[:20]
    auth.seed_account(
        subject_id=subject,
        email=details["email"],
        display_name=details["display_name"],
        password=details["password"],
        email_verified=True,
    )
    ensure_profile(subject, details["display_name"], details["email"])
    return {"subject_id": subject, "email": details["email"], "display_name": details["display_name"]}


def sign_in(session_token: str, email: str, password: str) -> dict[str, Any]:
    result = auth.sign_in(session_token, email=email, password=password)
    account = result["account"]
    ensure_profile(account["subject_id"], account["display_name"], account["email_normalized"])
    return result


def sign_out(session_token: str | None) -> None:
    auth.sign_out(session_token)


def ensure_profile(subject_id: str, display_name: str, email: str) -> None:
    now = int(time.time())
    with backend.lifecycle.connection(transaction=True) as connection:
        connection.execute(
            "INSERT OR IGNORE INTO everydollar_profiles(subject_id,display_name,email,created_at) VALUES(?,?,?,?)",
            (subject_id, display_name, email, now),
        )


def transfer_budget(actor_id: str, subject_id: str) -> None:
    """Move anonymous local work into the newly authenticated site-local account."""
    with backend.lifecycle.connection(transaction=True) as connection:
        actor_months = connection.execute(
            "SELECT month FROM everydollar_budgets WHERE owner_id=?", (actor_id,)
        ).fetchall()
        for row in actor_months:
            month = row["month"]
            existing = connection.execute(
                "SELECT 1 FROM everydollar_budgets WHERE owner_id=? AND month=?",
                (subject_id, month),
            ).fetchone()
            if existing:
                continue
            for table in ("everydollar_budgets", "everydollar_groups", "everydollar_items", "everydollar_transactions"):
                connection.execute(
                    f"UPDATE {table} SET owner_id=? WHERE owner_id=? AND month=?",
                    (subject_id, actor_id, month),
                )

        # Goals have globally unique IDs; move guest work to the authenticated owner.
        connection.execute("UPDATE everydollar_goals SET owner_id=? WHERE owner_id=?", (subject_id, actor_id))
        # Existing account preferences win. New accounts inherit their guest choices.
        existing_preferences = connection.execute("SELECT 1 FROM everydollar_preferences WHERE owner_id=?", (subject_id,)).fetchone()
        if not existing_preferences:
            connection.execute("UPDATE everydollar_preferences SET owner_id=? WHERE owner_id=?", (subject_id, actor_id))
        else:
            connection.execute("DELETE FROM everydollar_preferences WHERE owner_id=?", (actor_id,))


def ensure_budget(owner_id: str, month: str) -> None:
    if not month or len(month) != 7 or month[4] != "-":
        raise ValueError("Use a month in YYYY-MM format.")
    now = int(time.time())
    with backend.lifecycle.connection(transaction=True) as connection:
        connection.execute(
            "INSERT OR IGNORE INTO everydollar_budgets(owner_id,month,created_at,updated_at) VALUES(?,?,?,?)",
            (owner_id, month, now, now),
        )
        for name, position in GROUPS:
            group_id = hashlib.sha256(f"{owner_id}|{month}|{name}".encode()).hexdigest()[:24]
            connection.execute(
                "INSERT OR IGNORE INTO everydollar_groups(group_id,owner_id,month,name,position) VALUES(?,?,?,?,?)",
                (group_id, owner_id, month, name, position),
            )
        connection.execute(
            "INSERT OR IGNORE INTO everydollar_preferences(owner_id,updated_at) VALUES(?,?)",
            (owner_id, now),
        )


def _group_id(connection: Any, owner_id: str, month: str, name: str) -> str:
    row = connection.execute(
        "SELECT group_id FROM everydollar_groups WHERE owner_id=? AND month=? AND name=?",
        (owner_id, month, name),
    ).fetchone()
    if row:
        return str(row["group_id"])
    position = connection.execute(
        "SELECT COALESCE(MAX(position),-1)+1 value FROM everydollar_groups WHERE owner_id=? AND month=?",
        (owner_id, month),
    ).fetchone()["value"]
    group_id = secrets.token_hex(12)
    connection.execute(
        "INSERT INTO everydollar_groups(group_id,owner_id,month,name,position) VALUES(?,?,?,?,?)",
        (group_id, owner_id, month, name, int(position)),
    )
    return group_id


def snapshot(actor_id: str, account: dict[str, Any] | None, month: str | None = None) -> dict[str, Any]:
    month = month or current_month()
    owner_id = _owner(actor_id, account)
    ensure_budget(owner_id, month)
    with backend.lifecycle.connection() as connection:
        group_rows = connection.execute(
            "SELECT * FROM everydollar_groups WHERE owner_id=? AND month=? ORDER BY position,name",
            (owner_id, month),
        ).fetchall()
        item_rows = connection.execute(
            """SELECT i.*, COALESCE(SUM(CASE WHEN t.kind='expense' THEN t.amount_cents ELSE 0 END),0) expense_cents,
                      COALESCE(SUM(CASE WHEN t.kind='income' THEN t.amount_cents ELSE 0 END),0) income_cents
               FROM everydollar_items i LEFT JOIN everydollar_transactions t ON t.item_id=i.item_id
               WHERE i.owner_id=? AND i.month=? GROUP BY i.item_id ORDER BY i.position,i.label""",
            (owner_id, month),
        ).fetchall()
        transaction_rows = connection.execute(
            "SELECT * FROM everydollar_transactions WHERE owner_id=? AND month=? ORDER BY occurred_on DESC,created_at DESC",
            (owner_id, month),
        ).fetchall()
        goal_rows = connection.execute(
            "SELECT * FROM everydollar_goals WHERE owner_id=? ORDER BY updated_at DESC", (owner_id,)
        ).fetchall()
        pref = connection.execute(
            "SELECT * FROM everydollar_preferences WHERE owner_id=?", (owner_id,)
        ).fetchone()

    by_group: dict[str, list[dict[str, Any]]] = {}
    income_planned = expenses_planned = income_received = spent = 0
    for row in item_rows:
        is_income = next((g["name"] == "Income" for g in group_rows if g["group_id"] == row["group_id"]), False)
        actual = int(row["income_cents"] if is_income else row["expense_cents"])
        planned = int(row["planned_cents"])
        if is_income:
            income_planned += planned
            income_received += actual
        else:
            expenses_planned += planned
            spent += actual
        by_group.setdefault(str(row["group_id"]), []).append(
            {
                "id": row["item_id"], "label": row["label"], "planned": planned / 100,
                "actual": actual / 100, "remaining": (planned - actual) / 100,
                "favorite": bool(row["favorite"]), "due_day": row["due_day"], "notes": row["notes"],
            }
        )
    groups = []
    palette = ["#38b86a", "#c22d8d", "#f5a623", "#23a6d5", "#ef7952", "#6941c6", "#80bd45", "#e84c88", "#667085"]
    for index, group in enumerate(group_rows):
        items = by_group.get(str(group["group_id"]), [])
        groups.append({
            "id": group["group_id"], "name": group["name"], "position": group["position"],
            "items": items, "planned": sum(item["planned"] for item in items),
            "actual": sum(item["actual"] for item in items), "remaining": sum(item["remaining"] for item in items),
            "color": palette[index % len(palette)],
        })
    return {
        "site_id": SITE_ID,
        "month": month,
        "account": account,
        "groups": groups,
        "transactions": [
            {"id": row["transaction_id"], "kind": row["kind"], "amount": row["amount_cents"] / 100,
             "merchant": row["merchant"], "date": row["occurred_on"], "item_id": row["item_id"],
             "account_name": row["account_name"]}
            for row in transaction_rows
        ],
        "goals": [
            {"id": row["goal_id"], "label": row["label"], "target": row["target_cents"] / 100,
             "saved": row["saved_cents"] / 100, "target_month": row["target_month"]}
            for row in goal_rows
        ],
        "preferences": {"reminders": bool(pref["reminders"]), "weekly_summary": bool(pref["weekly_summary"]),
                        "safe_to_spend": bool(pref["safe_to_spend"]), "whole_numbers": bool(pref["whole_numbers"])},
        "summary": {"income": income_planned / 100, "received": income_received / 100,
                    "planned": expenses_planned / 100, "spent": spent / 100,
                    "left_to_budget": (income_planned - expenses_planned) / 100,
                    "remaining": (expenses_planned - spent) / 100},
    }


def add_item(actor_id: str, account: dict[str, Any] | None, payload: dict[str, Any]) -> dict[str, Any]:
    month = str(payload.get("month") or current_month())
    owner_id = _owner(actor_id, account)
    ensure_budget(owner_id, month)
    label = str(payload.get("label", "")).strip()
    group_name = str(payload.get("group", "")).strip() or "Lifestyle"
    if not label:
        raise ValueError("Enter a budget item name.")
    planned = round(float(payload.get("planned", 0)) * 100)
    if planned < 0 or planned > 100_000_000_00:
        raise ValueError("Enter a valid planned amount.")
    now = int(time.time())
    with backend.lifecycle.connection(transaction=True) as connection:
        group_id = _group_id(connection, owner_id, month, group_name)
        position = connection.execute(
            "SELECT COALESCE(MAX(position),-1)+1 value FROM everydollar_items WHERE owner_id=? AND month=? AND group_id=?",
            (owner_id, month, group_id),
        ).fetchone()["value"]
        item_id = secrets.token_hex(12)
        connection.execute(
            "INSERT INTO everydollar_items(item_id,owner_id,month,group_id,label,planned_cents,position,updated_at) VALUES(?,?,?,?,?,?,?,?)",
            (item_id, owner_id, month, group_id, label, planned, int(position), now),
        )
    return snapshot(actor_id, account, month)


def update_item(actor_id: str, account: dict[str, Any] | None, item_id: str, payload: dict[str, Any]) -> dict[str, Any]:
    owner_id = _owner(actor_id, account)
    with backend.lifecycle.connection(transaction=True) as connection:
        row = connection.execute(
            "SELECT * FROM everydollar_items WHERE item_id=? AND owner_id=?", (item_id, owner_id)
        ).fetchone()
        if not row:
            raise PermissionError("Budget item was not found for this budget.")
        label = str(payload.get("label", row["label"])).strip()
        if not label:
            raise ValueError("Enter a budget item name.")
        planned = round(float(payload.get("planned", row["planned_cents"] / 100)) * 100)
        if planned < 0:
            raise ValueError("Planned amount cannot be negative.")
        connection.execute(
            "UPDATE everydollar_items SET label=?,planned_cents=?,favorite=?,notes=?,updated_at=? WHERE item_id=? AND owner_id=?",
            (label, planned, int(bool(payload.get("favorite", row["favorite"]))), str(payload.get("notes", row["notes"])), int(time.time()), item_id, owner_id),
        )
        month = row["month"]
    return snapshot(actor_id, account, month)


def delete_item(actor_id: str, account: dict[str, Any] | None, item_id: str) -> dict[str, Any]:
    owner_id = _owner(actor_id, account)
    with backend.lifecycle.connection(transaction=True) as connection:
        row = connection.execute(
            "SELECT month FROM everydollar_items WHERE item_id=? AND owner_id=?", (item_id, owner_id)
        ).fetchone()
        if not row:
            raise PermissionError("Budget item was not found for this budget.")
        connection.execute("UPDATE everydollar_transactions SET item_id=NULL WHERE item_id=? AND owner_id=?", (item_id, owner_id))
        connection.execute("DELETE FROM everydollar_items WHERE item_id=? AND owner_id=?", (item_id, owner_id))
        month = row["month"]
    return snapshot(actor_id, account, month)


def move_item(actor_id: str, account: dict[str, Any] | None, item_id: str, direction: str) -> dict[str, Any]:
    owner_id = _owner(actor_id, account)
    if direction not in {"up", "down"}:
        raise ValueError("Choose up or down.")
    with backend.lifecycle.connection(transaction=True) as connection:
        row = connection.execute(
            "SELECT * FROM everydollar_items WHERE item_id=? AND owner_id=?", (item_id, owner_id)
        ).fetchone()
        if not row:
            raise PermissionError("Budget item was not found for this budget.")
        operator = "<" if direction == "up" else ">"
        order = "DESC" if direction == "up" else "ASC"
        neighbor = connection.execute(
            f"SELECT * FROM everydollar_items WHERE owner_id=? AND month=? AND group_id=? AND position {operator} ? ORDER BY position {order} LIMIT 1",
            (owner_id, row["month"], row["group_id"], row["position"]),
        ).fetchone()
        if neighbor:
            connection.execute("UPDATE everydollar_items SET position=? WHERE item_id=?", (neighbor["position"], item_id))
            connection.execute("UPDATE everydollar_items SET position=? WHERE item_id=?", (row["position"], neighbor["item_id"]))
        month = row["month"]
    return snapshot(actor_id, account, month)


def _transaction_date(value: str, month: str) -> str:
    try:
        parsed = date.fromisoformat(value)
    except (ValueError, TypeError):
        raise ValueError("Enter a valid transaction date.") from None
    if parsed.isoformat() != value or value[:7] != month:
        raise ValueError("Transaction date must be in the selected budget month.")
    return value


def add_transaction(actor_id: str, account: dict[str, Any] | None, payload: dict[str, Any]) -> dict[str, Any]:
    owner_id = _owner(actor_id, account)
    month = str(payload.get("month") or current_month())
    ensure_budget(owner_id, month)
    kind = str(payload.get("kind", "expense"))
    if kind not in {"expense", "income"}:
        raise ValueError("Choose Expense or Income.")
    amount = round(float(payload.get("amount", 0)) * 100)
    merchant = str(payload.get("merchant", "")).strip()
    item_id = str(payload.get("item_id") or "") or None
    occurred_on = _transaction_date(str(payload.get("date") or month + "-01"), month)
    if amount <= 0:
        raise ValueError("Enter an amount greater than zero.")
    if not merchant:
        raise ValueError("Enter a merchant or income source.")
    with backend.lifecycle.connection(transaction=True) as connection:
        if item_id and not connection.execute(
            "SELECT 1 FROM everydollar_items WHERE item_id=? AND owner_id=? AND month=?", (item_id, owner_id, month)
        ).fetchone():
            raise PermissionError("Choose a budget item from this budget.")
        connection.execute(
            "INSERT INTO everydollar_transactions(transaction_id,owner_id,month,kind,amount_cents,merchant,occurred_on,item_id,account_name,created_at) VALUES(?,?,?,?,?,?,?,?,?,?)",
            (secrets.token_hex(12), owner_id, month, kind, amount, merchant, occurred_on, item_id, str(payload.get("account_name") or "Cash"), int(time.time())),
        )
    return snapshot(actor_id, account, month)


def update_transaction(actor_id: str, account: dict[str, Any] | None, transaction_id: str, payload: dict[str, Any]) -> dict[str, Any]:
    owner_id = _owner(actor_id, account)
    with backend.lifecycle.connection(transaction=True) as connection:
        row = connection.execute(
            "SELECT * FROM everydollar_transactions WHERE transaction_id=? AND owner_id=?", (transaction_id, owner_id)
        ).fetchone()
        if not row:
            raise PermissionError("Transaction was not found.")
        kind = str(payload.get("kind", row["kind"]))
        amount = round(float(payload.get("amount", row["amount_cents"] / 100)) * 100)
        merchant = str(payload.get("merchant", row["merchant"])).strip()
        item_id = str(payload.get("item_id", row["item_id"]) or "") or None
        if kind not in {"expense", "income"} or amount <= 0 or not merchant:
            raise ValueError("Enter a valid transaction type, amount and merchant.")
        occurred_on = _transaction_date(str(payload.get("date") or row["occurred_on"]), row["month"])
        if item_id and not connection.execute(
            "SELECT 1 FROM everydollar_items WHERE item_id=? AND owner_id=? AND month=?", (item_id, owner_id, row["month"])
        ).fetchone():
            raise PermissionError("Choose a budget item from this budget.")
        connection.execute(
            "UPDATE everydollar_transactions SET kind=?,amount_cents=?,merchant=?,occurred_on=?,item_id=?,account_name=? WHERE transaction_id=? AND owner_id=?",
            (kind, amount, merchant, occurred_on, item_id,
             str(payload.get("account_name") or row["account_name"]), transaction_id, owner_id),
        )
        month = row["month"]
    return snapshot(actor_id, account, month)


def delete_transaction(actor_id: str, account: dict[str, Any] | None, transaction_id: str) -> dict[str, Any]:
    owner_id = _owner(actor_id, account)
    with backend.lifecycle.connection(transaction=True) as connection:
        row = connection.execute(
            "SELECT month FROM everydollar_transactions WHERE transaction_id=? AND owner_id=?", (transaction_id, owner_id)
        ).fetchone()
        if not row:
            raise PermissionError("Transaction was not found.")
        connection.execute("DELETE FROM everydollar_transactions WHERE transaction_id=? AND owner_id=?", (transaction_id, owner_id))
        month = row["month"]
    return snapshot(actor_id, account, month)


def copy_month(actor_id: str, account: dict[str, Any] | None, source: str, target: str) -> dict[str, Any]:
    owner_id = _owner(actor_id, account)
    ensure_budget(owner_id, source)
    ensure_budget(owner_id, target)
    with backend.lifecycle.connection(transaction=True) as connection:
        existing = connection.execute(
            "SELECT COUNT(*) count FROM everydollar_items WHERE owner_id=? AND month=?", (owner_id, target)
        ).fetchone()["count"]
        if existing:
            raise ValueError("The destination month already has planned items.")
        source_items = connection.execute(
            """SELECT i.*,g.name group_name FROM everydollar_items i JOIN everydollar_groups g ON g.group_id=i.group_id
               WHERE i.owner_id=? AND i.month=? ORDER BY g.position,i.position""", (owner_id, source)
        ).fetchall()
        for row in source_items:
            target_group = _group_id(connection, owner_id, target, row["group_name"])
            connection.execute(
                "INSERT INTO everydollar_items(item_id,owner_id,month,group_id,label,planned_cents,position,favorite,due_day,notes,updated_at) VALUES(?,?,?,?,?,?,?,?,?,?,?)",
                (secrets.token_hex(12), owner_id, target, target_group, row["label"], row["planned_cents"], row["position"], row["favorite"], row["due_day"], row["notes"], int(time.time())),
            )
    return snapshot(actor_id, account, target)


def save_goal(actor_id: str, account: dict[str, Any] | None, payload: dict[str, Any]) -> dict[str, Any]:
    owner_id = _owner(actor_id, account)
    label = str(payload.get("label", "")).strip()
    target = round(float(payload.get("target", 0)) * 100)
    saved = round(float(payload.get("saved", 0)) * 100)
    target_month = str(payload.get("target_month") or current_month())
    if not label or target <= 0 or saved < 0:
        raise ValueError("Enter a goal name and a target greater than zero.")
    with backend.lifecycle.connection(transaction=True) as connection:
        connection.execute(
            "INSERT INTO everydollar_goals(goal_id,owner_id,label,target_cents,saved_cents,target_month,updated_at) VALUES(?,?,?,?,?,?,?)",
            (secrets.token_hex(12), owner_id, label, target, saved, target_month, int(time.time())),
        )
    return snapshot(actor_id, account)


def update_goal(actor_id: str, account: dict[str, Any] | None, goal_id: str, payload: dict[str, Any]) -> dict[str, Any]:
    owner_id = _owner(actor_id, account)
    with backend.lifecycle.connection(transaction=True) as connection:
        row = connection.execute("SELECT * FROM everydollar_goals WHERE goal_id=? AND owner_id=?", (goal_id, owner_id)).fetchone()
        if not row:
            raise PermissionError("Goal was not found.")
        saved = round(float(payload.get("saved", row["saved_cents"] / 100)) * 100)
        target = round(float(payload.get("target", row["target_cents"] / 100)) * 100)
        if saved < 0 or target <= 0:
            raise ValueError("Enter valid goal amounts.")
        connection.execute(
            "UPDATE everydollar_goals SET label=?,target_cents=?,saved_cents=?,target_month=?,updated_at=? WHERE goal_id=? AND owner_id=?",
            (str(payload.get("label", row["label"])).strip(), target, saved,
             str(payload.get("target_month", row["target_month"])), int(time.time()), goal_id, owner_id),
        )
    return snapshot(actor_id, account)


def save_preferences(actor_id: str, account: dict[str, Any] | None, payload: dict[str, Any]) -> dict[str, Any]:
    owner_id = _owner(actor_id, account)
    ensure_budget(owner_id, current_month())
    with backend.lifecycle.connection(transaction=True) as connection:
        connection.execute(
            """UPDATE everydollar_preferences SET reminders=?,weekly_summary=?,safe_to_spend=?,whole_numbers=?,updated_at=?
               WHERE owner_id=?""",
            (int(bool(payload.get("reminders"))), int(bool(payload.get("weekly_summary"))),
             int(bool(payload.get("safe_to_spend"))), int(bool(payload.get("whole_numbers"))), int(time.time()), owner_id),
        )
    return snapshot(actor_id, account)


def reset() -> None:
    def site_reset(connection: Any) -> None:
        for table in (
            "everydollar_transactions", "everydollar_items", "everydollar_groups", "everydollar_budgets",
            "everydollar_goals", "everydollar_preferences", "everydollar_profiles",
        ):
            connection.execute(f"DELETE FROM {table}")
    auth.reset_site_state(site_reset=site_reset, seed_accounts=[])