labelFormDatePreview.ts
14.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
import type { LabelElement } from "../types/labelTemplate";
import {
canonicalElementType,
elementInputKey,
isDateTimeDataEntryField,
normalizeValueSourceTypeForElement,
resolvedTypeAddForPersist,
} from "../types/labelTemplate";
/**
* 标签创建/编辑表单:相对时间偏移 + 按模板 format 预览(与 LabelCanvas formatDateByPreset 对齐)
*/
export const LABEL_FORM_OFFSET_UNITS = [
"Minutes",
"Hours",
"Days",
"Weeks",
"Months (30 Day)",
"Years",
] as const;
export type LabelFormOffsetUnit = (typeof LABEL_FORM_OFFSET_UNITS)[number];
export function applyOffsetToDate(base: Date, amount: number, unit: string): Date {
const d = new Date(base.getTime());
const u = String(unit ?? "").trim();
switch (u) {
case "Minutes":
d.setMinutes(d.getMinutes() + amount);
break;
case "Hours":
d.setHours(d.getHours() + amount);
break;
case "Days":
d.setDate(d.getDate() + amount);
break;
case "Weeks":
d.setDate(d.getDate() + amount * 7);
break;
case "Months (30 Day)":
d.setDate(d.getDate() + amount * 30);
break;
case "Years":
d.setFullYear(d.getFullYear() + amount);
break;
default:
d.setDate(d.getDate() + amount);
}
return d;
}
/** 与 LabelCanvas 中 formatDateByPreset 一致 */
export function formatDateByPreset(format: string, date: Date): string {
const yyyy = String(date.getFullYear());
const yy = yyyy.slice(-2);
const mm = String(date.getMonth() + 1).padStart(2, "0");
const dd = String(date.getDate()).padStart(2, "0");
const hh = String(date.getHours()).padStart(2, "0");
const min = String(date.getMinutes()).padStart(2, "0");
const monthLong = date.toLocaleString("en-US", { month: "long" }).toUpperCase();
const dayLong = date.toLocaleString("en-US", { weekday: "long" }).toUpperCase();
const dayShort = date.toLocaleString("en-US", { weekday: "short" }).toUpperCase();
const monthShort = date.toLocaleString("en-US", { month: "short" }).toUpperCase();
switch (format) {
case "DD/MM/YYYY":
return `${dd}/${mm}/${yyyy}`;
case "MM/DD/YYYY":
return `${mm}/${dd}/${yyyy}`;
case "DD/MM/YY":
return `${dd}/${mm}/${yy}`;
case "MM/DD/YY":
return `${mm}/${dd}/${yy}`;
case "MM/YY":
return `${mm}/${yy}`;
case "MM/DD":
return `${mm}/${dd}`;
case "MM":
return mm;
case "DD":
return dd;
case "YY":
return yy;
case "FULLY DAY(WEDNESDAY)":
return dayLong;
case "DAY (WED)":
return dayShort;
case "MONTH (DECEMBER)":
return monthLong;
case "YEAR (2025)":
return yyyy;
case "DD MONTH YEAR (25 DECEMBER 2025)":
return `${dd} ${monthLong} ${yyyy}`;
default:
return format
.replace(/YYYY/g, yyyy)
.replace(/YY/g, yy)
.replace(/MM/g, mm)
.replace(/DD/g, dd)
.replace(/HH/g, hh)
.replace(/mm/g, min);
}
}
const OFFSET_UNIT_SET = new Set<string>(LABEL_FORM_OFFSET_UNITS as unknown as string[]);
/** 已算好的日期/时间展示串(非 format 预设名、非 JSON 偏移) */
export function isLikelyResolvedDateTimeLiteral(raw: string | null | undefined): boolean {
const t = String(raw ?? "").trim();
if (!t || t.startsWith("{")) return false;
if (OFFSET_UNIT_SET.has(t)) return false;
if (/^\d{4}-\d{2}-\d{2}/.test(t)) return true;
if (/^\d{4}-\d{2}-\d{2}\s+\d{1,2}:\d{2}/.test(t)) return true;
if (/^\d{1,2}\/\d{1,2}\/\d{2,4}/.test(t)) return true;
if (/^\d{1,2}:\d{2}(:\d{2})?$/.test(t)) return true;
return false;
}
export type NormalizedLabelFormOffset =
| { kind: "zero" }
| { kind: "amount"; amount: number; storeValue: string }
| { kind: "invalid" };
/**
* 创建/编辑标签表单:日期时间类偏移的**空串**或**数值 0**(含 0、0.0、+0 等)均视为相对基准偏移 0;
* 预览即「当前基准时刻」;落库建议用 {@link serializePrintInputOffset}(unit, "0")。
*/
export function normalizeLabelFormOffsetInput(valueRaw: string | undefined): NormalizedLabelFormOffset {
const t = String(valueRaw ?? "").trim();
if (t === "") return { kind: "zero" };
const n = Number(t);
if (!Number.isFinite(n)) return { kind: "invalid" };
if (n === 0) return { kind: "zero" };
return { kind: "amount", amount: n, storeValue: t };
}
/**
* 模板 productDefault 中日期/时间/时长录入:存 `{"unit":"Days","value":"2"}`,供 App 与打印按 BaseTime 解析。
*/
export function serializePrintInputOffset(unit: string, value: string): string {
const u = String(unit ?? "").trim() || "Days";
return JSON.stringify({ unit: u, value: String(value ?? "") });
}
export function tryParsePrintInputOffsetStored(
raw: string | null | undefined,
): { unit: string; value: string } | null {
const t = String(raw ?? "").trim();
if (!t.startsWith("{")) return null;
try {
const o = JSON.parse(t) as unknown;
if (o == null || typeof o !== "object" || Array.isArray(o)) return null;
const rec = o as Record<string, unknown>;
const unit = String(rec.unit ?? rec.Unit ?? "").trim();
const value = String(rec.value ?? rec.Value ?? "");
if (!unit || !OFFSET_UNIT_SET.has(unit)) return null;
return { unit, value };
} catch {
return null;
}
}
/** 批量录入格:无 JSON 时纯数字按 Days 预填,便于兼容旧 duration 整数 */
export function offsetFieldUiStateFromStored(stored: string | undefined): { unit: string; value: string } {
const p = tryParsePrintInputOffsetStored(stored);
if (p) return p;
const t = String(stored ?? "").trim();
if (/^\d+$/.test(t)) return { unit: "Days", value: t };
return { unit: "Days", value: "" };
}
/**
* 将落库的 JSON(或旧版纯文案)解析为画布/预览用的展示字符串(相对 base 时间)。
*/
export function resolveStoredPrintValueToDisplayText(
el: LabelElement,
stored: string,
base: Date,
): string {
const s = String(stored ?? "").trim();
if (!s) return "";
if (!isDateTimeDataEntryField(el)) return s;
const parsed = tryParsePrintInputOffsetStored(s);
if (!parsed) {
if (isLikelyResolvedDateTimeLiteral(s)) {
const norm = normalizeLabelFormOffsetInput("0");
const amount = norm.kind === "zero" ? 0 : norm.kind === "amount" ? norm.amount : 0;
const unit = "Days";
const d = applyOffsetToDate(base, amount, unit);
const type = canonicalElementType(el.type);
const cfg = el.config as Record<string, unknown>;
if (type === "DATE") {
const it = String(cfg.inputType ?? cfg.InputType ?? "").toLowerCase();
const format =
(typeof cfg.format === "string" && cfg.format.trim()
? cfg.format
: typeof cfg.Format === "string" && cfg.Format.trim()
? cfg.Format
: it === "datetime"
? "YYYY-MM-DD HH:mm"
: "DD/MM/YYYY") ?? "DD/MM/YYYY";
const fmt = isLikelyResolvedDateTimeLiteral(format)
? it === "datetime"
? "YYYY-MM-DD HH:mm"
: "DD/MM/YYYY"
: format;
return formatDateByPreset(fmt, d);
}
if (type === "TIME") return formatDateByPreset("HH:mm", d);
}
return s;
}
const unit = parsed.unit || "Days";
const norm = normalizeLabelFormOffsetInput(parsed.value);
if (norm.kind === "invalid") return s;
const amount = norm.kind === "zero" ? 0 : norm.amount;
const type = canonicalElementType(el.type);
const d = applyOffsetToDate(base, amount, unit);
const cfg = el.config as Record<string, unknown>;
if (type === "DATE") {
const it = String(cfg.inputType ?? cfg.InputType ?? "").toLowerCase();
const format =
(typeof cfg.format === "string" && cfg.format.trim()
? cfg.format
: typeof cfg.Format === "string" && cfg.Format.trim()
? cfg.Format
: it === "datetime"
? "YYYY-MM-DD HH:mm"
: "DD/MM/YYYY") ?? "DD/MM/YYYY";
return formatDateByPreset(format, d);
}
if (type === "TIME") {
return formatDateByPreset("HH:mm", d);
}
return `${amount} ${unit}`;
}
function applyElementPrefix(cfg: Record<string, unknown>, body: string): string {
const prefix = String(cfg.prefix ?? cfg.Prefix ?? "");
if (!prefix) return body;
if (body.startsWith(prefix)) return body;
return `${prefix}${body}`;
}
function dateFormatPatternForElement(el: LabelElement, cfg: Record<string, unknown>): string {
const type = canonicalElementType(el.type);
if (type === "TIME") return "HH:mm";
const it = String(cfg.inputType ?? cfg.InputType ?? "").toLowerCase();
const raw =
(typeof cfg.format === "string" && cfg.format.trim()
? cfg.format
: typeof cfg.Format === "string" && cfg.Format.trim()
? cfg.Format
: it === "datetime"
? "YYYY-MM-DD HH:mm"
: "DD/MM/YYYY") || "DD/MM/YYYY";
if (isLikelyResolvedDateTimeLiteral(raw) || OFFSET_UNIT_SET.has(raw)) {
return it === "datetime" ? "YYYY-MM-DD HH:mm" : "DD/MM/YYYY";
}
return raw;
}
function readOffsetFromElementConfig(el: LabelElement): { amount: number; unit: string } | null {
const type = canonicalElementType(el.type);
const cfg = (el.config ?? {}) as Record<string, unknown>;
if (type === "DURATION") {
const unit = String(cfg.format ?? cfg.Format ?? "Days").trim() || "Days";
const u = OFFSET_UNIT_SET.has(unit) ? unit : "Days";
const rawV =
cfg.durationValue ??
cfg.value ??
cfg.offsetDays ??
cfg.DurationValue ??
cfg.Value ??
cfg.OffsetDays;
const val = Number(rawV);
return { amount: Number.isFinite(val) ? val : 0, unit: u };
}
const od = cfg.offsetDays ?? cfg.OffsetDays;
if (od != null && String(od).trim() !== "") {
const n = Number(od);
if (Number.isFinite(n)) return { amount: n, unit: "Days" };
}
const fmt = String(cfg.format ?? cfg.Format ?? "").trim();
if (fmt && OFFSET_UNIT_SET.has(fmt)) {
const rawV = cfg.durationValue ?? cfg.value ?? cfg.DurationValue ?? cfg.Value ?? 0;
const val = Number(rawV);
return { amount: Number.isFinite(val) ? val : 0, unit: fmt };
}
return null;
}
function resolveFromOffsetAmount(
el: LabelElement,
amount: number,
unit: string,
base: Date,
): string {
const type = canonicalElementType(el.type);
const cfg = (el.config ?? {}) as Record<string, unknown>;
const d = applyOffsetToDate(base, amount, unit);
if (type === "DATE") {
return applyElementPrefix(cfg, formatDateByPreset(dateFormatPatternForElement(el, cfg), d));
}
if (type === "TIME") {
return applyElementPrefix(cfg, formatDateByPreset("HH:mm", d));
}
return applyElementPrefix(cfg, `${amount} ${unit}`.trim());
}
/** 与 App isUniAppDateTimeOffsetField 对齐:含 auto current date/time 等相对基准解析字段 */
export function isDateTimeLiveResolveField(el: LabelElement): boolean {
const type = canonicalElementType(el.type);
const cfg = (el.config ?? {}) as Record<string, unknown>;
if (type === "TIME" || type === "DURATION") return true;
if (type !== "DATE") return false;
const it = String(cfg.inputType ?? cfg.InputType ?? "").toLowerCase();
if (it === "datetime" || it === "date") return true;
const ta = resolvedTypeAddForPersist(el).trim().toLowerCase().replace(/\s+/g, " ");
if (ta === "label_duration date" || ta.includes("duration date")) return true;
if (ta === "auto_current date" || ta.includes("current date")) return true;
if (ta === "auto_current time" || ta.includes("current time")) return true;
const nameHint = `${el.elementName ?? ""} ${elementInputKey(el)}`.toLowerCase();
if (/(durationdate|duration_date|duration\s*date)/.test(nameHint)) return true;
return false;
}
/**
* 画布预览 / 打印:按基准时刻解析 DATE/TIME/DURATION(与 App resolveElementDateTimeDisplay 一致)。
*/
export function resolveElementDateTimeDisplay(
el: LabelElement,
base: Date = new Date(),
): string | null {
const type = canonicalElementType(el.type);
if (type !== "DATE" && type !== "TIME" && type !== "DURATION") return null;
const cfg = (el.config ?? {}) as Record<string, unknown>;
const vst = normalizeValueSourceTypeForElement(el);
const inputType = String(cfg.inputType ?? cfg.InputType ?? "").toLowerCase();
const rawText = String(cfg.text ?? cfg.Text ?? "").trim();
const fromOffsetJson = (raw: string): string | null => {
const p = tryParsePrintInputOffsetStored(raw);
if (!p) return null;
const norm = normalizeLabelFormOffsetInput(p.value);
if (norm.kind === "invalid") return null;
const amount = norm.kind === "zero" ? 0 : norm.amount;
return resolveFromOffsetAmount(el, amount, p.unit || "Days", base);
};
const jsonResolved =
(rawText ? fromOffsetJson(rawText) : null) ??
fromOffsetJson(String(cfg.format ?? cfg.Format ?? ""));
if (jsonResolved) return jsonResolved;
if (vst === "PRINT_INPUT") {
if (
rawText &&
!tryParsePrintInputOffsetStored(rawText) &&
!isDateTimeLiveResolveField(el)
) {
return applyElementPrefix(cfg, rawText);
}
if (
isDateTimeLiveResolveField(el) ||
inputType === "date" ||
inputType === "datetime" ||
type === "TIME"
) {
const off = readOffsetFromElementConfig(el);
return resolveFromOffsetAmount(el, off?.amount ?? 0, off?.unit ?? "Days", base);
}
return null;
}
const off = readOffsetFromElementConfig(el);
if (off) return resolveFromOffsetAmount(el, off.amount, off.unit, base);
return resolveFromOffsetAmount(el, 0, "Days", base);
}
/** 预览前:按同一基准时刻重算所有 DATE/TIME/DURATION,写入 __previewFormatted */
export function applyLiveDateTimePreviewToElements(
elements: LabelElement[],
base: Date = new Date(),
): LabelElement[] {
return elements.map((el) => {
const type = canonicalElementType(el.type);
const needsLive =
type === "DATE" ||
type === "TIME" ||
type === "DURATION" ||
isDateTimeLiveResolveField(el);
if (!needsLive) return el;
const live = resolveElementDateTimeDisplay(el, base);
if (live == null || !String(live).trim()) return el;
const cfg = { ...(el.config as Record<string, unknown>) };
cfg.__previewFormatted = live;
return { ...el, config: cfg };
});
}