contentoh-components-library 21.3.19 → 21.3.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. package/.env.development +5 -0
  2. package/.env.production +2 -2
  3. package/dist/assets/images/customSelect/starIcon.svg +14 -0
  4. package/dist/assets/images/defaultImages/Spinner.gif +0 -0
  5. package/dist/assets/images/defaultImages/notFound.svg +124 -0
  6. package/dist/assets/images/generalButton/closeIcon.svg +2 -2
  7. package/dist/assets/sounds/newMessage.mp3 +0 -0
  8. package/dist/components/atoms/ButtonFileChooser/ButtonFileChooser.stories.js +72 -0
  9. package/dist/components/atoms/ButtonFileChooser/index.js +110 -0
  10. package/dist/components/atoms/ButtonFileChooser/styles.js +20 -0
  11. package/dist/components/atoms/ButtonV2/ButtonV2.stories.js +66 -0
  12. package/dist/components/atoms/ButtonV2/index.js +110 -0
  13. package/dist/components/atoms/ButtonV2/styles.js +53 -0
  14. package/dist/components/atoms/CustomIcon/CustomIcon.stories.js +50 -0
  15. package/dist/components/atoms/CustomIcon/index.js +40 -0
  16. package/dist/components/atoms/CustomIcon/styles.js +33 -0
  17. package/dist/components/atoms/IconFile/IconFile.stories.js +48 -0
  18. package/dist/components/atoms/IconFile/index.js +249 -0
  19. package/dist/components/atoms/IconFile/styles.js +23 -0
  20. package/dist/components/atoms/Image/Image.stories.js +73 -0
  21. package/dist/components/atoms/Image/index.js +76 -0
  22. package/dist/components/atoms/Image/styles.js +43 -0
  23. package/dist/components/atoms/ImageLink/ImageLink.stories.js +63 -0
  24. package/dist/components/atoms/ImageLink/index.js +77 -0
  25. package/dist/components/atoms/ImageLink/styles.js +40 -0
  26. package/dist/components/atoms/ImagePreview/ImagePreview.stories.js +70 -0
  27. package/dist/components/atoms/ImagePreview/index.js +208 -0
  28. package/dist/components/atoms/ImagePreview/styles.js +44 -0
  29. package/dist/components/atoms/InputText/InputText.stories.js +60 -0
  30. package/dist/components/atoms/InputText/index.js +66 -0
  31. package/dist/components/atoms/InputText/styles.js +32 -0
  32. package/dist/components/atoms/NotFound/NotFound.stories.js +36 -0
  33. package/dist/components/atoms/NotFound/index.js +75 -0
  34. package/dist/components/atoms/NotFound/styles.js +20 -0
  35. package/dist/components/atoms/ProgressBar/index.js +36 -6
  36. package/dist/components/atoms/ProgressBar/styles.js +11 -3
  37. package/dist/components/atoms/SelectItemV2/SelectItemV2.stories.js +45 -0
  38. package/dist/components/atoms/SelectItemV2/index.js +57 -0
  39. package/dist/components/atoms/SelectItemV2/styles.js +30 -0
  40. package/dist/components/atoms/Tooltip/Tooltip.stories.js +66 -0
  41. package/dist/components/atoms/Tooltip/index.js +72 -0
  42. package/dist/components/atoms/Tooltip/styles.js +20 -0
  43. package/dist/components/molecules/ButtonDownloadFile/DownloadFile.stories.js +66 -0
  44. package/dist/components/molecules/ButtonDownloadFile/index.js +179 -0
  45. package/dist/components/molecules/ButtonDownloadFile/styles.js +23 -0
  46. package/dist/components/molecules/CustomSelect/CustomSelect.stories.js +21 -22
  47. package/dist/components/molecules/CustomSelect/SelectItem.js +10 -1
  48. package/dist/components/molecules/Dropdown/Dropdown.stories.js +98 -0
  49. package/dist/components/molecules/Dropdown/index.js +150 -0
  50. package/dist/components/molecules/Dropdown/styles.js +26 -0
  51. package/dist/components/molecules/HeaderTop/index.js +23 -6
  52. package/dist/components/molecules/HeaderTop/styles.js +1 -1
  53. package/dist/components/molecules/ImageTooltip/ImageTooltip.stories.js +82 -0
  54. package/dist/components/molecules/ImageTooltip/index.js +85 -0
  55. package/dist/components/molecules/ImageTooltip/styles.js +33 -0
  56. package/dist/components/molecules/ProductNameHeader/index.js +6 -4
  57. package/dist/components/molecules/SelectV2/SelectV2.stories.js +120 -0
  58. package/dist/components/molecules/SelectV2/index.js +306 -0
  59. package/dist/components/molecules/SelectV2/styles.js +42 -0
  60. package/dist/components/molecules/SelectV2/test.js +94 -0
  61. package/dist/components/molecules/SelectV2/test.stories.js +27 -0
  62. package/dist/components/organisms/Chat/Chat.stories.js +160 -0
  63. package/dist/components/organisms/Chat/ChatLists/ChatLists.stories.js +83 -0
  64. package/dist/components/organisms/Chat/ChatLists/index.js +160 -0
  65. package/dist/components/organisms/Chat/ChatLists/styles.js +29 -0
  66. package/dist/components/organisms/Chat/ContainerItems/ContainerItems.stories.js +176 -0
  67. package/dist/components/organisms/Chat/ContainerItems/index.js +537 -0
  68. package/dist/components/organisms/Chat/ContainerItems/styles.js +20 -0
  69. package/dist/components/organisms/Chat/ContentChat/ContentChat.stories.js +142 -0
  70. package/dist/components/organisms/Chat/ContentChat/index.js +1466 -0
  71. package/dist/components/organisms/Chat/ContentChat/styles.js +20 -0
  72. package/dist/components/organisms/Chat/Footer/Footer.stories.js +43 -0
  73. package/dist/components/organisms/Chat/Footer/index.js +976 -0
  74. package/dist/components/organisms/Chat/Footer/styles.js +32 -0
  75. package/dist/components/organisms/Chat/Header/Header.stories.js +96 -0
  76. package/dist/components/organisms/Chat/Header/index.js +83 -0
  77. package/dist/components/organisms/Chat/Header/styles.js +20 -0
  78. package/dist/components/organisms/Chat/index.js +253 -0
  79. package/dist/components/organisms/Chat/styles.js +29 -0
  80. package/dist/components/organisms/FullProductNameHeader/index.js +1 -0
  81. package/dist/components/organisms/Modal/Modal.stories.js +66 -0
  82. package/dist/components/organisms/Modal/index.js +95 -0
  83. package/dist/components/organisms/Modal/styles.js +20 -0
  84. package/dist/components/organisms/RangeCalendar/RangeCalendar.stories.js +33 -0
  85. package/dist/components/organisms/RangeCalendar/index.js +149 -0
  86. package/dist/components/organisms/RangeCalendar/styles.js +27 -0
  87. package/dist/components/pages/ProviderProductEdition/ProviderProductEdition.stories.js +65 -50
  88. package/dist/components/pages/ProviderProductEdition/index.js +15 -11
  89. package/dist/components/pages/RetailerProductEdition/RetailerProductEdition.stories.js +36 -44
  90. package/dist/components/pages/RetailerProductEdition/index.js +13 -12
  91. package/dist/global-files/data.js +18 -23
  92. package/dist/global-files/fonts.css +6 -0
  93. package/dist/global-files/handle_http.js +381 -0
  94. package/dist/global-files/handle_userTech.js +20 -0
  95. package/dist/global-files/utils.js +514 -0
  96. package/dist/global-files/variables.js +2 -0
  97. package/dist/index.js +267 -46
  98. package/package.json +13 -1
  99. package/src/assets/images/customSelect/starIcon.svg +14 -0
  100. package/src/assets/images/defaultImages/Spinner.gif +0 -0
  101. package/src/assets/images/defaultImages/notFound.svg +124 -0
  102. package/src/assets/images/generalButton/closeIcon.svg +2 -2
  103. package/src/assets/sounds/newMessage.mp3 +0 -0
  104. package/src/components/atoms/ButtonFileChooser/ButtonFileChooser.stories.js +47 -0
  105. package/src/components/atoms/ButtonFileChooser/index.js +68 -0
  106. package/src/components/atoms/ButtonFileChooser/styles.js +4 -0
  107. package/src/components/atoms/ButtonV2/ButtonV2.stories.js +53 -0
  108. package/src/components/atoms/ButtonV2/index.js +85 -0
  109. package/src/components/atoms/ButtonV2/styles.js +217 -0
  110. package/src/components/atoms/CustomIcon/CustomIcon.stories.js +36 -0
  111. package/src/components/atoms/CustomIcon/index.js +41 -0
  112. package/src/components/atoms/CustomIcon/styles.js +85 -0
  113. package/src/components/atoms/IconFile/IconFile.stories.js +35 -0
  114. package/src/components/atoms/IconFile/index.js +119 -0
  115. package/src/components/atoms/IconFile/styles.js +67 -0
  116. package/src/components/atoms/Image/Image.stories.js +51 -0
  117. package/src/components/atoms/Image/index.js +55 -0
  118. package/src/components/atoms/Image/styles.js +34 -0
  119. package/src/components/atoms/ImageLink/ImageLink.stories.js +43 -0
  120. package/src/components/atoms/ImageLink/index.js +57 -0
  121. package/src/components/atoms/ImageLink/styles.js +30 -0
  122. package/src/components/atoms/ImagePreview/ImagePreview.stories.js +52 -0
  123. package/src/components/atoms/ImagePreview/index.js +178 -0
  124. package/src/components/atoms/ImagePreview/styles.js +77 -0
  125. package/src/components/atoms/InputText/InputText.stories.js +39 -0
  126. package/src/components/atoms/InputText/index.js +61 -0
  127. package/src/components/atoms/InputText/styles.js +89 -0
  128. package/src/components/atoms/NotFound/NotFound.stories.js +19 -0
  129. package/src/components/atoms/NotFound/index.js +52 -0
  130. package/src/components/atoms/NotFound/styles.js +55 -0
  131. package/src/components/atoms/ProgressBar/index.js +40 -5
  132. package/src/components/atoms/ProgressBar/styles.js +24 -0
  133. package/src/components/atoms/SelectItemV2/SelectItemV2.stories.js +26 -0
  134. package/src/components/atoms/SelectItemV2/index.js +61 -0
  135. package/src/components/atoms/SelectItemV2/styles.js +90 -0
  136. package/src/components/atoms/Tooltip/Tooltip.stories.js +51 -0
  137. package/src/components/atoms/Tooltip/index.js +59 -0
  138. package/src/components/atoms/Tooltip/styles.js +42 -0
  139. package/src/components/molecules/ButtonDownloadFile/DownloadFile.stories.js +54 -0
  140. package/src/components/molecules/ButtonDownloadFile/index.js +109 -0
  141. package/src/components/molecules/ButtonDownloadFile/styles.js +66 -0
  142. package/src/components/molecules/CustomSelect/CustomSelect.stories.js +20 -12
  143. package/src/components/molecules/CustomSelect/SelectItem.js +7 -0
  144. package/src/components/molecules/Dropdown/Dropdown.stories.js +103 -0
  145. package/src/components/molecules/Dropdown/index.js +150 -0
  146. package/src/components/molecules/Dropdown/styles.js +75 -0
  147. package/src/components/molecules/HeaderTop/index.js +29 -8
  148. package/src/components/molecules/HeaderTop/styles.js +4 -0
  149. package/src/components/molecules/ImageTooltip/ImageTooltip.stories.js +68 -0
  150. package/src/components/molecules/ImageTooltip/index.js +63 -0
  151. package/src/components/molecules/ImageTooltip/styles.js +18 -0
  152. package/src/components/molecules/ProductNameHeader/index.js +7 -2
  153. package/src/components/molecules/SelectV2/SelectV2.stories.js +115 -0
  154. package/src/components/molecules/SelectV2/index.js +357 -0
  155. package/src/components/molecules/SelectV2/styles.js +105 -0
  156. package/src/components/molecules/SelectV2/test.js +60 -0
  157. package/src/components/molecules/SelectV2/test.stories.js +10 -0
  158. package/src/components/organisms/Chat/Chat.stories.js +147 -0
  159. package/src/components/organisms/Chat/ChatLists/ChatLists.stories.js +65 -0
  160. package/src/components/organisms/Chat/ChatLists/Rotoplas.jpeg +0 -0
  161. package/src/components/organisms/Chat/ChatLists/THD.png +0 -0
  162. package/src/components/organisms/Chat/ChatLists/index.js +141 -0
  163. package/src/components/organisms/Chat/ChatLists/styles.js +162 -0
  164. package/src/components/organisms/Chat/ContainerItems/ContainerItems.stories.js +142 -0
  165. package/src/components/organisms/Chat/ContainerItems/index.js +512 -0
  166. package/src/components/organisms/Chat/ContainerItems/styles.js +328 -0
  167. package/src/components/organisms/Chat/ContentChat/ContentChat.stories.js +102 -0
  168. package/src/components/organisms/Chat/ContentChat/Rotoplas.jpeg +0 -0
  169. package/src/components/organisms/Chat/ContentChat/THD.png +0 -0
  170. package/src/components/organisms/Chat/ContentChat/index.js +919 -0
  171. package/src/components/organisms/Chat/ContentChat/styles.js +41 -0
  172. package/src/components/organisms/Chat/Footer/Footer.stories.js +22 -0
  173. package/src/components/organisms/Chat/Footer/index.js +661 -0
  174. package/src/components/organisms/Chat/Footer/styles.js +286 -0
  175. package/src/components/organisms/Chat/Header/Header.stories.js +66 -0
  176. package/src/components/organisms/Chat/Header/index.js +93 -0
  177. package/src/components/organisms/Chat/Header/styles.js +49 -0
  178. package/src/components/organisms/Chat/index.js +235 -0
  179. package/src/components/organisms/Chat/styles.js +42 -0
  180. package/src/components/organisms/FullProductNameHeader/index.js +1 -0
  181. package/src/components/organisms/Modal/Modal.stories.js +55 -0
  182. package/src/components/organisms/Modal/index.js +97 -0
  183. package/src/components/organisms/Modal/styles.js +103 -0
  184. package/src/components/organisms/RangeCalendar/RangeCalendar.stories.js +16 -0
  185. package/src/components/organisms/RangeCalendar/index.js +121 -0
  186. package/src/components/organisms/RangeCalendar/styles.js +883 -0
  187. package/src/components/pages/ProviderProductEdition/ProviderProductEdition.stories.js +67 -49
  188. package/src/components/pages/ProviderProductEdition/index.js +16 -9
  189. package/src/components/pages/RetailerProductEdition/RetailerProductEdition.stories.js +36 -46
  190. package/src/components/pages/RetailerProductEdition/index.js +14 -10
  191. package/src/global-files/data.js +18 -23
  192. package/src/global-files/fonts.css +6 -0
  193. package/src/global-files/handle_http.js +225 -0
  194. package/src/global-files/handle_userTech.js +7 -0
  195. package/src/global-files/utils.js +330 -0
  196. package/src/global-files/variables.js +2 -0
  197. package/src/index.js +17 -0
