koishi-plugin-rina-currency 0.0.2 → 0.0.3
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.js +89 -30
- package/lib/scheduler.d.ts +5 -0
- package/lib/service.d.ts +8 -2
- package/lib/types.d.ts +2 -0
- package/package.json +1 -1
- package/readme.md +1 -1
package/lib/index.js
CHANGED
|
@@ -215,32 +215,43 @@ async function renderTrendChart(metrics, rateType, options) {
|
|
|
215
215
|
const padding = { top: 184, right: 72, bottom: 76, left: 88 };
|
|
216
216
|
const plotWidth = width - padding.left - padding.right;
|
|
217
217
|
const plotHeight = height - padding.top - padding.bottom;
|
|
218
|
-
const
|
|
218
|
+
const rangeStart = metrics.rangeStart.getTime();
|
|
219
|
+
const rangeEnd = metrics.rangeEnd.getTime();
|
|
220
|
+
const chartPoints = metrics.points.map((point) => ({
|
|
221
|
+
...point,
|
|
222
|
+
collectedAt: new Date(Math.max(point.collectedAt.getTime(), rangeStart))
|
|
223
|
+
}));
|
|
224
|
+
const lastPoint = chartPoints.at(-1);
|
|
225
|
+
if (lastPoint.collectedAt.getTime() < rangeEnd) {
|
|
226
|
+
chartPoints.push({ ...metrics.latest, collectedAt: new Date(rangeEnd) });
|
|
227
|
+
}
|
|
228
|
+
const values = chartPoints.map((point) => point[rateType]);
|
|
219
229
|
const min = Math.min(...values);
|
|
220
230
|
const max = Math.max(...values);
|
|
221
231
|
const spread = Math.max(max - min, Math.max(max, 1) * 2e-3);
|
|
222
232
|
const lower = min - spread * 0.14;
|
|
223
233
|
const upper = max + spread * 0.14;
|
|
224
234
|
const range = upper - lower;
|
|
225
|
-
const
|
|
226
|
-
const
|
|
227
|
-
const timeRange = Math.max(lastTime - firstTime, 1);
|
|
228
|
-
const xFor = /* @__PURE__ */ __name((time) => padding.left + (time - firstTime) / timeRange * plotWidth, "xFor");
|
|
235
|
+
const timeRange = Math.max(rangeEnd - rangeStart, 1);
|
|
236
|
+
const xFor = /* @__PURE__ */ __name((time) => padding.left + (time - rangeStart) / timeRange * plotWidth, "xFor");
|
|
229
237
|
const yFor = /* @__PURE__ */ __name((value) => padding.top + (upper - value) / range * plotHeight, "yFor");
|
|
230
|
-
const coordinates =
|
|
231
|
-
const latestX = xFor(
|
|
238
|
+
const coordinates = chartPoints.map((point) => `${xFor(point.collectedAt.getTime()).toFixed(1)},${yFor(point[rateType]).toFixed(1)}`).join(" ");
|
|
239
|
+
const latestX = xFor(rangeEnd);
|
|
232
240
|
const latestY = yFor(metrics.latest[rateType]);
|
|
233
241
|
const highPoint = metrics.points.reduce((best, point) => point[rateType] > best[rateType] ? point : best);
|
|
234
242
|
const lowPoint = metrics.points.reduce((best, point) => point[rateType] < best[rateType] ? point : best);
|
|
235
|
-
const highX = xFor(highPoint.
|
|
243
|
+
const highX = xFor(Math.max(highPoint.collectedAt.getTime(), rangeStart));
|
|
236
244
|
const highY = yFor(highPoint[rateType]);
|
|
237
|
-
const lowX = xFor(lowPoint.
|
|
245
|
+
const lowX = xFor(Math.max(lowPoint.collectedAt.getTime(), rangeStart));
|
|
238
246
|
const lowY = yFor(lowPoint[rateType]);
|
|
239
247
|
const change = metrics.change == null ? "暂无前日数据" : `${metrics.change >= 0 ? "+" : ""}${formatRate(metrics.change)} ${metrics.changePercent >= 0 ? "+" : ""}${metrics.changePercent.toFixed(2)}%`;
|
|
240
248
|
const changeColor = metrics.change == null ? "#94a3b8" : metrics.change > 0 ? "#fb7185" : "#34d399";
|
|
241
249
|
const ticks = Array.from({ length: 4 }, (_, index) => lower + (upper - lower) * index / 3);
|
|
242
|
-
const
|
|
243
|
-
|
|
250
|
+
const labels = [
|
|
251
|
+
new Date(rangeStart),
|
|
252
|
+
new Date((rangeStart + rangeEnd) / 2),
|
|
253
|
+
new Date(rangeEnd)
|
|
254
|
+
];
|
|
244
255
|
const grid = ticks.map((value) => {
|
|
245
256
|
const y = yFor(value);
|
|
246
257
|
return `<line x1="${padding.left}" x2="${width - padding.right}" y1="${y}" y2="${y}" stroke="#26334a" stroke-width="1" />
|
|
@@ -248,7 +259,7 @@ async function renderTrendChart(metrics, rateType, options) {
|
|
|
248
259
|
}).join("");
|
|
249
260
|
const xLabels = labels.map((point, index) => {
|
|
250
261
|
const anchor = index === 0 ? "start" : index === labels.length - 1 ? "end" : "middle";
|
|
251
|
-
return `<text x="${xFor(point.
|
|
262
|
+
return `<text x="${xFor(point.getTime())}" y="${height - 30}" text-anchor="${anchor}" class="axis">${dateLabel(point)}</text>`;
|
|
252
263
|
}).join("");
|
|
253
264
|
const title = `${BANK_LABELS[metrics.latest.bank]} · 日元${RATE_TYPE_LABELS[rateType]}走势`;
|
|
254
265
|
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">
|
|
@@ -558,13 +569,56 @@ var Scheduler = class {
|
|
|
558
569
|
__name(this, "Scheduler");
|
|
559
570
|
}
|
|
560
571
|
sentBroadcasts = /* @__PURE__ */ new Set();
|
|
572
|
+
lastCollectionSlot;
|
|
561
573
|
start() {
|
|
562
574
|
this.ctx.on("ready", async () => {
|
|
563
|
-
|
|
564
|
-
|
|
575
|
+
const due = this.getDueCollection();
|
|
576
|
+
if (due) {
|
|
577
|
+
this.lastCollectionSlot = due.key;
|
|
578
|
+
await this.collectAndAlert({
|
|
579
|
+
recordUnchanged: due.isDailyAnchor,
|
|
580
|
+
collectedAt: due.at
|
|
581
|
+
});
|
|
582
|
+
} else if (this.config.collectOnStart) {
|
|
583
|
+
await this.collectAndAlert();
|
|
584
|
+
}
|
|
585
|
+
this.scheduleAlignedCollections();
|
|
565
586
|
this.ctx.setInterval(() => void this.runBroadcasts(), 3e4);
|
|
566
587
|
});
|
|
567
588
|
}
|
|
589
|
+
/** Runs on China-time minute boundaries, with 17:00 as the daily anchor. */
|
|
590
|
+
scheduleAlignedCollections() {
|
|
591
|
+
const now = /* @__PURE__ */ new Date();
|
|
592
|
+
const delay = 6e4 - now.getSeconds() * 1e3 - now.getMilliseconds();
|
|
593
|
+
this.ctx.setTimeout(() => {
|
|
594
|
+
void this.collectIfDue();
|
|
595
|
+
this.ctx.setInterval(() => void this.collectIfDue(), 6e4);
|
|
596
|
+
}, delay);
|
|
597
|
+
}
|
|
598
|
+
getDueCollection(now = /* @__PURE__ */ new Date()) {
|
|
599
|
+
const clock = chinaClock(now);
|
|
600
|
+
const minutesSinceMidnight = clock.hour * 60 + clock.minute;
|
|
601
|
+
const dailyAnchor = 17 * 60;
|
|
602
|
+
const minutesSinceAnchor = minutesSinceMidnight >= dailyAnchor ? minutesSinceMidnight - dailyAnchor : minutesSinceMidnight + 24 * 60 - dailyAnchor;
|
|
603
|
+
const isDailyAnchor = minutesSinceMidnight === dailyAnchor;
|
|
604
|
+
if (!isDailyAnchor && minutesSinceAnchor % this.config.collectIntervalMinutes !== 0) return;
|
|
605
|
+
const at = new Date(now);
|
|
606
|
+
at.setSeconds(0, 0);
|
|
607
|
+
return {
|
|
608
|
+
key: `${clock.date}:${clock.hour}:${clock.minute}`,
|
|
609
|
+
at,
|
|
610
|
+
isDailyAnchor
|
|
611
|
+
};
|
|
612
|
+
}
|
|
613
|
+
async collectIfDue() {
|
|
614
|
+
const due = this.getDueCollection();
|
|
615
|
+
if (!due || due.key === this.lastCollectionSlot) return;
|
|
616
|
+
this.lastCollectionSlot = due.key;
|
|
617
|
+
await this.collectAndAlert({
|
|
618
|
+
recordUnchanged: due.isDailyAnchor,
|
|
619
|
+
collectedAt: due.at
|
|
620
|
+
});
|
|
621
|
+
}
|
|
568
622
|
getBot(target) {
|
|
569
623
|
return this.ctx.bots.find((bot) => bot.platform === target.platform && bot.selfId === target.selfId);
|
|
570
624
|
}
|
|
@@ -577,9 +631,9 @@ var Scheduler = class {
|
|
|
577
631
|
await bot.sendMessage(target.channelId, content);
|
|
578
632
|
if (image) await bot.sendMessage(target.channelId, import_koishi3.h.image(image, "image/png"));
|
|
579
633
|
}
|
|
580
|
-
async collectAndAlert() {
|
|
634
|
+
async collectAndAlert(options = {}) {
|
|
581
635
|
try {
|
|
582
|
-
const result = await this.service.collect();
|
|
636
|
+
const result = await this.service.collect(options);
|
|
583
637
|
await Promise.all(result.collected.map((item) => this.maybeAlert(item)));
|
|
584
638
|
} catch (error) {
|
|
585
639
|
this.logger.warn(`定时采集日元牌价失败:${String(error)}`);
|
|
@@ -646,10 +700,10 @@ function toQuote(record) {
|
|
|
646
700
|
return { ...record };
|
|
647
701
|
}
|
|
648
702
|
__name(toQuote, "toQuote");
|
|
649
|
-
function
|
|
650
|
-
return records.sort((left, right) => left.
|
|
703
|
+
function sortByCollectedAt(records) {
|
|
704
|
+
return records.sort((left, right) => left.collectedAt.getTime() - right.collectedAt.getTime());
|
|
651
705
|
}
|
|
652
|
-
__name(
|
|
706
|
+
__name(sortByCollectedAt, "sortByCollectedAt");
|
|
653
707
|
var RateService = class {
|
|
654
708
|
constructor(ctx, logger, providers) {
|
|
655
709
|
this.ctx = ctx;
|
|
@@ -659,11 +713,12 @@ var RateService = class {
|
|
|
659
713
|
static {
|
|
660
714
|
__name(this, "RateService");
|
|
661
715
|
}
|
|
662
|
-
async collect() {
|
|
716
|
+
async collect(options = {}) {
|
|
663
717
|
const settled = await Promise.allSettled(this.providers.map(async (provider) => {
|
|
664
718
|
const previous = await this.getLatest(provider.id);
|
|
665
719
|
const quote = await provider.fetch();
|
|
666
|
-
if (
|
|
720
|
+
if (options.collectedAt) quote.collectedAt = options.collectedAt;
|
|
721
|
+
if (previous?.publishedAt.getTime() === quote.publishedAt.getTime() && !options.recordUnchanged) {
|
|
667
722
|
return { quote: previous, previous, isNew: false };
|
|
668
723
|
}
|
|
669
724
|
await this.ctx.database.create("rina_currency_rate", quote);
|
|
@@ -685,7 +740,7 @@ var RateService = class {
|
|
|
685
740
|
async getLatest(bank) {
|
|
686
741
|
const rows = await this.ctx.database.get("rina_currency_rate", { bank, currency: "JPY" });
|
|
687
742
|
if (!rows.length) return;
|
|
688
|
-
return
|
|
743
|
+
return sortByCollectedAt(rows.map(toQuote)).at(-1);
|
|
689
744
|
}
|
|
690
745
|
async getLatestAll() {
|
|
691
746
|
const entries = await Promise.all(["boc", "icbc"].map(async (bank) => [bank, await this.getLatest(bank)]));
|
|
@@ -698,18 +753,20 @@ var RateService = class {
|
|
|
698
753
|
snapshot = await this.getLatestAll();
|
|
699
754
|
return snapshot;
|
|
700
755
|
}
|
|
701
|
-
async getTrend(bank, rateType, days) {
|
|
702
|
-
const since = new Date(
|
|
756
|
+
async getTrend(bank, rateType, days, now = /* @__PURE__ */ new Date()) {
|
|
757
|
+
const since = new Date(now.getTime() - days * 24 * 60 * 60 * 1e3);
|
|
703
758
|
const rows = await this.ctx.database.get("rina_currency_rate", {
|
|
704
759
|
bank,
|
|
705
|
-
currency: "JPY"
|
|
706
|
-
publishedAt: { $gte: since }
|
|
760
|
+
currency: "JPY"
|
|
707
761
|
});
|
|
708
|
-
const
|
|
762
|
+
const history = sortByCollectedAt(rows.map(toQuote));
|
|
763
|
+
const prior = [...history].reverse().find((point) => point.collectedAt.getTime() < since.getTime());
|
|
764
|
+
const points = history.filter((point) => point.collectedAt.getTime() >= since.getTime());
|
|
765
|
+
if (prior) points.unshift(prior);
|
|
709
766
|
if (!points.length) return;
|
|
710
767
|
const latest = points.at(-1);
|
|
711
|
-
const dayBefore =
|
|
712
|
-
const previous = [...
|
|
768
|
+
const dayBefore = now.getTime() - 24 * 60 * 60 * 1e3;
|
|
769
|
+
const previous = [...history].reverse().find((point) => point.collectedAt.getTime() <= dayBefore);
|
|
713
770
|
const values = points.map((point) => point[rateType]);
|
|
714
771
|
const change = previous ? latest[rateType] - previous[rateType] : void 0;
|
|
715
772
|
return {
|
|
@@ -719,7 +776,9 @@ var RateService = class {
|
|
|
719
776
|
changePercent: change == null ? void 0 : change / previous[rateType] * 100,
|
|
720
777
|
high: Math.max(...values),
|
|
721
778
|
low: Math.min(...values),
|
|
722
|
-
points
|
|
779
|
+
points,
|
|
780
|
+
rangeStart: since,
|
|
781
|
+
rangeEnd: now
|
|
723
782
|
};
|
|
724
783
|
}
|
|
725
784
|
};
|
package/lib/scheduler.d.ts
CHANGED
|
@@ -7,8 +7,13 @@ export declare class Scheduler {
|
|
|
7
7
|
private service;
|
|
8
8
|
private config;
|
|
9
9
|
private sentBroadcasts;
|
|
10
|
+
private lastCollectionSlot?;
|
|
10
11
|
constructor(ctx: Context, logger: Logger, service: RateService, config: Config);
|
|
11
12
|
start(): void;
|
|
13
|
+
/** Runs on China-time minute boundaries, with 17:00 as the daily anchor. */
|
|
14
|
+
private scheduleAlignedCollections;
|
|
15
|
+
private getDueCollection;
|
|
16
|
+
private collectIfDue;
|
|
12
17
|
private getBot;
|
|
13
18
|
private send;
|
|
14
19
|
private collectAndAlert;
|
package/lib/service.d.ts
CHANGED
|
@@ -13,14 +13,20 @@ export interface CollectionResult {
|
|
|
13
13
|
error: unknown;
|
|
14
14
|
}>;
|
|
15
15
|
}
|
|
16
|
+
export interface CollectOptions {
|
|
17
|
+
/** Store an unchanged quote as a scheduled confirmation point. */
|
|
18
|
+
recordUnchanged?: boolean;
|
|
19
|
+
/** The scheduler slot represented by this collection. */
|
|
20
|
+
collectedAt?: Date;
|
|
21
|
+
}
|
|
16
22
|
export declare class RateService {
|
|
17
23
|
private ctx;
|
|
18
24
|
private logger;
|
|
19
25
|
private providers;
|
|
20
26
|
constructor(ctx: Context, logger: Logger, providers: RateProvider[]);
|
|
21
|
-
collect(): Promise<CollectionResult>;
|
|
27
|
+
collect(options?: CollectOptions): Promise<CollectionResult>;
|
|
22
28
|
getLatest(bank: BankId): Promise<ExchangeRateQuote | undefined>;
|
|
23
29
|
getLatestAll(): Promise<Partial<Record<BankId, ExchangeRateQuote>>>;
|
|
24
30
|
ensureSnapshot(): Promise<Partial<Record<BankId, ExchangeRateQuote>>>;
|
|
25
|
-
getTrend(bank: BankId, rateType: RateType, days: number): Promise<TrendMetrics | undefined>;
|
|
31
|
+
getTrend(bank: BankId, rateType: RateType, days: number, now?: Date): Promise<TrendMetrics | undefined>;
|
|
26
32
|
}
|
package/lib/types.d.ts
CHANGED
|
@@ -21,6 +21,8 @@ export interface TrendMetrics {
|
|
|
21
21
|
high: number;
|
|
22
22
|
low: number;
|
|
23
23
|
points: ExchangeRateQuote[];
|
|
24
|
+
rangeStart: Date;
|
|
25
|
+
rangeEnd: Date;
|
|
24
26
|
}
|
|
25
27
|
export declare const BANK_LABELS: Record<BankId, string>;
|
|
26
28
|
export declare const RATE_TYPE_LABELS: Record<RateType, string>;
|
package/package.json
CHANGED
package/readme.md
CHANGED
|
@@ -30,7 +30,7 @@ plugins:
|
|
|
30
30
|
|
|
31
31
|
## 采集和来源
|
|
32
32
|
|
|
33
|
-
|
|
33
|
+
插件启动时可立即采集,之后按北京时间以每日 17:00 为基准、按 `collectIntervalMinutes` 分钟间隔采集,不受插件启动时刻影响。趋势图按采样时间绘制并始终延伸至查询当下;周末等未更新时会保持水平线。若每日 17:00 的牌价与上一次相同,仍会保存一条确认采样点,表示此前一天内牌价未变。
|
|
34
34
|
|
|
35
35
|
- 中国银行:公开外汇牌价页面(HTML 表格)
|
|
36
36
|
- 中国工商银行:公开最新牌价接口(JSON)
|