Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 0 additions & 4 deletions nonebot_plugin_value/action_type.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,3 @@ class Method(str, Enum):
WITHDRAW = "WITHDRAW" # 取款
TRANSFER_IN = "TRANSFER_IN" # 转入(与转出同时存在)
TRANSFER_OUT = "TRANSFER_OUT" # 转出(与转入同时存在)

@classmethod
def valid_actions(cls, action: str) -> bool:
return action in cls.__dict__.values()
18 changes: 9 additions & 9 deletions nonebot_plugin_value/api/api_balance.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from ..services.balance import set_frozen as _set_frozen
from ..services.balance import set_frozen_all as _set_frozen_all
from ..services.balance import transfer_funds as _transfer
from .api_currency import get_default_currency as _get_default
from ..uuid_lib import DEFAULT_CURRENCY_UUID


async def set_frozen_all(account_id: str, frozen: bool) -> None:
Expand Down Expand Up @@ -47,7 +47,7 @@ async def list_accounts(currency_id: str | None = None) -> list[UserAccountData]
list[UserAccountData]: 包含用户数据的列表
"""
if currency_id is None:
currency_id = (await _get_default()).id
currency_id = DEFAULT_CURRENCY_UUID.hex
async with get_session() as session:
return [
UserAccountData(
Expand All @@ -72,7 +72,7 @@ async def del_account(user_id: str, currency_id: str | None = None) -> bool:
bool: 是否成功
"""
if currency_id is None:
currency_id = (await _get_default()).id
currency_id = DEFAULT_CURRENCY_UUID.hex
return await _del_account(user_id, currency_id=currency_id)


