src/graphQL/Api.js

mail@pastecode.io avatar
unknown
typescript
a month ago
18 kB
2
Indexable
Never
import { API, graphqlOperation } from 'aws-amplify'
import client from '@GraphQL/apolloClient'
import {
  GET_COMPANY_INFOS,
  GET_DAY_RESULTS,
  GET_FUEL_MILE_RESULTS,
  GET_LOCO_INFRACTIONS,
  GET_TRIPS,
  GET_TRIP_FUEL_SAVING,
  GET_TRIPS_DETAILS,
  GET_FUEL_SAVING_HERO_METRICS,
  GET_FUEL_SAVING_TRENDS,
  GET_ROUTES_BY_RAILROAD,
  GET_TRIP,
  GET_USERS_AND_ROLES_BY_EMAIL,
  GET_BROADCAST_DATA_BY_RAILROAD_ID,
  GET_FEATURIZERS_TRIP_INFORMATION_ON_PATH,
  GET_STATIONS_BY_ROUTE_ID
} from '@GraphQL/Queries'
import { date_to_YYYY_MM_DD, getNthDatePriorGivenDate } from '@Utils'
import {
  END_SIMPLE_TRAIN_CONSIST_TRIP,
  REPROCESS_TRIP,
  ADD_NEW_USER,
  EDIT_USER_PERMISSION,
  SOFT_DELETE_TRIP
} from '@GraphQL/Mutations'
import {
  GET_FEATURIZERS_INTERPOLATE_REVERIFY_PATH,
  GET_TRIP_BY_STC_ID,
  GET_LOCALIZATION_UNITS,
  GET_ZONE_SPEED_LIMITS_BY_ROUTES_ID
} from './Queries'
import { queries } from '@testing-library/react'

export const getCompanyInfos = async () => {
  try {
    const { data } = await API.graphql(graphqlOperation(GET_COMPANY_INFOS))
    return data.companyInfos
  } catch (error) {
    console.error(
      'Oops something went wrong with the fetchCompanyInfos API',
      error
    )
    throw error
  }
}

export const getUserAuth = async email => {
  try {
    // const { data } = await API.graphql(graphqlOperation(GET_USER_AUTH(email)))
    // return data.user_authorization

    return {
      railroad_id: 'abc',
      company_id: 101,
      user_id: 'u12',
      display_name: 'Metrolinx',
      role_names: 'ECORAIL_BASIC'
    }
  } catch (error) {
    console.error('Oops something went wrong with the fetchUserAuth API', error)
    throw error
  }
}

export const getLatestDate = async () => {
  try {
    // Will be replace with GraphQL query later. hard code the latest date to be daily's date - 2 for now.
    return date_to_YYYY_MM_DD(getNthDatePriorGivenDate(new Date(), 0))
  } catch (error) {
    console.error('Oops something went wrong with the getLatestDate API', error)
  }
}

export const getDailyDaysResults = async (companyId, date) => {
  try {
    const { data } = await API.graphql(
      graphqlOperation(
        GET_DAY_RESULTS(
          companyId,
          date_to_YYYY_MM_DD(date),
          date_to_YYYY_MM_DD(date)
        )
      )
    )
    // console.log('dailyDayResults', data)
    return data.dayResults[0]
  } catch (error) {
    console.error(
      'Oops something went wrong with the fetchDailyDaysResults API',
      error
    )
    throw error
  }
}

export const getTrendingDaysResults = async (companyId, startDate, endDate) => {
  try {
    const { data } = await API.graphql(
      graphqlOperation(
        GET_DAY_RESULTS(
          companyId,
          date_to_YYYY_MM_DD(startDate),
          date_to_YYYY_MM_DD(endDate)
        )
      )
    )
    // console.log('dayResults', data)
    return data.dayResults
  } catch (error) {
    console.error(
      'Oops something went wrong with the fetchDaysResults API',
      error
    )
    throw error
  }
}

export const getDailyFuelMileResults = async (companyId, date) => {
  try {
    const { data } = await API.graphql(
      graphqlOperation(
        GET_FUEL_MILE_RESULTS(
          companyId,
          date_to_YYYY_MM_DD(date),
          date_to_YYYY_MM_DD(date)
        )
      )
    )
    // console.log('dailyFuelMileResults', data)
    return data.fuelMileResults[0] ? data.fuelMileResults[0] : null
  } catch (error) {
    console.error(
      'Oops something went wrong with the fetchDailyFuelMileResults API',
      error
    )
    throw error
  }
}

export const getFuelMileResults = async (companyId, startDate, endDate) => {
  try {
    const { data } = await API.graphql(
      graphqlOperation(
        GET_FUEL_MILE_RESULTS(
          companyId,
          date_to_YYYY_MM_DD(startDate),
          date_to_YYYY_MM_DD(endDate)
        )
      )
    )
    // console.log('fuelMileResults', data)
    return data.fuelMileResults
  } catch (error) {
    console.error(
      'Oops something went wrong with the fetchFuelMileResults API',
      error
    )
    throw error
  }
}

