All files / store grades.js

0% Statements 0/125
0% Branches 0/82
0% Functions 0/47
0% Lines 0/105

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
import { firstBy } from 'thenby'
import {
  isBefore,
  isWithinInterval,
  parseISO,
  isWeekend,
  differenceInWeeks,
  isSameWeek,
} from 'date-fns'
import { getMutations, getValidator } from './index'
 
export const state = () => ({
  grades: [],
})
 
const parseGradeDates = grade => ({
  ...grade,
  added: parseISO(grade.added),
  obtained_date: parseISO(grade.obtained),
})
 
export const getters = {
  all: (state, getters) => getters.order(state.grades),
  one: (state, getters) => (value, prop = 'uuid') =>
    getters.all.find(o => o[prop] === value) || null,
  of: (state, getters, rootState, rootGetters) => (
    value,
    what = 'trimester',
    date = 'added'
  ) => {
    switch (what) {
      case 'trimester': {
        let trimesterInterval
        if (value === null) {
          trimesterInterval = rootGetters['schedule/currentTrimester']
        } else {
          if (![1, 2, 3].includes(value)) return []
          trimesterInterval = rootGetters['schedule/trimester'](value)
        }
        if (trimesterInterval === null) return []
        // Gets all the grades that have been added within the `value`th trimester
        return getters.all.filter(
          o => o[date] && isWithinInterval(o[date], trimesterInterval)
        )
      }
      case 'interval':
        return getters.all.filter(
          o => o[date] && isWithinInterval(o[date], value)
        )
 
      default:
        return []
    }
  },
  pending: (state, getters) => getters.all.filter(o => o.obtained === null),
  order: (state, getters) => grades => {
    // ↓ Makes a copy of grades to avoid mutating
    return [...grades].sort(firstBy((o1, o2) => isBefore(o1, o2)))
  },
  format: (state, getters, rootState, rootGetters) => value => {
    let unit = rootGetters['settings/value']('grade_max')
    unit = unit === 100 ? '%' : `/${unit}`
    return { value, unit }
  },
  mean: (state, getters) => (grades, debug = false) => {
    let ret
    grades = grades.filter(o => o.obtained !== null)
    if (!grades.length) ret = null
    else {
      const sumOfWeights = grades
        .map(o => o.weight * o.subject.weight)
        .reduce((acc, cur) => acc + cur)
      const sumOfGrades = grades
        .map(o => o.obtained * o.weight * o.subject.weight)
        .reduce((acc, cur) => acc + cur)
 
      ret = sumOfGrades / sumOfWeights
    }
    return ret
  },
  evolution: (state, getters) => grades => {
    /* Returns a number ∈ [0,1] that represents the relative gap between...
     * - the old mean (mean before the latest grade), and
     * - the new mean (mean with the latest grade)
     *
     * Effectively represents the relative evolution of the mean caused by the latest grade.
     */
    // Just to be sure, sort the grades
    // Also remove notes that have no `obtained` score (see `const oldMean = `) for why
    grades = getters.order(grades).filter(o => !!o.obtained)
    if (!grades.length) return null
    // Get the current mean (w/ all the grades given)
    const newMean = getters.mean(grades)
    // Get the mean w/o the latest grade *that has been obtained*
    //                                     ↓ we use .slice, .pop would mutate *the state*, which… no.
    const oldMean = getters.mean(grades.slice(0, -1))
    // Classic relative gap formula
    return (newMean - oldMean) / oldMean
  },
  currentTrimester: (state, getters, rootState, rootGetters) => {
    return getters.of(rootGetters['schedule/currentTrimester'], 'trimester')
  },
  currentTrimesterMean: (state, getters, rootState, rootGetters) =>
    getters.mean(getters.currentTrimester),
  currentTrimesterEvolution: (state, getters, rootState, rootGetters) =>
    getters.evolution(getters.currentTrimester),
  display: (_, __, ___, rootGetters) => (
    grade,
    unit = null,
    precision = 2,
    abs = false
  ) => {
    if (!grade && grade !== 0) return '—'
    grade = abs ? ~~grade : grade
    unit = unit || rootGetters['settings/value']('grade_max')
    return (grade * unit).toFixed(precision).replace('.', ',')
  },
  absoluteUnit: (_, __, ___, rootGetters) => (value, unit = null) => {
    unit = unit || rootGetters['settings/value']('grade_max')
    return value / unit
  },
  formatUnit: (_, __, ___, rootGetters) => (value, unit = null) => {
    unit = unit || rootGetters['settings/value']('grade_max')
    return value * unit
  },
  meanOfDays: (state, getters, rootState, rootGetters) => (
    start = null,
    end = null
  ) => {
    let grades
    if (start && end) {
      grades = getters.of({ start, end }, 'interval', 'obtained_date')
    } else if (end === null) {
      grades = getters.of(start, 'trimester', 'obtained_date')
    } else {
      grades = getters.of(null, 'trimester', 'obtained_date')
    }
    return getters.mean(grades)
  },
  ofWeekSmart: (_, { all }) =>
    all.filter(o => {
      const now = Date.now()
      if (isWeekend(now)) return differenceInWeeks(o.added, now) === 1
      else return isSameWeek(o.added, now)
    }),
  validate: getValidator({
    constraints: {
      maxLength: {
        300: ['name'],
      },
      minimum: {
        0: ['obtained', 'expected', 'goal', 'weight'],
        1: ['unit'],
      },
      required: ['name', 'subject', 'weight', 'unit'],
    },
    /* We use custom constraints because the default error message
     * is "should be less than 1", which does not coincide
     * with the UI, which shows the "real", non-normalized grade
     */
    customConstraints: [
      {
        message: 'La note obtenue est trop grande',
        field: 'obtained',
        constraint: (getters, object) =>
          object.obtained === null || object.obtained <= 1,
      },
      {
        message: 'La note estimée est trop grande',
        field: 'expected',
        constraint: (getters, object) =>
          object.expected === null || object.expected <= 1,
      },
      {
        message: "L'objectif de note est trop grand",
        field: 'goal',
        constraint: (getters, object) =>
          object.goal === null || object.goal <= 1,
      },
    ],
    fieldNames: {
      name: { gender: 'M', name: 'nom' },
      obtained: { gender: 'F', name: 'note obtenue' },
      expected: { gender: 'F', name: 'note estimée' },
      goal: { gender: 'M', name: 'objectif de note' },
      weight: { gender: 'M', name: 'coefficient' },
      unit: { gender: 'F', name: 'unité' },
      subject: { gender: 'F', name: 'matière' },
    },
    resourceName: { gender: 'F', name: 'note' },
  }),
}
 
