All files / lib/awareness/collective/components/charts data-mapper.ts

0% Statements 0/53
0% Branches 0/1
0% Functions 0/1
0% Lines 0/53

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                                                   
// src/lib/awareness/collective/components/charts/data-mapper.ts
import { EvolutionLog } from '@/lib/evolution/history.collector';
import { ChartDataPoint } from './types';
 
/** تحويل أسماء الاتجاهات إلى أرقام */
const trendValueMap = { Integrate: 1, Reform: 2, Reset: 3 } as const;
 
/** يحوّل اللوجز الخام إلى نقاط رسم مرتّبة زمنيًا */
export function mapLogsToChartData(logs: EvolutionLog[]): ChartDataPoint[] {
  if (!Array.isArray(logs)) return [];
  return logs
    .map((log) => ({
      timestamp: new Date(log.timestamp).getTime(),
      trendValue: trendValueMap[log.trend],
      originalTrend: log.trend,
      confidence: log.confidence,
      changeRate: log.changeRate,
      notes: log.notes,
    }))
    .sort((a, b) => a.timestamp - b.timestamp);
}
 
/**
 * لو البيانات ضخمة (> threshold) بيجّمعها يوميًا لتسريع الرسم
 */
export function downsampleDaily(rows: ChartDataPoint[], threshold = 1000): ChartDataPoint[] {
  if (rows.length <= threshold) return rows;
 
  const byDay = new Map<string, ChartDataPoint[]>();
  for (const r of rows) {
    const d = new Date(r.timestamp);
    const key = `${d.getUTCFullYear()}-${d.getUTCMonth() + 1}-${d.getUTCDate()}`;
    const arr = byDay.get(key) ?? [];
    arr.push(r);
    byDay.set(key, arr);
  }
 
  const out: ChartDataPoint[] = [];
  for (const [key, arr] of byDay) {
    const freq: Record<number, number> = { 1: 0, 2: 0, 3: 0 };
    let tsSum = 0,
      confSum = 0,
      crSum = 0;
    for (const r of arr) {
      freq[r.trendValue]++;
      tsSum += r.timestamp;
      confSum += r.confidence;
      crSum += r.changeRate;
    }
    const trendValue = Object.entries(freq).sort((a, b) => b[1] - a[1])[0][0] as unknown as
      | 1
      | 2
      | 3;
    const originalTrend = trendValue === 1 ? 'Integrate' : trendValue === 2 ? 'Reform' : 'Reset';
    out.push({
      timestamp: Math.round(tsSum / arr.length),
      trendValue,
      originalTrend,
      confidence: confSum / arr.length,
      changeRate: crSum / arr.length,
    });
  }
 
  return out.sort((a, b) => a.timestamp - b.timestamp);
}