Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 3694 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
3719 stevensc 1
import React, { useMemo, useRef, useState } from 'react';
2
import { useDispatch, useSelector } from 'react-redux';
3
import { Box, Grid, MenuItem, Select, styled } from '@mui/material';
4
import Search from '@mui/icons-material/Search';
5
 
6
import { useFetch, useSearchQuery } from '@hooks';
7
import { axios, debounce } from '@utils';
8
import { addNotification } from '@store/notification/notification.actions';
9
 
10
import TitleSection from '@components/UI/TitleSection';
11
import SideMenu from '@components/UI/sidemenu/SideMenu';
12
import Input from '@components/UI/inputs/Input';
13
import QuestionCard from '@components/my-coach/QuestionCard';
14
import EmptySection from '@components/UI/EmptySection';
15
import QuestionModal from '@components/my-coach/QuestionModal';
16
import ConfirmModal from '@components/modals/ConfirmModal';
17
import Pagination from '@components/common/Pagination';
18
 
19
const QuestionsGrid = styled(Box)`
20
  display: grid;
21
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
22
  gap: 1rem;
23
`;
24
 
25
const MyCoachPage = () => {
26
  const [modalShow, setModalShow] = useState(null);
27
  const actionUrl = useRef('');
28
  const labels = useSelector(({ intl }) => intl.labels);
29
  const dispatch = useDispatch();
30
 
31
  const { getStringParams, getParam, setParam } = useSearchQuery();
32
  const { data: categoriesData } = useFetch(`/my-coach`);
33
  const { data, refetch } = useFetch('/my-coach/questions' + getStringParams());
34
 
35
  const categories = useMemo(() => {
36
    const defaultCategories = [{ name: 'Todas', value: '' }];
37
 
38
    if (!categoriesData.categories) return defaultCategories;
39
 
40
    const results = Object.entries(categoriesData.categories).map(([uuid, name]) => ({
41
      name,
42
      value: uuid
43
    }));
44
 
45
    return defaultCategories.concat(results);
46
  }, [categoriesData]);
47
 
48
  const confirmDelete = () => {
49
    axios
50
      .post(actionUrl.current)
51
      .then((response) => {
52
        const { data, success } = response.data;
53
 
54
        if (!success) {
55
          const errorMessage =
56
            typeof data === 'string' ? data : 'Ha ocurrido un error, por favor intente más tarde.';
57
 
58
          dispatch(addNotification({ style: 'danger', msg: errorMessage }));
59
          return;
60
        }
61
 
62
        dispatch(addNotification({ style: 'success', msg: data }));
63
        refetch();
64
        closeModal();
65
      })
66
      .catch((error) => {
67
        dispatch(addNotification({ style: 'danger', msg: error.message }));
68
      });
69
  };
70
 
71
  const addQuestion = () => {
72
    actionUrl.current = '/my-coach/questions/add';
73
    setModalShow('add');
74
  };
75
 
76
  const editQuestion = (url) => {
77
    actionUrl.current = url;
78
    setModalShow('edit');
79
  };
80
 
81
  const deleteQuestion = (url) => {
82
    actionUrl.current = url;
83
    setModalShow('delete');
84
  };
85
 
86
  const closeModal = () => {
87
    actionUrl.current = '';
88
    setModalShow(null);
89
  };
90
 
91
  const handleInputChange = debounce((value) => setParam('search', value), 500);
92
 
93
  return (
94
    <>
95
      <TitleSection
96
        title={labels.my_coach}
97
        onAdd={() => addQuestion()}
98
        addLabel={labels.my_coach_question_add}
99
      />
100
 
101
      <Grid container spacing={1}>
102
        <Grid size={{ xs: 12, md: 3 }} sx={{ display: { md: 'block', xs: 'none' } }}>
103
          <SideMenu
104
            title='Categorias'
105
            items={categories}
106
            onChange={(value) => setParam('category_id', value)}
107
            current={getParam('category_id')}
108
          />
109
        </Grid>
110
 
111
        <Grid size={{ xs: 12, md: 9 }} sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
112
          <Input
113
            icon={<Search />}
114
            onChange={(e) => handleInputChange(e.target.value)}
115
            placeholder={labels.search}
116
            variant='search'
117
          />
118
 
119
          <Select
120
            name='categories'
121
            options={categories}
122
            onChange={(e) => setParam('category_id', e.target.value)}
123
            sx={{
124
              mt: 1,
125
              mx: 2,
126
              display: { md: 'none', xs: 'block' }
127
            }}
128
          >
129
            {categories.map(({ name, value }) => (
130
              <MenuItem key={value} value={value}>
131
                {name}
132
              </MenuItem>
133
            ))}
134
          </Select>
135
 
136
          <QuestionsGrid className='mt-3'>
137
            {data.items?.length ? (
138
              data.items.map((question) => (
139
                <QuestionCard
140
                  key={question.uuid}
141
                  onEdit={editQuestion}
142
                  onDelete={deleteQuestion}
143
                  {...question}
144
                />
145
              ))
146
            ) : (
147
              <EmptySection message={labels.error_no_record_matched_your_query} />
148
            )}
149
          </QuestionsGrid>
150
 
151
          <Pagination
152
            page={data.page}
153
            pages={data.total_pages}
154
            onChange={(page) => setParam('page', page)}
155
          />
156
        </Grid>
157
      </Grid>
158
 
159
      <QuestionModal
160
        show={['add', 'edit'].includes(modalShow)}
161
        onClose={closeModal}
162
        onComplete={refetch}
163
        url={actionUrl.current}
164
        isEdit={modalShow === 'edit'}
165
      />
166
 
167
      <ConfirmModal show={modalShow === 'delete'} onClose={closeModal} onAccept={confirmDelete} />
168
    </>
169
  );
170
};
171
 
172
export default MyCoachPage;