contentoh-components-library 21.3.16 → 21.3.18

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