@ysgroup/core 0.1.30 → 0.1.32

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ysgroup/core",
3
- "version": "0.1.30",
3
+ "version": "0.1.32",
4
4
  "type": "module",
5
5
  "main": "src/index.ts",
6
6
  "types": "src/index.ts",
@@ -0,0 +1,304 @@
1
+ /**
2
+ * 日历用的日期纯函数和日期信息类型(YsCalendar 用,业务页也可以直接用)。
3
+ *
4
+ * - 日期一律是 `YYYY-MM-DD` 字符串、月份是 `YYYY-MM`,按日历日计算(内部用 UTC,不受浏览器时区和夏令时影响)。
5
+ * - 「今天」按上海时间(`ysToday`),和服务端 ys_base.calendar 一致。
6
+ * - 一周从周一开始。
7
+ * - 工作日、交易日由服务端 ys_base.calendar 判断后下发(YsCalendarDay),前端只显示,不自己按周一到周五猜;
8
+ * 交易控制一律在服务端判断。
9
+ */
10
+
11
+ /** workday 工作日、weekend 周末、holiday 放假、adjusted 调休上班。 */
12
+ export type YsDayKind = "workday" | "weekend" | "holiday" | "adjusted";
13
+
14
+ /** 一天的信息(服务端 ys_base.calendar 的 DayInfo.to_dict,covered=false 表示这一年还没有放假安排)。 */
15
+ export interface YsCalendarDay {
16
+ date: string;
17
+ kind: YsDayKind;
18
+ name?: string;
19
+ label?: string;
20
+ workday?: boolean;
21
+ trading?: boolean;
22
+ covered?: boolean;
23
+ }
24
+
25
+ export interface YsMonthCell {
26
+ date: string;
27
+ /** 是否属于当前月(首尾补的上月、下月日期为 false)。 */
28
+ inMonth: boolean;
29
+ /** 0 = 周一 … 6 = 周日。 */
30
+ weekday: number;
31
+ }
32
+
33
+ export const YS_WEEKDAY_LABELS = [
34
+ "一",
35
+ "二",
36
+ "三",
37
+ "四",
38
+ "五",
39
+ "六",
40
+ "日",
41
+ ] as const;
42
+
43
+ export const YS_DAY_KIND_LABELS: Record<YsDayKind, string> = {
44
+ workday: "工作日",
45
+ weekend: "周末",
46
+ holiday: "放假",
47
+ adjusted: "调休上班",
48
+ };
49
+
50
+ const DATE_RE = /^(\d{4})-(\d{2})-(\d{2})$/;
51
+ const MONTH_RE = /^(\d{4})-(\d{2})$/;
52
+ const DAY_MS = 86_400_000;
53
+ const pad = (value: number) => String(value).padStart(2, "0");
54
+
55
+ function toUtc(date: string): number | null {
56
+ const match = DATE_RE.exec(date);
57
+ if (!match) return null;
58
+ const [year, month, day] = [
59
+ Number(match[1]),
60
+ Number(match[2]),
61
+ Number(match[3]),
62
+ ];
63
+ const time = Date.UTC(year, month - 1, day);
64
+ const back = new Date(time);
65
+ // 2027-02-30 这类不存在的日期会被 Date 滚到下个月,这里拒绝
66
+ return back.getUTCFullYear() === year &&
67
+ back.getUTCMonth() === month - 1 &&
68
+ back.getUTCDate() === day
69
+ ? time
70
+ : null;
71
+ }
72
+
73
+ function fromUtc(time: number): string {
74
+ const date = new Date(time);
75
+ return `${date.getUTCFullYear()}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())}`;
76
+ }
77
+
78
+ /** 是不是存在的日期(格式对、月和日合法,2 月 29 日只在闰年有)。 */
79
+ export function ysIsDate(value: unknown): value is string {
80
+ return typeof value === "string" && toUtc(value) !== null;
81
+ }
82
+
83
+ /** 上海时间的今天。 */
84
+ export function ysToday(now: Date = new Date()): string {
85
+ return new Intl.DateTimeFormat("sv-SE", { timeZone: "Asia/Shanghai" }).format(
86
+ now,
87
+ );
88
+ }
89
+
90
+ /** 加减天数;日期不合法时原样返回。 */
91
+ export function ysAddDays(date: string, days: number): string {
92
+ const time = toUtc(date);
93
+ return time === null ? date : fromUtc(time + days * DAY_MS);
94
+ }
95
+
96
+ /** 两个日期相差几天(to - from)。 */
97
+ export function ysDaysBetween(from: string, to: string): number {
98
+ const a = toUtc(from);
99
+ const b = toUtc(to);
100
+ return a === null || b === null ? Number.NaN : Math.round((b - a) / DAY_MS);
101
+ }
102
+
103
+ /** 0 = 周一 … 6 = 周日;日期不合法时 -1。 */
104
+ export function ysWeekday(date: string): number {
105
+ const time = toUtc(date);
106
+ return time === null ? -1 : (new Date(time).getUTCDay() + 6) % 7;
107
+ }
108
+
109
+ /** 「周一」…「周日」。 */
110
+ export function ysWeekdayLabel(date: string): string {
111
+ const index = ysWeekday(date);
112
+ return index < 0 ? "" : `周${YS_WEEKDAY_LABELS[index]}`;
113
+ }
114
+
115
+ /** 日期所在月份 `YYYY-MM`。 */
116
+ export function ysMonthOf(date: string): string {
117
+ return date.slice(0, 7);
118
+ }
119
+
120
+ /** 月份加减;`2026-01` 减 1 得 `2025-12`。格式不对时原样返回。 */
121
+ export function ysShiftMonth(month: string, delta: number): string {
122
+ const match = MONTH_RE.exec(month);
123
+ if (!match) return month;
124
+ const index = Number(match[1]) * 12 + Number(match[2]) - 1 + delta;
125
+ return `${Math.floor(index / 12)}-${pad((index % 12) + 1)}`;
126
+ }
127
+
128
+ /** 这个月有几天。 */
129
+ export function ysDaysInMonth(month: string): number {
130
+ const match = MONTH_RE.exec(month);
131
+ if (!match) return 0;
132
+ return new Date(Date.UTC(Number(match[1]), Number(match[2]), 0)).getUTCDate();
133
+ }
134
+
135
+ /** 月历网格:固定 6 行 × 7 列(周一开头),首行补上月尾、末行补下月头,翻月时高度不跳。 */
136
+ export function ysMonthGrid(month: string): YsMonthCell[] {
137
+ if (!MONTH_RE.test(month)) return [];
138
+ const first = `${month}-01`;
139
+ const start = ysAddDays(first, -ysWeekday(first));
140
+ return Array.from({ length: 42 }, (_, index) => {
141
+ const date = ysAddDays(start, index);
142
+ return { date, inMonth: date.startsWith(month), weekday: index % 7 };
143
+ });
144
+ }
145
+
146
+ /** 月历网格覆盖的闭区间(按这个范围向服务端取日期信息)。 */
147
+ export function ysMonthRange(month: string): { from: string; to: string } {
148
+ const grid = ysMonthGrid(month);
149
+ return grid.length
150
+ ? { from: grid[0]!.date, to: grid[41]!.date }
151
+ : { from: "", to: "" };
152
+ }
153
+
154
+ /** 「2026 年 10 月」。 */
155
+ export function ysMonthTitle(month: string): string {
156
+ const match = MONTH_RE.exec(month);
157
+ return match ? `${match[1]} 年 ${Number(match[2])} 月` : "";
158
+ }
159
+
160
+ /** 「2026 年 10 月 1 日 周四」。 */
161
+ export function ysDateTitle(date: string): string {
162
+ const match = DATE_RE.exec(date);
163
+ if (!match || !ysIsDate(date)) return "";
164
+ return `${match[1]} 年 ${Number(match[2])} 月 ${Number(match[3])} 日 ${ysWeekdayLabel(date)}`;
165
+ }
166
+
167
+ // ---------- 交易日标记(按服务端下发的 trading 推出来,只用于显示) ----------
168
+
169
+ /** pre-holiday 节前最后交易日、post-holiday 节后首个交易日、month-first 月初首个交易日、month-last 月末最后交易日。 */
170
+ export type YsTradingTag =
171
+ | "pre-holiday"
172
+ | "post-holiday"
173
+ | "month-first"
174
+ | "month-last";
175
+
176
+ export const YS_TRADING_TAG_LABELS: Record<
177
+ YsTradingTag,
178
+ { short: string; full: string }
179
+ > = {
180
+ "pre-holiday": { short: "节前最后", full: "节前最后交易日" },
181
+ "post-holiday": { short: "节后首日", full: "节后首个交易日" },
182
+ "month-first": { short: "月初首日", full: "本月首个交易日" },
183
+ "month-last": { short: "月末最后", full: "本月最后交易日" },
184
+ };
185
+
186
+ export interface YsTradingMark {
187
+ /** 本月第几个交易日;这个月的日期信息不全(或有没发布的年份)时没有。 */
188
+ ordinal?: number;
189
+ tags: YsTradingTag[];
190
+ }
191
+
192
+ function monthComplete(
193
+ byDate: Map<string, YsCalendarDay>,
194
+ month: string,
195
+ ): boolean {
196
+ const total = ysDaysInMonth(month);
197
+ for (let day = 1; day <= total; day += 1) {
198
+ const item = byDate.get(`${month}-${pad(day)}`);
199
+ if (!item || item.covered === false) return false;
200
+ }
201
+ return total > 0;
202
+ }
203
+
204
+ /**
205
+ * 每个交易日的标记:本月第几个交易日、节前最后、节后首个、月初首个、月末最后。
206
+ * - 只用服务端下发的 trading 字段,不自己按星期判断;没有放假安排(covered=false)的日子不标。
207
+ * - 「节前」「节后」:和相邻交易日之间隔着放假日(kind=holiday)才算,只隔周末或调休上班日不算;
208
+ * 隔开的那段休市延伸到数据范围之外时不标(不知道后面是什么)。
209
+ * - 序号和月初、月末只对日期信息完整的月份标。
210
+ */
211
+ export function ysTradingMarks(
212
+ days: readonly YsCalendarDay[],
213
+ ): Map<string, YsTradingMark> {
214
+ const sorted = [...days]
215
+ .filter((item) => ysIsDate(item.date))
216
+ .sort((a, b) => a.date.localeCompare(b.date));
217
+ const byDate = new Map(sorted.map((item) => [item.date, item]));
218
+ const isTrading = (item: YsCalendarDay | undefined) =>
219
+ Boolean(item && item.covered !== false && item.trading);
220
+ const marks = new Map<string, YsTradingMark>();
221
+ const complete = new Map<string, boolean>();
222
+ const counters = new Map<string, number>();
223
+
224
+ for (const item of sorted) {
225
+ if (!isTrading(item)) continue;
226
+ const mark: YsTradingMark = { tags: [] };
227
+ const month = ysMonthOf(item.date);
228
+ if (!complete.has(month)) complete.set(month, monthComplete(byDate, month));
229
+ if (complete.get(month)) {
230
+ const ordinal = (counters.get(month) ?? 0) + 1;
231
+ counters.set(month, ordinal);
232
+ mark.ordinal = ordinal;
233
+ if (ordinal === 1) mark.tags.push("month-first");
234
+ }
235
+ // 往后、往前看到下一个交易日为止,中间有放假日就是节前、节后
236
+ for (const [step, tag] of [
237
+ [1, "pre-holiday"],
238
+ [-1, "post-holiday"],
239
+ ] as const) {
240
+ let cursor = ysAddDays(item.date, step);
241
+ let holiday = false;
242
+ let known = true;
243
+ for (;;) {
244
+ const next = byDate.get(cursor);
245
+ if (!next || next.covered === false) {
246
+ known = false;
247
+ break;
248
+ }
249
+ if (isTrading(next)) break;
250
+ if (next.kind === "holiday") holiday = true;
251
+ cursor = ysAddDays(cursor, step);
252
+ }
253
+ if (known && holiday) mark.tags.push(tag);
254
+ }
255
+ marks.set(item.date, mark);
256
+ }
257
+ // 月末最后交易日:每个完整月份的最大序号
258
+ for (const [date, mark] of marks) {
259
+ const month = ysMonthOf(date);
260
+ if (mark.ordinal && mark.ordinal === counters.get(month))
261
+ mark.tags.push("month-last");
262
+ }
263
+ const order: YsTradingTag[] = [
264
+ "pre-holiday",
265
+ "post-holiday",
266
+ "month-first",
267
+ "month-last",
268
+ ];
269
+ for (const mark of marks.values())
270
+ mark.tags.sort((a, b) => order.indexOf(a) - order.indexOf(b));
271
+ return marks;
272
+ }
273
+
274
+ export interface YsMonthSummary {
275
+ /** 这个月的日期信息完整、都有放假安排;为 false 时其余数字不可信,不要显示。 */
276
+ complete: boolean;
277
+ workdays: number;
278
+ trading: number;
279
+ /** 休市天数(含周末、放假日、调休上班的周末)。 */
280
+ closed: number;
281
+ holidays: number;
282
+ adjusted: number;
283
+ }
284
+
285
+ /** 一个月的工作日、交易日、休市、放假、调休上班天数。 */
286
+ export function ysMonthSummary(
287
+ days: readonly YsCalendarDay[],
288
+ month: string,
289
+ ): YsMonthSummary {
290
+ const list = days.filter((item) => item.date.startsWith(`${month}-`));
291
+ const complete =
292
+ list.length === ysDaysInMonth(month) &&
293
+ list.every((item) => item.covered !== false);
294
+ const count = (test: (item: YsCalendarDay) => boolean) =>
295
+ list.filter(test).length;
296
+ return {
297
+ complete,
298
+ workdays: count((item) => Boolean(item.workday)),
299
+ trading: count((item) => Boolean(item.trading)),
300
+ closed: count((item) => !item.trading),
301
+ holidays: count((item) => item.kind === "holiday"),
302
+ adjusted: count((item) => item.kind === "adjusted"),
303
+ };
304
+ }
package/src/index.ts CHANGED
@@ -17,7 +17,14 @@ export {
17
17
  type YsDisconnectInfo,
18
18
  type YsWsClientOptions,
19
19
  } from "./ws";