Expand All @@ -89,7 +89,7 @@ async def get_or_create_account(
UserAccountData: 用户数据
"""
if currency_id is None:
currency_id = (await _get_default()).id
currency_id = DEFAULT_CURRENCY_UUID.hex
async with get_session() as session:
data = await _go_account(user_id, currency_id, session)
session.add(data)
Expand All @@ -113,7 +113,7 @@ async def batch_del_balance(
"""
data_list: list[UserAccountData] = []
if currency_id is None:
currency_id = (await _get_default()).id
currency_id = DEFAULT_CURRENCY_UUID.hex
await _batch_del(updates, currency_id, source, return_all_on_fail=True)
for user_id, _ in updates:
data_list.append(await get_or_create_account(user_id, currency_id))
Expand All @@ -137,7 +137,7 @@ async def batch_add_balance(
"""
data_list: list[UserAccountData] = []
if currency_id is None:
currency_id = (await _get_default()).id
currency_id = DEFAULT_CURRENCY_UUID.hex
await _batch_add(updates, currency_id, source, return_all_on_fail=True)
for user_id, _ in updates:
data_list.append(await get_or_create_account(user_id, currency_id))
Expand Down Expand Up @@ -166,7 +166,7 @@ async def add_balance(
"""

if currency_id is None:
currency_id = (await _get_default()).id
currency_id = DEFAULT_CURRENCY_UUID.hex
data = await _a_balance(user_id, currency_id, amount, source)
if not data.success:
raise RuntimeError(data.message)
Expand Down Expand Up @@ -194,7 +194,7 @@ async def del_balance(
UserAccountData: 用户数据
"""
if currency_id is None:
currency_id = (await _get_default()).id
currency_id = DEFAULT_CURRENCY_UUID.hex
data = await _d_balance(user_id, currency_id, amount, source)
if not data.success:
raise RuntimeError(data.message)
Expand Down Expand Up @@ -224,7 +224,7 @@ async def transfer_funds(
UserAccountData: 用户账户数据
"""
if currency_id is None:
currency_id = (await _get_default()).id
currency_id = DEFAULT_CURRENCY_UUID.hex
if not source:
source = f"from '{from_id}' to '{to_id}'"
data = await _transfer(from_id, to_id, currency_id, amount, source)
Expand Down
4 changes: 2 additions & 2 deletions nonebot_plugin_value/api/depends/data_classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from nonebot.adapters import Event

from ...uuid_lib import to_uuid
from ...uuid_lib import DEFAULT_CURRENCY_UUID, to_uuid
from ..api_balance import UserAccountData, get_or_create_account
from ..api_currency import CurrencyData, get_currency, get_default_currency
from ..api_transaction import (
Expand Down Expand Up @@ -34,7 +34,7 @@ class Account:

async def __call__(self, event: Event) -> UserAccountData:
if self.currency_id is None:
self.currency_id = (await get_default_currency()).id
self.currency_id = DEFAULT_CURRENCY_UUID.hex
return await get_or_create_account(
to_uuid(event.get_user_id()), self.currency_id
)
Expand Down
7 changes: 5 additions & 2 deletions nonebot_plugin_value/api/depends/factory.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
from collections.abc import Awaitable, Callable
from typing import Any

from ...pyd_models.balance_pyd import UserAccountData
from ...pyd_models.currency_pyd import CurrencyData
from ...pyd_models.transaction_pyd import TransactionData
from ...uuid_lib import DEFAULT_CURRENCY_UUID
from ..executor import AccountExecutor
from .data_classes import Account, Currency, TransactionHistory

Expand Down Expand Up @@ -60,7 +62,8 @@ def transaction_data(
@staticmethod
def account_executor(
*,
currency_id: str | None = None,
currency_id: str = DEFAULT_CURRENCY_UUID.hex,
**kwargs: Any,
) -> Callable[..., Awaitable[AccountExecutor]]:
"""
Args:
Expand All @@ -69,4 +72,4 @@ def account_executor(
Returns:
Callable[..., Awaitable[AccountExecutor]]: 账号数据操作对象
"""
return AccountExecutor(currency_id)
return AccountExecutor(currency_id=currency_id, **kwargs)
20 changes: 9 additions & 11 deletions nonebot_plugin_value/api/executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,24 @@
from nonebot.adapters import Event
from typing_extensions import Self

from ..uuid_lib import to_uuid
from ..uuid_lib import DEFAULT_CURRENCY_UUID, to_uuid
from .api_balance import (
UserAccountData,
add_balance,
del_balance,
get_or_create_account,
)
from .api_currency import get_default_currency


@dataclass
class AccountExecutor:
currency_id: str | None = field(default=None)
currency_id: str = field(default=DEFAULT_CURRENCY_UUID.hex)
user_id: str = field(default="")
data_map: dict[str, UserAccountData] = field(default_factory=lambda: {})

async def __call__(self, event: Event) -> Self:
self.user_id = to_uuid(event.get_user_id())
if self.currency_id is None:
currency_id = (await get_default_currency()).id
else:
currency_id = self.currency_id
currency_id = self.currency_id
self.data_map[currency_id] = await get_or_create_account(
self.user_id, currency_id
)
Expand All @@ -40,11 +36,15 @@ async def get_data(self, currency_id: str | None = None) -> UserAccountData:
UserAccountData: 账号数据
"""
currency_id = currency_id or self.currency_id
assert currency_id is not None, "Currency ID is required"
return self.data_map.get(
if data := self.data_map.get(
currency_id,
):
return data
self.data_map[currency_id] = self.data_map.get(
currency_id,
await get_or_create_account(self.user_id, currency_id),
)
return self.data_map[currency_id]

async def get_balance(
self,
Expand Down Expand Up @@ -77,7 +77,6 @@ async def add_balance(
Self: Self
"""
currency_id = currency_id or self.currency_id
assert currency_id is not None, "Currency ID is required"
self.data_map[currency_id] = await add_balance(
self.user_id,
amount,
Expand All @@ -103,7 +102,6 @@ async def decrease_balance(
Self: Self
"""
currency_id = currency_id or self.currency_id
assert currency_id is not None, "Currency ID is required"
self.data_map[currency_id] = await del_balance(
self.user_id,
amount,
Expand Down
10 changes: 4 additions & 6 deletions nonebot_plugin_value/hook/hooks_manager.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,18 @@
# 事件预处理/后处理钩子
from collections.abc import Awaitable, Callable
from typing import Any

from nonebot import logger

from .context import TransactionComplete, TransactionContext
from .exception import CancelAction
from .exception import CancelAction, DataUpdate
from .hooks_type import HooksType


class HooksManager:
__hooks: dict[str, list[Callable[..., Awaitable[None]]]]
_instance = None

def __new__(cls, *args: Any, **kwargs: Any):
"""重写 __new__ 方法实现单例模式"""
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance.__hooks = {}
Expand All @@ -38,7 +36,7 @@ def register(
self, hook_name: str, hook_func: Callable[..., Awaitable[None]]
) -> None:
"""注册一个Hook"""
if not HooksType.valid_hooks(hook_name):
if hook_name not in HooksType:
raise ValueError(f"Invalid hook name: {hook_name}")
self.__hooks.setdefault(hook_name, []).append(hook_func)

Expand All @@ -51,7 +49,7 @@ async def run_hooks(
async def _run_single_hook(hook: Callable[..., Awaitable[None]]) -> None:
try:
await hook(context)
except CancelAction:
except CancelAction | DataUpdate:
raise
except Exception:
logger.opt(exception=True).error("钩子执行失败")
Expand Down
20 changes: 9 additions & 11 deletions nonebot_plugin_value/hook/hooks_type.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,17 @@
class HooksType:
__pre = "vault_pre_transaction"
__post = "vault_post_transaction"
from enum import Enum


class HooksType(str, Enum):
PRE = "vault_pre_transaction"
POST = "vault_post_transaction"

@classmethod
def pre(cls) -> str:
return cls.__pre
return cls.PRE.value

@classmethod
def post(cls) -> str:
return cls.__post

@classmethod
def valid_hooks(cls, hook_name: str) -> bool:
return hook_name in [cls.__pre, cls.__post]

return cls.POST.value
@classmethod
def methods(cls) -> list[str]:
return [cls.__pre, cls.__post]
return [hook.value for hook in cls]
6 changes: 4 additions & 2 deletions nonebot_plugin_value/models/balance.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
)
from sqlalchemy.orm import MappedColumn, mapped_column, relationship

from ..uuid_lib import NAMESPACE_VALUE
from ..uuid_lib import NAMESPACE_VALUE, get_uni_id
from .utils import OnDeleteEnum


Expand Down Expand Up @@ -63,7 +63,9 @@ def __init__(self, **kwargs: Any):
raise ValueError("id and currency_id must be provided")
if "uni_id" not in kwargs:
namespace = NAMESPACE_VALUE
uni_id_val = uuid.uuid5(namespace, kwargs["id"] + kwargs["currency_id"])
uni_id_val = uuid.uuid5(
namespace, get_uni_id(kwargs["id"], kwargs["currency_id"])
)
kwargs["id"] = uni_id_val
super().__init__(**kwargs)

Expand Down
11 changes: 7 additions & 4 deletions nonebot_plugin_value/repository.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Repository,更加底层的数据库操作接口
from collections.abc import Sequence
from datetime import datetime, timezone
from uuid import uuid1, uuid5
from uuid import uuid1

from nonebot import logger
from nonebot_plugin_orm import AsyncSession
Expand All @@ -17,10 +17,13 @@
from .models.balance import Transaction, UserAccount
from .models.currency import CurrencyMeta
from .pyd_models.currency_pyd import CurrencyData
from .uuid_lib import NAMESPACE_VALUE, get_uni_id
from .uuid_lib import DEFAULT_CURRENCY_UUID, DEFAULT_NAME, NAMESPACE_VALUE, get_uni_id

DEFAULT_NAME = "DEFAULT_CURRENCY_USD"
DEFAULT_CURRENCY_UUID = uuid5(NAMESPACE_VALUE, DEFAULT_NAME)
__all__ = [
"DEFAULT_CURRENCY_UUID",
"DEFAULT_NAME",
"NAMESPACE_VALUE",
]


class CurrencyRepository:
Expand Down
16 changes: 8 additions & 8 deletions nonebot_plugin_value/services/balance.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ async def del_balance(
account_id = account.id
try:
await HooksManager().run_hooks(
HooksType.pre(),
HooksType.PRE.value,
TransactionContext(
user_id=user_id,
currency=currency_id,
Expand Down Expand Up @@ -218,7 +218,7 @@ async def del_balance(
)
try:
await HooksManager().run_hooks(
HooksType.post(),
HooksType.POST.value,
TransactionComplete(
message="交易完成",
source_balance=balance_before,
Expand Down Expand Up @@ -298,7 +298,7 @@ async def add_balance(
balance_before = account.balance
try:
await HooksManager().run_hooks(
HooksType.pre(),
HooksType.PRE.value,
TransactionContext(
user_id=user_id,
currency=currency_id,
Expand Down Expand Up @@ -329,7 +329,7 @@ async def add_balance(
)
try:
await HooksManager().run_hooks(
HooksType.post(),
HooksType.POST.value,
TransactionComplete(
message="交易完成",
source_balance=balance_before,
Expand Down Expand Up @@ -396,7 +396,7 @@ async def transfer_funds(
try:
try:
await HooksManager().run_hooks(
HooksType.pre(),
HooksType.PRE.value,
TransactionContext(
user_id=fromuser_id,
currency=currency_id,
Expand All @@ -408,7 +408,7 @@ async def transfer_funds(
amount = abs(du.amount)
try:
await HooksManager().run_hooks(
HooksType.pre(),
HooksType.PRE.value,
TransactionContext(
user_id=touser_id,
currency=currency_id,
Expand Down Expand Up @@ -454,7 +454,7 @@ async def transfer_funds(
)
try:
await HooksManager().run_hooks(
HooksType.post(),
HooksType.POST.value,
TransactionComplete(
message="交易完成(转账)",
source_balance=from_balance_before,
Expand All @@ -464,7 +464,7 @@ async def transfer_funds(
),
)
await HooksManager().run_hooks(
HooksType.post(),
HooksType.POST.value,
TransactionComplete(
message="交易完成(转账)",
source_balance=to_balance_before,
Expand Down
3 changes: 2 additions & 1 deletion nonebot_plugin_value/uuid_lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

# UUID namespace常量定义。
NAMESPACE_VALUE = UUID("e6fec076-98df-4979-8618-36ad04dea39f")

DEFAULT_NAME = "DEFAULT_CURRENCY_USD"
DEFAULT_CURRENCY_UUID = uuid5(NAMESPACE_VALUE, DEFAULT_NAME)

def to_uuid(s: str) -> str:
"""获取UUID
Expand Down
Loading
Loading