minerva-plexus-csd 1.1.13 → 1.1.14

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.
@@ -925,22 +925,31 @@ const FD = (e) => {
925
925
  createConversation: async (e, t) => {
926
926
  if (!t)
927
927
  throw new Error("Service is required to create a conversation.");
928
- const { apiUrl: n } = pt(), r = `${n}${Wt.CONVERSATIONS_CREATE}/?service=${encodeURIComponent(t)}${e ? `&title=${encodeURIComponent(e)}` : ""}`, a = await at(r, {
928
+ const { apiUrl: n } = pt(), r = `${n}${Wt.CONVERSATIONS_CREATE}/?service=${encodeURIComponent(t)}${e ? `&title=${encodeURIComponent(e)}` : ""}`, i = document.cookie.split("; ").find((u) => u.startsWith("access_token=")), o = i ? i.split("=")[1] : null;
929
+ console.log(
930
+ "Intentando crear conversación con token de cookies:",
931
+ o ? `Sí (token: ${o.substring(0, 20)}...)` : "No (token no encontrado)"
932
+ );
933
+ const s = await at(r, {
929
934
  method: "POST",
930
935
  mode: "cors",
931
936
  headers: {
932
937
  "Content-Type": "application/x-www-form-urlencoded"
933
938
  }
934
939
  });
935
- if (!a)
940
+ if (console.log("Respuesta al crear conversación:", {
941
+ status: s.status,
942
+ ok: s.ok,
943
+ url: s.url
944
+ }), !s)
936
945
  throw new Error(
937
946
  "Failed to create conversation: No response from server."
938
947
  );
939
- if (!a.ok)
948
+ if (!s.ok)
940
949
  throw new Error(
941
- `Failed to create conversation. Status: ${a.status}`
950
+ `Failed to create conversation. Status: ${s.status}`
942
951
  );
943
- return await a.json();
952
+ return await s.json();
944
953
  },
945
954
  /**
946
955
  * Obtiene todas las conversaciones del usuario con opción de paginación.
@@ -950,21 +959,30 @@ const FD = (e) => {
950
959
  * @returns {Promise<Conversation[]>} Promesa que resuelve con una lista de conversaciones.
951
960
  */
952
961
  getUserConversations: async (e) => {
953
- const { apiUrl: t } = pt(), n = await at(
962
+ const { apiUrl: t } = pt(), r = document.cookie.split("; ").find((s) => s.startsWith("access_token=")), a = r ? r.split("=")[1] : null;
963
+ console.log(
964
+ "Intentando obtener conversaciones de usuario con token de cookies:",
965
+ a ? `Sí (token: ${a.substring(0, 20)}...)` : "No (token no encontrado)"
966
+ );
967
+ const i = await at(
954
968
  `${t}${Wt.USER_CONVERSATIONS}?service=${e}`,
955
969
  {
956
970
  method: "GET"
957
971
  }
958
972
  );
959
- if (!n)
973
+ if (console.log("Respuesta al obtener conversaciones de usuario:", {
974
+ status: i.status,
975
+ ok: i.ok,
976
+ url: i.url
977
+ }), !i)
960
978
  throw new Error(
961
979
  "Failed to fetch user conversations: No response from server."
962
980
  );
963
- if (!n.ok)
981
+ if (!i.ok)
964
982
  throw new Error(
965
- `Failed to fetch user conversations. Status: ${n.status}`
983
+ `Failed to fetch user conversations. Status: ${i.status}`
966
984
  );
967
- return await n.json();
985
+ return await i.json();
968
986
  },
969
987
  /**
970
988
  * Obtiene una conversación específica por ID.
@@ -974,7 +992,12 @@ const FD = (e) => {
974
992
  * @returns {Promise<Conversation>} Promesa que resuelve con la conversación obtenida.
975
993
  */
976
994
  getConversationById: async (e, t) => {
977
- const { apiUrl: n } = pt(), r = await at(
995
+ const { apiUrl: n } = pt(), a = document.cookie.split("; ").find((l) => l.startsWith("access_token=")), i = a ? a.split("=")[1] : null;
996
+ console.log(
997
+ "Intentando obtener conversación por ID con token de cookies:",
998
+ i ? `Sí (token: ${i.substring(0, 20)}...)` : "No (token no encontrado)"
999
+ );
1000
+ const o = await at(
978
1001
  `${n}${Wt.CONVERSATION_MESSAGES}/${e}?service=${t}`,
979
1002
  {
980
1003
  method: "GET",
@@ -983,15 +1006,19 @@ const FD = (e) => {
983
1006
  }
984
1007
  }
985
1008
  );
986
- if (!r)
1009
+ if (console.log("Respuesta al obtener conversación por ID:", {
1010
+ status: o.status,
1011
+ ok: o.ok,
1012
+ url: o.url
1013
+ }), !o)
987
1014
  throw new Error(
988
1015
  "Failed to fetch conversation by ID: No response from server."
989
1016
  );
990
- if (!r.ok)
1017
+ if (!o.ok)
991
1018
  throw new Error(
992
- `Failed to fetch conversation by ID. Status: ${r.status}`
1019
+ `Failed to fetch conversation by ID. Status: ${o.status}`
993
1020
  );
994
- return await r.json();
1021
+ return await o.json();
995
1022
  },
996
1023
  /**
997
1024
  * Elimina una conversación por ID.
@@ -1002,19 +1029,28 @@ const FD = (e) => {
1002
1029
  * @throws {Error}
1003
1030
  */
1004
1031
  deleteConversationById: async (e, t) => {
1005
- const { apiUrl: n } = pt(), r = await at(
1032
+ const { apiUrl: n } = pt(), a = document.cookie.split("; ").find((s) => s.startsWith("access_token=")), i = a ? a.split("=")[1] : null;
1033
+ console.log(
1034
+ "Intentando eliminar conversación con token de cookies:",
1035
+ i ? `Sí (token: ${i.substring(0, 20)}...)` : "No (token no encontrado)"
1036
+ );
1037
+ const o = await at(
1006
1038
  `${n}${Wt.DELETE_CONVERSATION}${e}?conversation_id=${e}&service=${t}`,
1007
1039
  {
1008
1040
  method: "POST"
1009
1041
  }
1010
1042
  );
1011
- if (!r)
1043
+ if (console.log("Respuesta al eliminar conversación:", {
1044
+ status: o.status,
1045
+ ok: o.ok,
1046
+ url: o.url
1047
+ }), !o)
1012
1048
  throw new Error(
1013
1049
  "Failed to delete conversation: No response from server."
1014
1050
  );
1015
- if (!r.ok)
1051
+ if (!o.ok)
1016
1052
  throw new Error(
1017
- `Failed to delete conversation with ID: ${e}. Status: ${r.status}`
1053
+ `Failed to delete conversation with ID: ${e}. Status: ${o.status}`
1018
1054
  );
1019
1055
  }
1020
1056
  }, Yv = async (e, t) => {
@@ -27,7 +27,7 @@ Check the top-level render call using <`+J+">.")}return j}}function yv(_,j){{if(
27
27
  <%s {...props} />
28
28
  React keys must be passed directly to JSX without using spread:
29
29
  let props = %s;
30
- <%s key={someKey} {...props} />`,Ic,Wt,CL,Wt),Sv[Wt+Ic]=!0}}return _===a?EL(Re):bL(Re),Re}}function yL(_,j,J){return wv(_,j,J,!0)}function vL(_,j,J){return wv(_,j,J,!1)}var SL=vL,wL=yL;En.Fragment=a,En.jsx=SL,En.jsxs=wL}(),En}var _v={};_v.NODE_ENV==="production"?Ar.exports=xv():Ar.exports=Av();var g=Ar.exports;const _r=({enableAutoCreate:e,enableAutoCreateCsd:t,addConversation:n,selectConversation:r,service:a,conversations:i})=>{const o=I.useRef(!1);return{autoCreateConversationCsd:I.useCallback(async()=>{if(t&&!o.current){o.current=!0;try{const l=await n("New Conversation",a);l&&r(l.id,a)}catch(l){console.error("Error creando la conversación:",l)}}},[t,a,n,r])}};var Lc=(e=>(e.minia="Minia",e.uxia="Uxía",e.helia="Helia",e.iria="Iria",e.flavia="Flavia",e))(Lc||{});const Dc={API_URL:"http://dev-chatbot-drupal.plexus.tech:8311",API_KEY:"ai"};let Ot={apiUrl:"",apiKey:""};const kv=e=>{Ot={...Ot,...e}},Ze=()=>(Ot.apiUrl||(console.warn("[Minerva] apiUrl no configurado. Usando valor por defecto."),Ot.apiUrl=Dc.API_URL),Ot.apiKey||(console.warn("[Minerva] apiKey no configurado. Usando valor por defecto."),Ot.apiKey=Dc.API_KEY),Ot),Rv=e=>{},Xe=async(e,t={})=>{const{apiUrl:n}=Ze(),r={"Content-Type":"application/json",...t.headers||{}},a=e.startsWith("http")?e:`${n.replace(/\/$/,"")}/${e.replace(/^\//,"")}`;try{const i=await fetch(a,{...t,headers:r});if(i.status===401){console.warn("INVALID ACCESS");return}if(!i.ok)throw new Error(`HTTP error! status: ${i.status}`);return i}catch(i){throw console.error("Fetch failed:",i),i}},Lt={CONVERSATIONS_CREATE:"/conversations",USER_CONVERSATIONS:"/conversations/user",CONVERSATION_MESSAGES:"/messages/conversation",DELETE_CONVERSATION:"/conversations/delete/",GET_MESSAGES_BY_CONVERSATION_ID:"/messages/conversation",SEND_MESSAGE:"/bot/user_request_stream"},Vn={getMessagesByConversationId:async e=>{const{apiUrl:t}=Ze(),n=await Xe(`${t}${Lt.GET_MESSAGES_BY_CONVERSATION_ID}/${e}?conversation_id=${e}`,{method:"GET",headers:{"Content-Type":"application/x-www-form-urlencoded"}});if(!n)throw new Error("Failed to fetch messages: No response from server (possible redirection).");if(!n.ok)throw new Error(`Failed to fetch messages. Status: ${n.status}`);return await n.json()},sendMessage:async(e,t)=>{const{apiUrl:n}=Ze(),r=await Xe(`${n}${Lt.SEND_MESSAGE}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({conversation:{id:e},text:t})});if(!r)throw new Error("Failed to send message: No response from server.");if(!r.ok)throw new Error(`Failed to send message. Status: ${r.status}`);if(r.status===201)debugger;return await r.json()},stopBotStream:async e=>{const{apiUrl:t}=Ze(),n=`${t}/bot/stop_request_stream?conversation_id=${e}`;console.log("Enviando petición para detener el stream al endpoint:",n),console.log("Conversación ID:",e);try{const r=await Xe(n,{method:"POST",headers:{"Content-Type":"application/json"}});if(!r)throw console.error("No se recibió respuesta del servidor"),new Error("No se recibió respuesta del servidor al intentar detener el stream");if(!r.ok){const a=await r.text().catch(()=>"No se pudo leer el error");throw console.error(`Error del servidor (${r.status}):`,a),new Error(`Error al detener el stream: ${r.status}`)}console.log("Backend confirmó detención del stream")}catch(r){throw console.error("Error al detener el stream:",r),r}},sendMessageStreaming:async(e,t,n,r)=>{const{apiUrl:a}=Ze(),i={conversation:{id:e},text:t,service:n},o=await Xe(`${a}${Lt.SEND_MESSAGE}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i),signal:r});if(!o)throw new Error("Failed to send message streaming: No response from server.");if(o.status!==200&&o.status!==201){let s;try{s=await o.json()}catch{s="No JSON response available"}throw console.error("Error details from server:",s),new Error(`Failed to send message streaming. Status: ${o.status}, Details: ${JSON.stringify(s)}`)}if(!o.body)throw new Error("No body in response");return o},editMessageAndResend:async({conversationId:e,messageId:t,text:n})=>{const a=await Xe("/bot/edit_request_stream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({conversation:{id:e},message_id:t,text:n})});if(!a)throw new Error("Failed to send message streaming: No response from server.");if(!a.ok){let i;try{i=await a.json()}catch{i="No JSON response available"}throw console.error("Error details from server:",i),new Error(`Failed to send message streaming. Status: ${a.status}, Details: ${JSON.stringify(i)}`)}if(!a.body)throw new Error("No body in response");return a}},Iv=async e=>(await Vn.getMessagesByConversationId(e)).map(a=>({...a,conversation_id:e})).slice().sort((a,i)=>new Date(a.created_at).getTime()-new Date(i.created_at).getTime()),Nv=async(e,t,n,r)=>await Vn.sendMessageStreaming(e,t,n,r),Mc=async e=>{console.log(`Solicitando detener el stream para la conversación: ${e}`);try{console.log("Enviando solicitud para detener el stream al backend..."),await Vn.stopBotStream(e),console.log(`✅ Solicitud de detención enviada correctamente para conversación: ${e}`)}catch(t){throw console.error(`❌ Error al solicitar detención del stream para conversación ${e}:`,t),t}},Ov=async(e,t,n)=>await Vn.editMessageAndResend({conversationId:e,messageId:t,text:n}),Pc=(e,t,n)=>new Promise(r=>{let a=0;const i=10,o=setInterval(()=>{if(a<e.length){const s=e.slice(a,a+i);n(s),a+=i}else clearInterval(o),r()},t)}),kr={createConversation:async(e,t)=>{if(!t)throw new Error("Service is required to create a conversation.");const{apiUrl:n}=Ze(),r=`${n}${Lt.CONVERSATIONS_CREATE}/?service=${encodeURIComponent(t)}${e?`&title=${encodeURIComponent(e)}`:""}`,a=await Xe(r,{method:"POST",mode:"cors",headers:{"Content-Type":"application/x-www-form-urlencoded"}});if(!a)throw new Error("Failed to create conversation: No response from server.");if(!a.ok)throw new Error(`Failed to create conversation. Status: ${a.status}`);return await a.json()},getUserConversations:async e=>{const{apiUrl:t}=Ze(),n=await Xe(`${t}${Lt.USER_CONVERSATIONS}?service=${e}`,{method:"GET"});if(!n)throw new Error("Failed to fetch user conversations: No response from server.");if(!n.ok)throw new Error(`Failed to fetch user conversations. Status: ${n.status}`);return await n.json()},getConversationById:async(e,t)=>{const{apiUrl:n}=Ze(),r=await Xe(`${n}${Lt.CONVERSATION_MESSAGES}/${e}?service=${t}`,{method:"GET",headers:{"Content-Type":"application/x-www-form-urlencoded"}});if(!r)throw new Error("Failed to fetch conversation by ID: No response from server.");if(!r.ok)throw new Error(`Failed to fetch conversation by ID. Status: ${r.status}`);return await r.json()},deleteConversationById:async(e,t)=>{const{apiUrl:n}=Ze(),r=await Xe(`${n}${Lt.DELETE_CONVERSATION}${e}?conversation_id=${e}&service=${t}`,{method:"POST"});if(!r)throw new Error("Failed to delete conversation: No response from server.");if(!r.ok)throw new Error(`Failed to delete conversation with ID: ${e}. Status: ${r.status}`)}},Lv=async(e,t)=>{try{return await kr.createConversation(e,t)}catch(n){throw console.error("Error creating conversation:",n),n}},Dv=async e=>await kr.getUserConversations(e),Mv=async(e,t)=>await kr.deleteConversationById(e,t),Fc=I.createContext(void 0),Pv=({children:e,usedService:t})=>{const[n,r]=I.useState(t??"CsdInteraccion"),a=I.useMemo(()=>({service:n,setService:r}),[n]);return g.jsx(Fc.Provider,{value:a,children:e})},Rr=()=>{const e=I.useContext(Fc);if(!e)throw new Error("useService must be used within ServiceProvider");return e},Uc=I.createContext(void 0),Fv=({children:e,enableAutoCreate:t=!1,enableAutoCreateCsd:n=!1,serviceTicketing:r=!0,serviceTicketingNoUSer:a=!0})=>{const{service:i}=Rr(),[o,s]=I.useState({}),[l,u]=I.useState(null),c=async()=>{if(i)try{const x=await Dv(i);s(T=>({...T,[i]:x})),!l&&x.length>0&&!n&&u(x[x.length-1])}catch(x){console.error("❌ Error al obtener conversaciones:",x)}};I.useEffect(()=>{i&&c()},[i]);const d=async(x,T)=>{try{const E=await Lv(x,T);return s(m=>({...m,[T]:[...m[T]||[],E]})),u(E),E}catch(E){throw console.error("Failed to create conversation:",E),E}},f=async(x,T)=>{if(T)try{await Mv(x,T),s(E=>({...E,[T]:(E[T]||[]).filter(m=>m.id!==x)})),u(null)}catch(E){console.error("Failed to delete conversation:",E)}},p=async(x,T)=>{const m=(o[T??""]||[]).find(A=>A.id===x);m&&(l!=null&&l.id&&await Mc(l==null?void 0:l.id),u(m))},{autoCreateConversationCsd:y}=_r({enableAutoCreate:t,enableAutoCreateCsd:n,addConversation:d,selectConversation:p,service:i,conversations:o[i]||[]});I.useEffect(()=>{n&&y()},[y]);const S=I.useMemo(()=>({conversations:o[i]||[],fetchConversations:c,addConversation:d,removeConversation:f,selectConversation:p,selectedConversation:l,selectedConversationId:(l==null?void 0:l.id)??null,service:i,serviceTicketing:r,serviceTicketingNoUSer:a}),[o,l,i,r,a]);return g.jsx(Uc.Provider,{value:S,children:e})},Yt=()=>{const e=I.useContext(Uc);if(!e)throw new Error("useConversation must be used within a ConversationProvider");return e};L.div.attrs({className:"row"})`
30
+ <%s key={someKey} {...props} />`,Ic,Wt,CL,Wt),Sv[Wt+Ic]=!0}}return _===a?EL(Re):bL(Re),Re}}function yL(_,j,J){return wv(_,j,J,!0)}function vL(_,j,J){return wv(_,j,J,!1)}var SL=vL,wL=yL;En.Fragment=a,En.jsx=SL,En.jsxs=wL}(),En}var _v={};_v.NODE_ENV==="production"?Ar.exports=xv():Ar.exports=Av();var g=Ar.exports;const _r=({enableAutoCreate:e,enableAutoCreateCsd:t,addConversation:n,selectConversation:r,service:a,conversations:i})=>{const o=I.useRef(!1);return{autoCreateConversationCsd:I.useCallback(async()=>{if(t&&!o.current){o.current=!0;try{const l=await n("New Conversation",a);l&&r(l.id,a)}catch(l){console.error("Error creando la conversación:",l)}}},[t,a,n,r])}};var Lc=(e=>(e.minia="Minia",e.uxia="Uxía",e.helia="Helia",e.iria="Iria",e.flavia="Flavia",e))(Lc||{});const Dc={API_URL:"http://dev-chatbot-drupal.plexus.tech:8311",API_KEY:"ai"};let Ot={apiUrl:"",apiKey:""};const kv=e=>{Ot={...Ot,...e}},Ze=()=>(Ot.apiUrl||(console.warn("[Minerva] apiUrl no configurado. Usando valor por defecto."),Ot.apiUrl=Dc.API_URL),Ot.apiKey||(console.warn("[Minerva] apiKey no configurado. Usando valor por defecto."),Ot.apiKey=Dc.API_KEY),Ot),Rv=e=>{},Xe=async(e,t={})=>{const{apiUrl:n}=Ze(),r={"Content-Type":"application/json",...t.headers||{}},a=e.startsWith("http")?e:`${n.replace(/\/$/,"")}/${e.replace(/^\//,"")}`;try{const i=await fetch(a,{...t,headers:r});if(i.status===401){console.warn("INVALID ACCESS");return}if(!i.ok)throw new Error(`HTTP error! status: ${i.status}`);return i}catch(i){throw console.error("Fetch failed:",i),i}},Lt={CONVERSATIONS_CREATE:"/conversations",USER_CONVERSATIONS:"/conversations/user",CONVERSATION_MESSAGES:"/messages/conversation",DELETE_CONVERSATION:"/conversations/delete/",GET_MESSAGES_BY_CONVERSATION_ID:"/messages/conversation",SEND_MESSAGE:"/bot/user_request_stream"},Vn={getMessagesByConversationId:async e=>{const{apiUrl:t}=Ze(),n=await Xe(`${t}${Lt.GET_MESSAGES_BY_CONVERSATION_ID}/${e}?conversation_id=${e}`,{method:"GET",headers:{"Content-Type":"application/x-www-form-urlencoded"}});if(!n)throw new Error("Failed to fetch messages: No response from server (possible redirection).");if(!n.ok)throw new Error(`Failed to fetch messages. Status: ${n.status}`);return await n.json()},sendMessage:async(e,t)=>{const{apiUrl:n}=Ze(),r=await Xe(`${n}${Lt.SEND_MESSAGE}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({conversation:{id:e},text:t})});if(!r)throw new Error("Failed to send message: No response from server.");if(!r.ok)throw new Error(`Failed to send message. Status: ${r.status}`);if(r.status===201)debugger;return await r.json()},stopBotStream:async e=>{const{apiUrl:t}=Ze(),n=`${t}/bot/stop_request_stream?conversation_id=${e}`;console.log("Enviando petición para detener el stream al endpoint:",n),console.log("Conversación ID:",e);try{const r=await Xe(n,{method:"POST",headers:{"Content-Type":"application/json"}});if(!r)throw console.error("No se recibió respuesta del servidor"),new Error("No se recibió respuesta del servidor al intentar detener el stream");if(!r.ok){const a=await r.text().catch(()=>"No se pudo leer el error");throw console.error(`Error del servidor (${r.status}):`,a),new Error(`Error al detener el stream: ${r.status}`)}console.log("Backend confirmó detención del stream")}catch(r){throw console.error("Error al detener el stream:",r),r}},sendMessageStreaming:async(e,t,n,r)=>{const{apiUrl:a}=Ze(),i={conversation:{id:e},text:t,service:n},o=await Xe(`${a}${Lt.SEND_MESSAGE}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i),signal:r});if(!o)throw new Error("Failed to send message streaming: No response from server.");if(o.status!==200&&o.status!==201){let s;try{s=await o.json()}catch{s="No JSON response available"}throw console.error("Error details from server:",s),new Error(`Failed to send message streaming. Status: ${o.status}, Details: ${JSON.stringify(s)}`)}if(!o.body)throw new Error("No body in response");return o},editMessageAndResend:async({conversationId:e,messageId:t,text:n})=>{const a=await Xe("/bot/edit_request_stream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({conversation:{id:e},message_id:t,text:n})});if(!a)throw new Error("Failed to send message streaming: No response from server.");if(!a.ok){let i;try{i=await a.json()}catch{i="No JSON response available"}throw console.error("Error details from server:",i),new Error(`Failed to send message streaming. Status: ${a.status}, Details: ${JSON.stringify(i)}`)}if(!a.body)throw new Error("No body in response");return a}},Iv=async e=>(await Vn.getMessagesByConversationId(e)).map(a=>({...a,conversation_id:e})).slice().sort((a,i)=>new Date(a.created_at).getTime()-new Date(i.created_at).getTime()),Nv=async(e,t,n,r)=>await Vn.sendMessageStreaming(e,t,n,r),Mc=async e=>{console.log(`Solicitando detener el stream para la conversación: ${e}`);try{console.log("Enviando solicitud para detener el stream al backend..."),await Vn.stopBotStream(e),console.log(`✅ Solicitud de detención enviada correctamente para conversación: ${e}`)}catch(t){throw console.error(`❌ Error al solicitar detención del stream para conversación ${e}:`,t),t}},Ov=async(e,t,n)=>await Vn.editMessageAndResend({conversationId:e,messageId:t,text:n}),Pc=(e,t,n)=>new Promise(r=>{let a=0;const i=10,o=setInterval(()=>{if(a<e.length){const s=e.slice(a,a+i);n(s),a+=i}else clearInterval(o),r()},t)}),kr={createConversation:async(e,t)=>{if(!t)throw new Error("Service is required to create a conversation.");const{apiUrl:n}=Ze(),r=`${n}${Lt.CONVERSATIONS_CREATE}/?service=${encodeURIComponent(t)}${e?`&title=${encodeURIComponent(e)}`:""}`,i=document.cookie.split("; ").find(u=>u.startsWith("access_token=")),o=i?i.split("=")[1]:null;console.log("Intentando crear conversación con token de cookies:",o?`Sí (token: ${o.substring(0,20)}...)`:"No (token no encontrado)");const s=await Xe(r,{method:"POST",mode:"cors",headers:{"Content-Type":"application/x-www-form-urlencoded"}});if(console.log("Respuesta al crear conversación:",{status:s.status,ok:s.ok,url:s.url}),!s)throw new Error("Failed to create conversation: No response from server.");if(!s.ok)throw new Error(`Failed to create conversation. Status: ${s.status}`);return await s.json()},getUserConversations:async e=>{const{apiUrl:t}=Ze(),r=document.cookie.split("; ").find(s=>s.startsWith("access_token=")),a=r?r.split("=")[1]:null;console.log("Intentando obtener conversaciones de usuario con token de cookies:",a?`Sí (token: ${a.substring(0,20)}...)`:"No (token no encontrado)");const i=await Xe(`${t}${Lt.USER_CONVERSATIONS}?service=${e}`,{method:"GET"});if(console.log("Respuesta al obtener conversaciones de usuario:",{status:i.status,ok:i.ok,url:i.url}),!i)throw new Error("Failed to fetch user conversations: No response from server.");if(!i.ok)throw new Error(`Failed to fetch user conversations. Status: ${i.status}`);return await i.json()},getConversationById:async(e,t)=>{const{apiUrl:n}=Ze(),a=document.cookie.split("; ").find(l=>l.startsWith("access_token=")),i=a?a.split("=")[1]:null;console.log("Intentando obtener conversación por ID con token de cookies:",i?`Sí (token: ${i.substring(0,20)}...)`:"No (token no encontrado)");const o=await Xe(`${n}${Lt.CONVERSATION_MESSAGES}/${e}?service=${t}`,{method:"GET",headers:{"Content-Type":"application/x-www-form-urlencoded"}});if(console.log("Respuesta al obtener conversación por ID:",{status:o.status,ok:o.ok,url:o.url}),!o)throw new Error("Failed to fetch conversation by ID: No response from server.");if(!o.ok)throw new Error(`Failed to fetch conversation by ID. Status: ${o.status}`);return await o.json()},deleteConversationById:async(e,t)=>{const{apiUrl:n}=Ze(),a=document.cookie.split("; ").find(s=>s.startsWith("access_token=")),i=a?a.split("=")[1]:null;console.log("Intentando eliminar conversación con token de cookies:",i?`Sí (token: ${i.substring(0,20)}...)`:"No (token no encontrado)");const o=await Xe(`${n}${Lt.DELETE_CONVERSATION}${e}?conversation_id=${e}&service=${t}`,{method:"POST"});if(console.log("Respuesta al eliminar conversación:",{status:o.status,ok:o.ok,url:o.url}),!o)throw new Error("Failed to delete conversation: No response from server.");if(!o.ok)throw new Error(`Failed to delete conversation with ID: ${e}. Status: ${o.status}`)}},Lv=async(e,t)=>{try{return await kr.createConversation(e,t)}catch(n){throw console.error("Error creating conversation:",n),n}},Dv=async e=>await kr.getUserConversations(e),Mv=async(e,t)=>await kr.deleteConversationById(e,t),Fc=I.createContext(void 0),Pv=({children:e,usedService:t})=>{const[n,r]=I.useState(t??"CsdInteraccion"),a=I.useMemo(()=>({service:n,setService:r}),[n]);return g.jsx(Fc.Provider,{value:a,children:e})},Rr=()=>{const e=I.useContext(Fc);if(!e)throw new Error("useService must be used within ServiceProvider");return e},Uc=I.createContext(void 0),Fv=({children:e,enableAutoCreate:t=!1,enableAutoCreateCsd:n=!1,serviceTicketing:r=!0,serviceTicketingNoUSer:a=!0})=>{const{service:i}=Rr(),[o,s]=I.useState({}),[l,u]=I.useState(null),c=async()=>{if(i)try{const x=await Dv(i);s(T=>({...T,[i]:x})),!l&&x.length>0&&!n&&u(x[x.length-1])}catch(x){console.error("❌ Error al obtener conversaciones:",x)}};I.useEffect(()=>{i&&c()},[i]);const d=async(x,T)=>{try{const E=await Lv(x,T);return s(m=>({...m,[T]:[...m[T]||[],E]})),u(E),E}catch(E){throw console.error("Failed to create conversation:",E),E}},f=async(x,T)=>{if(T)try{await Mv(x,T),s(E=>({...E,[T]:(E[T]||[]).filter(m=>m.id!==x)})),u(null)}catch(E){console.error("Failed to delete conversation:",E)}},p=async(x,T)=>{const m=(o[T??""]||[]).find(A=>A.id===x);m&&(l!=null&&l.id&&await Mc(l==null?void 0:l.id),u(m))},{autoCreateConversationCsd:y}=_r({enableAutoCreate:t,enableAutoCreateCsd:n,addConversation:d,selectConversation:p,service:i,conversations:o[i]||[]});I.useEffect(()=>{n&&y()},[y]);const S=I.useMemo(()=>({conversations:o[i]||[],fetchConversations:c,addConversation:d,removeConversation:f,selectConversation:p,selectedConversation:l,selectedConversationId:(l==null?void 0:l.id)??null,service:i,serviceTicketing:r,serviceTicketingNoUSer:a}),[o,l,i,r,a]);return g.jsx(Uc.Provider,{value:S,children:e})},Yt=()=>{const e=I.useContext(Uc);if(!e)throw new Error("useConversation must be used within a ConversationProvider");return e};L.div.attrs({className:"row"})`
31
31
  display: flex;
32
32
  flex-wrap: wrap;
33
33
  margin-right: -8px;
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "minerva-plexus-csd",
3
3
  "private": false,
4
4
  "description": "A reusable chat logic library for React applications",
5
- "version": "1.1.13",
5
+ "version": "1.1.14",
6
6
  "main": "dist/minerva-plexus-csd.umd.js",
7
7
  "module": "dist/minerva-plexus-csd.es.js",
8
8
  "types": "dist/index.d.ts",