Search by

goletter / hyperf-asset

goletter

Strict multi-channel asset ledger for Hyperf: fixed pipeline + ChannelInterface + ActionParser DSL.

Package info

github.com/goletter/hyperf-asset

pkg:composer/goletter/hyperf-asset

Statistics

Installs: 1

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v1.0.0 2026-11-22 02:20 UTC

This package is auto-updated.

Last update: 2026-11-22 02:25:39 UTC


README

配置驱动的多渠道资金账本。包内核只做一件事:固定流水线;业务差异全部写在 ChannelInterface 实现里。

validate → lock → snapshot → attributes → action → parse → assert → flow → apply → after

安装

composer require goletter/hyperf-asset

# 发布渠道映射 + 流水类型 DSL
php bin/hyperf.php vendor:publish goletter/hyperf-asset

# 或按 id 分别发布
php bin/hyperf.php vendor:publish goletter/hyperf-asset --id=config    # → config/autoload/asset.php
php bin/hyperf.php vendor:publish goletter/hyperf-asset --id=linkage   # → config/autoload/linkage.php

若项目里已有 linkage.php,发布前请先合并,避免覆盖。

分层

层 职责
ActionParser 纯 DSL:add@field / sub@field,金额用字符串 + bcmath(有则优先)
AssetManager 事务 + 上述固定步骤,不接受「插队」钩子
ChannelInterface 锁哪一行、类型表、附加字段、校验、回写、联动

Channel 方法说明

按流水线顺序。业务项目继承 AbstractChannel,按需覆写。

标识 / 元数据

方法 作用
name() 渠道名,必须与 asset.channels 的 key 一致(如 wallet)。不一致 Manager 会报错。
flowModel() 流水表 Model(如 WalletFlow)。用于生成单号、create 流水。
balanceFields() 哪些字段是余额。变更前快照进流水,变更后默认由 apply 回写。不能为空。
types() 流水类型字典:type => ['asset' => 'add@x,sub@y', 'remark' => …]。示例未手写:设 $typesConfig 后由 AbstractChannel::types() 自动 config($typesConfig);要内联类型表时可覆写本方法。

主路径(通常要写)

方法 调用时机 作用
lock($input) 校验 user_id / money / type 之后 查出余额主体并 lockForUpdate。钱包:先找企业,再锁对应 Wallet。找不到抛 AssetException。
attributes($owner, $input, $typeConfig) 锁行后、算 DSL 前 往流水塞非余额字段:company_id、account_id、source、is_show 等。不要在这里改余额。
action($input, $typeConfig) 组好流水骨架后 返回 DSL,如 sub@wallet_money,add@no_wallet_money。基类默认读类型里的 asset;variantWhen 为真时读 asset1;$input[$actionKey] 可覆盖。返回空串 = 本渠道不改余额,跳过 parse/落库,仍走 after。
assert($owner, $input, $typeConfig, &$flow) DSL 算完、写库前 业务校验,并可改 $flow(引用传递)。例如预付不足抛错、可用余额未变则 is_show = 0。抛错则整笔事务回滚。
apply($owner, $flow, $input) 流水 create 成功后 把流水结果写回主体并 save。基类按 balanceFields 原样拷贝;有手续费等特殊回写时覆写本方法。
after($owner, $flow, $input, $typeConfig) 本渠道落库完成后(同事务) 后续动作。钱包一般空实现;账户在此 changeInTransaction('wallet', …) 联动。无 DSL 时 $flow 为 null。

基类开关(可选覆写)

成员 作用
$typesConfig 类型配置路径,如 linkage.wallet_flow_type。
$actionKey DSL 在类型 / input 上的字段名,默认 asset;账户可改为 account。
$variantActionKey 变体 DSL 字段名,默认 asset1(如月结规则)。
variantWhen($input, $typeConfig) 是否改用变体 DSL。例如 !empty($input['wallet_type'])。

与旧 tool 对应关系

旧 WalletManage / AccountManage 现在
查 Company + 锁 Wallet / AccountUser lock
拼 $log 业务字段 attributes
asset / asset1 选择 action + variantWhen
预付不足、is_show assert
回写余额、扣手续费 apply
账户内调 wallet_change AccountChannel::after

配置

config/autoload/asset.php(渠道类)

return [
    'channels' => [
        'wallet' => App\Asset\WalletChannel::class,
        'account' => App\Asset\AccountChannel::class,
    ],
];

config/autoload/linkage.php(流水类型 DSL)

包内模板见 publish/linkage.php,发布后得到:

key 用途
linkage.wallet_flow_type 钱包流水类型 + asset / asset1
linkage.account_flow_type 账户流水类型 + asset + wallet_type(联动钱包 type)

Channel 里用 $typesConfig 指向即可:

protected string $typesConfig = 'linkage.wallet_flow_type';
// types() 由 AbstractChannel 读取 config($typesConfig)

实现示例:WalletChannel

namespace App\Asset;

use App\Model\Company;
use App\Model\Wallet;
use App\Model\WalletFlow;
use Goletter\Asset\Contract\AbstractChannel;
use Goletter\Asset\Exception\AssetException;
use Hyperf\Database\Model\Model;