export const getLocoInfractions = async (
  companyId,
  locoNum,
  startDate,
  endDate
) => {
  try {
    const { data } = await API.graphql(
      graphqlOperation(
        GET_LOCO_INFRACTIONS(
          companyId,
          locoNum,
          date_to_YYYY_MM_DD(startDate),
          date_to_YYYY_MM_DD(endDate)
        )
      )
    )
    // console.log('locoInfractions', data)
    return data.locoInfractions
  } catch (error) {
    console.error(
      'Oops something went wrong with the fetchLocoInfractions API',
      error
    )
    throw error
  }
}

export const getTripFuelSaving = async (
  companyId,
  locoNum,
  startDate,
  endDate
) => {
  try {
    const { data } = await API.graphql(
      graphqlOperation(
        GET_TRIP_FUEL_SAVING(
          companyId,
          locoNum,
          date_to_YYYY_MM_DD(startDate),
          date_to_YYYY_MM_DD(endDate)
        )
      )
    )
    // console.log('tripFuelSaving', data)
    return data.tripFuelSaving
  } catch (error) {
    console.error(
      'Oops something went wrong with the fetchTripFuelSaving API',
      error
    )
    throw error
  }
}

export const getTrips = async (railroadId, startDate, endDate) => {
  try {
    const res = await client.query({
      query: GET_TRIPS,
      variables: {
        railroad_id: railroadId,
        start_date_utc: startDate,
        end_date_utc: endDate
      },
      context: { clientName: 'ecorail' },
      fetchPolicy: 'no-cache'
    })

    console.log('Fetched trips:', res)
    return res?.data?.trips
  } catch (error) {
    console.error('Oops something went wrong with the fetchTrips API', error)
    throw error
  }
}

export const getTripDetails = async tripId => {
  try {
    const res = await client.query({
      query: GET_TRIPS_DETAILS,
      variables: {
        trip_id: tripId
      },
      context: { clientName: 'analytics' }
    })

    console.log('Fetched trip detailss:', res)
    return res?.data?.trip_details

    // return new Promise((resolve, reject) => {
    //   setTimeout(() => {
    //     resolve(mockTripDetails.tripDetails)
    //   }, 1000)
    // })
  } catch (error) {
    throw error
  }
}

export const getFuelSavingHeroMetrics = async (
  railroadId,
  startDate,
  endDate,
  route_id,
  route_direction
) => {
  try {
    const res = await client.query({
      query: GET_FUEL_SAVING_HERO_METRICS,
      variables: {
        railroad_id: railroadId,
        start_date_utc: startDate,
        end_date_utc: endDate,
        route_id: route_id,
        route_direction: route_direction
      },
      context: { clientName: 'analytics' }
    })

    console.log('Fetched fuel saving hero metrics:', res)
    return res?.data?.fuel_saving_hero_metrics
  } catch (error) {
    console.error(
      'Oops something went wrong with the fetchFuelSavingHeroMetrics API',
      error
    )
    throw error
  }
}

export const getFuelSavingTrends = async (
  railroadId,
  startDate,
  endDate,
  route_id,
  route_direction
) => {
  try {
    const res = await client.query({
      query: GET_FUEL_SAVING_TRENDS,
      variables: {
        railroad_id: railroadId,
        start_date_utc: startDate,
        end_date_utc: endDate,
        route_id: route_id,
        route_direction: route_direction
      },
      context: { clientName: 'analytics' }
    })

    console.log('Fetched fuel saving trends:', res)
    return res?.data?.fuel_saving_trends
  } catch (error) {
    console.error(
      'Oops something went wrong with the fetchFuelSavingTrends API',
      error
    )
    throw error
  }
}

export const getRoutesByRailroad = async railroadid => {
  try {
    const res = await client.query({
      query: GET_ROUTES_BY_RAILROAD,
      variables: {
        railroad_id: railroadid
      },
      context: { clientName: 'ecorail' }
    })
    console.log('Fetched routes by railroad:', res)
    return res?.data?.routes_by_railroad_id
  } catch (error) {
    console.error(
      'Oops something went wrong with the fetchRoutesByRailroad API',
      error
    )
    throw error
  }
}

export const endSimpleTrainConsistTrip = async ({
  createdBy,
  endDateUtc,
  simpleTrainConsistId
}) => {
  try {
    const res = await client.mutate({
      mutation: END_SIMPLE_TRAIN_CONSIST_TRIP,
      variables: {
        createdBy,
        endDateUtc,
        simpleTrainConsistId
      },
      refetchQueries: () => [{ query: GET_TRIPS }],
      context: { clientName: 'ecorail' }
    })
    console.log('Response from endSimpleTrainConsistTrip:', res)
    return res?.data?.end_simple_train_consist_trip
  } catch (error) {
    console.error(
      'Oops, something went wrong with endSimpleTrainConsistTrip API:',
      error
    )
    throw error
  }
}

