{"size": 4725, "ext": "js", "max_stars_repo_path": "common/utils/loadUserData.js", "max_stars_repo_name": "MTES-MCT/mobilic", "max_stars_repo_stars_event_min_datetime": "2021-12-06T17:00:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-07T10:58:33.000Z", "max_issues_repo_path": "common/utils/loadUserData.js", "max_issues_repo_name": "MTES-MCT/mobilic", "max_issues_repo_issues_event_min_datetime": "2021-03-23T15:55:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T10:07:43.000Z", "max_forks_repo_path": "common/utils/loadUserData.js", "max_forks_repo_name": "MTES-MCT/mobilic", "max_forks_repo_forks_event_min_datetime": "2021-12-21T10:11:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T10:11:22.000Z"}
{"max_stars_count": 2, "max_issues_count": 6, "max_forks_count": 1, "avg_line_length": 26.1049723757, "max_line_length": 78, "alphanum_fraction": 0.6061375661}
import { broadCastChannel } from "./store";
import { parseActivityPayloadFromBackend } from "./activities";
import { parseMissionPayloadFromBackend } from "./mission";
import { DAY, now } from "./time";
import {
  COMPANY_SETTINGS_FRAGMENT,
  CURRENT_MISSION_INFO,
  FULL_MISSION_FRAGMENT
} from "./apiQueries";
import { gql } from "@apollo/client/core";
import { captureSentryException } from "./sentry";

const USER_QUERY = gql`
  ${COMPANY_SETTINGS_FRAGMENT}
  ${FULL_MISSION_FRAGMENT}
  query user($id: Int!, $activityAfter: TimeStamp) {
    user(id: $id) {
      id
      firstName
      lastName
      birthDate
      email
      hasConfirmedEmail
      hasActivatedEmail
      disabledWarnings
      missions(fromTime: $activityAfter, first: 200) {
        edges {
          node {
            ...FullMissionData
          }
        }
      }
      currentEmployments {
        id
        startDate
        isAcknowledged
        isPrimary
        hasAdminRights
        company {
          id
          name
          siren
          sirets
          ...CompanySettings
          users {
            id
            firstName
            lastName
          }
          knownAddresses {
            id
            alias
            name
            postalCode
            city
          }
          vehicles {
            id
            name
            registrationNumber
          }
        }
      }
    }
  }
`;

export async function loadUserData(api, store, alerts) {
  const userId = store.userId();
  if (!userId) return;
  await alerts.withApiErrorHandling(async () => {
    const userResponse = await api.graphQlQuery(
      USER_QUERY,
      {
        id: userId,
        activityAfter: now() - DAY * 215
      },
      { context: { timeout: 12000 } }
    );
    await syncUser(userResponse.data.user, api, store);
    await broadCastChannel.postMessage("update");
  }, "load-user");
}

export async function syncUser(userPayload, api, store) {
  const {
    firstName,
    lastName,
    email,
    birthDate,
    hasConfirmedEmail,
    hasActivatedEmail,
    disabledWarnings,
    missions: missionsPayload,
    currentEmployments
  } = userPayload;

  const activities = [];
  const expenditures = [];
  const missionData = [];
  const comments = [];
  const missions = missionsPayload.edges.map(e => e.node);

  // Get end status for latest mission;
  if (missions.length > 0) {
    const latestMission = missions[0];
    try {
      const latestMissionInfo = await api.graphQlQuery(CURRENT_MISSION_INFO, {
        id: latestMission.id
      });
      latestMission.ended = latestMissionInfo.data.mission.isEndedForSelf;
      latestMission.submitter = latestMissionInfo.data.mission.submitter;
    } catch (err) {
      captureSentryException(err);
    }
  }
  missions.forEach(mission => {
    activities.push(...mission.activities);
    expenditures.push(...mission.expenditures);
    comments.push(...mission.comments);
    missionData.push(parseMissionPayloadFromBackend(mission, store.userId()));
  });

  const syncActions = [];
  firstName &&
    lastName &&
    syncActions.push(
      store.setUserInfo(
        {
          firstName,
          lastName,
          email,
          birthDate,
          hasConfirmedEmail,
          hasActivatedEmail,
          disabledWarnings
        },
        false
      )
    );
  missions && syncActions.push(store.syncEntity(missionData, "missions"));
  activities &&
    syncActions.push(
      store.syncEntity(
        activities.map(parseActivityPayloadFromBackend),
        "activities"
      )
    );

  expenditures &&
    syncActions.push(store.syncEntity(expenditures, "expenditures"));
  comments && syncActions.push(store.syncEntity(comments, "comments"));
  const users = [];
  const vehicles = [];
  const knownAddresses = [];
  currentEmployments.forEach(e => {
    const company = e.company;
    company.users.forEach(u => {
      if (u.id !== userPayload.id) {
        const userMatch = users.find(u2 => u2.id === u.id);
        if (!userMatch) {
          users.push({ ...u, companyIds: [company.id] });
        } else userMatch.companyIds.push(company.id);
      }
    });
    vehicles.push(
      ...company.vehicles.map(v => ({ ...v, companyId: company.id }))
    );
    knownAddresses.push(
      ...company.knownAddresses.map(a => ({ ...a, companyId: company.id }))
    );
  });
  syncActions.push(store.syncEntity(users, "coworkers"));
  syncActions.push(store.syncEntity(vehicles, "vehicles"));
  syncActions.push(store.syncEntity(knownAddresses, "knownAddresses"));
  currentEmployments &&
    syncActions.push(store.syncEntity(currentEmployments, "employments"));
  store.batchUpdateStore();
  await Promise.all(syncActions);
}
