contentoh-components-library 21.3.11 → 21.3.13

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