import { createReducer, createAction } from '@reduxjs/toolkit'; import { DayEarning } from '@app-types/index'; import { mockWeeklyEarnings, mockTodayEarnings } from '../../mockData/mockEarnings'; import { getTodayEarningsThunk, getWeeklyEarningsThunk } from './thunk'; export interface EarningsState { todayEarnings: number; completedCount: number; onlineMinutes: number; weeklyData: DayEarning[]; loading: boolean; error: string | null; } const initialState: EarningsState = { todayEarnings: mockTodayEarnings.total, completedCount: mockTodayEarnings.completedCount, onlineMinutes: mockTodayEarnings.onlineMinutes, weeklyData: mockWeeklyEarnings, loading: false, error: null, }; export const addEarning = createAction('earnings/addEarning'); export const setEarnings = createAction>('earnings/setEarnings'); export const incrementOnlineMinutes = createAction('earnings/incrementOnlineMinutes'); export const resetTodayEarnings = createAction('earnings/resetTodayEarnings'); export const earningsReducer = createReducer(initialState, (builder) => { builder // Sync Actions .addCase(addEarning, (state, action) => { state.todayEarnings += action.payload; state.completedCount += 1; }) .addCase(setEarnings, (state, action) => { return { ...state, ...action.payload }; }) .addCase(incrementOnlineMinutes, (state) => { state.onlineMinutes += 1; }) .addCase(resetTodayEarnings, (state) => { state.todayEarnings = 0; state.completedCount = 0; state.onlineMinutes = 0; }) // Async Thunks .addCase(getTodayEarningsThunk.pending, (state) => { state.loading = true; state.error = null; }) .addCase(getTodayEarningsThunk.fulfilled, (state, action) => { state.loading = false; state.todayEarnings = action.payload.total; state.completedCount = action.payload.completedCount; state.onlineMinutes = action.payload.onlineMinutes; }) .addCase(getTodayEarningsThunk.rejected, (state, action) => { state.loading = false; state.error = action.payload as string; }) .addCase(getWeeklyEarningsThunk.pending, (state) => { state.loading = true; state.error = null; }) .addCase(getWeeklyEarningsThunk.fulfilled, (state, action) => { state.loading = false; state.weeklyData = action.payload; }) .addCase(getWeeklyEarningsThunk.rejected, (state, action) => { state.loading = false; state.error = action.payload as string; }); });