From b6f08e58fae35d5dd8a610af31c2950b37746695 Mon Sep 17 00:00:00 2001 From: cedricnjanga Date: Fri, 6 Oct 2017 10:17:17 +0200 Subject: Add webpacker gem and migrate the React apps --- app/javascript/date_filters/calendar.js | 6 + .../date_filters/compliance_control_set.js | 5 + app/javascript/date_filters/import.js | 5 + app/javascript/date_filters/index.js | 13 + app/javascript/date_filters/time_table.js | 5 + app/javascript/date_filters/workbench.js | 3 + app/javascript/helpers/clone.js | 12 + app/javascript/helpers/date_filters.js | 35 +++ app/javascript/journey_patterns/actions/index.js | 220 ++++++++++++++ app/javascript/journey_patterns/components/App.js | 21 ++ .../journey_patterns/components/ConfirmModal.js | 46 +++ .../journey_patterns/components/CreateModal.js | 122 ++++++++ .../journey_patterns/components/EditModal.js | 110 +++++++ .../journey_patterns/components/JourneyPattern.js | 131 +++++++++ .../journey_patterns/components/JourneyPatterns.js | 155 ++++++++++ .../journey_patterns/components/Navigate.js | 62 ++++ .../components/SaveJourneyPattern.js | 39 +++ .../containers/AddJourneyPattern.js | 30 ++ .../journey_patterns/containers/ConfirmModal.js | 30 ++ .../containers/JourneyPatternList.js | 34 +++ .../journey_patterns/containers/Modal.js | 26 ++ .../journey_patterns/containers/Navigate.js | 15 + .../containers/SaveJourneyPattern.js | 27 ++ .../journey_patterns/reducers/editMode.js | 10 + app/javascript/journey_patterns/reducers/index.js | 18 ++ .../journey_patterns/reducers/journeyPatterns.js | 90 ++++++ app/javascript/journey_patterns/reducers/modal.js | 41 +++ .../journey_patterns/reducers/pagination.js | 35 +++ app/javascript/journey_patterns/reducers/status.js | 21 ++ .../journey_patterns/reducers/stopPointsList.js | 6 + app/javascript/packs/application.js | 10 + app/javascript/packs/date_filters.js | 1 + app/javascript/packs/journey_patterns/index.js | 49 ++++ app/javascript/packs/routes/edit.js | 82 ++++++ app/javascript/packs/routes/show.js | 102 +++++++ app/javascript/packs/time_tables/edit.js | 77 +++++ app/javascript/routes/actions/index.js | 62 ++++ app/javascript/routes/components/App.js | 25 ++ app/javascript/routes/components/BSelect2.js | 125 ++++++++ app/javascript/routes/components/OlMap.js | 169 +++++++++++ app/javascript/routes/components/StopPoint.js | 94 ++++++ app/javascript/routes/components/StopPointList.js | 69 +++++ app/javascript/routes/containers/AddStopPoint.js | 20 ++ .../routes/containers/VisibleStopPoints.js | 58 ++++ app/javascript/routes/form_helper.js | 55 ++++ app/javascript/routes/index.js | 80 +++++ app/javascript/routes/reducers/index.js | 8 + app/javascript/routes/reducers/stopPoints.js | 144 +++++++++ app/javascript/routes/show.js | 102 +++++++ app/javascript/time_tables/actions/index.js | 324 +++++++++++++++++++++ .../time_tables/components/ConfirmModal.js | 50 ++++ .../time_tables/components/ErrorModal.js | 42 +++ .../time_tables/components/ExceptionsInDay.js | 71 +++++ app/javascript/time_tables/components/Metas.js | 139 +++++++++ app/javascript/time_tables/components/Navigate.js | 88 ++++++ .../time_tables/components/PeriodForm.js | 148 ++++++++++ .../time_tables/components/PeriodManager.js | 85 ++++++ .../time_tables/components/PeriodsInDay.js | 75 +++++ .../time_tables/components/SaveTimetable.js | 42 +++ .../time_tables/components/TagsSelect2.js | 77 +++++ .../time_tables/components/TimeTableDay.js | 31 ++ app/javascript/time_tables/components/Timetable.js | 115 ++++++++ app/javascript/time_tables/containers/App.js | 55 ++++ .../time_tables/containers/ConfirmModal.js | 31 ++ .../time_tables/containers/ErrorModal.js | 22 ++ app/javascript/time_tables/containers/Metas.js | 38 +++ app/javascript/time_tables/containers/Navigate.js | 18 ++ .../time_tables/containers/PeriodForm.js | 46 +++ .../time_tables/containers/SaveTimetable.js | 25 ++ app/javascript/time_tables/containers/Timetable.js | 44 +++ app/javascript/time_tables/reducers/index.js | 16 + app/javascript/time_tables/reducers/metas.js | 40 +++ app/javascript/time_tables/reducers/modal.js | 64 ++++ app/javascript/time_tables/reducers/pagination.js | 44 +++ app/javascript/time_tables/reducers/status.js | 15 + app/javascript/time_tables/reducers/timetable.js | 117 ++++++++ 76 files changed, 4567 insertions(+) create mode 100644 app/javascript/date_filters/calendar.js create mode 100644 app/javascript/date_filters/compliance_control_set.js create mode 100644 app/javascript/date_filters/import.js create mode 100644 app/javascript/date_filters/index.js create mode 100644 app/javascript/date_filters/time_table.js create mode 100644 app/javascript/date_filters/workbench.js create mode 100644 app/javascript/helpers/clone.js create mode 100644 app/javascript/helpers/date_filters.js create mode 100644 app/javascript/journey_patterns/actions/index.js create mode 100644 app/javascript/journey_patterns/components/App.js create mode 100644 app/javascript/journey_patterns/components/ConfirmModal.js create mode 100644 app/javascript/journey_patterns/components/CreateModal.js create mode 100644 app/javascript/journey_patterns/components/EditModal.js create mode 100644 app/javascript/journey_patterns/components/JourneyPattern.js create mode 100644 app/javascript/journey_patterns/components/JourneyPatterns.js create mode 100644 app/javascript/journey_patterns/components/Navigate.js create mode 100644 app/javascript/journey_patterns/components/SaveJourneyPattern.js create mode 100644 app/javascript/journey_patterns/containers/AddJourneyPattern.js create mode 100644 app/javascript/journey_patterns/containers/ConfirmModal.js create mode 100644 app/javascript/journey_patterns/containers/JourneyPatternList.js create mode 100644 app/javascript/journey_patterns/containers/Modal.js create mode 100644 app/javascript/journey_patterns/containers/Navigate.js create mode 100644 app/javascript/journey_patterns/containers/SaveJourneyPattern.js create mode 100644 app/javascript/journey_patterns/reducers/editMode.js create mode 100644 app/javascript/journey_patterns/reducers/index.js create mode 100644 app/javascript/journey_patterns/reducers/journeyPatterns.js create mode 100644 app/javascript/journey_patterns/reducers/modal.js create mode 100644 app/javascript/journey_patterns/reducers/pagination.js create mode 100644 app/javascript/journey_patterns/reducers/status.js create mode 100644 app/javascript/journey_patterns/reducers/stopPointsList.js create mode 100644 app/javascript/packs/application.js create mode 100644 app/javascript/packs/date_filters.js create mode 100644 app/javascript/packs/journey_patterns/index.js create mode 100644 app/javascript/packs/routes/edit.js create mode 100644 app/javascript/packs/routes/show.js create mode 100644 app/javascript/packs/time_tables/edit.js create mode 100644 app/javascript/routes/actions/index.js create mode 100644 app/javascript/routes/components/App.js create mode 100644 app/javascript/routes/components/BSelect2.js create mode 100644 app/javascript/routes/components/OlMap.js create mode 100644 app/javascript/routes/components/StopPoint.js create mode 100644 app/javascript/routes/components/StopPointList.js create mode 100644 app/javascript/routes/containers/AddStopPoint.js create mode 100644 app/javascript/routes/containers/VisibleStopPoints.js create mode 100644 app/javascript/routes/form_helper.js create mode 100644 app/javascript/routes/index.js create mode 100644 app/javascript/routes/reducers/index.js create mode 100644 app/javascript/routes/reducers/stopPoints.js create mode 100644 app/javascript/routes/show.js create mode 100644 app/javascript/time_tables/actions/index.js create mode 100644 app/javascript/time_tables/components/ConfirmModal.js create mode 100644 app/javascript/time_tables/components/ErrorModal.js create mode 100644 app/javascript/time_tables/components/ExceptionsInDay.js create mode 100644 app/javascript/time_tables/components/Metas.js create mode 100644 app/javascript/time_tables/components/Navigate.js create mode 100644 app/javascript/time_tables/components/PeriodForm.js create mode 100644 app/javascript/time_tables/components/PeriodManager.js create mode 100644 app/javascript/time_tables/components/PeriodsInDay.js create mode 100644 app/javascript/time_tables/components/SaveTimetable.js create mode 100644 app/javascript/time_tables/components/TagsSelect2.js create mode 100644 app/javascript/time_tables/components/TimeTableDay.js create mode 100644 app/javascript/time_tables/components/Timetable.js create mode 100644 app/javascript/time_tables/containers/App.js create mode 100644 app/javascript/time_tables/containers/ConfirmModal.js create mode 100644 app/javascript/time_tables/containers/ErrorModal.js create mode 100644 app/javascript/time_tables/containers/Metas.js create mode 100644 app/javascript/time_tables/containers/Navigate.js create mode 100644 app/javascript/time_tables/containers/PeriodForm.js create mode 100644 app/javascript/time_tables/containers/SaveTimetable.js create mode 100644 app/javascript/time_tables/containers/Timetable.js create mode 100644 app/javascript/time_tables/reducers/index.js create mode 100644 app/javascript/time_tables/reducers/metas.js create mode 100644 app/javascript/time_tables/reducers/modal.js create mode 100644 app/javascript/time_tables/reducers/pagination.js create mode 100644 app/javascript/time_tables/reducers/status.js create mode 100644 app/javascript/time_tables/reducers/timetable.js (limited to 'app/javascript') diff --git a/app/javascript/date_filters/calendar.js b/app/javascript/date_filters/calendar.js new file mode 100644 index 000000000..266fcd16a --- /dev/null +++ b/app/javascript/date_filters/calendar.js @@ -0,0 +1,6 @@ +const DateFilter = require('../helpers/date_filters') + +const calendarDF = new DateFilter("calendar_filter_btn", "Tous les champs du filtre de date doivent être remplis", "#q_contains_date_NUMi") + +module.exports = calendarDF + diff --git a/app/javascript/date_filters/compliance_control_set.js b/app/javascript/date_filters/compliance_control_set.js new file mode 100644 index 000000000..8ac90f54d --- /dev/null +++ b/app/javascript/date_filters/compliance_control_set.js @@ -0,0 +1,5 @@ +const DateFilter = require('../helpers/date_filters') + +const complianceControlSetDF = new DateFilter("compliance_control_set_filter_btn", "Tous les champs du filtre de date doivent être remplis", "#q_updated_at_start_date_NUMi", "#q_updated_at_end_date_NUMi") + +module.exports = complianceControlSetDF \ No newline at end of file diff --git a/app/javascript/date_filters/import.js b/app/javascript/date_filters/import.js new file mode 100644 index 000000000..997dbd3f6 --- /dev/null +++ b/app/javascript/date_filters/import.js @@ -0,0 +1,5 @@ +const DateFilter = require('../helpers/date_filters') + +const importDF = new DateFilter("import_filter_btn", "Tous les champs du filtre de date doivent être remplis", "#q_started_at_start_date_NUMi", "#q_started_at_end_date_NUMi") + +module.exports = importDF \ No newline at end of file diff --git a/app/javascript/date_filters/index.js b/app/javascript/date_filters/index.js new file mode 100644 index 000000000..1e09c8cf6 --- /dev/null +++ b/app/javascript/date_filters/index.js @@ -0,0 +1,13 @@ +const calendarDF = require('./calendar') +const complianceControlSetDF = require('./compliance_control_set') +const timetableDF = require('./time_table') +const importDF = require('./import') +const workbenchDF = require('./workbench') + +module.exports = { + calendarDF: () => calendarDF, + complianceControlSetDF: () => complianceControlSetDF, + timetableDF: () => timetableDF, + importDF: () => importDF, + workbenchDF: () => workbenchDF +} \ No newline at end of file diff --git a/app/javascript/date_filters/time_table.js b/app/javascript/date_filters/time_table.js new file mode 100644 index 000000000..e211bc12e --- /dev/null +++ b/app/javascript/date_filters/time_table.js @@ -0,0 +1,5 @@ +const DateFilter = require('../helpers/date_filters') + +const timetableDF = new DateFilter("time_table_filter_btn", "Tous les champs du filtre de date doivent être remplis", "#q_bounding_dates_start_date_NUMi", "#q_bounding_dates_end_date_NUMi") + +module.exports = timetableDF diff --git a/app/javascript/date_filters/workbench.js b/app/javascript/date_filters/workbench.js new file mode 100644 index 000000000..e5fd58e53 --- /dev/null +++ b/app/javascript/date_filters/workbench.js @@ -0,0 +1,3 @@ +const DateFilter = require('../helpers/date_filters') + +const workbenchDF = new DateFilter("referential_filter_btn", "Tous les champs du filtre de date doivent être remplis", "#q_validity_period_start_date_NUMi", "#q_validity_period_end_date_NUMi") diff --git a/app/javascript/helpers/clone.js b/app/javascript/helpers/clone.js new file mode 100644 index 000000000..00127e2b1 --- /dev/null +++ b/app/javascript/helpers/clone.js @@ -0,0 +1,12 @@ +import _ from 'lodash' + +/* This function helps having a bit more security when we pass data from the backend to the React parts + It clones the obj (window variable) and then conditionnaly delete the window variable +*/ + +export default function clone(window, key, deletable = false) { + let obj = _.cloneDeep(window[key]) + + if (deletable) delete window[key] + return obj +} \ No newline at end of file diff --git a/app/javascript/helpers/date_filters.js b/app/javascript/helpers/date_filters.js new file mode 100644 index 000000000..621e163ad --- /dev/null +++ b/app/javascript/helpers/date_filters.js @@ -0,0 +1,35 @@ +export default function DateFilter(buttonId, message, ...inputIds) { + this.buttonId = buttonId + this.inputIds = inputIds + this.message = message + + const getVal = (str, key) => { + let newStr = str.replace(/NUM/, key) + return $(newStr).val() + } + + const getDates = () => { + return this.inputIds.reduce((arr, id) => { + let newIds = [1, 2, 3].map(key => getVal(id, key)) + arr.push(...newIds) + return arr + },[]) + } + + const allInputFilled = () => { + return getDates().every(date => !!date) + } + + const noInputFilled = () => { + return getDates().every(date => !date) + } + + const button = document.getElementById(this.buttonId) + + button && button.addEventListener('click', (event) => { + if (!allInputFilled() && !noInputFilled()) { + event.preventDefault() + alert(this.message) + } + }) +} \ No newline at end of file diff --git a/app/javascript/journey_patterns/actions/index.js b/app/javascript/journey_patterns/actions/index.js new file mode 100644 index 000000000..0c1cb5f5c --- /dev/null +++ b/app/javascript/journey_patterns/actions/index.js @@ -0,0 +1,220 @@ +import Promise from 'promise-polyfill' + +// To add to window +if (!window.Promise) { + window.Promise = Promise; +} + +const actions = { + enterEditMode: () => ({ + type: "ENTER_EDIT_MODE" + }), + exitEditMode: () => ({ + type: "EXIT_EDIT_MODE" + }), + receiveJourneyPatterns : (json) => ({ + type: "RECEIVE_JOURNEY_PATTERNS", + json + }), + receiveErrors : (json) => ({ + type: "RECEIVE_ERRORS", + json + }), + unavailableServer : () => ({ + type: 'UNAVAILABLE_SERVER' + }), + goToPreviousPage : (dispatch, pagination) => ({ + type: 'GO_TO_PREVIOUS_PAGE', + dispatch, + pagination, + nextPage : false + }), + goToNextPage : (dispatch, pagination) => ({ + type: 'GO_TO_NEXT_PAGE', + dispatch, + pagination, + nextPage : true + }), + updateCheckboxValue : (e, index) => ({ + type : 'UPDATE_CHECKBOX_VALUE', + id : e.currentTarget.id, + index + }), + checkConfirmModal : (event, callback, stateChanged,dispatch) => { + if(stateChanged === true){ + return actions.openConfirmModal(callback) + }else{ + dispatch(actions.fetchingApi()) + return callback + } + }, + openConfirmModal : (callback) => ({ + type : 'OPEN_CONFIRM_MODAL', + callback + }), + openEditModal : (index, journeyPattern) => ({ + type : 'EDIT_JOURNEYPATTERN_MODAL', + index, + journeyPattern + }), + openCreateModal : () => ({ + type : 'CREATE_JOURNEYPATTERN_MODAL' + }), + deleteJourneyPattern : (index) => ({ + type : 'DELETE_JOURNEYPATTERN', + index, + }), + closeModal : () => ({ + type : 'CLOSE_MODAL' + }), + saveModal : (index, data) => ({ + type: 'SAVE_MODAL', + data, + index + }), + addJourneyPattern : (data) => ({ + type: 'ADD_JOURNEYPATTERN', + data, + }), + savePage : (dispatch, currentPage) => ({ + type: 'SAVE_PAGE', + dispatch + }), + updateTotalCount: (diff) => ({ + type: 'UPDATE_TOTAL_COUNT', + diff + }), + fetchingApi: () =>({ + type: 'FETCH_API' + }), + resetValidation: (target) => { + $(target).parent().removeClass('has-error').children('.help-block').remove() + }, + humanOID : (oid) => oid.split(':')[2].split("-").pop(), + validateFields : (fields) => { + const test = [] + + Object.keys(fields).map(function(key) { + test.push(fields[key].validity.valid) + }) + if(test.indexOf(false) >= 0) { + // Form is invalid + test.map(function(item, i) { + if(item == false) { + const k = Object.keys(fields)[i] + $(fields[k]).parent().addClass('has-error').children('.help-block').remove() + $(fields[k]).parent().append("" + fields[k].validationMessage + "") + } + }) + return false + } else { + // Form is valid + return true + } + }, + submitJourneyPattern : (dispatch, state, next) => { + dispatch(actions.fetchingApi()) + let urlJSON = window.location.pathname + ".json" + let hasError = false + fetch(urlJSON, { + credentials: 'same-origin', + method: 'PATCH', + contentType: 'application/json; charset=utf-8', + Accept: 'application/json', + body: JSON.stringify(state), + headers: { + 'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content') + } + }).then(response => { + if(!response.ok) { + hasError = true + } + return response.json() + }).then((json) => { + if(hasError == true) { + dispatch(actions.receiveErrors(json)) + } else { + if(next) { + dispatch(next) + } else { + if(json.length != window.currentItemsLength){ + dispatch(actions.updateTotalCount(window.currentItemsLength - json.length)) + } + window.currentItemsLength = json.length + dispatch(actions.exitEditMode()) + dispatch(actions.receiveJourneyPatterns(json)) + } + } + }) + }, + fetchJourneyPatterns : (dispatch, currentPage, nextPage) => { + if(currentPage == undefined){ + currentPage = 1 + } + let journeyPatterns = [] + let page + + switch (nextPage) { + case true: + page = currentPage + 1 + break + case false: + if(currentPage > 1){ + page = currentPage - 1 + } + break + default: + page = currentPage + break + } + let str = ".json" + if(page > 1){ + str = '.json?page=' + page.toString() + } + let urlJSON = window.location.pathname + str + let hasError = false + fetch(urlJSON, { + credentials: 'same-origin', + }).then(response => { + if(response.status == 500) { + hasError = true + } + return response.json() + }).then((json) => { + if(hasError == true) { + dispatch(actions.unavailableServer()) + } else { + if(json.length != 0){ + let val + for (val of json){ + for (let stop_point of val.route_short_description.stop_points){ + stop_point.checked = false + val.stop_area_short_descriptions.map((element) => { + if(element.stop_area_short_description.id === stop_point.id){ + stop_point.checked = true + } + }) + } + journeyPatterns.push({ + name: val.name, + object_id: val.object_id, + published_name: val.published_name, + registration_number: val.registration_number, + stop_points: val.route_short_description.stop_points, + deletable: false + }) + } + } + window.currentItemsLength = journeyPatterns.length + dispatch(actions.receiveJourneyPatterns(journeyPatterns)) + } + }) + }, + getChecked : (jp) => { + return jp.filter((obj) => { + return obj.checked + }) + } +} + +export default actions \ No newline at end of file diff --git a/app/javascript/journey_patterns/components/App.js b/app/javascript/journey_patterns/components/App.js new file mode 100644 index 000000000..ac6214cc1 --- /dev/null +++ b/app/javascript/journey_patterns/components/App.js @@ -0,0 +1,21 @@ +import React from 'react' +import AddJourneyPattern from '../containers/AddJourneyPattern' +import Navigate from '../containers/Navigate' +import Modal from '../containers/Modal' +import ConfirmModal from '../containers/ConfirmModal' +import SaveJourneyPattern from '../containers/SaveJourneyPattern' +import JourneyPatternList from '../containers/JourneyPatternList' + +const App = () => ( +
+ + + + + + + +
+) + +export default App diff --git a/app/javascript/journey_patterns/components/ConfirmModal.js b/app/javascript/journey_patterns/components/ConfirmModal.js new file mode 100644 index 000000000..2cc1bef44 --- /dev/null +++ b/app/javascript/journey_patterns/components/ConfirmModal.js @@ -0,0 +1,46 @@ +import React, { PropTypes } from 'react' + +export default function ConfirmModal({dispatch, modal, onModalAccept, onModalCancel, journeyPatterns}) { + return ( +
+
+
+
+
+

Confirmation

+
+
+
+

Vous vous apprêtez à changer de page. Voulez-vous valider vos modifications avant cela ?

+
+
+
+ + +
+
+
+
+
+ ) +} + +ConfirmModal.propTypes = { + modal: PropTypes.object.isRequired, + onModalAccept: PropTypes.func.isRequired, + onModalCancel: PropTypes.func.isRequired +} \ No newline at end of file diff --git a/app/javascript/journey_patterns/components/CreateModal.js b/app/javascript/journey_patterns/components/CreateModal.js new file mode 100644 index 000000000..d0eff6e57 --- /dev/null +++ b/app/javascript/journey_patterns/components/CreateModal.js @@ -0,0 +1,122 @@ +import React, { PropTypes, Component } from 'react' +import actions from '../actions' + +export default class CreateModal extends Component { + constructor(props) { + super(props) + } + + handleSubmit() { + if(actions.validateFields(this.refs) == true) { + this.props.onAddJourneyPattern(this.refs) + this.props.onModalClose() + $('#NewJourneyPatternModal').modal('hide') + } + } + + render() { + if(this.props.status.isFetching == true || this.props.status.policy['journey_patterns.create'] == false || this.props.editMode == false) { + return false + } + if(this.props.status.fetchSuccess == true) { + return ( +
+ +
+ ) + } else { + return false + } + } +} + +CreateModal.propTypes = { + index: PropTypes.number, + modal: PropTypes.object.isRequired, + status: PropTypes.object.isRequired, + onOpenCreateModal: PropTypes.func.isRequired, + onModalClose: PropTypes.func.isRequired, + onAddJourneyPattern: PropTypes.func.isRequired +} \ No newline at end of file diff --git a/app/javascript/journey_patterns/components/EditModal.js b/app/javascript/journey_patterns/components/EditModal.js new file mode 100644 index 000000000..699f89b85 --- /dev/null +++ b/app/javascript/journey_patterns/components/EditModal.js @@ -0,0 +1,110 @@ +import React, { PropTypes, Component } from 'react' +import actions from '../actions' + +export default class EditModal extends Component { + constructor(props) { + super(props) + } + + handleSubmit() { + if(actions.validateFields(this.refs) == true) { + this.props.saveModal(this.props.modal.modalProps.index, this.refs) + $('#JourneyPatternModal').modal('hide') + } + } + + render() { + return ( +
+
+
+
+
+

+ Editer la mission + {(this.props.modal.type == 'edit') && ( + "{this.props.modal.modalProps.journeyPattern.name}" + )} +

+
+ + {(this.props.modal.type == 'edit') && ( +
+
+
+ + actions.resetValidation(e.currentTarget)} + required + /> +
+ +
+
+
+ + actions.resetValidation(e.currentTarget)} + required + /> +
+
+
+
+ + actions.resetValidation(e.currentTarget)} + /> +
+
+
+
+ +
+ + +
+
+ )} +
+
+
+
+ ) + } +} + +EditModal.propTypes = { + index: PropTypes.number, + modal: PropTypes.object, + onModalClose: PropTypes.func.isRequired, + saveModal: PropTypes.func.isRequired +} \ No newline at end of file diff --git a/app/javascript/journey_patterns/components/JourneyPattern.js b/app/javascript/journey_patterns/components/JourneyPattern.js new file mode 100644 index 000000000..dde73a957 --- /dev/null +++ b/app/javascript/journey_patterns/components/JourneyPattern.js @@ -0,0 +1,131 @@ +import React, { PropTypes, Component } from 'react' +import actions from '../actions' + +export default class JourneyPattern extends Component{ + constructor(props){ + super(props) + this.previousCity = undefined + } + + vehicleJourneyURL(jpOid) { + let routeURL = window.location.pathname.split('/', 7).join('/') + let vjURL = routeURL + '/vehicle_journeys?jp=' + jpOid + + return ( + Horaires des courses + ) + } + + cityNameChecker(sp) { + let bool = false + if(sp.city_name != this.previousCity){ + bool = true + this.previousCity = sp.city_name + } + return ( +
+ + this.props.onCheckboxChange(e)} + type='checkbox' + id={sp.id} + checked={sp.checked} + disabled={(this.props.value.deletable || this.props.status.policy['journey_patterns.update'] == false || this.props.editMode == false) ? 'disabled' : ''} + > + + + +
+ ) + } + + getErrors(errors) { + let err = Object.keys(errors).map((key, index) => { + return ( +
  • + {key} { errors[key] } +
  • + ) + }) + + return ( + + ) + } + + isDisabled(action) { + return !this.props.status.policy[`journey_patterns.${action}`] && !this.props.editMode + } + + render() { + this.previousCity = undefined + + return ( +
    + {/* Errors */} + {/* this.props.value.errors ? this.getErrors(this.props.value.errors) : '' */} + +
    +
    {this.props.value.object_id ? actions.humanOID(this.props.value.object_id) : '-'}
    +
    {this.props.value.registration_number}
    +
    {actions.getChecked(this.props.value.stop_points).length} arrêt(s)
    + +
    +
    + +
    +
      +
    • + +
    • +
    • + {this.vehicleJourneyURL(this.props.value.object_id)} +
    • +
    • + +
    • +
    +
    +
    + + {this.props.value.stop_points.map((stopPoint, i) =>{ + return ( +
    + {this.cityNameChecker(stopPoint)} +
    + ) + })} +
    + ) + } +} + +JourneyPattern.propTypes = { + value: PropTypes.object, + index: PropTypes.number, + onCheckboxChange: PropTypes.func.isRequired, + onOpenEditModal: PropTypes.func.isRequired, + onDeleteJourneyPattern: PropTypes.func.isRequired +} \ No newline at end of file diff --git a/app/javascript/journey_patterns/components/JourneyPatterns.js b/app/javascript/journey_patterns/components/JourneyPatterns.js new file mode 100644 index 000000000..4b2badabb --- /dev/null +++ b/app/javascript/journey_patterns/components/JourneyPatterns.js @@ -0,0 +1,155 @@ +import React, { PropTypes, Component } from 'react' +import _ from 'lodash' +import JourneyPattern from './JourneyPattern' + + +export default class JourneyPatterns extends Component { + constructor(props){ + super(props) + this.previousCity = undefined + } + componentDidMount() { + this.props.onLoadFirstPage() + } + componentDidUpdate(prevProps, prevState) { + if(this.props.status.isFetching == false){ + $('.table-2entries').each(function() { + var refH = [] + var refCol = [] + + $(this).find('.t2e-head').children('div').each(function() { + var h = $(this).outerHeight(); + refH.push(h) + }); + + var i = 0 + $(this).find('.t2e-item').children('div').each(function() { + var h = $(this).outerHeight(); + if(refCol.length < refH.length){ + refCol.push(h) + } else { + if(h > refCol[i]) { + refCol[i] = h + } + } + if(i == (refH.length - 1)){ + i = 0 + } else { + i++ + } + }); + + for(var n = 0; n < refH.length; n++) { + if(refCol[n] < refH[n]) { + refCol[n] = refH[n] + } + } + + $(this).find('.th').css('height', refCol[0]); + + for(var nth = 1; nth < refH.length; nth++) { + $(this).find('.td:nth-child('+ (nth + 1) +')').css('height', refCol[nth]); + } + }); + } + } + + cityNameChecker(sp) { + let bool = false + if(sp.city_name != this.previousCity){ + bool = true + this.previousCity = sp.city_name + } + return ( +
    + {sp.name} +
    + ) + } + + render() { + this.previousCity = undefined + + if(this.props.status.isFetching == true) { + return ( +
    +
    +
    + ) + } else { + return ( +
    +
    + {(this.props.status.fetchSuccess == false) && ( +
    + Erreur : + la récupération des missions a rencontré un problème. Rechargez la page pour tenter de corriger le problème +
    + )} + + { _.some(this.props.journeyPatterns, 'errors') && ( +
    + Erreur : + {this.props.journeyPatterns.map((jp, index) => + jp.errors && jp.errors.map((err, i) => { + return ( +
      +
    • {err}
    • +
    + ) + }) + )} +
    + )} + +
    0) ? '' : ' no_result')}> +
    +
    +
    ID Mission
    +
    Code mission
    +
    Nb arrêts
    +
    + {this.props.stopPointsList.map((sp, i) =>{ + return ( +
    + {this.cityNameChecker(sp)} +
    + ) + })} +
    + +
    +
    + {this.props.journeyPatterns.map((journeyPattern, index) => + this.props.onCheckboxChange(e, index)} + onOpenEditModal= {() => this.props.onOpenEditModal(index, journeyPattern)} + onDeleteJourneyPattern={() => this.props.onDeleteJourneyPattern(index)} + status= {this.props.status} + editMode= {this.props.editMode} + /> + )} +
    +
    +
    +
    +
    + ) + } + } +} + +JourneyPatterns.propTypes = { + journeyPatterns: PropTypes.array.isRequired, + stopPointsList: PropTypes.array.isRequired, + status: PropTypes.object.isRequired, + onCheckboxChange: PropTypes.func.isRequired, + onLoadFirstPage: PropTypes.func.isRequired, + onOpenEditModal: PropTypes.func.isRequired +} \ No newline at end of file diff --git a/app/javascript/journey_patterns/components/Navigate.js b/app/javascript/journey_patterns/components/Navigate.js new file mode 100644 index 000000000..f2fdd668f --- /dev/null +++ b/app/javascript/journey_patterns/components/Navigate.js @@ -0,0 +1,62 @@ +import React, { PropTypes, Component } from 'react' +import actions from '../actions' + +export default function Navigate({ dispatch, journeyPatterns, pagination, status }) { + let firstPage = 1 + let lastPage = Math.ceil(pagination.totalCount / window.journeyPatternsPerPage) + + let firstItemOnPage = firstPage + (pagination.perPage * (pagination.page - firstPage)) + let lastItemOnPage = firstItemOnPage + (pagination.perPage - firstPage) + + if(status.isFetching == true) { + return false + } + if(status.fetchSuccess == true) { + return ( +
    +
    +
    + Liste des missions {firstItemOnPage} à {(lastItemOnPage < pagination.totalCount) ? lastItemOnPage : pagination.totalCount} sur {pagination.totalCount} +
    { + e.preventDefault() + }}> + + +
    +
    +
    +
    + ) + } else { + return false + } +} + +Navigate.propTypes = { + journeyPatterns: PropTypes.array.isRequired, + status: PropTypes.object.isRequired, + pagination: PropTypes.object.isRequired, + dispatch: PropTypes.func.isRequired +} \ No newline at end of file diff --git a/app/javascript/journey_patterns/components/SaveJourneyPattern.js b/app/javascript/journey_patterns/components/SaveJourneyPattern.js new file mode 100644 index 000000000..d071fa542 --- /dev/null +++ b/app/javascript/journey_patterns/components/SaveJourneyPattern.js @@ -0,0 +1,39 @@ +import React, { PropTypes, Component } from 'react' +import actions from '../actions' + +export default class SaveJourneyPattern extends Component { + constructor(props){ + super(props) + } + + render() { + if(this.props.status.policy['journey_patterns.update'] == false) { + return false + }else{ + return ( +
    +
    +
    {e.preventDefault()}}> + +
    +
    +
    + ) + } + } +} + +SaveJourneyPattern.propTypes = { + journeyPatterns: PropTypes.array.isRequired, + status: PropTypes.object.isRequired, + page: PropTypes.number.isRequired +} \ No newline at end of file diff --git a/app/javascript/journey_patterns/containers/AddJourneyPattern.js b/app/javascript/journey_patterns/containers/AddJourneyPattern.js new file mode 100644 index 000000000..b093fd111 --- /dev/null +++ b/app/javascript/journey_patterns/containers/AddJourneyPattern.js @@ -0,0 +1,30 @@ +import { connect } from 'react-redux' +import actions from '../actions' +import CreateModal from '../components/CreateModal' + +const mapStateToProps = (state) => { + return { + modal: state.modal, + journeyPatterns: state.journeyPatterns, + editMode: state.editMode, + status: state.status + } +} + +const mapDispatchToProps = (dispatch) => { + return { + onModalClose: () =>{ + dispatch(actions.closeModal()) + }, + onAddJourneyPattern: (data) =>{ + dispatch(actions.addJourneyPattern(data)) + }, + onOpenCreateModal: () =>{ + dispatch(actions.openCreateModal()) + } + } +} + +const AddJourneyPattern = connect(mapStateToProps, mapDispatchToProps)(CreateModal) + +export default AddJourneyPattern diff --git a/app/javascript/journey_patterns/containers/ConfirmModal.js b/app/javascript/journey_patterns/containers/ConfirmModal.js new file mode 100644 index 000000000..92ce09f33 --- /dev/null +++ b/app/javascript/journey_patterns/containers/ConfirmModal.js @@ -0,0 +1,30 @@ +import { connect } from 'react-redux' +import actions from '../actions' +import ConfirmModal from '../components/ConfirmModal' + +const mapStateToProps = (state) => { + return { + modal: state.modal, + journeyPatterns: state.journeyPatterns + } +} + +const mapDispatchToProps = (dispatch) => { + return { + onModalAccept: (next, state) =>{ + dispatch(actions.fetchingApi()) + actions.submitJourneyPattern(dispatch, state, next) + }, + onModalCancel: (next) =>{ + dispatch(actions.fetchingApi()) + dispatch(next) + }, + onModalClose: () =>{ + dispatch(actions.closeModal()) + } + } +} + +const ConfirmModalContainer = connect(mapStateToProps, mapDispatchToProps)(ConfirmModal) + +export default ConfirmModalContainer diff --git a/app/javascript/journey_patterns/containers/JourneyPatternList.js b/app/javascript/journey_patterns/containers/JourneyPatternList.js new file mode 100644 index 000000000..d98734407 --- /dev/null +++ b/app/javascript/journey_patterns/containers/JourneyPatternList.js @@ -0,0 +1,34 @@ +import { connect } from 'react-redux' +import actions from '../actions' +import JourneyPatterns from '../components/JourneyPatterns' + +const mapStateToProps = (state) => { + return { + journeyPatterns: state.journeyPatterns, + status: state.status, + editMode: state.editMode, + stopPointsList: state.stopPointsList + } +} + +const mapDispatchToProps = (dispatch) => { + return { + onLoadFirstPage: () =>{ + dispatch(actions.fetchingApi()) + actions.fetchJourneyPatterns(dispatch) + }, + onCheckboxChange: (e, index) =>{ + dispatch(actions.updateCheckboxValue(e, index)) + }, + onOpenEditModal: (index, journeyPattern) =>{ + dispatch(actions.openEditModal(index, journeyPattern)) + }, + onDeleteJourneyPattern: (index) =>{ + dispatch(actions.deleteJourneyPattern(index)) + } + } +} + +const JourneyPatternList = connect(mapStateToProps, mapDispatchToProps)(JourneyPatterns) + +export default JourneyPatternList diff --git a/app/javascript/journey_patterns/containers/Modal.js b/app/javascript/journey_patterns/containers/Modal.js new file mode 100644 index 000000000..ace71a857 --- /dev/null +++ b/app/javascript/journey_patterns/containers/Modal.js @@ -0,0 +1,26 @@ +import { connect } from 'react-redux' +import actions from '../actions' +import EditModal from '../components/EditModal' +import CreateModal from '../components/CreateModal' + +const mapStateToProps = (state) => { + return { + modal: state.modal, + journeyPattern: state.journeyPattern + } +} + +const mapDispatchToProps = (dispatch) => { + return { + onModalClose: () =>{ + dispatch(actions.closeModal()) + }, + saveModal: (index, data) =>{ + dispatch(actions.saveModal(index, data)) + } + } +} + +const ModalContainer = connect(mapStateToProps, mapDispatchToProps)(EditModal, CreateModal) + +export default ModalContainer diff --git a/app/javascript/journey_patterns/containers/Navigate.js b/app/javascript/journey_patterns/containers/Navigate.js new file mode 100644 index 000000000..d34e0b4c5 --- /dev/null +++ b/app/javascript/journey_patterns/containers/Navigate.js @@ -0,0 +1,15 @@ +import { connect } from 'react-redux' +import actions from '../actions' +import NavigateComponent from '../components/Navigate' + +const mapStateToProps = (state) => { + return { + journeyPatterns: state.journeyPatterns, + status: state.status, + pagination: state.pagination + } +} + +const Navigate = connect(mapStateToProps)(NavigateComponent) + +export default Navigate \ No newline at end of file diff --git a/app/javascript/journey_patterns/containers/SaveJourneyPattern.js b/app/javascript/journey_patterns/containers/SaveJourneyPattern.js new file mode 100644 index 000000000..b630c121c --- /dev/null +++ b/app/javascript/journey_patterns/containers/SaveJourneyPattern.js @@ -0,0 +1,27 @@ +import { connect } from 'react-redux' +import actions from '../actions' +import SaveJourneyPatternComponent from '../components/SaveJourneyPattern' + +const mapStateToProps = (state) => { + return { + journeyPatterns: state.journeyPatterns, + editMode: state.editMode, + page: state.pagination.page, + status: state.status + } +} + +const mapDispatchToProps = (dispatch) => { + return { + onEnterEditMode: () => { + dispatch(actions.enterEditMode()) + }, + onSubmitJourneyPattern: (next, state) => { + actions.submitJourneyPattern(dispatch, state, next) + } + } +} + +const SaveJourneyPattern = connect(mapStateToProps, mapDispatchToProps)(SaveJourneyPatternComponent) + +export default SaveJourneyPattern diff --git a/app/javascript/journey_patterns/reducers/editMode.js b/app/javascript/journey_patterns/reducers/editMode.js new file mode 100644 index 000000000..bff976804 --- /dev/null +++ b/app/javascript/journey_patterns/reducers/editMode.js @@ -0,0 +1,10 @@ +export default function editMode(state = {}, action ) { + switch (action.type) { + case "ENTER_EDIT_MODE": + return true + case "EXIT_EDIT_MODE": + return false + default: + return state + } +} \ No newline at end of file diff --git a/app/javascript/journey_patterns/reducers/index.js b/app/javascript/journey_patterns/reducers/index.js new file mode 100644 index 000000000..2ffaf86d4 --- /dev/null +++ b/app/javascript/journey_patterns/reducers/index.js @@ -0,0 +1,18 @@ +import { combineReducers } from 'redux' +import editMode from './editMode' +import status from './status' +import journeyPatterns from './journeyPatterns' +import pagination from './pagination' +import modal from './modal' +import stopPointsList from './stopPointsList' + +const journeyPatternsApp = combineReducers({ + editMode, + status, + journeyPatterns, + pagination, + stopPointsList, + modal +}) + +export default journeyPatternsApp diff --git a/app/javascript/journey_patterns/reducers/journeyPatterns.js b/app/javascript/journey_patterns/reducers/journeyPatterns.js new file mode 100644 index 000000000..7702e21bc --- /dev/null +++ b/app/javascript/journey_patterns/reducers/journeyPatterns.js @@ -0,0 +1,90 @@ +import _ from 'lodash' +import actions from "../actions" + +export default function journeyPattern(state = {}, action) { + switch (action.type) { + case 'ADD_JOURNEYPATTERN': + let stopPoints = window.stopPoints + + if(stopPoints != undefined) { + stopPoints.map((s)=>{ + s.checked = false + return s + }) + } + return { + name: action.data.name.value, + published_name: action.data.published_name.value, + registration_number: action.data.registration_number.value, + stop_points: stopPoints, + deletable: false + } + case 'UPDATE_CHECKBOX_VALUE': + var updatedStopPoints = state.stop_points.map((s) => { + if (String(s.id) == action.id) { + return _.assign({}, s, {checked : !s.checked}) + }else { + return s + } + }) + return _.assign({}, state, {stop_points: updatedStopPoints}) + default: + return state + } +} + +const journeyPatterns = (state = [], action) => { + switch (action.type) { + case 'RECEIVE_JOURNEY_PATTERNS': + return [...action.json] + case 'RECEIVE_ERRORS': + return [...action.json] + case 'GO_TO_PREVIOUS_PAGE': + $('#ConfirmModal').modal('hide') + if(action.pagination.page > 1){ + actions.fetchJourneyPatterns(action.dispatch, action.pagination.page, action.nextPage) + } + return state + case 'GO_TO_NEXT_PAGE': + $('#ConfirmModal').modal('hide') + if (action.pagination.totalCount - (action.pagination.page * action.pagination.perPage) > 0){ + actions.fetchJourneyPatterns(action.dispatch, action.pagination.page, action.nextPage) + } + return state + case 'UPDATE_CHECKBOX_VALUE': + return state.map((j, i) =>{ + if(i == action.index) { + return journeyPattern(j, action) + } else { + return j + } + }) + case 'DELETE_JOURNEYPATTERN': + return state.map((j, i) =>{ + if(i == action.index) { + return _.assign({}, j, {deletable: true}) + } else { + return j + } + }) + case 'ADD_JOURNEYPATTERN': + return [ + journeyPattern(state, action), + ...state + ] + case 'SAVE_MODAL': + return state.map((j, i) =>{ + if(i == action.index) { + return _.assign({}, j, { + name: action.data.name.value, + published_name: action.data.published_name.value, + registration_number: action.data.registration_number.value + }) + } else { + return j + } + }) + default: + return state + } +} \ No newline at end of file diff --git a/app/javascript/journey_patterns/reducers/modal.js b/app/javascript/journey_patterns/reducers/modal.js new file mode 100644 index 000000000..0a96f1679 --- /dev/null +++ b/app/javascript/journey_patterns/reducers/modal.js @@ -0,0 +1,41 @@ +import _ from 'lodash' + +export default function modal(state = {}, action) { + switch (action.type) { + case 'OPEN_CONFIRM_MODAL': + $('#ConfirmModal').modal('show') + return _.assign({}, state, { + type: 'confirm', + confirmModal: { + callback: action.callback, + } + }) + case 'EDIT_JOURNEYPATTERN_MODAL': + return { + type: 'edit', + modalProps: { + index: action.index, + journeyPattern: action.journeyPattern + }, + confirmModal: {} + } + case 'CREATE_JOURNEYPATTERN_MODAL': + return { + type: 'create', + modalProps: {}, + confirmModal: {} + } + case 'DELETE_JOURNEYPATTERN': + return _.assign({}, state, { type: '' }) + case 'SAVE_MODAL': + return _.assign({}, state, { type: '' }) + case 'CLOSE_MODAL': + return { + type: '', + modalProps: {}, + confirmModal: {} + } + default: + return state + } +} \ No newline at end of file diff --git a/app/javascript/journey_patterns/reducers/pagination.js b/app/javascript/journey_patterns/reducers/pagination.js new file mode 100644 index 000000000..01fdf21d4 --- /dev/null +++ b/app/javascript/journey_patterns/reducers/pagination.js @@ -0,0 +1,35 @@ +import _ from 'lodash' + +export default function pagination (state = {}, action) { + switch (action.type) { + case 'RECEIVE_JOURNEY_PATTERNS': + return _.assign({}, state, {stateChanged: false}) + case 'GO_TO_PREVIOUS_PAGE': + if (action.pagination.page > 1){ + toggleOnConfirmModal() + return _.assign({}, state, {page : action.pagination.page - 1, stateChanged: false}) + } + return state + case 'GO_TO_NEXT_PAGE': + if (state.totalCount - (action.pagination.page * action.pagination.perPage) > 0){ + toggleOnConfirmModal() + return _.assign({}, state, {page : action.pagination.page + 1, stateChanged: false}) + } + return state + case 'UPDATE_CHECKBOX_VALUE': + case 'ADD_JOURNEYPATTERN': + case 'SAVE_MODAL': + toggleOnConfirmModal('modal') + return _.assign({}, state, {stateChanged: true}) + case 'UPDATE_TOTAL_COUNT': + return _.assign({}, state, {totalCount : state.totalCount - action.diff }) + default: + return state + } +} + +const toggleOnConfirmModal = (arg = '') =>{ + $('.confirm').each(function(){ + $(this).data('toggle','') + }) +} \ No newline at end of file diff --git a/app/javascript/journey_patterns/reducers/status.js b/app/javascript/journey_patterns/reducers/status.js new file mode 100644 index 000000000..88c75966d --- /dev/null +++ b/app/javascript/journey_patterns/reducers/status.js @@ -0,0 +1,21 @@ +import _ from 'lodash' +import actions from '../actions' + +export default function status (state = {}, action) { + switch (action.type) { + case 'UNAVAILABLE_SERVER': + return _.assign({}, state, {fetchSuccess: false}) + case 'FETCH_API': + return _.assign({}, state, {isFetching: true}) + case 'RECEIVE_JOURNEY_PATTERNS': + return _.assign({}, state, {fetchSuccess: true, isFetching: false}) + case 'RECEIVE_ERRORS': + return _.assign({}, state, {isFetching: false}) + case 'ENTER_EDIT_MODE': + return _.assign({}, state, {editMode: true}) + case 'EXIT_EDIT_MODE': + return _.assign({}, state, {editMode: false}) + default: + return state + } +} \ No newline at end of file diff --git a/app/javascript/journey_patterns/reducers/stopPointsList.js b/app/javascript/journey_patterns/reducers/stopPointsList.js new file mode 100644 index 000000000..ee5eb1a80 --- /dev/null +++ b/app/javascript/journey_patterns/reducers/stopPointsList.js @@ -0,0 +1,6 @@ +export default function stopPointsList (state = [], action) { + switch (action.type) { + default: + return state + } +} \ No newline at end of file diff --git a/app/javascript/packs/application.js b/app/javascript/packs/application.js new file mode 100644 index 000000000..54b106ee0 --- /dev/null +++ b/app/javascript/packs/application.js @@ -0,0 +1,10 @@ +/* eslint no-console:0 */ +// This file is automatically compiled by Webpack, along with any other files +// present in this directory. You're encouraged to place your actual application logic in +// a relevant structure within app/javascript and only use these pack files to reference +// that code so it'll be compiled. +// +// To reference this file, add <%= javascript_pack_tag 'application' %> to the appropriate +// layout file, like app/views/layouts/application.html.erb + +console.log('Hello World from Webpacker') diff --git a/app/javascript/packs/date_filters.js b/app/javascript/packs/date_filters.js new file mode 100644 index 000000000..db58bd679 --- /dev/null +++ b/app/javascript/packs/date_filters.js @@ -0,0 +1 @@ +const DateFilter = require('../date_filters/index') \ No newline at end of file diff --git a/app/javascript/packs/journey_patterns/index.js b/app/javascript/packs/journey_patterns/index.js new file mode 100644 index 000000000..fde28b45d --- /dev/null +++ b/app/javascript/packs/journey_patterns/index.js @@ -0,0 +1,49 @@ +import React from 'react' +import { render } from 'react-dom' +import { Provider } from 'react-redux' +import { createStore } from 'redux' +import journeyPatternsApp from '../../journey_patterns/reducers' +import App from '../../journey_patterns/components/App' +import clone from '../../helpers/clone' + +// logger, DO NOT REMOVE +// var applyMiddleware = require('redux').applyMiddleware +// var createLogger = require('redux-logger') +// var thunkMiddleware = require('redux-thunk').default +// var promise = require('redux-promise') + +var initialState = { + editMode: false, + status: { + policy: window.perms, + fetchSuccess: true, + isFetching: false + }, + journeyPatterns: [], + stopPointsList: window.stopPoints, + pagination: { + page : 1, + totalCount: window.journeyPatternLength, + perPage: window.journeyPatternsPerPage, + stateChanged: false + }, + modal: { + type: '', + modalProps: {}, + confirmModal: {} + } +} +// const loggerMiddleware = createLogger() + +let store = createStore( + journeyPatternsApp, + initialState, + // applyMiddleware(thunkMiddleware, promise, loggerMiddleware) +) + +render( + + + , + document.getElementById('journey_patterns') +) diff --git a/app/javascript/packs/routes/edit.js b/app/javascript/packs/routes/edit.js new file mode 100644 index 000000000..810489353 --- /dev/null +++ b/app/javascript/packs/routes/edit.js @@ -0,0 +1,82 @@ +import React from 'react' +import PropTypes from 'prop-types' +import { render } from 'react-dom' +import { Provider } from 'react-redux' +import { createStore } from 'redux' + +import reducers from '../../routes/reducers' +import App from '../../routes/components/App' +import { handleForm, handleStopPoints } from '../../routes/form_helper' +import clone from '../../helpers/clone' +let datas = clone(window, "itinerary_stop", true) +datas = JSON.parse(decodeURIComponent(datas)) + +// logger, DO NOT REMOVE +// var applyMiddleware = require('redux').applyMiddleware +// var createLogger = require('redux-logger') +// var thunkMiddleware = require('redux-thunk').default +// var promise = require('redux-promise') + +const getInitialState = () => { + let state = [] + + datas.map(function (v, i) { + let fancyText = v.name.replace("'", "\'") + if (v.zip_code && v.city_name) + fancyText += ", " + v.zip_code + " " + v.city_name.replace("'", "\'") + + state.push({ + stoppoint_id: v.stoppoint_id, + stoparea_id: v.stoparea_id, + user_objectid: v.user_objectid, + short_name: v.short_name ? v.short_name.replace("'", "\'") : '', + area_type: v.area_type, + index: i, + edit: false, + city_name: v.city_name ? v.city_name.replace("'", "\'") : '', + zip_code: v.zip_code, + name: v.name ? v.name.replace("'", "\'") : '', + registration_number: v.registration_number, + text: fancyText, + for_boarding: v.for_boarding || "normal", + for_alighting: v.for_alighting || "normal", + longitude: v.longitude || 0, + latitude: v.latitude || 0, + comment: v.comment ? v.comment.replace("'", "\'") : '', + olMap: { + isOpened: false, + json: {} + } + }) + }) + + return state +} + +var initialState = { stopPoints: getInitialState() } +// const loggerMiddleware = createLogger() +let store = createStore( + reducers, + initialState + // applyMiddleware(thunkMiddleware, promise, loggerMiddleware) +) + +render( + + + , + document.getElementById('stop_points') +) + +document.querySelector('input[name=commit]').addEventListener('click', (event) => { + let state = store.getState() + + let name = $("#route_name").val() + let publicName = $("#route_published_name").val() + if (name == "" || publicName == "") { + event.preventDefault() + handleForm("#route_name", "#route_published_name") + } + + handleStopPoints(event, state) +}) diff --git a/app/javascript/packs/routes/show.js b/app/javascript/packs/routes/show.js new file mode 100644 index 000000000..7f14a6f11 --- /dev/null +++ b/app/javascript/packs/routes/show.js @@ -0,0 +1,102 @@ +import clone from '../../helpers/clone' +let route = clone(window, "route", true) +route = JSON.parse(decodeURIComponent(route)) + +const geoColPts = [] +const geoColLns = [] +const geoColEdges = [ + new ol.Feature({ + geometry: new ol.geom.Point(ol.proj.fromLonLat([parseFloat(route[0].longitude), parseFloat(route[0].latitude)])) + }), + new ol.Feature({ + geometry: new ol.geom.Point(ol.proj.fromLonLat([parseFloat(route[route.length - 1].longitude), parseFloat(route[route.length - 1].latitude)])) + }) +] +route.forEach(function (stop, i) { + if (i < route.length - 1) { + geoColLns.push(new ol.Feature({ + geometry: new ol.geom.LineString([ + ol.proj.fromLonLat([parseFloat(route[i].longitude), parseFloat(route[i].latitude)]), + ol.proj.fromLonLat([parseFloat(route[i + 1].longitude), parseFloat(route[i + 1].latitude)]) + ]) + })) + } + geoColPts.push(new ol.Feature({ + geometry: new ol.geom.Point(ol.proj.fromLonLat([parseFloat(stop.longitude), parseFloat(stop.latitude)])) + }) + ) +}) +var edgeStyles = new ol.style.Style({ + image: new ol.style.Circle(({ + radius: 5, + stroke: new ol.style.Stroke({ + color: '#007fbb', + width: 2 + }), + fill: new ol.style.Fill({ + color: '#007fbb', + width: 2 + }) + })) +}) +var defaultStyles = new ol.style.Style({ + image: new ol.style.Circle(({ + radius: 4, + stroke: new ol.style.Stroke({ + color: '#007fbb', + width: 2 + }), + fill: new ol.style.Fill({ + color: '#ffffff', + width: 2 + }) + })) +}) +var lineStyle = new ol.style.Style({ + stroke: new ol.style.Stroke({ + color: '#007fbb', + width: 3 + }) +}) + +var vectorPtsLayer = new ol.layer.Vector({ + source: new ol.source.Vector({ + features: geoColPts + }), + style: defaultStyles, + zIndex: 2 +}) +var vectorEdgesLayer = new ol.layer.Vector({ + source: new ol.source.Vector({ + features: geoColEdges + }), + style: edgeStyles, + zIndex: 3 +}) +var vectorLnsLayer = new ol.layer.Vector({ + source: new ol.source.Vector({ + features: geoColLns + }), + style: [lineStyle], + zIndex: 1 +}) + +var map = new ol.Map({ + target: 'route_map', + layers: [ + new ol.layer.Tile({ + source: new ol.source.OSM() + }), + vectorPtsLayer, + vectorEdgesLayer, + vectorLnsLayer + ], + controls: [new ol.control.ScaleLine(), new ol.control.Zoom(), new ol.control.ZoomSlider()], + interactions: ol.interaction.defaults({ + zoom: true + }), + view: new ol.View({ + center: ol.proj.fromLonLat([parseFloat(route[0].longitude), parseFloat(route[0].latitude)]), + zoom: 13 + }) +}); diff --git a/app/javascript/packs/time_tables/edit.js b/app/javascript/packs/time_tables/edit.js new file mode 100644 index 000000000..cf058d501 --- /dev/null +++ b/app/javascript/packs/time_tables/edit.js @@ -0,0 +1,77 @@ +import React from 'react' +import { render } from 'react-dom' +import { Provider } from 'react-redux' +import { createStore } from 'redux' +import timeTablesApp from '../../time_tables/reducers' +import App from '../../time_tables/containers/App' +import clone from '../../helpers/clone' + +const actionType = clone(window, "actionType", true) + +// logger, DO NOT REMOVE +// var applyMiddleware = require('redux').applyMiddleware +// var createLogger = require('redux-logger') +// var thunkMiddleware = require('redux-thunk').default +// var promise = require('redux-promise') + +let initialState = { + status: { + actionType: actionType, + policy: window.perms, + fetchSuccess: true, + isFetching: false + }, + timetable: { + current_month: [], + current_periode_range: '', + periode_range: [], + time_table_periods: [], + time_table_dates: [] + }, + metas: { + comment: '', + day_types: [], + tags: [], + initial_tags: [], + color: '', + calendar: null + }, + pagination: { + stateChanged: false, + currentPage: '', + periode_range: [] + }, + modal: { + type: '', + modalProps: { + active: false, + begin: { + day: '01', + month: '01', + year: String(new Date().getFullYear()) + }, + end: { + day: '01', + month: '01', + year: String(new Date().getFullYear()) + }, + index: false, + error: '' + }, + confirmModal: {} + } +} +// const loggerMiddleware = createLogger() + +let store = createStore( + timeTablesApp, + initialState, + // applyMiddleware(thunkMiddleware, promise, loggerMiddleware) +) + +render( + + + , + document.getElementById('periods') +) diff --git a/app/javascript/routes/actions/index.js b/app/javascript/routes/actions/index.js new file mode 100644 index 000000000..13b2d60b2 --- /dev/null +++ b/app/javascript/routes/actions/index.js @@ -0,0 +1,62 @@ +const actions = { + addStop : () => { + return { + type: 'ADD_STOP' + } + }, + moveStopUp : (index) => { + return { + type: 'MOVE_STOP_UP', + index + } + }, + moveStopDown : (index) => { + return { + type: 'MOVE_STOP_DOWN', + index + } + }, + deleteStop : (index) => { + return { + type: 'DELETE_STOP', + index + } + }, + updateInputValue : (index, text) => { + return { + type : 'UPDATE_INPUT_VALUE', + index, + text + } + }, + updateSelectValue: (e, index) => { + return { + type :'UPDATE_SELECT_VALUE', + select_id: e.currentTarget.id, + select_value: e.currentTarget.value, + index + } + }, + toggleMap: (index) =>({ + type: 'TOGGLE_MAP', + index + }), + toggleEdit: (index) =>({ + type: 'TOGGLE_EDIT', + index + }), + closeMaps: () => ({ + type : 'CLOSE_MAP' + }), + selectMarker: (index, data) =>({ + type: 'SELECT_MARKER', + index, + data + }), + unselectMarker: (index) => ({ + type: 'UNSELECT_MARKER', + index + }) +} + +module.exports = actions diff --git a/app/javascript/routes/components/App.js b/app/javascript/routes/components/App.js new file mode 100644 index 000000000..0f5786407 --- /dev/null +++ b/app/javascript/routes/components/App.js @@ -0,0 +1,25 @@ +import React, { Component, PropTypes } from 'react' +import AddStopPoint from '../containers/AddStopPoint' +import VisibleStopPoints from'../containers/VisibleStopPoints' +import clone from '../../helpers/clone' +const I18n = clone(window , "I18n", true) + +export default class App extends Component { + + getChildContext() { + return { I18n } + } + + render() { + return ( +
    + + +
    + ) + } +} + +App.childContextTypes = { + I18n: PropTypes.object +} diff --git a/app/javascript/routes/components/BSelect2.js b/app/javascript/routes/components/BSelect2.js new file mode 100644 index 000000000..5cc9561e9 --- /dev/null +++ b/app/javascript/routes/components/BSelect2.js @@ -0,0 +1,125 @@ +import _ from'lodash' +import React, { Component, PropTypes } from 'react' +import Select2 from 'react-select2-wrapper' + + +// get JSON full path +var origin = window.location.origin +var path = window.location.pathname.split('/', 3).join('/') + + +class BSelect3 extends Component{ + constructor(props, context) { + super(props, context) + } + onChange(e) { + this.props.onChange(this.props.index, { + text: e.currentTarget.textContent, + stoparea_id: e.currentTarget.value, + user_objectid: e.params.data.user_objectid, + longitude: e.params.data.longitude, + latitude: e.params.data.latitude, + name: e.params.data.name, + short_name: e.params.data.short_name, + city_name: e.params.data.city_name, + area_type: e.params.data.area_type, + zip_code: e.params.data.zip_code, + comment: e.params.data.comment + }) + } + + parsedText(data) { + let a = data.replace('', '') + let b = a.split('') + if (b.length > 1) { + return ( + + {b[0]} + {b[1]} + + ) + } else { + return ( + {data} + ) + } + } + + render() { + if(this.props.value.edit) + return ( +
    + +
    + ) + else + if(!this.props.value.stoparea_id) + return ( +
    + +
    + ) + else + return ( + + {this.parsedText(this.props.value.text)} + + ) + } +} + +export default class BSelect2 extends Component{ + componentDidMount() { + this.refs.newSelect.el.select2('open') + } + + render() { + return ( + _.assign( + {}, + item, + { text: item.name + ", " + item.zip_code + " " + item.short_city_name + " (" + item.user_objectid + ")" } + ) + ) + }; + }, + cache: true + }, + escapeMarkup: function (markup) { return markup; }, + minimumInputLength: 3 + }} + /> + ) + } +} + +BSelect2.contextTypes = { + I18n: PropTypes.object +} diff --git a/app/javascript/routes/components/OlMap.js b/app/javascript/routes/components/OlMap.js new file mode 100644 index 000000000..2c01dfa7f --- /dev/null +++ b/app/javascript/routes/components/OlMap.js @@ -0,0 +1,169 @@ +import _ from 'lodash' +import React, { Component, PropTypes } from 'react' + +export default class OlMap extends Component{ + constructor(props, context){ + super(props, context) + } + + fetchApiURL(id){ + const origin = window.location.origin + const path = window.location.pathname.split('/', 3).join('/') + return origin + path + "/autocomplete_stop_areas/" + id + "/around?target_type=zdep" + } + + componentDidUpdate(prevProps, prevState){ + if(prevProps.value.olMap.isOpened == false && this.props.value.olMap.isOpened == true){ + var source = new ol.source.Vector({ + format: new ol.format.GeoJSON(), + url: this.fetchApiURL(this.props.value.stoparea_id) + }) + var feature = new ol.Feature({ + geometry: new ol.geom.Point(ol.proj.fromLonLat([parseFloat(this.props.value.longitude), parseFloat(this.props.value.latitude)])) + }) + + var defaultStyles = new ol.style.Style({ + image: new ol.style.Circle(({ + radius: 4, + fill: new ol.style.Fill({ + color: '#004d87' + }) + })) + }) + var selectedStyles = new ol.style.Style({ + image: new ol.style.Circle(({ + radius: 6, + fill: new ol.style.Fill({ + color: '#da2f36' + }) + })) + }) + + var centerLayer = new ol.layer.Vector({ + source: new ol.source.Vector({ + features: [feature] + }), + style: selectedStyles, + zIndex: 2 + }) + var vectorLayer = new ol.layer.Vector({ + source: source, + style: defaultStyles, + zIndex: 1 + }); + + var map = new ol.Map({ + target: 'stoppoint_map' + this.props.index, + layers: [ + new ol.layer.Tile({ + source: new ol.source.OSM() + }), + vectorLayer, + centerLayer + ], + controls: [ new ol.control.ScaleLine() ], + interactions: ol.interaction.defaults({ + dragPan: false, + doubleClickZoom: false, + shiftDragZoom: false, + mouseWheelZoom: false + }), + view: new ol.View({ + center: ol.proj.fromLonLat([parseFloat(this.props.value.longitude), parseFloat(this.props.value.latitude)]), + zoom: 18 + }) + }); + + // Selectable marker + var select = new ol.interaction.Select({ + style: selectedStyles + }); + + map.addInteraction(select); + + select.on('select', function(e) { + feature.setStyle(defaultStyles); + centerLayer.setZIndex(0); + + if(e.selected.length != 0) { + + if(e.selected[0].getGeometry() == feature.getGeometry()) { + if(e.selected[0].style_.image_.fill_.color_ != '#da2f36'){ + feature.setStyle(selectedStyles); + centerLayer.setZIndex(2); + e.preventDefault() + return false + } + } + let data = _.assign({}, e.selected[0].getProperties(), {geometry: undefined}); + + this.props.onSelectMarker(this.props.index, data) + } else { + this.props.onUnselectMarker(this.props.index) + } + }, this); + } + } + + render() { + if (this.props.value.olMap.isOpened) { + return ( +
    +
    +

    + {this.props.value.olMap.json.name} +

    +

    + {this.context.I18n.routes.edit.stop_point_type} : + {this.props.value.olMap.json.area_type} +

    +

    + {this.context.I18n.routes.edit.short_name} : + {this.props.value.olMap.json.short_name} +

    +

    + {this.context.I18n.id_reflex} : + {this.props.value.olMap.json.user_objectid} +

    + +

    {this.context.I18n.routes.edit.map.coordinates} :

    +

    + {this.context.I18n.routes.edit.map.proj}.: WSG84
    + {this.context.I18n.routes.edit.map.lat}.: {this.props.value.olMap.json.latitude}
    + {this.context.I18n.routes.edit.map.lon}.: {this.props.value.olMap.json.longitude} +

    +

    + {this.context.I18n.routes.edit.map.postal_code} : + {this.props.value.olMap.json.zip_code} +

    +

    + {this.context.I18n.routes.edit.map.city} : + {this.props.value.olMap.json.city_name} +

    +

    + {this.context.I18n.routes.edit.map.comment} : + {this.props.value.olMap.json.comment} +

    + {(this.props.value.stoparea_id != this.props.value.olMap.json.stoparea_id) &&( +
    {this.props.onUpdateViaOlMap(this.props.index, this.props.value.olMap.json)}} + >{this.context.I18n.actions.select}
    + )} +
    +
    +
    +
    +
    + ) + } else { + return false + } + } +} + +OlMap.PropTypes = { +} + +OlMap.contextTypes = { + I18n: PropTypes.object +} diff --git a/app/javascript/routes/components/StopPoint.js b/app/javascript/routes/components/StopPoint.js new file mode 100644 index 000000000..606121f99 --- /dev/null +++ b/app/javascript/routes/components/StopPoint.js @@ -0,0 +1,94 @@ +import React, { PropTypes } from 'react' +import BSelect2 from './BSelect2' +import OlMap from './OlMap' + +export default function StopPoint(props, {I18n}) { + return ( +
    +
    +
    + {props.value.user_objectid} +
    + +
    + +
    + +
    + +
    + +
    + +
    + +
    +
    + +
    + +
    + +
    +
    + +
    + +
    + +
    +
    + +
    +
    +
    + + +
    + ) +} + +StopPoint.PropTypes = { + onToggleMap: PropTypes.func.isRequired, + onToggleEdit: PropTypes.func.isRequired, + onDeleteClick: PropTypes.func.isRequired, + onMoveUpClick: PropTypes.func.isRequired, + onMoveDownClick: PropTypes.func.isRequired, + onChange: PropTypes.func.isRequired, + onSelectChange: PropTypes.func.isRequired, + first: PropTypes.bool, + last: PropTypes.bool, + index: PropTypes.number, + value: PropTypes.object +} + +StopPoint.contextTypes = { + I18n: PropTypes.object +} \ No newline at end of file diff --git a/app/javascript/routes/components/StopPointList.js b/app/javascript/routes/components/StopPointList.js new file mode 100644 index 000000000..68af16f57 --- /dev/null +++ b/app/javascript/routes/components/StopPointList.js @@ -0,0 +1,69 @@ +import React, { PropTypes } from 'react' +import StopPoint from './StopPoint' + +export default function StopPointList({ stopPoints, onDeleteClick, onMoveUpClick, onMoveDownClick, onChange, onSelectChange, onToggleMap, onToggleEdit, onSelectMarker, onUnselectMarker, onUpdateViaOlMap }, {I18n}) { + return ( +
    +
    +
    +
    +
    + +
    +
    +
    +
    + +
    +
    +
    +
    + +
    +
    +
    +
    + +
    +
    +
    +
    +
    + {stopPoints.map((stopPoint, index) => + onDeleteClick(index)} + onMoveUpClick={() => { + onMoveUpClick(index) + }} + onMoveDownClick={() => onMoveDownClick(index)} + onChange={ onChange } + onSelectChange={ (e) => onSelectChange(e, index) } + onToggleMap={() => onToggleMap(index)} + onToggleEdit={() => onToggleEdit(index)} + onSelectMarker={onSelectMarker} + onUnselectMarker={onUnselectMarker} + onUpdateViaOlMap={onUpdateViaOlMap} + first={ index === 0 } + last={ index === (stopPoints.length - 1) } + index={ index } + value={ stopPoint } + /> + )} +
    + ) +} + +StopPointList.PropTypes = { + stopPoints: PropTypes.array.isRequired, + onDeleteClick: PropTypes.func.isRequired, + onMoveUpClick: PropTypes.func.isRequired, + onMoveDownClick: PropTypes.func.isRequired, + onSelectChange: PropTypes.func.isRequired, + onSelectMarker: PropTypes.func.isRequired, + onUnselectMarker : PropTypes.func.isRequired +} + +StopPointList.contextTypes = { + I18n: PropTypes.object +} \ No newline at end of file diff --git a/app/javascript/routes/containers/AddStopPoint.js b/app/javascript/routes/containers/AddStopPoint.js new file mode 100644 index 000000000..fd9227ff3 --- /dev/null +++ b/app/javascript/routes/containers/AddStopPoint.js @@ -0,0 +1,20 @@ +import React from 'react' +import { connect } from 'react-redux' +import actions from '../actions' + +let AddStopPoint = ({ dispatch }) => { + return ( +
    +
    { + e.preventDefault() + dispatch(actions.closeMaps()) + dispatch(actions.addStop()) + }}> + +
    +
    + ) +} +export default AddStopPoint = connect()(AddStopPoint) diff --git a/app/javascript/routes/containers/VisibleStopPoints.js b/app/javascript/routes/containers/VisibleStopPoints.js new file mode 100644 index 000000000..67d77af50 --- /dev/null +++ b/app/javascript/routes/containers/VisibleStopPoints.js @@ -0,0 +1,58 @@ +import actions from '../actions' +import { connect } from 'react-redux' +import StopPointList from '../components/StopPointList' + +const mapStateToProps = (state) => { + return { + stopPoints: state.stopPoints + } +} + +const mapDispatchToProps = (dispatch) => { + return { + onDeleteClick: (index) =>{ + dispatch(actions.deleteStop(index)) + dispatch(actions.closeMaps()) + }, + onMoveUpClick: (index) =>{ + dispatch(actions.moveStopUp(index)) + dispatch(actions.closeMaps()) + }, + onMoveDownClick: (index) =>{ + dispatch(actions.moveStopDown(index)) + dispatch(actions.closeMaps()) + }, + onChange: (index, text) =>{ + dispatch(actions.updateInputValue(index, text)) + dispatch(actions.closeMaps()) + dispatch(actions.toggleEdit(index)) + }, + onSelectChange: (e, index) =>{ + dispatch(actions.updateSelectValue(e, index)) + dispatch(actions.closeMaps()) + }, + onToggleMap: (index) =>{ + dispatch(actions.toggleMap(index)) + }, + onToggleEdit: (index) =>{ + dispatch(actions.toggleEdit(index)) + }, + onSelectMarker: (index, data) =>{ + dispatch(actions.selectMarker(index, data)) + }, + onUnselectMarker: (index) =>{ + dispatch(actions.unselectMarker(index)) + }, + onUpdateViaOlMap: (index, data) =>{ + dispatch(actions.updateInputValue(index, data)) + dispatch(actions.toggleMap(index)) + } + } +} + +const VisibleStopPoints = connect( + mapStateToProps, + mapDispatchToProps +)(StopPointList) + +export default VisibleStopPoints diff --git a/app/javascript/routes/form_helper.js b/app/javascript/routes/form_helper.js new file mode 100644 index 000000000..8a3277234 --- /dev/null +++ b/app/javascript/routes/form_helper.js @@ -0,0 +1,55 @@ +const formHelper = { + addInput: (name, value, index) => { + let form = document.querySelector('form') + let input = document.createElement('input') + let formatedName = `route[stop_points_attributes][${index.toString()}][${name}]` + input.setAttribute('type', 'hidden') + input.setAttribute('name', formatedName) + input.setAttribute('value', value) + form.appendChild(input) + }, + addError: (ids) => { + ids.forEach((id) => { + if (!$(id).parents('.form-group').hasClass('has-error')) { + $(id).parents('.form-group').addClass('has-error') + $(id).parent().append(`${'doit être rempli(e)'}`) + } + }) + }, + cleanInputs: (ids) => { + ids.forEach((id) =>{ + $(id).parents('.form-group').removeClass('has-error') + $(id).siblings('span').remove() + }) + }, + handleForm: (...ids) => { + let filledInputs = [] + let blankInputs = [] + ids.forEach(id => { + $(id).val() == "" ? blankInputs.push(id) : filledInputs.push(id) + }) + + if (filledInputs.length > 0) formHelper.cleanInputs(filledInputs) + if (blankInputs.length > 0) formHelper.addError(blankInputs) + }, + handleStopPoints: (event, state) => { + if (state.stopPoints.length >= 2) { + state.stopPoints.map((stopPoint, i) => { + formHelper.addInput('id', stopPoint.stoppoint_id ? stopPoint.stoppoint_id : '', i) + formHelper.addInput('stop_area_id', stopPoint.stoparea_id, i) + formHelper.addInput('position', i, i) + formHelper.addInput('for_boarding', stopPoint.for_boarding, i) + formHelper.addInput('for_alighting', stopPoint.for_alighting, i) + }) + if ($('.alert.alert-danger').length > 0) $('.alert.alert-danger').remove() + } else { + event.preventDefault() + let msg = "L'itinéraire doit comporter au moins deux arrêts" + if ($('.alert.alert-danger').length == 0) { + $('#stop_points').find('.subform').after(`
    " ${msg} "
    `) + } + } + } +} + +export default formHelper \ No newline at end of file diff --git a/app/javascript/routes/index.js b/app/javascript/routes/index.js new file mode 100644 index 000000000..febae7d54 --- /dev/null +++ b/app/javascript/routes/index.js @@ -0,0 +1,80 @@ +import React from 'react' +import { render } from 'react-dom' +import { Provider } from 'react-redux' +import { createStore } from 'redux' +import reducers from './reducers' +import App from './components/App' +import { handleForm, handleStopPoints } from './form_helper' +import clone from '../helpers/clone' +let datas = clone(window, "itinerary_stop", true) +datas = JSON.parse(decodeURIComponent(datas)) + +// logger, DO NOT REMOVE +// var applyMiddleware = require('redux').applyMiddleware +// var createLogger = require('redux-logger') +// var thunkMiddleware = require('redux-thunk').default +// var promise = require('redux-promise') + +const getInitialState = () => { + let state = [] + + datas.map(function(v, i) { + let fancyText = v.name.replace("'", "\'") + if(v.zip_code && v.city_name) + fancyText += ", " + v.zip_code + " " + v.city_name.replace("'", "\'") + + state.push({ + stoppoint_id: v.stoppoint_id, + stoparea_id: v.stoparea_id, + user_objectid: v.user_objectid, + short_name: v.short_name ? v.short_name.replace("'", "\'") : '', + area_type: v.area_type, + index: i, + edit: false, + city_name: v.city_name ? v.city_name.replace("'", "\'") : '', + zip_code: v.zip_code, + name: v.name ? v.name.replace("'", "\'") : '', + registration_number: v.registration_number, + text: fancyText, + for_boarding: v.for_boarding || "normal", + for_alighting: v.for_alighting || "normal", + longitude: v.longitude || 0, + latitude: v.latitude || 0, + comment: v.comment ? v.comment.replace("'", "\'") : '', + olMap: { + isOpened: false, + json: {} + } + }) + }) + + return state +} + +var initialState = {stopPoints: getInitialState()} +// const loggerMiddleware = createLogger() +let store = createStore( + reducers, + initialState + // applyMiddleware(thunkMiddleware, promise, loggerMiddleware) +) + +render( + + + , + document.getElementById('stop_points') +) + +document.querySelector('input[name=commit]').addEventListener('click', (event)=>{ + let state = store.getState() + + let name = $("#route_name").val() + let publicName = $("#route_published_name").val() + if (name == "" || publicName == "") { + event.preventDefault() + handleForm("#route_name", "#route_published_name") + } + + handleStopPoints(event, state) +}) diff --git a/app/javascript/routes/reducers/index.js b/app/javascript/routes/reducers/index.js new file mode 100644 index 000000000..eb01ea9f7 --- /dev/null +++ b/app/javascript/routes/reducers/index.js @@ -0,0 +1,8 @@ +import { combineReducers } from 'redux' +import stopPoints from './stopPoints' + +const stopPointsApp = combineReducers({ + stopPoints +}) + +export default stopPointsApp diff --git a/app/javascript/routes/reducers/stopPoints.js b/app/javascript/routes/reducers/stopPoints.js new file mode 100644 index 000000000..25679e747 --- /dev/null +++ b/app/javascript/routes/reducers/stopPoints.js @@ -0,0 +1,144 @@ +import _ from 'lodash' +import { addInput } from '../form_helper' + +const stopPoint = (state = {}, action, length) => { + switch (action.type) { + case 'ADD_STOP': + return { + text: '', + index: length, + edit: true, + for_boarding: 'normal', + for_alighting: 'normal', + olMap: { + isOpened: false, + json: {} + } + } + default: + return state + } +} + +const updateFormForDeletion = (stop) =>{ + if (stop.stoppoint_id !== undefined){ + let now = Date.now() + addInput('id', stop.stoppoint_id, now) + addInput('_destroy', 'true', now) + } +} + +const stopPoints = (state = [], action) => { + switch (action.type) { + case 'ADD_STOP': + return [ + ...state, + stopPoint(undefined, action, state.length) + ] + case 'MOVE_STOP_UP': + return [ + ...state.slice(0, action.index - 1), + _.assign({}, state[action.index], { stoppoint_id: state[action.index - 1].stoppoint_id }), + _.assign({}, state[action.index - 1], { stoppoint_id: state[action.index].stoppoint_id }), + ...state.slice(action.index + 1) + ] + case 'MOVE_STOP_DOWN': + return [ + ...state.slice(0, action.index), + _.assign({}, state[action.index + 1], { stoppoint_id: state[action.index].stoppoint_id }), + _.assign({}, state[action.index], { stoppoint_id: state[action.index + 1].stoppoint_id }), + ...state.slice(action.index + 2) + ] + case 'DELETE_STOP': + updateFormForDeletion(state[action.index]) + return [ + ...state.slice(0, action.index), + ...state.slice(action.index + 1).map((stopPoint)=>{ + stopPoint.index-- + return stopPoint + }) + ] + case 'UPDATE_INPUT_VALUE': + return state.map( (t, i) => { + if (i === action.index) { + return _.assign( + {}, + t, + { + stoppoint_id: t.stoppoint_id, + text: action.text.text, + stoparea_id: action.text.stoparea_id, + user_objectid: action.text.user_objectid, + latitude: action.text.latitude, + longitude: action.text.longitude, + name: action.text.name, + short_name: action.text.short_name, + area_type: action.text.area_type, + city_name: action.text.city_name, + comment: action.text.comment, + registration_number: action.text.registration_number + } + ) + } else { + return t + } + }) + case 'UPDATE_SELECT_VALUE': + return state.map( (t, i) => { + if (i === action.index) { + let stopState = _.assign({}, t) + stopState[action.select_id] = action.select_value + return stopState + } else { + return t + } + }) + case 'TOGGLE_EDIT': + return state.map((t, i) => { + if (i === action.index){ + return _.assign({}, t, {edit: !t.edit}) + } else { + return t + } + }) + case 'TOGGLE_MAP': + return state.map( (t, i) => { + if (i === action.index){ + let val = !t.olMap.isOpened + let jsonData = val ? _.assign({}, t, {olMap: undefined}) : {} + let stateMap = _.assign({}, t.olMap, {isOpened: val, json: jsonData}) + return _.assign({}, t, {olMap: stateMap}) + }else { + let emptyMap = _.assign({}, t.olMap, {isOpened: false, json : {}}) + return _.assign({}, t, {olMap: emptyMap}) + } + }) + case 'SELECT_MARKER': + return state.map((t, i) => { + if (i === action.index){ + let stateMap = _.assign({}, t.olMap, {json: action.data}) + return _.assign({}, t, {olMap: stateMap}) + } else { + return t + } + }) + case 'UNSELECT_MARKER': + return state.map((t, i) => { + if (i === action.index){ + let stateMap = _.assign({}, t.olMap, {json: {}}) + return _.assign({}, t, {olMap: stateMap}) + } else { + return t + } + }) + case 'CLOSE_MAP': + return state.map( (t, i) => { + let emptyMap = _.assign({}, t.olMap, {isOpened: false, json: {}}) + return _.assign({}, t, {olMap: emptyMap}) + }) + default: + return state + } +} + +export default stopPoints \ No newline at end of file diff --git a/app/javascript/routes/show.js b/app/javascript/routes/show.js new file mode 100644 index 000000000..e88469900 --- /dev/null +++ b/app/javascript/routes/show.js @@ -0,0 +1,102 @@ +const clone = require('../helpers/clone') +let route = clone(window, "route", true) +route = JSON.parse(decodeURIComponent(route)) + +const geoColPts = [] +const geoColLns= [] +const geoColEdges = [ + new ol.Feature({ + geometry: new ol.geom.Point(ol.proj.fromLonLat([parseFloat(route[0].longitude), parseFloat(route[0].latitude)])) + }), + new ol.Feature({ + geometry: new ol.geom.Point(ol.proj.fromLonLat([parseFloat(route[route.length - 1].longitude), parseFloat(route[route.length - 1].latitude)])) + }) +] +route.forEach(function(stop, i){ + if (i < route.length - 1){ + geoColLns.push(new ol.Feature({ + geometry: new ol.geom.LineString([ + ol.proj.fromLonLat([parseFloat(route[i].longitude), parseFloat(route[i].latitude)]), + ol.proj.fromLonLat([parseFloat(route[i+1].longitude), parseFloat(route[i+1].latitude)]) + ]) + })) + } + geoColPts.push(new ol.Feature({ + geometry: new ol.geom.Point(ol.proj.fromLonLat([parseFloat(stop.longitude), parseFloat(stop.latitude)])) + }) + ) +}) +var edgeStyles = new ol.style.Style({ + image: new ol.style.Circle(({ + radius: 5, + stroke: new ol.style.Stroke({ + color: '#007fbb', + width: 2 + }), + fill: new ol.style.Fill({ + color: '#007fbb', + width: 2 + }) + })) +}) +var defaultStyles = new ol.style.Style({ + image: new ol.style.Circle(({ + radius: 4, + stroke: new ol.style.Stroke({ + color: '#007fbb', + width: 2 + }), + fill: new ol.style.Fill({ + color: '#ffffff', + width: 2 + }) + })) +}) +var lineStyle = new ol.style.Style({ + stroke: new ol.style.Stroke({ + color: '#007fbb', + width: 3 + }) +}) + +var vectorPtsLayer = new ol.layer.Vector({ + source: new ol.source.Vector({ + features: geoColPts + }), + style: defaultStyles, + zIndex: 2 +}) +var vectorEdgesLayer = new ol.layer.Vector({ + source: new ol.source.Vector({ + features: geoColEdges + }), + style: edgeStyles, + zIndex: 3 +}) +var vectorLnsLayer = new ol.layer.Vector({ + source: new ol.source.Vector({ + features: geoColLns + }), + style: [lineStyle], + zIndex: 1 +}) + +var map = new ol.Map({ + target: 'route_map', + layers: [ + new ol.layer.Tile({ + source: new ol.source.OSM() + }), + vectorPtsLayer, + vectorEdgesLayer, + vectorLnsLayer + ], + controls: [ new ol.control.ScaleLine(), new ol.control.Zoom(), new ol.control.ZoomSlider() ], + interactions: ol.interaction.defaults({ + zoom: true + }), + view: new ol.View({ + center: ol.proj.fromLonLat([parseFloat(route[0].longitude), parseFloat(route[0].latitude)]), + zoom: 13 + }) +}); diff --git a/app/javascript/time_tables/actions/index.js b/app/javascript/time_tables/actions/index.js new file mode 100644 index 000000000..5a02e8523 --- /dev/null +++ b/app/javascript/time_tables/actions/index.js @@ -0,0 +1,324 @@ +import _ from 'lodash' +import clone from '../../helpers/clone' +const I18n = clone(window, "I18n") + +const actions = { + weekDays: (index) => { + return _.range(1, 8).map(n => I18n.time_tables.edit.metas.days[n]) + }, + strToArrayDayTypes: (str) =>{ + return actions.weekDays().map(day => str.indexOf(day) !== -1) + }, + arrayToStrDayTypes: (dayTypes) => { + let newDayTypes = dayTypes.reduce((arr, dayActive, i) => { + if (dayActive) arr.push(actions.weekDays()[i]) + return arr + }, []) + + return newDayTypes.join(',') + }, + fetchingApi: () =>({ + type: 'FETCH_API' + }), + receiveErrors : (json) => ({ + type: "RECEIVE_ERRORS", + json + }), + unavailableServer: () => ({ + type: 'UNAVAILABLE_SERVER' + }), + receiveMonth: (json) => ({ + type: 'RECEIVE_MONTH', + json + }), + receiveTimeTables: (json) => ({ + type: 'RECEIVE_TIME_TABLES', + json + }), + goToPreviousPage : (dispatch, pagination) => ({ + type: 'GO_TO_PREVIOUS_PAGE', + dispatch, + pagination, + nextPage : false + }), + goToNextPage : (dispatch, pagination) => ({ + type: 'GO_TO_NEXT_PAGE', + dispatch, + pagination, + nextPage : true + }), + changePage : (dispatch, val) => ({ + type: 'CHANGE_PAGE', + dispatch, + page: val + }), + updateDayTypes: (dayTypes) => ({ + type: 'UPDATE_DAY_TYPES', + dayTypes + }), + updateCurrentMonthFromDaytypes: (dayTypes) => ({ + type: 'UPDATE_CURRENT_MONTH_FROM_DAYTYPES', + dayTypes + }), + updateComment: (comment) => ({ + type: 'UPDATE_COMMENT', + comment + }), + updateColor: (color) => ({ + type: 'UPDATE_COLOR', + color + }), + select2Tags: (selectedTag) => ({ + type: 'UPDATE_SELECT_TAG', + selectedItem: { + id: selectedTag.id, + name: selectedTag.name + } + }), + unselect2Tags: (selectedTag) => ({ + type: 'UPDATE_UNSELECT_TAG', + selectedItem: { + id: selectedTag.id, + name: selectedTag.name + } + }), + deletePeriod: (index, dayTypes) => ({ + type: 'DELETE_PERIOD', + index, + dayTypes + }), + openAddPeriodForm: () => ({ + type: 'OPEN_ADD_PERIOD_FORM' + }), + openEditPeriodForm: (period, index) => ({ + type: 'OPEN_EDIT_PERIOD_FORM', + period, + index + }), + closePeriodForm: () => ({ + type: 'CLOSE_PERIOD_FORM' + }), + resetModalErrors: () => ({ + type: 'RESET_MODAL_ERRORS' + }), + updatePeriodForm: (val, group, selectType) => ({ + type: 'UPDATE_PERIOD_FORM', + val, + group, + selectType + }), + validatePeriodForm: (modalProps, timeTablePeriods, metas, timetableInDates, error) => ({ + type: 'VALIDATE_PERIOD_FORM', + modalProps, + timeTablePeriods, + metas, + timetableInDates, + error + }), + addIncludedDate: (index, dayTypes, date) => ({ + type: 'ADD_INCLUDED_DATE', + index, + dayTypes, + date + }), + removeIncludedDate: (index, dayTypes, date) => ({ + type: 'REMOVE_INCLUDED_DATE', + index, + dayTypes, + date + }), + addExcludedDate: (index, dayTypes, date) => ({ + type: 'ADD_EXCLUDED_DATE', + index, + dayTypes, + date + }), + removeExcludedDate: (index, dayTypes, date) => ({ + type: 'REMOVE_EXCLUDED_DATE', + index, + dayTypes, + date + }), + openConfirmModal : (callback) => ({ + type : 'OPEN_CONFIRM_MODAL', + callback + }), + showErrorModal: (error) => ({ + type: 'OPEN_ERROR_MODAL', + error + }), + closeModal : () => ({ + type : 'CLOSE_MODAL' + }), + monthName(strDate) { + let monthList = _.range(1,13).map(n => I18n.calendars.months[n]) + let date = new Date(strDate) + return monthList[date.getMonth()] + }, + getHumanDate(strDate, mLimit) { + let origin = strDate.split('-') + let D = origin[2] + let M = actions.monthName(strDate).toLowerCase() + let Y = origin[0] + + if(mLimit && M.length > mLimit) { + M = M.substr(0, mLimit) + '.' + } + + return (D + ' ' + M + ' ' + Y) + }, + getLocaleDate(strDate) { + let date = new Date(strDate) + return date.toLocaleDateString() + }, + updateSynthesis: ({current_month, time_table_dates: dates, time_table_periods: periods}) => { + let newPeriods = _.reject(periods, 'deleted') + let improvedCM = current_month.map((d, i) => { + let isInPeriod = actions.isInPeriod(newPeriods, d.date) + let isIncluded = _.some(dates, {'date': d.date, 'in_out': true}) + + return _.assign({}, current_month[i], { + in_periods: isInPeriod, + include_date: isIncluded, + excluded_date: !isInPeriod ? false : current_month[i].excluded_date + }) + }) + return improvedCM + }, + isInPeriod: (periods, date) => { + date = new Date(date) + + for (let period of periods) { + let begin = new Date(period.period_start) + let end = new Date(period.period_end) + if (date >= begin && date <= end) return true + } + + return false + }, + checkConfirmModal: (event, callback, stateChanged, dispatch, metas, timetable) => { + if(stateChanged){ + const error = actions.errorModalKey(timetable.time_table_periods, metas.day_types) + if(error){ + return actions.showErrorModal(error) + }else{ + return actions.openConfirmModal(callback) + } + }else{ + dispatch(actions.fetchingApi()) + return callback + } + }, + formatDate: (props) => { + return props.year + '-' + props.month + '-' + props.day + }, + checkErrorsInPeriods: (start, end, index, periods) => { + let error = '' + start = new Date(start) + end = new Date(end) + + for (let i = 0; i < periods.length; i++) { + let period = periods[i] + if (index !== i && !period.deleted) { + if (new Date(period.period_start) <= end && new Date(period.period_end) >= start) { + error = I18n.time_tables.edit.error_submit.periods_overlaps + break + } + } + } + return error + }, + checkErrorsInDates: (start, end, in_days) => { + let error = '' + start = new Date(start) + end = new Date(end) + + for (let day of in_days) { + if (start <= new Date(day.date) && end >= new Date(day.date)) { + error = I18n.time_tables.edit.error_submit.dates_overlaps + break + } + } + return error + }, + fetchTimeTables: (dispatch, nextPage) => { + let urlJSON = window.location.pathname.split('/', 5).join('/') + if(nextPage) { + urlJSON += "/month.json?date=" + nextPage + }else{ + urlJSON += ".json" + } + let hasError = false + fetch(urlJSON, { + credentials: 'same-origin', + }).then(response => { + if(response.status == 500) { + hasError = true + } + return response.json() + }).then((json) => { + if(hasError == true) { + dispatch(actions.unavailableServer()) + } else { + if(nextPage){ + dispatch(actions.receiveMonth(json)) + }else{ + dispatch(actions.receiveTimeTables(json)) + } + } + }) + }, + submitTimetable: (dispatch, timetable, metas, next) => { + dispatch(actions.fetchingApi()) + let strDayTypes = actions.arrayToStrDayTypes(metas.day_types) + metas.day_types= strDayTypes + let sentState = _.assign({}, timetable, metas) + let urlJSON = window.location.pathname.split('/', 5).join('/') + let hasError = false + fetch(urlJSON + '.json', { + credentials: 'same-origin', + method: 'PATCH', + contentType: 'application/json; charset=utf-8', + Accept: 'application/json', + body: JSON.stringify(sentState), + headers: { + 'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content') + } + }).then(response => { + if(!response.ok) { + hasError = true + } + return response.json() + }).then((json) => { + if(hasError == true) { + dispatch(actions.receiveErrors(json)) + } else { + if(next) { + dispatch(next) + } else { + dispatch(actions.receiveTimeTables(json)) + } + } + }) + }, + errorModalKey: (periods, dayTypes) => { + const withoutPeriodsWithDaysTypes = _.reject(periods, 'deleted').length == 0 && _.some(dayTypes) && "withoutPeriodsWithDaysTypes" + const withPeriodsWithoutDayTypes = _.reject(periods, 'deleted').length > 0 && _.every(dayTypes, dt => dt == false) && "withPeriodsWithoutDayTypes" + + return (withoutPeriodsWithDaysTypes || withPeriodsWithoutDayTypes) && (withoutPeriodsWithDaysTypes ? "withoutPeriodsWithDaysTypes" : "withPeriodsWithoutDayTypes") + + }, + errorModalMessage: (errorKey) => { + switch (errorKey) { + case "withoutPeriodsWithDaysTypes": + return I18n.time_tables.edit.error_modal.withoutPeriodsWithDaysTypes + case "withPeriodsWithoutDayTypes": + return I18n.time_tables.edit.error_modal.withPeriodsWithoutDayTypes + default: + return errorKey + + } + } +} + +export default actions \ No newline at end of file diff --git a/app/javascript/time_tables/components/ConfirmModal.js b/app/javascript/time_tables/components/ConfirmModal.js new file mode 100644 index 000000000..d89170ee7 --- /dev/null +++ b/app/javascript/time_tables/components/ConfirmModal.js @@ -0,0 +1,50 @@ +import React, { PropTypes } from 'react' + +export default function ConfirmModal({dispatch, modal, onModalAccept, onModalCancel, timetable, metas}, {I18n}) { + return ( +
    +
    +
    +
    +
    +

    {I18n.time_tables.edit.confirm_modal.title}

    +
    +
    +
    +

    {I18n.time_tables.edit.confirm_modal.message}

    +
    +
    +
    + + +
    +
    +
    +
    +
    + ) +} + +ConfirmModal.propTypes = { + modal: PropTypes.object.isRequired, + onModalAccept: PropTypes.func.isRequired, + onModalCancel: PropTypes.func.isRequired +} + +ConfirmModal.contextTypes = { + I18n: PropTypes.object +} \ No newline at end of file diff --git a/app/javascript/time_tables/components/ErrorModal.js b/app/javascript/time_tables/components/ErrorModal.js new file mode 100644 index 000000000..e810f49ab --- /dev/null +++ b/app/javascript/time_tables/components/ErrorModal.js @@ -0,0 +1,42 @@ +import React, { PropTypes } from 'react' +import actions from '../actions' + +export default function ErrorModal({dispatch, modal, onModalClose}, {I18n}) { + return ( +
    +
    +
    +
    +
    +

    {I18n.time_tables.edit.error_modal.title}

    +
    +
    +
    +

    {actions.errorModalMessage(modal.modalProps.error)}

    +
    +
    +
    + +
    +
    +
    +
    +
    + ) +} + +ErrorModal.propTypes = { + modal: PropTypes.object.isRequired, + onModalClose: PropTypes.func.isRequired +} + +ErrorModal.contextTypes = { + I18n: PropTypes.object +} \ No newline at end of file diff --git a/app/javascript/time_tables/components/ExceptionsInDay.js b/app/javascript/time_tables/components/ExceptionsInDay.js new file mode 100644 index 000000000..3335ee89d --- /dev/null +++ b/app/javascript/time_tables/components/ExceptionsInDay.js @@ -0,0 +1,71 @@ +import React, { PropTypes, Component } from 'react' +import actions from '../actions' + +export default class ExceptionsInDay extends Component { + constructor(props) { + super(props) + } + + handleClick() { + const {index, day, metas: {day_types} } = this.props + if (day.in_periods && day_types[day.wday]) { + day.excluded_date ? this.props.onRemoveExcludedDate(index, day_types, day.date) : this.props.onAddExcludedDate(index, day_types, day.date) + } else { + day.include_date ? this.props.onRemoveIncludedDate(index, day_types, day.date) : this.props.onAddIncludedDate(index, day_types, day.date) + } + } + + render() { + {/* display add or remove link, only if true in daytypes */} + {/* display add or remove link, according to context (presence in period, or not) */} + if(this.props.value.current_month[this.props.index].in_periods == true && this.props.blueDaytype == true) { + return ( +
    + +
    + ) + } else { + return ( +
    + +
    + ) + // } else if(this.props.value.current_month[this.props.index].in_periods == true && this.props.blueDaytype == false){ + // return ( + //
    + // ) + // } else{ + // return false + // } + } + } +} + +ExceptionsInDay.propTypes = { + value: PropTypes.object.isRequired, + metas: PropTypes.object.isRequired, + blueDaytype: PropTypes.bool.isRequired, + onExcludeDateFromPeriod: PropTypes.func.isRequired, + onIncludeDateInPeriod: PropTypes.func.isRequired, + index: PropTypes.number.isRequired +} diff --git a/app/javascript/time_tables/components/Metas.js b/app/javascript/time_tables/components/Metas.js new file mode 100644 index 000000000..7098d2b82 --- /dev/null +++ b/app/javascript/time_tables/components/Metas.js @@ -0,0 +1,139 @@ +import React, { PropTypes } from 'react' +import actions from '../actions' +import TagsSelect2 from './TagsSelect2' + +export default function Metas({metas, onUpdateDayTypes, onUpdateComment, onUpdateColor, onSelect2Tags, onUnselect2Tags}, {I18n}) { + let colorList = ["", "#9B9B9B", "#FFA070", "#C67300", "#7F551B", "#41CCE3", "#09B09C", "#3655D7", "#6321A0", "#E796C6", "#DD2DAA"] + return ( +
    +
    +
    + {/* comment (name) */} +
    + +
    + (onUpdateComment(e.currentTarget.value))} + /> +
    +
    + + {/* color */} +
    + +
    +
    + + +
    + {colorList.map((c, i) => + {onUpdateColor(c)}} + > + + + )} +
    +
    +
    +
    + + {/* tags */} +
    + +
    + onSelect2Tags(e)} + onUnselect2Tags={(e) => onUnselect2Tags(e)} + /> +
    +
    + + {/* calendar */} +
    + +
    + {metas.calendar ? metas.calendar.name : I18n.time_tables.edit.metas.no_calendar} +
    +
    + + {/* day_types */} +
    + +
    +
    + {metas.day_types.map((day, i) => +
    +
    + +
    +
    + )} +
    +
    +
    +
    +
    +
    + ) +} + +Metas.propTypes = { + metas: PropTypes.object.isRequired, + onUpdateDayTypes: PropTypes.func.isRequired, + onUpdateColor: PropTypes.func.isRequired, + onUpdateColor: PropTypes.func.isRequired, + onSelect2Tags: PropTypes.func.isRequired, + onUnselect2Tags: PropTypes.func.isRequired +} + +Metas.contextTypes = { + I18n: PropTypes.object +} diff --git a/app/javascript/time_tables/components/Navigate.js b/app/javascript/time_tables/components/Navigate.js new file mode 100644 index 000000000..6ae80bce0 --- /dev/null +++ b/app/javascript/time_tables/components/Navigate.js @@ -0,0 +1,88 @@ +import React, { PropTypes, Component } from 'react' +import _ from 'lodash' +import actions from '../actions' + +export default function Navigate({ dispatch, metas, timetable, pagination, status, filters}) { + if(status.isFetching == true) { + return false + } + if(status.fetchSuccess == true) { + let pageIndex = pagination.periode_range.indexOf(pagination.currentPage) + let firstPage = pageIndex == 0 + let lastPage = pageIndex == pagination.periode_range.length - 1 + return ( +
    +
    {e.preventDefault()}}> + {/* date selector */} +
    +
    +
    + {pagination.currentPage ? (actions.monthName(pagination.currentPage) + ' ' + new Date(pagination.currentPage).getFullYear()) : ''} + +
    +
      + {_.map(pagination.periode_range, (month, i) => ( +
    • + +
    • + ))} +
    +
    +
    + + {/* prev/next */} +
    +
    + + +
    +
    +
    +
    + ) + } else { + return false + } +} + +Navigate.propTypes = { + status: PropTypes.object.isRequired, + pagination: PropTypes.object.isRequired, + dispatch: PropTypes.func.isRequired +} \ No newline at end of file diff --git a/app/javascript/time_tables/components/PeriodForm.js b/app/javascript/time_tables/components/PeriodForm.js new file mode 100644 index 000000000..893a1fa6a --- /dev/null +++ b/app/javascript/time_tables/components/PeriodForm.js @@ -0,0 +1,148 @@ +import React, { PropTypes } from 'react' +import _ from 'lodash' +let monthsArray = ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'] + +const formatNumber = (val) => { + return ("0" + val).slice(-2) +} + +const makeDaysOptions = (daySelected) => { + let arr = [] + for(let i = 1; i < 32; i++) { + arr.push() + } + return arr +} + +const makeMonthsOptions = (monthSelected) => { + let arr = [] + for(let i = 1; i < 13; i++) { + arr.push() + } + return arr +} + +const makeYearsOptions = (yearSelected) => { + let arr = [] + let startYear = new Date().getFullYear() - 3 + for(let i = startYear; i <= startYear + 6; i++) { + arr.push() + } + return arr +} + +export default function PeriodForm({modal, timetable, metas, onOpenAddPeriodForm, onClosePeriodForm, onUpdatePeriodForm, onValidatePeriodForm}, {I18n}) { + return ( +
    +
    +
    +
    + {modal.modalProps.active && +
    +
    +
    +
    +
    + +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    +
    +
    +
    + + + +
    +
    +
    +
    +
    +
    + + + +
    +
    +
    +
    +
    + +
    + + {modal.modalProps.error} + + + +
    +
    + } + {!modal.modalProps.active && +
    + +
    + } +
    +
    +
    +
    + ) +} + +PeriodForm.propTypes = { + modal: PropTypes.object.isRequired, + metas: PropTypes.object.isRequired, + onOpenAddPeriodForm: PropTypes.func.isRequired, + onClosePeriodForm: PropTypes.func.isRequired, + onUpdatePeriodForm: PropTypes.func.isRequired, + onValidatePeriodForm: PropTypes.func.isRequired, + timetable: PropTypes.object.isRequired +} + +PeriodForm.contextTypes = { + I18n: PropTypes.object +} \ No newline at end of file diff --git a/app/javascript/time_tables/components/PeriodManager.js b/app/javascript/time_tables/components/PeriodManager.js new file mode 100644 index 000000000..9922ce2c4 --- /dev/null +++ b/app/javascript/time_tables/components/PeriodManager.js @@ -0,0 +1,85 @@ +import React, { PropTypes, Component } from 'react' +import actions from '../actions' + +export default class PeriodManager extends Component { + constructor(props, context) { + super(props, context) + } + + toEndPeriod(curr, end) { + let diff + + let startCurrM = curr.split('-')[1] + let endPeriodM = end.split('-')[1] + + let lastDayInM = new Date(curr.split('-')[2], startCurrM + 1, 0) + lastDayInM = lastDayInM.toJSON().substr(0, 10).split('-')[2] + + if(startCurrM === endPeriodM) { + diff = (end.split('-')[2] - curr.split('-')[2]) + } else { + diff = (lastDayInM - curr.split('-')[2]) + } + + return diff + } + + render() { + return ( +
    +

    + {actions.getLocaleDate(this.props.value.period_start) + ' > ' + actions.getLocaleDate(this.props.value.period_end)} +

    + +
    +
    + +
    +
      +
    • + +
    • +
    • + +
    • +
    +
    +
    + ) + } +} + +PeriodManager.propTypes = { + value: PropTypes.object.isRequired, + currentDate: PropTypes.object.isRequired, + onDeletePeriod: PropTypes.func.isRequired, + onOpenEditPeriodForm: PropTypes.func.isRequired +} + +PeriodManager.contextTypes = { + I18n: PropTypes.object +} \ No newline at end of file diff --git a/app/javascript/time_tables/components/PeriodsInDay.js b/app/javascript/time_tables/components/PeriodsInDay.js new file mode 100644 index 000000000..888537579 --- /dev/null +++ b/app/javascript/time_tables/components/PeriodsInDay.js @@ -0,0 +1,75 @@ +import React, { PropTypes, Component } from 'react' +import PeriodManager from './PeriodManager' + +export default class PeriodsInDay extends Component { + constructor(props) { + super(props) + } + + isIn(date) { + let currentDate = date.getTime() + let cls = 'td' + let periods = this.props.value + + periods.map((p, i) => { + if (!p.deleted){ + let begin = new Date(p.period_start).getTime() + let end = new Date(p.period_end).getTime() + + if(currentDate >= begin && currentDate <= end) { + if(currentDate == begin) { + cls += ' in_periods start_period' + } else if(currentDate == end) { + cls += ' in_periods end_period' + } else { + cls += ' in_periods' + } + } + } + }) + return cls + } + + render() { + return ( +
    + {this.props.value.map((p, i) => { + if(!p.deleted){ + let begin = new Date(p.period_start).getTime() + let end = new Date(p.period_end).getTime() + let d = this.props.currentDate.getTime() + + if(d >= begin && d <= end) { + if(d == begin || (this.props.currentDate.getUTCDate() == 1)) { + return ( + + ) + } else { + return false + } + } + }else{ + return false + } + })} +
    + ) + } +} + +PeriodsInDay.propTypes = { + value: PropTypes.array.isRequired, + currentDate: PropTypes.object.isRequired, + index: PropTypes.number.isRequired, + onDeletePeriod: PropTypes.func.isRequired +} diff --git a/app/javascript/time_tables/components/SaveTimetable.js b/app/javascript/time_tables/components/SaveTimetable.js new file mode 100644 index 000000000..0dffc7936 --- /dev/null +++ b/app/javascript/time_tables/components/SaveTimetable.js @@ -0,0 +1,42 @@ +import React, { PropTypes, Component } from 'react' +import _ from 'lodash' +import actions from '../actions' + +export default class SaveTimetable extends Component{ + constructor(props){ + super(props) + } + + render() { + const error = actions.errorModalKey(this.props.timetable.time_table_periods, this.props.metas.day_types) + + return ( +
    +
    +
    {e.preventDefault()}}> + +
    +
    +
    + ) + } +} + +SaveTimetable.propTypes = { + timetable: PropTypes.object.isRequired, + status: PropTypes.object.isRequired, + metas: PropTypes.object.isRequired +} \ No newline at end of file diff --git a/app/javascript/time_tables/components/TagsSelect2.js b/app/javascript/time_tables/components/TagsSelect2.js new file mode 100644 index 000000000..24f473f42 --- /dev/null +++ b/app/javascript/time_tables/components/TagsSelect2.js @@ -0,0 +1,77 @@ +import React, { PropTypes, Component } from 'react' +import _ from 'lodash' +import Select2 from 'react-select2-wrapper' + +// get JSON full path +let origin = window.location.origin +let path = window.location.pathname.split('/', 4).join('/') + +export default class TagsSelect2 extends Component { + constructor(props, context) { + super(props, context) + } + + mapKeys(array){ + return array.map((item) => + _.mapKeys(item, (v, k) => + ((k == 'name') ? 'text' : k) + ) + ) + } + + render() { + return ( + this.props.onSelect2Tags(e)} + onUnselect={(e) => setTimeout( () => this.props.onUnselect2Tags(e, 150))} + multiple={true} + ref='tags_id' + options={{ + tags:true, + createTag: function(params) { + return {name: params.term, text: params.term, id: params.term} + }, + allowClear: true, + theme: 'bootstrap', + width: '100%', + placeholder: this.context.I18n.time_tables.edit.select2.tag.placeholder, + ajax: { + url: origin + path + '/tags.json', + dataType: 'json', + delay: '500', + data: function(params) { + return { + tag: params.term, + }; + }, + processResults: function(data, params) { + let items = _.filter(data, ({name}) => name.includes(params.term) ) + return { + results: items.map( + item => _.assign( + {}, + item, + {text: item.name} + ) + ) + }; + }, + cache: true + }, + minimumInputLength: 1, + templateResult: formatRepo + }} + /> + ) + } +} + +const formatRepo = (props) => { + if(props.name) return props.name +} + +TagsSelect2.contextTypes = { + I18n: PropTypes.object +} \ No newline at end of file diff --git a/app/javascript/time_tables/components/TimeTableDay.js b/app/javascript/time_tables/components/TimeTableDay.js new file mode 100644 index 000000000..165c7b848 --- /dev/null +++ b/app/javascript/time_tables/components/TimeTableDay.js @@ -0,0 +1,31 @@ +import React, { PropTypes, Component } from 'react' + +export default class TimeTableDay extends Component { + constructor(props) { + super(props) + } + + render() { + return ( + + + {((this.props.value.day).charAt(0) == 'm') ? (this.props.value.day).substr(0, 2) : (this.props.value.day).charAt(0)} + + + {this.props.value.mday} + + + ) + } +} + +TimeTableDay.propTypes = { + value: PropTypes.object.isRequired, + index: PropTypes.number.isRequired, + dayTypeActive: PropTypes.bool.isRequired +} diff --git a/app/javascript/time_tables/components/Timetable.js b/app/javascript/time_tables/components/Timetable.js new file mode 100644 index 000000000..df6e6016b --- /dev/null +++ b/app/javascript/time_tables/components/Timetable.js @@ -0,0 +1,115 @@ +import React, { PropTypes, Component } from 'react' +import actions from '../actions' +import TimeTableDay from './TimeTableDay' +import PeriodsInDay from './PeriodsInDay' +import ExceptionsInDay from './ExceptionsInDay' + + +export default class Timetable extends Component { + constructor(props, context){ + super(props, context) + } + + currentDate(mFirstday, day) { + let currentMonth = mFirstday.split('-') + let twodigitsDay = day < 10 ? ('0' + day) : day + let currentDate = new Date(currentMonth[0] + '-' + currentMonth[1] + '-' + twodigitsDay) + + return currentDate + } + + render() { + if(this.props.status.isFetching == true) { + return ( +
    +
    +
    + ) + } else { + return ( +
    +
    +
    +
    {this.context.I18n.time_tables.synthesis}
    +
    +
    {this.context.I18n.time_tables.edit.day_types}
    +
    {this.context.I18n.time_tables.edit.periods}
    +
    {this.context.I18n.time_tables.edit.exceptions}
    +
    +
    +
    +
    +
    +
    + {actions.monthName(this.props.timetable.current_periode_range)} +
    + +
    + {this.props.timetable.current_month.map((d, i) => + + )} +
    +
    + + {this.props.timetable.current_month.map((d, i) => +
    + {/* day_types */} +
    + + {/* periods */} + + + {/* exceptions */} + +
    + )} +
    +
    +
    +
    + ) + } + } +} + +Timetable.propTypes = { + metas: PropTypes.object.isRequired, + timetable: PropTypes.object.isRequired, + status: PropTypes.object.isRequired, + onDeletePeriod: PropTypes.func.isRequired, + onExcludeDateFromPeriod: PropTypes.func.isRequired, + onIncludeDateInPeriod: PropTypes.func.isRequired +} + +Timetable.contextTypes = { + I18n: PropTypes.object +} diff --git a/app/javascript/time_tables/containers/App.js b/app/javascript/time_tables/containers/App.js new file mode 100644 index 000000000..235dccb50 --- /dev/null +++ b/app/javascript/time_tables/containers/App.js @@ -0,0 +1,55 @@ +import React, { PropTypes, Component } from 'react' +import { connect } from'react-redux' +import actions from '../actions' +import Metas from './Metas' +import Timetable from './Timetable' +import Navigate from './Navigate' +import PeriodForm from './PeriodForm' +import SaveTimetable from './SaveTimetable' +import ConfirmModal from './ConfirmModal' +import ErrorModal from './ErrorModal' +import clone from '../../helpers/clone' +const I18n = clone(window, "I18n", true) + +class App extends Component { + componentDidMount(){ + this.props.onLoadFirstPage() + } + + getChildContext() { + return { I18n } + } + + render(){ + return( +
    +
    + + + + + + + +
    +
    + ) + } +} + +const mapDispatchToProps = (dispatch) => { + return { + onLoadFirstPage: () =>{ + dispatch(actions.fetchingApi()) + actions.fetchTimeTables(dispatch) + } + } +} + +App.childContextTypes = { + I18n: PropTypes.object +} + +const timeTableApp = connect(null, mapDispatchToProps)(App) + +export default timeTableApp diff --git a/app/javascript/time_tables/containers/ConfirmModal.js b/app/javascript/time_tables/containers/ConfirmModal.js new file mode 100644 index 000000000..f3742b038 --- /dev/null +++ b/app/javascript/time_tables/containers/ConfirmModal.js @@ -0,0 +1,31 @@ +import { connect } from 'react-redux' +import actions from '../actions' +import ConfirmModal from '../components/ConfirmModal' + +const mapStateToProps = (state) => { + return { + modal: state.modal, + timetable: state.timetable, + metas: state.metas + } +} + +const mapDispatchToProps = (dispatch) => { + return { + onModalAccept: (next, timetable, metas) =>{ + dispatch(actions.fetchingApi()) + actions.submitTimetable(dispatch, timetable, metas, next) + }, + onModalCancel: (next) =>{ + dispatch(actions.fetchingApi()) + dispatch(next) + }, + onModalClose: () =>{ + dispatch(actions.closeModal()) + } + } +} + +const ConfirmModalContainer = connect(mapStateToProps, mapDispatchToProps)(ConfirmModal) + +export default ConfirmModalContainer diff --git a/app/javascript/time_tables/containers/ErrorModal.js b/app/javascript/time_tables/containers/ErrorModal.js new file mode 100644 index 000000000..37099073b --- /dev/null +++ b/app/javascript/time_tables/containers/ErrorModal.js @@ -0,0 +1,22 @@ +import { connect } from 'react-redux' +import actions from '../actions' +import ErrorModal from '../components/ErrorModal' + +const mapStateToProps = (state) => { + return { + modal: state.modal + } +} + +const mapDispatchToProps = (dispatch) => { + return { + onModalClose: () =>{ + dispatch(actions.closeModal()) + dispatch(actions.resetModalErrors()) + } + } +} + +const ErrorModalContainer = connect(mapStateToProps, mapDispatchToProps)(ErrorModal) + +export default ErrorModalContainer diff --git a/app/javascript/time_tables/containers/Metas.js b/app/javascript/time_tables/containers/Metas.js new file mode 100644 index 000000000..ebccf556e --- /dev/null +++ b/app/javascript/time_tables/containers/Metas.js @@ -0,0 +1,38 @@ +import { connect } from 'react-redux' +import actions from '../actions' +import MetasComponent from '../components/Metas' + +const mapStateToProps = (state) => { + return { + metas: state.metas + } +} + +const mapDispatchToProps = (dispatch) => { + return { + onUpdateDayTypes: (index, dayTypes) => { + let newDayTypes = dayTypes.slice(0) + newDayTypes[index] = !newDayTypes[index] + dispatch(actions.updateDayTypes(newDayTypes)) + dispatch(actions.updateCurrentMonthFromDaytypes(newDayTypes)) + }, + onUpdateComment: (comment) => { + dispatch(actions.updateComment(comment)) + }, + onUpdateColor: (color) => { + dispatch(actions.updateColor(color)) + }, + onSelect2Tags: (e) => { + e.preventDefault() + dispatch(actions.select2Tags(e.params.data)) + }, + onUnselect2Tags: (e) => { + e.preventDefault() + dispatch(actions.unselect2Tags(e.params.data)) + } + } +} + +const Metas = connect(mapStateToProps, mapDispatchToProps)(MetasComponent) + +export default Metas diff --git a/app/javascript/time_tables/containers/Navigate.js b/app/javascript/time_tables/containers/Navigate.js new file mode 100644 index 000000000..8d163659c --- /dev/null +++ b/app/javascript/time_tables/containers/Navigate.js @@ -0,0 +1,18 @@ +import React from 'react' +import { connect } from 'react-redux' +import actions from '../actions' +import NavigateComponent from '../components/Navigate' + +const mapStateToProps = (state) => { + return { + metas: state.metas, + timetable: state.timetable, + status: state.status, + pagination: state.pagination + } +} + + +const Navigate = connect(mapStateToProps)(NavigateComponent) + +export default Navigate diff --git a/app/javascript/time_tables/containers/PeriodForm.js b/app/javascript/time_tables/containers/PeriodForm.js new file mode 100644 index 000000000..49e79f348 --- /dev/null +++ b/app/javascript/time_tables/containers/PeriodForm.js @@ -0,0 +1,46 @@ +import { connect } from 'react-redux' +import _ from 'lodash' +import actions from '../actions' +import PeriodFormComponent from '../components/PeriodForm' + + + +const mapStateToProps = (state) => { + return { + modal: state.modal, + timetable: state.timetable, + metas: state.metas, + } +} + +const mapDispatchToProps = (dispatch) => { + return { + onOpenAddPeriodForm: () => { + dispatch(actions.openAddPeriodForm()) + }, + onClosePeriodForm: () => { + dispatch(actions.closePeriodForm()) + }, + onUpdatePeriodForm: (e, group, selectType, modalProps) => { + dispatch(actions.updatePeriodForm(e.currentTarget.value, group, selectType)) + let mProps = _.assign({}, modalProps) + mProps[group][selectType] = e.currentTarget.value + let val = window.correctDay([parseInt(mProps[group]['day']), parseInt(mProps[group]['month']), parseInt(mProps[group]['year'])]) + val = (val < 10) ? '0' + String(val) : String(val) + dispatch(actions.updatePeriodForm(val, group, 'day')) + }, + onValidatePeriodForm: (modalProps, timeTablePeriods, metas, timetableInDates) => { + let period_start = actions.formatDate(modalProps.begin) + let period_end = actions.formatDate(modalProps.end) + let error = '' + if (new Date(period_end) <= new Date(period_start)) error = 'La date de départ doit être antérieure à la date de fin' + if (error == '') error = actions.checkErrorsInPeriods(period_start, period_end, modalProps.index, timeTablePeriods) + if (error == '') error = actions.checkErrorsInDates(period_start, period_end, timetableInDates) + dispatch(actions.validatePeriodForm(modalProps, timeTablePeriods, metas, timetableInDates, error)) + } + } +} + +const PeriodForm = connect(mapStateToProps, mapDispatchToProps)(PeriodFormComponent) + +export default PeriodForm diff --git a/app/javascript/time_tables/containers/SaveTimetable.js b/app/javascript/time_tables/containers/SaveTimetable.js new file mode 100644 index 000000000..7574dc5cc --- /dev/null +++ b/app/javascript/time_tables/containers/SaveTimetable.js @@ -0,0 +1,25 @@ +import { connect } from 'react-redux' +import actions from '../actions' +import SaveTimetableComponent from '../components/SaveTimetable' + +const mapStateToProps = (state) => { + return { + timetable: state.timetable, + metas: state.metas, + status: state.status + } +} + +const mapDispatchToProps = (dispatch) => { + return { + onShowErrorModal: (errorKey) => { + dispatch(actions.showErrorModal(errorKey)) + }, + getDispatch: () => { + return dispatch + } + } +} +const SaveTimetable = connect(mapStateToProps, mapDispatchToProps)(SaveTimetableComponent) + +export default SaveTimetable diff --git a/app/javascript/time_tables/containers/Timetable.js b/app/javascript/time_tables/containers/Timetable.js new file mode 100644 index 000000000..e78e8840a --- /dev/null +++ b/app/javascript/time_tables/containers/Timetable.js @@ -0,0 +1,44 @@ +import { connect } from 'react-redux' +import actions from '../actions' +import TimetableComponent from '../components/Timetable' + +const mapStateToProps = (state) => { + return { + metas: state.metas, + timetable: state.timetable, + status: state.status + } +} + +const mapDispatchToProps = (dispatch) => { + return { + onDeletePeriod: (index, dayTypes) =>{ + dispatch(actions.deletePeriod(index, dayTypes)) + }, + onAddIncludedDate: (index, dayTypes, date) => { + dispatch(actions.addIncludedDate(index, dayTypes, date)) + }, + onRemoveIncludedDate: (index, dayTypes, date) => { + dispatch(actions.removeIncludedDate(index, dayTypes, date)) + }, + onAddExcludedDate: (index, dayTypes, date) => { + dispatch(actions.addExcludedDate(index, dayTypes, date)) + }, + onRemoveExcludedDate: (index, dayTypes, date) => { + dispatch(actions.removeExcludedDate(index, dayTypes, date)) + }, + onExcludeDateFromPeriod: (index, dayTypes, date) => { + dispatch(actions.excludeDateFromPeriod(index, dayTypes, date)) + }, + onIncludeDateInPeriod: (index, dayTypes, date) => { + dispatch(actions.includeDateInPeriod(index, dayTypes, date)) + }, + onOpenEditPeriodForm: (period, index) => { + dispatch(actions.openEditPeriodForm(period, index)) + } + } +} + +const Timetable = connect(mapStateToProps, mapDispatchToProps)(TimetableComponent) + +export default Timetable diff --git a/app/javascript/time_tables/reducers/index.js b/app/javascript/time_tables/reducers/index.js new file mode 100644 index 000000000..aed9035b5 --- /dev/null +++ b/app/javascript/time_tables/reducers/index.js @@ -0,0 +1,16 @@ +import { combineReducers } from 'redux' +import status from './status' +import pagination from './pagination' +import modal from './modal' +import timetable from './timetable' +import metas from './metas' + +const timeTablesApp = combineReducers({ + timetable, + metas, + status, + pagination, + modal +}) + +export default timeTablesApp diff --git a/app/javascript/time_tables/reducers/metas.js b/app/javascript/time_tables/reducers/metas.js new file mode 100644 index 000000000..548798012 --- /dev/null +++ b/app/javascript/time_tables/reducers/metas.js @@ -0,0 +1,40 @@ +import _ from 'lodash' +import actions from '../actions' + +export default function metas(state = {}, action) { + switch (action.type) { + case 'RECEIVE_TIME_TABLES': + return _.assign({}, state, { + comment: action.json.comment, + day_types: actions.strToArrayDayTypes(action.json.day_types), + tags: action.json.tags, + initial_tags: action.json.tags, + color: action.json.color, + calendar: action.json.calendar ? action.json.calendar : null + }) + case 'RECEIVE_MONTH': + let dt = (typeof state.day_types === 'string') ? actions.strToArrayDayTypes(state.day_types) : state.day_types + return _.assign({}, state, {day_types: dt}) + case 'ADD_INCLUDED_DATE': + case 'REMOVE_INCLUDED_DATE': + case 'ADD_EXCLUDED_DATE': + case 'REMOVE_EXCLUDED_DATE': + case 'DELETE_PERIOD': + case 'VALIDATE_PERIOD_FORM': + return _.assign({}, state, {calendar: null}) + case 'UPDATE_DAY_TYPES': + return _.assign({}, state, {day_types: action.dayTypes, calendar : null}) + case 'UPDATE_COMMENT': + return _.assign({}, state, {comment: action.comment}) + case 'UPDATE_COLOR': + return _.assign({}, state, {color: action.color}) + case 'UPDATE_SELECT_TAG': + let tags = [...state.tags] + tags.push(action.selectedItem) + return _.assign({}, state, {tags: tags}) + case 'UPDATE_UNSELECT_TAG': + return _.assign({}, state, {tags: _.filter(state.tags, (t) => (t.id != action.selectedItem.id))}) + default: + return state + } +} \ No newline at end of file diff --git a/app/javascript/time_tables/reducers/modal.js b/app/javascript/time_tables/reducers/modal.js new file mode 100644 index 000000000..a530b2717 --- /dev/null +++ b/app/javascript/time_tables/reducers/modal.js @@ -0,0 +1,64 @@ +import _ from 'lodash' +import actions from '../actions' + +let newModalProps = {} +let emptyDate = { + day: '01', + month: '01', + year: String(new Date().getFullYear()) +} +let period_start = '', period_end = '' + +export default function modal(state = {}, action) { + switch (action.type) { + case 'OPEN_CONFIRM_MODAL': + $('#ConfirmModal').modal('show') + return _.assign({}, state, { + type: 'confirm', + confirmModal: { + callback: action.callback, + } + }) + case 'OPEN_ERROR_MODAL': + $('#ErrorModal').modal('show') + newModalProps = _.assign({}, state.modalProps, {error: action.error}) + return _.assign({}, state, {type: 'error'}, {modalProps: newModalProps}) + case 'RESET_MODAL_ERRORS': + newModalProps = _.assign({}, state.modalProps, {error: ''}) + return _.assign({}, state, {type: ''}, {modalProps: newModalProps}) + case 'CLOSE_PERIOD_FORM': + newModalProps = _.assign({}, state.modalProps, {active: false, error: ""}) + return _.assign({}, state, {modalProps: newModalProps}) + case 'OPEN_EDIT_PERIOD_FORM': + period_start = action.period.period_start.split('-') + period_end = action.period.period_end.split('-') + newModalProps = JSON.parse(JSON.stringify(state.modalProps)) + + newModalProps.begin.year = period_start[0] + newModalProps.begin.month = period_start[1] + newModalProps.begin.day = period_start[2] + + newModalProps.end.year = period_end[0] + newModalProps.end.month = period_end[1] + newModalProps.end.day = period_end[2] + + newModalProps.active = true + newModalProps.index = action.index + newModalProps.error = '' + return _.assign({}, state, {modalProps: newModalProps}) + case 'OPEN_ADD_PERIOD_FORM': + newModalProps = _.assign({}, state.modalProps, {active: true, begin: emptyDate, end: emptyDate, index: false, error: ''}) + return _.assign({}, state, {modalProps: newModalProps}) + case 'UPDATE_PERIOD_FORM': + newModalProps = JSON.parse(JSON.stringify(state.modalProps)) + newModalProps[action.group][action.selectType] = action.val + return _.assign({}, state, {modalProps: newModalProps}) + case 'VALIDATE_PERIOD_FORM': + newModalProps = JSON.parse(JSON.stringify(state.modalProps)) + newModalProps.error = action.error + newModalProps.active = (newModalProps.error == '') ? false : true + return _.assign({}, state, {modalProps: newModalProps}) + default: + return state + } +} \ No newline at end of file diff --git a/app/javascript/time_tables/reducers/pagination.js b/app/javascript/time_tables/reducers/pagination.js new file mode 100644 index 000000000..e9ca9e1ec --- /dev/null +++ b/app/javascript/time_tables/reducers/pagination.js @@ -0,0 +1,44 @@ +import _ from 'lodash' + +export default function pagination(state = {}, action) { + switch (action.type) { + case 'RECEIVE_TIME_TABLES': + return _.assign({}, state, { + currentPage: action.json.current_periode_range, + periode_range: action.json.periode_range, + stateChanged: false + }) + case 'RECEIVE_MONTH': + case 'RECEIVE_ERRORS': + return _.assign({}, state, {stateChanged: false}) + case 'GO_TO_PREVIOUS_PAGE': + case 'GO_TO_NEXT_PAGE': + let nextPage = action.nextPage ? 1 : -1 + let newPage = action.pagination.periode_range[action.pagination.periode_range.indexOf(action.pagination.currentPage) + nextPage] + toggleOnConfirmModal() + return _.assign({}, state, {currentPage : newPage, stateChanged: false}) + case 'CHANGE_PAGE': + toggleOnConfirmModal() + return _.assign({}, state, {currentPage : action.page, stateChanged: false}) + case 'ADD_INCLUDED_DATE': + case 'REMOVE_INCLUDED_DATE': + case 'ADD_EXCLUDED_DATE': + case 'REMOVE_EXCLUDED_DATE': + case 'DELETE_PERIOD': + case 'VALIDATE_PERIOD_FORM': + case 'UPDATE_COMMENT': + case 'UPDATE_COLOR': + case 'UPDATE_DAY_TYPES': + case 'UPDATE_CURRENT_MONTH_FROM_DAYTYPES': + toggleOnConfirmModal('modal') + return _.assign({}, state, {stateChanged: true}) + default: + return state + } +} + +const toggleOnConfirmModal = (arg = '') =>{ + $('.confirm').each(function(){ + $(this).data('toggle','') + }) +} \ No newline at end of file diff --git a/app/javascript/time_tables/reducers/status.js b/app/javascript/time_tables/reducers/status.js new file mode 100644 index 000000000..8d93bc2e2 --- /dev/null +++ b/app/javascript/time_tables/reducers/status.js @@ -0,0 +1,15 @@ +import _ from 'lodash' + +export default function status(state = {}, action) { + switch (action.type) { + case 'UNAVAILABLE_SERVER': + return _.assign({}, state, {fetchSuccess: false}) + case 'FETCH_API': + return _.assign({}, state, {isFetching: true}) + case 'RECEIVE_TIME_TABLES': + case 'RECEIVE_MONTH': + return _.assign({}, state, {fetchSuccess: true, isFetching: false}) + default: + return state + } +} \ No newline at end of file diff --git a/app/javascript/time_tables/reducers/timetable.js b/app/javascript/time_tables/reducers/timetable.js new file mode 100644 index 000000000..274153a69 --- /dev/null +++ b/app/javascript/time_tables/reducers/timetable.js @@ -0,0 +1,117 @@ +import _ from 'lodash' +import actions from '../actions' +let newState, newPeriods, newDates, newCM + +export default function timetable(state = {}, action) { + switch (action.type) { + case 'RECEIVE_TIME_TABLES': + let fetchedState = _.assign({}, state, { + current_month: action.json.current_month, + current_periode_range: action.json.current_periode_range, + periode_range: action.json.periode_range, + time_table_periods: action.json.time_table_periods, + time_table_dates: _.sortBy(action.json.time_table_dates, ['date']) + }) + return _.assign({}, fetchedState, {current_month: actions.updateSynthesis(fetchedState)}) + case 'RECEIVE_MONTH': + newState = _.assign({}, state, { + current_month: action.json.days + }) + return _.assign({}, newState, {current_month: actions.updateSynthesis(newState)}) + case 'GO_TO_PREVIOUS_PAGE': + case 'GO_TO_NEXT_PAGE': + let nextPage = action.nextPage ? 1 : -1 + let newPage = action.pagination.periode_range[action.pagination.periode_range.indexOf(action.pagination.currentPage) + nextPage] + $('#ConfirmModal').modal('hide') + actions.fetchTimeTables(action.dispatch, newPage) + return _.assign({}, state, {current_periode_range: newPage}) + case 'CHANGE_PAGE': + $('#ConfirmModal').modal('hide') + actions.fetchTimeTables(action.dispatch, action.page) + return _.assign({}, state, {current_periode_range: action.page}) + case 'DELETE_PERIOD': + newPeriods = state.time_table_periods.map((period, i) =>{ + if(i == action.index){ + period.deleted = true + } + return period + }) + let deletedPeriod = Array.of(state.time_table_periods[action.index]) + newDates = _.reject(state.time_table_dates, d => actions.isInPeriod(deletedPeriod, d.date) && !d.in_out) + newState = _.assign({}, state, {time_table_periods : newPeriods, time_table_dates: newDates}) + return _.assign({}, newState, { current_month: actions.updateSynthesis(newState)}) + case 'ADD_INCLUDED_DATE': + newDates = state.time_table_dates.concat({date: action.date, in_out: true}) + newCM = state.current_month.map((d, i) => { + if (i == action.index) d.include_date = true + return d + }) + return _.assign({}, state, {current_month: newCM, time_table_dates: newDates}) + case 'REMOVE_INCLUDED_DATE': + newDates = _.reject(state.time_table_dates, ['date', action.date]) + newCM = state.current_month.map((d, i) => { + if (i == action.index) d.include_date = false + return d + }) + return _.assign({}, state, {current_month: newCM, time_table_dates: newDates}) + case 'ADD_EXCLUDED_DATE': + newDates = state.time_table_dates.concat({date: action.date, in_out: false}) + newCM = state.current_month.map((d, i) => { + if (i == action.index) d.excluded_date = true + return d + }) + return _.assign({}, state, {current_month: newCM, time_table_dates: newDates}) + case 'REMOVE_EXCLUDED_DATE': + newDates = _.reject(state.time_table_dates, ['date', action.date]) + newCM = state.current_month.map((d, i) => { + if (i == action.index) d.excluded_date = false + return d + }) + return _.assign({}, state, {current_month: newCM, time_table_dates: newDates}) + case 'UPDATE_DAY_TYPES': + // We get the week days of the activated day types to reject the out_dates that that are out of newDayTypes + let weekDays = _.reduce(action.dayTypes, (array, dt, i) => { + if (dt) array.push(i) + return array + }, []) + + newDates = _.reject(state.time_table_dates, (d) => { + let weekDay = new Date(d.date).getDay() + + if (d.in_out) { + return actions.isInPeriod(state.time_table_periods, d.date) && weekDays.includes(weekDay) + } else { + return !weekDays.includes(weekDay) + } + }) + return _.assign({}, state, {time_table_dates: newDates}) + case 'UPDATE_CURRENT_MONTH_FROM_DAYTYPES': + return _.assign({}, state, {current_month: actions.updateSynthesis(state)}) + case 'VALIDATE_PERIOD_FORM': + if (action.error != '') return state + + let period_start = actions.formatDate(action.modalProps.begin) + let period_end = actions.formatDate(action.modalProps.end) + + let newPeriods = JSON.parse(JSON.stringify(action.timeTablePeriods)) + + if (action.modalProps.index !== false){ + let updatedPeriod = newPeriods[action.modalProps.index] + updatedPeriod.period_start = period_start + updatedPeriod.period_end = period_end + newDates = _.reject(state.time_table_dates, d => actions.isInPeriod(newPeriods, d.date) && !d.in_out) + }else{ + let newPeriod = { + period_start: period_start, + period_end: period_end + } + newPeriods.push(newPeriod) + } + + newDates = newDates || state.time_table_dates + newState =_.assign({}, state, {time_table_periods: newPeriods, time_table_dates: newDates}) + return _.assign({}, newState, {current_month: actions.updateSynthesis(newState)}) + default: + return state + } +} \ No newline at end of file -- cgit v1.2.3 From c4362d355d6f3b2f407e8c51bb6c0bee43f39df3 Mon Sep 17 00:00:00 2001 From: cedricnjanga Date: Fri, 6 Oct 2017 11:50:05 +0200 Subject: Add vehicle journey app --- app/javascript/packs/vehicle_journeys/index.js | 102 +++++ app/javascript/vehicle_journeys/actions/index.js | 463 +++++++++++++++++++++ app/javascript/vehicle_journeys/batch.js | 26 ++ app/javascript/vehicle_journeys/components/App.js | 38 ++ .../vehicle_journeys/components/ConfirmModal.js | 40 ++ .../vehicle_journeys/components/Filters.js | 168 ++++++++ .../vehicle_journeys/components/Navigate.js | 55 +++ .../components/SaveVehicleJourneys.js | 42 ++ .../vehicle_journeys/components/ToggleArrivals.js | 27 ++ .../vehicle_journeys/components/Tools.js | 39 ++ .../vehicle_journeys/components/VehicleJourney.js | 145 +++++++ .../vehicle_journeys/components/VehicleJourneys.js | 156 +++++++ .../components/tools/CreateModal.js | 131 ++++++ .../components/tools/DeleteVehicleJourneys.js | 26 ++ .../components/tools/DuplicateVehicleJourney.js | 196 +++++++++ .../components/tools/EditVehicleJourney.js | 167 ++++++++ .../components/tools/NotesEditVehicleJourney.js | 150 +++++++ .../components/tools/ShiftVehicleJourney.js | 114 +++++ .../tools/TimetablesEditVehicleJourney.js | 131 ++++++ .../components/tools/select2s/CompanySelect2.js | 64 +++ .../components/tools/select2s/MissionSelect2.js | 63 +++ .../components/tools/select2s/TimetableSelect2.js | 68 +++ .../components/tools/select2s/VJSelect2.js | 62 +++ .../components/tools/select2s/fr.js | 9 + .../vehicle_journeys/containers/ConfirmModal.js | 30 ++ .../vehicle_journeys/containers/Filters.js | 48 +++ .../vehicle_journeys/containers/Navigate.js | 17 + .../containers/SaveVehicleJourneys.js | 28 ++ .../vehicle_journeys/containers/ToggleArrivals.js | 21 + .../vehicle_journeys/containers/Tools.js | 23 + .../containers/VehicleJourneysList.js | 32 ++ .../containers/tools/AddVehicleJourney.js | 37 ++ .../containers/tools/DeleteVehicleJourneys.js | 22 + .../containers/tools/DuplicateVehicleJourney.js | 30 ++ .../containers/tools/EditVehicleJourney.js | 36 ++ .../containers/tools/NotesEditVehicleJourney.js | 33 ++ .../containers/tools/ShiftVehicleJourney.js | 30 ++ .../tools/TimetablesEditVehicleJourney.js | 37 ++ .../vehicle_journeys/reducers/editMode.js | 10 + .../vehicle_journeys/reducers/filters.js | 73 ++++ app/javascript/vehicle_journeys/reducers/index.js | 20 + app/javascript/vehicle_journeys/reducers/modal.js | 138 ++++++ .../vehicle_journeys/reducers/pagination.js | 37 ++ app/javascript/vehicle_journeys/reducers/status.js | 17 + .../vehicle_journeys/reducers/stopPointsList.js | 6 + .../vehicle_journeys/reducers/vehicleJourneys.js | 227 ++++++++++ 46 files changed, 3434 insertions(+) create mode 100644 app/javascript/packs/vehicle_journeys/index.js create mode 100644 app/javascript/vehicle_journeys/actions/index.js create mode 100644 app/javascript/vehicle_journeys/batch.js create mode 100644 app/javascript/vehicle_journeys/components/App.js create mode 100644 app/javascript/vehicle_journeys/components/ConfirmModal.js create mode 100644 app/javascript/vehicle_journeys/components/Filters.js create mode 100644 app/javascript/vehicle_journeys/components/Navigate.js create mode 100644 app/javascript/vehicle_journeys/components/SaveVehicleJourneys.js create mode 100644 app/javascript/vehicle_journeys/components/ToggleArrivals.js create mode 100644 app/javascript/vehicle_journeys/components/Tools.js create mode 100644 app/javascript/vehicle_journeys/components/VehicleJourney.js create mode 100644 app/javascript/vehicle_journeys/components/VehicleJourneys.js create mode 100644 app/javascript/vehicle_journeys/components/tools/CreateModal.js create mode 100644 app/javascript/vehicle_journeys/components/tools/DeleteVehicleJourneys.js create mode 100644 app/javascript/vehicle_journeys/components/tools/DuplicateVehicleJourney.js create mode 100644 app/javascript/vehicle_journeys/components/tools/EditVehicleJourney.js create mode 100644 app/javascript/vehicle_journeys/components/tools/NotesEditVehicleJourney.js create mode 100644 app/javascript/vehicle_journeys/components/tools/ShiftVehicleJourney.js create mode 100644 app/javascript/vehicle_journeys/components/tools/TimetablesEditVehicleJourney.js create mode 100644 app/javascript/vehicle_journeys/components/tools/select2s/CompanySelect2.js create mode 100644 app/javascript/vehicle_journeys/components/tools/select2s/MissionSelect2.js create mode 100644 app/javascript/vehicle_journeys/components/tools/select2s/TimetableSelect2.js create mode 100644 app/javascript/vehicle_journeys/components/tools/select2s/VJSelect2.js create mode 100644 app/javascript/vehicle_journeys/components/tools/select2s/fr.js create mode 100644 app/javascript/vehicle_journeys/containers/ConfirmModal.js create mode 100644 app/javascript/vehicle_journeys/containers/Filters.js create mode 100644 app/javascript/vehicle_journeys/containers/Navigate.js create mode 100644 app/javascript/vehicle_journeys/containers/SaveVehicleJourneys.js create mode 100644 app/javascript/vehicle_journeys/containers/ToggleArrivals.js create mode 100644 app/javascript/vehicle_journeys/containers/Tools.js create mode 100644 app/javascript/vehicle_journeys/containers/VehicleJourneysList.js create mode 100644 app/javascript/vehicle_journeys/containers/tools/AddVehicleJourney.js create mode 100644 app/javascript/vehicle_journeys/containers/tools/DeleteVehicleJourneys.js create mode 100644 app/javascript/vehicle_journeys/containers/tools/DuplicateVehicleJourney.js create mode 100644 app/javascript/vehicle_journeys/containers/tools/EditVehicleJourney.js create mode 100644 app/javascript/vehicle_journeys/containers/tools/NotesEditVehicleJourney.js create mode 100644 app/javascript/vehicle_journeys/containers/tools/ShiftVehicleJourney.js create mode 100644 app/javascript/vehicle_journeys/containers/tools/TimetablesEditVehicleJourney.js create mode 100644 app/javascript/vehicle_journeys/reducers/editMode.js create mode 100644 app/javascript/vehicle_journeys/reducers/filters.js create mode 100644 app/javascript/vehicle_journeys/reducers/index.js create mode 100644 app/javascript/vehicle_journeys/reducers/modal.js create mode 100644 app/javascript/vehicle_journeys/reducers/pagination.js create mode 100644 app/javascript/vehicle_journeys/reducers/status.js create mode 100644 app/javascript/vehicle_journeys/reducers/stopPointsList.js create mode 100644 app/javascript/vehicle_journeys/reducers/vehicleJourneys.js (limited to 'app/javascript') diff --git a/app/javascript/packs/vehicle_journeys/index.js b/app/javascript/packs/vehicle_journeys/index.js new file mode 100644 index 000000000..38431af1d --- /dev/null +++ b/app/javascript/packs/vehicle_journeys/index.js @@ -0,0 +1,102 @@ +import React from 'react' +import { render } from 'react-dom' +import { Provider } from 'react-redux' +import { createStore } from 'redux' +import vehicleJourneysApp from '../../vehicle_journeys/reducers' +import App from '../../vehicle_journeys/components/App' +import actions from "../../vehicle_journeys/actions" +import { enableBatching } from '../../vehicle_journeys/batch' + +// logger, DO NOT REMOVE +// var applyMiddleware = require('redux').applyMiddleware +// var createLogger = require('redux-logger') +// var thunkMiddleware = require('redux-thunk').default +// var promise = require('redux-promise') + +var selectedJP = [] + +if (window.journeyPatternId) + selectedJP.push(window.journeyPatternId) + +var initialState = { + editMode: false, + filters: { + selectedJourneyPatterns : selectedJP, + policy: window.perms, + toggleArrivals: false, + queryString: '', + query: { + interval: { + start:{ + hour: '00', + minute: '00' + }, + end:{ + hour: '23', + minute: '59' + } + }, + journeyPattern: { + published_name: '' + }, + vehicleJourney: { + objectid: '' + }, + company: { + name: '' + }, + timetable: { + comment: '' + }, + withoutSchedule: true, + withoutTimeTable: true + } + + }, + status: { + fetchSuccess: true, + isFetching: false + }, + vehicleJourneys: [], + stopPointsList: window.stopPoints, + pagination: { + page : 1, + totalCount: 0, + perPage: window.vehicleJourneysPerPage, + stateChanged: false + }, + modal: { + type: '', + modalProps: {}, + confirmModal: {} + } +} + +if (window.jpOrigin){ + initialState.filters.query.journeyPattern = { + id: window.jpOrigin.id, + name: window.jpOrigin.name, + published_name: window.jpOrigin.published_name, + objectid: window.jpOrigin.objectid + } + let params = { + 'q[journey_pattern_id_eq]': initialState.filters.query.journeyPattern.id, + 'q[objectid_cont]': initialState.filters.query.vehicleJourney.objectid + } + initialState.filters.queryString = actions.encodeParams(params) +} + +// const loggerMiddleware = createLogger() + +let store = createStore( + enableBatching(vehicleJourneysApp), + initialState, + // applyMiddleware(thunkMiddleware, promise, loggerMiddleware) +) + +render( + + + , + document.getElementById('vehicle_journeys_wip') +) \ No newline at end of file diff --git a/app/javascript/vehicle_journeys/actions/index.js b/app/javascript/vehicle_journeys/actions/index.js new file mode 100644 index 000000000..4272c7915 --- /dev/null +++ b/app/javascript/vehicle_journeys/actions/index.js @@ -0,0 +1,463 @@ +import Promise from 'promise-polyfill' + +// To add to window +if (!window.Promise) { + window.Promise = Promise; +} +import { batchActions } from '../batch' + +const actions = { + enterEditMode: () => ({ + type: "ENTER_EDIT_MODE" + }), + exitEditMode: () => ({ + type: "EXIT_EDIT_MODE" + }), + receiveVehicleJourneys : (json) => ({ + type: "RECEIVE_VEHICLE_JOURNEYS", + json + }), + receiveErrors : (json) => ({ + type: "RECEIVE_ERRORS", + json + }), + fetchingApi: () =>({ + type: 'FETCH_API' + }), + unavailableServer : () => ({ + type: 'UNAVAILABLE_SERVER' + }), + goToPreviousPage : (dispatch, pagination, queryString) => ({ + type: 'GO_TO_PREVIOUS_PAGE', + dispatch, + pagination, + nextPage : false, + queryString + }), + goToNextPage : (dispatch, pagination, queryString) => ({ + type: 'GO_TO_NEXT_PAGE', + dispatch, + pagination, + nextPage : true, + queryString + }), + checkConfirmModal : (event, callback, stateChanged, dispatch) => { + if(stateChanged === true){ + return actions.openConfirmModal(callback) + }else{ + dispatch(actions.fetchingApi()) + return callback + } + }, + openCreateModal : () => ({ + type : 'CREATE_VEHICLEJOURNEY_MODAL' + }), + selectJPCreateModal : (selectedJP) => ({ + type : 'SELECT_JP_CREATE_MODAL', + selectedItem: { + id: selectedJP.id, + objectid: selectedJP.object_id, + name: selectedJP.name, + published_name: selectedJP.published_name, + stop_areas: selectedJP.stop_area_short_descriptions + } + }), + openEditModal : (vehicleJourney) => ({ + type : 'EDIT_VEHICLEJOURNEY_MODAL', + vehicleJourney + }), + openNotesEditModal : (vehicleJourney) => ({ + type : 'EDIT_NOTES_VEHICLEJOURNEY_MODAL', + vehicleJourney + }), + toggleFootnoteModal : (footnote, isShown) => ({ + type: 'TOGGLE_FOOTNOTE_MODAL', + footnote, + isShown + }), + openCalendarsEditModal : (vehicleJourneys) => ({ + type : 'EDIT_CALENDARS_VEHICLEJOURNEY_MODAL', + vehicleJourneys + }), + selectTTCalendarsModal: (selectedTT) =>({ + type: 'SELECT_TT_CALENDAR_MODAL', + selectedItem:{ + id: selectedTT.id, + comment: selectedTT.comment, + objectid: selectedTT.objectid + } + }), + addSelectedTimetable: () => ({ + type: 'ADD_SELECTED_TIMETABLE' + }), + deleteCalendarModal : (timetable) => ({ + type : 'DELETE_CALENDAR_MODAL', + timetable + }), + editVehicleJourneyTimetables : (vehicleJourneys, timetables) => ({ + type: 'EDIT_VEHICLEJOURNEYS_TIMETABLES', + vehicleJourneys, + timetables + }), + openShiftModal : () => ({ + type : 'SHIFT_VEHICLEJOURNEY_MODAL' + }), + openDuplicateModal : () => ({ + type : 'DUPLICATE_VEHICLEJOURNEY_MODAL' + }), + selectVehicleJourney : (index) => ({ + type : 'SELECT_VEHICLEJOURNEY', + index + }), + cancelSelection : () => ({ + type: 'CANCEL_SELECTION' + }), + addVehicleJourney : (data, selectedJourneyPattern, stopPointsList, selectedCompany) => ({ + type: 'ADD_VEHICLEJOURNEY', + data, + selectedJourneyPattern, + stopPointsList, + selectedCompany + }), + select2Company: (selectedCompany) => ({ + type: 'SELECT_CP_EDIT_MODAL', + selectedItem: { + id: selectedCompany.id, + name: selectedCompany.name, + objectid: selectedCompany.objectid + } + }), + unselect2Company: () => ({ + type: 'UNSELECT_CP_EDIT_MODAL', + }), + editVehicleJourney : (data, selectedCompany) => ({ + type: 'EDIT_VEHICLEJOURNEY', + data, + selectedCompany + }), + editVehicleJourneyNotes : (footnotes) => ({ + type: 'EDIT_VEHICLEJOURNEY_NOTES', + footnotes + }), + shiftVehicleJourney : (addtionalTime) => ({ + type: 'SHIFT_VEHICLEJOURNEY', + addtionalTime + }), + duplicateVehicleJourney : (addtionalTime, duplicateNumber, departureDelta) => ({ + type: 'DUPLICATE_VEHICLEJOURNEY', + addtionalTime, + duplicateNumber, + departureDelta + }), + deleteVehicleJourneys : () => ({ + type: 'DELETE_VEHICLEJOURNEYS' + }), + openConfirmModal : (callback) => ({ + type : 'OPEN_CONFIRM_MODAL', + callback + }), + closeModal : () => ({ + type : 'CLOSE_MODAL' + }), + resetValidation: (target) => { + $(target).parent().removeClass('has-error').children('.help-block').remove() + }, + validateFields : (fields) => { + const test = [] + + Object.keys(fields).map(function(key) { + test.push(fields[key].validity.valid) + }) + if(test.indexOf(false) >= 0) { + // Form is invalid + test.map(function(item, i) { + if(item == false) { + const k = Object.keys(fields)[i] + $(fields[k]).parent().addClass('has-error').children('.help-block').remove() + $(fields[k]).parent().append("" + fields[k].validationMessage + "") + } + }) + return false + } else { + // Form is valid + return true + } + }, + toggleArrivals : () => ({ + type: 'TOGGLE_ARRIVALS', + }), + updateTime : (val, subIndex, index, timeUnit, isDeparture, isArrivalsToggled) => ({ + type: 'UPDATE_TIME', + val, + subIndex, + index, + timeUnit, + isDeparture, + isArrivalsToggled + }), + resetStateFilters: () => ({ + type: 'RESET_FILTERS' + }), + toggleWithoutSchedule: () => ({ + type: 'TOGGLE_WITHOUT_SCHEDULE' + }), + toggleWithoutTimeTable: () => ({ + type: 'TOGGLE_WITHOUT_TIMETABLE' + }), + updateStartTimeFilter: (val, unit) => ({ + type: 'UPDATE_START_TIME_FILTER', + val, + unit + }), + updateEndTimeFilter: (val, unit) => ({ + type: 'UPDATE_END_TIME_FILTER', + val, + unit + }), + filterSelect2Timetable: (selectedTT) =>({ + type: 'SELECT_TT_FILTER', + selectedItem:{ + id: selectedTT.id, + comment: selectedTT.comment, + objectid: selectedTT.objectid + } + }), + filterSelect2JourneyPattern: (selectedJP) => ({ + type : 'SELECT_JP_FILTER', + selectedItem: { + id: selectedJP.id, + objectid: selectedJP.object_id, + name: selectedJP.name, + published_name: selectedJP.published_name + } + }), + filterSelect2VehicleJourney: (selectedVJ) => ({ + type : 'SELECT_VJ_FILTER', + selectedItem: { + objectid: selectedVJ.objectid + } + }), + createQueryString: () => ({ + type: 'CREATE_QUERY_STRING' + }), + resetPagination: () => ({ + type: 'RESET_PAGINATION' + }), + queryFilterVehicleJourneys: (dispatch) => ({ + type: 'QUERY_FILTER_VEHICLEJOURNEYS', + dispatch + }), + resetFilters: (dispatch) => ( + batchActions([ + actions.resetStateFilters(), + actions.resetPagination(), + actions.queryFilterVehicleJourneys(dispatch) + ]) + ), + filterQuery: (dispatch) => ( + batchActions([ + actions.createQueryString(), + actions.resetPagination(), + actions.queryFilterVehicleJourneys(dispatch) + ]) + ), + updateTotalCount: (diff) => ({ + type: 'UPDATE_TOTAL_COUNT', + diff + }), + receiveTotalCount: (total) => ({ + type: 'RECEIVE_TOTAL_COUNT', + total + }), + humanOID: (oid) => oid.split(':')[2].split("-").pop(), + fetchVehicleJourneys : (dispatch, currentPage, nextPage, queryString) => { + if(currentPage == undefined){ + currentPage = 1 + } + let vehicleJourneys = [] + let page + switch (nextPage) { + case true: + page = currentPage + 1 + break + case false: + if(currentPage > 1){ + page = currentPage - 1 + } + break + default: + page = currentPage + break + } + let str = ".json" + let sep = '?' + if(page > 1){ + str = '.json?page=' + page.toString() + sep = '&' + } + let urlJSON = window.location.pathname + str + if (queryString){ + urlJSON = urlJSON + sep + queryString + } + let hasError = false + fetch(urlJSON, { + credentials: 'same-origin', + }).then(response => { + if(response.status == 500) { + hasError = true + } + return response.json() + }).then((json) => { + if(hasError == true) { + dispatch(actions.unavailableServer()) + } else { + let val + for (val of json.vehicle_journeys){ + var timeTables = [] + let tt + for (tt of val.time_tables){ + timeTables.push({ + objectid: tt.objectid, + comment: tt.comment, + id: tt.id, + color: tt.color + }) + } + let vjasWithDelta = val.vehicle_journey_at_stops.map((vjas, i) => { + actions.fillEmptyFields(vjas) + return actions.getDelta(vjas) + }) + vehicleJourneys.push({ + journey_pattern: val.journey_pattern, + published_journey_name: val.published_journey_name, + objectid: val.objectid, + footnotes: val.footnotes, + time_tables: timeTables, + vehicle_journey_at_stops: vjasWithDelta, + deletable: false, + selected: false, + published_journey_name: val.published_journey_name || 'non renseigné', + published_journey_identifier: val.published_journey_identifier || 'non renseigné', + company: val.company || 'non renseigné', + transport_mode: val.route.line.transport_mode || 'undefined', + transport_submode: val.route.line.transport_submode || 'undefined' + }) + } + window.currentItemsLength = vehicleJourneys.length + dispatch(actions.receiveVehicleJourneys(vehicleJourneys)) + dispatch(actions.receiveTotalCount(json.total)) + } + }) + }, + submitVehicleJourneys : (dispatch, state, next) => { + dispatch(actions.fetchingApi()) + let urlJSON = window.location.pathname + "_collection.json" + let hasError = false + fetch(urlJSON, { + credentials: 'same-origin', + method: 'PATCH', + contentType: 'application/json; charset=utf-8', + Accept: 'application/json', + body: JSON.stringify(state), + headers: { + 'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content') + } + }).then(response => { + if(!response.ok) { + hasError = true + } + return response.json() + }).then((json) => { + if(hasError == true) { + dispatch(actions.receiveErrors(json)) + } else { + if(next) { + dispatch(next) + } else { + if(json.length != window.currentItemsLength){ + dispatch(actions.updateTotalCount(window.currentItemsLength - json.length)) + } + window.currentItemsLength = json.length + dispatch(actions.exitEditMode()) + dispatch(actions.receiveVehicleJourneys(json)) + } + } + }) + }, + // VJAS HELPERS + getSelected: (vj) => { + return vj.filter((obj) =>{ + return obj.selected + }) + }, + simplePad: (d) => { + if(d.toString().length == 1){ + return '0' + d.toString() + }else{ + return d.toString() + } + }, + pad: (d, timeUnit) => { + let val = d.toString() + if(d.toString().length == 1){ + val = (d < 10) ? '0' + d.toString() : d.toString(); + } + if(val.length > 2){ + val = val.substr(1) + } + if(timeUnit == 'minute' && parseInt(val) > 59){ + val = '59' + } + if(timeUnit == 'hour' && parseInt(val) > 23){ + val = '23' + } + return val + }, + encodeParams: (params) => { + let esc = encodeURIComponent + let queryString = Object.keys(params).map((k) => esc(k) + '=' + esc(params[k])).join('&') + return queryString + }, + fillEmptyFields: (vjas) => { + if (vjas.departure_time.hour == null) vjas.departure_time.hour = '00' + if (vjas.departure_time.minute == null) vjas.departure_time.minute = '00' + if (vjas.arrival_time.hour == null) vjas.arrival_time.hour = '00' + if (vjas.arrival_time.minute == null) vjas.arrival_time.minute = '00' + return vjas + }, + getDuplicateDelta: (original, newDeparture) => { + if (original.departure_time.hour != '' && original.departure_time.minute != '' && newDeparture.departure_time.hour != undefined && newDeparture.departure_time.minute != undefined){ + return (newDeparture.departure_time.hour - parseInt(original.departure_time.hour)) * 60 + (newDeparture.departure_time.minute - parseInt(original.departure_time.minute)) + } + return 0 + }, + getDelta: (vjas) => { + let delta = 0 + if (vjas.departure_time.hour != '' && vjas.departure_time.minute != '' && vjas.arrival_time.hour != '' && vjas.departure_time.minute != ''){ + delta = (parseInt(vjas.departure_time.hour) - parseInt(vjas.arrival_time.hour)) * 60 + (parseInt(vjas.departure_time.minute) - parseInt(vjas.arrival_time.minute)) + } + vjas.delta = delta + return vjas + }, + getShiftedSchedule: ({departure_time, arrival_time}, additional_time) => { + // We create dummy dates objects to manipulate time more easily + let departureDT = new Date (Date.UTC(2017, 2, 1, parseInt(departure_time.hour), parseInt(departure_time.minute))) + let arrivalDT = new Date (Date.UTC(2017, 2, 1, parseInt(arrival_time.hour), parseInt(arrival_time.minute))) + + let newDepartureDT = new Date (departureDT.getTime() + additional_time * 60000) + let newArrivalDT = new Date (arrivalDT.getTime() + additional_time * 60000) + + return { + departure_time: { + hour: actions.simplePad(newDepartureDT.getUTCHours()), + minute: actions.simplePad(newDepartureDT.getUTCMinutes()) + }, + arrival_time: { + hour: actions.simplePad(newArrivalDT.getUTCHours()), + minute: actions.simplePad(newArrivalDT.getUTCMinutes()) + } + } + }, +} + +export default actions diff --git a/app/javascript/vehicle_journeys/batch.js b/app/javascript/vehicle_journeys/batch.js new file mode 100644 index 000000000..ea08572aa --- /dev/null +++ b/app/javascript/vehicle_journeys/batch.js @@ -0,0 +1,26 @@ +// 'use strict'; + +// Object.defineProperty(exports, "__esModule", { +// value: true +// }); +// exports.batchActions = batchActions; +// exports.enableBatching = enableBatching; +// var BATCH = exports.BATCH = 'BATCH'; + +export function batchActions(actions) { + return { + type: 'BATCH', + payload: actions + }; +} + +export function enableBatching(reduce) { + return function batchingReducer(state, action) { + switch (action.type) { + case 'BATCH': + return action.payload.reduce(batchingReducer, state); + default: + return reduce(state, action); + } + } +} \ No newline at end of file diff --git a/app/javascript/vehicle_journeys/components/App.js b/app/javascript/vehicle_journeys/components/App.js new file mode 100644 index 000000000..8e5f7aa9d --- /dev/null +++ b/app/javascript/vehicle_journeys/components/App.js @@ -0,0 +1,38 @@ +import React from 'react' +import VehicleJourneysList from '../containers/VehicleJourneysList' +import Navigate from '../containers/Navigate' +import ToggleArrivals from '../containers/ToggleArrivals' +import Filters from '../containers/Filters' +import SaveVehicleJourneys from '../containers/SaveVehicleJourneys' +import ConfirmModal from '../containers/ConfirmModal' +import Tools from '../containers/Tools' + +export default function App() { + return ( +
    + +
    +
    + +
    +
    + +
    +
    + + + + +
    +
    + +
    +
    + + + + + +
    + ) +} \ No newline at end of file diff --git a/app/javascript/vehicle_journeys/components/ConfirmModal.js b/app/javascript/vehicle_journeys/components/ConfirmModal.js new file mode 100644 index 000000000..df3c96c48 --- /dev/null +++ b/app/javascript/vehicle_journeys/components/ConfirmModal.js @@ -0,0 +1,40 @@ +import React, { PropTypes, Component } from 'react' + +export default function ConfirmModal({dispatch, modal, onModalAccept, onModalCancel, vehicleJourneys}) { + return ( +
    +
    +
    +
    +

    Voulez-vous valider vos modifications avant de changer de page?

    +
    +
    + + +
    +
    +
    +
    + ) +} + +ConfirmModal.propTypes = { + vehicleJourneys: PropTypes.array.isRequired, + modal: PropTypes.object.isRequired, + onModalAccept: PropTypes.func.isRequired, + onModalCancel: PropTypes.func.isRequired +} \ No newline at end of file diff --git a/app/javascript/vehicle_journeys/components/Filters.js b/app/javascript/vehicle_journeys/components/Filters.js new file mode 100644 index 000000000..db6707520 --- /dev/null +++ b/app/javascript/vehicle_journeys/components/Filters.js @@ -0,0 +1,168 @@ +import React, { PropTypes } from 'react' +import MissionSelect2 from'./tools/select2s/MissionSelect2' +import VJSelect2 from'./tools/select2s/VJSelect2' +import TimetableSelect2 from'./tools/select2s/TimetableSelect2' + +export default function Filters({filters, pagination, onFilter, onResetFilters, onUpdateStartTimeFilter, onUpdateEndTimeFilter, onToggleWithoutSchedule, onToggleWithoutTimeTable, onSelect2Timetable, onSelect2JourneyPattern, onSelect2VehicleJourney}) { + return ( +
    +
    +
    +
    + {/* ID course */} +
    + +
    + + {/* Missions */} +
    + +
    + + {/* Calendriers */} +
    + +
    +
    + +
    + {/* Plage horaire */} +
    + +
    +
    + +
    +
    + {onUpdateStartTimeFilter(e, 'hour')}} + value={filters.query.interval.start.hour} + /> + : + {onUpdateStartTimeFilter(e, 'minute')}} + value={filters.query.interval.start.minute} + /> +
    +
    +
    +
    + +
    +
    + {onUpdateEndTimeFilter(e, 'hour')}} + value={filters.query.interval.end.hour} + /> + : + {onUpdateEndTimeFilter(e, 'minute')}} + value={filters.query.interval.end.minute} + /> +
    +
    +
    +
    +
    + + {/* Switch avec/sans horaires */} +
    + +
    +
    + +
    +
    +
    +
    + +
    + {/* Switch avec/sans calendrier */} +
    + +
    +
    + +
    +
    +
    +
    + + {/* Actions */} +
    + onResetFilters(e, pagination)}> + Effacer + + onFilter(e, pagination)}> + Filtrer + +
    +
    +
    +
    + ) +} + +Filters.propTypes = { + filters : PropTypes.object.isRequired, + pagination : PropTypes.object.isRequired, + onFilter: PropTypes.func.isRequired, + onResetFilters: PropTypes.func.isRequired, + onUpdateStartTimeFilter: PropTypes.func.isRequired, + onUpdateEndTimeFilter: PropTypes.func.isRequired, + onSelect2Timetable: PropTypes.func.isRequired, + onSelect2JourneyPattern: PropTypes.func.isRequired, + onSelect2VehicleJourney: PropTypes.func.isRequired +} \ No newline at end of file diff --git a/app/javascript/vehicle_journeys/components/Navigate.js b/app/javascript/vehicle_journeys/components/Navigate.js new file mode 100644 index 000000000..7493b705b --- /dev/null +++ b/app/javascript/vehicle_journeys/components/Navigate.js @@ -0,0 +1,55 @@ +import React, { PropTypes, Component } from 'react' +import actions from'../actions' + +export default function Navigate({ dispatch, vehicleJourneys, pagination, status, filters}) { + let firstPage = 1 + let lastPage = Math.ceil(pagination.totalCount / pagination.perPage) + let minVJ = (pagination.page - 1) * pagination.perPage + 1 + if (pagination.totalCount == 0){ + minVJ = 0 + lastPage = 1 + } + let maxVJ = Math.min((pagination.page * pagination.perPage), pagination.totalCount) + if(status.isFetching == true) { + return false + } + if(status.fetchSuccess == true) { + return ( +
    + Liste des horaires {minVJ} à {maxVJ} sur {pagination.totalCount} + +
    {e.preventDefault()}}> + + +
    +
    + ) + } else { + return false + } +} + +Navigate.propTypes = { + vehicleJourneys: PropTypes.array.isRequired, + status: PropTypes.object.isRequired, + pagination: PropTypes.object.isRequired, + dispatch: PropTypes.func.isRequired +} \ No newline at end of file diff --git a/app/javascript/vehicle_journeys/components/SaveVehicleJourneys.js b/app/javascript/vehicle_journeys/components/SaveVehicleJourneys.js new file mode 100644 index 000000000..e8c27f92e --- /dev/null +++ b/app/javascript/vehicle_journeys/components/SaveVehicleJourneys.js @@ -0,0 +1,42 @@ +import React, { PropTypes, Component } from 'react' +import actions from '../actions' + +export default class SaveVehicleJourneys extends Component{ + constructor(props){ + super(props) + } + + render() { + if (this.props.filters.policy['vehicle_journeys.update'] == false) { + return false + }else{ + return ( +
    +
    +
    {e.preventDefault()}}> + +
    +
    +
    + ) + } + } +} + +SaveVehicleJourneys.propTypes = { + vehicleJourneys: PropTypes.array.isRequired, + page: PropTypes.number.isRequired, + status: PropTypes.object.isRequired, + filters: PropTypes.object.isRequired, + onEnterEditMode: PropTypes.func.isRequired, + onSubmitVehicleJourneys: PropTypes.func.isRequired +} \ No newline at end of file diff --git a/app/javascript/vehicle_journeys/components/ToggleArrivals.js b/app/javascript/vehicle_journeys/components/ToggleArrivals.js new file mode 100644 index 000000000..e26ceec3a --- /dev/null +++ b/app/javascript/vehicle_journeys/components/ToggleArrivals.js @@ -0,0 +1,27 @@ +import React, { PropTypes } from 'react' + +export default function ToggleArrivals({filters, onToggleArrivals}) { + return ( +
    + +
    +
    + +
    +
    +
    + ) +} + +ToggleArrivals.propTypes = { + filters : PropTypes.object.isRequired, + onToggleArrivals: PropTypes.func.isRequired +} \ No newline at end of file diff --git a/app/javascript/vehicle_journeys/components/Tools.js b/app/javascript/vehicle_journeys/components/Tools.js new file mode 100644 index 000000000..a717408b9 --- /dev/null +++ b/app/javascript/vehicle_journeys/components/Tools.js @@ -0,0 +1,39 @@ +import React, { PropTypes } from 'react' +import actions from '../actions' +import AddVehicleJourney from '../containers/tools/AddVehicleJourney' +import DeleteVehicleJourneys from '../containers/tools/DeleteVehicleJourneys' +import ShiftVehicleJourney from '../containers/tools/ShiftVehicleJourney' +import DuplicateVehicleJourney from '../containers/tools/DuplicateVehicleJourney' +import EditVehicleJourney from '../containers/tools/EditVehicleJourney' +import NotesEditVehicleJourney from '../containers/tools/NotesEditVehicleJourney' +import TimetablesEditVehicleJourney from '../containers/tools/TimetablesEditVehicleJourney' + +export default function Tools({vehicleJourneys, onCancelSelection, filters: {policy}, editMode}) { + return ( +
    + { + (policy['vehicle_journeys.create'] && policy['vehicle_journeys.update'] && policy['vehicle_journeys.destroy'] && editMode) && +
    +
      + + + + + + + +
    + + {actions.getSelected(vehicleJourneys).length} course(s) sélectionnée(s) + +
    + } +
    + ) +} + +Tools.propTypes = { + vehicleJourneys : PropTypes.array.isRequired, + onCancelSelection: PropTypes.func.isRequired, + filters: PropTypes.object.isRequired +} \ No newline at end of file diff --git a/app/javascript/vehicle_journeys/components/VehicleJourney.js b/app/javascript/vehicle_journeys/components/VehicleJourney.js new file mode 100644 index 000000000..cb5407f81 --- /dev/null +++ b/app/javascript/vehicle_journeys/components/VehicleJourney.js @@ -0,0 +1,145 @@ +import React, { PropTypes, Component } from 'react' +import actions from '../actions' + +export default class VehicleJourney extends Component { + constructor(props) { + super(props) + this.previousCity = undefined + } + + cityNameChecker(sp) { + let bool = false + if(sp.stop_area_cityname != this.previousCity){ + bool = true + this.previousCity = sp.stop_area_cityname + } + + return bool + } + + timeTableURL(tt) { + let refURL = window.location.pathname.split('/', 3).join('/') + let ttURL = refURL + '/time_tables/' + tt.id + + return ( + + ) + } + + columnHasDelta() { + let a = [] + this.props.value.vehicle_journey_at_stops.map((vj, i) => { + a.push(vj.delta) + }) + let b = a.reduce((p, c) => p+c, 0) + + if(b > 0) { + return true + } + } + + isDisabled(bool1, bool2) { + return (bool1 || bool2) + } + + render() { + this.previousCity = undefined + + return ( +
    +
    +
    {this.props.value.objectid ? actions.humanOID(this.props.value.objectid) : '-'}
    +
    {actions.humanOID(this.props.value.journey_pattern.objectid)}
    +
    + {this.props.value.time_tables.map((tt, i)=> + {this.timeTableURL(tt)} + )} +
    + + {(this.props.filters.policy['vehicle_journeys.update'] == true && this.props.editMode) && +
    + this.props.onSelectVehicleJourney(this.props.index)} + type='checkbox' + disabled={this.props.value.deletable} + checked={this.props.value.selected} + > + +
    + } + +
    + {this.props.value.vehicle_journey_at_stops.map((vj, i) => +
    +
    + {this.props.filters.toggleArrivals && +
    + + {this.props.onUpdateTime(e, i, this.props.index, 'hour', false, false)}} + value={vj.arrival_time['hour']} + /> + : + {this.props.onUpdateTime(e, i, this.props.index, 'minute', false, false)}} + value={vj.arrival_time['minute']} + /> + +
    + } +
    + {(vj.delta != 0) && + + } +
    +
    + + {this.props.onUpdateTime(e, i, this.props.index, 'hour', true, this.props.filters.toggleArrivals)}} + value={vj.departure_time['hour']} + /> + : + {this.props.onUpdateTime(e, i, this.props.index, "minute", true, this.props.filters.toggleArrivals)}} + value={vj.departure_time['minute']} + /> + +
    +
    +
    + )} +
    + ) + } +} + +VehicleJourney.propTypes = { + value: PropTypes.object.isRequired, + filters: PropTypes.object.isRequired, + index: PropTypes.number.isRequired, + onUpdateTime: PropTypes.func.isRequired, + onSelectVehicleJourney: PropTypes.func.isRequired +} \ No newline at end of file diff --git a/app/javascript/vehicle_journeys/components/VehicleJourneys.js b/app/javascript/vehicle_journeys/components/VehicleJourneys.js new file mode 100644 index 000000000..6bce9766b --- /dev/null +++ b/app/javascript/vehicle_journeys/components/VehicleJourneys.js @@ -0,0 +1,156 @@ +import React, { PropTypes, Component } from 'react' +import _ from 'lodash' +import VehicleJourney from './VehicleJourney' + + +export default class VehicleJourneys extends Component { + constructor(props){ + super(props) + this.previousCity = undefined + } + componentDidMount() { + this.props.onLoadFirstPage(this.props.filters) + } + + componentDidUpdate(prevProps, prevState) { + if(this.props.status.isFetching == false){ + $('.table-2entries').each(function() { + var refH = [] + var refCol = [] + + $(this).find('.t2e-head').children('div').each(function() { + var h = $(this).outerHeight(); + refH.push(h) + }); + + var i = 0 + $(this).find('.t2e-item').children('div').each(function() { + var h = $(this).outerHeight(); + if(refCol.length < refH.length){ + refCol.push(h) + } else { + if(h > refCol[i]) { + refCol[i] = h + } + } + if(i == (refH.length - 1)){ + i = 0 + } else { + i++ + } + }); + + for(var n = 0; n < refH.length; n++) { + if(refCol[n] < refH[n]) { + refCol[n] = refH[n] + } + } + + $(this).find('.th').css('height', refCol[0]); + + for(var nth = 1; nth < refH.length; nth++) { + $(this).find('.td:nth-child('+ (nth + 1) +')').css('height', refCol[nth]); + } + }); + } + } + + cityNameChecker(sp) { + let bool = false + if(sp.city_name != this.previousCity){ + bool = true + this.previousCity = sp.city_name + } + return ( +
    + {sp.name} +
    + ) + } + + render() { + this.previousCity = undefined + + if(this.props.status.isFetching == true) { + return ( +
    +
    +
    + ) + } else { + return ( +
    +
    + {(this.props.status.fetchSuccess == false) && ( +
    + Erreur : + la récupération des missions a rencontré un problème. Rechargez la page pour tenter de corriger le problème. +
    + )} + + { _.some(this.props.vehicleJourneys, 'errors') && ( +
    + Erreur : + {this.props.vehicleJourneys.map((vj, index) => + vj.errors && vj.errors.map((err, i) => { + return ( +
      +
    • {err}
    • +
    + ) + }) + )} +
    + )} + +
    0) ? '' : ' no_result')}> +
    +
    +
    ID course
    +
    ID mission
    +
    Calendriers
    +
    + {this.props.stopPointsList.map((sp, i) =>{ + return ( +
    + {this.cityNameChecker(sp)} +
    + ) + })} +
    + +
    +
    + {this.props.vehicleJourneys.map((vj, index) => + + )} +
    +
    +
    +
    +
    + ) + } + } +} + +VehicleJourneys.propTypes = { + status: PropTypes.object.isRequired, + filters: PropTypes.object.isRequired, + stopPointsList: PropTypes.array.isRequired, + onLoadFirstPage: PropTypes.func.isRequired, + onUpdateTime: PropTypes.func.isRequired, + onSelectVehicleJourney: PropTypes.func.isRequired +} \ No newline at end of file diff --git a/app/javascript/vehicle_journeys/components/tools/CreateModal.js b/app/javascript/vehicle_journeys/components/tools/CreateModal.js new file mode 100644 index 000000000..5b5e2f849 --- /dev/null +++ b/app/javascript/vehicle_journeys/components/tools/CreateModal.js @@ -0,0 +1,131 @@ +import React, { PropTypes, Component } from 'react' +import actions from '../../actions' +import MissionSelect2 from './select2s/MissionSelect2' +import CompanySelect2 from './select2s/CompanySelect2' + +export default class CreateModal extends Component { + constructor(props) { + super(props) + } + + handleSubmit() { + if(actions.validateFields(this.refs) == true && this.props.modal.modalProps.selectedJPModal) { + this.props.onAddVehicleJourney(this.refs, this.props.modal.modalProps.selectedJPModal, this.props.stopPointsList, this.props.modal.modalProps.selectedCompany) + this.props.onModalClose() + $('#NewVehicleJourneyModal').modal('hide') + } + } + + render() { + if(this.props.status.isFetching == true) { + return false + } + if(this.props.status.fetchSuccess == true) { + return ( +
  • + + +
    +
    +
    +
    +
    +

    Ajouter une course

    +
    + + {(this.props.modal.type == 'create') && ( +
    +
    +
    +
    +
    + + actions.resetValidation(e.currentTarget)} + /> +
    +
    +
    +
    + + this.props.onSelect2Company(e)} + /> +
    +
    +
    +
    + + +
    +
    +
    +
    + + actions.resetValidation(e.currentTarget)} + /> +
    +
    +
    +
    +
    + + +
    +
    + )} +
    +
    +
    +
    +
  • + ) + } else { + return false + } + } +} + +CreateModal.propTypes = { + index: PropTypes.number, + modal: PropTypes.object.isRequired, + status: PropTypes.object.isRequired, + stopPointsList: PropTypes.array.isRequired, + onOpenCreateModal: PropTypes.func.isRequired, + onModalClose: PropTypes.func.isRequired, + onAddVehicleJourney: PropTypes.func.isRequired, + onSelect2JourneyPattern: PropTypes.func.isRequired +} \ No newline at end of file diff --git a/app/javascript/vehicle_journeys/components/tools/DeleteVehicleJourneys.js b/app/javascript/vehicle_journeys/components/tools/DeleteVehicleJourneys.js new file mode 100644 index 000000000..0a1dedd3c --- /dev/null +++ b/app/javascript/vehicle_journeys/components/tools/DeleteVehicleJourneys.js @@ -0,0 +1,26 @@ +import React, { PropTypes } from 'react' +import actions from '../../actions' + +export default function DeleteVehicleJourneys({onDeleteVehicleJourneys, vehicleJourneys, filters}) { + return ( +
  • + +
  • + ) +} + +DeleteVehicleJourneys.propTypes = { + onDeleteVehicleJourneys: PropTypes.func.isRequired, + vehicleJourneys: PropTypes.array.isRequired, + filters: PropTypes.object.isRequired +} \ No newline at end of file diff --git a/app/javascript/vehicle_journeys/components/tools/DuplicateVehicleJourney.js b/app/javascript/vehicle_journeys/components/tools/DuplicateVehicleJourney.js new file mode 100644 index 000000000..0c1c81114 --- /dev/null +++ b/app/javascript/vehicle_journeys/components/tools/DuplicateVehicleJourney.js @@ -0,0 +1,196 @@ +import React, { PropTypes, Component } from 'react' +import actions from '../../actions' +import _ from 'lodash' + +export default class DuplicateVehicleJourney extends Component { + constructor(props) { + super(props) + this.state = {} + this.onFormChange = this.onFormChange.bind(this) + this.handleSubmit = this.handleSubmit.bind(this) + } + + componentWillReceiveProps() { + if (actions.getSelected(this.props.vehicleJourneys).length > 0) { + let hour = parseInt(this.getDefaultValue('hour')) + let miunte = parseInt(this.getDefaultValue('minute')) + this.setState((state, props) => { + return { + originalDT: { + hour: hour, + minute: miunte + }, + duplicate_time_hh: hour, + duplicate_time_mm: miunte, + additional_time: 0, + duplicate_number: 1 + } + }) + } + } + + handleSubmit() { + if(actions.validateFields(this.refs) == true) { + let newDeparture = { + departure_time : { + hour: this.state.duplicate_time_hh, + minute: this.state.duplicate_time_mm + } + } + let val = actions.getDuplicateDelta(_.find(actions.getSelected(this.props.vehicleJourneys)[0].vehicle_journey_at_stops, {'dummy': false}), newDeparture) + this.props.onDuplicateVehicleJourney(this.state.additional_time, this.state.duplicate_number, val) + this.props.onModalClose() + $('#DuplicateVehicleJourneyModal').modal('hide') + } + } + + onFormChange(e) { + let {name, value} = e.target + this.setState((state, props) => { + return { + [name]: parseInt(value) + } + }) + } + + getDefaultValue(type) { + let vjas = _.find(actions.getSelected(this.props.vehicleJourneys)[0].vehicle_journey_at_stops, {'dummy': false}) + return vjas.departure_time[type] + } + + render() { + if(this.props.status.isFetching == true) { + return false + } + if(this.props.status.fetchSuccess == true && actions.getSelected(this.props.vehicleJourneys).length > 0) { + return ( +
  • + + +
    +
    +
    +
    +
    +

    + Dupliquer { actions.getSelected(this.props.vehicleJourneys).length > 1 ? 'plusieurs courses' : 'une course' } +

    +
    + + {(this.props.modal.type == 'duplicate') && ( +
    +
    +
    1 ? 'hidden' : '' )}> + + + 1 ? ' disabled' : '')}> + this.onFormChange(e)} + disabled={actions.getSelected(this.props.vehicleJourneys) && (actions.getSelected(this.props.vehicleJourneys).length > 1 ? 'disabled' : '')} + /> + : + this.onFormChange(e)} + disabled={actions.getSelected(this.props.vehicleJourneys) && (actions.getSelected(this.props.vehicleJourneys).length > 1 ? 'disabled' : '')} + /> + + +
    + +
    + +
    + this.onFormChange(e)} + onKeyDown={(e) => actions.resetValidation(e.currentTarget)} + required + /> +
    +
    + +
    + + + this.onFormChange(e)} + onKeyDown={(e) => actions.resetValidation(e.currentTarget)} + required + /> + +
    +
    + +
    + + +
    +
    + )} +
    +
    +
    +
    +
  • + ) + } else { + return false + } + } +} + +DuplicateVehicleJourney.propTypes = { + onOpenDuplicateModal: PropTypes.func.isRequired, + onModalClose: PropTypes.func.isRequired, + filters: PropTypes.object.isRequired +} \ No newline at end of file diff --git a/app/javascript/vehicle_journeys/components/tools/EditVehicleJourney.js b/app/javascript/vehicle_journeys/components/tools/EditVehicleJourney.js new file mode 100644 index 000000000..3a4a57024 --- /dev/null +++ b/app/javascript/vehicle_journeys/components/tools/EditVehicleJourney.js @@ -0,0 +1,167 @@ +import React, { PropTypes, Component } from 'react' +import actions from '../../actions' +import CompanySelect2 from './select2s/CompanySelect2' + +export default class EditVehicleJourney extends Component { + constructor(props) { + super(props) + } + + handleSubmit() { + if(actions.validateFields(this.refs) == true) { + var company; + if(this.props.modal.modalProps.selectedCompany) { + company = this.props.modal.modalProps.selectedCompany + } else if (typeof this.props.modal.modalProps.vehicleJourney.company === Object) { + company = this.props.modal.modalProps.vehicleJourney.company + } else { + company = undefined + } + this.props.onEditVehicleJourney(this.refs, company) + this.props.onModalClose() + $('#EditVehicleJourneyModal').modal('hide') + } + } + + render() { + if(this.props.status.isFetching == true) { + return false + } + if(this.props.status.fetchSuccess == true) { + return ( +
  • + + +
    +
    +
    +
    +
    +

    Informations

    +
    + + {(this.props.modal.type == 'edit') && ( +
    +
    +
    +
    +
    + + actions.resetValidation(e.currentTarget)} + /> +
    +
    +
    +
    + + +
    +
    +
    + +
    +
    +
    + + actions.resetValidation(e.currentTarget)} + /> +
    +
    +
    +
    + + this.props.onSelect2Company(e)} + onUnselect2Company = {() => this.props.onUnselect2Company()} + /> +
    +
    +
    + +
    +
    +
    + + +
    +
    +
    +
    + + +
    +
    +
    +
    + +
    + + +
    +
    + )} + +
    +
    +
    +
    +
  • + ) + } else { + return false + } + } +} + +EditVehicleJourney.propTypes = { + onOpenEditModal: PropTypes.func.isRequired, + onModalClose: PropTypes.func.isRequired, + filters: PropTypes.object.isRequired +} \ No newline at end of file diff --git a/app/javascript/vehicle_journeys/components/tools/NotesEditVehicleJourney.js b/app/javascript/vehicle_journeys/components/tools/NotesEditVehicleJourney.js new file mode 100644 index 000000000..1958faf5f --- /dev/null +++ b/app/javascript/vehicle_journeys/components/tools/NotesEditVehicleJourney.js @@ -0,0 +1,150 @@ +import React, { PropTypes, Component } from 'react' +import actions from '../../actions' +import _ from 'lodash' + +export default class NotesEditVehicleJourney extends Component { + constructor(props) { + super(props) + } + + handleSubmit() { + this.props.onNotesEditVehicleJourney(this.props.modal.modalProps.vehicleJourney.footnotes) + this.props.onModalClose() + $('#NotesEditVehicleJourneyModal').modal('hide') + } + + renderFootnoteButton(lf, vjArray){ + let footnote_id = undefined + vjArray.forEach((f) => { + if(f.id == lf.id){ + footnote_id = f.id + } + }) + + if(footnote_id){ + return + }else{ + return + } + } + + filterFN() { + return _.filter(window.line_footnotes, (lf, i) => { + let bool = true + _.map(this.props.modal.modalProps.vehicleJourney.footnotes, (f, j) => { + if(lf.id === f.id) { + bool = false + } + }) + return bool + }) + } + + render() { + if(this.props.status.isFetching == true) { + return false + } + if(this.props.status.fetchSuccess == true) { + return ( +
  • + + +
    +
    +
    +
    +
    +

    Notes

    +
    + + {(this.props.modal.type == 'notes_edit') && ( +
    +
    +

    Notes associées

    + {(this.props.modal.modalProps.vehicleJourney.footnotes).map((lf, i) => +
    +
    +

    +
    {lf.code}
    +
    {this.renderFootnoteButton(lf, this.props.modal.modalProps.vehicleJourney.footnotes)}
    +

    +
    +

    {lf.label}

    +
    + )} + +

    Sélectionnez les notes à associer à cette course :

    + {this.filterFN().map((lf, i) => +
    +
    +

    +
    {lf.code}
    +
    {this.renderFootnoteButton(lf, this.props.modal.modalProps.vehicleJourney.footnotes)}
    +

    +
    +

    {lf.label}

    +
    + )} +
    + +
    + + +
    +
    + )} + +
    +
    +
    +
    +
  • + ) + } else { + return false + } + } +} + +NotesEditVehicleJourney.propTypes = { + onOpenNotesEditModal: PropTypes.func.isRequired, + onModalClose: PropTypes.func.isRequired, + onToggleFootnoteModal: PropTypes.func.isRequired, + onNotesEditVehicleJourney: PropTypes.func.isRequired, + filters: PropTypes.object.isRequired +} \ No newline at end of file diff --git a/app/javascript/vehicle_journeys/components/tools/ShiftVehicleJourney.js b/app/javascript/vehicle_journeys/components/tools/ShiftVehicleJourney.js new file mode 100644 index 000000000..c1e2de779 --- /dev/null +++ b/app/javascript/vehicle_journeys/components/tools/ShiftVehicleJourney.js @@ -0,0 +1,114 @@ +import React, { PropTypes, Component } from 'react' +import actions from '../../actions' + +export default class ShiftVehicleJourney extends Component { + constructor(props) { + super(props) + this.state = { + additional_time: 0 + } + } + + handleSubmit() { + if(actions.validateFields(this.refs) == true) { + this.props.onShiftVehicleJourney(this.state.additional_time) + this.props.onModalClose() + $('#ShiftVehicleJourneyModal').modal('hide') + } + } + + handleAdditionalTimeChange() { + this.setState((state, props) => { + return { + additional_time: parseInt(this.refs.additional_time.value) + } + }) + } + + render() { + if(this.props.status.isFetching == true) { + return false + } + if(this.props.status.fetchSuccess == true) { + return ( +
  • + + +
    +
    +
    +
    +
    +

    Mettre à jour une course

    + {(this.props.modal.type == 'shift') && ( + Mettre à jour les horaires de la course {actions.humanOID(actions.getSelected(this.props.vehicleJourneys)[0].objectid)} + )} +
    + + {(this.props.modal.type == 'shift') && ( +
    +
    +
    +
    +
    + + actions.resetValidation(e.currentTarget)} + required + /> +
    +
    +
    +
    +
    + + +
    +
    + )} +
    +
    +
    +
    +
  • + ) + } else { + return false + } + } +} + +ShiftVehicleJourney.propTypes = { + onOpenShiftModal: PropTypes.func.isRequired, + onModalClose: PropTypes.func.isRequired, + filters: PropTypes.object.isRequired +} \ No newline at end of file diff --git a/app/javascript/vehicle_journeys/components/tools/TimetablesEditVehicleJourney.js b/app/javascript/vehicle_journeys/components/tools/TimetablesEditVehicleJourney.js new file mode 100644 index 000000000..fd2304901 --- /dev/null +++ b/app/javascript/vehicle_journeys/components/tools/TimetablesEditVehicleJourney.js @@ -0,0 +1,131 @@ +import React, { PropTypes, Component } from 'react' +import actions from '../../actions' +import TimetableSelect2 from './select2s/TimetableSelect2' + +export default class TimetablesEditVehicleJourney extends Component { + constructor(props) { + super(props) + } + + handleSubmit() { + this.props.onTimetablesEditVehicleJourney(this.props.modal.modalProps.vehicleJourneys, this.props.modal.modalProps.timetables) + this.props.onModalClose() + $('#CalendarsEditVehicleJourneyModal').modal('hide') + } + + render() { + if(this.props.status.isFetching == true) { + return false + } + if(this.props.status.fetchSuccess == true) { + return ( +
  • + + +
    +
    +
    +
    +
    +

    Calendriers associés

    +
    + + {(this.props.modal.type == 'calendars_edit') && ( +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    + {this.props.modal.modalProps.timetables.map((tt, i) => + + )} +
    +
    +
    + +
    +
    +
    +
    +
    +
    +
    + +
    + + +
    +
    + )} + +
    +
    +
    +
    +
  • + ) + } else { + return false + } + } +} + +TimetablesEditVehicleJourney.propTypes = { + onOpenCalendarsEditModal: PropTypes.func.isRequired, + onModalClose: PropTypes.func.isRequired, + onTimetablesEditVehicleJourney: PropTypes.func.isRequired, + onDeleteCalendarModal: PropTypes.func.isRequired, + onSelect2Timetable: PropTypes.func.isRequired, + filters: PropTypes.object.isRequired +} \ No newline at end of file diff --git a/app/javascript/vehicle_journeys/components/tools/select2s/CompanySelect2.js b/app/javascript/vehicle_journeys/components/tools/select2s/CompanySelect2.js new file mode 100644 index 000000000..03272e8b4 --- /dev/null +++ b/app/javascript/vehicle_journeys/components/tools/select2s/CompanySelect2.js @@ -0,0 +1,64 @@ +import _ from 'lodash' +import React, { PropTypes, Component } from 'react' +import Select2 from 'react-select2-wrapper' + +// get JSON full path +let origin = window.location.origin +let path = window.location.pathname.split('/', 3).join('/') +let line = window.location.pathname.split('/')[4] + + +export default class BSelect4 extends Component { + constructor(props) { + super(props) + } + + render() { + return ( + this.props.onSelect2Company(e) } + onUnselect={() => this.props.onUnselect2Company()} + multiple={false} + ref='company_id' + options={{ + allowClear: true, + theme: 'bootstrap', + width: '100%', + placeholder: 'Filtrer par transporteur...', + language: require('./fr'), + ajax: { + url: origin + path + '/companies.json' + '?line_id=' + line, + dataType: 'json', + delay: '500', + data: function(params) { + return { + q: {name_cont: params.term}, + }; + }, + processResults: function(data, params) { + + return { + results: data.map( + item => _.assign( + {}, + item, + {text: item.name} + ) + ) + }; + }, + cache: true + }, + minimumInputLength: 1, + templateResult: formatRepo + }} + /> + ) + } +} + +const formatRepo = (props) => { + if(props.text) return props.text +} \ No newline at end of file diff --git a/app/javascript/vehicle_journeys/components/tools/select2s/MissionSelect2.js b/app/javascript/vehicle_journeys/components/tools/select2s/MissionSelect2.js new file mode 100644 index 000000000..bf00a9d96 --- /dev/null +++ b/app/javascript/vehicle_journeys/components/tools/select2s/MissionSelect2.js @@ -0,0 +1,63 @@ +import _ from 'lodash' +import React, { PropTypes, Component } from 'react' +import Select2 from 'react-select2-wrapper' +import actions from '../../../actions' + +// get JSON full path +let origin = window.location.origin +let path = window.location.pathname.split('/', 7).join('/') + + +export default class BSelect4 extends Component { + constructor(props) { + super(props) + } + + render() { + return ( + this.props.onSelect2JourneyPattern(e)} + multiple={false} + ref='journey_pattern_id' + options={{ + allowClear: false, + theme: 'bootstrap', + placeholder: 'Filtrer par code, nom ou OID de mission...', + language: require('./fr'), + width: '100%', + ajax: { + url: origin + path + '/journey_patterns_collection.json', + dataType: 'json', + delay: '500', + data: function(params) { + return { + q: {published_name_or_objectid_or_registration_number_cont: params.term}, + }; + }, + processResults: function(data, params) { + return { + results: data.map( + item => _.assign( + {}, + item, + { text: "" + item.published_name + " - " + actions.humanOID(item.object_id) + "
    " + item.registration_number + "" } + ) + ) + }; + }, + cache: true + }, + minimumInputLength: 1, + escapeMarkup: function (markup) { return markup; }, + templateResult: formatRepo + }} + /> + ) + } +} + +const formatRepo = (props) => { + if(props.text) return props.text +} \ No newline at end of file diff --git a/app/javascript/vehicle_journeys/components/tools/select2s/TimetableSelect2.js b/app/javascript/vehicle_journeys/components/tools/select2s/TimetableSelect2.js new file mode 100644 index 000000000..8463965b9 --- /dev/null +++ b/app/javascript/vehicle_journeys/components/tools/select2s/TimetableSelect2.js @@ -0,0 +1,68 @@ +import _ from 'lodash' +import React, { PropTypes, Component } from 'react' +import Select2 from 'react-select2-wrapper' +import actions from '../../../actions' + +// get JSON full path +var origin = window.location.origin +var path = window.location.pathname.split('/', 3).join('/') + + +export default class BSelect4 extends Component { + constructor(props) { + super(props) + } + + render() { + return ( + this.props.onSelect2Timetable(e) } + multiple={false} + ref='timetable_id' + options={{ + allowClear: false, + theme: 'bootstrap', + width: '100%', + placeholder: 'Filtrer par calendrier...', + language: require('./fr'), + ajax: { + url: origin + path + this.props.chunkURL, + dataType: 'json', + delay: '500', + data: function(params) { + let newParmas = params.term.split(" ") + return { + q: { + objectid_cont_any: newParmas, + comment_cont_any: newParmas, + m: 'or' + } + }; + }, + processResults: function(data, params) { + return { + results: data.map( + item => _.assign( + {}, + item, + {text: '' + " " + item.comment + ' - ' + actions.humanOID(item.objectid) + '
    ' + (item.day_types ? item.day_types.match(/[A-Z]?[a-z]+/g).join(', ') : "") + ''} + ) + ) + }; + }, + cache: true + }, + minimumInputLength: 1, + escapeMarkup: function (markup) { return markup; }, + templateResult: formatRepo + }} + /> + ) + } +} + +const formatRepo = (props) => { + if(props.text) return props.text +} \ No newline at end of file diff --git a/app/javascript/vehicle_journeys/components/tools/select2s/VJSelect2.js b/app/javascript/vehicle_journeys/components/tools/select2s/VJSelect2.js new file mode 100644 index 000000000..34273fcf6 --- /dev/null +++ b/app/javascript/vehicle_journeys/components/tools/select2s/VJSelect2.js @@ -0,0 +1,62 @@ +import _ from 'lodash' +import React, { PropTypes, Component } from 'react' +import Select2 from 'react-select2-wrapper' +import actions from '../../../actions' + +// get JSON full path +let origin = window.location.origin +let path = window.location.pathname.split('/', 7).join('/') + + +export default class BSelect4b extends Component { + constructor(props) { + super(props) + } + + render() { + return ( + this.props.onSelect2VehicleJourney(e)} + multiple={false} + ref='vehicle_journey_objectid' + options={{ + allowClear: false, + theme: 'bootstrap', + placeholder: 'Filtrer par ID course...', + width: '100%', + language: require('./fr'), + ajax: { + url: origin + path + '/vehicle_journeys.json', + dataType: 'json', + delay: '500', + data: function(params) { + return { + q: {objectid_cont: params.term}, + }; + }, + processResults: function(data, params) { + return { + results: data.vehicle_journeys.map( + item => _.assign( + {}, + item, + { id: item.objectid, text: actions.humanOID(item.objectid) } + ) + ) + }; + }, + cache: true + }, + minimumInputLength: 1, + templateResult: formatRepo + }} + /> + ) + } +} + +const formatRepo = (props) => { + if(props.text) return props.text +} \ No newline at end of file diff --git a/app/javascript/vehicle_journeys/components/tools/select2s/fr.js b/app/javascript/vehicle_journeys/components/tools/select2s/fr.js new file mode 100644 index 000000000..20154d412 --- /dev/null +++ b/app/javascript/vehicle_journeys/components/tools/select2s/fr.js @@ -0,0 +1,9 @@ +module.exports = { + errorLoading:function(){return"Les résultats ne peuvent pas être chargés."}, + inputTooLong:function(e){var t=e.input.length-e.maximum,n="Supprimez "+t+" caractère";return t!==1&&(n+="s"),n}, + inputTooShort:function(e){var t=e.minimum-e.input.length,n="Saisissez "+t+" caractère";return t!==1&&(n+="s"),n}, + loadingMore:function(){return"Chargement de résultats supplémentaires…"}, + maximumSelected:function(e){var t="Vous pouvez seulement sélectionner "+e.maximum+" élément";return e.maximum!==1&&(t+="s"),t}, + noResults:function(){return"Aucun résultat trouvé"}, + searching:function(){return"Recherche en cours…"} +} diff --git a/app/javascript/vehicle_journeys/containers/ConfirmModal.js b/app/javascript/vehicle_journeys/containers/ConfirmModal.js new file mode 100644 index 000000000..e751a70f6 --- /dev/null +++ b/app/javascript/vehicle_journeys/containers/ConfirmModal.js @@ -0,0 +1,30 @@ +import actions from '../actions' +import { connect } from 'react-redux' +import ConfirmModal from '../components/ConfirmModal' + +const mapStateToProps = (state) => { + return { + modal: state.modal, + vehicleJourneys: state.vehicleJourneys + } +} + +const mapDispatchToProps = (dispatch) => { + return { + onModalAccept: (next, state) =>{ + dispatch(actions.fetchingApi()) + actions.submitVehicleJourneys(dispatch, state, next) + }, + onModalCancel: (next) =>{ + dispatch(actions.fetchingApi()) + dispatch(next) + }, + onModalClose: () =>{ + dispatch(actions.closeModal()) + } + } +} + +const ConfirmModalContainer = connect(mapStateToProps, mapDispatchToProps)(ConfirmModal) + +export default ConfirmModalContainer diff --git a/app/javascript/vehicle_journeys/containers/Filters.js b/app/javascript/vehicle_journeys/containers/Filters.js new file mode 100644 index 000000000..bec3527f4 --- /dev/null +++ b/app/javascript/vehicle_journeys/containers/Filters.js @@ -0,0 +1,48 @@ +import actions from '../actions' +import { connect } from 'react-redux' +import Filters from '../components/Filters' + +const mapStateToProps = (state) => { + return { + filters: state.filters, + pagination: state.pagination + } +} + +const mapDispatchToProps = (dispatch) => { + return { + onUpdateStartTimeFilter: (e, unit) =>{ + e.preventDefault() + dispatch(actions.updateStartTimeFilter(e.target.value, unit)) + }, + onUpdateEndTimeFilter: (e, unit) =>{ + e.preventDefault() + dispatch(actions.updateEndTimeFilter(e.target.value, unit)) + }, + onToggleWithoutSchedule: () =>{ + dispatch(actions.toggleWithoutSchedule()) + }, + onToggleWithoutTimeTable: () =>{ + dispatch(actions.toggleWithoutTimeTable()) + }, + onResetFilters: (e, pagination) =>{ + dispatch(actions.checkConfirmModal(e, actions.resetFilters(dispatch), pagination.stateChanged, dispatch)) + }, + onFilter: (e, pagination) =>{ + dispatch(actions.checkConfirmModal(e, actions.filterQuery(dispatch), pagination.stateChanged, dispatch)) + }, + onSelect2Timetable: (e) => { + dispatch(actions.filterSelect2Timetable(e.params.data)) + }, + onSelect2JourneyPattern: (e) => { + dispatch(actions.filterSelect2JourneyPattern(e.params.data)) + }, + onSelect2VehicleJourney: (e) => { + dispatch(actions.filterSelect2VehicleJourney(e.params.data)) + } + } +} + +const FiltersList = connect(mapStateToProps, mapDispatchToProps)(Filters) + +export default FiltersList diff --git a/app/javascript/vehicle_journeys/containers/Navigate.js b/app/javascript/vehicle_journeys/containers/Navigate.js new file mode 100644 index 000000000..f6cd4e2a1 --- /dev/null +++ b/app/javascript/vehicle_journeys/containers/Navigate.js @@ -0,0 +1,17 @@ +import actions from '../actions' +import { connect } from 'react-redux' +import NavigateComponent from '../components/Navigate' + +const mapStateToProps = (state) => { + return { + vehicleJourneys: state.vehicleJourneys, + status: state.status, + pagination: state.pagination, + filters: state.filters + } +} + + +const Navigate = connect(mapStateToProps)(NavigateComponent) + +export default Navigate diff --git a/app/javascript/vehicle_journeys/containers/SaveVehicleJourneys.js b/app/javascript/vehicle_journeys/containers/SaveVehicleJourneys.js new file mode 100644 index 000000000..18f9e994e --- /dev/null +++ b/app/javascript/vehicle_journeys/containers/SaveVehicleJourneys.js @@ -0,0 +1,28 @@ +import actions from '../actions' +import { connect } from 'react-redux' +import SaveVehicleJourneysComponent from '../components/SaveVehicleJourneys' + +const mapStateToProps = (state) => { + return { + editMode: state.editMode, + vehicleJourneys: state.vehicleJourneys, + page: state.pagination.page, + status: state.status, + filters: state.filters + } +} + +const mapDispatchToProps = (dispatch) => { + return { + onEnterEditMode: () => { + dispatch(actions.enterEditMode()) + }, + onSubmitVehicleJourneys: (next, state) => { + actions.submitVehicleJourneys(dispatch, state, next) + } + } +} + +const SaveVehicleJourneys = connect(mapStateToProps, mapDispatchToProps)(SaveVehicleJourneysComponent) + +export default SaveVehicleJourneys diff --git a/app/javascript/vehicle_journeys/containers/ToggleArrivals.js b/app/javascript/vehicle_journeys/containers/ToggleArrivals.js new file mode 100644 index 000000000..f6e180f80 --- /dev/null +++ b/app/javascript/vehicle_journeys/containers/ToggleArrivals.js @@ -0,0 +1,21 @@ +import actions from '../actions' +import { connect } from 'react-redux' +import ToggleArrivals from '../components/ToggleArrivals' + +const mapStateToProps = (state) => { + return { + filters: state.filters + } +} + +const mapDispatchToProps = (dispatch) => { + return { + onToggleArrivals: () =>{ + dispatch(actions.toggleArrivals()) + } + } +} + +const ToggleArrivalsList = connect(mapStateToProps, mapDispatchToProps)(ToggleArrivals) + +export default ToggleArrivalsList diff --git a/app/javascript/vehicle_journeys/containers/Tools.js b/app/javascript/vehicle_journeys/containers/Tools.js new file mode 100644 index 000000000..b760b52d6 --- /dev/null +++ b/app/javascript/vehicle_journeys/containers/Tools.js @@ -0,0 +1,23 @@ +import actions from '../actions' +import { connect } from 'react-redux' +import ToolsComponent from '../components/Tools' + +const mapStateToProps = (state) => { + return { + vehicleJourneys: state.vehicleJourneys, + editMode: state.editMode, + filters: state.filters + } +} + +const mapDispatchToProps = (dispatch) => { + return { + onCancelSelection: () => { + dispatch(actions.cancelSelection()) + } + } +} + +const Tools = connect(mapStateToProps, mapDispatchToProps)(ToolsComponent) + +export default Tools diff --git a/app/javascript/vehicle_journeys/containers/VehicleJourneysList.js b/app/javascript/vehicle_journeys/containers/VehicleJourneysList.js new file mode 100644 index 000000000..38ab9f6d3 --- /dev/null +++ b/app/javascript/vehicle_journeys/containers/VehicleJourneysList.js @@ -0,0 +1,32 @@ +import actions from '../actions' +import { connect } from 'react-redux' +import VehicleJourneys from '../components/VehicleJourneys' + +const mapStateToProps = (state) => { + return { + editMode: state.editMode, + vehicleJourneys: state.vehicleJourneys, + status: state.status, + filters: state.filters, + stopPointsList: state.stopPointsList + } +} + +const mapDispatchToProps = (dispatch) => { + return { + onLoadFirstPage: (filters) =>{ + dispatch(actions.fetchingApi()) + actions.fetchVehicleJourneys(dispatch, undefined, undefined, filters.queryString) + }, + onUpdateTime: (e, subIndex, index, timeUnit, isDeparture, isArrivalsToggled) => { + dispatch(actions.updateTime(e.target.value, subIndex, index, timeUnit, isDeparture, isArrivalsToggled)) + }, + onSelectVehicleJourney: (index) => { + dispatch(actions.selectVehicleJourney(index)) + } + } +} + +const VehicleJourneysList = connect(mapStateToProps, mapDispatchToProps)(VehicleJourneys) + +export default VehicleJourneysList diff --git a/app/javascript/vehicle_journeys/containers/tools/AddVehicleJourney.js b/app/javascript/vehicle_journeys/containers/tools/AddVehicleJourney.js new file mode 100644 index 000000000..b3f777448 --- /dev/null +++ b/app/javascript/vehicle_journeys/containers/tools/AddVehicleJourney.js @@ -0,0 +1,37 @@ +import actions from '../../actions' +import { connect } from 'react-redux' +import CreateModal from '../../components/tools/CreateModal' + +const mapStateToProps = (state) => { + return { + modal: state.modal, + vehicleJourneys: state.vehicleJourneys, + status: state.status, + stopPointsList: state.stopPointsList, + filters: state.filters + } +} + +const mapDispatchToProps = (dispatch) => { + return { + onModalClose: () =>{ + dispatch(actions.closeModal()) + }, + onAddVehicleJourney: (data, selectedJourneyPattern, stopPointsList, selectedCompany) =>{ + dispatch(actions.addVehicleJourney(data, selectedJourneyPattern, stopPointsList, selectedCompany)) + }, + onOpenCreateModal: () =>{ + dispatch(actions.openCreateModal()) + }, + onSelect2JourneyPattern: (e) =>{ + dispatch(actions.selectJPCreateModal(e.params.data)) + }, + onSelect2Company: (e) => { + dispatch(actions.select2Company(e.params.data)) + } + } +} + +const AddVehicleJourney = connect(mapStateToProps, mapDispatchToProps)(CreateModal) + +export default AddVehicleJourney diff --git a/app/javascript/vehicle_journeys/containers/tools/DeleteVehicleJourneys.js b/app/javascript/vehicle_journeys/containers/tools/DeleteVehicleJourneys.js new file mode 100644 index 000000000..d7d315da4 --- /dev/null +++ b/app/javascript/vehicle_journeys/containers/tools/DeleteVehicleJourneys.js @@ -0,0 +1,22 @@ +import actions from '../../actions' +import { connect } from 'react-redux' +import DeleteVJComponent from '../../components/tools/DeleteVehicleJourneys' + +const mapStateToProps = (state) => { + return { + vehicleJourneys: state.vehicleJourneys, + filters: state.filters + } +} + +const mapDispatchToProps = (dispatch) => { + return { + onDeleteVehicleJourneys: () =>{ + dispatch(actions.deleteVehicleJourneys()) + }, + } +} + +const DeleteVehicleJourneys = connect(mapStateToProps, mapDispatchToProps)(DeleteVJComponent) + +export default DeleteVehicleJourneys diff --git a/app/javascript/vehicle_journeys/containers/tools/DuplicateVehicleJourney.js b/app/javascript/vehicle_journeys/containers/tools/DuplicateVehicleJourney.js new file mode 100644 index 000000000..e9ca88040 --- /dev/null +++ b/app/javascript/vehicle_journeys/containers/tools/DuplicateVehicleJourney.js @@ -0,0 +1,30 @@ +import actions from '../../actions' +import { connect } from 'react-redux' +import DuplicateVJComponent from '../../components/tools/DuplicateVehicleJourney' + +const mapStateToProps = (state) => { + return { + modal: state.modal, + vehicleJourneys: state.vehicleJourneys, + status: state.status, + filters: state.filters + } +} + +const mapDispatchToProps = (dispatch) => { + return { + onModalClose: () =>{ + dispatch(actions.closeModal()) + }, + onOpenDuplicateModal: () =>{ + dispatch(actions.openDuplicateModal()) + }, + onDuplicateVehicleJourney: (addtionalTime, duplicateNumber, departureDelta) =>{ + dispatch(actions.duplicateVehicleJourney(addtionalTime, duplicateNumber, departureDelta)) + } + } +} + +const DuplicateVehicleJourney = connect(mapStateToProps, mapDispatchToProps)(DuplicateVJComponent) + +export default DuplicateVehicleJourney diff --git a/app/javascript/vehicle_journeys/containers/tools/EditVehicleJourney.js b/app/javascript/vehicle_journeys/containers/tools/EditVehicleJourney.js new file mode 100644 index 000000000..2d480aa0c --- /dev/null +++ b/app/javascript/vehicle_journeys/containers/tools/EditVehicleJourney.js @@ -0,0 +1,36 @@ +import actions from '../../actions' +import { connect } from 'react-redux' +import EditComponent from '../../components/tools/EditVehicleJourney' + +const mapStateToProps = (state) => { + return { + modal: state.modal, + vehicleJourneys: state.vehicleJourneys, + status: state.status, + filters: state.filters + } +} + +const mapDispatchToProps = (dispatch) => { + return { + onModalClose: () =>{ + dispatch(actions.closeModal()) + }, + onOpenEditModal: (vj) =>{ + dispatch(actions.openEditModal(vj)) + }, + onEditVehicleJourney: (data, selectedCompany) =>{ + dispatch(actions.editVehicleJourney(data, selectedCompany)) + }, + onSelect2Company: (e) => { + dispatch(actions.select2Company(e.params.data)) + }, + onUnselect2Company: () => { + dispatch(actions.unselect2Company()) + }, + } +} + +const EditVehicleJourney = connect(mapStateToProps, mapDispatchToProps)(EditComponent) + +export default EditVehicleJourney diff --git a/app/javascript/vehicle_journeys/containers/tools/NotesEditVehicleJourney.js b/app/javascript/vehicle_journeys/containers/tools/NotesEditVehicleJourney.js new file mode 100644 index 000000000..5a96ff273 --- /dev/null +++ b/app/javascript/vehicle_journeys/containers/tools/NotesEditVehicleJourney.js @@ -0,0 +1,33 @@ +import actions from '../../actions' +import { connect } from 'react-redux' +import NotesEditComponent from '../../components/tools/NotesEditVehicleJourney' + +const mapStateToProps = (state) => { + return { + modal: state.modal, + vehicleJourneys: state.vehicleJourneys, + status: state.status, + filters: state.filters + } +} + +const mapDispatchToProps = (dispatch) => { + return { + onModalClose: () =>{ + dispatch(actions.closeModal()) + }, + onOpenNotesEditModal: (vj) =>{ + dispatch(actions.openNotesEditModal(vj)) + }, + onToggleFootnoteModal: (footnote, isShown) => { + dispatch(actions.toggleFootnoteModal(footnote, isShown)) + }, + onNotesEditVehicleJourney: (footnotes) =>{ + dispatch(actions.editVehicleJourneyNotes(footnotes)) + } + } +} + +const NotesEditVehicleJourney = connect(mapStateToProps, mapDispatchToProps)(NotesEditComponent) + +export default NotesEditVehicleJourney diff --git a/app/javascript/vehicle_journeys/containers/tools/ShiftVehicleJourney.js b/app/javascript/vehicle_journeys/containers/tools/ShiftVehicleJourney.js new file mode 100644 index 000000000..a4b4fbe39 --- /dev/null +++ b/app/javascript/vehicle_journeys/containers/tools/ShiftVehicleJourney.js @@ -0,0 +1,30 @@ +import actions from '../../actions' +import { connect } from 'react-redux' +import ShiftVJComponent from '../../components/tools/ShiftVehicleJourney' + +const mapStateToProps = (state) => { + return { + modal: state.modal, + vehicleJourneys: state.vehicleJourneys, + status: state.status, + filters: state.filters + } +} + +const mapDispatchToProps = (dispatch) => { + return { + onModalClose: () =>{ + dispatch(actions.closeModal()) + }, + onOpenShiftModal: () =>{ + dispatch(actions.openShiftModal()) + }, + onShiftVehicleJourney: (data) =>{ + dispatch(actions.shiftVehicleJourney(data)) + } + } +} + +const ShiftVehicleJourney = connect(mapStateToProps, mapDispatchToProps)(ShiftVJComponent) + +export default ShiftVehicleJourney diff --git a/app/javascript/vehicle_journeys/containers/tools/TimetablesEditVehicleJourney.js b/app/javascript/vehicle_journeys/containers/tools/TimetablesEditVehicleJourney.js new file mode 100644 index 000000000..62150a06e --- /dev/null +++ b/app/javascript/vehicle_journeys/containers/tools/TimetablesEditVehicleJourney.js @@ -0,0 +1,37 @@ +import actions from '../../actions' +import { connect } from 'react-redux' +import TimetablesEditComponent from '../../components/tools/TimetablesEditVehicleJourney' + +const mapStateToProps = (state) => { + return { + modal: state.modal, + vehicleJourneys: state.vehicleJourneys, + status: state.status, + filters: state.filters + } +} + +const mapDispatchToProps = (dispatch) => { + return { + onModalClose: () =>{ + dispatch(actions.closeModal()) + }, + onOpenCalendarsEditModal: (vehicleJourneys) =>{ + dispatch(actions.openCalendarsEditModal(vehicleJourneys)) + }, + onDeleteCalendarModal: (timetable) => { + dispatch(actions.deleteCalendarModal(timetable)) + }, + onTimetablesEditVehicleJourney: (vehicleJourneys, timetables) =>{ + dispatch(actions.editVehicleJourneyTimetables(vehicleJourneys, timetables)) + }, + onSelect2Timetable: (e) =>{ + dispatch(actions.selectTTCalendarsModal(e.params.data)) + dispatch(actions.addSelectedTimetable()) + } + } +} + +const TimetablesEditVehicleJourney = connect(mapStateToProps, mapDispatchToProps)(TimetablesEditComponent) + +export default TimetablesEditVehicleJourney diff --git a/app/javascript/vehicle_journeys/reducers/editMode.js b/app/javascript/vehicle_journeys/reducers/editMode.js new file mode 100644 index 000000000..bff976804 --- /dev/null +++ b/app/javascript/vehicle_journeys/reducers/editMode.js @@ -0,0 +1,10 @@ +export default function editMode(state = {}, action ) { + switch (action.type) { + case "ENTER_EDIT_MODE": + return true + case "EXIT_EDIT_MODE": + return false + default: + return state + } +} \ No newline at end of file diff --git a/app/javascript/vehicle_journeys/reducers/filters.js b/app/javascript/vehicle_journeys/reducers/filters.js new file mode 100644 index 000000000..76fc98cc5 --- /dev/null +++ b/app/javascript/vehicle_journeys/reducers/filters.js @@ -0,0 +1,73 @@ +import _ from 'lodash' +import actions from '../actions' +let newQuery, newInterval + +export default function filters(state = {}, action) { + switch (action.type) { + case 'RESET_FILTERS': + let interval = { + start:{ + hour: '00', + minute: '00' + }, + end:{ + hour: '23', + minute: '59' + } + } + newQuery = _.assign({}, state.query, {interval: interval, journeyPattern: {}, vehicleJourney: {}, timetable: {}, withoutSchedule: true, withoutTimeTable: true }) + return _.assign({}, state, {query: newQuery, queryString: ''}) + case 'TOGGLE_WITHOUT_SCHEDULE': + newQuery = _.assign({}, state.query, {withoutSchedule: !state.query.withoutSchedule}) + return _.assign({}, state, {query: newQuery}) + case 'TOGGLE_WITHOUT_TIMETABLE': + newQuery = _.assign({}, state.query, {withoutTimeTable: !state.query.withoutTimeTable}) + return _.assign({}, state, {query: newQuery}) + case 'UPDATE_END_TIME_FILTER': + newInterval = JSON.parse(JSON.stringify(state.query.interval)) + newInterval.end[action.unit] = actions.pad(action.val, action.unit) + if(parseInt(newInterval.start.hour + newInterval.start.minute) < parseInt(newInterval.end.hour + newInterval.end.minute)){ + newQuery = _.assign({}, state.query, {interval: newInterval}) + return _.assign({}, state, {query: newQuery}) + }else{ + return state + } + case 'UPDATE_START_TIME_FILTER': + newInterval = JSON.parse(JSON.stringify(state.query.interval)) + newInterval.start[action.unit] = actions.pad(action.val, action.unit) + if(parseInt(newInterval.start.hour + newInterval.start.minute) < parseInt(newInterval.end.hour + newInterval.end.minute)){ + newQuery = _.assign({}, state.query, {interval: newInterval}) + return _.assign({}, state, {query: newQuery}) + }else{ + return state + } + case 'SELECT_TT_FILTER': + newQuery = _.assign({}, state.query, {timetable : action.selectedItem}) + return _.assign({}, state, {query: newQuery}) + case 'SELECT_JP_FILTER': + newQuery = _.assign({}, state.query, {journeyPattern : action.selectedItem}) + return _.assign({}, state, {query: newQuery}) + case 'SELECT_VJ_FILTER': + newQuery = _.assign({}, state.query, {vehicleJourney : action.selectedItem}) + return _.assign({}, state, {query: newQuery}) + case 'TOGGLE_ARRIVALS': + return _.assign({}, state, {toggleArrivals: !state.toggleArrivals}) + case 'QUERY_FILTER_VEHICLEJOURNEYS': + actions.fetchVehicleJourneys(action.dispatch, undefined, undefined, state.queryString) + return state + case 'CREATE_QUERY_STRING': + let params = { + 'q[journey_pattern_id_eq]': state.query.journeyPattern.id || undefined, + 'q[objectid_cont]': state.query.vehicleJourney.objectid || undefined, + 'q[time_tables_id_eq]': state.query.timetable.id || undefined, + 'q[vehicle_journey_at_stops_departure_time_gteq]': (state.query.interval.start.hour + ':' + state.query.interval.start.minute), + 'q[vehicle_journey_at_stops_departure_time_lteq]': (state.query.interval.end.hour + ':' + state.query.interval.end.minute), + 'q[vehicle_journey_without_departure_time]': state.query.withoutSchedule, + 'q[vehicle_journey_without_time_table]': state.query.withoutTimeTable + } + let queryString = actions.encodeParams(params) + return _.assign({}, state, {queryString: queryString}) + default: + return state + } +} \ No newline at end of file diff --git a/app/javascript/vehicle_journeys/reducers/index.js b/app/javascript/vehicle_journeys/reducers/index.js new file mode 100644 index 000000000..bb24aa185 --- /dev/null +++ b/app/javascript/vehicle_journeys/reducers/index.js @@ -0,0 +1,20 @@ +import { combineReducers } from 'redux' +import vehicleJourneys from './vehicleJourneys' +import pagination from './pagination' +import modal from './modal' +import status from './status' +import filters from './filters' +import editMode from './editMode' +import stopPointsList from './stopPointsList' + +const vehicleJourneysApp = combineReducers({ + vehicleJourneys, + pagination, + modal, + status, + filters, + editMode, + stopPointsList +}) + +export default vehicleJourneysApp diff --git a/app/javascript/vehicle_journeys/reducers/modal.js b/app/javascript/vehicle_journeys/reducers/modal.js new file mode 100644 index 000000000..57f54a144 --- /dev/null +++ b/app/javascript/vehicle_journeys/reducers/modal.js @@ -0,0 +1,138 @@ +import _ from 'lodash' + +let vehicleJourneysModal, newModalProps + +export default function modal(state = {}, action) { + switch (action.type) { + case 'OPEN_CONFIRM_MODAL': + $('#ConfirmModal').modal('show') + return _.assign({}, state, { + type: 'confirm', + confirmModal: { + callback: action.callback, + } + }) + case 'EDIT_NOTES_VEHICLEJOURNEY_MODAL': + let vehicleJourneyModal = _.assign({}, action.vehicleJourney) + return { + type: 'notes_edit', + modalProps: { + vehicleJourney: vehicleJourneyModal + }, + confirmModal: {} + } + case 'TOGGLE_FOOTNOTE_MODAL': + newModalProps = JSON.parse(JSON.stringify(state.modalProps)) + if (action.isShown){ + newModalProps.vehicleJourney.footnotes.push(action.footnote) + }else{ + newModalProps.vehicleJourney.footnotes = newModalProps.vehicleJourney.footnotes.filter((f) => {return f.id != action.footnote.id }) + } + return _.assign({}, state, {modalProps: newModalProps}) + case 'EDIT_VEHICLEJOURNEY_MODAL': + return { + type: 'edit', + modalProps: { + vehicleJourney: action.vehicleJourney + }, + confirmModal: {} + } + case 'EDIT_CALENDARS_VEHICLEJOURNEY_MODAL': + vehicleJourneysModal = JSON.parse(JSON.stringify(action.vehicleJourneys)) + let uniqTimetables = [] + let timetable = {} + vehicleJourneysModal.map((vj, i) => { + vj.time_tables.map((tt, j) =>{ + if(!(_.find(uniqTimetables, tt))){ + uniqTimetables.push(tt) + } + }) + }) + return { + type: 'calendars_edit', + modalProps: { + vehicleJourneys: vehicleJourneysModal, + timetables: uniqTimetables + }, + confirmModal: {} + } + case 'SELECT_CP_EDIT_MODAL': + newModalProps = _.assign({}, state.modalProps, {selectedCompany : action.selectedItem}) + return _.assign({}, state, {modalProps: newModalProps}) + case 'UNSELECT_CP_EDIT_MODAL': + newModalProps = _.assign({}, state.modalProps, {selectedCompany : undefined}) + return _.assign({}, state, {modalProps: newModalProps}) + case 'SELECT_TT_CALENDAR_MODAL': + newModalProps = _.assign({}, state.modalProps, {selectedTimetable : action.selectedItem}) + return _.assign({}, state, {modalProps: newModalProps}) + case 'ADD_SELECTED_TIMETABLE': + if(state.modalProps.selectedTimetable){ + newModalProps = JSON.parse(JSON.stringify(state.modalProps)) + if (!_.find(newModalProps.timetables, newModalProps.selectedTimetable)){ + newModalProps.timetables.push(newModalProps.selectedTimetable) + } + return _.assign({}, state, {modalProps: newModalProps}) + } + case 'DELETE_CALENDAR_MODAL': + newModalProps = JSON.parse(JSON.stringify(state.modalProps)) + let timetablesModal = state.modalProps.timetables.slice(0) + timetablesModal.map((tt, i) =>{ + if(tt == action.timetable){ + timetablesModal.splice(i, 1) + } + }) + vehicleJourneysModal = state.modalProps.vehicleJourneys.slice(0) + vehicleJourneysModal.map((vj) =>{ + vj.time_tables.map((tt, i) =>{ + if (_.isEqual(tt, action.timetable)){ + vj.time_tables.splice(i, 1) + } + }) + }) + newModalProps.vehicleJourneys = vehicleJourneysModal + newModalProps.timetables = timetablesModal + return _.assign({}, state, {modalProps: newModalProps}) + case 'CREATE_VEHICLEJOURNEY_MODAL': + let selectedJP = {} + if (window.jpOrigin){ + let stopAreas = _.map(window.jpOriginStopPoints, (sa, i) =>{ + return _.assign({}, {stop_area_short_description : {id : sa.stop_area_id}}) + }) + selectedJP = { + id: window.jpOrigin.id, + name: window.jpOrigin.name, + published_name: window.jpOrigin.published_name, + objectid: window.jpOrigin.objectid, + stop_areas: stopAreas + } + } + return { + type: 'create', + modalProps: window.jpOrigin ? {selectedJPModal: selectedJP} : {}, + confirmModal: {} + } + case 'SELECT_JP_CREATE_MODAL': + newModalProps = _.assign({}, state.modalProps, {selectedJPModal : action.selectedItem}) + return _.assign({}, state, {modalProps: newModalProps}) + case 'SHIFT_VEHICLEJOURNEY_MODAL': + return { + type: 'shift', + modalProps: {}, + confirmModal: {} + } + case 'DUPLICATE_VEHICLEJOURNEY_MODAL': + return { + type: 'duplicate', + modalProps: {}, + confirmModal: {} + } + case 'CLOSE_MODAL': + return { + type: '', + modalProps: {}, + confirmModal: {} + } + default: + return state + } +} \ No newline at end of file diff --git a/app/javascript/vehicle_journeys/reducers/pagination.js b/app/javascript/vehicle_journeys/reducers/pagination.js new file mode 100644 index 000000000..45c40c4c4 --- /dev/null +++ b/app/javascript/vehicle_journeys/reducers/pagination.js @@ -0,0 +1,37 @@ +import _ from 'lodash' + +export default function pagination(state = {}, action) { + switch (action.type) { + case 'RECEIVE_JOURNEY_PATTERNS': + case 'RECEIVE_VEHICLE_JOURNEYS': + return _.assign({}, state, {stateChanged: false}) + case 'GO_TO_PREVIOUS_PAGE': + if (action.pagination.page > 1){ + return _.assign({}, state, {page : action.pagination.page - 1, stateChanged: false}) + } + return state + case 'GO_TO_NEXT_PAGE': + if (state.totalCount - (action.pagination.page * action.pagination.perPage) > 0){ + return _.assign({}, state, {page : action.pagination.page + 1, stateChanged: false}) + } + return state + case 'ADD_VEHICLEJOURNEY': + case 'UPDATE_TIME': + toggleOnConfirmModal('modal') + return _.assign({}, state, {stateChanged: true}) + case 'RESET_PAGINATION': + return _.assign({}, state, {page: 1, stateChanged: false}) + case 'RECEIVE_TOTAL_COUNT': + return _.assign({}, state, {totalCount: action.total}) + case 'UPDATE_TOTAL_COUNT': + return _.assign({}, state, {totalCount : state.totalCount - action.diff }) + default: + return state + } +} + +const toggleOnConfirmModal = (arg = '') =>{ + $('.confirm').each(function(){ + $(this).data('toggle','') + }) +} \ No newline at end of file diff --git a/app/javascript/vehicle_journeys/reducers/status.js b/app/javascript/vehicle_journeys/reducers/status.js new file mode 100644 index 000000000..0bbb05124 --- /dev/null +++ b/app/javascript/vehicle_journeys/reducers/status.js @@ -0,0 +1,17 @@ +import _ from 'lodash' +import actions from '../actions' + +export default function status(state = {}, action) { + switch (action.type) { + case 'UNAVAILABLE_SERVER': + return _.assign({}, state, {fetchSuccess: false}) + case 'FETCH_API': + return _.assign({}, state, {isFetching: true}) + case 'RECEIVE_VEHICLE_JOURNEYS': + return _.assign({}, state, {fetchSuccess: true, isFetching: false}) + case 'RECEIVE_ERRORS': + return _.assign({}, state, {fetchSuccess: true, isFetching: false}) + default: + return state + } +} \ No newline at end of file diff --git a/app/javascript/vehicle_journeys/reducers/stopPointsList.js b/app/javascript/vehicle_journeys/reducers/stopPointsList.js new file mode 100644 index 000000000..9b22e08f2 --- /dev/null +++ b/app/javascript/vehicle_journeys/reducers/stopPointsList.js @@ -0,0 +1,6 @@ +export default function stopPointsList(state = [], action) { + switch (action.type) { + default: + return state + } +} \ No newline at end of file diff --git a/app/javascript/vehicle_journeys/reducers/vehicleJourneys.js b/app/javascript/vehicle_journeys/reducers/vehicleJourneys.js new file mode 100644 index 000000000..775fefdca --- /dev/null +++ b/app/javascript/vehicle_journeys/reducers/vehicleJourneys.js @@ -0,0 +1,227 @@ +import _ from 'lodash' +import actions from '../actions' + +const vehicleJourney= (state = {}, action, keep) => { + switch (action.type) { + case 'SELECT_VEHICLEJOURNEY': + return _.assign({}, state, {selected: !state.selected}) + case 'CANCEL_SELECTION': + return _.assign({}, state, {selected: false}) + case 'ADD_VEHICLEJOURNEY': + let pristineVjasList = [] + _.each(action.stopPointsList, (sp) =>{ + let newVjas = { + delta: 0, + departure_time:{ + hour: '00', + minute: '00' + }, + arrival_time:{ + hour: '00', + minute: '00' + }, + stop_point_objectid: sp.object_id, + stop_area_cityname: sp.city_name, + dummy: true + } + _.each(action.selectedJourneyPattern.stop_areas, (jp) =>{ + if (jp.stop_area_short_description.id == sp.id){ + newVjas.dummy = false + return + } + }) + pristineVjasList.push(newVjas) + }) + return { + company: action.selectedCompany, + journey_pattern: action.selectedJourneyPattern, + published_journey_name: action.data.published_journey_name.value, + published_journey_identifier: action.data.published_journey_identifier.value, + objectid: '', + footnotes: [], + time_tables: [], + vehicle_journey_at_stops: pristineVjasList, + selected: false, + deletable: false, + transport_mode: window.transportMode ? window.transportMode : 'undefined', + transport_submode: window.transportSubmode ? window.transportSubmode : 'undefined' + } + case 'DUPLICATE_VEHICLEJOURNEY': + case 'SHIFT_VEHICLEJOURNEY': + let shiftedArray, shiftedSchedule, shiftedVjas + shiftedArray = state.vehicle_journey_at_stops.map((vjas, i) => { + if (!vjas.dummy){ + shiftedSchedule = actions.getShiftedSchedule(vjas, action.addtionalTime) + + shiftedVjas = _.assign({}, state.vehicle_journey_at_stops[i], shiftedSchedule) + vjas = _.assign({}, state.vehicle_journey_at_stops[i], shiftedVjas) + if(!keep){ + delete vjas['id'] + } + return vjas + }else { + if(!keep){ + delete vjas['id'] + } + return vjas + } + }) + return _.assign({}, state, {vehicle_journey_at_stops: shiftedArray}) + case 'UPDATE_TIME': + let vj, vjas, vjasArray, newSchedule + vjasArray = state.vehicle_journey_at_stops.map((vjas, i) =>{ + if(i == action.subIndex){ + newSchedule = { + departure_time: _.assign({}, vjas.departure_time), + arrival_time: _.assign({}, vjas.arrival_time) + } + if (action.isDeparture){ + newSchedule.departure_time[action.timeUnit] = actions.pad(action.val, action.timeUnit) + if(!action.isArrivalsToggled) + newSchedule.arrival_time[action.timeUnit] = actions.pad(action.val, action.timeUnit) + newSchedule = actions.getDelta(newSchedule) + if(newSchedule.delta < 0){ + return vjas + } + return _.assign({}, state.vehicle_journey_at_stops[action.subIndex], {arrival_time: newSchedule.arrival_time, departure_time: newSchedule.departure_time, delta: newSchedule.delta}) + }else{ + newSchedule.arrival_time[action.timeUnit] = actions.pad(action.val, action.timeUnit) + newSchedule = actions.getDelta(newSchedule) + if(newSchedule.delta < 0){ + return vjas + } + return _.assign({}, state.vehicle_journey_at_stops[action.subIndex], {arrival_time: newSchedule.arrival_time, departure_time: newSchedule.departure_time, delta: newSchedule.delta}) + } + }else{ + return vjas + } + }) + return _.assign({}, state, {vehicle_journey_at_stops: vjasArray}) + default: + return state + } +} + +export default function vehicleJourneys(state = [], action) { + switch (action.type) { + case 'RECEIVE_VEHICLE_JOURNEYS': + return [...action.json] + case 'RECEIVE_ERRORS': + return [...action.json] + case 'GO_TO_PREVIOUS_PAGE': + if(action.pagination.page > 1){ + actions.fetchVehicleJourneys(action.dispatch, action.pagination.page, action.nextPage, action.queryString) + } + return state + case 'GO_TO_NEXT_PAGE': + if (action.pagination.totalCount - (action.pagination.page * action.pagination.perPage) > 0){ + actions.fetchVehicleJourneys(action.dispatch, action.pagination.page, action.nextPage, action.queryString) + } + return state + case 'ADD_VEHICLEJOURNEY': + return [ + vehicleJourney(state, action), + ...state + ] + case 'EDIT_VEHICLEJOURNEY': + return state.map((vj, i) => { + if (vj.selected){ + return _.assign({}, vj, { + company: action.selectedCompany, + published_journey_name: action.data.published_journey_name.value, + published_journey_identifier: action.data.published_journey_identifier.value, + }) + }else{ + return vj + } + }) + case 'EDIT_VEHICLEJOURNEY_NOTES': + return state.map((vj, i) => { + if (vj.selected){ + return _.assign({}, vj, { + footnotes: action.footnotes + }) + }else{ + return vj + } + }) + case 'EDIT_VEHICLEJOURNEYS_TIMETABLES': + let newTimetables = JSON.parse(JSON.stringify(action.timetables)) + return state.map((vj,i) =>{ + if(vj.selected){ + let updatedVJ = _.assign({}, vj) + action.vehicleJourneys.map((vjm, j) =>{ + if(vj.objectid == vjm.objectid){ + updatedVJ.time_tables = newTimetables + } + }) + return updatedVJ + }else{ + return vj + } + }) + case 'SHIFT_VEHICLEJOURNEY': + return state.map((vj, i) => { + if (vj.selected){ + return vehicleJourney(vj, action, true) + }else{ + return vj + } + }) + case 'DUPLICATE_VEHICLEJOURNEY': + let dupeVj + let dupes = [] + let selectedIndex + let val = action.addtionalTime + let departureDelta = action.departureDelta + state.map((vj, i) => { + if(vj.selected){ + selectedIndex = i + for (i = 0; i< action.duplicateNumber; i++){ + // We check if the departureDelta is != 0 to create the first VJ on the updated deparure time if it is the case + // let delta = departureDelta == 0 ? 1 : 0 + // action.addtionalTime = (val * (i + delta)) + departureDelta + action.addtionalTime = (val * (i + 1)) + departureDelta + dupeVj = vehicleJourney(vj, action, false) + dupeVj.published_journey_name = dupeVj.published_journey_name + '-' + i + dupeVj.selected = false + delete dupeVj['objectid'] + dupes.push(dupeVj) + } + } + }) + let concatArray = state.slice(0, selectedIndex + 1).concat(dupes) + concatArray = concatArray.concat(state.slice(selectedIndex + 1)) + return concatArray + case 'DELETE_VEHICLEJOURNEYS': + return state.map((vj, i) =>{ + if (vj.selected){ + return _.assign({}, vj, {deletable: true, selected: false}) + } else { + return vj + } + }) + case 'SELECT_VEHICLEJOURNEY': + return state.map((vj, i) =>{ + if (i == action.index){ + return vehicleJourney(vj, action) + } else { + return vj + } + }) + case 'CANCEL_SELECTION': + return state.map((vj) => { + return vehicleJourney(vj, action) + }) + case 'UPDATE_TIME': + return state.map((vj, i) =>{ + if (i == action.index){ + return vehicleJourney(vj, action) + } else { + return vj + } + }) + default: + return state + } +} \ No newline at end of file -- cgit v1.2.3 From 08b002abfb101b1edce9750231c989591e049bf7 Mon Sep 17 00:00:00 2001 From: cedricnjanga Date: Mon, 9 Oct 2017 17:14:27 +0200 Subject: Working standard webpacker config --- app/javascript/date_filters/calendar.js | 7 +++--- .../date_filters/compliance_check_set.js | 5 ++++ .../date_filters/compliance_control_set.js | 6 ++--- app/javascript/date_filters/import.js | 6 ++--- app/javascript/date_filters/index.js | 28 ++++++++++++---------- app/javascript/date_filters/time_table.js | 6 ++--- app/javascript/date_filters/workbench.js | 6 +++-- app/javascript/helpers/date_filters.js | 20 ++++++---------- app/javascript/packs/application.js | 3 ++- app/javascript/packs/date_filters.js | 2 +- app/javascript/packs/routes/edit.js | 23 +++++++++--------- app/javascript/routes/components/BSelect2.js | 6 ++--- app/javascript/routes/reducers/stopPoints.js | 6 ++--- .../time_tables/components/TagsSelect2.js | 2 +- .../components/tools/select2s/CompanySelect2.js | 2 +- .../components/tools/select2s/MissionSelect2.js | 2 +- .../components/tools/select2s/TimetableSelect2.js | 2 +- .../components/tools/select2s/VJSelect2.js | 2 +- 18 files changed, 69 insertions(+), 65 deletions(-) create mode 100644 app/javascript/date_filters/compliance_check_set.js (limited to 'app/javascript') diff --git a/app/javascript/date_filters/calendar.js b/app/javascript/date_filters/calendar.js index 266fcd16a..7e5f678e2 100644 --- a/app/javascript/date_filters/calendar.js +++ b/app/javascript/date_filters/calendar.js @@ -1,6 +1,5 @@ -const DateFilter = require('../helpers/date_filters') +import DateFilter from '../helpers/date_filters' -const calendarDF = new DateFilter("calendar_filter_btn", "Tous les champs du filtre de date doivent être remplis", "#q_contains_date_NUMi") - -module.exports = calendarDF +const calendarDF = new DateFilter("calendar_filter_btn", "Tous les champs du filtre de date doivent être remplis", "q_contains_date_NUMi") +export default calendarDF \ No newline at end of file diff --git a/app/javascript/date_filters/compliance_check_set.js b/app/javascript/date_filters/compliance_check_set.js new file mode 100644 index 000000000..09544a3cd --- /dev/null +++ b/app/javascript/date_filters/compliance_check_set.js @@ -0,0 +1,5 @@ +import DateFilter from '../helpers/date_filters' + +const complianceCheckSetDF = new DateFilter("compliance_check_set_filter_btn", "Tous les champs du filtre de date doivent être remplis", "q_created_at_start_date_NUMi", "q_created_at_end_date_NUMi") + +export default complianceCheckSetDF \ No newline at end of file diff --git a/app/javascript/date_filters/compliance_control_set.js b/app/javascript/date_filters/compliance_control_set.js index 8ac90f54d..60d8e3bfa 100644 --- a/app/javascript/date_filters/compliance_control_set.js +++ b/app/javascript/date_filters/compliance_control_set.js @@ -1,5 +1,5 @@ -const DateFilter = require('../helpers/date_filters') +import DateFilter from '../helpers/date_filters' -const complianceControlSetDF = new DateFilter("compliance_control_set_filter_btn", "Tous les champs du filtre de date doivent être remplis", "#q_updated_at_start_date_NUMi", "#q_updated_at_end_date_NUMi") +const complianceControlSetDF = new DateFilter("compliance_control_set_filter_btn", "Tous les champs du filtre de date doivent être remplis", "q_updated_at_start_date_NUMi", "q_updated_at_end_date_NUMi") -module.exports = complianceControlSetDF \ No newline at end of file +export default complianceControlSetDF \ No newline at end of file diff --git a/app/javascript/date_filters/import.js b/app/javascript/date_filters/import.js index 997dbd3f6..356371d30 100644 --- a/app/javascript/date_filters/import.js +++ b/app/javascript/date_filters/import.js @@ -1,5 +1,5 @@ -const DateFilter = require('../helpers/date_filters') +import DateFilter from '../helpers/date_filters' -const importDF = new DateFilter("import_filter_btn", "Tous les champs du filtre de date doivent être remplis", "#q_started_at_start_date_NUMi", "#q_started_at_end_date_NUMi") +const importDF = new DateFilter("import_filter_btn", "Tous les champs du filtre de date doivent être remplis", "q_started_at_start_date_NUMi", "q_started_at_end_date_NUMi") -module.exports = importDF \ No newline at end of file +export default importDF \ No newline at end of file diff --git a/app/javascript/date_filters/index.js b/app/javascript/date_filters/index.js index 1e09c8cf6..ee892a7fe 100644 --- a/app/javascript/date_filters/index.js +++ b/app/javascript/date_filters/index.js @@ -1,13 +1,17 @@ -const calendarDF = require('./calendar') -const complianceControlSetDF = require('./compliance_control_set') -const timetableDF = require('./time_table') -const importDF = require('./import') -const workbenchDF = require('./workbench') +import calendarDF from './calendar' +import complianceControlSetDF from './compliance_control_set' +import complianceCheckSetDF from './compliance_check_set' +import timetableDF from './time_table' +import importDF from './import' +import workbenchDF from './workbench' -module.exports = { - calendarDF: () => calendarDF, - complianceControlSetDF: () => complianceControlSetDF, - timetableDF: () => timetableDF, - importDF: () => importDF, - workbenchDF: () => workbenchDF -} \ No newline at end of file +const DateFilters = { + calendarDF, + complianceCheckSetDF, + complianceControlSetDF, + importDF, + timetableDF, + workbenchDF +} + +export default DateFilters \ No newline at end of file diff --git a/app/javascript/date_filters/time_table.js b/app/javascript/date_filters/time_table.js index e211bc12e..d26693993 100644 --- a/app/javascript/date_filters/time_table.js +++ b/app/javascript/date_filters/time_table.js @@ -1,5 +1,5 @@ -const DateFilter = require('../helpers/date_filters') +import DateFilter from '../helpers/date_filters' -const timetableDF = new DateFilter("time_table_filter_btn", "Tous les champs du filtre de date doivent être remplis", "#q_bounding_dates_start_date_NUMi", "#q_bounding_dates_end_date_NUMi") +const timetableDF = new DateFilter("time_table_filter_btn", "Tous les champs du filtre de date doivent être remplis", "q_bounding_dates_start_date_NUMi", "q_bounding_dates_end_date_NUMi") -module.exports = timetableDF +export default timetableDF \ No newline at end of file diff --git a/app/javascript/date_filters/workbench.js b/app/javascript/date_filters/workbench.js index e5fd58e53..cc4112d73 100644 --- a/app/javascript/date_filters/workbench.js +++ b/app/javascript/date_filters/workbench.js @@ -1,3 +1,5 @@ -const DateFilter = require('../helpers/date_filters') +import DateFilter from '../helpers/date_filters' -const workbenchDF = new DateFilter("referential_filter_btn", "Tous les champs du filtre de date doivent être remplis", "#q_validity_period_start_date_NUMi", "#q_validity_period_end_date_NUMi") +const workbenchDF = new DateFilter("referential_filter_btn", "Tous les champs du filtre de date doivent être remplis", "q_validity_period_start_date_NUMi", "q_validity_period_end_date_NUMi") + +export default workbenchDF \ No newline at end of file diff --git a/app/javascript/helpers/date_filters.js b/app/javascript/helpers/date_filters.js index 621e163ad..53c9da641 100644 --- a/app/javascript/helpers/date_filters.js +++ b/app/javascript/helpers/date_filters.js @@ -1,11 +1,11 @@ export default function DateFilter(buttonId, message, ...inputIds) { - this.buttonId = buttonId + this.button = document.getElementById(buttonId) this.inputIds = inputIds this.message = message const getVal = (str, key) => { let newStr = str.replace(/NUM/, key) - return $(newStr).val() + return document.getElementById(newStr).value } const getDates = () => { @@ -13,20 +13,14 @@ export default function DateFilter(buttonId, message, ...inputIds) { let newIds = [1, 2, 3].map(key => getVal(id, key)) arr.push(...newIds) return arr - },[]) + }, []) } - const allInputFilled = () => { - return getDates().every(date => !!date) - } - - const noInputFilled = () => { - return getDates().every(date => !date) - } - - const button = document.getElementById(this.buttonId) + const allInputFilled = () => getDates().every(date => !!date) - button && button.addEventListener('click', (event) => { + const noInputFilled = () => getDates().every(date => !date) + + this.button && this.button.addEventListener('click', (event) => { if (!allInputFilled() && !noInputFilled()) { event.preventDefault() alert(this.message) diff --git a/app/javascript/packs/application.js b/app/javascript/packs/application.js index 54b106ee0..0b3711e53 100644 --- a/app/javascript/packs/application.js +++ b/app/javascript/packs/application.js @@ -7,4 +7,5 @@ // To reference this file, add <%= javascript_pack_tag 'application' %> to the appropriate // layout file, like app/views/layouts/application.html.erb -console.log('Hello World from Webpacker') +// import jQuery from 'jquery' +// import {} from 'jquery-ujs' diff --git a/app/javascript/packs/date_filters.js b/app/javascript/packs/date_filters.js index db58bd679..88f508152 100644 --- a/app/javascript/packs/date_filters.js +++ b/app/javascript/packs/date_filters.js @@ -1 +1 @@ -const DateFilter = require('../date_filters/index') \ No newline at end of file +import DateFilter from '../date_filters' \ No newline at end of file diff --git a/app/javascript/packs/routes/edit.js b/app/javascript/packs/routes/edit.js index 810489353..d6ceed60f 100644 --- a/app/javascript/packs/routes/edit.js +++ b/app/javascript/packs/routes/edit.js @@ -1,21 +1,20 @@ -import React from 'react' -import PropTypes from 'prop-types' +import React, { PropTypes } from 'react' import { render } from 'react-dom' import { Provider } from 'react-redux' import { createStore } from 'redux' import reducers from '../../routes/reducers' import App from '../../routes/components/App' -import { handleForm, handleStopPoints } from '../../routes/form_helper' +import formHelper from '../../routes/form_helper' import clone from '../../helpers/clone' let datas = clone(window, "itinerary_stop", true) datas = JSON.parse(decodeURIComponent(datas)) // logger, DO NOT REMOVE -// var applyMiddleware = require('redux').applyMiddleware -// var createLogger = require('redux-logger') -// var thunkMiddleware = require('redux-thunk').default -// var promise = require('redux-promise') +var applyMiddleware = require('redux').applyMiddleware +var createLogger = require('redux-logger') +var thunkMiddleware = require('redux-thunk').default +var promise = require('redux-promise') const getInitialState = () => { let state = [] @@ -54,11 +53,11 @@ const getInitialState = () => { } var initialState = { stopPoints: getInitialState() } -// const loggerMiddleware = createLogger() +const loggerMiddleware = createLogger() let store = createStore( reducers, - initialState - // applyMiddleware(thunkMiddleware, promise, loggerMiddleware) + initialState, + applyMiddleware(thunkMiddleware, promise, loggerMiddleware) ) render( @@ -75,8 +74,8 @@ document.querySelector('input[name=commit]').addEventListener('click', (event) = let publicName = $("#route_published_name").val() if (name == "" || publicName == "") { event.preventDefault() - handleForm("#route_name", "#route_published_name") + formHelper.handleForm("#route_name", "#route_published_name") } - handleStopPoints(event, state) + formHelper.handleStopPoints(event, state) }) diff --git a/app/javascript/routes/components/BSelect2.js b/app/javascript/routes/components/BSelect2.js index 5cc9561e9..340d9df95 100644 --- a/app/javascript/routes/components/BSelect2.js +++ b/app/javascript/routes/components/BSelect2.js @@ -1,6 +1,6 @@ import _ from'lodash' import React, { Component, PropTypes } from 'react' -import Select2 from 'react-select2-wrapper' +import Select2 from 'react-select2' // get JSON full path @@ -8,7 +8,7 @@ var origin = window.location.origin var path = window.location.pathname.split('/', 3).join('/') -class BSelect3 extends Component{ +export default class BSelect3 extends Component { constructor(props, context) { super(props, context) } @@ -72,7 +72,7 @@ class BSelect3 extends Component{ } } -export default class BSelect2 extends Component{ +class BSelect2 extends Component{ componentDidMount() { this.refs.newSelect.el.select2('open') } diff --git a/app/javascript/routes/reducers/stopPoints.js b/app/javascript/routes/reducers/stopPoints.js index 25679e747..eeec06327 100644 --- a/app/javascript/routes/reducers/stopPoints.js +++ b/app/javascript/routes/reducers/stopPoints.js @@ -1,5 +1,5 @@ import _ from 'lodash' -import { addInput } from '../form_helper' +import formHelper from '../form_helper' const stopPoint = (state = {}, action, length) => { switch (action.type) { @@ -23,8 +23,8 @@ const stopPoint = (state = {}, action, length) => { const updateFormForDeletion = (stop) =>{ if (stop.stoppoint_id !== undefined){ let now = Date.now() - addInput('id', stop.stoppoint_id, now) - addInput('_destroy', 'true', now) + formHelper.addInput('id', stop.stoppoint_id, now) + formHelper.addInput('_destroy', 'true', now) } } diff --git a/app/javascript/time_tables/components/TagsSelect2.js b/app/javascript/time_tables/components/TagsSelect2.js index 24f473f42..22dc7aa9c 100644 --- a/app/javascript/time_tables/components/TagsSelect2.js +++ b/app/javascript/time_tables/components/TagsSelect2.js @@ -1,6 +1,6 @@ import React, { PropTypes, Component } from 'react' import _ from 'lodash' -import Select2 from 'react-select2-wrapper' +import Select2 from 'react-select2' // get JSON full path let origin = window.location.origin diff --git a/app/javascript/vehicle_journeys/components/tools/select2s/CompanySelect2.js b/app/javascript/vehicle_journeys/components/tools/select2s/CompanySelect2.js index 03272e8b4..9c259630d 100644 --- a/app/javascript/vehicle_journeys/components/tools/select2s/CompanySelect2.js +++ b/app/javascript/vehicle_journeys/components/tools/select2s/CompanySelect2.js @@ -1,6 +1,6 @@ import _ from 'lodash' import React, { PropTypes, Component } from 'react' -import Select2 from 'react-select2-wrapper' +import Select2 from 'react-select2' // get JSON full path let origin = window.location.origin diff --git a/app/javascript/vehicle_journeys/components/tools/select2s/MissionSelect2.js b/app/javascript/vehicle_journeys/components/tools/select2s/MissionSelect2.js index bf00a9d96..e4abdd651 100644 --- a/app/javascript/vehicle_journeys/components/tools/select2s/MissionSelect2.js +++ b/app/javascript/vehicle_journeys/components/tools/select2s/MissionSelect2.js @@ -1,6 +1,6 @@ import _ from 'lodash' import React, { PropTypes, Component } from 'react' -import Select2 from 'react-select2-wrapper' +import Select2 from 'react-select2' import actions from '../../../actions' // get JSON full path diff --git a/app/javascript/vehicle_journeys/components/tools/select2s/TimetableSelect2.js b/app/javascript/vehicle_journeys/components/tools/select2s/TimetableSelect2.js index 8463965b9..606bf8511 100644 --- a/app/javascript/vehicle_journeys/components/tools/select2s/TimetableSelect2.js +++ b/app/javascript/vehicle_journeys/components/tools/select2s/TimetableSelect2.js @@ -1,6 +1,6 @@ import _ from 'lodash' import React, { PropTypes, Component } from 'react' -import Select2 from 'react-select2-wrapper' +import Select2 from 'react-select2' import actions from '../../../actions' // get JSON full path diff --git a/app/javascript/vehicle_journeys/components/tools/select2s/VJSelect2.js b/app/javascript/vehicle_journeys/components/tools/select2s/VJSelect2.js index 34273fcf6..e1af8816d 100644 --- a/app/javascript/vehicle_journeys/components/tools/select2s/VJSelect2.js +++ b/app/javascript/vehicle_journeys/components/tools/select2s/VJSelect2.js @@ -1,6 +1,6 @@ import _ from 'lodash' import React, { PropTypes, Component } from 'react' -import Select2 from 'react-select2-wrapper' +import Select2 from 'react-select2' import actions from '../../../actions' // get JSON full path -- cgit v1.2.3 From 91af53dce7183146f79313df48f7e58b4d950598 Mon Sep 17 00:00:00 2001 From: cedricnjanga Date: Tue, 10 Oct 2017 01:23:01 +0200 Subject: Add plugins to webpack config --- app/javascript/time_tables/actions/index.js | 24 +++++----- app/javascript/time_tables/components/Navigate.js | 4 +- .../time_tables/components/PeriodForm.js | 4 +- .../time_tables/components/SaveTimetable.js | 1 - .../time_tables/components/TagsSelect2.js | 13 +++--- .../time_tables/containers/PeriodForm.js | 4 +- app/javascript/time_tables/reducers/metas.js | 19 ++++---- app/javascript/time_tables/reducers/modal.js | 26 +++++------ app/javascript/time_tables/reducers/pagination.js | 12 ++--- app/javascript/time_tables/reducers/status.js | 8 ++-- app/javascript/time_tables/reducers/timetable.js | 51 ++++++++++++---------- 11 files changed, 88 insertions(+), 78 deletions(-) (limited to 'app/javascript') diff --git a/app/javascript/time_tables/actions/index.js b/app/javascript/time_tables/actions/index.js index 5a02e8523..13cb96b64 100644 --- a/app/javascript/time_tables/actions/index.js +++ b/app/javascript/time_tables/actions/index.js @@ -1,10 +1,14 @@ -import _ from 'lodash' +import range from 'lodash/range' +import assign from 'lodash/assign' +import reject from 'lodash/reject' +import some from 'lodash/some' +import every from 'lodash/every' import clone from '../../helpers/clone' const I18n = clone(window, "I18n") const actions = { weekDays: (index) => { - return _.range(1, 8).map(n => I18n.time_tables.edit.metas.days[n]) + return range(1, 8).map(n => I18n.time_tables.edit.metas.days[n]) }, strToArrayDayTypes: (str) =>{ return actions.weekDays().map(day => str.indexOf(day) !== -1) @@ -151,7 +155,7 @@ const actions = { type : 'CLOSE_MODAL' }), monthName(strDate) { - let monthList = _.range(1,13).map(n => I18n.calendars.months[n]) + let monthList = range(1,13).map(n => I18n.calendars.months[n]) let date = new Date(strDate) return monthList[date.getMonth()] }, @@ -172,12 +176,12 @@ const actions = { return date.toLocaleDateString() }, updateSynthesis: ({current_month, time_table_dates: dates, time_table_periods: periods}) => { - let newPeriods = _.reject(periods, 'deleted') + let newPeriods = reject(periods, 'deleted') let improvedCM = current_month.map((d, i) => { let isInPeriod = actions.isInPeriod(newPeriods, d.date) - let isIncluded = _.some(dates, {'date': d.date, 'in_out': true}) + let isIncluded = some(dates, {'date': d.date, 'in_out': true}) - return _.assign({}, current_month[i], { + return assign({}, current_month[i], { in_periods: isInPeriod, include_date: isIncluded, excluded_date: !isInPeriod ? false : current_month[i].excluded_date @@ -271,8 +275,8 @@ const actions = { submitTimetable: (dispatch, timetable, metas, next) => { dispatch(actions.fetchingApi()) let strDayTypes = actions.arrayToStrDayTypes(metas.day_types) - metas.day_types= strDayTypes - let sentState = _.assign({}, timetable, metas) + metas.day_types = strDayTypes + let sentState = assign({}, timetable, metas) let urlJSON = window.location.pathname.split('/', 5).join('/') let hasError = false fetch(urlJSON + '.json', { @@ -302,8 +306,8 @@ const actions = { }) }, errorModalKey: (periods, dayTypes) => { - const withoutPeriodsWithDaysTypes = _.reject(periods, 'deleted').length == 0 && _.some(dayTypes) && "withoutPeriodsWithDaysTypes" - const withPeriodsWithoutDayTypes = _.reject(periods, 'deleted').length > 0 && _.every(dayTypes, dt => dt == false) && "withPeriodsWithoutDayTypes" + const withoutPeriodsWithDaysTypes = reject(periods, 'deleted').length == 0 && some(dayTypes) && "withoutPeriodsWithDaysTypes" + const withPeriodsWithoutDayTypes = reject(periods, 'deleted').length > 0 && every(dayTypes, dt => dt == false) && "withPeriodsWithoutDayTypes" return (withoutPeriodsWithDaysTypes || withPeriodsWithoutDayTypes) && (withoutPeriodsWithDaysTypes ? "withoutPeriodsWithDaysTypes" : "withPeriodsWithoutDayTypes") diff --git a/app/javascript/time_tables/components/Navigate.js b/app/javascript/time_tables/components/Navigate.js index 6ae80bce0..7307d819b 100644 --- a/app/javascript/time_tables/components/Navigate.js +++ b/app/javascript/time_tables/components/Navigate.js @@ -1,5 +1,5 @@ import React, { PropTypes, Component } from 'react' -import _ from 'lodash' +import map from 'lodash/map' import actions from '../actions' export default function Navigate({ dispatch, metas, timetable, pagination, status, filters}) { @@ -30,7 +30,7 @@ export default function Navigate({ dispatch, metas, timetable, pagination, statu className='dropdown-menu' aria-labelledby='date_selector' > - {_.map(pagination.periode_range, (month, i) => ( + {map(pagination.periode_range, (month, i) => (
  • diff --git a/app/javascript/time_tables/components/SaveTimetable.js b/app/javascript/time_tables/components/SaveTimetable.js index 0dffc7936..d5a57bd1c 100644 --- a/app/javascript/time_tables/components/SaveTimetable.js +++ b/app/javascript/time_tables/components/SaveTimetable.js @@ -1,5 +1,4 @@ import React, { PropTypes, Component } from 'react' -import _ from 'lodash' import actions from '../actions' export default class SaveTimetable extends Component{ diff --git a/app/javascript/time_tables/components/TagsSelect2.js b/app/javascript/time_tables/components/TagsSelect2.js index 22dc7aa9c..70a748a04 100644 --- a/app/javascript/time_tables/components/TagsSelect2.js +++ b/app/javascript/time_tables/components/TagsSelect2.js @@ -1,5 +1,8 @@ import React, { PropTypes, Component } from 'react' -import _ from 'lodash' +import mapKeys from 'lodash/mapKeys' +import map from 'lodash/map' +import filter from 'lodash/filter' +import assign from 'lodash/assign' import Select2 from 'react-select2' // get JSON full path @@ -13,7 +16,7 @@ export default class TagsSelect2 extends Component { mapKeys(array){ return array.map((item) => - _.mapKeys(item, (v, k) => + mapKeys(item, (v, k) => ((k == 'name') ? 'text' : k) ) ) @@ -22,7 +25,7 @@ export default class TagsSelect2 extends Component { render() { return ( this.props.onSelect2Tags(e)} onUnselect={(e) => setTimeout( () => this.props.onUnselect2Tags(e, 150))} @@ -47,10 +50,10 @@ export default class TagsSelect2 extends Component { }; }, processResults: function(data, params) { - let items = _.filter(data, ({name}) => name.includes(params.term) ) + let items = filter(data, ({name}) => name.includes(params.term) ) return { results: items.map( - item => _.assign( + item => assign( {}, item, {text: item.name} diff --git a/app/javascript/time_tables/containers/PeriodForm.js b/app/javascript/time_tables/containers/PeriodForm.js index 49e79f348..1bde039e2 100644 --- a/app/javascript/time_tables/containers/PeriodForm.js +++ b/app/javascript/time_tables/containers/PeriodForm.js @@ -1,5 +1,5 @@ import { connect } from 'react-redux' -import _ from 'lodash' +import assign from 'lodash/assign' import actions from '../actions' import PeriodFormComponent from '../components/PeriodForm' @@ -23,7 +23,7 @@ const mapDispatchToProps = (dispatch) => { }, onUpdatePeriodForm: (e, group, selectType, modalProps) => { dispatch(actions.updatePeriodForm(e.currentTarget.value, group, selectType)) - let mProps = _.assign({}, modalProps) + let mProps = assign({}, modalProps) mProps[group][selectType] = e.currentTarget.value let val = window.correctDay([parseInt(mProps[group]['day']), parseInt(mProps[group]['month']), parseInt(mProps[group]['year'])]) val = (val < 10) ? '0' + String(val) : String(val) diff --git a/app/javascript/time_tables/reducers/metas.js b/app/javascript/time_tables/reducers/metas.js index 548798012..51e1ec149 100644 --- a/app/javascript/time_tables/reducers/metas.js +++ b/app/javascript/time_tables/reducers/metas.js @@ -1,10 +1,11 @@ -import _ from 'lodash' +import assign from 'lodash/assign' +import filter from 'lodash/filter' import actions from '../actions' export default function metas(state = {}, action) { switch (action.type) { case 'RECEIVE_TIME_TABLES': - return _.assign({}, state, { + return assign({}, state, { comment: action.json.comment, day_types: actions.strToArrayDayTypes(action.json.day_types), tags: action.json.tags, @@ -14,26 +15,26 @@ export default function metas(state = {}, action) { }) case 'RECEIVE_MONTH': let dt = (typeof state.day_types === 'string') ? actions.strToArrayDayTypes(state.day_types) : state.day_types - return _.assign({}, state, {day_types: dt}) + return assign({}, state, {day_types: dt}) case 'ADD_INCLUDED_DATE': case 'REMOVE_INCLUDED_DATE': case 'ADD_EXCLUDED_DATE': case 'REMOVE_EXCLUDED_DATE': case 'DELETE_PERIOD': case 'VALIDATE_PERIOD_FORM': - return _.assign({}, state, {calendar: null}) + return assign({}, state, {calendar: null}) case 'UPDATE_DAY_TYPES': - return _.assign({}, state, {day_types: action.dayTypes, calendar : null}) + return assign({}, state, {day_types: action.dayTypes, calendar : null}) case 'UPDATE_COMMENT': - return _.assign({}, state, {comment: action.comment}) + return assign({}, state, {comment: action.comment}) case 'UPDATE_COLOR': - return _.assign({}, state, {color: action.color}) + return assign({}, state, {color: action.color}) case 'UPDATE_SELECT_TAG': let tags = [...state.tags] tags.push(action.selectedItem) - return _.assign({}, state, {tags: tags}) + return assign({}, state, {tags: tags}) case 'UPDATE_UNSELECT_TAG': - return _.assign({}, state, {tags: _.filter(state.tags, (t) => (t.id != action.selectedItem.id))}) + return assign({}, state, {tags: filter(state.tags, (t) => (t.id != action.selectedItem.id))}) default: return state } diff --git a/app/javascript/time_tables/reducers/modal.js b/app/javascript/time_tables/reducers/modal.js index a530b2717..5e870a6ef 100644 --- a/app/javascript/time_tables/reducers/modal.js +++ b/app/javascript/time_tables/reducers/modal.js @@ -1,4 +1,4 @@ -import _ from 'lodash' +import assign from 'lodash/assign' import actions from '../actions' let newModalProps = {} @@ -13,7 +13,7 @@ export default function modal(state = {}, action) { switch (action.type) { case 'OPEN_CONFIRM_MODAL': $('#ConfirmModal').modal('show') - return _.assign({}, state, { + return assign({}, state, { type: 'confirm', confirmModal: { callback: action.callback, @@ -21,14 +21,14 @@ export default function modal(state = {}, action) { }) case 'OPEN_ERROR_MODAL': $('#ErrorModal').modal('show') - newModalProps = _.assign({}, state.modalProps, {error: action.error}) - return _.assign({}, state, {type: 'error'}, {modalProps: newModalProps}) + newModalProps = assign({}, state.modalProps, {error: action.error}) + return assign({}, state, {type: 'error'}, {modalProps: newModalProps}) case 'RESET_MODAL_ERRORS': - newModalProps = _.assign({}, state.modalProps, {error: ''}) - return _.assign({}, state, {type: ''}, {modalProps: newModalProps}) + newModalProps = assign({}, state.modalProps, {error: ''}) + return assign({}, state, {type: ''}, {modalProps: newModalProps}) case 'CLOSE_PERIOD_FORM': - newModalProps = _.assign({}, state.modalProps, {active: false, error: ""}) - return _.assign({}, state, {modalProps: newModalProps}) + newModalProps = assign({}, state.modalProps, {active: false, error: ""}) + return assign({}, state, {modalProps: newModalProps}) case 'OPEN_EDIT_PERIOD_FORM': period_start = action.period.period_start.split('-') period_end = action.period.period_end.split('-') @@ -45,19 +45,19 @@ export default function modal(state = {}, action) { newModalProps.active = true newModalProps.index = action.index newModalProps.error = '' - return _.assign({}, state, {modalProps: newModalProps}) + return assign({}, state, {modalProps: newModalProps}) case 'OPEN_ADD_PERIOD_FORM': - newModalProps = _.assign({}, state.modalProps, {active: true, begin: emptyDate, end: emptyDate, index: false, error: ''}) - return _.assign({}, state, {modalProps: newModalProps}) + newModalProps = assign({}, state.modalProps, {active: true, begin: emptyDate, end: emptyDate, index: false, error: ''}) + return assign({}, state, {modalProps: newModalProps}) case 'UPDATE_PERIOD_FORM': newModalProps = JSON.parse(JSON.stringify(state.modalProps)) newModalProps[action.group][action.selectType] = action.val - return _.assign({}, state, {modalProps: newModalProps}) + return assign({}, state, {modalProps: newModalProps}) case 'VALIDATE_PERIOD_FORM': newModalProps = JSON.parse(JSON.stringify(state.modalProps)) newModalProps.error = action.error newModalProps.active = (newModalProps.error == '') ? false : true - return _.assign({}, state, {modalProps: newModalProps}) + return assign({}, state, {modalProps: newModalProps}) default: return state } diff --git a/app/javascript/time_tables/reducers/pagination.js b/app/javascript/time_tables/reducers/pagination.js index e9ca9e1ec..53a753356 100644 --- a/app/javascript/time_tables/reducers/pagination.js +++ b/app/javascript/time_tables/reducers/pagination.js @@ -1,25 +1,25 @@ -import _ from 'lodash' +import assign from 'lodash/assign' export default function pagination(state = {}, action) { switch (action.type) { case 'RECEIVE_TIME_TABLES': - return _.assign({}, state, { + return assign({}, state, { currentPage: action.json.current_periode_range, periode_range: action.json.periode_range, stateChanged: false }) case 'RECEIVE_MONTH': case 'RECEIVE_ERRORS': - return _.assign({}, state, {stateChanged: false}) + return assign({}, state, {stateChanged: false}) case 'GO_TO_PREVIOUS_PAGE': case 'GO_TO_NEXT_PAGE': let nextPage = action.nextPage ? 1 : -1 let newPage = action.pagination.periode_range[action.pagination.periode_range.indexOf(action.pagination.currentPage) + nextPage] toggleOnConfirmModal() - return _.assign({}, state, {currentPage : newPage, stateChanged: false}) + return assign({}, state, {currentPage : newPage, stateChanged: false}) case 'CHANGE_PAGE': toggleOnConfirmModal() - return _.assign({}, state, {currentPage : action.page, stateChanged: false}) + return assign({}, state, {currentPage : action.page, stateChanged: false}) case 'ADD_INCLUDED_DATE': case 'REMOVE_INCLUDED_DATE': case 'ADD_EXCLUDED_DATE': @@ -31,7 +31,7 @@ export default function pagination(state = {}, action) { case 'UPDATE_DAY_TYPES': case 'UPDATE_CURRENT_MONTH_FROM_DAYTYPES': toggleOnConfirmModal('modal') - return _.assign({}, state, {stateChanged: true}) + return assign({}, state, {stateChanged: true}) default: return state } diff --git a/app/javascript/time_tables/reducers/status.js b/app/javascript/time_tables/reducers/status.js index 8d93bc2e2..256059191 100644 --- a/app/javascript/time_tables/reducers/status.js +++ b/app/javascript/time_tables/reducers/status.js @@ -1,14 +1,14 @@ -import _ from 'lodash' +import assign from 'lodash/assign' export default function status(state = {}, action) { switch (action.type) { case 'UNAVAILABLE_SERVER': - return _.assign({}, state, {fetchSuccess: false}) + return assign({}, state, {fetchSuccess: false}) case 'FETCH_API': - return _.assign({}, state, {isFetching: true}) + return assign({}, state, {isFetching: true}) case 'RECEIVE_TIME_TABLES': case 'RECEIVE_MONTH': - return _.assign({}, state, {fetchSuccess: true, isFetching: false}) + return assign({}, state, {fetchSuccess: true, isFetching: false}) default: return state } diff --git a/app/javascript/time_tables/reducers/timetable.js b/app/javascript/time_tables/reducers/timetable.js index 274153a69..21ca1efed 100644 --- a/app/javascript/time_tables/reducers/timetable.js +++ b/app/javascript/time_tables/reducers/timetable.js @@ -1,34 +1,37 @@ -import _ from 'lodash' +import assign from 'lodash/assign' +import reject from 'lodash/reject' +import sortBy from 'lodash/sortBy' +import reduce from 'lodash/reduce' import actions from '../actions' let newState, newPeriods, newDates, newCM export default function timetable(state = {}, action) { switch (action.type) { case 'RECEIVE_TIME_TABLES': - let fetchedState = _.assign({}, state, { + let fetchedState = assign({}, state, { current_month: action.json.current_month, current_periode_range: action.json.current_periode_range, periode_range: action.json.periode_range, time_table_periods: action.json.time_table_periods, - time_table_dates: _.sortBy(action.json.time_table_dates, ['date']) + time_table_dates: sortBy(action.json.time_table_dates, ['date']) }) - return _.assign({}, fetchedState, {current_month: actions.updateSynthesis(fetchedState)}) + return assign({}, fetchedState, {current_month: actions.updateSynthesis(fetchedState)}) case 'RECEIVE_MONTH': - newState = _.assign({}, state, { + newState = assign({}, state, { current_month: action.json.days }) - return _.assign({}, newState, {current_month: actions.updateSynthesis(newState)}) + return assign({}, newState, {current_month: actions.updateSynthesis(newState)}) case 'GO_TO_PREVIOUS_PAGE': case 'GO_TO_NEXT_PAGE': let nextPage = action.nextPage ? 1 : -1 let newPage = action.pagination.periode_range[action.pagination.periode_range.indexOf(action.pagination.currentPage) + nextPage] $('#ConfirmModal').modal('hide') actions.fetchTimeTables(action.dispatch, newPage) - return _.assign({}, state, {current_periode_range: newPage}) + return assign({}, state, {current_periode_range: newPage}) case 'CHANGE_PAGE': $('#ConfirmModal').modal('hide') actions.fetchTimeTables(action.dispatch, action.page) - return _.assign({}, state, {current_periode_range: action.page}) + return assign({}, state, {current_periode_range: action.page}) case 'DELETE_PERIOD': newPeriods = state.time_table_periods.map((period, i) =>{ if(i == action.index){ @@ -37,45 +40,45 @@ export default function timetable(state = {}, action) { return period }) let deletedPeriod = Array.of(state.time_table_periods[action.index]) - newDates = _.reject(state.time_table_dates, d => actions.isInPeriod(deletedPeriod, d.date) && !d.in_out) - newState = _.assign({}, state, {time_table_periods : newPeriods, time_table_dates: newDates}) - return _.assign({}, newState, { current_month: actions.updateSynthesis(newState)}) + newDates = reject(state.time_table_dates, d => actions.isInPeriod(deletedPeriod, d.date) && !d.in_out) + newState = assign({}, state, {time_table_periods : newPeriods, time_table_dates: newDates}) + return assign({}, newState, { current_month: actions.updateSynthesis(newState)}) case 'ADD_INCLUDED_DATE': newDates = state.time_table_dates.concat({date: action.date, in_out: true}) newCM = state.current_month.map((d, i) => { if (i == action.index) d.include_date = true return d }) - return _.assign({}, state, {current_month: newCM, time_table_dates: newDates}) + return assign({}, state, {current_month: newCM, time_table_dates: newDates}) case 'REMOVE_INCLUDED_DATE': - newDates = _.reject(state.time_table_dates, ['date', action.date]) + newDates = reject(state.time_table_dates, ['date', action.date]) newCM = state.current_month.map((d, i) => { if (i == action.index) d.include_date = false return d }) - return _.assign({}, state, {current_month: newCM, time_table_dates: newDates}) + return assign({}, state, {current_month: newCM, time_table_dates: newDates}) case 'ADD_EXCLUDED_DATE': newDates = state.time_table_dates.concat({date: action.date, in_out: false}) newCM = state.current_month.map((d, i) => { if (i == action.index) d.excluded_date = true return d }) - return _.assign({}, state, {current_month: newCM, time_table_dates: newDates}) + return assign({}, state, {current_month: newCM, time_table_dates: newDates}) case 'REMOVE_EXCLUDED_DATE': - newDates = _.reject(state.time_table_dates, ['date', action.date]) + newDates = reject(state.time_table_dates, ['date', action.date]) newCM = state.current_month.map((d, i) => { if (i == action.index) d.excluded_date = false return d }) - return _.assign({}, state, {current_month: newCM, time_table_dates: newDates}) + return assign({}, state, {current_month: newCM, time_table_dates: newDates}) case 'UPDATE_DAY_TYPES': // We get the week days of the activated day types to reject the out_dates that that are out of newDayTypes - let weekDays = _.reduce(action.dayTypes, (array, dt, i) => { + let weekDays = reduce(action.dayTypes, (array, dt, i) => { if (dt) array.push(i) return array }, []) - newDates = _.reject(state.time_table_dates, (d) => { + newDates = reject(state.time_table_dates, (d) => { let weekDay = new Date(d.date).getDay() if (d.in_out) { @@ -84,9 +87,9 @@ export default function timetable(state = {}, action) { return !weekDays.includes(weekDay) } }) - return _.assign({}, state, {time_table_dates: newDates}) + return assign({}, state, {time_table_dates: newDates}) case 'UPDATE_CURRENT_MONTH_FROM_DAYTYPES': - return _.assign({}, state, {current_month: actions.updateSynthesis(state)}) + return assign({}, state, {current_month: actions.updateSynthesis(state)}) case 'VALIDATE_PERIOD_FORM': if (action.error != '') return state @@ -99,7 +102,7 @@ export default function timetable(state = {}, action) { let updatedPeriod = newPeriods[action.modalProps.index] updatedPeriod.period_start = period_start updatedPeriod.period_end = period_end - newDates = _.reject(state.time_table_dates, d => actions.isInPeriod(newPeriods, d.date) && !d.in_out) + newDates = reject(state.time_table_dates, d => actions.isInPeriod(newPeriods, d.date) && !d.in_out) }else{ let newPeriod = { period_start: period_start, @@ -109,8 +112,8 @@ export default function timetable(state = {}, action) { } newDates = newDates || state.time_table_dates - newState =_.assign({}, state, {time_table_periods: newPeriods, time_table_dates: newDates}) - return _.assign({}, newState, {current_month: actions.updateSynthesis(newState)}) + newState =assign({}, state, {time_table_periods: newPeriods, time_table_dates: newDates}) + return assign({}, newState, {current_month: actions.updateSynthesis(newState)}) default: return state } -- cgit v1.2.3 From 1c8f131301e7efa828f60945273bfb6b16a0e430 Mon Sep 17 00:00:00 2001 From: Guillaume Date: Mon, 16 Oct 2017 17:57:25 +0200 Subject: add jest for js test, fix js test errors, remove unused config in config/environement --- app/javascript/journey_patterns/reducers/journeyPatterns.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'app/javascript') diff --git a/app/javascript/journey_patterns/reducers/journeyPatterns.js b/app/javascript/journey_patterns/reducers/journeyPatterns.js index 7702e21bc..0bbcba976 100644 --- a/app/javascript/journey_patterns/reducers/journeyPatterns.js +++ b/app/javascript/journey_patterns/reducers/journeyPatterns.js @@ -1,7 +1,7 @@ import _ from 'lodash' import actions from "../actions" -export default function journeyPattern(state = {}, action) { +const journeyPattern = (state = {}, action) =>{ switch (action.type) { case 'ADD_JOURNEYPATTERN': let stopPoints = window.stopPoints @@ -33,7 +33,7 @@ export default function journeyPattern(state = {}, action) { } } -const journeyPatterns = (state = [], action) => { +export default function journeyPatterns (state = [], action) { switch (action.type) { case 'RECEIVE_JOURNEY_PATTERNS': return [...action.json] -- cgit v1.2.3