@asteby/metacore-runtime-react 46.1.0 → 46.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/CHANGELOG.md +6 -0
- package/dist/business/catalog.d.ts.map +1 -1
- package/dist/business/catalog.js +17 -0
- package/dist/business/index.d.ts +2 -0
- package/dist/business/index.d.ts.map +1 -1
- package/dist/business/index.js +2 -0
- package/dist/business/inspection-checklist.d.ts +36 -0
- package/dist/business/inspection-checklist.d.ts.map +1 -0
- package/dist/business/inspection-checklist.js +147 -0
- package/dist/business/inspection.d.ts +109 -0
- package/dist/business/inspection.d.ts.map +1 -0
- package/dist/business/inspection.js +176 -0
- package/package.json +1 -1
- package/src/__tests__/inspection-checklist.test.tsx +70 -0
- package/src/business/catalog.ts +17 -0
- package/src/business/index.ts +2 -0
- package/src/business/inspection-checklist.tsx +457 -0
- package/src/business/inspection.test.ts +125 -0
- package/src/business/inspection.ts +281 -0
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
// Inspección con checklist (recepción de vehículo, inspección multipunto, OT,
|
|
2
|
+
// alineación, garantía): lógica pura del <InspectionChecklist> (benchmark §7,
|
|
3
|
+
// TAL-4/TAL-5). El semáforo, el resumen y la salida hacia el backend viven aquí
|
|
4
|
+
// para que el componente y los addons (que guardan por una acción) coincidan.
|
|
5
|
+
import { makeLine, type LineItem } from './line-items'
|
|
6
|
+
import { roundMoney, toAmount } from './format'
|
|
7
|
+
|
|
8
|
+
/** Semáforo de un punto: pendiente (sin revisar), verde, amarillo, rojo. */
|
|
9
|
+
export type InspectionStatus = 'pending' | 'ok' | 'attention' | 'urgent'
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Qué captura el punto: `check` solo el semáforo; `tread` profundidad de dibujo
|
|
13
|
+
* en mm (el semáforo sale del valor); `measure` un valor numérico libre con su
|
|
14
|
+
* unidad. El nivel de combustible y el kilometraje van en el encabezado.
|
|
15
|
+
*/
|
|
16
|
+
export type InspectionPointKind = 'check' | 'tread' | 'measure'
|
|
17
|
+
|
|
18
|
+
export type InspectionMediaType = 'photo' | 'video'
|
|
19
|
+
|
|
20
|
+
export interface InspectionMedia {
|
|
21
|
+
/** Clave estable de UI. */
|
|
22
|
+
key: string
|
|
23
|
+
url: string
|
|
24
|
+
type: InspectionMediaType
|
|
25
|
+
caption?: string
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface InspectionPoint {
|
|
29
|
+
/** Clave estable de UI (no se envía). */
|
|
30
|
+
key: string
|
|
31
|
+
/** Id de la fila guardada, si ya existe. */
|
|
32
|
+
id?: string
|
|
33
|
+
/** Agrupa los puntos en el checklist («Llantas», «Frenos»...). */
|
|
34
|
+
section: string
|
|
35
|
+
name: string
|
|
36
|
+
kind: InspectionPointKind
|
|
37
|
+
status: InspectionStatus
|
|
38
|
+
/** Valor medido (`tread`/`measure`). */
|
|
39
|
+
value?: number | null
|
|
40
|
+
unit?: string
|
|
41
|
+
notes: string
|
|
42
|
+
/** Trabajo recomendado; con texto, el punto es un renglón candidato. */
|
|
43
|
+
recommendation: string
|
|
44
|
+
quantity: number
|
|
45
|
+
unit_price: number
|
|
46
|
+
media: InspectionMedia[]
|
|
47
|
+
/** Respuesta del cliente a la recomendación, cuando ya la dio. */
|
|
48
|
+
approval?: 'none' | 'pending' | 'approved' | 'declined'
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export type FuelLevel = 'empty' | 'quarter' | 'half' | 'three_quarters' | 'full'
|
|
52
|
+
|
|
53
|
+
export const FUEL_LEVELS: readonly FuelLevel[] = ['empty', 'quarter', 'half', 'three_quarters', 'full']
|
|
54
|
+
|
|
55
|
+
/** Encabezado de una recepción: lo que se ve al recibir el vehículo. */
|
|
56
|
+
export interface InspectionHeader {
|
|
57
|
+
odometer_km?: number | null
|
|
58
|
+
fuel_level?: FuelLevel | ''
|
|
59
|
+
/** Daños previos visibles, para deslindar responsabilidad. */
|
|
60
|
+
damage_notes: string
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Umbrales de profundidad de dibujo en mm (el límite legal común es 1.6). */
|
|
64
|
+
export interface TreadThresholds {
|
|
65
|
+
/** Por debajo de esto el semáforo es rojo. Default 1.6. */
|
|
66
|
+
urgent: number
|
|
67
|
+
/** Por debajo de esto (y sobre `urgent`) es amarillo. Default 3. */
|
|
68
|
+
attention: number
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export const DEFAULT_TREAD_THRESHOLDS: TreadThresholds = { urgent: 1.6, attention: 3 }
|
|
72
|
+
|
|
73
|
+
let seq = 0
|
|
74
|
+
export function newInspectionKey(prefix = 'ip'): string {
|
|
75
|
+
seq += 1
|
|
76
|
+
return `${prefix}-${Date.now().toString(36)}-${seq}`
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function makeInspectionPoint(partial: Partial<InspectionPoint> = {}): InspectionPoint {
|
|
80
|
+
return {
|
|
81
|
+
key: partial.key ?? newInspectionKey(),
|
|
82
|
+
section: '',
|
|
83
|
+
name: '',
|
|
84
|
+
kind: 'check',
|
|
85
|
+
status: 'pending',
|
|
86
|
+
notes: '',
|
|
87
|
+
recommendation: '',
|
|
88
|
+
quantity: 1,
|
|
89
|
+
unit_price: 0,
|
|
90
|
+
media: [],
|
|
91
|
+
...partial,
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Semáforo que le toca a una profundidad de dibujo. Sin valor: `pending`. */
|
|
96
|
+
export function treadStatus(mm: number | null | undefined, th: TreadThresholds = DEFAULT_TREAD_THRESHOLDS): InspectionStatus {
|
|
97
|
+
if (mm == null || !Number.isFinite(mm)) return 'pending'
|
|
98
|
+
if (mm < th.urgent) return 'urgent'
|
|
99
|
+
if (mm < th.attention) return 'attention'
|
|
100
|
+
return 'ok'
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const RANK: Record<InspectionStatus, number> = { pending: 0, ok: 1, attention: 2, urgent: 3 }
|
|
104
|
+
|
|
105
|
+
/** El peor estado de la lista (rojo > amarillo > verde > pendiente). */
|
|
106
|
+
export function worstStatus(points: Pick<InspectionPoint, 'status'>[]): InspectionStatus {
|
|
107
|
+
return points.reduce<InspectionStatus>((w, p) => (RANK[p.status] > RANK[w] ? p.status : w), 'pending')
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** ¿El punto trae una recomendación que se puede cotizar? */
|
|
111
|
+
export function hasRecommendation(p: Pick<InspectionPoint, 'recommendation'>): boolean {
|
|
112
|
+
return p.recommendation.trim() !== ''
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export interface InspectionSummary {
|
|
116
|
+
total: number
|
|
117
|
+
counts: Record<InspectionStatus, number>
|
|
118
|
+
worst: InspectionStatus
|
|
119
|
+
/** Puntos sin revisar. */
|
|
120
|
+
pending: number
|
|
121
|
+
/** Puntos con recomendación. */
|
|
122
|
+
recommendations: number
|
|
123
|
+
/** Suma cantidad × precio de las recomendaciones. */
|
|
124
|
+
recommendedTotal: number
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export function summarizeInspection(points: InspectionPoint[]): InspectionSummary {
|
|
128
|
+
const counts: Record<InspectionStatus, number> = { pending: 0, ok: 0, attention: 0, urgent: 0 }
|
|
129
|
+
let recommendations = 0
|
|
130
|
+
let recommendedTotal = 0
|
|
131
|
+
for (const p of points) {
|
|
132
|
+
counts[p.status] += 1
|
|
133
|
+
if (hasRecommendation(p)) {
|
|
134
|
+
recommendations += 1
|
|
135
|
+
recommendedTotal += p.quantity * p.unit_price
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return {
|
|
139
|
+
total: points.length,
|
|
140
|
+
counts,
|
|
141
|
+
worst: worstStatus(points),
|
|
142
|
+
pending: counts.pending,
|
|
143
|
+
recommendations,
|
|
144
|
+
recommendedTotal: roundMoney(recommendedTotal),
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export interface InspectionValidation {
|
|
149
|
+
ok: boolean
|
|
150
|
+
/** Errores por `"<índice>.<campo>"` (mismo contrato que LineItemsEditor). */
|
|
151
|
+
errors: Record<string, string>
|
|
152
|
+
/** Error de formulario (encabezado o conjunto). */
|
|
153
|
+
form?: string
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export interface InspectionRules {
|
|
157
|
+
/** Exige revisar todos los puntos (ninguno `pending`). Default false (borrador). */
|
|
158
|
+
requireAllReviewed?: boolean
|
|
159
|
+
/** Exige kilometraje en el encabezado (recepción). Default false. */
|
|
160
|
+
requireOdometer?: boolean
|
|
161
|
+
/** Un punto amarillo/rojo debe llevar nota, recomendación o evidencia. Default false. */
|
|
162
|
+
requireEvidenceOnIssues?: boolean
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export function validateInspection(
|
|
166
|
+
points: InspectionPoint[],
|
|
167
|
+
header?: InspectionHeader,
|
|
168
|
+
rules: InspectionRules = {},
|
|
169
|
+
): InspectionValidation {
|
|
170
|
+
const errors: Record<string, string> = {}
|
|
171
|
+
points.forEach((p, i) => {
|
|
172
|
+
if (p.name.trim() === '') errors[`${i}.name`] = 'Falta el nombre del punto'
|
|
173
|
+
if ((p.kind === 'tread' || p.kind === 'measure') && p.value != null && (!Number.isFinite(p.value) || p.value < 0)) {
|
|
174
|
+
errors[`${i}.value`] = 'La medición no puede ser negativa'
|
|
175
|
+
}
|
|
176
|
+
if (p.quantity < 0 || p.unit_price < 0) errors[`${i}.unit_price`] = 'Cantidad y precio no pueden ser negativos'
|
|
177
|
+
if (hasRecommendation(p) && p.status === 'ok') {
|
|
178
|
+
errors[`${i}.recommendation`] = 'Un punto en verde no lleva recomendación'
|
|
179
|
+
}
|
|
180
|
+
if (
|
|
181
|
+
rules.requireEvidenceOnIssues &&
|
|
182
|
+
(p.status === 'attention' || p.status === 'urgent') &&
|
|
183
|
+
p.notes.trim() === '' &&
|
|
184
|
+
!hasRecommendation(p) &&
|
|
185
|
+
p.media.length === 0
|
|
186
|
+
) {
|
|
187
|
+
errors[`${i}.notes`] = 'Anota, recomienda o agrega una foto'
|
|
188
|
+
}
|
|
189
|
+
})
|
|
190
|
+
let form: string | undefined
|
|
191
|
+
if (rules.requireAllReviewed && points.some((p) => p.status === 'pending')) {
|
|
192
|
+
form = 'Faltan puntos por revisar'
|
|
193
|
+
}
|
|
194
|
+
if (rules.requireOdometer && header && (header.odometer_km == null || !(header.odometer_km >= 0))) {
|
|
195
|
+
form = form ?? 'Captura el kilometraje'
|
|
196
|
+
}
|
|
197
|
+
return { ok: Object.keys(errors).length === 0 && !form, errors, form }
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Única puerta de salida hacia el backend: números reales, sin claves de UI,
|
|
202
|
+
* opcionales vacíos omitidos y `line_no` 1-based (mismo criterio que
|
|
203
|
+
* `serializeLineItems`).
|
|
204
|
+
*/
|
|
205
|
+
export function serializeInspectionPoints(points: InspectionPoint[]): Record<string, unknown>[] {
|
|
206
|
+
return points.map((p, i) => {
|
|
207
|
+
const o: Record<string, unknown> = {
|
|
208
|
+
line_no: i + 1,
|
|
209
|
+
section: p.section.trim(),
|
|
210
|
+
name: p.name.trim(),
|
|
211
|
+
kind: p.kind,
|
|
212
|
+
status: p.status,
|
|
213
|
+
notes: p.notes.trim(),
|
|
214
|
+
recommendation: p.recommendation.trim(),
|
|
215
|
+
quantity: toAmount(p.quantity),
|
|
216
|
+
unit_price: toAmount(p.unit_price),
|
|
217
|
+
media: p.media.map((m) => ({ url: m.url, type: m.type, ...(m.caption ? { caption: m.caption } : {}) })),
|
|
218
|
+
}
|
|
219
|
+
if (p.id) o.id = p.id
|
|
220
|
+
if (p.value != null && Number.isFinite(p.value)) o.measure_value = p.value
|
|
221
|
+
if (p.unit) o.unit = p.unit
|
|
222
|
+
return o
|
|
223
|
+
})
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** Inversa de `serializeInspectionPoints`: filas del backend a puntos de UI. */
|
|
227
|
+
export function parseInspectionPoints(rows: unknown): InspectionPoint[] {
|
|
228
|
+
if (!Array.isArray(rows)) return []
|
|
229
|
+
const str = (v: unknown) => (typeof v === 'string' ? v : v == null ? '' : String(v))
|
|
230
|
+
return rows.map((r) => {
|
|
231
|
+
const o = (r ?? {}) as Record<string, unknown>
|
|
232
|
+
const status = str(o.status) as InspectionStatus
|
|
233
|
+
const kind = str(o.kind) as InspectionPointKind
|
|
234
|
+
const media = Array.isArray(o.media)
|
|
235
|
+
? (o.media as Record<string, unknown>[]).map((m) => ({
|
|
236
|
+
key: newInspectionKey('im'),
|
|
237
|
+
url: str(m.url),
|
|
238
|
+
type: (str(m.type) === 'video' ? 'video' : 'photo') as InspectionMediaType,
|
|
239
|
+
caption: str(m.caption) || undefined,
|
|
240
|
+
}))
|
|
241
|
+
: []
|
|
242
|
+
const value = o.measure_value ?? o.value
|
|
243
|
+
return makeInspectionPoint({
|
|
244
|
+
id: str(o.id) || undefined,
|
|
245
|
+
section: str(o.section),
|
|
246
|
+
name: str(o.name),
|
|
247
|
+
kind: kind === 'tread' || kind === 'measure' ? kind : 'check',
|
|
248
|
+
status: status in RANK ? status : 'pending',
|
|
249
|
+
value: value == null || value === '' ? null : toAmount(value),
|
|
250
|
+
unit: str(o.unit) || undefined,
|
|
251
|
+
notes: str(o.notes),
|
|
252
|
+
recommendation: str(o.recommendation),
|
|
253
|
+
quantity: o.quantity == null ? 1 : toAmount(o.quantity),
|
|
254
|
+
unit_price: toAmount(o.unit_price),
|
|
255
|
+
media,
|
|
256
|
+
approval: ['none', 'pending', 'approved', 'declined'].includes(str(o.approval))
|
|
257
|
+
? (str(o.approval) as InspectionPoint['approval'])
|
|
258
|
+
: undefined,
|
|
259
|
+
})
|
|
260
|
+
})
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Recomendación → renglón del presupuesto: cada punto con recomendación se
|
|
265
|
+
* vuelve un renglón `item` (descripción «Punto — recomendación»). Se puede
|
|
266
|
+
* filtrar por respuesta del cliente (p. ej. solo las aprobadas).
|
|
267
|
+
*/
|
|
268
|
+
export function recommendationsToLines(
|
|
269
|
+
points: InspectionPoint[],
|
|
270
|
+
opts: { approval?: InspectionPoint['approval'][] } = {},
|
|
271
|
+
): LineItem[] {
|
|
272
|
+
return points
|
|
273
|
+
.filter((p) => hasRecommendation(p) && (!opts.approval || (p.approval != null && opts.approval.includes(p.approval))))
|
|
274
|
+
.map((p) =>
|
|
275
|
+
makeLine({
|
|
276
|
+
description: `${p.name} — ${p.recommendation.trim()}`,
|
|
277
|
+
quantity: p.quantity > 0 ? p.quantity : 1,
|
|
278
|
+
unit_price: p.unit_price,
|
|
279
|
+
}),
|
|
280
|
+
)
|
|
281
|
+
}
|