All files / services syncService.ts

98.77% Statements 161/163
96.96% Branches 128/132
100% Functions 24/24
98.75% Lines 159/161

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 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 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479                                                                                              28x 15x     13x 1x     12x 5x 1x   4x 4x                         10x 10x 10x 1x     9x 9x   9x 9x 24x 19x     5x 1x 1x     4x         3x 3x     1x     9x 3x             9x     9x 1x     9x 9x           9x 4x   4x 4x 3x 2x       3x 1x         4x               1x           1x 1x     2x                               13x 10x 10x 2x   8x 2x   6x 3x     6x       9x 2x 1x       1x 1x 4x         3x     1x       4x 4x 3x   1x         2x 2x     2x 2x                     1x       29x 28x 10x 5x   18x 10x   1x                           33x           5x 5x     5x 5x                             6x 5x 5x                         5x 5x   5x 5x 4x 4x         5x 5x 4x   1x 1x 1x 1x 1x 1x               31x 31x 31x       31x   31x 34x 34x 5x   29x   21x 21x     21x   13x 13x 13x   13x     3x 3x     10x           2x 2x 2x 2x   2x     8x   2x 2x       6x       31x             11x   11x       10x 1x     9x 9x 9x     6x             9x 7x     9x 9x         9x 1x     9x                 1x               4x 1x   3x 3x 3x   3x 3x 3x   1x           3x   3x           3x      
import * as Network from "expo-network";
import apiClient, { ApiClientError, isApiClientError } from "./apiClient";
import type { ApiEnvelope } from "../types/auth";
import type {
  MobileIntervention,
  MobileStep,
} from "../types/intervention";
import type { SyncQueueItem } from "../types/offline";
import { requireEnvironmentBaseUrl } from "../core/environmentService";
import { getMobileConfigForBaseUrl } from "../core/mobileConfigService";
import {
  applyServerStepsDelta,
  enqueueSyncAction,
  getLastSyncTimestamp,
  getPendingQueueItems,
  markQueueItemDead,
  markQueueItemDone,
  markQueueItemFailed,
  markQueueItemWalled,
  mergeInterventionsSnapshot,
  setLastSyncTimestamp,
} from "../core/localDatabase";
import { readSession } from "./tokenStorage";
import { flushCrashReports } from "../core/crashLog";
 
type DeltaPayload = {
  items?: MobileIntervention[];
  interventions?: MobileIntervention[];
  intervention_ids?: number[];
  steps?: MobileStep[];
  since?: string;
  server_time?: string;
};
 
type MultipartQueueFile = {
  field: string;
  uri: string;
  name: string;
  type: string;
};
 
type MultipartQueuePayload = Record<string, unknown> & {
  __multipart: boolean;
  upload_files: MultipartQueueFile[];
};
 
function isMultipartQueuePayload(payload: Record<string, unknown>): payload is MultipartQueuePayload {
  if (payload.__multipart !== true) {
    return false;
  }
 
  if (!Array.isArray(payload.upload_files)) {
    return false;
  }
 
  return payload.upload_files.every((file) => {
    if (!file || typeof file !== "object") {
      return false;
    }
    const candidate = file as Record<string, unknown>;
    return (
      typeof candidate.field === "string" &&
      typeof candidate.uri === "string" &&
      typeof candidate.name === "string" &&
      typeof candidate.type === "string"
    );
  });
}
 
async function postMultipartFromQueue(
  endpoint: string,
  payload: MultipartQueuePayload
): Promise<void> {
  const baseUrl = await requireEnvironmentBaseUrl();
  const session = await readSession();
  if (!session.accessToken) {
    throw new ApiClientError("Unauthorized", 401);
  }
 
  const config = await getMobileConfigForBaseUrl(baseUrl);
  const tenantId = config?.config.tenant_id;
 
  const formData = new FormData();
  Object.entries(payload).forEach(([key, value]) => {
    if (key === "__multipart" || key === "upload_files" || value === undefined) {
      return;
    }
 
    if (value === null) {
      formData.append(key, "");
      return;
    }
 
    if (
      typeof value === "string" ||
      typeof value === "number" ||
      typeof value === "boolean"
    ) {
      formData.append(key, String(value));
      return;
    }
 
    formData.append(key, JSON.stringify(value));
  });
 
  payload.upload_files.forEach((file) => {
    formData.append(file.field || "files[]", {
      uri: file.uri,
      name: file.name,
      type: file.type,
    } as unknown as Blob);
  });
 
  const headers: Record<string, string> = {
    Authorization: `Bearer ${session.accessToken}`,
  };
  if (tenantId !== undefined && tenantId !== null) {
    headers["X-Tenant-Id"] = String(tenantId);
  }
 
  const url = endpoint.startsWith("http") ? endpoint : `${baseUrl}${endpoint}`;
  const response = await fetch(url, {
    method: "POST",
    headers,
    body: formData,
  });
 
  if (!response.ok) {
    let message = `HTTP ${response.status}`;
    let code: string | undefined;
    try {
      const data = (await response.json()) as { message?: string; code?: string };
      if (data.message) {
        message = data.message;
      }
      // On capte aussi le code metier (ex: "BILLING_WALL") pour que la sync
      // puisse classer correctement un upload photo refuse par le mur.
      if (typeof data.code === "string" && data.code) {
        code = data.code;
      }
    } catch {
      // ignore json parse failure
    }
    throw new ApiClientError(message, response.status, code);
  }
}
 
