You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
2.2 KiB

  1. import { createAsyncThunk, createSelector, createSlice, PayloadAction } from '@reduxjs/toolkit';
  2. import { KTJOrg, RailType } from '../../services/apiTypes';
  3. import { labeledKtjOrgs } from '../../utils/helper';
  4. import { ktjOrgs } from '../../utils/constant';
  5. import Bridge from '../../utils/bridge';
  6. import { RootState } from '..';
  7. interface BaseDataState {
  8. ktjOrgs: KTJOrg[];
  9. railTypes: RailType[];
  10. syncingBaseData: boolean;
  11. }
  12. const initialState: BaseDataState = {
  13. ktjOrgs: ktjOrgs as KTJOrg[],
  14. railTypes: [],
  15. syncingBaseData: false,
  16. };
  17. export const fetchRailTypes = createAsyncThunk('base/fetchRailTypes', async (_, thunkAPI) => {
  18. const res = await Bridge.getBasicTrackList();
  19. return res.success ? res.data : null;
  20. });
  21. export const syncBaseData = createAsyncThunk('base/syncBaseData', async () => {
  22. return await Bridge.syncBaseData();
  23. });
  24. export const fetchOrgTree = createAsyncThunk('base/fetchOrgTree', async () => {
  25. return await Bridge.getOrgTree();
  26. });
  27. export const baseDataSlice = createSlice({
  28. name: 'baseData',
  29. initialState,
  30. reducers: {
  31. updateRailTypes: (state, action: PayloadAction<RailType[]>) => {
  32. state.railTypes = action.payload;
  33. },
  34. updateRailPoints: (state, action: PayloadAction<RailType>) => {
  35. const r = state.railTypes.find((r) => r.code === action.payload.code);
  36. if (r) {
  37. r.points = action.payload.points;
  38. r.calPoints = action.payload.calPoints;
  39. }
  40. },
  41. },
  42. extraReducers: (builder) => {
  43. builder.addCase(fetchRailTypes.fulfilled, (state, action) => {
  44. state.railTypes = action.payload || [];
  45. });
  46. builder.addCase(syncBaseData.pending, (state) => {
  47. state.syncingBaseData = true;
  48. });
  49. builder.addCase(syncBaseData.fulfilled, (state) => {
  50. state.syncingBaseData = false;
  51. });
  52. builder.addCase(fetchOrgTree.fulfilled, (state, action) => {
  53. if (action.payload.success) {
  54. state.ktjOrgs = action.payload.data;
  55. }
  56. });
  57. },
  58. });
  59. export const { updateRailPoints } = baseDataSlice.actions;
  60. export default baseDataSlice.reducer;
  61. export const selectKtjOrgs = (state: RootState) => state.baseData.ktjOrgs;
  62. export const selectLabeledKtjOrgs = createSelector(selectKtjOrgs, (orgs) => {
  63. return labeledKtjOrgs(orgs);
  64. });