import { type IChartBreakdown, type IChartEvent, type IInterval, } from "@/types"; import { getDaysOldDate } from "@/utils/date"; import { type PayloadAction, createSlice } from "@reduxjs/toolkit"; type InitialState = { events: IChartEvent[]; breakdowns: IChartBreakdown[]; interval: IInterval; startDate: Date; endDate: Date; }; // First approach: define the initial state using that type const initialState: InitialState = { startDate: getDaysOldDate(7), endDate: new Date(), interval: "day", breakdowns: [ { id: "A", name: 'properties.id' } ], events: [ { id: "A", name: "sign_up", filters: [] }, ], }; const IDS = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"] as const; export const reportSlice = createSlice({ name: "counter", initialState, reducers: { // Events addEvent: (state, action: PayloadAction>) => { state.events.push({ id: IDS[state.events.length]!, ...action.payload, }); }, removeEvent: ( state, action: PayloadAction<{ id: string; }>, ) => { state.events = state.events.filter( (event) => event.id !== action.payload.id, ); }, changeEvent: (state, action: PayloadAction) => { state.events = state.events.map((event) => { if (event.id === action.payload.id) { return action.payload; } return event; }); }, // Breakdowns addBreakdown: ( state, action: PayloadAction>, ) => { state.breakdowns.push({ id: IDS[state.breakdowns.length]!, ...action.payload, }); }, removeBreakdown: ( state, action: PayloadAction<{ id: string; }>, ) => { state.breakdowns = state.breakdowns.filter( (event) => event.id !== action.payload.id, ); }, changeBreakdown: (state, action: PayloadAction) => { state.breakdowns = state.breakdowns.map((breakdown) => { if (breakdown.id === action.payload.id) { return action.payload; } return breakdown; }); }, // Interval changeInterval: (state, action: PayloadAction) => { state.interval = action.payload; }, // Date range changeStartDate: (state, action: PayloadAction) => { state.startDate = action.payload; }, // Date range changeEndDate: (state, action: PayloadAction) => { state.endDate = action.payload; }, changeDateRanges: (state, action: PayloadAction) => { if(action.payload === 1) { state.interval = "hour"; } else if(action.payload <= 30) { state.interval = "day"; } else { state.interval = "month"; } state.startDate = getDaysOldDate(action.payload); state.endDate = new Date(); } }, }); // Action creators are generated for each case reducer function export const { addEvent, removeEvent, changeEvent, addBreakdown, removeBreakdown, changeBreakdown, changeInterval, changeDateRanges, } = reportSlice.actions; export default reportSlice.reducer;