Customer and executor drop Ozon links → the executor orders with their own card → the bot tracks how much the customer owes back.
- Customer and executor: both send links, both use
/listand/debt. - Executor: buttons
1 New | 2 Ordered | 3 Received | 🚫 Cancel | ✏️ Price | 🔢 Qty(plus↩️ Reopenon closed/cancelled items), commands/debt /stats /pay /payments. - Menu buttons:
📋 List,💰 Debts,📊 Stats,❌ Cancel(plus/menu,/cancel).💰 Debtsimmediately shows the debt summary and an action submenu:💰 Debt,📜 Repaymentsand (for the executor)➕ Debt,✏️ Past debt,🗑 Reset debt,💸 Repay,⬅️ Back. - Repayments: the executor sends
💸 Repay(amount + optional comment), the debt shrinks, the ledger lives in📜 Repayments(deleting a wrong entry asks for confirmation). - Past-orders debt:
➕ Debtadds an untracked amount (a negative value subtracts),✏️ Past debtoverwrites the whole figure (typo fix),🗑 Reset debtzeroes it with confirmation. It counts in the debt and the balance but never appears in the item list.
The bot runs 24/7 on Vercel (webhook, FastAPI ASGI) + Neon Postgres. Locally — long polling and a SQLite file. The MacBook is for development only.
cp .env.example .env # BOT_TOKEN, CUSTOMER_ID, EXECUTOR_ID, DATABASE_URL
uv sync
uv run alembic upgrade head
uv run python -m src.mainToken: @BotFather → /newbot. User IDs: @userinfobot.
| Command | Who | What |
|---|---|---|
/start |
anyone in the whitelist | greeting + role |
/list |
both | filterable, paged row list of Items; tap a row for its card (executor gets control buttons) |
/debt |
both | «Долг за товары» split into «заплатил заранее» (with in-hand vs in-transit counts) and «заплатил при получении» + «Долги за прошлое» (executor) + «Ещё не долг, оплачу при получении» + «Остаток» with the arithmetic (and «Аванс» on overpayment) |
/stats |
both | ordered/received/cancelled/refunds |
/pay |
executor | record a repayment (FSM: amount → optional comment) |
/payments |
both | repayment ledger (executor gets 🗑 with confirmation) |
Inline buttons under a card exist only for the executor (the customer sees a card without buttons). Updates from anyone outside the whitelist are ignored without a reply. For Ordered, the executor toggles payment with one button (💳 Switch to prepaid/postpaid); the default is prepaid. Received/Cancelled items have ↩️ Reopen (back to Ordered).
buckets = payment type × receipt status, one per in-work item (no gap)
debt_prepaid = prepaid_ordered + prepaid_received
debt_postpaid = postpaid_received
debt = debt_prepaid + debt_postpaid
pending = postpaid_ordered
manual_debt = signed past-orders figure (may be negative)
balance = debt + manual_debt − Σ repayment.amount_kop # < 0 → «advance» (overpayment)
Every in-work item falls into exactly one bucket, so no combination can fall
between the lines. A received postpaid item counts as debt: the executor paid
Ozon to collect it. Only an ordered postpaid item is still «Ещё не долг,
оплачу при получении» — not owed until it arrives, so it does not move the
balance. An in-work item that carries no money — no price yet, or a zero
line total — is reported separately («
A cancellation after prepayment is not counted as debt; it shows up in /stats as «refunds».
Repayments are a separate cash pool — cancellations do not adjust them automatically.
src/domain/ # entities, value objects, IItemRepository/IRepaymentRepository (pure)
src/use_cases/ # add_item, set_price, set_payment, change_status, calc_debt, calc_stats, add/list/delete_repayment, calc_balance, adjust/set_manual_debt
src/adapters/telegram/ # routers, keyboards, fsm
src/adapters/persistence/ # sqlalchemy models + SqlAlchemyItem/RepaymentRepository (SQLite + Postgres)
src/adapters/webhook/ # FastAPI ASGI app (Vercel) + set/delete webhook CLI
src/infrastructure/ # config, db, bootstrap (shared wiring), logging
asgi.py # Vercel entrypoint -> src.adapters.webhook.app:app
docs/adr/ # ADR: recorded decisions
docs/agents/ # skill setup (issue-tracker, triage-labels, domain)
Vocabulary lives in GLOSSARY.md; decisions in docs/adr/; specs and tickets in GitHub Issues; style in AGENTS.md.
Production is a Telegram webhook (FastAPI ASGI function on Vercel Hobby) + Neon
Postgres (asyncpg). Locally — long polling and SQLite. The decision and the
rejected Fly.io option are in docs/adr/0001-vercel-neon-webhook-over-fly.md.
vercel.json + asgi.py ([tool.vercel] entrypoint in pyproject.toml)
define the ASGI entrypoint; Vercel installs dependencies from pyproject.toml/uv.lock.
- Neon: create a project/database, copy the connection string into
DATABASE_URL(it can stay as-is,postgresql://…— the driver is upgraded toasyncpg, andsslmode/channel_bindingare normalized in code). - Migrations on Neon (from your local machine).
make migratereadsDATABASE_URLfrom the environment or.env. For migrations use the direct (ep-…, no-pooler) host: the pooler in transaction mode breaks DDL.make migrate # DATABASE_URL is already in .env, or: DATABASE_URL='postgresql://…' make migrate - Vercel: import the repository and set env vars (Production):
BOT_TOKEN,CUSTOMER_ID,EXECUTOR_ID,DATABASE_URL,WEBHOOK_BASE_URL=https://<app>.vercel.app,WEBHOOK_SECRET=<random string>. - Deploy + webhook:
make deploy— that isvercel deploy --prod+make webhook-set(setWebhookwith the secret). Code only, no webhook:make vercel-deploy. - Smoke test: send the bot
/start— it should reply.
make migrate # if the schema changed (DATABASE_URL from .env)
make deploy| Task | Command |
|---|---|
| Deploy + webhook | make deploy |
| Code deploy only | make vercel-deploy |
| Webhook status | make webhook-info |
| Unregister webhook (back to polling) | make webhook-delete |
| Register webhook | make webhook-set |
| Neon migrations | make migrate (reads DATABASE_URL from .env) |
| Production function logs | make logs-vercel (last 30 min) |
| Checks (lint + types + tests) | make check |
| SQLite↔Postgres drift | make test-pg |
Sequence in 0003 (destructive) |
make test-pg-reset |
- Logs.
make logs-vercelprints the last 30 minutes of production runtime logs and exits (it does not stream) — run it right after reproducing an issue. Vercel Hobby stores them for 1 hour per the docs, but the CLI on Hobby rejects--since 1h. - Why webhook. Telegram retries undelivered updates with backoff and wakes the function on every request — no always-on worker needed (ADR-0001).
- Updates outside the function.
WEBHOOK_SECRETis checked via theX-Telegram-Bot-Api-Secret-Tokenheader; foreign requests get403. Without a secret the endpoint is open — in production the secret is mandatory (the app logs a warning at startup). - Upload ignores.
vercel deployreads.vercelignoreonly (it does not honour.gitignore), so local-only paths stay out of the upload. This matters for.codegraph/: itsdaemon.sockis a unix socket andopen()on it aborts the upload withUnknown system error -102. - Schema — Alembic only (on both dialects).
init_dbdoes not create tables (onlyPRAGMA journal_mode=WALfor SQLite); if migrations were not run, startup fails with a hint to runmake migrate. Otherwise tables would appear withoutalembic_versionand the firstupgrade headwould fail onCREATE TABLE. - Connections on serverless. For Postgres the client-side pool is disabled
(
NullPool): pooling is done by the Neon pooler. Otherwise a frozen Vercel instance hands out a connection Neon has already closed (InterfaceError: connection is closed). - Dialect drift.
make test-pg TEST_DATABASE_URL='postgresql://…'runs migrations and a repo roundtrip on Postgres (optional, needs a separate DB). WithoutTEST_DATABASE_URLthe test is skipped, so it is not part ofmake check.make test-pg-reset— a destructive check of the sequence in0003(scratch DB only: rewinds the schema to0002and back). - Known limitation (FSM). The dispatcher uses
MemoryStorage: on serverless the FSM state lives in a specific instance and is lost on cold start, so multi-step flows (/pay) may reset between updates. A persistent storage is needed (follow-up ticket); for now the risk is mitigated by a warm instance.
Fly.io is no longer a production path (paid always-on, OOM on 256 MB — ADR-0001).
Dockerfile, fly.toml and the make *-fly/fly-* targets are kept as an optional
non-prod fallback; make fly-init/make deploy-fly only if really needed.
Removing the old app: fly apps destroy dolzhok.