// Mur de facturation (cote serveur, Lot 1) : une ecriture de completion refusee
// parce que l'abonnement du tenant n'est plus actif revient en 402 portant ce
// code. A distinguer d'un 402 generique (retryable) : ici l'item NE DOIT PAS
// mourir, il se re-poussera tel quel a la reactivation.
const BILLING_WALL_CODE = "BILLING_WALL";
 
// Handler global "mur de facturation" : la sync etant decouplee de l'UI, App
// l'enregistre au montage pour afficher un message dedie (SANS logout : le mur
// n'est pas une session invalide). Invoque une seule fois par episode de mur ;
// re-arme des qu'un envoi repasse (le mur est leve apres reactivation).
let billingWallHandler: ((message: string) => void) | null = null;
let billingWallNotified = false;
 
export function registerBillingWallHandler(handler: ((message: string) => void) | null): void {
  billingWallHandler = handler;
}
 
type SyncErrorKind = "auth" | "contract" | "wall" | "retryable";
 
// Classe l'erreur d'un envoi de file :
//  - "auth" (401/403)            -> session invalide : on STOPPE la passe
//    (les items restent 'pending' et repartiront apres re-auth/refresh).
//  - "contract" (400/404/409/422) -> l'item est definitivement mauvais :
//    inutile de rejouer, on le marque 'dead' et on CONTINUE les suivants.
//  - "wall" (402 BILLING_WALL)   -> mur de facturation : abonnement inactif.
//    L'ecriture est valide, on STOPPE la passe et on garde l'item 'pending'
//    SANS attempts++ (cf. markQueueItemWalled) -> re-pousse a la reactivation.
//  - "retryable" (5xx, reseau, erreur sans status) -> attempts++ (dead au
//    cap MAX_SYNC_ATTEMPTS) et on CONTINUE.
function classifySyncError(error: unknown): SyncErrorKind {
  if (isApiClientError(error) && typeof error.status === "number") {
    const status = error.status;
    if (status === 402 && error.code === BILLING_WALL_CODE) {
      return "wall";
    }
    if (status === 401 || status === 403) {
      return "auth";
    }
    if ([400, 404, 409, 422].includes(status)) {
      return "contract";
    }
  }
  return "retryable";
}
 
function pickItems(payload: DeltaPayload): MobileIntervention[] {
  if (Array.isArray(payload.items)) return payload.items;
  if (Array.isArray(payload.interventions)) return payload.interventions;
  return [];
}
 
function toPrimitiveParams(input: Record<string, unknown>): Record<string, string | number | boolean> {
  const out: Record<string, string | number | boolean> = {};
  Object.entries(input).forEach(([key, value]) => {
    if (
      typeof value === "string" ||
      typeof value === "number" ||
      typeof value === "boolean"
    ) {
      out[key] = value;
    }
  });
  return out;
}
 
export async function isNetworkOnline(): Promise<boolean> {
  try {
    const state = await Network.getNetworkStateAsync();
    return Boolean(state.isConnected && state.isInternetReachable !== false);
  } catch {
    return true;
  }
}
 
export function subscribeNetworkChanges(onChange: (online: boolean) => void): () => void {
  const subscription = Network.addNetworkStateListener((state) => {
    onChange(Boolean(state.isConnected && state.isInternetReachable !== false));
  });
 
  return () => {
    subscription.remove();
  };
}
 
export async function enqueueOfflineAction(input: {
  endpoint: string;
  method: "GET" | "POST";
  payload: Record<string, unknown>;
  entityType: string;
  entityId: string;
}): Promise<void> {
  await enqueueSyncAction(input);
}
 
