import { readdir, readFile } from 'fs' import path from 'path' import Papa from 'papaparse' var today = new Date() var monthAgo = new Date() monthAgo.setMonth(monthAgo.getMonth() - 1) export default { namespaced: true, state: { csv_files: [], rows: { data: [], meta: { fields: [] } }, start: monthAgo.toISOString().split('T')[0], end: today.toISOString().split('T')[0] }, getters: { csvs: (state) => { return state.csv_files }, rows: (state) => { return state.rows.data }, spending_rows: (state, getters) => { return getters.rows.filter(x => x.Montant < 0) }, start: (state) => { return state.start }, end: (state) => { return state.end }, date_filter_rows: (state, getters) => { var start = new Date(state.start) var end = new Date(state.end) return getters.spending_rows.filter(x => { return (new Date(x.Date) >= start) & (new Date(x.Date) < end) }) }, libelle_filter_rows: (state, getters) => (words, invert) => { if (!words) { return getters.date_filter_rows } if (invert) { return getters.date_filter_rows.filter(x => { return words.every(v => { return x.Libellé.indexOf(v) < 0 }) }) } else { return getters.date_filter_rows.filter(x => { return words.some(v => { return x.Libellé.indexOf(v) >= 0 }) }) } } }, mutations: { SET_CSV_FILES: (state, { csvs }) => { state.csv_files = csvs }, SET_DATA: (state, { data }) => { data.data = data.data.filter(x => x.Libellé !== undefined) state.rows = data }, APPEND_DATA: (state, { content }) => { state.rows.push(content) }, SET_START: (state, { start }) => { state.start = start }, SET_END: (state, { end }) => { state.end = end } }, actions: { find_csv (context) { try { readdir(context.rootGetters['config/data_dir'], (err, list) => { if (err) { console.log(err) } else { var csvs = list.filter(x => { return x.split('.').pop() === 'csv' }) for (var i in csvs) { context.dispatch('load_csv', csvs[i]) } context.commit('SET_CSV_FILES', { csvs }) } }) } catch (e) { console.log(e) } }, load_csv (context, csv) { readFile(path.join(context.rootGetters['config/data_dir'], csv), 'utf8', (err, content) => { if (err) { console.log(err) } else { var parseConfig = { header: true } var parsed = Papa.parse(content, parseConfig) context.commit('SET_DATA', { data: parsed }) } }) }, set_start (context, start) { context.commit('SET_START', { start }) }, set_end (context, end) { context.commit('SET_END', { end }) } } }