koishi-plugin-monetary-bank 1.1.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/index.d.ts +85 -10
- package/lib/index.js +585 -113
- package/package.json +1 -1
- package/readme.md +76 -5
package/lib/index.d.ts
CHANGED
|
@@ -3,29 +3,104 @@ export declare const name = "monetary-bank";
|
|
|
3
3
|
export interface Config {
|
|
4
4
|
defaultCurrency?: string;
|
|
5
5
|
debug?: boolean;
|
|
6
|
+
enableInterest?: boolean;
|
|
7
|
+
demandInterest?: {
|
|
8
|
+
enabled?: boolean;
|
|
9
|
+
rate?: number;
|
|
10
|
+
cycle?: 'day' | 'week' | 'month';
|
|
11
|
+
};
|
|
12
|
+
fixedInterest?: Array<{
|
|
13
|
+
name?: string;
|
|
14
|
+
rate?: number;
|
|
15
|
+
cycle?: 'day' | 'week' | 'month';
|
|
16
|
+
}>;
|
|
6
17
|
}
|
|
7
18
|
export declare const Config: Schema<Config>;
|
|
8
19
|
export declare const inject: {
|
|
9
20
|
required: string[];
|
|
10
21
|
};
|
|
11
22
|
/**
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
* 字段约定:
|
|
15
|
-
* - uid: 用户唯一 ID(由上层用户系统提供)
|
|
16
|
-
* - currency: 货币标识(例如 "coin")
|
|
17
|
-
* - value: 存款数值(数值类型)
|
|
18
|
-
* 注意:此处为类型声明与文档说明,不会主动修改数据库结构。
|
|
23
|
+
* 数据库表结构声明
|
|
24
|
+
* monetary_bank_int 表用于记录所有存款(活期和定期)
|
|
19
25
|
*/
|
|
20
26
|
declare module 'koishi' {
|
|
21
27
|
interface Tables {
|
|
22
|
-
|
|
28
|
+
monetary_bank_int: MonetaryBankInterest;
|
|
23
29
|
}
|
|
30
|
+
interface Context {
|
|
31
|
+
monetaryBank: MonetaryBankAPI;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* 银行API接口类
|
|
36
|
+
* 提供给其他插件调用的银行操作接口
|
|
37
|
+
*/
|
|
38
|
+
export declare class MonetaryBankAPI {
|
|
39
|
+
private ctx;
|
|
40
|
+
private config;
|
|
41
|
+
constructor(ctx: Context, config: Config);
|
|
42
|
+
/**
|
|
43
|
+
* 查询用户银行余额
|
|
44
|
+
* @param uid 用户ID
|
|
45
|
+
* @param currency 货币类型
|
|
46
|
+
* @returns 包含总资产、活期、定期的余额信息
|
|
47
|
+
*/
|
|
48
|
+
getBalance(uid: number, currency: string): Promise<{
|
|
49
|
+
total: number;
|
|
50
|
+
demand: number;
|
|
51
|
+
fixed: number;
|
|
52
|
+
}>;
|
|
53
|
+
/**
|
|
54
|
+
* 存款(从用户现金存入银行,自动转为活期)
|
|
55
|
+
* @param uid 用户ID
|
|
56
|
+
* @param currency 货币类型
|
|
57
|
+
* @param amount 存款金额
|
|
58
|
+
* @returns 成功返回 { success: true, newCash, newBalance },失败返回 { success: false, error }
|
|
59
|
+
*/
|
|
60
|
+
deposit(uid: number, currency: string, amount: number): Promise<{
|
|
61
|
+
success: boolean;
|
|
62
|
+
newCash?: number;
|
|
63
|
+
newBalance?: {
|
|
64
|
+
total: number;
|
|
65
|
+
demand: number;
|
|
66
|
+
fixed: number;
|
|
67
|
+
};
|
|
68
|
+
error?: string;
|
|
69
|
+
}>;
|
|
70
|
+
/**
|
|
71
|
+
* 取款(从银行取出到用户现金,仅可取活期)
|
|
72
|
+
* @param uid 用户ID
|
|
73
|
+
* @param currency 货币类型
|
|
74
|
+
* @param amount 取款金额
|
|
75
|
+
* @returns 成功返回 { success: true, newCash, newBalance },失败返回 { success: false, error }
|
|
76
|
+
*/
|
|
77
|
+
withdraw(uid: number, currency: string, amount: number): Promise<{
|
|
78
|
+
success: boolean;
|
|
79
|
+
newCash?: number;
|
|
80
|
+
newBalance?: {
|
|
81
|
+
total: number;
|
|
82
|
+
demand: number;
|
|
83
|
+
fixed: number;
|
|
84
|
+
};
|
|
85
|
+
error?: string;
|
|
86
|
+
}>;
|
|
24
87
|
}
|
|
25
|
-
|
|
88
|
+
/**
|
|
89
|
+
* 利息记录表结构
|
|
90
|
+
* 用于记录每笔存款的利息计算信息(活期和定期)
|
|
91
|
+
*/
|
|
92
|
+
export interface MonetaryBankInterest {
|
|
93
|
+
id: number;
|
|
26
94
|
uid: number;
|
|
27
95
|
currency: string;
|
|
28
|
-
|
|
96
|
+
amount: number;
|
|
97
|
+
type: 'demand' | 'fixed';
|
|
98
|
+
rate: number;
|
|
99
|
+
cycle: 'day' | 'week' | 'month';
|
|
100
|
+
settlementDate: Date;
|
|
101
|
+
extendRequested: boolean;
|
|
102
|
+
nextRate?: number;
|
|
103
|
+
nextCycle?: 'day' | 'week' | 'month';
|
|
29
104
|
}
|
|
30
105
|
/**
|
|
31
106
|
* 插件主函数
|
package/lib/index.js
CHANGED
|
@@ -21,6 +21,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
21
21
|
var src_exports = {};
|
|
22
22
|
__export(src_exports, {
|
|
23
23
|
Config: () => Config,
|
|
24
|
+
MonetaryBankAPI: () => MonetaryBankAPI,
|
|
24
25
|
apply: () => apply,
|
|
25
26
|
inject: () => inject,
|
|
26
27
|
name: () => name
|
|
@@ -30,7 +31,21 @@ var import_koishi = require("koishi");
|
|
|
30
31
|
var name = "monetary-bank";
|
|
31
32
|
var Config = import_koishi.Schema.object({
|
|
32
33
|
defaultCurrency: import_koishi.Schema.string().description("默认货币名称").default("coin"),
|
|
33
|
-
debug: import_koishi.Schema.boolean().description("开启调试日志(显示 info/success 等非 error/warn 日志)").default(true)
|
|
34
|
+
debug: import_koishi.Schema.boolean().description("开启调试日志(显示 info/success 等非 error/warn 日志)").default(true),
|
|
35
|
+
enableInterest: import_koishi.Schema.boolean().description("是否启用定期利息功能").default(false),
|
|
36
|
+
demandInterest: import_koishi.Schema.object({
|
|
37
|
+
enabled: import_koishi.Schema.boolean().description("是否启用活期利息").default(true),
|
|
38
|
+
rate: import_koishi.Schema.number().description("活期利率(%)").default(0.25),
|
|
39
|
+
cycle: import_koishi.Schema.union(["day", "week", "month"]).description("结算周期(day=日,week=周,month=月)").default("day")
|
|
40
|
+
}).description("活期利息配置"),
|
|
41
|
+
fixedInterest: import_koishi.Schema.array(import_koishi.Schema.object({
|
|
42
|
+
name: import_koishi.Schema.string().description("方案名称").required(),
|
|
43
|
+
rate: import_koishi.Schema.number().description("利率(%)").required(),
|
|
44
|
+
cycle: import_koishi.Schema.union(["day", "week", "month"]).description("结算周期(day=日,week=周,month=月)").required()
|
|
45
|
+
})).description("定期利息方案配置").default([
|
|
46
|
+
{ name: "周定期", rate: 4.35, cycle: "week" },
|
|
47
|
+
{ name: "月定期", rate: 50, cycle: "month" }
|
|
48
|
+
])
|
|
34
49
|
});
|
|
35
50
|
var inject = {
|
|
36
51
|
required: ["database"]
|
|
@@ -51,72 +66,122 @@ function logSuccess(...args) {
|
|
|
51
66
|
else logger.info && logger.info.apply(logger, args);
|
|
52
67
|
}
|
|
53
68
|
__name(logSuccess, "logSuccess");
|
|
69
|
+
var MonetaryBankAPI = class {
|
|
70
|
+
constructor(ctx, config) {
|
|
71
|
+
this.ctx = ctx;
|
|
72
|
+
this.config = config;
|
|
73
|
+
}
|
|
74
|
+
static {
|
|
75
|
+
__name(this, "MonetaryBankAPI");
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* 查询用户银行余额
|
|
79
|
+
* @param uid 用户ID
|
|
80
|
+
* @param currency 货币类型
|
|
81
|
+
* @returns 包含总资产、活期、定期的余额信息
|
|
82
|
+
*/
|
|
83
|
+
async getBalance(uid, currency) {
|
|
84
|
+
return await getBankBalance(this.ctx, uid, currency);
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* 存款(从用户现金存入银行,自动转为活期)
|
|
88
|
+
* @param uid 用户ID
|
|
89
|
+
* @param currency 货币类型
|
|
90
|
+
* @param amount 存款金额
|
|
91
|
+
* @returns 成功返回 { success: true, newCash, newBalance },失败返回 { success: false, error }
|
|
92
|
+
*/
|
|
93
|
+
async deposit(uid, currency, amount) {
|
|
94
|
+
try {
|
|
95
|
+
if (!amount || amount <= 0) {
|
|
96
|
+
return { success: false, error: "金额必须大于0" };
|
|
97
|
+
}
|
|
98
|
+
let cash = await getMonetaryBalance(this.ctx, uid, currency);
|
|
99
|
+
if (cash === null) {
|
|
100
|
+
const created = await createMonetaryUser(this.ctx, uid, currency);
|
|
101
|
+
if (!created) return { success: false, error: "无法验证/创建主货币账户" };
|
|
102
|
+
cash = 0;
|
|
103
|
+
}
|
|
104
|
+
if (cash < amount) {
|
|
105
|
+
return { success: false, error: `现金不足,当前现金:${cash} ${currency}` };
|
|
106
|
+
}
|
|
107
|
+
const newCash = await changeMonetary(this.ctx, uid, currency, -amount);
|
|
108
|
+
if (newCash === null) {
|
|
109
|
+
return { success: false, error: "扣除现金失败" };
|
|
110
|
+
}
|
|
111
|
+
const demandConfig = this.config.demandInterest || { enabled: true, rate: 0.25, cycle: "day" };
|
|
112
|
+
const settlementDate = calculateNextSettlementDate(demandConfig.cycle, true);
|
|
113
|
+
await this.ctx.database.create("monetary_bank_int", {
|
|
114
|
+
uid,
|
|
115
|
+
currency,
|
|
116
|
+
amount,
|
|
117
|
+
type: "demand",
|
|
118
|
+
rate: demandConfig.rate || 0.25,
|
|
119
|
+
cycle: demandConfig.cycle || "day",
|
|
120
|
+
settlementDate,
|
|
121
|
+
extendRequested: false
|
|
122
|
+
});
|
|
123
|
+
const newBalance = await getBankBalance(this.ctx, uid, currency);
|
|
124
|
+
logInfo(`API存款: uid=${uid}, amount=${amount}`);
|
|
125
|
+
return { success: true, newCash, newBalance };
|
|
126
|
+
} catch (error) {
|
|
127
|
+
logger.error("API存款失败:", error);
|
|
128
|
+
return { success: false, error: "存款操作失败" };
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* 取款(从银行取出到用户现金,仅可取活期)
|
|
133
|
+
* @param uid 用户ID
|
|
134
|
+
* @param currency 货币类型
|
|
135
|
+
* @param amount 取款金额
|
|
136
|
+
* @returns 成功返回 { success: true, newCash, newBalance },失败返回 { success: false, error }
|
|
137
|
+
*/
|
|
138
|
+
async withdraw(uid, currency, amount) {
|
|
139
|
+
try {
|
|
140
|
+
if (!amount || amount <= 0) {
|
|
141
|
+
return { success: false, error: "金额必须大于0" };
|
|
142
|
+
}
|
|
143
|
+
const balance = await getBankBalance(this.ctx, uid, currency);
|
|
144
|
+
if (balance.demand < amount) {
|
|
145
|
+
return { success: false, error: `可用余额不足,当前活期:${balance.demand} ${currency}` };
|
|
146
|
+
}
|
|
147
|
+
let remaining = amount;
|
|
148
|
+
const demandRecords = await this.ctx.database.select("monetary_bank_int").where({ uid, currency, type: "demand" }).orderBy("settlementDate", "asc").execute();
|
|
149
|
+
for (const record of demandRecords) {
|
|
150
|
+
if (remaining <= 0) break;
|
|
151
|
+
if (record.amount <= remaining) {
|
|
152
|
+
remaining -= record.amount;
|
|
153
|
+
await this.ctx.database.remove("monetary_bank_int", { id: record.id });
|
|
154
|
+
} else {
|
|
155
|
+
const newAmount = record.amount - remaining;
|
|
156
|
+
await this.ctx.database.set("monetary_bank_int", { id: record.id }, { amount: newAmount });
|
|
157
|
+
remaining = 0;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
const newCash = await changeMonetary(this.ctx, uid, currency, amount);
|
|
161
|
+
if (newCash === null) {
|
|
162
|
+
return { success: false, error: "转账到现金失败" };
|
|
163
|
+
}
|
|
164
|
+
const newBalance = await getBankBalance(this.ctx, uid, currency);
|
|
165
|
+
logInfo(`API取款: uid=${uid}, amount=${amount}`);
|
|
166
|
+
return { success: true, newCash, newBalance };
|
|
167
|
+
} catch (error) {
|
|
168
|
+
logger.error("API取款失败:", error);
|
|
169
|
+
return { success: false, error: "取款操作失败" };
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
};
|
|
54
173
|
async function initDatabase(ctx) {
|
|
55
174
|
try {
|
|
56
175
|
const tables = await ctx.database.tables;
|
|
57
|
-
if (tables && "
|
|
58
|
-
logInfo("检测到
|
|
59
|
-
const tableFields = tables["monetary_bank"];
|
|
60
|
-
const normalizeColumns = /* @__PURE__ */ __name((raw) => {
|
|
61
|
-
const map = {};
|
|
62
|
-
if (!raw) return map;
|
|
63
|
-
if (Array.isArray(raw)) {
|
|
64
|
-
for (const col of raw) {
|
|
65
|
-
if (!col) continue;
|
|
66
|
-
if (col.name && col.type) map[col.name] = String(col.type);
|
|
67
|
-
else if (col.field && col.type) map[col.field] = String(col.type);
|
|
68
|
-
else if (typeof col === "string") map[col] = "unknown";
|
|
69
|
-
}
|
|
70
|
-
return map;
|
|
71
|
-
}
|
|
72
|
-
if (raw.columns && typeof raw.columns === "object") {
|
|
73
|
-
for (const [k, v] of Object.entries(raw.columns)) {
|
|
74
|
-
if (v && typeof v === "object") {
|
|
75
|
-
const vv = v;
|
|
76
|
-
map[k] = (vv.type || vv.dataType || vv.typeName || JSON.stringify(vv)).toString();
|
|
77
|
-
} else {
|
|
78
|
-
map[k] = String(v);
|
|
79
|
-
}
|
|
80
|
-
}
|
|
81
|
-
return map;
|
|
82
|
-
}
|
|
83
|
-
if (typeof raw === "object") {
|
|
84
|
-
for (const [k, v] of Object.entries(raw)) {
|
|
85
|
-
if (v && typeof v === "object") {
|
|
86
|
-
if (v.type && typeof v.type === "string") map[k] = v.type;
|
|
87
|
-
else if (v.type && typeof v.type === "object") map[k] = JSON.stringify(v.type);
|
|
88
|
-
else if (v.dataType) map[k] = v.dataType;
|
|
89
|
-
else map[k] = JSON.stringify(v);
|
|
90
|
-
} else {
|
|
91
|
-
map[k] = String(v);
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
return map;
|
|
95
|
-
}
|
|
96
|
-
return map;
|
|
97
|
-
}, "normalizeColumns");
|
|
98
|
-
const columns = normalizeColumns(tableFields);
|
|
99
|
-
logInfo("monetary_bank 表结构(规范化):", columns);
|
|
100
|
-
let structureValid = true;
|
|
101
|
-
const missingFields = [];
|
|
102
|
-
const incompatibleFields = [];
|
|
103
|
-
if (!structureValid) {
|
|
104
|
-
logger.error("❌ monetary_bank 表结构与插件要求不一致!");
|
|
105
|
-
if (missingFields.length > 0) {
|
|
106
|
-
logger.error(` 缺少字段: ${missingFields.join(", ")}`);
|
|
107
|
-
}
|
|
108
|
-
if (incompatibleFields.length > 0) {
|
|
109
|
-
logger.error(` 字段类型不兼容: ${incompatibleFields.join(", ")}`);
|
|
110
|
-
}
|
|
111
|
-
logger.error(" 插件将不会加载以防止数据损坏。");
|
|
112
|
-
logger.error(" 请检查数据库表结构或删除现有表后重启插件。");
|
|
113
|
-
return false;
|
|
114
|
-
}
|
|
115
|
-
logSuccess("✓ 表结构验证通过");
|
|
116
|
-
return true;
|
|
176
|
+
if (tables && "monetary_bank_int" in tables) {
|
|
177
|
+
logInfo("检测到 monetary_bank_int 表已存在");
|
|
117
178
|
} else {
|
|
118
|
-
logInfo("
|
|
119
|
-
ctx.model.extend("
|
|
179
|
+
logInfo("monetary_bank_int 表不存在,正在创建...");
|
|
180
|
+
ctx.model.extend("monetary_bank_int", {
|
|
181
|
+
id: {
|
|
182
|
+
type: "unsigned",
|
|
183
|
+
nullable: false
|
|
184
|
+
},
|
|
120
185
|
uid: {
|
|
121
186
|
type: "unsigned",
|
|
122
187
|
nullable: false
|
|
@@ -125,19 +190,45 @@ async function initDatabase(ctx) {
|
|
|
125
190
|
type: "string",
|
|
126
191
|
nullable: false
|
|
127
192
|
},
|
|
128
|
-
|
|
193
|
+
amount: {
|
|
129
194
|
type: "unsigned",
|
|
130
195
|
nullable: false
|
|
196
|
+
},
|
|
197
|
+
type: {
|
|
198
|
+
type: "string",
|
|
199
|
+
nullable: false
|
|
200
|
+
},
|
|
201
|
+
rate: {
|
|
202
|
+
type: "double",
|
|
203
|
+
nullable: false
|
|
204
|
+
},
|
|
205
|
+
cycle: {
|
|
206
|
+
type: "string",
|
|
207
|
+
nullable: false
|
|
208
|
+
},
|
|
209
|
+
settlementDate: {
|
|
210
|
+
type: "timestamp",
|
|
211
|
+
nullable: false
|
|
212
|
+
},
|
|
213
|
+
extendRequested: {
|
|
214
|
+
type: "boolean",
|
|
215
|
+
nullable: false
|
|
216
|
+
},
|
|
217
|
+
nextRate: {
|
|
218
|
+
type: "double",
|
|
219
|
+
nullable: true
|
|
220
|
+
},
|
|
221
|
+
nextCycle: {
|
|
222
|
+
type: "string",
|
|
223
|
+
nullable: true
|
|
131
224
|
}
|
|
132
225
|
}, {
|
|
133
|
-
primary:
|
|
134
|
-
|
|
135
|
-
autoInc: false
|
|
136
|
-
// 不自增
|
|
226
|
+
primary: "id",
|
|
227
|
+
autoInc: true
|
|
137
228
|
});
|
|
138
|
-
logSuccess("✓
|
|
139
|
-
return true;
|
|
229
|
+
logSuccess("✓ monetary_bank_int 表创建成功");
|
|
140
230
|
}
|
|
231
|
+
return true;
|
|
141
232
|
} catch (error) {
|
|
142
233
|
logger.error("初始化数据库时发生错误:", error);
|
|
143
234
|
return false;
|
|
@@ -209,6 +300,185 @@ async function changeMonetary(ctx, uid, currency, delta) {
|
|
|
209
300
|
}
|
|
210
301
|
}
|
|
211
302
|
__name(changeMonetary, "changeMonetary");
|
|
303
|
+
function calculateNextSettlementDate(cycle, isNew = false) {
|
|
304
|
+
const now = /* @__PURE__ */ new Date();
|
|
305
|
+
const settlement = new Date(now);
|
|
306
|
+
settlement.setHours(0, 0, 0, 0);
|
|
307
|
+
if (isNew) {
|
|
308
|
+
settlement.setDate(settlement.getDate() + 1);
|
|
309
|
+
}
|
|
310
|
+
switch (cycle) {
|
|
311
|
+
case "day":
|
|
312
|
+
settlement.setDate(settlement.getDate() + 1);
|
|
313
|
+
break;
|
|
314
|
+
case "week":
|
|
315
|
+
settlement.setDate(settlement.getDate() + 7);
|
|
316
|
+
break;
|
|
317
|
+
case "month":
|
|
318
|
+
settlement.setDate(settlement.getDate() + 30);
|
|
319
|
+
break;
|
|
320
|
+
}
|
|
321
|
+
return settlement;
|
|
322
|
+
}
|
|
323
|
+
__name(calculateNextSettlementDate, "calculateNextSettlementDate");
|
|
324
|
+
async function scheduleInterestSettlement(ctx, config) {
|
|
325
|
+
if (!config.enableInterest) return;
|
|
326
|
+
function getMillisecondsUntilMidnight() {
|
|
327
|
+
const now = /* @__PURE__ */ new Date();
|
|
328
|
+
const tomorrow = new Date(now);
|
|
329
|
+
tomorrow.setDate(tomorrow.getDate() + 1);
|
|
330
|
+
tomorrow.setHours(0, 0, 0, 0);
|
|
331
|
+
return tomorrow.getTime() - now.getTime();
|
|
332
|
+
}
|
|
333
|
+
__name(getMillisecondsUntilMidnight, "getMillisecondsUntilMidnight");
|
|
334
|
+
async function performSettlement() {
|
|
335
|
+
try {
|
|
336
|
+
logInfo("开始执行利息结算任务...");
|
|
337
|
+
const today = /* @__PURE__ */ new Date();
|
|
338
|
+
today.setHours(0, 0, 0, 0);
|
|
339
|
+
const records = await ctx.database.get("monetary_bank_int", {});
|
|
340
|
+
for (const record of records) {
|
|
341
|
+
const settlementDate = new Date(record.settlementDate);
|
|
342
|
+
settlementDate.setHours(0, 0, 0, 0);
|
|
343
|
+
if (settlementDate <= today) {
|
|
344
|
+
await settleInterest(ctx, config, record);
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
await mergeDemandRecords(ctx);
|
|
348
|
+
logSuccess("利息结算任务执行完成");
|
|
349
|
+
} catch (error) {
|
|
350
|
+
logger.error("利息结算任务执行失败:", error);
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
__name(performSettlement, "performSettlement");
|
|
354
|
+
setTimeout(async () => {
|
|
355
|
+
await performSettlement();
|
|
356
|
+
setInterval(async () => {
|
|
357
|
+
await performSettlement();
|
|
358
|
+
}, 24 * 60 * 60 * 1e3);
|
|
359
|
+
}, getMillisecondsUntilMidnight());
|
|
360
|
+
logInfo("利息结算定时任务已启动,将在每日0点执行");
|
|
361
|
+
}
|
|
362
|
+
__name(scheduleInterestSettlement, "scheduleInterestSettlement");
|
|
363
|
+
async function settleInterest(ctx, config, record) {
|
|
364
|
+
try {
|
|
365
|
+
const interest = Math.floor(record.amount * record.rate / 100);
|
|
366
|
+
if (record.type === "demand") {
|
|
367
|
+
const newAmount = record.amount + interest;
|
|
368
|
+
const nextSettlement = calculateNextSettlementDate(record.cycle, false);
|
|
369
|
+
await ctx.database.set("monetary_bank_int", { id: record.id }, {
|
|
370
|
+
amount: newAmount,
|
|
371
|
+
settlementDate: nextSettlement
|
|
372
|
+
});
|
|
373
|
+
logInfo(`活期利息结算: uid=${record.uid}, 本金=${record.amount}, 利息=${interest}, 新本金=${newAmount}`);
|
|
374
|
+
} else {
|
|
375
|
+
if (record.extendRequested && record.nextRate !== void 0 && record.nextCycle) {
|
|
376
|
+
const newAmount = record.amount + interest;
|
|
377
|
+
const nextSettlement = calculateNextSettlementDate(record.nextCycle, false);
|
|
378
|
+
await ctx.database.set("monetary_bank_int", { id: record.id }, {
|
|
379
|
+
amount: newAmount,
|
|
380
|
+
rate: record.nextRate,
|
|
381
|
+
cycle: record.nextCycle,
|
|
382
|
+
settlementDate: nextSettlement,
|
|
383
|
+
extendRequested: false,
|
|
384
|
+
nextRate: null,
|
|
385
|
+
nextCycle: null
|
|
386
|
+
});
|
|
387
|
+
logInfo(`定期延期结算: uid=${record.uid}, 本金=${record.amount}, 利息=${interest}, 新本金=${newAmount}, 新利率=${record.nextRate}%, 新周期=${record.nextCycle}`);
|
|
388
|
+
} else {
|
|
389
|
+
await ctx.database.remove("monetary_bank_int", { id: record.id });
|
|
390
|
+
const totalAmount = record.amount + interest;
|
|
391
|
+
const demandConfig = config.demandInterest || { enabled: true, rate: 0.25, cycle: "day" };
|
|
392
|
+
if (demandConfig.enabled) {
|
|
393
|
+
const nextSettlement = calculateNextSettlementDate(demandConfig.cycle, false);
|
|
394
|
+
await ctx.database.create("monetary_bank_int", {
|
|
395
|
+
uid: record.uid,
|
|
396
|
+
currency: record.currency,
|
|
397
|
+
amount: totalAmount,
|
|
398
|
+
type: "demand",
|
|
399
|
+
rate: demandConfig.rate,
|
|
400
|
+
cycle: demandConfig.cycle,
|
|
401
|
+
settlementDate: nextSettlement,
|
|
402
|
+
extendRequested: false
|
|
403
|
+
});
|
|
404
|
+
}
|
|
405
|
+
logInfo(`定期到期结算: uid=${record.uid}, 本金=${record.amount}, 利息=${interest}, 转活期=${totalAmount}`);
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
} catch (error) {
|
|
409
|
+
logger.error(`结算利息失败 id=${record.id}:`, error);
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
__name(settleInterest, "settleInterest");
|
|
413
|
+
async function getBankBalance(ctx, uid, currency) {
|
|
414
|
+
const records = await ctx.database.get("monetary_bank_int", { uid, currency });
|
|
415
|
+
let demand = 0;
|
|
416
|
+
let fixed = 0;
|
|
417
|
+
for (const record of records) {
|
|
418
|
+
if (record.type === "demand") {
|
|
419
|
+
demand += record.amount;
|
|
420
|
+
} else {
|
|
421
|
+
fixed += record.amount;
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
return { total: demand + fixed, demand, fixed };
|
|
425
|
+
}
|
|
426
|
+
__name(getBankBalance, "getBankBalance");
|
|
427
|
+
async function mergeDemandRecords(ctx) {
|
|
428
|
+
try {
|
|
429
|
+
const records = await ctx.database.select("monetary_bank_int").where({ type: "demand" }).execute();
|
|
430
|
+
const groups = {};
|
|
431
|
+
for (const r of records) {
|
|
432
|
+
const sd = new Date(r.settlementDate);
|
|
433
|
+
sd.setHours(0, 0, 0, 0);
|
|
434
|
+
const key = `${r.uid}|${r.currency}|${sd.getTime()}|${r.rate}|${r.cycle}`;
|
|
435
|
+
if (!groups[key]) {
|
|
436
|
+
groups[key] = { ids: [], uid: r.uid, currency: r.currency, settlementDate: sd, rate: r.rate, cycle: r.cycle, total: 0 };
|
|
437
|
+
}
|
|
438
|
+
groups[key].ids.push(r.id);
|
|
439
|
+
groups[key].total += Number(r.amount || 0);
|
|
440
|
+
}
|
|
441
|
+
for (const key of Object.keys(groups)) {
|
|
442
|
+
const g = groups[key];
|
|
443
|
+
if (g.ids.length <= 1) continue;
|
|
444
|
+
for (const id of g.ids) {
|
|
445
|
+
try {
|
|
446
|
+
await ctx.database.remove("monetary_bank_int", { id });
|
|
447
|
+
} catch (e) {
|
|
448
|
+
logger.warn(`合并活期记录时删除 id=${id} 失败:`, e);
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
try {
|
|
452
|
+
await ctx.database.create("monetary_bank_int", {
|
|
453
|
+
uid: g.uid,
|
|
454
|
+
currency: g.currency,
|
|
455
|
+
amount: g.total,
|
|
456
|
+
type: "demand",
|
|
457
|
+
rate: g.rate,
|
|
458
|
+
cycle: g.cycle,
|
|
459
|
+
settlementDate: g.settlementDate,
|
|
460
|
+
extendRequested: false
|
|
461
|
+
});
|
|
462
|
+
logInfo(`合并活期记录: uid=${g.uid}, currency=${g.currency}, settlementDate=${g.settlementDate.toISOString()}, 合并后金额=${g.total}`);
|
|
463
|
+
} catch (e) {
|
|
464
|
+
logger.error("创建合并后活期记录失败:", e);
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
} catch (err) {
|
|
468
|
+
logger.error("合并活期记录失败:", err);
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
__name(mergeDemandRecords, "mergeDemandRecords");
|
|
472
|
+
function generateDepositConfirmMessage(amount, currency, cash) {
|
|
473
|
+
return `您将存入 ${amount} ${currency} 到银行,当前现金:${cash} ${currency}。
|
|
474
|
+
确认操作请回复 yes 或 y,取消请回复其他内容。`;
|
|
475
|
+
}
|
|
476
|
+
__name(generateDepositConfirmMessage, "generateDepositConfirmMessage");
|
|
477
|
+
function generateWithdrawConfirmMessage(amount, currency, bankBalance) {
|
|
478
|
+
return `您将从银行取出 ${amount} ${currency},当前存款:${bankBalance} ${currency}。
|
|
479
|
+
确认操作请回复 yes 或 y,取消请回复其他内容。`;
|
|
480
|
+
}
|
|
481
|
+
__name(generateWithdrawConfirmMessage, "generateWithdrawConfirmMessage");
|
|
212
482
|
async function apply(ctx, config) {
|
|
213
483
|
debugEnabled = typeof config?.debug === "boolean" ? config.debug : true;
|
|
214
484
|
const dbInitSuccess = await initDatabase(ctx);
|
|
@@ -217,90 +487,292 @@ async function apply(ctx, config) {
|
|
|
217
487
|
return;
|
|
218
488
|
}
|
|
219
489
|
logSuccess("✓ monetary-bank 插件加载成功");
|
|
220
|
-
ctx.
|
|
490
|
+
ctx.monetaryBank = new MonetaryBankAPI(ctx, config);
|
|
491
|
+
ctx.command("bank.bal [currency:string]", "查询银行存款").userFields(["id"]).option("currency", "-c <currency:string> 指定货币类型").action(async ({ session, options }, currencyArg) => {
|
|
221
492
|
const uid = session.user.id;
|
|
222
|
-
const currency = options?.currency || config.defaultCurrency || "coin";
|
|
493
|
+
const currency = options?.currency || currencyArg || config.defaultCurrency || "coin";
|
|
223
494
|
try {
|
|
224
|
-
const
|
|
225
|
-
|
|
226
|
-
currency
|
|
227
|
-
});
|
|
228
|
-
if (!records || records.length === 0) {
|
|
495
|
+
const balance = await ctx.monetaryBank.getBalance(uid, currency);
|
|
496
|
+
if (balance.total === 0) {
|
|
229
497
|
return `您在银行中还没有 ${currency} 存款。`;
|
|
230
498
|
}
|
|
231
|
-
|
|
232
|
-
|
|
499
|
+
return `您的银行资产:
|
|
500
|
+
总资产:${balance.total} ${currency}
|
|
501
|
+
活期资产(可用):${balance.demand} ${currency}
|
|
502
|
+
不可用资产(定期):${balance.fixed} ${currency}`;
|
|
233
503
|
} catch (error) {
|
|
234
504
|
logger.error("查询存款失败:", error);
|
|
235
505
|
return "查询失败,请稍后再试。";
|
|
236
506
|
}
|
|
237
507
|
});
|
|
238
|
-
ctx.command("bank.in
|
|
239
|
-
if (!amount || amount <= 0) {
|
|
240
|
-
return "请输入有效的存款金额(正整数)。";
|
|
241
|
-
}
|
|
508
|
+
ctx.command("bank.in [amount:string]", "存入货币到银行活期").userFields(["id"]).option("currency", "-c <currency:string> 指定货币类型").option("yes", "-y 跳过确认直接执行").action(async ({ session, options }, amount) => {
|
|
242
509
|
const uid = session.user.id;
|
|
243
510
|
const currency = options?.currency || config.defaultCurrency || "coin";
|
|
244
511
|
try {
|
|
512
|
+
if (!amount) {
|
|
513
|
+
await session.send(`请输入存款金额(正整数或 all):`);
|
|
514
|
+
const amountInput2 = await session.prompt(3e4);
|
|
515
|
+
if (!amountInput2) return "操作超时,已取消存款。";
|
|
516
|
+
amount = amountInput2.trim();
|
|
517
|
+
}
|
|
245
518
|
let cash = await getMonetaryBalance(ctx, uid, currency);
|
|
246
519
|
if (cash === null) {
|
|
247
520
|
const created = await createMonetaryUser(ctx, uid, currency);
|
|
248
521
|
if (!created) return "无法验证/创建主货币账户(monetary),请联系管理员。";
|
|
249
522
|
cash = 0;
|
|
250
523
|
}
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
if (
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
if (!records || records.length === 0) {
|
|
257
|
-
await ctx.database.create("monetary_bank", { uid, currency, value: amount });
|
|
258
|
-
newValue = amount;
|
|
259
|
-
logInfo(`首次存款,创建 monetary_bank 记录 uid=${uid}, currency=${currency}, value=${amount}`);
|
|
524
|
+
const amountInput = String(amount || "").trim().toLowerCase();
|
|
525
|
+
let amountNum;
|
|
526
|
+
if (amountInput === "all") {
|
|
527
|
+
amountNum = Math.floor(cash);
|
|
528
|
+
if (amountNum <= 0) return `没有可存入的现金。当前现金:${cash} ${currency}`;
|
|
260
529
|
} else {
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
530
|
+
amountNum = parseInt(amountInput, 10);
|
|
531
|
+
if (Number.isNaN(amountNum) || amountNum <= 0) {
|
|
532
|
+
return "请输入有效的存款金额(正整数或 all)。";
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
if (!options?.yes) {
|
|
536
|
+
const confirmMsg = generateDepositConfirmMessage(amountNum, currency, cash);
|
|
537
|
+
await session.send(confirmMsg);
|
|
538
|
+
const userInput = await session.prompt(3e4);
|
|
539
|
+
if (!userInput) return "操作超时,已取消存款。";
|
|
540
|
+
const confirmed = userInput.trim().toLowerCase();
|
|
541
|
+
if (confirmed !== "yes" && confirmed !== "y") {
|
|
542
|
+
return "已取消存款操作。";
|
|
543
|
+
}
|
|
264
544
|
}
|
|
265
|
-
|
|
545
|
+
const result = await ctx.monetaryBank.deposit(uid, currency, amountNum);
|
|
546
|
+
if (!result.success) {
|
|
547
|
+
return result.error || "存款失败";
|
|
548
|
+
}
|
|
549
|
+
return `成功存入 ${amountNum} ${currency}(活期)!
|
|
550
|
+
现金余额:${result.newCash} ${currency}
|
|
551
|
+
银行总资产:${result.newBalance.total} ${currency}`;
|
|
266
552
|
} catch (error) {
|
|
267
553
|
logger.error("存款失败:", error);
|
|
268
554
|
return "存款失败,请稍后再试。";
|
|
269
555
|
}
|
|
270
556
|
});
|
|
271
|
-
ctx.command("bank.out
|
|
272
|
-
if (!amount || amount <= 0) {
|
|
273
|
-
return "请输入有效的取款金额(正整数)。";
|
|
274
|
-
}
|
|
557
|
+
ctx.command("bank.out [amount:string]", "从银行取出货币").userFields(["id"]).option("currency", "-c <currency:string> 指定货币类型").option("yes", "-y 跳过确认直接执行").action(async ({ session, options }, amount) => {
|
|
275
558
|
const uid = session.user.id;
|
|
276
559
|
const currency = options?.currency || config.defaultCurrency || "coin";
|
|
277
560
|
try {
|
|
278
|
-
const
|
|
279
|
-
if (
|
|
280
|
-
return
|
|
561
|
+
const balance = await ctx.monetaryBank.getBalance(uid, currency);
|
|
562
|
+
if (balance.demand === 0) {
|
|
563
|
+
return `没有可取出的存款。当前活期:${balance.demand} ${currency}`;
|
|
281
564
|
}
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
565
|
+
if (!amount) {
|
|
566
|
+
await session.send(`请输入取款金额(正整数或 all):
|
|
567
|
+
当前可用余额:${balance.demand} ${currency}`);
|
|
568
|
+
const amountInput2 = await session.prompt(3e4);
|
|
569
|
+
if (!amountInput2) return "操作超时,已取消取款。";
|
|
570
|
+
amount = amountInput2.trim();
|
|
285
571
|
}
|
|
286
|
-
const
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
572
|
+
const amountInput = String(amount || "").trim().toLowerCase();
|
|
573
|
+
let amountNum;
|
|
574
|
+
if (amountInput === "all") {
|
|
575
|
+
amountNum = Math.floor(balance.demand);
|
|
576
|
+
} else {
|
|
577
|
+
amountNum = parseInt(amountInput, 10);
|
|
578
|
+
if (Number.isNaN(amountNum) || amountNum <= 0) {
|
|
579
|
+
return "请输入有效的取款金额(正整数或 all)。";
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
if (!options?.yes) {
|
|
583
|
+
const confirmMsg = generateWithdrawConfirmMessage(amountNum, currency, balance.demand);
|
|
584
|
+
await session.send(confirmMsg);
|
|
585
|
+
const userInput = await session.prompt(3e4);
|
|
586
|
+
if (!userInput) return "操作超时,已取消取款。";
|
|
587
|
+
const confirmed = userInput.trim().toLowerCase();
|
|
588
|
+
if (confirmed !== "yes" && confirmed !== "y") {
|
|
589
|
+
return "已取消取款操作。";
|
|
590
|
+
}
|
|
292
591
|
}
|
|
293
|
-
|
|
592
|
+
const result = await ctx.monetaryBank.withdraw(uid, currency, amountNum);
|
|
593
|
+
if (!result.success) {
|
|
594
|
+
return result.error || "取款失败";
|
|
595
|
+
}
|
|
596
|
+
return `成功取出 ${amountNum} ${currency}!
|
|
597
|
+
现金余额:${result.newCash} ${currency}
|
|
598
|
+
银行总资产:${result.newBalance.total} ${currency}`;
|
|
294
599
|
} catch (error) {
|
|
295
600
|
logger.error("取款失败:", error);
|
|
296
601
|
return "取款失败,请稍后再试。";
|
|
297
602
|
}
|
|
298
603
|
});
|
|
604
|
+
ctx.command("bank.fixed", "申请定期存款").userFields(["id"]).option("currency", "-c <currency:string> 指定货币类型").action(async ({ session, options }) => {
|
|
605
|
+
if (!config.enableInterest) {
|
|
606
|
+
return "利息功能未启用。";
|
|
607
|
+
}
|
|
608
|
+
const uid = session.user.id;
|
|
609
|
+
const currency = options?.currency || config.defaultCurrency || "coin";
|
|
610
|
+
const plans = config.fixedInterest || [];
|
|
611
|
+
if (plans.length === 0) {
|
|
612
|
+
return "当前没有可用的定期存款方案。";
|
|
613
|
+
}
|
|
614
|
+
let msg = "可选的定期存款方案:\n";
|
|
615
|
+
plans.forEach((plan, index) => {
|
|
616
|
+
const cycleText = plan.cycle === "day" ? "日" : plan.cycle === "week" ? "周" : "月";
|
|
617
|
+
msg += `${index + 1}. ${plan.name} - 利率:${plan.rate}% - 周期:${cycleText}
|
|
618
|
+
`;
|
|
619
|
+
});
|
|
620
|
+
msg += "\n请输入方案编号选择,或输入 0 取消:";
|
|
621
|
+
await session.send(msg);
|
|
622
|
+
const planInput = await session.prompt(3e4);
|
|
623
|
+
if (!planInput) return "操作超时,已取消。";
|
|
624
|
+
const planIndex = parseInt(planInput.trim()) - 1;
|
|
625
|
+
if (planIndex < 0) return "已取消定期存款申请。";
|
|
626
|
+
if (planIndex >= plans.length) return "无效的方案编号。";
|
|
627
|
+
const selectedPlan = plans[planIndex];
|
|
628
|
+
await session.send(`请输入存入金额(优先使用现金,不足时使用银行活期存款):`);
|
|
629
|
+
const amountInput = await session.prompt(3e4);
|
|
630
|
+
if (!amountInput) return "操作超时,已取消。";
|
|
631
|
+
const amount = parseInt(amountInput.trim());
|
|
632
|
+
if (!amount || amount <= 0) return "无效的金额。";
|
|
633
|
+
try {
|
|
634
|
+
const cash = await getMonetaryBalance(ctx, uid, currency) || 0;
|
|
635
|
+
const balance = await getBankBalance(ctx, uid, currency);
|
|
636
|
+
const totalAvailable = cash + balance.demand;
|
|
637
|
+
if (totalAvailable < amount) {
|
|
638
|
+
return `资金不足!现金:${cash} ${currency},活期存款:${balance.demand} ${currency},合计:${totalAvailable} ${currency}`;
|
|
639
|
+
}
|
|
640
|
+
await session.send(`将存入 ${amount} ${currency} 到定期(${selectedPlan.name}),利率 ${selectedPlan.rate}%。
|
|
641
|
+
确认请输入 yes 或 y:`);
|
|
642
|
+
const confirm = await session.prompt(3e4);
|
|
643
|
+
if (!confirm || !["yes", "y"].includes(confirm.trim().toLowerCase())) {
|
|
644
|
+
return "已取消定期存款申请。";
|
|
645
|
+
}
|
|
646
|
+
let remaining = amount;
|
|
647
|
+
let fromCash = 0;
|
|
648
|
+
let fromDemand = 0;
|
|
649
|
+
if (cash > 0) {
|
|
650
|
+
fromCash = Math.min(cash, remaining);
|
|
651
|
+
remaining -= fromCash;
|
|
652
|
+
const newCash = await changeMonetary(ctx, uid, currency, -fromCash);
|
|
653
|
+
if (newCash === null) return "扣除现金失败。";
|
|
654
|
+
}
|
|
655
|
+
if (remaining > 0) {
|
|
656
|
+
fromDemand = remaining;
|
|
657
|
+
const demandRecords = await ctx.database.select("monetary_bank_int").where({ uid, currency, type: "demand" }).orderBy("settlementDate", "asc").execute();
|
|
658
|
+
let toDeduct = fromDemand;
|
|
659
|
+
for (const record of demandRecords) {
|
|
660
|
+
if (toDeduct <= 0) break;
|
|
661
|
+
if (record.amount <= toDeduct) {
|
|
662
|
+
toDeduct -= record.amount;
|
|
663
|
+
await ctx.database.remove("monetary_bank_int", { id: record.id });
|
|
664
|
+
} else {
|
|
665
|
+
const newAmount = record.amount - toDeduct;
|
|
666
|
+
await ctx.database.set("monetary_bank_int", { id: record.id }, { amount: newAmount });
|
|
667
|
+
toDeduct = 0;
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
const settlementDate = calculateNextSettlementDate(selectedPlan.cycle, true);
|
|
672
|
+
await ctx.database.create("monetary_bank_int", {
|
|
673
|
+
uid,
|
|
674
|
+
currency,
|
|
675
|
+
amount,
|
|
676
|
+
type: "fixed",
|
|
677
|
+
rate: selectedPlan.rate,
|
|
678
|
+
cycle: selectedPlan.cycle,
|
|
679
|
+
settlementDate,
|
|
680
|
+
extendRequested: false
|
|
681
|
+
});
|
|
682
|
+
const newBalance = await getBankBalance(ctx, uid, currency);
|
|
683
|
+
return `成功申请定期存款!
|
|
684
|
+
方案:${selectedPlan.name}
|
|
685
|
+
金额:${amount} ${currency}
|
|
686
|
+
来源:现金 ${fromCash} + 活期 ${fromDemand}
|
|
687
|
+
到期日:${settlementDate.toLocaleDateString()}
|
|
688
|
+
银行总资产:${newBalance.total} ${currency}`;
|
|
689
|
+
} catch (error) {
|
|
690
|
+
logger.error("定期存款失败:", error);
|
|
691
|
+
return "定期存款失败,请稍后再试。";
|
|
692
|
+
}
|
|
693
|
+
});
|
|
694
|
+
ctx.command("bank.fixed.manage", "管理定期存款延期").userFields(["id"]).option("currency", "-c <currency:string> 指定货币类型").action(async ({ session, options }) => {
|
|
695
|
+
if (!config.enableInterest) {
|
|
696
|
+
return "利息功能未启用。";
|
|
697
|
+
}
|
|
698
|
+
const uid = session.user.id;
|
|
699
|
+
const currency = options?.currency || config.defaultCurrency || "coin";
|
|
700
|
+
try {
|
|
701
|
+
const fixedRecords = await ctx.database.select("monetary_bank_int").where({ uid, currency, type: "fixed" }).orderBy("settlementDate", "asc").execute();
|
|
702
|
+
if (fixedRecords.length === 0) {
|
|
703
|
+
return "您没有定期存款记录。";
|
|
704
|
+
}
|
|
705
|
+
let msg = "您的定期存款:\n";
|
|
706
|
+
fixedRecords.forEach((record, index) => {
|
|
707
|
+
const cycleText = record.cycle === "day" ? "日" : record.cycle === "week" ? "周" : "月";
|
|
708
|
+
const currentPlan = `${record.rate}%/${cycleText}`;
|
|
709
|
+
let status = "[未延期]";
|
|
710
|
+
if (record.extendRequested && record.nextRate !== void 0 && record.nextCycle) {
|
|
711
|
+
const nextCycleText = record.nextCycle === "day" ? "日" : record.nextCycle === "week" ? "周" : "月";
|
|
712
|
+
status = `[已延期至: ${record.nextRate}%/${nextCycleText}]`;
|
|
713
|
+
}
|
|
714
|
+
msg += `${index + 1}. ${currentPlan} -【 ${record.amount} ${currency} 】- 到期:${new Date(record.settlementDate).toLocaleDateString()} ${status}
|
|
715
|
+
`;
|
|
716
|
+
});
|
|
717
|
+
msg += "\n请输入编号管理,或输入 0 退出:";
|
|
718
|
+
await session.send(msg);
|
|
719
|
+
const input = await session.prompt(3e4);
|
|
720
|
+
if (!input) return "操作超时。";
|
|
721
|
+
const recordIndex = parseInt(input.trim()) - 1;
|
|
722
|
+
if (recordIndex < 0) return "已退出。";
|
|
723
|
+
if (recordIndex >= fixedRecords.length) return "无效的编号。";
|
|
724
|
+
const selectedRecord = fixedRecords[recordIndex];
|
|
725
|
+
if (selectedRecord.extendRequested) {
|
|
726
|
+
const nextCycleText = selectedRecord.nextCycle === "day" ? "日" : selectedRecord.nextCycle === "week" ? "周" : "月";
|
|
727
|
+
await session.send(`当前已申请延期至:${selectedRecord.nextRate}%/${nextCycleText}
|
|
728
|
+
输入 1 取消延期申请,输入 0 返回:`);
|
|
729
|
+
const action = await session.prompt(3e4);
|
|
730
|
+
if (!action || action.trim() === "0") return "已返回。";
|
|
731
|
+
if (action.trim() === "1") {
|
|
732
|
+
await ctx.database.set("monetary_bank_int", { id: selectedRecord.id }, {
|
|
733
|
+
extendRequested: false,
|
|
734
|
+
nextRate: null,
|
|
735
|
+
nextCycle: null
|
|
736
|
+
});
|
|
737
|
+
return "已取消延期申请,到期后将自动转为活期。";
|
|
738
|
+
}
|
|
739
|
+
} else {
|
|
740
|
+
const plans = config.fixedInterest || [];
|
|
741
|
+
let planMsg = "可选的续期方案:\n";
|
|
742
|
+
plans.forEach((plan, index) => {
|
|
743
|
+
const cycleText = plan.cycle === "day" ? "日" : plan.cycle === "week" ? "周" : "月";
|
|
744
|
+
planMsg += `${index + 1}. ${plan.name} - 利率:${plan.rate}% - 周期:${cycleText}
|
|
745
|
+
`;
|
|
746
|
+
});
|
|
747
|
+
planMsg += "\n请输入方案编号申请延期,或输入 0 返回:";
|
|
748
|
+
await session.send(planMsg);
|
|
749
|
+
const planInput = await session.prompt(3e4);
|
|
750
|
+
if (!planInput) return "操作超时。";
|
|
751
|
+
const planIndex = parseInt(planInput.trim()) - 1;
|
|
752
|
+
if (planIndex < 0) return "已返回。";
|
|
753
|
+
if (planIndex >= plans.length) return "无效的方案编号。";
|
|
754
|
+
const newPlan = plans[planIndex];
|
|
755
|
+
await ctx.database.set("monetary_bank_int", { id: selectedRecord.id }, {
|
|
756
|
+
extendRequested: true,
|
|
757
|
+
nextRate: newPlan.rate,
|
|
758
|
+
nextCycle: newPlan.cycle
|
|
759
|
+
});
|
|
760
|
+
return `已申请延期!到期后将按:${newPlan.name}(利率 ${newPlan.rate}%)继续存款。`;
|
|
761
|
+
}
|
|
762
|
+
} catch (error) {
|
|
763
|
+
logger.error("管理定期失败:", error);
|
|
764
|
+
return "操作失败,请稍后再试。";
|
|
765
|
+
}
|
|
766
|
+
});
|
|
767
|
+
if (config.enableInterest) {
|
|
768
|
+
await scheduleInterestSettlement(ctx, config);
|
|
769
|
+
}
|
|
299
770
|
}
|
|
300
771
|
__name(apply, "apply");
|
|
301
772
|
// Annotate the CommonJS export names for ESM import in node:
|
|
302
773
|
0 && (module.exports = {
|
|
303
774
|
Config,
|
|
775
|
+
MonetaryBankAPI,
|
|
304
776
|
apply,
|
|
305
777
|
inject,
|
|
306
778
|
name
|
package/package.json
CHANGED
package/readme.md
CHANGED
|
@@ -4,11 +4,25 @@
|
|
|
4
4
|
|
|
5
5
|
`Provides banking related services for monetary money`
|
|
6
6
|
|
|
7
|
-
---
|
|
8
|
-
|
|
9
7
|
`为 monetary 插件(或外部项目中的主货币表)提供轻量级银行功能,支持活期/定期存款与利息结算。`
|
|
10
8
|
|
|
11
|
-
|
|
9
|
+
**目录**
|
|
10
|
+
- 简介
|
|
11
|
+
- 特点
|
|
12
|
+
- 依赖
|
|
13
|
+
- 数据库表
|
|
14
|
+
- 快速安装
|
|
15
|
+
- 配置说明
|
|
16
|
+
- 命令一览
|
|
17
|
+
- API
|
|
18
|
+
- 利息结算
|
|
19
|
+
- 附加说明
|
|
20
|
+
- 更新日志
|
|
21
|
+
- 开发者/贡献
|
|
22
|
+
|
|
23
|
+
---
|
|
24
|
+
|
|
25
|
+
**版本**: v1.2.0
|
|
12
26
|
|
|
13
27
|
**特点**
|
|
14
28
|
- **查询/存取**: 提供银行资产查询、存入(存为活期)、取出(仅活期)。
|
|
@@ -21,6 +35,7 @@
|
|
|
21
35
|
|
|
22
36
|
**数据库表**
|
|
23
37
|
- **表名**: `monetary_bank_int` — 用于记录所有银行存款(活期与定期)。
|
|
38
|
+
- **早期表名**:`monetary_bank` — 用于存放用户和银行存款。
|
|
24
39
|
|
|
25
40
|
**快速安装**
|
|
26
41
|
- 在 Koishi 项目中安装并启用本插件(示例:`package.json` 或 Koishi 配置中添加插件)
|
|
@@ -71,7 +86,7 @@ plugins: {
|
|
|
71
86
|
- 支持从现金和活期组合扣款(优先扣现金)
|
|
72
87
|
- **`bank.fixed.manage`**: 管理已申请的定期(申请延期或取消延期)
|
|
73
88
|
|
|
74
|
-
|
|
89
|
+
命令示例:
|
|
75
90
|
|
|
76
91
|
```
|
|
77
92
|
bank.bal -c coin
|
|
@@ -81,6 +96,43 @@ bank.fixed -c coin
|
|
|
81
96
|
bank.fixed.manage -c coin
|
|
82
97
|
```
|
|
83
98
|
|
|
99
|
+
**API**
|
|
100
|
+
|
|
101
|
+
本插件提供可被其他插件直接调用的编程接口 `MonetaryBankAPI`,并在 `apply` 中注册为 `ctx.monetaryBank`。该 API 将业务逻辑与命令交互分离,便于测试和复用。
|
|
102
|
+
|
|
103
|
+
- `getBalance(uid: number, currency: string): Promise<{ total: number; demand: number; fixed: number }>`
|
|
104
|
+
- 说明:查询指定用户在银行的总资产、活期(可用)与定期(不可用)余额。
|
|
105
|
+
|
|
106
|
+
- `deposit(uid: number, currency: string, amount: number): Promise<{ success: boolean; newCash?: number; newBalance?: { total:number; demand:number; fixed:number }; error?: string }>`
|
|
107
|
+
- 说明:将用户的现金存入银行并创建活期记录(会自动尝试创建主货币账户)。返回操作结果与更新后的现金/银行余额。
|
|
108
|
+
|
|
109
|
+
- `withdraw(uid: number, currency: string, amount: number): Promise<{ success: boolean; newCash?: number; newBalance?: { total:number; demand:number; fixed:number }; error?: string }>`
|
|
110
|
+
- 说明:从活期中按时间顺序扣除金额并转回用户现金。仅能提取活期部分,返回操作结果与更新后的现金/银行余额。
|
|
111
|
+
|
|
112
|
+
返回格式说明(统一格式)
|
|
113
|
+
- `success`: 操作是否成功(布尔)
|
|
114
|
+
- `newCash`(可选):操作后用户主货币表中的现金余额
|
|
115
|
+
- `newBalance`(可选):操作后银行中归集的余额信息(`{ total, demand, fixed }`)
|
|
116
|
+
- `error`(可选):失败时的错误消息
|
|
117
|
+
|
|
118
|
+
API示例(在其他插件中调用):
|
|
119
|
+
|
|
120
|
+
```
|
|
121
|
+
// 查询余额
|
|
122
|
+
const balance = await ctx.monetaryBank.getBalance(uid, 'coin')
|
|
123
|
+
console.log(`总资产:${balance.total}, 活期:${balance.demand}, 定期:${balance.fixed}`)
|
|
124
|
+
|
|
125
|
+
// 存款
|
|
126
|
+
const res = await ctx.monetaryBank.deposit(uid, 'coin', 100)
|
|
127
|
+
if (res.success) console.log(`存款成功,新现金:${res.newCash}`)
|
|
128
|
+
else console.error(`存款失败:${res.error}`)
|
|
129
|
+
|
|
130
|
+
// 取款
|
|
131
|
+
const res2 = await ctx.monetaryBank.withdraw(uid, 'coin', 50)
|
|
132
|
+
if (res2.success) console.log(`取款成功,新现金:${res2.newCash}`)
|
|
133
|
+
else console.error(`取款失败:${res2.error}`)
|
|
134
|
+
```
|
|
135
|
+
|
|
84
136
|
**利息结算**
|
|
85
137
|
- 若在配置中启用 `enableInterest`,插件会在后台启动定时任务,每日0点检查并结算到期记录(对 `day/week/month` 周期分别按设定处理)。
|
|
86
138
|
- 到期的定期记录可以:延期(若用户已申请)或转为活期并结算利息。
|
|
@@ -93,13 +145,32 @@ bank.fixed.manage -c coin
|
|
|
93
145
|
- 插件作者: BYWled
|
|
94
146
|
- 仓库: `koishi-plugin-monetary-bank`
|
|
95
147
|
|
|
148
|
+
|
|
96
149
|
**更新日志**
|
|
97
150
|
|
|
98
|
-
- **1.
|
|
151
|
+
- **1.2.0**
|
|
152
|
+
- 新增:`MonetaryBankAPI` 类并导出为 `ctx.monetaryBank`(接口方法:`getBalance` / `deposit` / `withdraw`),所有方法返回统一格式 `{ success, newCash?, newBalance?, error? }`,便于其他插件以编程方式调用。
|
|
153
|
+
- 新增:在 `apply` 向 `Context` 注册 `monetaryBank`(`ctx.monetaryBank = new MonetaryBankAPI(ctx, config)`),并在类型声明中扩展 `Context`。
|
|
154
|
+
- 重构:命令接口使用新的 API:
|
|
155
|
+
- `bank.bal [currency]` 使用 `ctx.monetaryBank.getBalance()`,支持可选参数输入货币并改进显示为“活期(可用)/定期(不可用)”。
|
|
156
|
+
- `bank.in [amount]` 支持可选参数;无参数时交互式提示 `请输入存款金额(正整数或 all):`,支持 `all` 将全部现金存入;使用 `ctx.monetaryBank.deposit()` 执行业务逻辑。
|
|
157
|
+
- `bank.out [amount]` 支持可选参数;无参数时交互式提示并展示当前活期余额,支持 `all` 将全部活期取出;使用 `ctx.monetaryBank.withdraw()`。
|
|
158
|
+
- 改进:利息结算流程中在结算完成后合并相同组别的活期记录(`mergeDemandRecords`),减少碎片小额记录,提升性能与可读性。
|
|
159
|
+
- 改进:交互文本与超时处理更友好(30s 超时提示取消)。
|
|
160
|
+
|
|
161
|
+
- **1.1.1**
|
|
162
|
+
- 修复了代码未构建的问题。
|
|
163
|
+
|
|
164
|
+
- **1.1.0**
|
|
99
165
|
- 增加:命令 `bank.fixed`, `bank.fixed.manage` 与更完善的交互流程
|
|
100
166
|
- 增加:活期/定期利息配置与结算调度(可配置开启)
|
|
101
167
|
- 改进:兼容更多 `monetary` 表字段,增强容错与自动创建最小记录的能力
|
|
168
|
+
- **注意**:本版本重构了数据库,因此旧的数据库中的**数据将丢失**,请在更新前做好**数据备份**!
|
|
102
169
|
- **1.0.1**
|
|
103
170
|
- 修复依赖版本问题
|
|
104
171
|
- **1.0.0**
|
|
105
172
|
- 初始发布,提供银行存取与查询功能 `bank.in`, `bank.out`, `bank.bal`
|
|
173
|
+
|
|
174
|
+
---
|
|
175
|
+
|
|
176
|
+
萌新编写,部分借助了AI的力量,若有纰漏,还望海涵QwQ
|