@@ -0,0 +1,919 @@
1
+ import ReactHowler from 'react-howler'
2
+ import { Container } from "./styles";
3
+ import { useEffect, useState } from "react";
4
+ import { NotFound } from "../../../atoms/NotFound";
5
+ import { Header } from "../Header";
6
+ import { faComments as IconChat } from "@fortawesome/free-solid-svg-icons";
7
+ import { Loading } from "../../../atoms/Loading";
8
+ import { ContainerItems } from "../ContainerItems";
9
+ import { Footer } from "../Footer";
10
+ import { ChatLists } from "../ChatLists";
11
+ import { CustomIcon } from "../../../atoms/CustomIcon";
12
+ import { fetchGET, fetchPOST } from "../../../../global-files/handle_http";
13
+ import {
14
+ encodeUriJson,
15
+ isStringEmpty,
16
+ isValidNaturalNumber,
17
+ } from "../../../../global-files/utils";
18
+ import newMessage from "../../../../assets/sounds/newMessage.mp3"
19
+
20
+ export const ContentChat = (props) => {
21
+ const {
22
+ chatType, // "merchant_product" | "order_product" | "ticket"
23
+ chatContainerType, // "fixed" | "popUp"
24
+ dataChat, // { data | error }
25
+ showBtnClose, // boolean
26
+ onClickBtnClose, // () => {}
27
+ showPopUpChat, // boolean
28
+ } = props;
29
+ const [companies, setCompanies] = useState({}); /* {
30
+ companyId: {
31
+ name: string,
32
+ statusChat: string => current | open | closed
33
+ items: [{..}] ,
34
+ enabledLoadMore: boolean
35
+ },
36
+ ...
37
+ } chat orderProduct */
38
+ const [singleChat, setSingleChat] = useState({
39
+ items: undefined,
40
+ enabledLoadMore: false,
41
+ statusChat: undefined,
42
+ }); // chat merchantProduct o ticket
43
+ const [activeCompanyId, setActiveCompanyId] = useState(); // number
44
+ const [allUsers, setAllUsers] = useState({}); // {...}
45
+ const [currentUser, setCurrentUser] = useState({
46
+ id: undefined,
47
+ companyId: undefined,
48
+ });
49
+ const [currentArticle, setCurrentArticle] = useState({
50
+ status: undefined,
51
+ version: undefined,
52
+ });
53
+ const [lastUpdateDate, setLastUpdateDate] = useState(); // string
54
+ const [isLoading, setIsLoading] = useState(true); // boolean
55
+ const [showChatsList, setShowChatsList] = useState(false); // boolean
56
+ const [processUpdateID, setProcessUpdateID] = useState(); // number
57
+ const [startUpdate, setStartUpdate] = useState(0); // number
58
+ const [runUpdate, setRunUpdate] = useState(0); // number
59
+ const [errorChat, setErrorChat] = useState({
60
+ existError: false,
61
+ code: undefined,
62
+ message: undefined,
63
+ errorDetail: undefined,
64
+ });
65
+ const [errorUpdate, setErrorUpdate] = useState({
66
+ startDate: undefined, // Date()
67
+ lastDate: undefined, // Date()
68
+ });
69
+ const [playSound, setPlaySound] = useState(false);
70
+
71
+ // matar update al desmontar el componente del chat
72
+ useEffect(() => {
73
+ return () => {
74
+ if (processUpdateID !== undefined) clearTimeout(processUpdateID);
75
+ };
76
+ }, []);
77
+ // al cargar el componente
78
+ useEffect(() => {
79
+ if (dataChat) {
80
+ stopUpdate();
81
+ if (dataChat.code) {
82
+ setErrorChat({
83
+ existError: true,
84
+ code: dataChat.code,
85
+ message: dataChat.message,
86
+ errorDetail: dataChat.errorDetail,
87
+ });
88
+ setIsLoading(false);
89
+ return;
90
+ }
91
+ if (chatType === "merchant_product") getInitialMerchantProduct();
92
+ else if (chatType === "order_product") getInitialOrderProduct();
93
+ else getInitialTicket();
94
+ }
95
+ }, [dataChat, showPopUpChat]);
96
+
97
+ // comenzar temporizador del update de 20s
98
+ useEffect(() => {
99
+ //return; -- descomentarizar para hacer pruebas sin update
100
+ if (startUpdate == 0) return;
101
+ const processID = setTimeout(() => {
102
+ setRunUpdate((prev) => prev + 1);
103
+ }, 15000);
104
+ setProcessUpdateID(processID);
105
+ return () => clearTimeout(processID);
106
+ }, [startUpdate]);
107
+
108
+ // ejecutar update
109
+ useEffect(() => {
110
+ // if (runUpdate == 0) return;
111
+ if (chatType === "merchant_product") {
112
+ if (singleChat.items) getUpdateLatestMerchantProduct();
113
+ else getInitialMerchantProduct();
114
+ } else if (chatType === "order_product") {
115
+ if (companies) getUpdateLatestOrderProduct();
116
+ else getInitialOrderProduct();
117
+ } else {
118
+ if (singleChat.items) getUpdateLatestTicket(true);
119
+ else getInitialTicket();
120
+ }
121
+ }, [runUpdate]);
122
+
123
+ /*=======================================================================
124
+ PETICION GET INICIAL SEGUN EL TIPO DE CHAT
125
+ ======================================================================= */
126
+ const getInitialMerchantProduct = async () => {
127
+ const paramsQuery = {
128
+ getType: "initial",
129
+ id: JSON.stringify(dataChat.id),
130
+ version: JSON.stringify(dataChat.version),
131
+ };
132
+ const paramsHeaders = { Authorization: dataChat.userToken };
133
+ const response = await fetchGET(
134
+ process.env.REACT_APP_PRODUCTS_CHAT_ENDPOINT,
135
+ paramsQuery,
136
+ paramsHeaders
137
+ );
138
+ if (!response.body) {
139
+ setErrorChat({
140
+ existError: true,
141
+ code: 400,
142
+ message: response.message,
143
+ errorDetail: response.errorDetail,
144
+ });
145
+ setIsLoading(false);
146
+ return;
147
+ }
148
+ // success
149
+ setCurrentUser({
150
+ id: response.body.data.currentUserId,
151
+ companyId: response.body.data.currentCompanyId,
152
+ });
153
+ setLastUpdateDate(response.body.data.lastUpdateDate);
154
+ setAllUsers(response.body.users);
155
+ setSingleChat({
156
+ items: response.body.items,
157
+ enabledLoadMore: response.body.items.length === 50,
158
+ });
159
+ setErrorChat({ existError: false });
160
+ setIsLoading(false);
161
+ };
162
+
163
+ const getInitialOrderProduct = async () => {
164
+ clearTimeout(processUpdateID); // finalizamos el temporizador
165
+ const paramsQuery = {
166
+ getType: "initial",
167
+ id: JSON.stringify(dataChat.id),
168
+ orderId: JSON.stringify(dataChat.orderId),
169
+ retailerId: JSON.stringify(dataChat.retailerId),
170
+ };
171
+ const paramsHeaders = { Authorization: dataChat.userToken };
172
+ const response = await fetchGET(
173
+ process.env.REACT_APP_PRODUCTS_CHAT_ENDPOINT,
174
+ paramsQuery,
175
+ paramsHeaders
176
+ );
177
+ setStartUpdate((prev) => prev + 1); // TEMPORAL
178
+ if (!response.body) {
179
+ setErrorChat({
180
+ existError: true,
181
+ code: 400,
182
+ message: response.message,
183
+ errorDetail: response.errorDetail,
184
+ });
185
+ setIsLoading(false);
186
+ return;
187
+ }
188
+ // success
189
+ setCurrentUser({
190
+ id: response.body.data.currentUserId,
191
+ companyId: response.body.data.currentCompanyId,
192
+ });
193
+ setLastUpdateDate(response.body.data.lastUpdateDate);
194
+ setCurrentArticle({
195
+ status: response.body.data.status,
196
+ version: response.body.data.version,
197
+ });
198
+ setAllUsers(response.body.users);
199
+ const companiesList = response.body.companies;
200
+ const companiesIdList = Object.keys(companiesList);
201
+ let companyActive;
202
+ // encontrar el chat inicial a cargar y si se debe permitir cargar mas
203
+ for (const companyId of companiesIdList) {
204
+ if (companiesList[companyId].items.length < 50) {
205
+ companiesList[companyId].enabledLoadMore = false;
206
+ } else {
207
+ companiesList[companyId].enabledLoadMore = true;
208
+ }
209
+
210
+ if (companiesList[companyId].statusChat === "current") {
211
+ companyActive = Number(companyId);
212
+ }
213
+ }
214
+ if (!companyActive && companiesIdList.length) {
215
+ companyActive = Number(companiesIdList[0]);
216
+ }
217
+ setCompanies(companiesList);
218
+ if (companyActive) setActiveCompanyId(companyActive);
219
+ setErrorChat({ existError: false });
220
+ setIsLoading(false);
221
+ };
222
+
223
+ const getInitialTicket = async () => {
224
+ stopUpdate(); // finalizamos el temporizador
225
+ const dataUser = {
226
+ id: dataChat.currentUser?.id,
227
+ companyId: dataChat.currentUser?.companyId,
228
+ isUserTech: dataChat.currentUser?.isUserTech,
229
+ };
230
+ const paramsQuery = {
231
+ id: JSON.stringify(dataChat.id),
232
+ getType: "initial",
233
+ currentUser: encodeUriJson(dataUser),
234
+ currentItemsFront: encodeUriJson(getItemsIdSingleChat()),
235
+ };
236
+ const response = await fetchGET(
237
+ process.env.REACT_APP_TICKETS_CHAT_ENDPOINT,
238
+ paramsQuery,
239
+ { Authorization: dataChat.currentUser?.token }
240
+ );
241
+ // programar update en 20s
242
+ setStartUpdate((prev) => prev + 1);
243
+ if (!response.body) {
244
+ setErrorChat({
245
+ existError: true,
246
+ code: 400,
247
+ message: response.message,
248
+ errorDetail: response.errorDetail,
249
+ });
250
+ setIsLoading(false);
251
+ return;
252
+ }
253
+ // success
254
+ setLastUpdateDate(response.body.data.lastUpdateDate);
255
+ setAllUsers(response.body.users);
256
+ setSingleChat({
257
+ items: response.body.items,
258
+ enabledLoadMore: response.body.items.length === 50,
259
+ statusChat: dataChat.statusChat,
260
+ });
261
+ setErrorChat({ existError: false });
262
+ setIsLoading(false);
263
+ };
264
+
265
+ /*=======================================================================
266
+ PETICION GET LOAD_MORE SEGUN EL TIPO DE CHAT
267
+ ======================================================================= */
268
+ const getLoadMoreMerchantProduct = async () => {
269
+ clearTimeout(processUpdateID); // finalizamos el temporizador
270
+ let date = singleChat.items[singleChat.items.length - 1].date;
271
+ const paramsQuery = {
272
+ getType: "loadMore",
273
+ id: JSON.stringify(dataChat.id),
274
+ version: JSON.stringify(dataChat.version),
275
+ date: encodeURIComponent(date),
276
+ };
277
+ const response = await fetchGET(
278
+ process.env.REACT_APP_PRODUCTS_CHAT_ENDPOINT,
279
+ paramsQuery
280
+ );
281
+ //setStartUpdate((prev) => prev + 1); // comendar un nuevo temporizador
282
+ if (!response.body) {
283
+ return {
284
+ title: response.message,
285
+ message: response.errorDetail,
286
+ };
287
+ }
288
+ // success
289
+ // actualizar la lista de los users
290
+ updateAllUsers(response.body.users);
291
+ // actualizar los items del chat
292
+ let newSingleChat = { ...singleChat };
293
+ newSingleChat.items = addOldItemsChat(
294
+ newSingleChat.items,
295
+ response.body.items
296
+ );
297
+ newSingleChat.enabledLoadMore = response.body.items.length === 50;
298
+ setSingleChat(newSingleChat);
299
+ };
300
+
301
+ const getLoadMoreOrderProduct = async () => {
302
+ clearTimeout(processUpdateID); // finalizamos el temporizador
303
+ let company = companies[activeCompanyId];
304
+ let date = company.items[company.items.length - 1].date;
305
+ const paramsQuery = {
306
+ getType: "loadMore",
307
+ id: JSON.stringify(dataChat.id),
308
+ orderId: JSON.stringify(dataChat.orderId),
309
+ version: JSON.stringify(currentArticle.version),
310
+ currentCompanyId: JSON.stringify(currentUser.companyId),
311
+ date: encodeURIComponent(date),
312
+ othersCompanyId: JSON.stringify([activeCompanyId]),
313
+ };
314
+ const response = await fetchGET(
315
+ process.env.REACT_APP_PRODUCTS_CHAT_ENDPOINT,
316
+ paramsQuery
317
+ );
318
+ //setStartUpdate((prev) => prev + 1); // comendar un nuevo temporizador
319
+ if (!response.body) {
320
+ return {
321
+ title: response.message,
322
+ message: response.errorDetail,
323
+ };
324
+ }
325
+ // success
326
+ // actualizar la lista de los users
327
+ updateAllUsers(response.body.users);
328
+ // actualizar los items del chat y la lista de users
329
+ company.items = addOldItemsChat(company.items, response.body.items);
330
+ company.enabledLoadMore = response.body.items.length === 50;
331
+ setCompanies((prev) => ({
332
+ ...prev,
333
+ [activeCompanyId]: company,
334
+ }));
335
+ };
336
+
337
+ // este GET obtiene la lista de compañoas con las que se puede chatear
338
+ const getLoadMoreTicket = async () => {
339
+ stopUpdate(); // finalizamos el temporizador
340
+ let date = singleChat.items[singleChat.items.length - 1].date;
341
+ const dataUser = {
342
+ id: dataChat.currentUser?.id,
343
+ companyId: dataChat.currentUser?.companyId,
344
+ isUserTech: dataChat.currentUser?.isUserTech,
345
+ };
346
+ const paramsQuery = {
347
+ id: JSON.stringify(dataChat.id),
348
+ getType: "loadMore",
349
+ date: encodeURIComponent(date),
350
+ currentUser: encodeUriJson(dataUser),
351
+ currentItemsFront: encodeUriJson(getItemsIdSingleChat()),
352
+ };
353
+ const response = await fetchGET(
354
+ process.env.REACT_APP_TICKETS_CHAT_ENDPOINT,
355
+ paramsQuery,
356
+ { Authorization: dataChat.currentUser?.token }
357
+ );
358
+ //programar update en 20s
359
+ setStartUpdate((prev) => prev + 1);
360
+ if (!response.body) {
361
+ return {
362
+ title: response.message,
363
+ message: response.errorDetail,
364
+ };
365
+ }
366
+ // success
367
+ // actualizar la lista de los users
368
+ updateAllUsers(response.body.users);
369
+ // actualizar los items del chat
370
+ let newSingleChat = { ...singleChat };
371
+ newSingleChat.items = addOldItemsChat(
372
+ newSingleChat.items,
373
+ response.body.items
374
+ );
375
+ newSingleChat.enabledLoadMore = response.body.items.length === 50;
376
+ setSingleChat(newSingleChat);
377
+ };
378
+
379
+ /*=======================================================================
380
+ PETICION GET UPDATE_LATEST SEGUN EL TIPO DE CHAT
381
+ ======================================================================= */
382
+ const getUpdateLatestMerchantProduct = async () => {
383
+ const paramsQuery = {
384
+ getType: "updateLatest",
385
+ id: JSON.stringify(dataChat.id),
386
+ version: JSON.stringify(dataChat.version),
387
+ date: encodeURIComponent(lastUpdateDate),
388
+ };
389
+ const response = await fetchGET(
390
+ process.env.REACT_APP_PRODUCTS_CHAT_ENDPOINT,
391
+ paramsQuery
392
+ );
393
+ if (!response.body) {
394
+ console.log("ERROR updateLatest:", {
395
+ message: response.message,
396
+ errorDetail: response.errorDetail,
397
+ });
398
+ return;
399
+ }
400
+ // success
401
+ setLastUpdateDate(response.body.data.lastUpdateDate);
402
+ // actualizar la lista de los users
403
+ updateAllUsers(response.body.users);
404
+ // actualizar los items del chat
405
+ let newSingleChat = { ...singleChat };
406
+ newSingleChat.items = addNewItemsChat(
407
+ newSingleChat.items,
408
+ response.body.items
409
+ );
410
+ setSingleChat(newSingleChat);
411
+ };
412
+
413
+ const getUpdateLatestOrderProduct = async () => {
414
+ const paramsQuery = {
415
+ getType: "updateLatest",
416
+ id: JSON.stringify(dataChat.id),
417
+ orderId: JSON.stringify(dataChat.orderId),
418
+ retailerId: JSON.stringify(dataChat.retailerId),
419
+ version: JSON.stringify(currentArticle.version),
420
+ status: currentArticle.status,
421
+ currentCompanyId: JSON.stringify(currentUser.companyId),
422
+ othersCompanyId: encodeURIComponent(
423
+ JSON.stringify(Object.keys(companies))
424
+ ),
425
+ date: encodeURIComponent(lastUpdateDate),
426
+ };
427
+ const response = await fetchGET(
428
+ process.env.REACT_APP_PRODUCTS_CHAT_ENDPOINT,
429
+ paramsQuery
430
+ );
431
+ if (!response.body) {
432
+ console.log("ERROR update: ", {
433
+ message: response.message,
434
+ errorDetail: response.errorDetail,
435
+ });
436
+ return;
437
+ }
438
+ // success
439
+
440
+ // cuando cambie la lista de chats por un cambio de version o estatus
441
+ if (response.body.data.status) {
442
+ setIsLoading(true);
443
+ setTimeout(() => {
444
+ setLastUpdateDate(response.body.data.lastUpdateDate);
445
+ setCurrentArticle({
446
+ status: response.body.data.status,
447
+ version: response.body.data.version,
448
+ });
449
+ setAllUsers(response.body.users);
450
+ const companiesList = response.body.companies;
451
+ const companiesIdList = Object.keys(companiesList);
452
+ let companyActive;
453
+ // encontrar el chat inicial a cargar y si se debe permitir cargar mas
454
+ for (const companyId of companiesIdList) {
455
+ if (companiesList[companyId].items.length < 50) {
456
+ companiesList[companyId].enabledLoadMore = false;
457
+ } else {
458
+ companiesList[companyId].enabledLoadMore = true;
459
+ }
460
+
461
+ if (companiesList[companyId].statusChat === "current") {
462
+ companyActive = Number(companyId);
463
+ }
464
+ }
465
+ if (!companyActive && companiesIdList.length) {
466
+ companyActive = Number(companiesIdList[0]);
467
+ }
468
+ setCompanies(companiesList);
469
+ if (companyActive) setActiveCompanyId(companyActive);
470
+ setErrorChat({ existError: false });
471
+ setIsLoading(false);
472
+ }, 2000);
473
+ }
474
+ // cuando se hizo un update de los mismos chats
475
+ else {
476
+ setLastUpdateDate(response.body.data.lastUpdateDate);
477
+ // actualizar la lista de los users
478
+ updateAllUsers(response.body.users);
479
+ // actualizar los items de los chats
480
+ let companiesList = { ...companies };
481
+ Object.keys(response.body.companies).forEach((companyId) => {
482
+ companiesList[companyId].items = addNewItemsChat(
483
+ companiesList[companyId].items,
484
+ response.body.companies[companyId].items
485
+ );
486
+ });
487
+ setCompanies(companiesList);
488
+ }
489
+ };
490
+
491
+ const getUpdateLatestTicket = async (fromUpdate = false) => {
492
+ const dataUser = {
493
+ id: dataChat.currentUser?.id,
494
+ companyId: dataChat.currentUser?.companyId,
495
+ isUserTech: dataChat.currentUser?.isUserTech,
496
+ };
497
+ const paramsQuery = {
498
+ id: JSON.stringify(dataChat.id),
499
+ getType: "updateLatest",
500
+ date: encodeURIComponent(lastUpdateDate),
501
+ currentUser: encodeUriJson(dataUser),
502
+ currentItemsFront: encodeUriJson(getItemsIdSingleChat()),
503
+ };
504
+ const response = await fetchGET(
505
+ process.env.REACT_APP_TICKETS_CHAT_ENDPOINT,
506
+ paramsQuery,
507
+ { Authorization: dataChat.currentUser?.token }
508
+ );
509
+ //programar update en 20s
510
+ setStartUpdate((prev) => prev + 1);
511
+ if (!response.body) {
512
+ if (errorUpdate.startDate) {
513
+ setErrorUpdate((prev) => ({
514
+ ...prev,
515
+ lastDate: new Date(),
516
+ }));
517
+ } else {
518
+ setErrorUpdate((prev) => ({
519
+ startDate: new Date(),
520
+ }));
521
+ }
522
+ console.log("ERROR updateLatest:", {
523
+ message: response.message,
524
+ errorDetail: response.errorDetail,
525
+ });
526
+ return;
527
+ }
528
+ // limpiar error update
529
+ if (errorUpdate.startDate) {
530
+ setErrorUpdate({});
531
+ }
532
+ // success
533
+ setLastUpdateDate(response.body.data.lastUpdateDate);
534
+ // actualizar la lista de los users
535
+ updateAllUsers(response.body.users);
536
+ // actualizar los items del chat
537
+ if (response.body.items.length === 0) return;
538
+ let newSingleChat = { ...singleChat };
539
+ newSingleChat.items = addNewItemsChat(
540
+ newSingleChat.items,
541
+ response.body.items,
542
+ fromUpdate,
543
+ );
544
+ newSingleChat.statusChat = response.body.data.statusChat;
545
+
546
+ setSingleChat(newSingleChat);
547
+ };
548
+
549
+ /*=======================================================================
550
+ FUNCION QUE EJECUTA EL MICROSERVICIO CREATE-ITEM
551
+ Este metodo recibe los items que queremos agregar al chat.
552
+ requiere:
553
+ => items: [ { type , value } , ... ]
554
+ NOTA: si se quiere agregar un mensaje mandar un array con un object
555
+ example: [ {
556
+ type: "message" ,
557
+ value: "mi mensaje"
558
+ } ]
559
+ ======================================================================= */
560
+ const createItemsChat = async (items = []) => {
561
+ if (items.length === 0) {
562
+ return {
563
+ message:
564
+ "No se especifico ningun mensaje, imagen o archivo nuevo " +
565
+ "que se quiera enviar al chat",
566
+ errorDetail: "Reporta esto a TI",
567
+ };
568
+ }
569
+ for (const item of items) {
570
+ if (!["message", "img", "file"].includes(item.type)) {
571
+ return {
572
+ message:
573
+ "Uno de los elementos que se quiere enviar al chat " +
574
+ `no es un tipo valido "${item.type}"`,
575
+ errorDetail: "Reporta esto a TI",
576
+ };
577
+ }
578
+ if (isStringEmpty(item.value)) {
579
+ return {
580
+ message:
581
+ "Uno de los elementos que se quiere enviar al chat " +
582
+ `contiene un valor vacio`,
583
+ errorDetail: "Reporta esto a TI",
584
+ };
585
+ }
586
+ }
587
+ let errorCreate;
588
+ stopUpdate(); // finalizamos el temporizador
589
+
590
+ // enviar items a la BD
591
+ if (chatType === "merchant_product") {
592
+ errorCreate = await createItemsMerchantProduct(items);
593
+ } else if (chatType === "order_product") {
594
+ errorCreate = await createItemsOrderProduct(items);
595
+ } else errorCreate = await createItemsTicket(items);
596
+
597
+ // actualizar chat para que aparezcan los items enviados
598
+ if (chatType === "merchant_product") {
599
+ await getUpdateLatestMerchantProduct();
600
+ } else if (chatType === "order_product") {
601
+ await getUpdateLatestOrderProduct();
602
+ } else await getUpdateLatestTicket();
603
+
604
+ // cuando no se pudieron guardar los items
605
+ if (errorCreate) {
606
+ return errorCreate;
607
+ }
608
+ };
609
+
610
+ const createItemsMerchantProduct = async (items = []) => {
611
+ const paramsBody = {
612
+ id: JSON.stringify(dataChat.id),
613
+ version: JSON.stringify(dataChat.version),
614
+ userId: JSON.stringify(currentUser.id),
615
+ items: JSON.stringify(items),
616
+ };
617
+ const response = await fetchPOST(
618
+ process.env.REACT_APP_PRODUCTS_CHAT_ENDPOINT,
619
+ paramsBody
620
+ );
621
+ if (!response.body) {
622
+ return {
623
+ message: response.message,
624
+ errorDetail: response.errorDetail,
625
+ };
626
+ }
627
+ };
628
+
629
+ const createItemsOrderProduct = async (items = []) => {
630
+ const paramsBody = {
631
+ id: JSON.stringify(dataChat.id),
632
+ version: JSON.stringify(currentArticle.version),
633
+ userId: JSON.stringify(currentUser.id),
634
+ items: JSON.stringify(items),
635
+ orderId: JSON.stringify(dataChat.orderId),
636
+ sentCompanyId: JSON.stringify(currentUser.companyId),
637
+ receivedCompanyId: JSON.stringify(activeCompanyId),
638
+ };
639
+ const response = await fetchPOST(
640
+ process.env.REACT_APP_PRODUCTS_CHAT_ENDPOINT,
641
+ paramsBody
642
+ );
643
+ if (!response.body) {
644
+ return {
645
+ message: response.message,
646
+ errorDetail: response.errorDetail,
647
+ };
648
+ }
649
+ };
650
+
651
+ const createItemsTicket = async (items = []) => {
652
+ const paramsBody = {
653
+ id: JSON.stringify(dataChat.id),
654
+ userId: JSON.stringify(dataChat.currentUser.id),
655
+ items: JSON.stringify(items),
656
+ };
657
+ const response = await fetchPOST(
658
+ process.env.REACT_APP_TICKETS_CHAT_ENDPOINT,
659
+ paramsBody
660
+ );
661
+ if (!response.body) {
662
+ return {
663
+ message: response.message,
664
+ errorDetail: response.errorDetail,
665
+ };
666
+ }
667
+ };
668
+
669
+ /*=======================================================================
670
+ SECCION DE FUNCIONES
671
+ ======================================================================= */
672
+ const isSingleChat = () => {
673
+ if (chatType === "merchant_product" || chatType === "ticket") {
674
+ return true;
675
+ }
676
+ if (companies && Object.keys(companies).length < 2) return true;
677
+ else return false;
678
+ };
679
+
680
+ const getItemsIdSingleChat = () => {
681
+ const itemsId = {};
682
+ if (Array.isArray(singleChat.items)) {
683
+ singleChat.items.forEach((item) => {
684
+ if (isValidNaturalNumber(item.id)) itemsId[item.id] = true;
685
+ });
686
+ }
687
+ return itemsId;
688
+ };
689
+
690
+ const getChatCompany = () => {
691
+ if (chatType === "merchant_product" || chatType === "ticket") {
692
+ return undefined;
693
+ }
694
+ if (companies && companies[activeCompanyId]) {
695
+ return {
696
+ ...companies[activeCompanyId],
697
+ id: activeCompanyId,
698
+ };
699
+ }
700
+ return undefined;
701
+ };
702
+
703
+ const addOldItemsChat = (currentItems = [], newItems = []) => {
704
+ let items = currentItems.slice();
705
+ let itemsId = {};
706
+ items.forEach((item) => {
707
+ itemsId[item.id] = true;
708
+ });
709
+ newItems.forEach((item) => {
710
+ if (!itemsId[item.id]) {
711
+ items.push(item);
712
+ itemsId[item.id] = true;
713
+ }
714
+ });
715
+ return items;
716
+ };
717
+
718
+ const addNewItemsChat = (currentItems = [], newItems = [], fromUpdate = false) => {
719
+ let itemsId = {};
720
+ currentItems.forEach((item) => {
721
+ itemsId[item.id] = item;
722
+ });
723
+ let thereAreNewItems = false;
724
+ newItems.forEach((newitem) => {
725
+ if (!itemsId[newitem.id]) {
726
+ itemsId[newitem.id] = newitem;
727
+ thereAreNewItems = true;
728
+ }
729
+ });
730
+ if (thereAreNewItems && fromUpdate) {
731
+ setPlaySound(true);
732
+ setTimeout(() => {
733
+ setPlaySound(false);
734
+ }, 5000);
735
+ }
736
+ return Object.values(itemsId).sort((a, b) => {
737
+ if (a.id < b.id) return 1;
738
+ if (a.id > b.id) return -1;
739
+ return 0;
740
+ });
741
+ };
742
+
743
+ const updateAllUsers = (newUsers = {}) => {
744
+ let currentUsers = { ...allUsers };
745
+ Object.keys(newUsers).forEach((userId) => {
746
+ if (!currentUsers[userId]) {
747
+ currentUsers[userId] = newUsers[userId];
748
+ }
749
+ });
750
+ setAllUsers(currentUsers);
751
+ };
752
+
753
+ const stopUpdate = () => {
754
+ if (processUpdateID !== undefined) {
755
+ clearTimeout(processUpdateID);
756
+ setProcessUpdateID(undefined);
757
+ }
758
+ };
759
+
760
+ const renderBodyChat = () => {
761
+ if (isLoading) return <Loading />;
762
+ if (errorChat.existError) {
763
+ return (
764
+ <NotFound
765
+ code={errorChat.code}
766
+ message={errorChat.message}
767
+ details={errorChat.errorDetail}
768
+ />
769
+ );
770
+ }
771
+ // cuando se quiere ver la lista de chats
772
+ if (showChatsList) {
773
+ return (
774
+ <ChatLists
775
+ companies={companies}
776
+ currentCompanyId={currentUser?.companyId}
777
+ onClickCompany={(companyIdSelected) => {
778
+ setActiveCompanyId(Number(companyIdSelected));
779
+ setShowChatsList(false);
780
+ }}
781
+ />
782
+ );
783
+ }
784
+ // mostrar chat?
785
+ let items;
786
+ let enabledLoadMore;
787
+ if (["merchant_product", "ticket"].includes(chatType)) {
788
+ items = singleChat.items;
789
+ enabledLoadMore = singleChat.enabledLoadMore;
790
+ }
791
+ // ORDER_PRODUCT
792
+ else if (companies) {
793
+ // caso 0 chats
794
+ if (Object.keys(companies).length === 0) {
795
+ return (
796
+ <div className="container-chatEmpty">
797
+ <CustomIcon
798
+ className="icon-chat"
799
+ transparent
800
+ size={35}
801
+ icon={IconChat}
802
+ type={"gray"}
803
+ />
804
+ <label>
805
+ De acuerdo al estatus del producto, tu compañia no tiene
806
+ disponible ningun chat abierto o cerrado
807
+ </label>
808
+ </div>
809
+ );
810
+ }
811
+ // caso 1 o mas chats
812
+ if (companies[activeCompanyId]) {
813
+ items = companies[activeCompanyId].items;
814
+ enabledLoadMore = companies[activeCompanyId].enabledLoadMore;
815
+ }
816
+ }
817
+ if (items) {
818
+ let containerItems = null;
819
+ if (items.length) {
820
+ containerItems = (
821
+ <ContainerItems
822
+ items={items}
823
+ users={allUsers}
824
+ showBtnLoadMore={enabledLoadMore}
825
+ chatType={chatType}
826
+ activeCompanyId={activeCompanyId}
827
+ currentUser={
828
+ ["merchant_product", "order_product"].includes(chatType)
829
+ ? currentUser
830
+ : dataChat.currentUser
831
+ }
832
+ onClickBtnLoadMore={
833
+ chatType === "merchant_product"
834
+ ? getLoadMoreMerchantProduct
835
+ : chatType === "order_product"
836
+ ? getLoadMoreOrderProduct
837
+ : getLoadMoreTicket
838
+ }
839
+ />
840
+ );
841
+ } else {
842
+ containerItems = (
843
+ <div className="container-chatEmpty">
844
+ <CustomIcon
845
+ className="icon-chat"
846
+ size={35}
847
+ icon={IconChat}
848
+ type={"gray"}
849
+ transparent
850
+ />
851
+ <label>Este chat no tiene mensajes</label>
852
+ </div>
853
+ );
854
+ }
855
+ return (
856
+ <>
857
+ {containerItems}
858
+ <Footer
859
+ chatType={chatType}
860
+ dataChat={
861
+ chatType === "merchant_product"
862
+ ? { id: dataChat.id, version: dataChat.version }
863
+ : chatType === "order_product"
864
+ ? { id: dataChat.id, version: currentArticle.version }
865
+ : chatType === "ticket"
866
+ ? { id: dataChat.id }
867
+ : undefined
868
+ }
869
+ chatCompany={getChatCompany()}
870
+ statusChat={
871
+ chatType === "order_product"
872
+ ? getChatCompany()?.statusChat
873
+ : chatType === "ticket"
874
+ ? singleChat.statusChat
875
+ : undefined
876
+ }
877
+ messageDisabled={
878
+ chatType === "order_product"
879
+ ? `La conversación con ${getChatCompany()?.name} ha finalizado`
880
+ : chatType === "ticket"
881
+ ? "Ticket cerrado"
882
+ : `La conversación ha finalizado`
883
+ }
884
+ createItemsChat={createItemsChat}
885
+ errorUpdate={errorUpdate}
886
+ />
887
+ </>
888
+ );
889
+ }
890
+ return <Loading />;
891
+ };
892
+
893
+ return (
894
+ <>
895
+ <Container>
896
+ {/* header */}
897
+ {(chatContainerType !== "fixed" || !isSingleChat()) && (
898
+ <Header
899
+ showBtnClose={showBtnClose}
900
+ onClickBtnClose={onClickBtnClose}
901
+ showChatsList={showChatsList}
902
+ chatCompany={getChatCompany()}
903
+ multipleCompanies={!isSingleChat()}
904
+ onClickBtnChooseChat={() => {
905
+ setShowChatsList(true);
906
+ }}
907
+ />
908
+ )}
909
+
910
+ {/* body */}
911
+ {renderBodyChat()}
912
+ </Container>
913
+ <ReactHowler
914
+ src={newMessage}
915
+ playing={playSound}
916
+ />
917
+ </>
918
+ );
919
+ };