async function dispatchQueueItem(item: SyncQueueItem): Promise<void> {
  if (item.method === "POST") {
    if (isMultipartQueuePayload(item.payload)) {
      await postMultipartFromQueue(item.endpoint, item.payload);
      return;
    }
    await apiClient.post(item.endpoint, item.payload);
    return;
  }
  await apiClient.get(item.endpoint, { params: toPrimitiveParams(item.payload) });
}
 
// Un save_step mis en file hors-ligne porte la `version` du workflow FIGEE au
// moment de la saisie. Le serveur applique un verrou optimiste
// (assertVersion -> 409 WORKFLOW_VERSION_STALE). Au rejeu sequentiel, le 1er
// save passe et le serveur incremente la version -> tous les saves suivants,
// avec leur version perimee, sont rejetes en 409 et l'item est jete (classe
// "contract"). Resultat : les etapes remplies hors-ligne sont silencieusement
// perdues. La file d'un meme tech rejouee en sequence n'a aucune concurrence
// reelle : on REBASE donc chaque save sur la version courante (cf. dispatch).
function isOfflineSaveStep(
  payload: Record<string, unknown>
): payload is Record<string, unknown> & { intervention_id: number } {
  return payload?.action === "save_step" && Number(payload?.intervention_id) > 0;
}
 
// Lit la version courante du workflow d'une intervention (best-effort) pour
// rebaser un save_step rejoue. Renvoie null si indisponible (offline/erreur).
async function fetchCurrentWorkflowVersion(interventionId: number): Promise<number | null> {
  try {
    const resp = await apiClient.get<
      ApiEnvelope<{ workflow?: { version?: number } }>
    >("/mobile/intervention_steps.php", { params: { id: interventionId } });
    const v = Number(resp.data?.data?.workflow?.version);
    return Number.isFinite(v) && v > 0 ? v : null;
  } catch {
    return null;
  }
}
 
type WorkflowSavePost = ApiEnvelope<{ workflow?: { version?: number } }>;
 
// POST un save_step en injectant `version`, et renvoie la nouvelle version du
// workflow (fallback version+1 : advanceWorkflowAfterSave incremente de 1).
async function postSaveStepWithVersion(
  endpoint: string,
  payload: Record<string, unknown>,
  version: number
): Promise<number> {
  const resp = await apiClient.post<WorkflowSavePost>(endpoint, { ...payload, version });
  const next = Number(resp.data?.data?.workflow?.version);
  return Number.isFinite(next) && next > 0 ? next : version + 1;
}
 
// Rejoue un save_step hors-ligne en rebasant sa version sur l'etat serveur
// courant. `versionByIntervention` suit la version a travers les saves
// successifs d'une meme intervention dans la passe (seed via 1 GET, puis on
// chaine la version renvoyee par chaque POST). Backstop : un 409 residuel
// (drift via une autre ecriture, ex. upload photo) re-seed via GET et retente
// une fois avant d'abandonner a la classification standard.
async function dispatchOfflineSaveStep(
  item: SyncQueueItem,
  versionByIntervention: Map<number, number>
): Promise<void> {
  const payload = item.payload as Record<string, unknown> & { intervention_id: number };
  const interventionId = Number(payload.intervention_id);
 
  let version = versionByIntervention.get(interventionId);
  if (version === undefined) {
    const fromPayload = Number(payload.version);
    version =
      (await fetchCurrentWorkflowVersion(interventionId)) ??
      (Number.isFinite(fromPayload) ? fromPayload : 0);
  }
 
  try {
    const next = await postSaveStepWithVersion(item.endpoint, payload, version);
    versionByIntervention.set(interventionId, next);
  } catch (error) {
    Eif (isApiClientError(error) && error.status === 409) {
      const fresh = await fetchCurrentWorkflowVersion(interventionId);
      Eif (fresh !== null) {
        const next = await postSaveStepWithVersion(item.endpoint, payload, fresh);
        versionByIntervention.set(interventionId, next);
        return;
      }
    }
    throw error;
  }
}
 
