File size: 9,190 Bytes
759768a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**

 * ACCURACY VALIDATOR

 * Validate data accuracy and consistency across the application

 */

export class AccuracyValidator {
    constructor() {
        this.validationRules = new Map();
        this.validationHistory = [];
        this.setupDefaultRules();
    }

    setupDefaultRules() {
        // Environmental data validation rules
        this.addRule('temperature', {
            min: -50,
            max: 60,
            unit: '°C',
            precision: 1
        });

        this.addRule('humidity', {
            min: 0,
            max: 100,
            unit: '%',
            precision: 1
        });

        this.addRule('airQuality', {
            min: 0,
            max: 500,
            unit: 'AQI',
            precision: 0
        });

        this.addRule('waterPH', {
            min: 0,
            max: 14,
            unit: 'pH',
            precision: 2
        });

        this.addRule('coordinates', {
            latitude: { min: -90, max: 90 },
            longitude: { min: -180, max: 180 },
            precision: 6
        });

        // Device pricing validation
        this.addRule('devicePrice', {
            min: 0,
            max: 10000,
            unit: '$',
            precision: 0
        });

        // Carbon footprint validation
        this.addRule('carbonFootprint', {
            min: 0,
            max: 1000,
            unit: 'kg CO2',
            precision: 2
        });
    }

    addRule(field, rule) {
        this.validationRules.set(field, rule);
    }

    validateField(field, value, context = {}) {
        const rule = this.validationRules.get(field);
        if (!rule) {
            return { valid: true, message: 'No validation rule found' };
        }

        const result = {
            valid: true,
            message: '',
            warnings: [],
            correctedValue: value
        };

        try {
            // Type validation
            if (typeof value !== 'number' && !Array.isArray(value) && typeof value !== 'object') {
                const numValue = parseFloat(value);
                if (isNaN(numValue)) {
                    result.valid = false;
                    result.message = `Invalid ${field}: must be a number`;
                    return result;
                }
                result.correctedValue = numValue;
                value = numValue;
            }

            // Range validation
            if (rule.min !== undefined && value < rule.min) {
                result.valid = false;
                result.message = `${field} value ${value} is below minimum ${rule.min}`;
                result.correctedValue = rule.min;
            }

            if (rule.max !== undefined && value > rule.max) {
                result.valid = false;
                result.message = `${field} value ${value} is above maximum ${rule.max}`;
                result.correctedValue = rule.max;
            }

            // Precision validation
            if (rule.precision !== undefined) {
                const rounded = parseFloat(value.toFixed(rule.precision));
                if (rounded !== value) {
                    result.warnings.push(`${field} rounded to ${rule.precision} decimal places`);
                    result.correctedValue = rounded;
                }
            }

            // Special validations
            if (field === 'coordinates') {
                return this.validateCoordinates(value, rule);
            }

            // Context-based validation
            if (context.previousValue !== undefined) {
                const change = Math.abs(value - context.previousValue);
                const threshold = (rule.max - rule.min) * 0.1; // 10% change threshold
                
                if (change > threshold) {
                    result.warnings.push(`Large change detected: ${change.toFixed(2)} ${rule.unit || ''}`);
                }
            }

        } catch (error) {
            result.valid = false;
            result.message = `Validation error: ${error.message}`;
        }

        // Record validation
        this.recordValidation(field, value, result);

        return result;
    }

    validateCoordinates(coords, rule) {
        const result = {
            valid: true,
            message: '',
            warnings: [],
            correctedValue: coords
        };

        if (!coords || typeof coords !== 'object') {
            result.valid = false;
            result.message = 'Coordinates must be an object with lat and lng properties';
            return result;
        }

        const { lat, lng } = coords;

        // Validate latitude
        if (typeof lat !== 'number' || lat < rule.latitude.min || lat > rule.latitude.max) {
            result.valid = false;
            result.message = `Invalid latitude: ${lat}. Must be between ${rule.latitude.min} and ${rule.latitude.max}`;
        }

        // Validate longitude
        if (typeof lng !== 'number' || lng < rule.longitude.min || lng > rule.longitude.max) {
            result.valid = false;
            result.message = `Invalid longitude: ${lng}. Must be between ${rule.longitude.min} and ${rule.longitude.max}`;
        }

        // Precision correction
        if (rule.precision !== undefined) {
            result.correctedValue = {
                lat: parseFloat(lat.toFixed(rule.precision)),
                lng: parseFloat(lng.toFixed(rule.precision))
            };
        }

        return result;
    }

    validateDataSet(data, schema = {}) {
        const results = {
            valid: true,
            errors: [],
            warnings: [],
            correctedData: { ...data }
        };

        for (const [field, value] of Object.entries(data)) {
            const context = schema[field] || {};
            const validation = this.validateField(field, value, context);

            if (!validation.valid) {
                results.valid = false;
                results.errors.push({
                    field,
                    message: validation.message,
                    value,
                    correctedValue: validation.correctedValue
                });
            }

            if (validation.warnings.length > 0) {
                results.warnings.push(...validation.warnings.map(w => ({ field, warning: w })));
            }

            results.correctedData[field] = validation.correctedValue;
        }

        return results;
    }

    recordValidation(field, value, result) {
        this.validationHistory.push({
            field,
            value,
            result,
            timestamp: Date.now()
        });

        // Keep only last 1000 validations
        if (this.validationHistory.length > 1000) {
            this.validationHistory = this.validationHistory.slice(-1000);
        }
    }

    getValidationStats() {
        const stats = {
            totalValidations: this.validationHistory.length,
            successRate: 0,
            fieldStats: new Map(),
            recentErrors: []
        };

        let successCount = 0;
        const now = Date.now();
        const oneHourAgo = now - (60 * 60 * 1000);

        this.validationHistory.forEach(validation => {
            if (validation.result.valid) {
                successCount++;
            } else if (validation.timestamp > oneHourAgo) {
                stats.recentErrors.push({
                    field: validation.field,
                    message: validation.result.message,
                    timestamp: validation.timestamp
                });
            }

            // Field statistics
            if (!stats.fieldStats.has(validation.field)) {
                stats.fieldStats.set(validation.field, {
                    total: 0,
                    errors: 0,
                    warnings: 0
                });
            }

            const fieldStat = stats.fieldStats.get(validation.field);
            fieldStat.total++;
            if (!validation.result.valid) fieldStat.errors++;
            if (validation.result.warnings && validation.result.warnings.length > 0) {
                fieldStat.warnings++;
            }
        });

        stats.successRate = stats.totalValidations > 0 ? 
            (successCount / stats.totalValidations) * 100 : 100;

        return stats;
    }

    clearHistory() {
        this.validationHistory = [];
    }
}

// Global validator instance
export const accuracyValidator = new AccuracyValidator();

// Utility functions
export const validateField = (field, value, context) => 
    accuracyValidator.validateField(field, value, context);

export const validateDataSet = (data, schema) => 
    accuracyValidator.validateDataSet(data, schema);

export const getValidationStats = () => 
    accuracyValidator.getValidationStats();

export const addValidationRule = (field, rule) => 
    accuracyValidator.addRule(field, rule);