Blame view

泰额版/Food Labeling Management App UniApp/src/utils/labelPreview/printInputOffset.ts 12.1 KB
59e51671   “wangming”   1
1
2
3
4
  /**
   * 与 Web 管理端 labelFormDatePreview 一致:templateProductDefaults 中日期/时间/时长存 JSON
   * `{"unit":"Days","value":"2"}`,预览与打印时按 BaseTime 解析为 config.text。
   */
fdce24a6   杨鑫   修改bug
5
  import type { SystemLabelTemplate, SystemTemplateElementBase } from '../print/types/printer'
59e51671   “wangming”   1
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
  
  const OFFSET_UNITS = new Set([
    'Minutes',
    'Hours',
    'Days',
    'Weeks',
    'Months (30 Day)',
    'Years',
  ])
  
  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
  }
  
  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')
fdce24a6   杨鑫   修改bug
51
52
53
    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()
59e51671   “wangming”   1
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
    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
fdce24a6   杨鑫   修改bug
73
74
75
76
77
78
79
80
81
82
      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}`
59e51671   “wangming”   1
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
      case 'YYYY-MM-DD':
        return `${yyyy}-${mm}-${dd}`
      case 'YYYY-MM-DD HH:mm':
        return `${yyyy}-${mm}-${dd} ${hh}:${min}`
      case 'HH:mm':
        return `${hh}:${min}`
      default:
        return String(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)
    }
  }
  
fdce24a6   杨鑫   修改bug
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
  /** 已算好的日期/时间展示串(非 format 预设名、非 JSON 偏移) */
  export function isLikelyResolvedDateTimeLiteral (raw: string | null | undefined): boolean {
    const t = String(raw ?? '').trim()
    if (!t || t.startsWith('{')) return false
    if (OFFSET_UNITS.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
  }
  
  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 normalizeOffsetAmount (valueRaw: string): number | null {
    const t = String(valueRaw ?? '').trim()
    if (t === '') return 0
    const n = Number(t)
    return Number.isFinite(n) ? n : null
  }
  
  function dateFormatPatternForElement (
    el: SystemTemplateElementBase,
    cfg: Record<string, unknown>,
  ): string {
    const type = String(el.type || '').toUpperCase()
    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_UNITS.has(raw)) {
      return it === 'datetime' ? 'YYYY-MM-DD HH:mm' : 'DD/MM/YYYY'
    }
    return raw
  }
  
  function readOffsetFromElementConfig (
    el: SystemTemplateElementBase,
  ): { amount: number; unit: string } | null {
    const type = String(el.type || '').toUpperCase()
    const cfg = (el.config || {}) as Record<string, unknown>
    if (type === 'DURATION') {
      const unit = String(cfg.format ?? cfg.Format ?? 'Days').trim() || 'Days'
      const u = OFFSET_UNITS.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_UNITS.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: SystemTemplateElementBase,
    amount: number,
    unit: string,
    base: Date,
  ): string {
    const type = String(el.type || '').toUpperCase()
    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())
  }
  
  /**
   * 画布预览 / 原生打印:按基准时刻解析 DATE/TIME/DURATION,忽略 AUTO_DB 上已过期的 text/format。
   */
  export function resolveElementDateTimeDisplay (
    el: SystemTemplateElementBase,
    base: Date = new Date(),
  ): string | null {
    const type = String(el.type || '').toUpperCase()
    if (type !== 'DATE' && type !== 'TIME' && type !== 'DURATION') return null
  
    const cfg = (el.config || {}) as Record<string, unknown>
    const vst = String(el.valueSourceType ?? '').toUpperCase()
    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 amount = normalizeOffsetAmount(p.value)
      if (amount === null) return null
      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') {
      /** 保质期/Prep 等相对偏移字段:须按 base 重算,勿用接口首屏写入的过期 literal */
      if (
        rawText &&
        !tryParsePrintInputOffsetStored(rawText) &&
        !isUniAppDateTimeOffsetField(el)
      ) {
        return applyElementPrefix(cfg, rawText)
      }
      if (
        isUniAppDateTimeOffsetField(el) ||
        inputType === 'date' ||
        inputType === 'datetime' ||
        type === 'TIME'
      ) {
        const off = readOffsetFromElementConfig(el)
        if (off) return resolveFromOffsetAmount(el, off.amount, off.unit, base)
        /** 默认值已展开为字面日期时仍保留,避免丢失 durationdate 等 +N Days */
        if (
          rawText &&
          !tryParsePrintInputOffsetStored(rawText) &&
          isLikelyResolvedDateTimeLiteral(rawText) &&
          !isUniAppDateTimeOffsetField(el)
        ) {
          return applyElementPrefix(cfg, rawText)
        }
        return resolveFromOffsetAmount(el, 0, 'Days', base)
      }
      return null
    }
  
    /** FIXED 的 durationdate/durationtime 等:config.text 可能已是平台录入的偏移 JSON */
    if (vst === 'FIXED' && isUniAppDateTimeOffsetField(el)) {
      const off = readOffsetFromElementConfig(el)
      if (off && (off.amount !== 0 || rawText)) {
        return resolveFromOffsetAmount(el, off.amount, off.unit, base)
      }
      if (
        rawText &&
        !tryParsePrintInputOffsetStored(rawText) &&
        isLikelyResolvedDateTimeLiteral(rawText)
      ) {
        return applyElementPrefix(cfg, rawText)
      }
      return resolveFromOffsetAmount(el, 0, 'Days', base)
    }
  
    const off = readOffsetFromElementConfig(el)
    if (off) return resolveFromOffsetAmount(el, off.amount, off.unit, base)
    if (
      rawText &&
      !tryParsePrintInputOffsetStored(rawText) &&
      isLikelyResolvedDateTimeLiteral(rawText) &&
      isUniAppDateTimeOffsetField(el)
    ) {
      return applyElementPrefix(cfg, rawText)
    }
    return resolveFromOffsetAmount(el, 0, 'Days', base)
  }
  
59e51671   “wangming”   1
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
  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_UNITS.has(unit)) return null
      return { unit, value }
    } catch {
      return null
    }
  }
  
  /** 与 Web isDateTimeDataEntryField 对齐(App 侧元素无 typeAdd 时用命名兜底) */
  export function isUniAppDateTimeOffsetField (el: SystemTemplateElementBase): boolean {
    const type = String(el.type || '').toUpperCase()
    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 = String((el as { typeAdd?: string }).typeAdd ?? '').trim().toLowerCase().replace(/\s+/g, ' ')
    if (ta === 'label_duration date' || ta.includes('duration date')) return true
fdce24a6   杨鑫   修改bug
312
313
    if (ta === 'auto_current date' || ta.includes('current date')) return true
    if (ta === 'auto_current time' || ta.includes('current time')) return true
59e51671   “wangming”   1
314
315
316
317
318
319
    const nameHint = `${el.elementName ?? ''} ${el.inputKey ?? ''}`.toLowerCase()
    if (/(durationdate|duration_date|duration\s*date)/.test(nameHint)) return true
    return false
  }
  
  /**
fdce24a6   杨鑫   修改bug
320
   * 预览/出纸前:按同一基准时刻重算所有 DATE/TIME/DURATION 及偏移类字段,保证 Prep 与 Use By 一致。
59e51671   “wangming”   1
321
   */
fdce24a6   杨鑫   修改bug
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
  export function applyLiveDateTimeFieldsToTemplate (
    template: SystemLabelTemplate,
    base: Date = new Date(),
  ): SystemLabelTemplate {
    const elements = (template.elements || []).map((el) => {
      const type = String(el.type || '').toUpperCase()
      const needsLive =
        type === 'DATE' ||
        type === 'TIME' ||
        type === 'DURATION' ||
        isUniAppDateTimeOffsetField(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.text = live
      cfg.Text = live
      return { ...el, config: cfg }
    })
    return { ...template, elements }
  }
  
59e51671   “wangming”   1
344
345
346
347
348
349
350
351
352
  export function resolveTemplateDefaultValueForElement (
    el: SystemTemplateElementBase,
    stored: string,
    now: Date,
  ): string {
    const s = String(stored ?? '').trim()
    if (!s) return ''
    if (!isUniAppDateTimeOffsetField(el)) return s
    const parsed = tryParsePrintInputOffsetStored(s)
fdce24a6   杨鑫   修改bug
353
354
355
356
    if (parsed) {
      const amount = normalizeOffsetAmount(parsed.value)
      if (amount === null) return ''
      return resolveFromOffsetAmount(el, amount, parsed.unit || 'Days', now)
59e51671   “wangming”   1
357
    }
fdce24a6   杨鑫   修改bug
358
359
360
    if (isLikelyResolvedDateTimeLiteral(s)) {
      const off = readOffsetFromElementConfig(el)
      return resolveFromOffsetAmount(el, off?.amount ?? 0, off?.unit ?? 'Days', now)
59e51671   “wangming”   1
361
    }
fdce24a6   杨鑫   修改bug
362
    return s
59e51671   “wangming”   1
363
  }