export const reprocessTrip = async ({ requestedBy, simpleTrainConsistId }) => {
  try {
    const res = await client.mutate({
      mutation: REPROCESS_TRIP,
      variables: {
        requestedBy: requestedBy,
        simpleTrainConsistId: simpleTrainConsistId
      },
      context: { clientName: 'ecorail' },
      fetchPolicy: 'no-cache'
    })
    console.log('Reprocess trip:', res)
    return res?.data?.reprocess_trip
  } catch (error) {
    console.error('Oops something went wrong with the reprocessTrip API', error)
    throw error
  }
}

export const getTrip = async tripId => {
  try {
    const res = await client.query({
      query: GET_TRIP,
      variables: {
        trip_id: tripId
      },
      context: { clientName: 'ecorail' }
    })

    console.log('Fetched trip:', res)
    return res?.data?.get_trip
  } catch (error) {
    throw error
  }
}

export const getTripByStcId = async stcId => {
  try {
    const res = await client.query({
      query: GET_TRIP_BY_STC_ID,
      variables: {
        simple_train_consist_id: stcId
      },
      context: { clientName: 'ecorail' }
    })

    console.log('Fetched trip:', res)
    return res?.data?.get_trip
  } catch (error) {
    throw error
  }
}

export const getUsersAndRolesbyEmail = async email => {
  try {
    const res = await client.query({
      query: GET_USERS_AND_ROLES_BY_EMAIL,
      variables: {
        email: email
      },
      context: { clientName: 'ecorail' }
    })

    console.log('Fetched user and roles by email:', res)
    return res?.data?.users_and_roles_by_email
  } catch (error) {
    throw error
  }
}

export const editUserPermission = async ({
  userId,
  railroadId,
  newRoleBitmask,
  newIsTest
}) => {
  try {
    const res = await client.mutate({
      mutation: EDIT_USER_PERMISSION,
      variables: {
        userId,
        railroadId,
        newRoleBitmask,
        newIsTest
      },
      context: { clientName: 'ecorail' },
      fetchPolicy: 'no-cache'
    })
    console.log('Edit user permission:', res)
    return res?.data?.edit_user_permission
  } catch (error) {
    console.error(
      'Oops, something went wrong with editUserPermission API:',
      error
    )
    throw error
  }
}

export const addNewUser = async ({
  email,
  password,
  railroad_id,
  role_bitmask,
  is_test
}) => {
  try {
    const res = await client.mutate({
      mutation: ADD_NEW_USER,
      variables: {
        email: email,
        password: password,
        railroad_id: railroad_id,
        role_bitmask: role_bitmask,
        is_test: is_test
      },
      context: { clientName: 'ecorail' },
      fetchPolicy: 'no-cache'
    })
    console.log('Add new user:', res)
    return res?.data?.add_new_user
  } catch (error) {
    console.error('Oops, something went wrong with addNewUser API:', error)
    throw error
  }
}

export const getStationsByRouteId = async ({ railroadId, routeId }) => {
  try {
    const res = await client.query({
      query: GET_STATIONS_BY_ROUTE_ID,
      variables: {
        railroadId: railroadId,
        routeId: routeId
      },
      context: { clientName: 'ecorail' },
      fetchPolicy: 'cache-first'
    })
    console.log('Stations by routeId:', res)
    return res?.data?.stations_by_route_id
  } catch (error) {
    console.error(
      'Oops, something went wrong with getStationsByRouteId API:',
      error
    )
    throw error
  }
}

export const getFeaturizersTripInformationOnPath = async ({
  expirySecs,
  simpleTrainConsistId
}) => {
  try {
    const res = await client.query({
      query: GET_FEATURIZERS_TRIP_INFORMATION_ON_PATH,
      variables: {
        expirySecs: expirySecs,
        simpleTrainConsistId: simpleTrainConsistId
      },
      context: { clientName: 'analytics' },
      fetchPolicy: 'no-cache'
    })
    console.log('Featurizers Trip Information On Path:', res)
    return res?.data?.get_featurizers_trip_information_path
  } catch (error) {
    console.error(
      'Oops, something went wrong with getFeaturizersTripInformationOnPath API:'
    )
    throw error
  }
}

export const softDeleteTrip = async ({ tripId, softDelete, context }) => {
  try {
    const res = await client.mutate({
      mutation: SOFT_DELETE_TRIP,
      variables: {
        tripId: tripId,
        softDelete: softDelete
      },
      context: { clientName: context },
      fetchPolicy: 'no-cache'
    })
    console.log('Soft delete trip:', res)
  } catch (error) {
    console.error(
      'Oops something went wrong with the softDeleteTrip API',
      error
    )
    throw error
  }
}