export async function processSyncQueue(limit = 50): Promise<{ processed: number; failed: number }> {
  const items = await getPendingQueueItems(limit);
  let processed = 0;
  let failed = 0;
  // Suivi de la version workflow par intervention sur la passe : permet de
  // rebaser les save_step hors-ligne (version figee a la saisie) sur l'etat
  // serveur courant et d'eviter les 409 en cascade qui les feraient jeter.
  const versionByIntervention = new Map<number, number>();
 
  for (const item of items) {
    try {
      if (item.method === "POST" && isOfflineSaveStep(item.payload)) {
        await dispatchOfflineSaveStep(item, versionByIntervention);
      } else {
        await dispatchQueueItem(item);
      }
      await markQueueItemDone(item.id);
      processed += 1;
      // Un envoi a repasse -> le mur (s'il y en avait un) est leve : on re-arme
      // la notification pour le prochain episode eventuel.
      billingWallNotified = false;
    } catch (error) {
      const message = error instanceof Error ? error.message : "Sync failed";
      const kind = classifySyncError(error);
      failed += 1;
 
      if (kind === "contract") {
        // Item definitivement mauvais : on le sort de la file et on poursuit
        // les suivants (un seul 404 ne doit plus bloquer tout le drain).
        await markQueueItemDead(item.id, message);
        continue;
      }
 
      if (kind === "wall") {
        // Mur de facturation : abonnement tenant inactif. L'ecriture est valide,
        // on la GARDE 'pending' sans attempts++ (markQueueItemWalled) -> elle ne
        // meurt pas au cap et se re-poussera a la reactivation. Inutile
        // d'insister sur le reste de la passe (tout sera mure pareil) : on stoppe
        // et on previent l'UI une seule fois par episode.
        await markQueueItemWalled(item.id, message);
        Eif (!billingWallNotified) {
          billingWallNotified = true;
          billingWallHandler?.(message);
        }
        break;
      }
 
      if (kind === "auth") {
        // Session invalide : inutile d'insister sur le reste de la passe.
        await markQueueItemFailed(item.id, message);
        break;
      }
 
      // Retryable (5xx / reseau) : on incremente (dead au cap) et on continue.
      await markQueueItemFailed(item.id, message);
    }
  }
 
  return { processed, failed };
}
 
export async function pullSyncDelta(): Promise<number> {
  // Watermark au format MySQL 'Y-m-d H:i:s' (le serveur le renvoie via
  // server_time et le compare a interventions.updated_at, en tz serveur).
  // Defaut = epoch -> pull complet au premier demarrage / cache vide.
  const since = (await getLastSyncTimestamp()) || "1970-01-01 00:00:00";
 
  const response = await apiClient.get<ApiEnvelope<DeltaPayload>>("/mobile/sync_pull.php", {
    params: { since },
  });
 
  if (!response.data?.success || !response.data.data) {
    return 0;
  }
 
  const payload = response.data.data;
  const items = pickItems(payload);
  const keepIds = Array.isArray(payload.intervention_ids)
    ? payload.intervention_ids
        .map(Number)
        .filter((id) => Number.isFinite(id))
    : null;
 
  // Merge non destructif : upsert des interventions changees + purge des ids
  // disparus (keepIds = liste complete serveur). On NE remplace plus tout le
  // snapshot (l'ancien saveInterventionsSnapshot vidait la table -> un delta
  // partiel effacait toutes les interventions non modifiees).
  if (items.length > 0 || keepIds) {
    await mergeInterventionsSnapshot(items, keepIds);
  }
 
  const steps = Array.isArray(payload.steps) ? payload.steps : [];
  const appliedSteps = steps.length > 0 ? await applyServerStepsDelta(steps) : 0;
 
  // Watermark = horloge SERVEUR (server_time), jamais celle du device :
  // updated_at est en tz serveur, comparer avec l'heure locale du tel
  // introduirait un decalage (lignes ratees ou rejouees).
  if (typeof payload.server_time === "string" && payload.server_time) {
    await setLastSyncTimestamp(payload.server_time);
  }
 
  return items.length + appliedSteps;
}
 
// Garde de reentrance : la sync est declenchee par 3 sources (boot, retour
// reseau, retour foreground) qui peuvent coincider. Sans verrou, deux passes
// concurrentes liraient les memes items 'pending' et les enverraient en double
// (intervention_start/precheck n'ont pas de cle d'idempotence). Le flag
// module-level serialise : la 2e source recoit un resultat neutre et n'envoie
// rien tant que la 1ere n'a pas fini.
let syncInFlight = false;
 
export async function syncOnReconnect(): Promise<{
  pushed: number;
  failed: number;
  pulled: number;
  skipped?: boolean;
}> {
  if (syncInFlight) {
    return { pushed: 0, failed: 0, pulled: 0, skipped: true };
  }
  syncInFlight = true;
  try {
    const pushResult = await processSyncQueue();
 
    let pulled = 0;
    try {
      pulled = await pullSyncDelta();
    } catch {
      pulled = 0;
    }
 
    // Remontee best-effort des incidents au backend, sur le meme cycle que la
    // sync (boot / reconnexion / foreground). flushCrashReports ne lance jamais
    // et conserve les logs si l'endpoint n'est pas encore deploye (404).
    await flushCrashReports();
 
    return {
      pushed: pushResult.processed,
      failed: pushResult.failed,
      pulled,
    };
  } finally {
    syncInFlight = false;
  }
}