class WalletChannel extends AbstractChannel
{
    /**
     * 流水类型配置路径。
     * AbstractChannel::types() 会 config() 读取,无需再写 types()。
     * 例:linkage.wallet_flow_type.recharge.asset = 'add@wallet_money,...'
     */
    protected string $typesConfig = 'linkage.wallet_flow_type';

    /**
     * DSL 在类型配置 / $input 上的字段名。
     * 默认读 typeConfig['asset'],也可用 $input['asset'] 覆盖本次规则。
     */
    protected string $actionKey = 'asset';

    /**
     * 变体 DSL 字段名(如月结规则)。
     * 当 variantWhen() 为 true 时,改读 typeConfig['asset1']。
     */
    protected string $variantActionKey = 'asset1';

    /**
     * 渠道名,必须与 config/autoload/asset.php 里 channels 的 key 一致。
     */
    public function name(): string
    {
        return 'wallet';
    }

    /**
     * 流水表 Model;用于生成单号、create 流水记录。
     */
    public function flowModel(): string
    {
        return WalletFlow::class;
    }

    /**
     * 余额字段列表。
     * - 变更前:从钱包快照写入流水
     * - 变更后:apply() 默认按此列表回写钱包
     */
    public function balanceFields(): array
    {
        return [
            'wallet_money', 'no_wallet_money', 'recharge_amount',
            'fee_amount', 'service_amount',
            'use_facebook_amount_spent', 'use_tiktok_amount_spent',
            'facebook_service_amount', 'tiktok_service_amount',
        ];
    }

    /**
     * 锁定余额主体(必须 lockForUpdate)。
     * 钱包:按企业找到对应 Wallet 行并加锁。
     */
    public function lock(array $input): Model
    {
        $company = Company::query()->find($input['company_id'] ?? 0);
        if (! $company) {
            throw new AssetException('企业不存在');
        }

        return Wallet::query()
            ->where('type', $company->type)
            ->where('company_id', $company->id)
            ->lockForUpdate()
            ->firstOrFail();
    }

    /**
     * 是否启用变体 DSL(asset1)。
     * 有 wallet_type(如月结)时用 asset1,否则用 asset。
     */
    protected function variantWhen(array $input, array $typeConfig): bool
    {
        return ! empty($input['wallet_type']);
    }

    /**
     * 流水附加字段(非余额)。
     * 在 DSL 计算前合并进流水数据,如 company_id / source / is_show。
     */
    public function attributes(Model $owner, array $input, array $typeConfig): array
    {
        $company = Company::query()->findOrFail($input['company_id'] ?? 0);

        return [
            'company_id' => $company->id,
            'account_id' => $input['account_id'] ?? 0,
            'wallet_type' => $company->type,
            'source' => $input['source'] ?? 0,
            'is_show' => $input['is_show'] ?? 1,
        ];
    }

    /**
     * DSL 算完、写库前的校验;可改 $flow(引用传递)。
     * 抛异常则整笔事务回滚。
     */
    public function assert(Model $owner, array $input, array $typeConfig, array &$flow): void
    {
        $company = Company::query()->find($input['company_id'] ?? 0);
        $type = $input['type'] ?? '';

        // 预付企业做账户充值时,可用余额不能为负
        if ($company && ! $company->type && ($flow['wallet_money'] ?? 0) < 0 && $type === 'account_recharge') {
            throw new AssetException('可用金额不足');
        }
        // 可用余额未变则客户端不展示该流水
        if ($owner->wallet_money == ($flow['wallet_money'] ?? null)) {
            $flow['is_show'] = 0;
        }
    }

    /**
     * 流水 create 后,把结果回写钱包并 save。
     * 此处额外用 fee_money 扣减总充值(业务特殊逻辑)。
     */
    public function apply(Model $owner, Model $flow, array $input): void
    {
        $fee = (float) ($input['fee_money'] ?? 0);
        foreach ($this->balanceFields() as $field) {
            $owner->{$field} = $flow->{$field};
        }
        $owner->recharge_amount = $flow->recharge_amount - $fee;
        $owner->save();
    }

    /**
     * 本渠道落库后的同事务后续动作(钱包通常不需要)。
     * 账户渠道可在此 changeInTransaction('wallet', ...) 联动钱包。
     */
    // public function after(Model $owner, ?Model $flow, array $input, array $typeConfig): void {}
}

账户联动钱包写在 AccountChannel::after():

public function after(Model $owner, ?Model $flow, array $input, array $typeConfig): void
{
    // 业务判断后:
    $this->assets->changeInTransaction('wallet', [
        'user_id' => $input['user_id'],
        'company_id' => $owner->company_id,
        // ...
        'type' => $typeConfig['wallet_type'] ?? null,
        'money' => $input['money'],
    ]);
}

(构造注入 AssetManager $assets。)

调用

wallet_change([
    'user_id' => 1,
    'company_id' => 10,
    'type' => 'recharge',
    'money' => 100,
]);

asset_change('wallet', [...]);

请删除业务项目 Helper 里旧的同名 wallet_change / account_change,避免与包 Functions.php 冲突。

License

MIT