{
  "name": "Coach santé - ingestion Apple Santé",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "coach-sante-ingestion",
        "authentication": "headerAuth",
        "responseMode": "responseNode",
        "options": {}
      },
      "id": "7075e67d-ce7c-4e9d-93e4-d79c5d1738a1",
      "name": "Webhook Health Auto Export",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2.1,
      "position": [0, 0],
      "notesInFlow": true,
      "notes": "POST depuis iPhone, auth par en-tete",
      "credentials": {
        "httpHeaderAuth": { "id": "", "name": "Jeton Health Auto Export" }
      }
    },
    {
      "parameters": {
        "jsCode": "// Health Auto Export -> lots d'INSERT ... ON DUPLICATE KEY UPDATE (MySQL / MariaDB).\n// Chaque item de sortie porte sa propre requête et ses valeurs : le node MySQL\n// s'exécute une fois par item. Pas de JSON_TABLE ni de CONVERT_TZ, donc\n// compatible MariaDB comme MySQL, anciennes versions comprises.\n\nconst CHUNK = 500;              // lignes par requête (agrégation minute : gros lots)\nconst KEEP_ECG_VOLTAGE = true;  // false = ne pas stocker le tracé ECG (~1 Mo par enregistrement)\n\nconst body = $input.first().json.body ?? $input.first().json ?? {};\nconst data = body.data ?? body;\n\nconst RE_FULL = /^(\\d{4}-\\d{2}-\\d{2})[ T](\\d{2}:\\d{2}:\\d{2})(?:\\.\\d+)?\\s*(Z|[+-]\\d{2}:?\\d{2})?$/;\nconst RE_DAY = /^(\\d{4}-\\d{2}-\\d{2})$/;\n\n// \"2026-09-17 23:40:00 +0200\" -> { ts: \"2026-09-17 21:40:00\" (UTC), day: \"2026-09-17\" }\n// Le jour civil vient de l'horodatage tel que le téléphone l'a écrit, donc déjà\n// en heure locale : pas besoin de charger les tables de fuseaux côté MySQL.\n// Le sommeil peut arriver en date seule (\"2026-09-17\") : traité à minuit local.\nconst parseDate = (raw) => {\n  if (!raw) return null;\n  const s = String(raw).trim();\n\n  const dayOnly = s.match(RE_DAY);\n  if (dayOnly) return { ts: `${dayOnly[1]} 00:00:00`, day: dayOnly[1] };\n\n  const m = s.match(RE_FULL);\n  if (!m) return null;\n  let tz = m[3] ?? 'Z';\n  if (/^[+-]\\d{4}$/.test(tz)) tz = tz.slice(0, 3) + ':' + tz.slice(3);\n  const d = new Date(`${m[1]}T${m[2]}${tz}`);\n  if (Number.isNaN(d.getTime())) return null;\n  const ts = d.toISOString().slice(0, 19).replace('T', ' ');\n  let day = tz === 'Z' ? null : m[1]; // offset explicite => date locale telle quelle\n  if (!day) {\n    try {\n      day = DateTime.fromJSDate(d).setZone('Europe/Paris').toISODate(); // Luxon, fourni par n8n\n    } catch (e) {\n      day = ts.slice(0, 10); // dernier recours : jour UTC\n    }\n  }\n  return { ts, day };\n};\n\nconst num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);\nconst str = (v, n) => (v === undefined || v === null ? null : String(v).slice(0, n));\n\n// Un point peut donner plusieurs lignes : la tension se scinde en systolique et\n// diastolique, le sommeil en phases, pour que chaque série soit traçable seule.\nconst expand = (name, p) => {\n  const out = [];\n  const add = (suffix, qty) => {\n    if (qty !== null) out.push({ metric: suffix ? `${name}_${suffix}` : name, qty });\n  };\n\n  if (name === 'blood_pressure') {\n    add('systolic', num(p.systolic));\n    add('diastolic', num(p.diastolic));\n    return out;\n  }\n\n  if (name === 'sleep_analysis') {\n    add('', num(p.totalSleep) ?? num(p.asleep));\n    add('deep', num(p.deep));\n    add('core', num(p.core));\n    add('rem', num(p.rem));\n    add('awake', num(p.awake));\n    add('in_bed', num(p.inBed));\n    return out;\n  }\n\n  // Cas général : qty pour les cumuls, Avg pour les séries agrégées (FC…)\n  add('', num(p.qty) ?? num(p.Avg) ?? num(p.averageHeartRate) ?? num(p.value));\n  return out;\n};\n\n// --- Métriques ---------------------------------------------------------------\n// Clé = métrique + horodatage, sans la source : Health Auto Export renseigne\n// \"source\" avec la LISTE des appareils contributeurs, et cette liste change d'une\n// synchro à l'autre (\"iPhone|Montre|Bague\" puis \"iPhone|Bague\"). L'inclure dans la\n// clé créerait deux lignes pour la même mesure, et doublerait les cumuls.\nconst metrics = new Map();\nfor (const m of data.metrics ?? []) {\n  const units = str(m.units, 64);\n  for (const p of m.data ?? []) {\n    const d = parseDate(p.date ?? p.startDate ?? p.sleepStart ?? p.start);\n    if (!d) continue;\n    const source = str(p.source, 190) ?? '';\n    for (const row of expand(String(m.name), p)) {\n      metrics.set(`${row.metric}|${d.ts}`, [\n        str(row.metric, 190), d.ts, d.day, source, units, row.qty, JSON.stringify(p),\n      ]);\n    }\n  }\n}\n\n// --- Séances -----------------------------------------------------------------\nconst workouts = new Map();\nfor (const w of data.workouts ?? []) {\n  const s = parseDate(w.start);\n  const e = parseDate(w.end);\n  const id = str(w.id ?? w.workoutId ?? `${w.name}|${s ? s.ts : ''}`, 190);\n  workouts.set(id, [\n    id, str(w.name, 190), s ? s.ts : null, s ? s.day : null, e ? e.ts : null,\n    num(w.duration), JSON.stringify(w),\n  ]);\n}\n\n// --- ECG ---------------------------------------------------------------------\nconst ecgs = new Map();\nfor (const g of data.ecg ?? []) {\n  const s = parseDate(g.start);\n  const e = parseDate(g.end);\n  const source = str(g.source, 190) ?? '';\n  const id = str(`${s ? s.ts : ''}|${source}`, 190);\n  ecgs.set(id, [\n    id, s ? s.ts : null, s ? s.day : null, e ? e.ts : null,\n    str(g.classification, 190), str(g.severity, 190),\n    num(g.averageHeartRate), num(g.samplingFrequency),\n    num(g.numberOfVoltageMeasurements),\n    source,\n    KEEP_ECG_VOLTAGE && g.voltageMeasurements ? JSON.stringify(g.voltageMeasurements) : null,\n  ]);\n}\n\n// --- Construction des requêtes ----------------------------------------------\nconst SQL = {\n  metrics: {\n    head: 'INSERT INTO sante.health_metrics (metric, ts, local_day, source, units, qty, payload) VALUES ',\n    cols: 7,\n    tail: ' ON DUPLICATE KEY UPDATE local_day=VALUES(local_day), units=VALUES(units), ' +\n          'source=VALUES(source), qty=VALUES(qty), payload=VALUES(payload)',\n  },\n  workouts: {\n    head: 'INSERT INTO sante.health_workouts (id, name, start_ts, local_day, end_ts, duration, payload) VALUES ',\n    cols: 7,\n    tail: ' ON DUPLICATE KEY UPDATE name=VALUES(name), start_ts=VALUES(start_ts), ' +\n          'local_day=VALUES(local_day), end_ts=VALUES(end_ts), duration=VALUES(duration), ' +\n          'payload=VALUES(payload)',\n  },\n  ecg: {\n    head: 'INSERT INTO sante.health_ecg (id, start_ts, local_day, end_ts, classification, severity, ' +\n          'avg_heart_rate, sampling_hz, n_measurements, source, voltage) VALUES ',\n    cols: 11,\n    tail: ' ON DUPLICATE KEY UPDATE classification=VALUES(classification), ' +\n          'severity=VALUES(severity), avg_heart_rate=VALUES(avg_heart_rate), ' +\n          'sampling_hz=VALUES(sampling_hz), n_measurements=VALUES(n_measurements), ' +\n          'voltage=VALUES(voltage)',\n  },\n};\n\n// Le node MySQL de n8n attend des placeholders $1, $2, … et la liste de valeurs\n// dans l'option Query Parameters. Les valeurs contenant des virgules passent\n// intactes tant qu'on fournit un tableau (vérifié sur l'instance).\nconst placeholders = (startAt, cols) => {\n  const parts = [];\n  for (let i = 0; i < cols; i++) parts.push('$' + (startAt + i));\n  return '(' + parts.join(',') + ')';\n};\n\nconst metricRows = [...metrics.values()];\nconst workoutRows = [...workouts.values()];\nconst ecgRows = [...ecgs.values()];\n\nconst counts = {\n  metricCount: metricRows.length,\n  workoutCount: workoutRows.length,\n  ecgCount: ecgRows.length,\n};\n\nconst items = [];\nconst pushChunks = (rows, kind, chunk) => {\n  const s = SQL[kind];\n  for (let i = 0; i < rows.length; i += chunk) {\n    const slice = rows.slice(i, i + chunk);\n    const groups = [];\n    for (let j = 0; j < slice.length; j++) groups.push(placeholders(j * s.cols + 1, s.cols));\n    items.push({\n      json: {\n        table: kind,\n        rows: slice.length,\n        sql: s.head + groups.join(',') + s.tail,\n        values: slice.flat(),\n        ...counts,\n      },\n    });\n  }\n};\n\npushChunks(metricRows, 'metrics', CHUNK);\npushChunks(workoutRows, 'workouts', CHUNK);\npushChunks(ecgRows, 'ecg', 1); // un ECG par requête : le tracé est volumineux\n\n// Lot vide : on garde un item pour que la suite du workflow s'exécute quand même.\nif (items.length === 0) {\n  items.push({ json: { table: 'aucun', rows: 0, sql: 'SELECT $1 AS noop', values: ['aucune donnee'], ...counts } });\n}\n\nreturn items;\n"
      },
      "id": "16123dee-47f5-4a68-a177-6e768ca82ccd",
      "name": "Normaliser le payload",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [240, 0],
      "notesInFlow": true,
      "notes": "Metriques, seances et ECG, dates UTC + jour local, lots de 500"
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "{{ $json.sql }}",
        "options": {
          "queryBatching": "transaction",
          "queryReplacement": "={{ $json.values }}"
        }
      },
      "id": "d19a7ad6-91ac-4d7d-b9f9-d4de82216c31",
      "name": "Ecrire en base",
      "type": "n8n-nodes-base.mySql",
      "typeVersion": 2.5,
      "position": [480, 0],
      "notesInFlow": true,
      "notes": "Chaque item porte sa requete et ses valeurs",
      "credentials": {
        "mySql": { "id": "", "name": "MySQL sante" }
      }
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ JSON.stringify({ ok: true, metrics: $('Normaliser le payload').first().json.metricCount, workouts: $('Normaliser le payload').first().json.workoutCount, ecg: $('Normaliser le payload').first().json.ecgCount }) }}",
        "options": {}
      },
      "id": "7d0cbfb2-4a2a-45de-8b77-9e8227c4a418",
      "name": "Repondre a iPhone",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.5,
      "position": [720, 0]
    }
  ],
  "connections": {
    "Webhook Health Auto Export": { "main": [[{ "node": "Normaliser le payload", "type": "main", "index": 0 }]] },
    "Normaliser le payload": { "main": [[{ "node": "Ecrire en base", "type": "main", "index": 0 }]] },
    "Ecrire en base": { "main": [[{ "node": "Repondre a iPhone", "type": "main", "index": 0 }]] }
  },
  "settings": { "executionOrder": "v1" },
  "pinData": {},
  "meta": {
    "note": "Export de https://www.le-programmeur.com/mon-coach-minceur-avec-l-ia/ . A importer dans n8n, puis choisir vos identifiants (en-tete du webhook et MySQL). Base : voir coach-sante-schema.sql."
  }
}
