Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 49 minutes ago History
setup_accounts.py · 8.8 KB · 182 lines
1"""setup_accounts -- 65 multi-entity, slice 4: seed an entity's chart of
2accounts from its mode.
3
4POST /finance/setup-accounts {entity_id}. A faithful port of the predecessor's
5Entity.create_default_accounts / the setup_finance_accounts MCP tool: given one
6of the caller's entities, create its fin_accounts based on the entity's `mode`
7(simple = income + expenses; standard = a 15-account chart; double_entry = a
8full 29-account chart). Idempotent -- an account already present for the entity
9(matched by name, the predecessor's get_or_create key) is skipped, so running
10it twice, or after adding a few accounts by hand, never duplicates.
11
12Owner-gated in the handler (like app-timers' timer_actions): the entity must
13belong to the caller, and every account is created owned by the caller and
14scoped to that entity_id. No public/cross-owner path -- a caller can only set
15up accounts for their own set of books.
16"""
17
18import json
19import os
20
21import object_records
22
23DATA_DIR_ENV = "DBBASIC_DATA_DIR"
24ACCOUNTS_COLLECTION = "fin_accounts"
25ENTITIES_COLLECTION = "entities"
26
27# (account_type, name, code) per mode -- carried verbatim from the predecessor's
28# Entity.STANDARD_ACCOUNTS / DOUBLE_ENTRY_ACCOUNTS (private source audit).
29_SIMPLE = [
30 ("income", "Income", "4000"),
31 ("expense", "Expenses", "5000"),
32]
33_STANDARD = [
34 ("asset", "Cash", "1010"), ("asset", "Checking Account", "1020"),
35 ("asset", "Savings Account", "1030"), ("asset", "Accounts Receivable", "1100"),
36 ("liability", "Accounts Payable", "2100"), ("income", "Income", "4000"),
37 ("expense", "Cost of Goods Sold", "5000"), ("expense", "Rent", "5100"),
38 ("expense", "Utilities", "5200"), ("expense", "Software & Subscriptions", "5300"),
39 ("expense", "Marketing", "5400"), ("expense", "Travel", "5500"),
40 ("expense", "Meals & Entertainment", "5600"), ("expense", "Payroll", "5700"),
41 ("expense", "Taxes", "5800"),
42]
43_DOUBLE_ENTRY = [
44 ("asset", "Cash", "1010"), ("asset", "Checking Account", "1020"),
45 ("asset", "Savings Account", "1030"), ("asset", "Accounts Receivable", "1100"),
46 ("asset", "Inventory", "1200"), ("asset", "Equipment", "1500"),
47 ("asset", "Prepaid Expenses", "1510"), ("asset", "Barter Clearing", "1290"),
48 ("liability", "Accounts Payable", "2100"),
49 ("liability", "Credit Card", "2200"), ("liability", "Sales Tax Payable", "2300"),
50 # Billed in advance, not yet earned (decision 4, 2026-11-30).
51 ("liability", "Deferred Revenue", "2350"),
52 ("liability", "Loans Payable", "2400"), ("equity", "Owner's Equity", "3100"),
53 ("equity", "Retained Earnings", "3200"), ("equity", "Owner's Draw", "3300"),
54 ("income", "Sales Revenue", "4100"), ("income", "Service Revenue", "4200"),
55 ("income", "Other Income", "4900"), ("income", "Interest Income", "4910"),
56 ("expense", "Cost of Goods Sold", "5000"),
57 # Contra-COGS (decision 6, 2026-11-30): scrap proceeds and supplier
58 # rebates bring the cost of what was sold down; expense-type accounts
59 # that carry a credit balance, so the income statement nets them against
60 # cost of goods instead of calling them income.
61 ("expense", "Scrap Sales (contra-COGS)", "5010"),
62 ("expense", "Vendor Rebates (contra-COGS)", "5020"),
63 ("expense", "Rent", "5100"), ("expense", "Utilities", "5200"),
64 ("expense", "Software & Subscriptions", "5300"), ("expense", "Marketing", "5400"),
65 ("expense", "Travel", "5500"), ("expense", "Meals & Entertainment", "5600"),
66 ("expense", "Payroll", "5700"), ("expense", "Insurance", "5800"),
67 ("expense", "Depreciation", "5810"), ("expense", "Interest Expense", "5820"),
68 ("expense", "Taxes", "5830"), ("expense", "Bank Fees", "5840"),
69]
70# The settings an account answers (decision 7, 2026-11-30): with a chart
71# that has the account, setup maps the key to it -- only where the key is
72# not set already, because an operator's own mapping is never overwritten.
73# The banking pair is what /books-status reported as "Books NOT READY" on a
74# fresh double-entry chart (reconcile.journal.interest_account had no
75# account to point at at all, since the chart had no Interest Income).
76SETTINGS_BY_ACCOUNT = (
77 ("reconcile.journal.interest_account", "Interest Income"),
78 ("reconcile.journal.fees_account", "Bank Fees"),
79 ("payments.journal.tax_account", "Sales Tax Payable"),
80 ("payments.journal.deferred_revenue_account", "Deferred Revenue"),
81 ("barter.journal.clearing_account", "Barter Clearing"),
82 ("inventory.journal.scrap_sales_account", "Scrap Sales (contra-COGS)"),
83 ("inventory.journal.vendor_rebates_account", "Vendor Rebates (contra-COGS)"),
84)
85
86CHART_BY_MODE = {"simple": _SIMPLE, "standard": _STANDARD, "double_entry": _DOUBLE_ENTRY}
87
88
89def _data_dir():
90 return os.environ.get(DATA_DIR_ENV, object_records.DEFAULT_DATA_DIR)
91
92
93def _error(status, message):
94 return {"content_type": "application/json", "status": status,
95 "body": json.dumps({"status": "error", "error": message})}
96
97
98def POST(request):
99 identity = request.get("_identity") or {}
100 user_id = identity.get("user_id")
101 if not user_id:
102 return _error(401, "Sign in to set up accounts.")
103
104 entity_id = str(request.get("entity_id") or "").strip()
105 if not entity_id:
106 return _error(400, "entity_id is required.")
107
108 base_dir = _data_dir()
109 try:
110 # access: the entity must be the caller's own: owner_id == user_id is checked on the next lines
111 entity = object_records.get_collection_record(ENTITIES_COLLECTION, entity_id, base_dir=base_dir)
112 except (object_records.RecordNotFoundError, object_records.InvalidRecordIdError):
113 return _error(404, f"Entity not found: {entity_id}")
114 if entity.get("owner_id") != user_id:
115 return _error(403, "That entity belongs to another owner.")
116
117 mode = (entity.get("mode") or "simple").strip()
118 chart = CHART_BY_MODE.get(mode)
119 if chart is None:
120 return _error(400, f"Unknown entity mode: {mode!r}")
121
122 # Idempotent: match the predecessor's get_or_create-by-name. Only this
123 # entity's existing accounts count -- two entities may share account names.
124 try:
125 # access: accounts of the caller's own entity, after the owner check above
126 all_accounts = object_records.read_collection_records(ACCOUNTS_COLLECTION, base_dir=base_dir)
127 except (LookupError, OSError, ValueError):
128 all_accounts = []
129 have = {a.get("name") for a in all_accounts if a.get("entity_id") == entity_id}
130
131 created, skipped = 0, 0
132 ids = {a.get("name"): a.get("id") for a in all_accounts if a.get("entity_id") == entity_id}
133 for account_type, name, code in chart:
134 if name in have:
135 skipped += 1
136 continue
137 # access: accounts of the caller's own entity, after the owner check above
138 row = object_records.create_collection_record(
139 ACCOUNTS_COLLECTION,
140 {"name": name, "code": code, "account_type": account_type,
141 "entity_id": entity_id, "owner_id": user_id, "is_active": "true"},
142 base_dir=base_dir, actor="setup_accounts",
143 )
144 ids[name] = row["id"]
145 created += 1
146 mapped = _map_settings(base_dir, ids)
147
148 _logger.info("setup_accounts", entity_id=entity_id, mode=mode, created=created, skipped=skipped)
149 return {"content_type": "application/json",
150 "body": json.dumps({"status": "ok", "mode": mode,
151 "created": created, "skipped": skipped,
152 "settings": mapped})}
153
154
155def _map_settings(base_dir, ids):
156 """Point each unset setting at the account that answers it, when this
157 chart has one. Returns {key: account_id} for what was written. A box
158 without app-settings is left alone: the keys are then the operator's."""
159 try:
160 # access: box configuration, read to leave an operator's own mapping alone
161 settings = object_records.read_collection_records("app_settings", base_dir=base_dir)
162 except Exception:
163 return {}
164 have = {row.get("key") for row in settings if str(row.get("value") or "").strip()}
165 mapped = {}
166 for key, account_name in SETTINGS_BY_ACCOUNT:
167 account_id = ids.get(account_name)
168 if key in have or not account_id:
169 continue
170 existing = next((row for row in settings if row.get("key") == key), None)
171 if existing is not None:
172 # access: box configuration, an unset key written by the account setup the entity's owner asked for
173 object_records.update_collection_record(
174 "app_settings", existing["id"], {"value": account_id},
175 base_dir=base_dir, actor="setup_accounts")
176 else:
177 # access: box configuration, an unset key written by the account setup the entity's owner asked for
178 object_records.create_collection_record(
179 "app_settings", {"key": key, "value": account_id},
180 base_dir=base_dir, actor="setup_accounts")
181 mapped[key] = account_id
182 return mapped