export const getBroadcastDataByRailroadId = async ({ railroadId }) => {
  try {
    const res = await client.query({
      query: GET_BROADCAST_DATA_BY_RAILROAD_ID,
      variables: {
        railroadId: railroadId
      },
      context: { clientName: 'ecorail' },
      fetchPolicy: 'no-cache'
    })
    console.log('Broadcast data by railroadId:', res)
    return res?.data?.get_broadcast_data_by_railroad_id
  } catch (error) {
    console.error(
      'Oops, something went wrong with getBroadcastDataByRailroadId API:'
    )
    throw error
  }
}

export const GetLocalizationUnits = async railroadId => {
  try {
    const res = await client.query({
      query: GET_LOCALIZATION_UNITS,
      variables: {
        railroad_id: railroadId
      },
      context: { clientName: 'ecorail' }
    })

    console.log('Fetched localization units:', res)
    return res?.data?.localization_units
  } catch (error) {
    throw error
  }
}

export const getFeaturizersInterpolateReverifyPath = async ({
  expirySecs,
  simpleTrainConsistId
}) => {
  try {
    const res = await client.query({
      query: GET_FEATURIZERS_INTERPOLATE_REVERIFY_PATH,
      variables: {
        expirySecs: expirySecs,
        simpleTrainConsistId: simpleTrainConsistId
      },
      context: { clientName: 'analytics' },
      fetchPolicy: 'no-cache'
    })
    console.log('Featurizers  Interpolate Reverify Path:', res)
    return res?.data?.get_featurizers_interpolate_reverify_path
  } catch (error) {
    console.error(
      'Oops, something went wrong with getFeaturizersInterpolateReverifyPath API:'
    )
    throw error
  }
}

export const getZoneSpeedLimitsByRouteId = async ({
  railroadId,
  routeId,
  startDestinationId,
  endDestinationId
}) => {
  try {
    const res = await client.query({
      query: GET_ZONE_SPEED_LIMITS_BY_ROUTES_ID,
      variables: {
        railroadId: railroadId,
        routeId: routeId,
        startDestinationId: startDestinationId,
        endDestinationId: endDestinationId
      },
      context: { clientName: 'ecorail' }
    })
    // console.log('🚀 ~ getSpeedLimitsByRouteId:', res)
    return res?.data?.track_data?.speed_limits
  } catch (error) {
    console.error(
      'Oops, something went wrong with getSpeedLimitsByRouteId API:'
    )
    throw error
  }
}

export const addZoneSpeedLimit = async ({}) => {
  try {
    // const res = await client.query({
    //   query: GET_ZONE_SPEED_LIMITS_BY_ROUTES_ID,
    //   variables: {
    //     railroadId: railroadId,
    //     routeId: routeId,
    //     startDestinationId: startDestinationId,
    //     endDestinationId: endDestinationId
    //   },
    //   context: { clientName: 'ecorail' }
    // })
    // console.log('🚀 ~ getSpeedLimitsByRouteId:', res)
    return new Promise(resolve => {
      setTimeout(() => {
        resolve({ status: 'ok' })
      }, 500)
    })
  } catch (error) {
    console.error(
      'Oops, something went wrong with getSpeedLimitsByRouteId API:'
    )
    throw error
  }
}

export const editZoneSpeedLimit = async ({}) => {
  try {
    // const res = await client.query({
    //   query: GET_ZONE_SPEED_LIMITS_BY_ROUTES_ID,
    //   variables: {
    //     railroadId: railroadId,
    //     routeId: routeId,
    //     startDestinationId: startDestinationId,
    //     endDestinationId: endDestinationId
    //   },
    //   context: { clientName: 'ecorail' }
    // })
    // console.log('🚀 ~ getSpeedLimitsByRouteId:', res)
    return { status: 'ok' }
  } catch (error) {
    console.error(
      'Oops, something went wrong with getSpeedLimitsByRouteId API:'
    )
    throw error
  }
}

export const deleteZoneSpeedLimit = async ({}) => {
  try {
    // const res = await client.query({
    //   query: GET_ZONE_SPEED_LIMITS_BY_ROUTES_ID,
    //   variables: {
    //     railroadId: railroadId,
    //     routeId: routeId,
    //     startDestinationId: startDestinationId,
    //     endDestinationId: endDestinationId
    //   },
    //   context: { clientName: 'ecorail' }
    // })
    // console.log('🚀 ~ getSpeedLimitsByRouteId:', res)
    return { status: 'ok' }
  } catch (error) {
    console.error(
      'Oops, something went wrong with getSpeedLimitsByRouteId API:'
    )
    throw error
  }
}
Leave a Comment