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
record_barter.py · 7.4 KB · 153 lines
1"""action_record_barter -- book a barter as what it is: a sale and a purchase,
2each at fair value, through a clearing account.
3
4POST {"reference": "BARTER-7", "date": "2026-11-30", "counterparty": "Joe's Print",
5 "given": "Catering for 20", "given_value_cents": 40000, "tax_rate_bps": 825,
6 "received": "500 menus printed", "received_value_cents": 40000,
7 "received_account": "<fin_accounts id: an expense or an asset>"}
8
9**Decision 6 (owner, 2026-11-30).** A barter is a sale and a purchase at fair
10value, taxable, via a clearing account. Swapping catering for printing with
11no money changing hands is still revenue the shop earned and a cost it
12incurred; booking nothing (or netting the two) hides both, and hides the
13sales tax owed on the sale.
14
15Two journals, each idempotent by the reference (barter/<reference>:sale and
16:purchase), both posted:
17
18 sale DR Barter Clearing given + tax
19 CR Revenue given
20 CR Sales Tax Payable tax (half-up, at tax_rate_bps)
21 purchase DR received_account received
22 CR Barter Clearing received
23
24What is left in Barter Clearing is the difference the two sides still owe
25each other (boot, or the tax the counterparty pays in cash); it is settled
26by an ordinary payment, and the clearing account showing it is the point.
27
28Accounts: barter.journal.clearing_account, payments.journal.revenue_account
29and, where there is tax, payments.journal.tax_account (app_settings; account
30setup maps them for a double-entry chart). An unmapped account refuses with
31the setting to set; nothing is booked half.
32
33Only the books' keepers run this (role:finance, role:owner; admins). What is
34NOT decided, and so not done: input tax on what was received (whether the
35shop may reclaim tax on the printing) -- the purchase is booked at fair
36value with no input tax (docs/logic-decisions.md, open questions).
37"""
38
39import os
40import re
41from decimal import ROUND_HALF_UP, Decimal
42
43import object_finance
44import object_records
45
46ACTOR = "action_record_barter"
47_KEEPERS = {"admin", "finance", "owner"}
48
49
50def _base_dir():
51 return os.environ.get("DBBASIC_DATA_DIR", "data")
52
53
54def _text(value):
55 return str(value if value is not None else "").strip()
56
57
58def _setting(base, key):
59 try:
60 # access: box configuration
61 for row in object_records.read_collection_records("app_settings", base_dir=base):
62 if row.get("key") == key and _text(row.get("value")):
63 return _text(row.get("value"))
64 except Exception:
65 pass
66 return ""
67
68
69def _cents(value):
70 text = _text(value)
71 if not re.fullmatch(r"\d+", text):
72 return None
73 return int(text)
74
75
76def barter_journals(*, given_value, received_value, tax_rate_bps, clearing, revenue,
77 tax_account, received_account):
78 """The two journals' lines, or raise ValueError. Pure: the decision's
79 arithmetic in one place."""
80 tax = int((Decimal(given_value) * Decimal(tax_rate_bps) / Decimal(10000)).to_integral_value(
81 rounding=ROUND_HALF_UP)) if tax_rate_bps else 0
82 sale = [{"account_id": clearing, "debit_cents": given_value + tax, "credit_cents": 0},
83 {"account_id": revenue, "debit_cents": 0, "credit_cents": given_value}]
84 if tax:
85 sale.append({"account_id": tax_account, "debit_cents": 0, "credit_cents": tax,
86 "memo": "Sales tax on a barter, at fair value"})
87 purchase = [{"account_id": received_account, "debit_cents": received_value,
88 "credit_cents": 0},
89 {"account_id": clearing, "debit_cents": 0, "credit_cents": received_value}]
90 return sale, purchase, tax
91
92
93def POST(request):
94 identity = request.get("_identity") or {}
95 roles = {str(r).split(":", 1)[-1] for r in (identity.get("roles") or [])}
96 user_id = _text(identity.get("user_id"))
97 if not user_id:
98 return {"status": 401, "error": "Sign in to record a barter."}
99 if not roles & _KEEPERS:
100 return {"status": 403, "error": "Only the bookkeeper or the owner records a barter."}
101 reference = _text(request.get("reference"))
102 if not re.fullmatch(r"[A-Za-z0-9._-]{1,64}", reference):
103 return {"status": 400, "error": "reference is required (letters, digits, . _ -), "
104 "and is what makes recording it twice book nothing twice."}
105 given_value = _cents(request.get("given_value_cents"))
106 received_value = _cents(request.get("received_value_cents"))
107 rate = _cents(request.get("tax_rate_bps") or "0")
108 if not given_value or not received_value or rate is None:
109 return {"status": 400, "error": "given_value_cents and received_value_cents are fair "
110 "values in whole cents above zero; tax_rate_bps is "
111 "whole basis points."}
112 date = _text(request.get("date"))[:10]
113 if not re.fullmatch(r"\d{4}-\d{2}-\d{2}", date):
114 return {"status": 400, "error": "date is YYYY-MM-DD."}
115 base = _base_dir()
116 clearing = _setting(base, "barter.journal.clearing_account")
117 revenue = _setting(base, "payments.journal.revenue_account")
118 tax_account = _setting(base, "payments.journal.tax_account")
119 received_account = _text(request.get("received_account"))
120 needed = [key for key, value in (("barter.journal.clearing_account", clearing),
121 ("payments.journal.revenue_account", revenue),
122 ("payments.journal.tax_account", tax_account if rate else "x"))
123 if not value]
124 if needed:
125 return {"status": 409, "needs_settings": needed,
126 "error": f"Set {' and '.join(needed)} in app_settings; nothing was booked."}
127 if not received_account:
128 return {"status": 400, "error": "received_account is the account what was received "
129 "is booked to (an expense, or an asset)."}
130 missing = object_finance.accounts_missing(
131 base, [a for a in (clearing, revenue, received_account, tax_account if rate else "") if a])
132 if missing is object_finance.UNREADABLE:
133 return {"status": 503, "error": "The chart of accounts could not be read; nothing was booked."}
134 if missing:
135 return {"status": 409, "error": f"Not in the chart of accounts: {', '.join(missing)}."}
136 sale, purchase, tax = barter_journals(
137 given_value=given_value, received_value=received_value, tax_rate_bps=rate,
138 clearing=clearing, revenue=revenue, tax_account=tax_account,
139 received_account=received_account)
140 who = _text(request.get("counterparty"))[:120] or "a counterparty"
141 out = {}
142 for side, lines, what in (("sale", sale, _text(request.get("given"))),
143 ("purchase", purchase, _text(request.get("received")))):
144 result = object_finance.compose_posted_journal(
145 base, generated_from=f"barter/{reference}:{side}", date=date,
146 description=f"Barter {reference} with {who}: {side} -- {what[:120]}",
147 lines=lines, owner_id=user_id, actor=f"{ACTOR}:{user_id}", if_closed="refuse")
148 if not result.get("ok"):
149 return {"status": 409, "error": f"The {side} was not booked: {result.get('error')}",
150 **out}
151 out[f"{side}_journal_id"] = result.get("journal_id")
152 return {"status": 200, "ok": True, "reference": reference, "tax_cents": tax,
153 "clearing_left_cents": given_value + tax - received_value, **out}