Source

api/identification-api.js

/**
 * @namespace api
 * @category api
 * @module identification-api
 * */
import Vue from 'vue'
import moment from 'moment'
import { getNestedValue } from '../utils/object'
import { getQueryStringValue } from '@/utils/querystring'
import { getFormattedAddress } from '@/utils/address.js'
import api from '@/api'
import APIUrls from '../config/simpliciti-apis'

/**
 *
 * @param {*} item Synthesis per circuit (v2/levees_bac -> syntheses)
 * @returns {Object}
 */
export function normalizeLeveesSynthesisItem(item) {
  return {
    circuitId: getNestedValue(item, 'circuit_id'),
    circuitName: getNestedValue(item, 'circuit_nom_court'),
    leveesTotal: getNestedValue(item, 'nb_levees_total', 0),
    leveesWeightTotal: getNestedValue(item, 'poids_levees_total', 0),
    identifiedTotal: getNestedValue(item, 'nb_identifies', 0),
    unidentifiedTotal: getNestedValue(item, 'nb_non_identifies', 0),
    authorizedTotal: getNestedValue(item, 'nb_autorises', 0),
    unauthorizedTotal: getNestedValue(item, 'nb_non_autorises', 0),
    collectedTotal: getNestedValue(item, 'nb_collectes', 0),
    uncollectedTotal: getNestedValue(item, 'nb_non_collectes', 0),
    highPointTotal: getNestedValue(item, 'nb_point_haut', 0),
    nonHighPointTotal: getNestedValue(item, 'nb_non_point_haut', 0),
    stoppedTotal: getNestedValue(item, 'nb_stoppe', 0),
    blacklistedTotal: getNestedValue(item, 'nb_blackliste', 0),
    aboveWeightTotal: getNestedValue(item, 'nb_poids_sur_charge', 0),
    underWeightTotal: getNestedValue(item, 'nb_poids_sous_charge', 0),
  }
}

/**
 * @todo Move to entity
 * @param {*} item
 * @returns {Object}
 */
export function normalizeLeveeDetailsItem(item) {
  let datetime = moment(getNestedValue(item, 'dateheure'))
  let newItem = {
    id: getNestedValue(item, 'levee_id'),
    timestamp: datetime._d.getTime(),
    datetime: datetime._d,
    formattedDate: Vue.$date.formatDate(datetime),
    formattedTime: Vue.$date.formatTimeWithSeconds(datetime),
    timeUnix: moment()
      .hour(datetime.hour())
      .minute(datetime.minute())
      .second(datetime.second()),
    vehicleName: getNestedValue(item, 'vehicule_nom'),
    circuitId: getNestedValue(item, 'circuit_id'),
    circuitName: getNestedValue(item, 'circuit_nom_court'),
    puceNumber: getNestedValue(item, 'puce_fondeur'),
    memoryPuceNumber: getNestedValue(item, 'puce_memoire'),
    formattedAddress: getFormattedAddress(item, {
      streetNumber: 'num_rue',
      streetAddress: 'rue',
      zipCode: 'cp',
      city: 'ville',
    }),
    chairType: getNestedValue(item, 'chaise'),
    isIdentified: getNestedValue(item, 'identifie', false) ? true : false,
    isStopped: getNestedValue(item, 'stoppe', false) ? true : false,
    isHighPoint: getNestedValue(item, 'point_haut', false, {
      transform(value, apiValue) {
        if (apiValue === '') return 'n/c'
        return !!value //0/1 = false/true
      },
    }),
    isBlacklisted: getNestedValue(item, 'blackliste', false) ? true : false,
    weight: getNestedValue(item, 'poids'),
    lat: getNestedValue(item, 'latitude'),
    lng: getNestedValue(item, 'longitude'),
  }
  newItem.hasInvalidCoords =
    (!newItem.lat && !newItem.lng) ||
    ((newItem.lat || '').toString() === '91' &&
      (newItem.lng || '').toString() === '181')
  return newItem
}

/**
 *
 * @param {*} date
 * @param {*} vehicleId
 * @param {*} circuitId
 * @returns
 */
export async function fetchLeveesDetails(
  date,
  vehicleId,
  circuitId,
  options = {}
) {
  let res = (
    await api.v2.get(
      `${
        APIUrls.APIV2_IDENTIFICATION_LEVEE_BAC
      }?vehicule_id=${vehicleId}&circuit_id=${circuitId}&dates=${moment(
        date
      ).format('YYYY-MM-DD')}&groups=levees`,
      {
        identifie: options?.filters?.identified,
        stoppe: options?.filters?.stopped,
        point_haut: options?.filters?.highPoint,
        blackliste: options?.filters?.blacklisted,
        numero_puce: options?.filters?.puceNumber,
      }
    )
  ).data
  let items = getNestedValue(res, `${Object.keys(res)[0]}.${vehicleId}.levees`)
  return items.map(normalizeLeveeDetailsItem)
}

export async function fetchLeveesSynthesis(elementIds, dates, options = {}) {
  let groups = 'syntheses'
  groups = options.groups || groups
  let elementParamName = {
    vehicle: 'vehicule_id',
    circuit: 'circuit_id',
  }
  let res =
    (getQueryStringValue('test') === '1' &&
      require('@/api/mocks/v2/levee_bac/46262.json').data.items) ||
    (
      await api.v2.get(
        `${APIUrls.APIV2_IDENTIFICATION_LEVEE_BAC}?${
          elementParamName[options.elementType || 'vehicle']
        }=${elementIds}&dates=${dates.map((date) =>
          moment(date).format('YYYY-MM-DD')
        )}&groups=${groups}`,
        {
          identifie: options.filters.identified,
          stoppe: options.filters.stopped,
          point_haut: options.filters.highPoint,
          blackliste: options.filters.blacklisted,
          numero_puce: options?.filters?.puceNumber,
        }
      )
    ).data

  let arr = []
  let item = null
  let circuit = null

  !!res &&
    Object.keys(res).forEach((dateKey) => {
      let date = moment(dateKey, 'YYYY-MM-DD')._d
      Object.keys(res[dateKey]).forEach((vehicleId) => {
        item = res[dateKey][vehicleId]

        let circuits = Object.keys(item.syntheses).map((circuitId) => {
          circuit = item.syntheses[circuitId]
          return normalizeLeveesSynthesisItem(circuit)
        })

        arr.push({
          date,
          timestamp: date.getTime(),
          dateFormatted: Vue.$date.formatDate(date),
          vehicleId,
          vehicleName: getNestedValue(item, 'vehicule_nom'),
          vehicleImmatriculation: getNestedValue(
            item,
            'vehicule_immatriculation'
          ),
          vehicleCategory: getNestedValue(item, 'categorie_nom'),

          //Synthesis by circuit
          circuits,
          synthesis: circuits,
        })
      })
    })

  return arr
}