Files
myrzx_bot/ranch_assistant/market.py
T

33 lines
1.4 KiB
Python

"""Per-role purchase accounting, recorded before sending a non-retryable buy."""
from datetime import datetime, timedelta, timezone
import json
from pathlib import Path
class PurchaseBudget:
def __init__(self, path=None):
self.path = Path(path) if path else None
self.state = {"day": "", "spent": 0}
if self.path and self.path.exists():
self.state = json.loads(self.path.read_text(encoding="utf-8"))
if not isinstance(self.state.get("day"), str) or int(self.state["spent"]) < 0:
raise ValueError("购蛋额度记录无效")
def spent(self, now):
day = datetime.fromtimestamp(now, timezone(timedelta(hours=8))).strftime("%Y-%m-%d")
return int(self.state["spent"]) if self.state["day"] == day else 0
def remaining(self, now, limit):
return max(0, int(limit) - self.spent(now))
def record(self, now, cost, limit):
if cost <= 0 or cost > self.remaining(now, limit):
raise ValueError("购蛋花费超过今日剩余额度")
state = {"day": datetime.fromtimestamp(now, timezone(timedelta(hours=8))).strftime("%Y-%m-%d"), "spent": self.spent(now) + cost}
if self.path:
self.path.parent.mkdir(parents=True, exist_ok=True)
temporary = self.path.with_suffix(".tmp")
temporary.write_text(json.dumps(state), encoding="utf-8")
temporary.replace(self.path)
self.state = state