export const mutations = {
  ...getMutations('grade', parseGradeDates),
}
 
export const actions = {
  async load({ commit, state }, force = false) {
    if (!force && state.grades.length) return
    try {
      const { data } = await this.$axios.get(`/grades/`)
      // console.log(`[from API] GET /grades/: OK`)
      if (data) commit('SET', data)
    } catch (error) {
      // console.error(`[from API] GET /grades/: Error`)
      try {
        // console.error(error.response.data)
      } catch (_) {
        // eslint-disable-next-line
        console.error(error)
      }
    }
  },
  async post({ commit, getters }, { grade, force }) {
    force = force || false
    if (!force) {
      const validation = getters.validate(grade)
      if (!validation.validated) return false
    }
    try {
      grade.subject = grade.subject.uuid
      const res = await this.$axios.post(`/grades/`, grade)
      const { data } = this.$axios.get(`/grades/${res.data.uuid}`)
      if (data) commit('ADD', data)
      return true
    } catch (error) {
      // eslint-disable-next-line
      console.error(error)
      return false
    }
  },
 
  async patch(
    { commit, dispatch, getters },
    uuid,
    modifications,
    force = false
  ) {
    if (!force) {
      let grade = getters.one(uuid)
      grade = { ...grade, ...modifications }
      const validation = await dispatch('validate', grade)
      if (!validation.validated) return validation
    }
    try {
      const { data } = await this.$axios.patch(`/grades/${uuid}`, modifications)
      if (data) commit('PATCH', uuid, data)
      // console.log(`[from API] PATCH /grades/${uuid}: OK`)
    } catch (error) {
      // console.error(`[from API] PATCH /grades/${uuid}: Error`)
      try {
        // console.error(error.response.data)
      } catch (_) {
        // eslint-disable-next-line
        console.error(error)
      }
    }
  },
  async delete({ commit }, uuid) {
    try {
      const { data } = await this.$axios.delete(`/grades/${uuid}`)
      if (data) commit('DEL', uuid)
      // console.log(`[from API] DELETE /grades/${uuid}: OK`)
    } catch (error) {
      // console.error(`[from API] DELETE /grades/${uuid}: Error`)
      try {
        // console.error(error.response.data)
      } catch (_) {
        // eslint-disable-next-line
        console.error(error)
      }
    }
  },
}