feat(v2): own dca_lp writes + auto-init on first dashboard access
Pairs with the satmachineadmin Phase 1 refactor that hoisted LP state
into `satoshimachine.dca_lp` (one row per user). This extension is now
the WRITER for that table; satmachineadmin only reads it during
distribution.
API surface:
- `GET /api/v1/dca-client/preferences` — returns the LP's
`dca_lp` row, AUTO-CREATING it with the authenticated wallet
as the default DCA destination on first call. Hitting this
endpoint is the act that marks the LP as onboarded on the
operator side (gating their deposit creation).
- `PUT /api/v1/dca-client/preferences` — LP-side update of
wallet / mode / fixed-mode limit / autoforward fields. Ensures
the row exists before applying. Replaces the old
`PUT /autoforward` endpoint (which is gone).
- `GET /api/v1/dca-client/positions` — same shape as before
but also auto-inits dca_lp on entry (so opening the dashboard
onboards the LP). Now INNER JOINs dca_lp so only onboarded
LPs see positions (matches the operator-side "must onboard
before deposits" gate).
- `GET /api/v1/dca-client/transactions` — unchanged.
Models:
- New `LpPreferences` / `UpdateLpPreferences` exposing the
dca_lp fields.
- `UpdateClientAutoforward` removed (replaced by the broader
`UpdateLpPreferences`).
- `PerMachinePosition.dca_mode` now sourced from `dca_lp` (it's
LP-wide, echoed on each position row for legacy display
compatibility).
CRUD:
- `_fetch_user_clients` rewritten: INNER JOIN dca_lp, drop
references to removed `dca_clients.wallet_id` / `.dca_mode`
columns (they don't exist anymore post-Phase-1).
- New: `get_lp_preferences`, `ensure_lp_preferences`,
`update_lp_preferences`. The first writes nothing; the second
is the get-or-create that defends the auto-onboard invariant.
- `update_lp_autoforward` removed — write path is now
`update_lp_preferences` against `dca_lp`, not the multi-row
UPDATE on `dca_clients` that used to be needed because the
state was denormalised across enrolments.
Note: the legacy static/js/index.js in this extension references
endpoints that no longer exist (`/registration-status`, `/register`,
`/dashboard/summary`, ...) — that's pre-existing tech debt from when
the LP UX was moved to ~/dev/webapp. Not regressed by this commit;
the deprecated frontend is out of scope. For now LP onboarding works
via direct API call (curl `GET /preferences` once with the LP's wallet
admin key); the webapp will own the proper UI.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
ade4e67541
commit
7dac898a10
3 changed files with 166 additions and 66 deletions
97
crud.py
97
crud.py
|
|
@ -1,8 +1,9 @@
|
|||
# Satoshi Machine Client v2 — CRUD over admin schema.
|
||||
#
|
||||
# Cross-extension reads of satoshimachine.dca_* tables, filtered by the
|
||||
# LP's user_id. The admin extension owns writes; this client surface is
|
||||
# strictly read + LP-self autoforward toggle.
|
||||
# LP's user_id. The admin extension owns writes to dca_clients/deposits/
|
||||
# settlements; this extension owns writes to satoshimachine.dca_lp
|
||||
# (the LP's per-user preferences row — wallet, mode, autoforward).
|
||||
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
|
|
@ -14,8 +15,9 @@ from loguru import logger
|
|||
from .models import (
|
||||
ClientDashboardSummary,
|
||||
ClientTransaction,
|
||||
LpPreferences,
|
||||
PerMachinePosition,
|
||||
UpdateClientAutoforward,
|
||||
UpdateLpPreferences,
|
||||
)
|
||||
|
||||
# Same DB schema as the admin extension — we share satoshimachine.* tables.
|
||||
|
|
@ -24,20 +26,26 @@ db = Database("ext_satoshimachine")
|
|||
|
||||
async def _fetch_user_clients(user_id: str) -> List[dict]:
|
||||
"""All dca_clients rows for this LP, joined with their machines for
|
||||
per-machine display metadata."""
|
||||
per-machine display metadata.
|
||||
|
||||
`dca_mode` lives on the LP's per-user `dca_lp` row now, not per
|
||||
enrolment — INNER JOIN dca_lp so positions only return when the LP
|
||||
has actually onboarded (otherwise distribution can't pay them either,
|
||||
so listing them in the dashboard would be misleading).
|
||||
"""
|
||||
return await db.fetchall(
|
||||
"""
|
||||
SELECT c.id AS client_id,
|
||||
c.machine_id,
|
||||
c.wallet_id,
|
||||
c.dca_mode,
|
||||
c.status,
|
||||
m.machine_npub,
|
||||
m.name AS machine_name,
|
||||
m.location AS machine_location,
|
||||
m.fiat_code AS machine_fiat_code
|
||||
m.fiat_code AS machine_fiat_code,
|
||||
lp.default_dca_mode AS dca_mode
|
||||
FROM satoshimachine.dca_clients c
|
||||
JOIN satoshimachine.dca_machines m ON m.id = c.machine_id
|
||||
JOIN satoshimachine.dca_lp lp ON lp.user_id = c.user_id
|
||||
WHERE c.user_id = :user_id
|
||||
ORDER BY c.created_at DESC
|
||||
""",
|
||||
|
|
@ -207,30 +215,63 @@ async def get_client_transactions(
|
|||
]
|
||||
|
||||
|
||||
async def update_lp_autoforward(
|
||||
user_id: str, data: UpdateClientAutoforward
|
||||
) -> int:
|
||||
"""LPs control their own auto-forward. Update applies to ALL of this
|
||||
LP's dca_clients rows (every machine they're on) — operator can't
|
||||
override LP-controlled settings."""
|
||||
async def get_lp_preferences(user_id: str) -> Optional[LpPreferences]:
|
||||
"""Read this LP's preferences row from `dca_lp`. Returns None if the
|
||||
LP hasn't onboarded yet (no row). Callers in this extension generally
|
||||
use `ensure_lp_preferences` instead, which auto-creates on first
|
||||
access."""
|
||||
return await db.fetchone(
|
||||
"SELECT * FROM satoshimachine.dca_lp WHERE user_id = :uid",
|
||||
{"uid": user_id},
|
||||
LpPreferences,
|
||||
)
|
||||
|
||||
|
||||
async def ensure_lp_preferences(user_id: str, default_wallet_id: str) -> LpPreferences:
|
||||
"""Get-or-create the LP's preferences row.
|
||||
|
||||
First call (no row): seed with `default_wallet_id` (passed by the
|
||||
caller — typically the wallet the LP authenticated through). LP can
|
||||
change it later via `update_lp_preferences`.
|
||||
|
||||
This is the structural enforcement of the "LP must onboard before
|
||||
deposits work" gate: the act of opening satmachineclient and hitting
|
||||
any endpoint creates the dca_lp row, which unlocks deposit creation
|
||||
on the operator side.
|
||||
"""
|
||||
existing = await get_lp_preferences(user_id)
|
||||
if existing is not None:
|
||||
return existing
|
||||
now = datetime.now()
|
||||
await db.execute(
|
||||
"""
|
||||
INSERT INTO satoshimachine.dca_lp
|
||||
(user_id, dca_wallet_id, default_dca_mode,
|
||||
autoforward_enabled, created_at, updated_at)
|
||||
VALUES (:uid, :wallet, 'flow', false, :now, :now)
|
||||
""",
|
||||
{"uid": user_id, "wallet": default_wallet_id, "now": now},
|
||||
)
|
||||
created = await get_lp_preferences(user_id)
|
||||
assert created is not None
|
||||
return created
|
||||
|
||||
|
||||
async def update_lp_preferences(
|
||||
user_id: str, data: UpdateLpPreferences
|
||||
) -> Optional[LpPreferences]:
|
||||
"""LP-side update of their `dca_lp` row. Caller must ensure the row
|
||||
exists first (typically via `ensure_lp_preferences` on dashboard
|
||||
load). Operator cannot reach this path — it requires the LP's wallet
|
||||
admin key per the API auth dependency."""
|
||||
update_data = {k: v for k, v in data.dict().items() if v is not None}
|
||||
if not update_data:
|
||||
return 0
|
||||
return await get_lp_preferences(user_id)
|
||||
update_data["updated_at"] = datetime.now()
|
||||
update_data["uid"] = user_id
|
||||
set_clause = ", ".join(
|
||||
f"{k} = :{k}" for k in update_data if k not in ("uid",)
|
||||
)
|
||||
result = await db.execute(
|
||||
f"UPDATE satoshimachine.dca_clients SET {set_clause} WHERE user_id = :uid",
|
||||
set_clause = ", ".join(f"{k} = :{k}" for k in update_data if k not in ("uid",))
|
||||
await db.execute(
|
||||
f"UPDATE satoshimachine.dca_lp SET {set_clause} WHERE user_id = :uid",
|
||||
update_data,
|
||||
)
|
||||
# db.execute return varies by backend; just return count of rows that
|
||||
# exist (best-effort indicator of rows touched).
|
||||
rows = await db.fetchone(
|
||||
"SELECT COUNT(*) AS n FROM satoshimachine.dca_clients WHERE user_id = :uid",
|
||||
{"uid": user_id},
|
||||
)
|
||||
_ = result
|
||||
return int(rows["n"]) if rows else 0
|
||||
|
||||
return await get_lp_preferences(user_id)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue