saleStatisticsReducer.js 2.22 KB
/**
 * # guideReducer.js
 *
 * The reducer for all the actions from the various log states
 */
'use strict';
/**
 * ## Imports
 *
 * InitialState
 */
import InitialState from './saleStatisticsInitialState';

import Immutable, {List, Record} from 'immutable';
import moment from 'moment';

const {

	SALE_STATS_REQUEST,
	SALE_STATS_SUCCESS,
	SALE_STATS_FAILURE,

	SWITCH_SHOP,
	LOGOUT,

} = require('../../constants/actionTypes').default;

const initialState = new InitialState;

/**
 * ## guideReducer function
 * @param {Object} state - initialState
 * @param {Object} action - type and payload
 */
export default function saleStatisticsReducer(state = initialState, action) {
    if (!(state instanceof InitialState)) return initialState.merge(state);

    switch (action.type) {

		case SALE_STATS_REQUEST: {
			let nextState =  state.set('isFetching', true)
				.set('error', null)
			return nextState;
		}

		case SALE_STATS_SUCCESS: {
			let {list, additionInfo} = action.payload;
			let sevenDays = [];
			let trendInSevenDays = [];
			if (list) {
				for (let i = 0; i < list.length; i++) {
					let item = action.payload.list[i];
					sevenDays.push(moment(item.dateId).format('MM.DD'));
					trendInSevenDays.push(item.allNums);
				}
			}

			let amountRate = additionInfo.allAmountRate || 0;
			let countRate = additionInfo.allNumberRate || 0;
			let amountHasTrendData = additionInfo.allAmountRateFlag;
			let countHasTrendData = additionInfo.allNumberRateFlag;

			let nextState =  state.set('isFetching', false)
				.set('error', null)
				.set('goodsAmount', additionInfo.allAmount || 0)
				.set('amountHasTrendData', amountHasTrendData)
				.set('amountRise', amountRate >= 0)
				.set('amountRisePercent', Math.abs(amountRate))
				.set('goodsCount', additionInfo.allNumber || 0)
				.set('countHasTrendData', countHasTrendData)
				.set('countRise', countRate >= 0)
				.set('countRisePercent', Math.abs(countRate))
				.set('sevenDays', Immutable.fromJS(sevenDays))
				.set('trendInSevenDays', Immutable.fromJS(trendInSevenDays));
			return nextState;
		}

		case SALE_STATS_FAILURE:
	    	return state.set('isFetching', false)
	      		.set('error', action.payload);

		case SWITCH_SHOP:
		case LOGOUT:
			return initialState;
    }

    return state;
}