aboutsummaryrefslogtreecommitdiff
path: root/jb-ui/src/models/cashoutMethodsSlice.ts
blob: 080cb0479a2a7ef7988ddb18ddef2a7f4a892e78 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import { WalletApi, CashoutMethodOut } from "@/api_fsb";
import type { RootState } from "@/store";
import {
  PayloadAction,
  createSlice,
  createEntityAdapter,
} from "@reduxjs/toolkit";
import { bpid } from "@/lib/utils";
import { createAsyncThunk } from "@reduxjs/toolkit";

// Entity adapter for normalized storage
const cashoutMethodsAdapter = createEntityAdapter({
  selectId: (model: CashoutMethodOut) => model.id!,
  sortComparer: (a, b) => {
    return (a.min_value ?? 0) - (b.min_value ?? 0);
  },
});

export const fetchCashoutMethods = createAsyncThunk(
  "cashoutMethodsSlice/fetchCashoutMethods",
  async (bpuid: string) => {
    console.log("cashoutMethodsSlice/fetchCashoutMethods");
    const res =
      await new WalletApi().getCashoutMethodsProductIdCashoutMethodsGet(
        bpid,
        bpuid,
      );
    return res.data.cashout_methods as CashoutMethodOut[];
  },
);

interface CashoutMethodClientState {
  is_active?: boolean;
  is_expanded?: boolean;
}

const withClientDefaults = (method: CashoutMethodOut): CashoutMethodEntity => ({
  ...method,
  is_active: false,
  is_expanded: false,
});

type CashoutMethodEntity = CashoutMethodOut & CashoutMethodClientState;

const cashoutMethodsSlice = createSlice({
  name: "cashoutMethods",
  initialState: cashoutMethodsAdapter.getInitialState(),

  reducers: {
    addCashoutMethod: (state, action: PayloadAction<CashoutMethodOut>) => {
      cashoutMethodsAdapter.addOne(state, withClientDefaults(action.payload));
    },

    addCashoutMethods: (state, action: PayloadAction<CashoutMethodOut[]>) => {
      cashoutMethodsAdapter.addMany(
        state,
        action.payload.map(withClientDefaults),
      );
    },

    upsertCashoutMethod: (state, action: PayloadAction<CashoutMethodOut>) => {
      cashoutMethodsAdapter.upsertOne(
        state,
        withClientDefaults(action.payload),
      );
    },
  },
});

export const { addCashoutMethod, addCashoutMethods, upsertCashoutMethod } =
  cashoutMethodsSlice.actions;

export const cashoutMethodsSelectors = cashoutMethodsAdapter.getSelectors(
  (state: RootState) => state.cashoutMethods,
);

export const selectAllCashoutMethods = (
  state: RootState,
): CashoutMethodOut[] => {
  return cashoutMethodsSelectors.selectAll(state) ?? [];
};

export default cashoutMethodsSlice.reducer;