2023-02-18 12:40:37 +03:00
|
|
|
import type { PayloadAction } from '@reduxjs/toolkit';
|
|
|
|
import { createSlice } from '@reduxjs/toolkit';
|
|
|
|
import type { ShlinkApiClientBuilder } from '../../api/services/ShlinkApiClientBuilder';
|
2023-02-18 13:11:01 +03:00
|
|
|
import type { ShlinkVisitsOverview } from '../../api/types';
|
2022-11-11 22:23:19 +03:00
|
|
|
import { createAsyncThunk } from '../../utils/helpers/redux';
|
2021-02-27 22:03:51 +03:00
|
|
|
import { groupNewVisitsByType } from '../types/helpers';
|
2022-11-11 22:23:19 +03:00
|
|
|
import { createNewVisits } from './visitCreation';
|
2020-12-07 14:12:39 +03:00
|
|
|
|
2022-11-11 22:23:19 +03:00
|
|
|
const REDUCER_PREFIX = 'shlink/visitsOverview';
|
2020-12-07 14:12:39 +03:00
|
|
|
|
|
|
|
export interface VisitsOverview {
|
|
|
|
visitsCount: number;
|
2022-05-02 20:28:07 +03:00
|
|
|
orphanVisitsCount: number;
|
2020-12-07 14:12:39 +03:00
|
|
|
loading: boolean;
|
|
|
|
error: boolean;
|
|
|
|
}
|
|
|
|
|
2022-11-11 22:23:19 +03:00
|
|
|
export type GetVisitsOverviewAction = PayloadAction<ShlinkVisitsOverview>;
|
2020-12-07 14:12:39 +03:00
|
|
|
|
|
|
|
const initialState: VisitsOverview = {
|
|
|
|
visitsCount: 0,
|
2021-02-21 22:55:39 +03:00
|
|
|
orphanVisitsCount: 0,
|
2020-12-07 14:12:39 +03:00
|
|
|
loading: false,
|
|
|
|
error: false,
|
|
|
|
};
|
|
|
|
|
2022-11-11 22:23:19 +03:00
|
|
|
export const loadVisitsOverview = (buildShlinkApiClient: ShlinkApiClientBuilder) => createAsyncThunk(
|
|
|
|
`${REDUCER_PREFIX}/loadVisitsOverview`,
|
|
|
|
(_: void, { getState }): Promise<ShlinkVisitsOverview> => buildShlinkApiClient(getState).getVisitsOverview(),
|
|
|
|
);
|
|
|
|
|
|
|
|
export const visitsOverviewReducerCreator = (
|
|
|
|
loadVisitsOverviewThunk: ReturnType<typeof loadVisitsOverview>,
|
|
|
|
) => createSlice({
|
|
|
|
name: REDUCER_PREFIX,
|
|
|
|
initialState,
|
|
|
|
reducers: {},
|
|
|
|
extraReducers: (builder) => {
|
|
|
|
builder.addCase(loadVisitsOverviewThunk.pending, () => ({ ...initialState, loading: true }));
|
|
|
|
builder.addCase(loadVisitsOverviewThunk.rejected, () => ({ ...initialState, error: true }));
|
|
|
|
builder.addCase(loadVisitsOverviewThunk.fulfilled, (_, { payload }) => ({ ...initialState, ...payload }));
|
|
|
|
|
|
|
|
builder.addCase(createNewVisits, ({ visitsCount, orphanVisitsCount = 0, ...rest }, { payload }) => {
|
|
|
|
const { createdVisits } = payload;
|
|
|
|
const { regularVisits, orphanVisits } = groupNewVisitsByType(createdVisits);
|
|
|
|
return {
|
|
|
|
...rest,
|
|
|
|
visitsCount: visitsCount + regularVisits.length,
|
|
|
|
orphanVisitsCount: orphanVisitsCount + orphanVisits.length,
|
|
|
|
};
|
|
|
|
});
|
2021-02-27 22:03:51 +03:00
|
|
|
},
|
2022-11-11 22:23:19 +03:00
|
|
|
});
|