20
- export { formatAmount, formatNumber, splitAmount, type YsAmountParts, type YsAmountUnit, type YsNumberFormatOptions } from "./number";
20
+ export {
21
+ formatAmount,
22
+ formatNumber,
23
+ splitAmount,
24
+ type YsAmountParts,
25
+ type YsAmountUnit,
26
+ type YsNumberFormatOptions,
27
+ } from "./number";
21
28
  export {
22
29
  currentEntry,
23
30
  latestEntry,
@@ -111,3 +118,29 @@ export {
111
118
  type YsStatusCounts,
112
119
  type YsStatusOption,
113
120
  } from "./status";
121
+ export {
122
+ YS_DAY_KIND_LABELS,
123
+ YS_TRADING_TAG_LABELS,
124
+ YS_WEEKDAY_LABELS,
125
+ ysAddDays,
126
+ ysDateTitle,
127
+ ysDaysBetween,
128
+ ysDaysInMonth,
129
+ ysIsDate,
130
+ ysMonthGrid,
131
+ ysMonthOf,
132
+ ysMonthRange,
133
+ ysMonthSummary,
134
+ ysMonthTitle,
135
+ ysShiftMonth,
136
+ ysToday,
137
+ ysTradingMarks,
138
+ ysWeekday,
139
+ ysWeekdayLabel,
140
+ type YsCalendarDay,
141
+ type YsMonthSummary,
142
+ type YsTradingMark,
143
+ type YsTradingTag,
144
+ type YsDayKind,
145
+ type YsMonthCell,
146
+ } from "./calendar";