codicent-app-sdk 0.5.5 → 0.5.7

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 (152) hide show
  1. package/dist/cjs/_virtual/_commonjsHelpers.js +1 -1
  2. package/dist/cjs/_virtual/index19.js +1 -1
  3. package/dist/cjs/_virtual/index20.js +1 -1
  4. package/dist/cjs/_virtual/index4.js +1 -1
  5. package/dist/cjs/_virtual/index5.js +1 -1
  6. package/dist/cjs/components/AiInput.js +1 -1
  7. package/dist/cjs/components/AudioIcon.js +1 -1
  8. package/dist/cjs/components/ChatInput.js +1 -1
  9. package/dist/cjs/components/ChatMessage.js +1 -1
  10. package/dist/cjs/components/CombinedPlaceholderDialog.js +1 -1
  11. package/dist/cjs/components/Footer.js +1 -1
  12. package/dist/cjs/components/GenericJsonRenderer.js +1 -1
  13. package/dist/cjs/components/Header.js +1 -1
  14. package/dist/cjs/components/HtmlView.js +1 -1
  15. package/dist/cjs/components/MessageInput.js +1 -1
  16. package/dist/cjs/components/MessageItem.js +1 -1
  17. package/dist/cjs/components/Profile.js +1 -1
  18. package/dist/cjs/components/Prompt.js +1 -1
  19. package/dist/cjs/components/SnapFooter.js +1 -1
  20. package/dist/cjs/components/TextHeader.js +1 -1
  21. package/dist/cjs/components/TypingIndicator.js +1 -1
  22. package/dist/cjs/components/UploadFile.js +1 -1
  23. package/dist/cjs/components/UrlProcessor.js +1 -1
  24. package/dist/cjs/components/VoiceIcon.js +1 -1
  25. package/dist/cjs/hooks/useAuthState.js +1 -1
  26. package/dist/cjs/hooks/useChat.js +1 -1
  27. package/dist/cjs/hooks/useCodicentState.js +1 -1
  28. package/dist/cjs/hooks/useObserveDataSchemas.js +1 -1
  29. package/dist/cjs/hooks/useTools.js +1 -1
  30. package/dist/cjs/hooks/useUserRoles.d.ts +1 -1
  31. package/dist/cjs/hooks/useUserRoles.d.ts.map +1 -1
  32. package/dist/cjs/hooks/useUserRoles.js +1 -1
  33. package/dist/cjs/node_modules/@fast-csv/format/build/src/formatter/RowFormatter.js +1 -1
  34. package/dist/cjs/node_modules/@fast-csv/format/build/src/index.js +1 -1
  35. package/dist/cjs/node_modules/@fast-csv/format/build/src/types.js +1 -1
  36. package/dist/cjs/node_modules/@fast-csv/parse/build/src/index.js +1 -1
  37. package/dist/cjs/node_modules/@fast-csv/parse/build/src/transforms/RowTransformerValidator.js +1 -1
  38. package/dist/cjs/node_modules/@fast-csv/parse/build/src/types.js +1 -1
  39. package/dist/cjs/node_modules/concat-map/index.js +1 -1
  40. package/dist/cjs/node_modules/exceljs/lib/xlsx/xform/sheet/cf-ext/cf-rule-ext-xform.js +1 -1
  41. package/dist/cjs/node_modules/fs.realpath/index.js +1 -1
  42. package/dist/cjs/node_modules/fs.realpath/old.js +1 -1
  43. package/dist/cjs/node_modules/glob/common.js +1 -1
  44. package/dist/cjs/node_modules/glob/glob.js +1 -1
  45. package/dist/cjs/node_modules/glob/sync.js +1 -1
  46. package/dist/cjs/node_modules/inflight/inflight.js +1 -1
  47. package/dist/cjs/node_modules/minimatch/minimatch.js +1 -1
  48. package/dist/cjs/node_modules/minimatch/node_modules/brace-expansion/index.js +1 -1
  49. package/dist/cjs/node_modules/react-is/index.js +1 -1
  50. package/dist/cjs/node_modules/safe-buffer/index.js +1 -1
  51. package/dist/cjs/node_modules/scheduler/index.js +1 -1
  52. package/dist/cjs/node_modules/style-to-js/cjs/index.js +1 -1
  53. package/dist/cjs/node_modules/style-to-object/cjs/index.js +1 -1
  54. package/dist/cjs/node_modules/unzipper/node_modules/safe-buffer/index.js +1 -1
  55. package/dist/cjs/node_modules/zip-stream/node_modules/archiver-utils/index.js +1 -1
  56. package/dist/cjs/pages/AppFrame.js +1 -1
  57. package/dist/cjs/pages/Chat.js +1 -1
  58. package/dist/cjs/pages/Compose.js +1 -1
  59. package/dist/cjs/pages/CrmPage.js +1 -1
  60. package/dist/cjs/pages/CrmPagePersistent.js +1 -1
  61. package/dist/cjs/pages/FormAccept.js +1 -1
  62. package/dist/cjs/pages/FormInvite.js +1 -1
  63. package/dist/cjs/pages/Home.js +1 -1
  64. package/dist/cjs/pages/HtmlViewer.js +1 -1
  65. package/dist/cjs/pages/ImageView.js +1 -1
  66. package/dist/cjs/pages/ListPage.js +1 -1
  67. package/dist/cjs/pages/Log.js +1 -1
  68. package/dist/cjs/pages/Login.js +1 -1
  69. package/dist/cjs/pages/Menu.js +1 -1
  70. package/dist/cjs/pages/Purchase.js +1 -1
  71. package/dist/cjs/pages/Sales.js +1 -1
  72. package/dist/cjs/pages/Search.js +1 -1
  73. package/dist/cjs/pages/Snap.js +1 -1
  74. package/dist/cjs/services/codicent.js +1 -1
  75. package/dist/cjs/utils/excelExport.js +1 -1
  76. package/dist/esm/_virtual/_commonjsHelpers.js +1 -1
  77. package/dist/esm/_virtual/index14.js +1 -1
  78. package/dist/esm/_virtual/index17.js +1 -1
  79. package/dist/esm/_virtual/index19.js +1 -1
  80. package/dist/esm/_virtual/index20.js +1 -1
  81. package/dist/esm/_virtual/index4.js +1 -1
  82. package/dist/esm/_virtual/index5.js +1 -1
  83. package/dist/esm/components/AiInput.js +1 -1
  84. package/dist/esm/components/AudioIcon.js +1 -1
  85. package/dist/esm/components/ChatInput.js +1 -1
  86. package/dist/esm/components/ChatMessage.js +1 -1
  87. package/dist/esm/components/CombinedPlaceholderDialog.js +1 -1
  88. package/dist/esm/components/Footer.js +1 -1
  89. package/dist/esm/components/GenericJsonRenderer.js +1 -1
  90. package/dist/esm/components/Header.js +1 -1
  91. package/dist/esm/components/HtmlView.js +1 -1
  92. package/dist/esm/components/MessageInput.js +1 -1
  93. package/dist/esm/components/MessageItem.js +1 -1
  94. package/dist/esm/components/Profile.js +1 -1
  95. package/dist/esm/components/Prompt.js +1 -1
  96. package/dist/esm/components/SnapFooter.js +1 -1
  97. package/dist/esm/components/TextHeader.js +1 -1
  98. package/dist/esm/components/TypingIndicator.js +1 -1
  99. package/dist/esm/components/UploadFile.js +1 -1
  100. package/dist/esm/components/UrlProcessor.js +1 -1
  101. package/dist/esm/components/VoiceIcon.js +1 -1
  102. package/dist/esm/hooks/useAuthState.js +1 -1
  103. package/dist/esm/hooks/useChat.js +1 -1
  104. package/dist/esm/hooks/useCodicentState.js +1 -1
  105. package/dist/esm/hooks/useObserveDataSchemas.js +1 -1
  106. package/dist/esm/hooks/useTools.js +1 -1
  107. package/dist/esm/hooks/useUserRoles.d.ts +1 -1
  108. package/dist/esm/hooks/useUserRoles.d.ts.map +1 -1
  109. package/dist/esm/hooks/useUserRoles.js +1 -1
  110. package/dist/esm/node_modules/@fast-csv/format/build/src/CsvFormatterStream.js +1 -1
  111. package/dist/esm/node_modules/@fast-csv/format/build/src/formatter/index.js +1 -1
  112. package/dist/esm/node_modules/@fast-csv/parse/build/src/CsvParserStream.js +1 -1
  113. package/dist/esm/node_modules/@fast-csv/parse/build/src/parser/index.js +1 -1
  114. package/dist/esm/node_modules/@fast-csv/parse/build/src/transforms/index.js +1 -1
  115. package/dist/esm/node_modules/concat-map/index.js +1 -1
  116. package/dist/esm/node_modules/exceljs/lib/xlsx/xform/sheet/cf-ext/cf-rule-ext-xform.js +1 -1
  117. package/dist/esm/node_modules/fs.realpath/index.js +1 -1
  118. package/dist/esm/node_modules/fs.realpath/old.js +1 -1
  119. package/dist/esm/node_modules/glob/common.js +1 -1
  120. package/dist/esm/node_modules/glob/glob.js +1 -1
  121. package/dist/esm/node_modules/glob/sync.js +1 -1
  122. package/dist/esm/node_modules/inflight/inflight.js +1 -1
  123. package/dist/esm/node_modules/minimatch/minimatch.js +1 -1
  124. package/dist/esm/node_modules/minimatch/node_modules/brace-expansion/index.js +1 -1
  125. package/dist/esm/node_modules/react-is/index.js +1 -1
  126. package/dist/esm/node_modules/scheduler/index.js +1 -1
  127. package/dist/esm/node_modules/style-to-js/cjs/index.js +1 -1
  128. package/dist/esm/node_modules/style-to-object/cjs/index.js +1 -1
  129. package/dist/esm/node_modules/unzipper/node_modules/safe-buffer/index.js +1 -1
  130. package/dist/esm/node_modules/zip-stream/node_modules/archiver-utils/index.js +1 -1
  131. package/dist/esm/pages/AppFrame.js +1 -1
  132. package/dist/esm/pages/Chat.js +1 -1
  133. package/dist/esm/pages/Compose.js +1 -1
  134. package/dist/esm/pages/CrmPage.js +1 -1
  135. package/dist/esm/pages/CrmPagePersistent.js +1 -1
  136. package/dist/esm/pages/FormAccept.js +1 -1
  137. package/dist/esm/pages/FormInvite.js +1 -1
  138. package/dist/esm/pages/Home.js +1 -1
  139. package/dist/esm/pages/HtmlViewer.js +1 -1
  140. package/dist/esm/pages/ImageView.js +1 -1
  141. package/dist/esm/pages/ListPage.js +1 -1
  142. package/dist/esm/pages/Log.js +1 -1
  143. package/dist/esm/pages/Login.js +1 -1
  144. package/dist/esm/pages/Menu.js +1 -1
  145. package/dist/esm/pages/Purchase.js +1 -1
  146. package/dist/esm/pages/Sales.js +1 -1
  147. package/dist/esm/pages/Search.js +1 -1
  148. package/dist/esm/pages/Snap.js +1 -1
  149. package/dist/esm/services/codicent.js +1 -1
  150. package/dist/esm/utils/excelExport.js +1 -1
  151. package/dist/index.d.ts +1 -1
  152. package/package.json +2 -2
@@ -1 +1 @@
1
- import{jsx as o,jsxs as e,Fragment as t}from"react/jsx-runtime";import{useState as n,useCallback as i,useEffect as s}from"react";import{makeStyles as r,tokens as a,shorthands as c,Image as p,mergeClasses as l}from"@fluentui/react-components";import{useNavigate as m}from"react-router-dom";import"../components/Markdown.js";import{Textarea as d}from"../components/Textarea.js";import{Button as h}from"../components/Button.js";import"../components/CompoundButton.js";import{Text as g}from"../components/Text.js";import"../components/Spinner.js";import{Input as u}from"../components/Input.js";import"../components/TextHeader.js";import"../components/TypingIndicator.js";import{Dialog as j,DialogTitle as f,DialogContent as x,DialogActions as C}from"../components/Dialog.js";import"../components/ChatInput.js";import"../components/CombinedPlaceholderDialog.js";import"../components/ChatMessage.js";import"../components/Header.js";import"@fluentui/react-icons";import"../services/codicent.js";import"../utils/MessageContent.js";import"../node_modules/tinycolor2/esm/tinycolor.js";import"../_virtual/index.js";import{getConfigValue as k}from"../config/index.js";import"../utils/cacheManager.js";import"../lib/wavtools/lib/wav_packer.js";import"../lib/wavtools/lib/analysis/audio_analysis.js";import"../lib/wavtools/lib/wav_stream_player.js";import"../lib/wavtools/lib/wav_recorder.js";import"../node_modules/exceljs/excel.js";import"./AppFrame.js";import"./Canvas.js";import"./Chat.js";import"./Compose.js";import"./Snap.js";import"./Search.js";import"./Menu.js";import"./Log.js";import"./Login.js";import"./Home.js";import"./ListPage.js";import"./CrmPage.js";import"./CrmPagePersistent.js";import"./ImageView.js";import"./FormInvite.js";import"./FormAccept.js";import"./Purchase.js";import"../components/Content.js";import{Page as b}from"../components/Page.js";import"./QrScan.js";import v from"../hooks/useLocalization.js";import"../components/FileThumbnail.js";import"react-dom/client";import"../node_modules/@auth0/auth0-react/dist/auth0-react.esm.js";import"../hooks/useAppStyles.js";import"../components/MessageInput.js";import"../components/UploadFile.js";import"../components/SnapFooter.js";import"../components/Profile.js";import"../components/MessageItem.js";import"../components/AiInput.js";import"../components/SearchBox.js";import"../components/DataMessagePicker.js";import"../components/HtmlView.js";import"../components/Footer.js";import{QrCodeDialog as w}from"../components/QrCodeDialog.js";import"../components/QrScanner.js";import"../components/OfflineMessage.js";import"../components/LanguageSelector.js";import"../components/ListView.js";import"../components/RecordModal.js";import"../components/BulkUploadDialog.js";import"../components/CookieBanner.js";const _=r({root:{display:"flex",flexDirection:"column",height:"100%",touchAction:"pan-y"},header:{display:"flex",justifyContent:"space-between",alignItems:"center",color:a.colorNeutralForegroundOnBrand,...c.padding("10px","20px")},logo:{maxWidth:"100px",maxHeight:"50px",height:"auto",cursor:"pointer"},inputContainer:{display:"flex",justifyContent:"flex-end",alignItems:"center",maxWidth:"300px",width:"200px",paddingLeft:"10px"},dashboard:{display:"flex",justifyContent:"space-around",width:"100%",marginTop:"20px"},statBox:{...c.padding("10px"),...c.borderRadius("12px"),minWidth:"50px",textAlign:"center",color:"white"},buttonContainer:{display:"flex",flexDirection:"column",height:"100%",justifyContent:"center",gap:"30px",alignItems:"center",...c.padding("20px")},actionButton:{width:"14rem",minWidth:"15rem",height:"3rem"},textAreaContainer:{display:"flex",flexDirection:"column",gap:"10px"},opened:{backgroundColor:"#1a5614"},not_home:{backgroundColor:"#f44336"},sales:{backgroundColor:"#2196F3"},call_back:{backgroundColor:"#FF9800"},backButton:{position:"absolute",top:"10px",left:"10px",zIndex:1e3}}),y={opened:"#1a5614",not_home:"#f44336",sales:"#2196F3",call_back:"#FF9800"},I=()=>{const r=_(),{t:c}=v(),I=m(),[P,A]=n(""),[F,B]=n(),[M,$]=n({opened:0,not_home:0,sales:0,call_back:0}),[N,D]=n([]),[S,L]=n(!1),[O,H]=n(""),[T,z]=n(""),[R,U]=n(""),[E,G]=n(!1),[W,Q]=n(!1),[V,K]=n(!1),q={backgroundColor:k("APP_HEADER_COLOR")||a.colorBrandBackground},J=i((()=>new Promise((o=>{navigator.geolocation?navigator.geolocation.getCurrentPosition((e=>{const t=`#position (${e.coords.latitude},${e.coords.longitude})`;o(t)})):o(void 0)}))),[B]);s((()=>{window.Codicent.getDataMessages({codicent:k("APP_NAME"),tags:["sales_code"]}).then((o=>{o=o.filter((o=>"1"!==o.data.inactive)),D(o)})).catch(console.error),J()}),[]);const X=async()=>{if(!P)return;const o=["not_home","sales","call_back","opened"],e=new Date;e.setHours(0,0,0,0);const t={...M};for(const n of o){const o=await window.Codicent.getMessages({search:`#${n} #sales_code_${P}`,afterTimestamp:e,length:1e4});t[n]=o.filter((o=>o.content.includes(`#${n} `)&&o.content.includes(`#sales_code_${P}`))).length}$(t)},Y=async(o,e="")=>{const t=await J();console.log("Got position",t);const n=`@${k("APP_NAME")} #sales_code_${P} #${o} ${t||""} ${e.trim().length>0?"#comment ":""}${e}`.trim();await window.Codicent.postMessage({message:n}),X()};return o(b,{hideHeader:!0,children:e("div",{className:r.root,children:[o("div",{className:r.backButton,children:o(h,{appearance:"subtle",icon:"ArrowLeft24Regular",onClick:()=>I(-1),children:c("Tillbaka")})}),e("div",{className:r.header,style:q,children:[o(p,{src:T||k("APP_ICON_URL")||"https://via.placeholder.com/100",className:r.logo,onClick:()=>{T?K(!0):R&&Q(!0)}}),o("div",{className:r.inputContainer,children:o(u,{value:P,onChange:o=>A(o.target.value),onBlur:()=>{const o=N.find((o=>o.data.code===P));if(o)z(`https://codicent.com/app/GetImage?fileId=${o.fileId}&width=100`),U(o.data.link),G(!0),X();else{const o=N.find((o=>o.data.code2===P.toUpperCase()));o?(z(`https://codicent.com/app/GetImage?fileId=${o.fileIds&&o.fileIds.length>1?o.fileIds[1]:o.fileId}&width=100`),U(o.data.link2),G(!0),X()):(G(!1),alert(c("Fel försäljningskod!")))}},placeholder:c("Fyll i försäljningskod"),maxLength:16,size:"large"})})]}),E&&e(t,{children:[o("div",{className:r.dashboard,children:Object.keys(M).map((e=>{return o("div",{className:(t=e,l(r.statBox,r[t])),children:o(g,{weight:"bold",size:400,children:M[e]})},e);var t}))}),o("div",{className:r.buttonContainer,children:Object.entries(y).map((([e,t])=>o(h,{size:"large",className:r.actionButton,style:{backgroundColor:t,color:"white"},onClick:()=>{Y(e),"opened"===e&&L(!0),"sales"===e&&Q(!0)},children:e.charAt(0).toUpperCase()+e.slice(1).replace("_"," ")},e)))}),e(j,{open:S,children:[o(f,{children:c("Skriv in avvikelse")}),o(x,{children:o("div",{className:r.textAreaContainer,children:o(d,{value:O,onChange:o=>H(o.target.value),placeholder:c("Skriv din text här..."),rows:4,size:"large"})})}),o(C,{children:o(h,{appearance:"primary",onClick:()=>{Y("anomaly",`\n${O}`),L(!1),H("")},children:c("Spara")})})]}),e(j,{open:W,children:[o(f,{children:c("Godkännande")}),o(x,{children:c("Är kunden över 23 år?")}),e(C,{children:[o(h,{appearance:"primary",onClick:()=>window.open(R,"_blank"),children:c("OK")}),o(h,{appearance:"secondary",onClick:()=>Q(!1),children:c("Avbryt")})]})]})]}),o(w,{isOpen:V,onDismiss:()=>K(!1),imageUrl:T})]})})};export{I as Sales,I as default};
1
+ import{jsx as o,jsxs as e,Fragment as t}from"react/jsx-runtime";import{useState as n,useCallback as i,useEffect as r}from"react";import{makeStyles as s,tokens as a,shorthands as c,Image as p,mergeClasses as l}from"@fluentui/react-components";import{useNavigate as m}from"react-router-dom";import"../components/Markdown.js";import{Textarea as d}from"../components/Textarea.js";import{Button as h}from"../components/Button.js";import"../components/CompoundButton.js";import{Text as g}from"../components/Text.js";import"../components/Spinner.js";import{Input as u}from"../components/Input.js";import"../components/TextHeader.js";import"../components/TypingIndicator.js";import{Dialog as j,DialogTitle as f,DialogContent as x,DialogActions as C}from"../components/Dialog.js";import"../components/ChatInput.js";import"../components/CombinedPlaceholderDialog.js";import"../components/ChatMessage.js";import"../components/Header.js";import"@fluentui/react-icons";import"../services/codicent.js";import"../utils/MessageContent.js";import"../node_modules/tinycolor2/esm/tinycolor.js";import"../_virtual/index.js";import{getConfigValue as k}from"../config/index.js";import"../utils/cacheManager.js";import"../lib/wavtools/lib/wav_packer.js";import"../lib/wavtools/lib/analysis/audio_analysis.js";import"../lib/wavtools/lib/wav_stream_player.js";import"../lib/wavtools/lib/wav_recorder.js";import"exceljs";import"./AppFrame.js";import"./Canvas.js";import"./Chat.js";import"./Compose.js";import"./Snap.js";import"./Search.js";import"./Menu.js";import"./Log.js";import"./Login.js";import"./Home.js";import"./ListPage.js";import"./CrmPage.js";import"./CrmPagePersistent.js";import"./ImageView.js";import"./FormInvite.js";import"./FormAccept.js";import"./Purchase.js";import"../components/Content.js";import{Page as b}from"../components/Page.js";import"./QrScan.js";import v from"../hooks/useLocalization.js";import"../components/FileThumbnail.js";import"react-dom/client";import"../node_modules/@auth0/auth0-react/dist/auth0-react.esm.js";import"../hooks/useAppStyles.js";import"../components/MessageInput.js";import"../components/UploadFile.js";import"../components/SnapFooter.js";import"../components/Profile.js";import"../components/MessageItem.js";import"../components/AiInput.js";import"../components/SearchBox.js";import"../components/DataMessagePicker.js";import"../components/HtmlView.js";import"../components/Footer.js";import{QrCodeDialog as w}from"../components/QrCodeDialog.js";import"../components/QrScanner.js";import"../components/OfflineMessage.js";import"../components/LanguageSelector.js";import"../components/ListView.js";import"../components/RecordModal.js";import"../components/BulkUploadDialog.js";import"../components/CookieBanner.js";const _=s({root:{display:"flex",flexDirection:"column",height:"100%",touchAction:"pan-y"},header:{display:"flex",justifyContent:"space-between",alignItems:"center",color:a.colorNeutralForegroundOnBrand,...c.padding("10px","20px")},logo:{maxWidth:"100px",maxHeight:"50px",height:"auto",cursor:"pointer"},inputContainer:{display:"flex",justifyContent:"flex-end",alignItems:"center",maxWidth:"300px",width:"200px",paddingLeft:"10px"},dashboard:{display:"flex",justifyContent:"space-around",width:"100%",marginTop:"20px"},statBox:{...c.padding("10px"),...c.borderRadius("12px"),minWidth:"50px",textAlign:"center",color:"white"},buttonContainer:{display:"flex",flexDirection:"column",height:"100%",justifyContent:"center",gap:"30px",alignItems:"center",...c.padding("20px")},actionButton:{width:"14rem",minWidth:"15rem",height:"3rem"},textAreaContainer:{display:"flex",flexDirection:"column",gap:"10px"},opened:{backgroundColor:"#1a5614"},not_home:{backgroundColor:"#f44336"},sales:{backgroundColor:"#2196F3"},call_back:{backgroundColor:"#FF9800"},backButton:{position:"absolute",top:"10px",left:"10px",zIndex:1e3}}),y={opened:"#1a5614",not_home:"#f44336",sales:"#2196F3",call_back:"#FF9800"},I=()=>{const s=_(),{t:c}=v(),I=m(),[P,A]=n(""),[F,B]=n(),[M,$]=n({opened:0,not_home:0,sales:0,call_back:0}),[N,D]=n([]),[S,L]=n(!1),[O,H]=n(""),[T,z]=n(""),[R,U]=n(""),[E,G]=n(!1),[W,Q]=n(!1),[V,K]=n(!1),q={backgroundColor:k("APP_HEADER_COLOR")||a.colorBrandBackground},J=i((()=>new Promise((o=>{navigator.geolocation?navigator.geolocation.getCurrentPosition((e=>{const t=`#position (${e.coords.latitude},${e.coords.longitude})`;o(t)})):o(void 0)}))),[B]);r((()=>{window.Codicent.getDataMessages({codicent:k("APP_NAME"),tags:["sales_code"]}).then((o=>{o=o.filter((o=>"1"!==o.data.inactive)),D(o)})).catch(console.error),J()}),[]);const X=async()=>{if(!P)return;const o=["not_home","sales","call_back","opened"],e=new Date;e.setHours(0,0,0,0);const t={...M};for(const n of o){const o=await window.Codicent.getMessages({search:`#${n} #sales_code_${P}`,afterTimestamp:e,length:1e4});t[n]=o.filter((o=>o.content.includes(`#${n} `)&&o.content.includes(`#sales_code_${P}`))).length}$(t)},Y=async(o,e="")=>{const t=await J();console.log("Got position",t);const n=`@${k("APP_NAME")} #sales_code_${P} #${o} ${t||""} ${e.trim().length>0?"#comment ":""}${e}`.trim();await window.Codicent.postMessage({message:n}),X()};return o(b,{hideHeader:!0,children:e("div",{className:s.root,children:[o("div",{className:s.backButton,children:o(h,{appearance:"subtle",icon:"ArrowLeft24Regular",onClick:()=>I(-1),children:c("Tillbaka")})}),e("div",{className:s.header,style:q,children:[o(p,{src:T||k("APP_ICON_URL")||"https://via.placeholder.com/100",className:s.logo,onClick:()=>{T?K(!0):R&&Q(!0)}}),o("div",{className:s.inputContainer,children:o(u,{value:P,onChange:o=>A(o.target.value),onBlur:()=>{const o=N.find((o=>o.data.code===P));if(o)z(`https://codicent.com/app/GetImage?fileId=${o.fileId}&width=100`),U(o.data.link),G(!0),X();else{const o=N.find((o=>o.data.code2===P.toUpperCase()));o?(z(`https://codicent.com/app/GetImage?fileId=${o.fileIds&&o.fileIds.length>1?o.fileIds[1]:o.fileId}&width=100`),U(o.data.link2),G(!0),X()):(G(!1),alert(c("Fel försäljningskod!")))}},placeholder:c("Fyll i försäljningskod"),maxLength:16,size:"large"})})]}),E&&e(t,{children:[o("div",{className:s.dashboard,children:Object.keys(M).map((e=>{return o("div",{className:(t=e,l(s.statBox,s[t])),children:o(g,{weight:"bold",size:400,children:M[e]})},e);var t}))}),o("div",{className:s.buttonContainer,children:Object.entries(y).map((([e,t])=>o(h,{size:"large",className:s.actionButton,style:{backgroundColor:t,color:"white"},onClick:()=>{Y(e),"opened"===e&&L(!0),"sales"===e&&Q(!0)},children:e.charAt(0).toUpperCase()+e.slice(1).replace("_"," ")},e)))}),e(j,{open:S,children:[o(f,{children:c("Skriv in avvikelse")}),o(x,{children:o("div",{className:s.textAreaContainer,children:o(d,{value:O,onChange:o=>H(o.target.value),placeholder:c("Skriv din text här..."),rows:4,size:"large"})})}),o(C,{children:o(h,{appearance:"primary",onClick:()=>{Y("anomaly",`\n${O}`),L(!1),H("")},children:c("Spara")})})]}),e(j,{open:W,children:[o(f,{children:c("Godkännande")}),o(x,{children:c("Är kunden över 23 år?")}),e(C,{children:[o(h,{appearance:"primary",onClick:()=>window.open(R,"_blank"),children:c("OK")}),o(h,{appearance:"secondary",onClick:()=>Q(!1),children:c("Avbryt")})]})]})]}),o(w,{isOpen:V,onDismiss:()=>K(!1),imageUrl:T})]})})};export{I as Sales,I as default};
@@ -1 +1 @@
1
- import{jsx as o,jsxs as t}from"react/jsx-runtime";import{useRef as e,useState as n,useEffect as r}from"react";import{makeStyles as i,tokens as s}from"@fluentui/react-components";import a from"../components/Markdown.js";import"../components/Textarea.js";import{Button as m}from"../components/Button.js";import"../components/CompoundButton.js";import{Title as p}from"../components/Title.js";import"../components/Spinner.js";import"../components/TextHeader.js";import c from"../components/TypingIndicator.js";import"../components/Dialog.js";import l from"../components/ChatInput.js";import"../components/CombinedPlaceholderDialog.js";import"../components/ChatMessage.js";import"../components/Header.js";import"@fluentui/react-icons";import d from"../hooks/useStateWithLocalStorage.js";import{CodicentService as j}from"../services/codicent.js";import"../utils/MessageContent.js";import"../node_modules/tinycolor2/esm/tinycolor.js";import"../_virtual/index.js";import{getConfigValue as u}from"../config/index.js";import"../utils/cacheManager.js";import"../lib/wavtools/lib/wav_packer.js";import"../lib/wavtools/lib/analysis/audio_analysis.js";import"../lib/wavtools/lib/wav_stream_player.js";import"../lib/wavtools/lib/wav_recorder.js";import"../node_modules/exceljs/excel.js";import"./AppFrame.js";import"./Canvas.js";import"./Chat.js";import"./Compose.js";import"./Snap.js";import"./Menu.js";import"./Log.js";import"./Login.js";import"./Home.js";import"./ListPage.js";import"./CrmPage.js";import"./CrmPagePersistent.js";import"./ImageView.js";import"./FormInvite.js";import"./FormAccept.js";import"./Sales.js";import"react-router-dom";import"./Purchase.js";import"../components/Content.js";import{Page as g}from"../components/Page.js";import"./QrScan.js";import h from"../hooks/useLocalization.js";import"../components/FileThumbnail.js";import"react-dom/client";import"../node_modules/@auth0/auth0-react/dist/auth0-react.esm.js";import{useChat as f}from"../hooks/useChat.js";import{useTemplateVariables as x}from"../hooks/useTemplateVariables.js";import"../hooks/useAppStyles.js";import"../components/MessageInput.js";import"../components/UploadFile.js";import"../components/SnapFooter.js";import"../components/Profile.js";import"../components/MessageItem.js";import"../components/AiInput.js";import"../components/SearchBox.js";import"../components/DataMessagePicker.js";import"../components/HtmlView.js";import"../components/Footer.js";import"../components/QrCodeDialog.js";import"../components/QrScanner.js";import"../components/OfflineMessage.js";import"../components/LanguageSelector.js";import"../components/ListView.js";import"../components/RecordModal.js";import"../components/BulkUploadDialog.js";import"../components/CookieBanner.js";const C=i({chatContainer:{width:"100%",flex:1,maxWidth:"800px",height:"100%",backgroundColor:"#ffffff",display:"flex",flexDirection:"column",margin:"0 auto",overflow:"hidden","@media (max-width: 768px)":{maxWidth:"100%",borderRadius:"0"},"@media (max-width: 480px)":{},backgroundPosition:"calc(50%) center",backgroundRepeat:"no-repeat",backgroundSize:"contain",touchAction:"pan-y",overflowY:"auto",marginBottom:"16px"},chatMessages:{display:"flex",flexDirection:"column",flex:1,padding:"16px",overflowY:"auto",touchAction:"pan-y"},inputArea:{display:"flex",flexDirection:"column",justifyContent:"start",alignItems:"center",height:"100%",padding:"0 16px"},promptButtons:{display:"flex",flexDirection:"row",flexWrap:"wrap",justifyContent:"start",alignItems:"center",gap:"8px",marginTop:"8px",marginLeft:"6px",marginRight:"2px",marginBottom:"12px"},answerArea:{width:"100%",marginLeft:"12px",marginRight:"12px",padding:"12px",borderRadius:"16px",marginBottom:"24px"},title:{marginLeft:"12px",padding:"16px"}}),A=({state:i})=>{const A=C(),{t:w}=h(),{messages:T,isBotTyping:_,handleSend:v,newChat:S}=f(i.stateMachine),N=e(null),{service:b}=i;u("CHAT_BOT_BACKGROUND_COLOR")||s.colorBrandBackground2;const[k,O]=d(i.context.selectedApp+"_searchprompts",["Leta information","Vad kan jag göra?","Sök supportställe"]),[y,I]=n(),[B,M]=n(null),[P,D]=n(!1);x(b.uploadFile);r((()=>{_&&D(!0)}),[_]),r((()=>{S();const o=u("APP_CONFIG"),t=u("APP_BUTTONS");t?o.apps[t].questions&&O(o.apps[t].questions.map((o=>w(o)))):console.error("APP_BUTTONS is not defined in the configuration."),void 0!==u("ANONYMOUS_CODICENT")&&void 0!==u("ANONYMOUS_TOKEN")?(b.codicent=u("ANONYMOUS_CODICENT"),b.setToken(u("ANONYMOUS_TOKEN"))):console.error("Anonymous Codicent or Token is not defined in the configuration.")}),[S,b,O,w]),r((()=>{setTimeout((()=>{N.current?.scrollIntoView({behavior:"smooth"})}),10)}),[T]);const L=o=>{I(o),v(o)};return r((()=>{const o=T.filter((o=>"bot"===o.sender));let t=o.length>0?o[o.length-1]:null;M({...t,createdAt:new Date}),t&&D(!1)}),[T]),o(g,{hideHeader:!0,hideFooter:!0,children:t("div",{id:"search-container",className:A.chatContainer,style:{backgroundImage:`url(${u("CHAT_BACKGROUND_IMAGE_URL")})`},children:[o("div",{className:A.title,children:o(p,{children:w(u("APP_SEARCH_TITLE")||"Frågor")})}),t("div",{className:A.inputArea,children:[o(l,{noMemory:!0,defaultText:y,codicent:i.context.selectedApp,disableSend:_,onSend:L,rows:3,getImageUrl:j.getImageUrl,getFileInfo:o=>b.getFileInfo(o),selectAll:!0}),o("div",{className:A.promptButtons,children:k.length>0&&k.map(((t,e)=>o(m,{onClick:()=>L(t),size:"large",appearance:"primary",shape:"circular",children:t},`search-prompt-${e}`)))}),P&&o(c,{}),B&&!_&&t("div",{className:A.answerArea,children:[o("div",{ref:N}),o(a,{content:B.content})]})]})]})})};export{A as default};
1
+ import{jsx as o,jsxs as t}from"react/jsx-runtime";import{useRef as e,useState as n,useEffect as r}from"react";import{makeStyles as i,tokens as s}from"@fluentui/react-components";import a from"../components/Markdown.js";import"../components/Textarea.js";import{Button as m}from"../components/Button.js";import"../components/CompoundButton.js";import{Title as p}from"../components/Title.js";import"../components/Spinner.js";import"../components/TextHeader.js";import c from"../components/TypingIndicator.js";import"../components/Dialog.js";import l from"../components/ChatInput.js";import"../components/CombinedPlaceholderDialog.js";import"../components/ChatMessage.js";import"../components/Header.js";import"@fluentui/react-icons";import d from"../hooks/useStateWithLocalStorage.js";import{CodicentService as j}from"../services/codicent.js";import"../utils/MessageContent.js";import"../node_modules/tinycolor2/esm/tinycolor.js";import"../_virtual/index.js";import{getConfigValue as u}from"../config/index.js";import"../utils/cacheManager.js";import"../lib/wavtools/lib/wav_packer.js";import"../lib/wavtools/lib/analysis/audio_analysis.js";import"../lib/wavtools/lib/wav_stream_player.js";import"../lib/wavtools/lib/wav_recorder.js";import"exceljs";import"./AppFrame.js";import"./Canvas.js";import"./Chat.js";import"./Compose.js";import"./Snap.js";import"./Menu.js";import"./Log.js";import"./Login.js";import"./Home.js";import"./ListPage.js";import"./CrmPage.js";import"./CrmPagePersistent.js";import"./ImageView.js";import"./FormInvite.js";import"./FormAccept.js";import"./Sales.js";import"react-router-dom";import"./Purchase.js";import"../components/Content.js";import{Page as g}from"../components/Page.js";import"./QrScan.js";import h from"../hooks/useLocalization.js";import"../components/FileThumbnail.js";import"react-dom/client";import"../node_modules/@auth0/auth0-react/dist/auth0-react.esm.js";import{useChat as f}from"../hooks/useChat.js";import{useTemplateVariables as x}from"../hooks/useTemplateVariables.js";import"../hooks/useAppStyles.js";import"../components/MessageInput.js";import"../components/UploadFile.js";import"../components/SnapFooter.js";import"../components/Profile.js";import"../components/MessageItem.js";import"../components/AiInput.js";import"../components/SearchBox.js";import"../components/DataMessagePicker.js";import"../components/HtmlView.js";import"../components/Footer.js";import"../components/QrCodeDialog.js";import"../components/QrScanner.js";import"../components/OfflineMessage.js";import"../components/LanguageSelector.js";import"../components/ListView.js";import"../components/RecordModal.js";import"../components/BulkUploadDialog.js";import"../components/CookieBanner.js";const C=i({chatContainer:{width:"100%",flex:1,maxWidth:"800px",height:"100%",backgroundColor:"#ffffff",display:"flex",flexDirection:"column",margin:"0 auto",overflow:"hidden","@media (max-width: 768px)":{maxWidth:"100%",borderRadius:"0"},"@media (max-width: 480px)":{},backgroundPosition:"calc(50%) center",backgroundRepeat:"no-repeat",backgroundSize:"contain",touchAction:"pan-y",overflowY:"auto",marginBottom:"16px"},chatMessages:{display:"flex",flexDirection:"column",flex:1,padding:"16px",overflowY:"auto",touchAction:"pan-y"},inputArea:{display:"flex",flexDirection:"column",justifyContent:"start",alignItems:"center",height:"100%",padding:"0 16px"},promptButtons:{display:"flex",flexDirection:"row",flexWrap:"wrap",justifyContent:"start",alignItems:"center",gap:"8px",marginTop:"8px",marginLeft:"6px",marginRight:"2px",marginBottom:"12px"},answerArea:{width:"100%",marginLeft:"12px",marginRight:"12px",padding:"12px",borderRadius:"16px",marginBottom:"24px"},title:{marginLeft:"12px",padding:"16px"}}),A=({state:i})=>{const A=C(),{t:w}=h(),{messages:T,isBotTyping:v,handleSend:_,newChat:S}=f(i.stateMachine),N=e(null),{service:b}=i;u("CHAT_BOT_BACKGROUND_COLOR")||s.colorBrandBackground2;const[k,O]=d(i.context.selectedApp+"_searchprompts",["Leta information","Vad kan jag göra?","Sök supportställe"]),[y,I]=n(),[B,M]=n(null),[P,D]=n(!1);x(b.uploadFile);r((()=>{v&&D(!0)}),[v]),r((()=>{S();const o=u("APP_CONFIG"),t=u("APP_BUTTONS");t?o.apps[t].questions&&O(o.apps[t].questions.map((o=>w(o)))):console.error("APP_BUTTONS is not defined in the configuration."),void 0!==u("ANONYMOUS_CODICENT")&&void 0!==u("ANONYMOUS_TOKEN")?(b.codicent=u("ANONYMOUS_CODICENT"),b.setToken(u("ANONYMOUS_TOKEN"))):console.error("Anonymous Codicent or Token is not defined in the configuration.")}),[S,b,O,w]),r((()=>{setTimeout((()=>{N.current?.scrollIntoView({behavior:"smooth"})}),10)}),[T]);const L=o=>{I(o),_(o)};return r((()=>{const o=T.filter((o=>"bot"===o.sender));let t=o.length>0?o[o.length-1]:null;M({...t,createdAt:new Date}),t&&D(!1)}),[T]),o(g,{hideHeader:!0,hideFooter:!0,children:t("div",{id:"search-container",className:A.chatContainer,style:{backgroundImage:`url(${u("CHAT_BACKGROUND_IMAGE_URL")})`},children:[o("div",{className:A.title,children:o(p,{children:w(u("APP_SEARCH_TITLE")||"Frågor")})}),t("div",{className:A.inputArea,children:[o(l,{noMemory:!0,defaultText:y,codicent:i.context.selectedApp,disableSend:v,onSend:L,rows:3,getImageUrl:j.getImageUrl,getFileInfo:o=>b.getFileInfo(o),selectAll:!0}),o("div",{className:A.promptButtons,children:k.length>0&&k.map(((t,e)=>o(m,{onClick:()=>L(t),size:"large",appearance:"primary",shape:"circular",children:t},`search-prompt-${e}`)))}),P&&o(c,{}),B&&!v&&t("div",{className:A.answerArea,children:[o("div",{ref:N}),o(a,{content:B.content})]})]})]})})};export{A as default};
@@ -1 +1 @@
1
- import{jsxs as o,jsx as t}from"react/jsx-runtime";import{useState as e,useRef as i,useMemo as n,useCallback as r,useEffect as s}from"react";import{makeStyles as a}from"@fluentui/react-components";import{useSearchParams as p,useNavigate as m}from"react-router-dom";import"../components/Markdown.js";import"../components/Textarea.js";import"../components/Button.js";import"../components/CompoundButton.js";import{Text as c}from"../components/Text.js";import"../components/Spinner.js";import"../components/TextHeader.js";import"../components/TypingIndicator.js";import"../components/Dialog.js";import"../components/ChatInput.js";import{CombinedPlaceholderDialog as l}from"../components/CombinedPlaceholderDialog.js";import"../components/ChatMessage.js";import"../components/Header.js";import"@fluentui/react-icons";import"../services/codicent.js";import"../utils/MessageContent.js";import"../node_modules/tinycolor2/esm/tinycolor.js";import"../_virtual/index.js";import"../config/index.js";import"../utils/cacheManager.js";import"../lib/wavtools/lib/wav_packer.js";import"../lib/wavtools/lib/analysis/audio_analysis.js";import"../lib/wavtools/lib/wav_stream_player.js";import"../lib/wavtools/lib/wav_recorder.js";import"../node_modules/exceljs/excel.js";import"./AppFrame.js";import"./Canvas.js";import"./Chat.js";import"./Compose.js";import"./Search.js";import"./Menu.js";import"./Log.js";import"./Login.js";import"./Home.js";import"./ListPage.js";import"./CrmPage.js";import"./CrmPagePersistent.js";import"./ImageView.js";import"./FormInvite.js";import"./FormAccept.js";import"./Sales.js";import"./Purchase.js";import"../components/Content.js";import"../components/Page.js";import"./QrScan.js";import d from"../hooks/useLocalization.js";import"../components/FileThumbnail.js";import"react-dom/client";import"../node_modules/@auth0/auth0-react/dist/auth0-react.esm.js";import{useTemplateVariables as u}from"../hooks/useTemplateVariables.js";import"../hooks/useAppStyles.js";import h from"../components/MessageInput.js";import"../components/UploadFile.js";import g from"../components/SnapFooter.js";import"../components/Profile.js";import"../components/MessageItem.js";import"../components/AiInput.js";import"../components/SearchBox.js";import"../components/DataMessagePicker.js";import"../components/HtmlView.js";import"../components/Footer.js";import"../components/QrCodeDialog.js";import"../components/QrScanner.js";import"../components/OfflineMessage.js";import"../components/LanguageSelector.js";import"../components/ListView.js";import"../components/RecordModal.js";import"../components/BulkUploadDialog.js";import"../components/CookieBanner.js";const j=a({container:{position:"relative",height:"100vh",width:"100vw",overflow:"auto"},flashOverlay:{position:"fixed",top:0,left:0,width:"100%",height:"100%",backgroundColor:"transparent",transition:"background-color 0.2s ease-out",pointerEvents:"none",zIndex:3},video:{position:"absolute",top:0,left:0,width:"100%",height:"100%",objectFit:"cover",zIndex:1},canvas:{display:"none"},bottomControls:{position:"fixed",bottom:"100px",width:"100%",display:"flex",justifyContent:"center",alignItems:"center",zIndex:2,boxSizing:"border-box"},controlContainer:{width:"100%",maxWidth:"600px",position:"relative"},sendButton:{position:"absolute",right:"10px",bottom:"10px",width:"50px",height:"50px",borderRadius:"50%",backgroundColor:"#0078d4",color:"white",border:"none",cursor:"pointer",display:"flex",justifyContent:"center",alignItems:"center"},topControls:{position:"fixed",top:"20px",width:"100%",display:"flex",justifyContent:"space-between",alignItems:"center",zIndex:2,padding:"0 10px",boxSizing:"border-box"},backButton:{width:"60px",height:"60px",borderRadius:"50%",backgroundColor:"transparent",color:"white",border:"none",cursor:"pointer"},input:{padding:"5px",width:"200px",fontSize:"larger",backgroundColor:"#fff8"},bottomButtons:{position:"fixed",bottom:"0px",width:"100%",display:"flex",justifyContent:"space-around",alignItems:"center",zIndex:2,boxSizing:"border-box"},iconButton:{width:"60px",height:"60px",borderRadius:"50%",backgroundColor:"transparent",color:"white",border:"none",cursor:"pointer"},centerText:{position:"fixed",top:"30%",left:"50%",transform:"translate(-50%, -50%)",zIndex:2,textAlign:"center"}}),f=({state:a,audio:f})=>{const w=j(),{service:x}=a,[b,v]=e(null),[C,y]=e(!0),k=i(null),I=i(null),[F]=p(),S=F.get("extra"),z=F.get("template"),[M,T]=e(""),[P]=e("log"),V=n((()=>new Audio("/audio/camera.mp3")),[]),[B,$]=e(!1),E=m(),{t:_}=d(),{extractTemplateVariables:L}=u(x.uploadFile),[N,D]=e(L(z||"")),[H,A]=e(N.length>0),[O,R]=e(""),[Q,U]=e(100),W=r((()=>N.map((o=>`#${o.value}`)).join(" ")),[N]);s((()=>{const o=W();R(`${S?" #"+S:""}${o.length>0?" "+o:""}`.trim())}),[N,S,W]),s((()=>{if(window.visualViewport){const o=()=>{const o=window.visualViewport?window.innerHeight-window.visualViewport.height:0;U(o>150?o+20:100)};return window.visualViewport.addEventListener("resize",o),o(),()=>{window.visualViewport&&window.visualViewport.removeEventListener("resize",o)}}}),[]);const K=async o=>{try{const t=new FormData;t.append("file",o);const e=await x.uploadFile(o.name,t),i=W(),n=`${P?" #"+P:""}${S?" #"+S:""}${i.length>0?" "+i:""} #photo #file:${e}`;await x.sendMessage(n)}catch(o){alert(_("Failed to send image:")+" "+o)}};return s((()=>()=>{b&&b.getTracks().forEach((o=>o.stop()))}),[b]),o("div",{className:w.container,children:[t("div",{className:w.flashOverlay,style:{backgroundColor:B?"#ffffff":"transparent"}}),t("video",{ref:k,autoPlay:!0,playsInline:!0,className:w.video}),t("canvas",{ref:I,width:"640",height:"480",className:w.canvas}),!b&&t(c,{weight:"semibold",size:400,className:w.centerText,children:_("Klicka på Byt kamera för att starta!")}),t("div",{className:w.bottomControls,style:{bottom:`${Q}px`},children:t("div",{className:w.controlContainer,children:t(h,{onSend:async()=>{if(""===M.trim())return;const o=W(),t=`${P?" #"+P:""}${S?" #"+S:""}${o.length>0?" "+o:""} ${M}`;try{await x.sendMessage(t),T("")}catch(o){alert(_("Failed to send message: ")+o)}},rows:4,onChange:T})})}),t("div",{className:w.bottomButtons,children:t(g,{audio:f,onHome:()=>E("/"),onTakePhoto:()=>{const o=I.current,t=k.current;if(o&&t){o.width=t.videoWidth,o.height=t.videoHeight;const e=o.getContext("2d");e&&(V.play(),$(!0),setTimeout((()=>$(!1)),100),e.drawImage(t,0,0,o.width,o.height),o.toBlob((o=>{if(o){const t=new File([o],"snapshot.png",{type:"image/png"});K(t)}})))}},onSwichCamera:()=>{y((o=>!o)),(async()=>{b&&b.getTracks().forEach((o=>o.stop()));const o={video:{facingMode:C?"user":"environment"},audio:!1};try{const t=await navigator.mediaDevices.getUserMedia(o);v(t),k.current&&(k.current.srcObject=t,k.current.play())}catch(o){console.error("Error accessing the camera: ",o),o instanceof Error?alert(_("Error accessing the camera:")+" "+o.message):alert(_("Error accessing the camera"))}})()},tag:O})}),t(l,{open:H,templateVariables:N,filePlaceholders:[],onTemplateVariablesChange:D,onFilePlaceholdersChange:()=>{},onConfirm:()=>A(!1),onCancel:()=>{A(!1),E(-1)},uploadFile:x.uploadFile})]})};export{f as default};
1
+ import{jsxs as o,jsx as t}from"react/jsx-runtime";import{useState as e,useRef as i,useMemo as n,useCallback as r,useEffect as s}from"react";import{makeStyles as a}from"@fluentui/react-components";import{useSearchParams as p,useNavigate as m}from"react-router-dom";import"../components/Markdown.js";import"../components/Textarea.js";import"../components/Button.js";import"../components/CompoundButton.js";import{Text as c}from"../components/Text.js";import"../components/Spinner.js";import"../components/TextHeader.js";import"../components/TypingIndicator.js";import"../components/Dialog.js";import"../components/ChatInput.js";import{CombinedPlaceholderDialog as l}from"../components/CombinedPlaceholderDialog.js";import"../components/ChatMessage.js";import"../components/Header.js";import"@fluentui/react-icons";import"../services/codicent.js";import"../utils/MessageContent.js";import"../node_modules/tinycolor2/esm/tinycolor.js";import"../_virtual/index.js";import"../config/index.js";import"../utils/cacheManager.js";import"../lib/wavtools/lib/wav_packer.js";import"../lib/wavtools/lib/analysis/audio_analysis.js";import"../lib/wavtools/lib/wav_stream_player.js";import"../lib/wavtools/lib/wav_recorder.js";import"exceljs";import"./AppFrame.js";import"./Canvas.js";import"./Chat.js";import"./Compose.js";import"./Search.js";import"./Menu.js";import"./Log.js";import"./Login.js";import"./Home.js";import"./ListPage.js";import"./CrmPage.js";import"./CrmPagePersistent.js";import"./ImageView.js";import"./FormInvite.js";import"./FormAccept.js";import"./Sales.js";import"./Purchase.js";import"../components/Content.js";import"../components/Page.js";import"./QrScan.js";import d from"../hooks/useLocalization.js";import"../components/FileThumbnail.js";import"react-dom/client";import"../node_modules/@auth0/auth0-react/dist/auth0-react.esm.js";import{useTemplateVariables as u}from"../hooks/useTemplateVariables.js";import"../hooks/useAppStyles.js";import h from"../components/MessageInput.js";import"../components/UploadFile.js";import g from"../components/SnapFooter.js";import"../components/Profile.js";import"../components/MessageItem.js";import"../components/AiInput.js";import"../components/SearchBox.js";import"../components/DataMessagePicker.js";import"../components/HtmlView.js";import"../components/Footer.js";import"../components/QrCodeDialog.js";import"../components/QrScanner.js";import"../components/OfflineMessage.js";import"../components/LanguageSelector.js";import"../components/ListView.js";import"../components/RecordModal.js";import"../components/BulkUploadDialog.js";import"../components/CookieBanner.js";const j=a({container:{position:"relative",height:"100vh",width:"100vw",overflow:"auto"},flashOverlay:{position:"fixed",top:0,left:0,width:"100%",height:"100%",backgroundColor:"transparent",transition:"background-color 0.2s ease-out",pointerEvents:"none",zIndex:3},video:{position:"absolute",top:0,left:0,width:"100%",height:"100%",objectFit:"cover",zIndex:1},canvas:{display:"none"},bottomControls:{position:"fixed",bottom:"100px",width:"100%",display:"flex",justifyContent:"center",alignItems:"center",zIndex:2,boxSizing:"border-box"},controlContainer:{width:"100%",maxWidth:"600px",position:"relative"},sendButton:{position:"absolute",right:"10px",bottom:"10px",width:"50px",height:"50px",borderRadius:"50%",backgroundColor:"#0078d4",color:"white",border:"none",cursor:"pointer",display:"flex",justifyContent:"center",alignItems:"center"},topControls:{position:"fixed",top:"20px",width:"100%",display:"flex",justifyContent:"space-between",alignItems:"center",zIndex:2,padding:"0 10px",boxSizing:"border-box"},backButton:{width:"60px",height:"60px",borderRadius:"50%",backgroundColor:"transparent",color:"white",border:"none",cursor:"pointer"},input:{padding:"5px",width:"200px",fontSize:"larger",backgroundColor:"#fff8"},bottomButtons:{position:"fixed",bottom:"0px",width:"100%",display:"flex",justifyContent:"space-around",alignItems:"center",zIndex:2,boxSizing:"border-box"},iconButton:{width:"60px",height:"60px",borderRadius:"50%",backgroundColor:"transparent",color:"white",border:"none",cursor:"pointer"},centerText:{position:"fixed",top:"30%",left:"50%",transform:"translate(-50%, -50%)",zIndex:2,textAlign:"center"}}),f=({state:a,audio:f})=>{const w=j(),{service:x}=a,[b,v]=e(null),[C,y]=e(!0),k=i(null),I=i(null),[F]=p(),S=F.get("extra"),z=F.get("template"),[M,T]=e(""),[P]=e("log"),V=n((()=>new Audio("/audio/camera.mp3")),[]),[B,$]=e(!1),E=m(),{t:L}=d(),{extractTemplateVariables:N}=u(x.uploadFile),[_,D]=e(N(z||"")),[H,A]=e(_.length>0),[O,R]=e(""),[Q,U]=e(100),W=r((()=>_.map((o=>`#${o.value}`)).join(" ")),[_]);s((()=>{const o=W();R(`${S?" #"+S:""}${o.length>0?" "+o:""}`.trim())}),[_,S,W]),s((()=>{if(window.visualViewport){const o=()=>{const o=window.visualViewport?window.innerHeight-window.visualViewport.height:0;U(o>150?o+20:100)};return window.visualViewport.addEventListener("resize",o),o(),()=>{window.visualViewport&&window.visualViewport.removeEventListener("resize",o)}}}),[]);const K=async o=>{try{const t=new FormData;t.append("file",o);const e=await x.uploadFile(o.name,t),i=W(),n=`${P?" #"+P:""}${S?" #"+S:""}${i.length>0?" "+i:""} #photo #file:${e}`;await x.sendMessage(n)}catch(o){alert(L("Failed to send image:")+" "+o)}};return s((()=>()=>{b&&b.getTracks().forEach((o=>o.stop()))}),[b]),o("div",{className:w.container,children:[t("div",{className:w.flashOverlay,style:{backgroundColor:B?"#ffffff":"transparent"}}),t("video",{ref:k,autoPlay:!0,playsInline:!0,className:w.video}),t("canvas",{ref:I,width:"640",height:"480",className:w.canvas}),!b&&t(c,{weight:"semibold",size:400,className:w.centerText,children:L("Klicka på Byt kamera för att starta!")}),t("div",{className:w.bottomControls,style:{bottom:`${Q}px`},children:t("div",{className:w.controlContainer,children:t(h,{onSend:async()=>{if(""===M.trim())return;const o=W(),t=`${P?" #"+P:""}${S?" #"+S:""}${o.length>0?" "+o:""} ${M}`;try{await x.sendMessage(t),T("")}catch(o){alert(L("Failed to send message: ")+o)}},rows:4,onChange:T})})}),t("div",{className:w.bottomButtons,children:t(g,{audio:f,onHome:()=>E("/"),onTakePhoto:()=>{const o=I.current,t=k.current;if(o&&t){o.width=t.videoWidth,o.height=t.videoHeight;const e=o.getContext("2d");e&&(V.play(),$(!0),setTimeout((()=>$(!1)),100),e.drawImage(t,0,0,o.width,o.height),o.toBlob((o=>{if(o){const t=new File([o],"snapshot.png",{type:"image/png"});K(t)}})))}},onSwichCamera:()=>{y((o=>!o)),(async()=>{b&&b.getTracks().forEach((o=>o.stop()));const o={video:{facingMode:C?"user":"environment"},audio:!1};try{const t=await navigator.mediaDevices.getUserMedia(o);v(t),k.current&&(k.current.srcObject=t,k.current.play())}catch(o){console.error("Error accessing the camera: ",o),o instanceof Error?alert(L("Error accessing the camera:")+" "+o.message):alert(L("Error accessing the camera"))}})()},tag:O})}),t(l,{open:H,templateVariables:_,filePlaceholders:[],onTemplateVariablesChange:D,onFilePlaceholdersChange:()=>{},onConfirm:()=>A(!1),onCancel:()=>{A(!1),E(-1)},uploadFile:x.uploadFile})]})};export{f as default};
@@ -1 +1 @@
1
- import{loadStripe as t}from"../node_modules/@stripe/stripe-js/dist/index.js";import e from"../utils/MessageContent.js";import"../node_modules/tinycolor2/esm/tinycolor.js";import"react/jsx-runtime";import"react";import"../_virtual/index.js";import"../config/index.js";import"../utils/cacheManager.js";import"../lib/wavtools/lib/wav_packer.js";import"../lib/wavtools/lib/analysis/audio_analysis.js";import"../lib/wavtools/lib/wav_stream_player.js";import"../lib/wavtools/lib/wav_recorder.js";import"../node_modules/exceljs/excel.js";var o;let n="https://codicent.com/",a="https://pubsub.codicent.com/hub",s="-";const i=()=>"undefined"!=typeof window&&void 0!==window.Codicent&&"function"==typeof window.Codicent.init,r=t=>{t&&"string"==typeof t?(n=t.endsWith("/")?t:t+"/",i()&&window.Codicent.init({token:s,baseUrl:n,signalRHost:a})):console.warn("Invalid base URL provided, using default")},c=t=>{t&&"string"==typeof t&&(a=t,i()&&window.Codicent.init({token:s,baseUrl:n,signalRHost:a}))},h=()=>void 0!==window.Codicent&&(window.Codicent.handleMessage=function(t){const e=new CustomEvent("codicent-log",{detail:{message:t}});window.dispatchEvent(e)},window.Codicent.init({token:s,baseUrl:n,signalRHost:a}),!0);let d=h();if(!d){const t=setInterval((()=>{d=h(),d&&clearInterval(t)}),100)}class l{constructor(o){this.createDataMessage=async(t,e,o)=>await window.Codicent.data.create({codicent:o||this.codicent,tag:t,data:e}),this.readDataMessages=async(t,e,o,n,a,s,i,r)=>await window.Codicent.data.read({codicent:o||this.codicent,tag:t,search:e,start:n,length:a,afterTimestamp:s,beforeTimestamp:i,dataFilters:r}),this.readOneDataMessage=async t=>await window.Codicent.data.readOne(t),this.getLeafDataMessage=async(t,e)=>{const o=e||this.codicent;try{const e=await fetch(`${this.options.API_BASE_URL}app/GetLeafMessageByOriginalMessageId?project=${encodeURIComponent(o)}&originalMessageId=${encodeURIComponent(t)}`,{headers:{Authorization:`Bearer ${this.getToken()}`}});if(!e.ok)return null;const n=await e.json();if(!n||!n.content)return null;const a=n.content.indexOf("{");if(-1===a)return null;const s=JSON.parse(n.content.slice(a));return{id:n.id,fileId:n.fileId??null,fileIds:n.fileIds??[],data:s,createdAt:n.createdAt,tags:n.tags??[],mentions:n.mentions??[]}}catch{return null}},this.updateDataMessage=async(t,e,o)=>await window.Codicent.data.update({id:t,data:e,codicent:o||this.codicent}),this.deleteDataMessage=async(t,e)=>await window.Codicent.data.delete({id:t,codicent:e||this.codicent}),this.getSchema=async(t,e)=>{try{const e=await fetch(`${this.options.API_BASE_URL}api/GetSchema/${t}`,{method:"GET",headers:{Authorization:`Bearer ${this.options.APP_LOG_TOKEN}`,"Content-Type":"application/json"}});if(!e.ok){if(404===e.status)return null;throw new Error(`Failed to fetch schema: ${e.statusText}`)}const o=await e.text();return JSON.parse(o)}catch(e){return console.error(`Error fetching schema for tag ${t}:`,e),null}},this.getAppTheme=async()=>{try{const t=await window.Codicent.getDataMessages({tags:["app-theme"],codicent:this.codicent});return t.length>0?t[0].data:null}catch(t){return console.error("Error fetching app theme:",t),null}},this.getAppButtons=async()=>{const t=(await window.Codicent.getDataMessages({tags:[this.options.BUTTON_TAG],codicent:this.codicent})).map((t=>t.data));return t.sort(((t,e)=>t.title>e.title?1:-1)),t},this.getAppTasks=async()=>[...(await window.Codicent.getMessages({search:`@${this.codicent} #app-task`,length:50})).map((t=>{const o=new e(t.content).content.split("\n"),n=o[0],a=o.slice(1).join("\n");return{id:t.id,title:n,content:a}})),...(await window.Codicent.getDataMessages({tags:["skill"],codicent:this.codicent})).map((t=>t.data)).filter((t=>t.name&&t.title)).map((t=>({id:t.name,title:t.title,content:t.content||t.description||""})))],this.getAppPrompts=async t=>(await window.Codicent.getDataMessages({tags:["chatprompt"],codicent:t||this.codicent})).map((t=>t.data)).map((({title:t,prompt:e})=>({title:t,prompt:e}))),this.uploadFile=async(t,e)=>await window.Codicent.upload(e,t),this.getFileInfo=async t=>await window.Codicent.getFileInfo(t),this.generateApiToken=async(t,e)=>{const o=await fetch(`${n}api/GenerateApiToken?project=${this.codicent}${t?`&expires=${t.toISOString()}`:""}${e?`&forUserNickname=${e}`:""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText}`);return await o.text()},this.sendMessage=(t,e,o)=>window.Codicent.postMessage({message:`@${o||this.codicent} ${t}`,type:"text",parentId:e}),this.chat=(t,e,o)=>window.Codicent.getChatReply4({message:t,codicent:o||this.codicent,messageId:e}),this.getMessagesFast=async(t,e,o=100,a=void 0,s,i=0)=>{const r=await this.request(`${n}app/AppGetMessages`,"POST",{headers:[["Authorization",`Bearer ${this.getToken()}`],["Content-Type","application/json; charset=utf-8"]],body:JSON.stringify({tags:t,codicent:s||this.codicent,search:e,start:i,length:o})});let c=await r.json();if(c.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),a){const t=await this.getPublicFlow(a);c=c.concat(t),c.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime()))}return c},this.getMessages=async(t,e,o=10)=>{let n=[];const a=t.map((async t=>{const e=await window.Codicent.getMessages({search:`@${this.codicent} #${t}`,length:o});return"chat"===t&&e.forEach((t=>t.content=`#chat\n${t.content}`)),e}));if((await Promise.all(a)).forEach((t=>{n=n.concat(t)})),e)try{const t=await this.getPublicFlow(e);n=n.concat(t)}catch(t){console.warn("Error fetching public flow, PUBLIC_TAG missing in codicent?",t)}return n=n.filter(((t,e,o)=>e===o.findIndex((e=>e.id===t.id)))),n.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime())),n},this.registerUser=async(t,e,o,s)=>{const i=await fetch(`${n}app/RegisterAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${s}`]],body:JSON.stringify({nickname:t,email:e,userId:o})});if(!i.ok)return"";const r=await i.text();return window.Codicent.init({token:r,baseUrl:n,signalRHost:a}),r},this.loginUser=async(t,e)=>{try{const o=await fetch(`${n}app/LoginAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${e}`]],body:JSON.stringify({userId:t})});if(!o.ok)return 404===o.status||400===o.status?null:401===o.status?(this.handleUnauthorized(),null):"";const a=await o.text();return this.setToken(a),a}catch(t){return console.warn("Error logging in user:",t),""}},this.loginMicrosoftUser=async(t,e)=>{try{const o=await fetch(`${n}app/LoginMicrosoftUser`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${e}`]],body:JSON.stringify({userId:t})});if(!o.ok)return 404===o.status||400===o.status?null:401===o.status?(this.handleUnauthorized(),null):"";const a=await o.text();return this.setToken(a),a}catch(t){return console.warn("Error logging in Microsoft user:",t),""}},this.registerMicrosoftUser=async(t,e,o,a)=>{const s=await fetch(`${n}app/RegisterMicrosoftUser`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${a}`]],body:JSON.stringify({nickname:t,email:e,userId:o})});if(!s.ok)return"";return await s.text()},this.nicknameExists=async t=>{const e=await fetch(`${n}app/NicknameExists?nickname=${encodeURIComponent(t)}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"]]});if(!e.ok)return!1;return await e.json()},this.logout=()=>{this.setToken("")},this.isRegistered=()=>null!==localStorage.getItem("codicent_nickname"),this.getApps=async()=>{try{const t=await fetch(`${n}app/AppGetApps`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw t.status,new Error(`${t.statusText}`);const e=await t.json();return e.filter(((t,e,o)=>e===o.findIndex((e=>e.id===t.id))&&(this.options.APP_NAME||t.id.startsWith(this.options.APP_PREFIX))))}catch(t){return console.warn("Error fetching apps:",t),null}},this.addFollower=async(t,e)=>{const o=await fetch(`${n}app/AddFollower?nickname=${t}&followerNickname=${e}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText||"Failed to add follower!"}`);return await o.json()},this.cloneProject=async(t,e)=>{const o=await fetch(`${n}app/CloneProject?project=${t}&newProject=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText}`);let a=await o.json();if(a){const t='#data #app-theme \n{\n "textcolor": "#212121",\n "backgroundcolor": "#273044",\n "color": "#ffffff",\n "logo": "https://codicent.com/logo512.png",\n "title": "",\n "themeColor": "#581d71",\n "buttonColor": "#c0c0c0",\n "buttonTextColor": "#000000",\n "font": "Montserrat",\n "welcome": "Hej {{username}}!",\n "chatPlaceholder": "Tjena, Loociz här! Vad vill du?",\n "textPlaceholder": "Skriv det du vill spara, så tar jag (Loociz alltså) hand om det!",\n "transcriptionInstructions": "Tryck på knappen för att start och sedan stoppa ljudinspelning."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(a=!1)}catch{a=!1}if(a){const t='#data #app-button\n{\n "title": "Ta fram företagsinfo",\n "url": "/#/chat?text=Hej!%20Jag%20vill%20spara%20f%C3%B6retagsinfo.%20Guida%20mig%20steg%20f%C3%B6r%20steg%2C%20ett%20i%20taget%2C%20tills%20vi%20har%20all%20info%20om%20mitt%20f%C3%B6retag.%20Exempel%20p%C3%A5%20data%3A%20f%C3%B6retagsnamn%20eller%20id%C3%A9namn%2C%20org.nr.%2C%20%C3%A4gare%2C%20kontaktinformation%2C%20vision%2C%20aff%C3%A4rsid%C3%A9%2C%20mm."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(a=!1)}catch{a=!1}}}return a},this.getNickname=async()=>{try{const t=s.split(".")[1],e=atob(t),o=JSON.parse(e),a=o.sub||o.userId,i=await fetch(`${n}app/GetNickname?userId=${a}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!i.ok)throw 401===i.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${i.statusText}`);return await i.text()}catch{return""}},this.getChatInstructions=async()=>{try{const t=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:1});if(t.length>0)return t[0].content}catch{console.warn("Error fetching chat instructions")}return""},this.updateChatInstructions=async t=>{try{const e=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:100}),o=`@${this.codicent} #instructions\n${t}`;e.length>0?e[0].content!==o&&(console.log("updating instructions",o),await window.Codicent.postMessage({message:o,type:"text",parentId:e[0].id})):(console.log("new instructions",o),await window.Codicent.postMessage({message:o,type:"text"}))}catch{console.warn("Error updating chat instructions")}},this.getUserInfo=async(t,e=!1)=>{const o=await fetch(`${n}app/GetUserInfo?nickname=${t}${e?"&t="+Date.now():""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw 401===o.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${o.statusText}`);const a=await o.json(),{email:s,picture:i,description:r,followers:c,properties:h,owner:d}=a;return{nickname:t,email:s,name:r,picture:i,followers:c,properties:h,owner:d}},this.updateUserInfo=async({nickname:t,email:e,name:o,picture:a})=>{const s=await fetch(`${n}app/AddOrUpdateUser`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify({nickname:t,email:e,name:o,picture:a,description:""})});if(!s.ok)throw s.status,new Error(`${s.statusText}`);return await this.getUserInfo(t,!0)},this.requestInvite=async(t,e)=>{const o=await fetch(`${n}app/CreateInvitationOrRequest?forUserNickname=${t}&toProjectNickname=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!o.ok||(console.warn(`requestInvite() => ${o.statusText}`),!1)},this.getProjectInfo=this.getUserInfo,this.updateMembersAccess=async(t,e)=>{const o=await fetch(`${n}app/AddOrUpdateProjectProperty?project=${t}&key=APP_EDITORS&value=${e.join(",")}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!o.ok||(console.warn(`updateMembersAccess() => ${o.statusText}`),!1)},this.getMembersAccess=async t=>{const e=(await this.getProjectInfo(t,!0)).properties.find((t=>"APP_EDITORS"===t.name));return e&&e.value?e.value.split(","):[]},this.getMemberInfo=async(t,e)=>{const o=await fetch(`${n}app/GetMemberInfo?projectNickname=${encodeURIComponent(t)}&memberNickname=${encodeURIComponent(e)}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw 401===o.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${o.statusText}`);return await o.json()},this.setToken=t=>{s=t,s&&window.Codicent.init({token:s,baseUrl:n,signalRHost:a})},this.getToken=()=>s,this.checkPurchaseStatus=async()=>{const t=await fetch(`${n}payments/GetPaymentStatus`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw new Error("Failed to check purchase status");const{isPaid:e}=await t.json();return e},this.checkSubscriptionStatus=async()=>{if(!this.options.SUBSCRIPTION_NEEDED)return"active";const t=await fetch(`${n}payments/GetSubscriptionStatus?t=${Date.now()}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`],["Cache-Control","no-cache, no-store, must-revalidate"],["Pragma","no-cache"],["Expires","0"]]});if(!t.ok)throw new Error("Failed to check subscription status");const{status:e}=await t.json();return e},this.createCheckoutSession=async t=>{const e=this.options.STRIPE_SOURCE,o=this.options.STRIPE_TRIAL_PERIOD_DAYS,a={priceId:t,successUrl:window.location.href,cancelUrl:window.location.href};e&&(a.source=e),o&&o>0&&(a.trialPeriodDays=o);const s=await fetch(`${n}payments/CreateCheckoutSession`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify(a)});if(!s.ok)throw new Error("Failed to create checkout session");const{id:i}=await s.json();return i},this.redirectToCheckout=async e=>{const o=await t(this.options.STRIPE_PUBLIC_KEY);if(!o)throw new Error("Stripe failed to load");const n=await this.createCheckoutSession(e),{error:a}=await o.redirectToCheckout({sessionId:n});if(a)throw new Error(a.message)},this.getChatHistory=async t=>{const e=await fetch(`${n}api/GetMessageHistory?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get chat history");let o=await e.json();return o=o.filter((t=>!(t.content.includes("#function_result")||t.content.includes("#finish_reason_function_call")||t.content.includes("#function_results_batch")||t.content.includes("#finish_reason_tool_calls_batch")))),o},this.getPublicFlow=async t=>{const e=await fetch(`${n}app/GetPublicFlow?codicent=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get public flow");const o=await e.json();return o.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),o},this.getMessageContent=async t=>{const e=await fetch(`${n}app/GetMessageContent?id=${t}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(e.ok){const t=await e.json();return{content:t.content,url:t.url}}return{content:"",url:""}},this.logAction=async(t,e)=>{if(!this.options.APP_LOG_CODICENT)return"";const o={content:`@${this.options.APP_LOG_CODICENT} #debug #${e}\n${t}`,type:"text"},a=await fetch(`${n}app/AddChatMessage`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.options.APP_LOG_TOKEN}`]],body:JSON.stringify(o)});if(!a.ok)throw new Error(`${a.statusText||"Failed to post log message!"}`);return(await a.json()).id},this.createApp=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.APP_PREFIX}${t}`;if(!await this.nicknameExists(e)){if(await this.cloneProject(this.options.APP_TEMPLATE,e)){if(this.options.ANONYMOUS_TOKEN)try{const t=this.options.ANONYMOUS_TOKEN.split(".")[1],o=atob(t),n=JSON.parse(o).nickname;if(!await this.addFollower(e,n))throw new Error("Failed to add follower: "+n)}catch(t){console.error("Error extracting adding anonymous follower:",t)}return e}}}}catch(t){console.error("Error creating app:",t)}return null},this.findUsername=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.USER_PREFIX}${t}`;if(!await this.nicknameExists(e))return e}}catch(t){console.warn("Error finding username:",t)}return null},this.getForms=async()=>{const t=await this.request(`${n}app/GetForms?codicent=${this.codicent}`,"GET",{headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await t.json()},this.getFormById=async t=>{const e=await fetch(`${n}app/GetFormById?id=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await e.json()},this.getTodoStatus=async t=>{const e=await fetch(`${n}app/GetTodoStatus?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return e.ok?await e.text():(e.status,console.warn(`getTodoStatus() => ${e.statusText}`),"unknown")},this.updateTodoStatus=async(t,e)=>{const o=await fetch(`${n}app/UpdateTodoStatus?messageId=${t}&status=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)return console.warn(`updateTodoStatus() => ${o.statusText}`),!1;return await o.json()},this.codicent="",this.options=o,r(o.API_BASE_URL),o.PUBSUB_URL&&c(o.PUBSUB_URL)}async request(t,e,o={}){const n={};o.headers&&o.headers.forEach((([t,e])=>{n[t]=e}));const a=await fetch(t,{...o,method:e,headers:n});if(!a.ok)throw 401===a.status&&this.handleUnauthorized(),new Error(`${a.statusText}`);return a}handleUnauthorized(){this.onUnauthorized&&this.onUnauthorized()}async getRealtimeSessionToken(t="alloy",e="openai"){const o=`${n}realtime/session?voice=${t}&provider=${e}`,a=await fetch(o,{headers:{Authorization:`Bearer ${this.getToken()}`}});if(!a.ok)throw new Error(`Failed to fetch session token: ${a.statusText}`);const s=await a.json(),i=s.client_secret?.value??s.value;if(!i)throw new Error("No ephemeral key returned from session endpoint");return i}async getRealtimeConfig(t="openai"){try{const e=`${n}realtime/config?provider=${t}`,o=await fetch(e,{method:"GET",headers:{Authorization:`Bearer ${this.getToken()}`}});return o.ok?await o.json():null}catch(t){return console.warn("Failed to fetch realtime config:",t),null}}}o=l,l.getImageUrl=(t,e)=>`${n}app/GetImage?fileId=${t}&width=${e}`,l.getFileUrl=(t,e)=>`${n}app/DownloadFile?fileId=${t}${e?`&extension=${e}`:""}`,l.downloadFile=async t=>{fetch(o.getFileUrl(t.id)).then((t=>{if(t.headers.forEach(((t,e)=>{console.log(`${e}: ${t}`)})),t.ok)return t.blob();throw new Error("Network response was not ok.")})).then((e=>{const o=window.URL.createObjectURL(e),n=document.createElement("a");n.style.display="none",n.href=o,n.download=t.filename,document.body.appendChild(n),n.click(),window.URL.revokeObjectURL(o)})).catch((t=>{console.error("There was a problem with the fetch operation:",t)}))},l.getMiniChatReplyOld=async(t,e="codicent-mini",o)=>{let a={project:e,message:t};o&&(a.messageId=o);const i=await fetch(`${n}app/GetAi2ChatReply`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${s}`]],body:JSON.stringify(a)});if(!i.ok)return void i.status;return(await i.json()).content.replace("@codicent-mini","").trim()},l.getMiniChatReply=async(t,e="codicent-mini",o,a=3e5,i=2e3,r)=>{const c={project:e,message:t};let h;o&&(c.messageId=o),r&&(c.previousResponseId=r);try{const t=await fetch(`${n}app/StartAi2ChatAsync`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${s}`]],body:JSON.stringify(c)});if(!t.ok)return t.status,void console.error(`Failed to start AI chat: ${t.status}`);if(h=(await t.json()).promptMessageId,!h)return void console.error("No promptMessageId returned from server")}catch(t){return void console.error("Error starting AI chat:",t)}const d=Date.now();for(;Date.now()-d<a;)try{const t=await fetch(`${n}app/GetAi2ChatReplyStatus?promptMessageId=${h}`,{method:"GET",headers:[["Authorization",`Bearer ${s}`]]});if(202===t.status){await new Promise((t=>setTimeout(t,i)));continue}if(!t.ok)return void console.error(`Error polling AI chat status: ${t.status}`);const o=await t.json(),a=o.content??o.content??"";return{content:a.replace(`@${e}`,"").replace("@codicent-mini","").trim(),responseId:o.responseId??void 0}}catch(t){return void console.error("Error polling AI chat status:",t)}console.error("Polling timeout reached for AI chat")},l.getTranslations=async(t,e,o="codicent-mini")=>{if(!s||"-"===s)return{translation:t};const a=await fetch(`${n}app/GetTranslations`,{method:"POST",headers:{"Content-Type":"application/json; charset=utf-8",Authorization:`Bearer ${s}`},body:JSON.stringify({project:o,text:t,targetLanguage:e})});if(!a.ok)throw a.status,new Error(`Failed to get translations: ${a.statusText}`);return await a.json()};export{l as CodicentService,r as setBaseUrl,c as setSignalRHost};
1
+ import{loadStripe as t}from"../node_modules/@stripe/stripe-js/dist/index.js";import e from"../utils/MessageContent.js";import"../node_modules/tinycolor2/esm/tinycolor.js";import"react/jsx-runtime";import"react";import"../_virtual/index.js";import"../config/index.js";import"../utils/cacheManager.js";import"../lib/wavtools/lib/wav_packer.js";import"../lib/wavtools/lib/analysis/audio_analysis.js";import"../lib/wavtools/lib/wav_stream_player.js";import"../lib/wavtools/lib/wav_recorder.js";import"exceljs";var o;let n="https://codicent.com/",a="https://pubsub.codicent.com/hub",s="-";const i=()=>"undefined"!=typeof window&&void 0!==window.Codicent&&"function"==typeof window.Codicent.init,r=t=>{t&&"string"==typeof t?(n=t.endsWith("/")?t:t+"/",i()&&window.Codicent.init({token:s,baseUrl:n,signalRHost:a})):console.warn("Invalid base URL provided, using default")},c=t=>{t&&"string"==typeof t&&(a=t,i()&&window.Codicent.init({token:s,baseUrl:n,signalRHost:a}))},h=()=>void 0!==window.Codicent&&(window.Codicent.handleMessage=function(t){const e=new CustomEvent("codicent-log",{detail:{message:t}});window.dispatchEvent(e)},window.Codicent.init({token:s,baseUrl:n,signalRHost:a}),!0);let d=h();if(!d){const t=setInterval((()=>{d=h(),d&&clearInterval(t)}),100)}class l{constructor(o){this.createDataMessage=async(t,e,o)=>await window.Codicent.data.create({codicent:o||this.codicent,tag:t,data:e}),this.readDataMessages=async(t,e,o,n,a,s,i,r)=>await window.Codicent.data.read({codicent:o||this.codicent,tag:t,search:e,start:n,length:a,afterTimestamp:s,beforeTimestamp:i,dataFilters:r}),this.readOneDataMessage=async t=>await window.Codicent.data.readOne(t),this.getLeafDataMessage=async(t,e)=>{const o=e||this.codicent;try{const e=await fetch(`${this.options.API_BASE_URL}app/GetLeafMessageByOriginalMessageId?project=${encodeURIComponent(o)}&originalMessageId=${encodeURIComponent(t)}`,{headers:{Authorization:`Bearer ${this.getToken()}`}});if(!e.ok)return null;const n=await e.json();if(!n||!n.content)return null;const a=n.content.indexOf("{");if(-1===a)return null;const s=JSON.parse(n.content.slice(a));return{id:n.id,fileId:n.fileId??null,fileIds:n.fileIds??[],data:s,createdAt:n.createdAt,tags:n.tags??[],mentions:n.mentions??[]}}catch{return null}},this.updateDataMessage=async(t,e,o)=>await window.Codicent.data.update({id:t,data:e,codicent:o||this.codicent}),this.deleteDataMessage=async(t,e)=>await window.Codicent.data.delete({id:t,codicent:e||this.codicent}),this.getSchema=async(t,e)=>{try{const e=await fetch(`${this.options.API_BASE_URL}api/GetSchema/${t}`,{method:"GET",headers:{Authorization:`Bearer ${this.options.APP_LOG_TOKEN}`,"Content-Type":"application/json"}});if(!e.ok){if(404===e.status)return null;throw new Error(`Failed to fetch schema: ${e.statusText}`)}const o=await e.text();return JSON.parse(o)}catch(e){return console.error(`Error fetching schema for tag ${t}:`,e),null}},this.getAppTheme=async()=>{try{const t=await window.Codicent.getDataMessages({tags:["app-theme"],codicent:this.codicent});return t.length>0?t[0].data:null}catch(t){return console.error("Error fetching app theme:",t),null}},this.getAppButtons=async()=>{const t=(await window.Codicent.getDataMessages({tags:[this.options.BUTTON_TAG],codicent:this.codicent})).map((t=>t.data));return t.sort(((t,e)=>t.title>e.title?1:-1)),t},this.getAppTasks=async()=>[...(await window.Codicent.getMessages({search:`@${this.codicent} #app-task`,length:50})).map((t=>{const o=new e(t.content).content.split("\n"),n=o[0],a=o.slice(1).join("\n");return{id:t.id,title:n,content:a}})),...(await window.Codicent.getDataMessages({tags:["skill"],codicent:this.codicent})).map((t=>t.data)).filter((t=>t.name&&t.title)).map((t=>({id:t.name,title:t.title,content:t.content||t.description||""})))],this.getAppPrompts=async t=>(await window.Codicent.getDataMessages({tags:["chatprompt"],codicent:t||this.codicent})).map((t=>t.data)).map((({title:t,prompt:e})=>({title:t,prompt:e}))),this.uploadFile=async(t,e)=>await window.Codicent.upload(e,t),this.getFileInfo=async t=>await window.Codicent.getFileInfo(t),this.generateApiToken=async(t,e)=>{const o=await fetch(`${n}api/GenerateApiToken?project=${this.codicent}${t?`&expires=${t.toISOString()}`:""}${e?`&forUserNickname=${e}`:""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText}`);return await o.text()},this.sendMessage=(t,e,o)=>window.Codicent.postMessage({message:`@${o||this.codicent} ${t}`,type:"text",parentId:e}),this.chat=(t,e,o)=>window.Codicent.getChatReply4({message:t,codicent:o||this.codicent,messageId:e}),this.getMessagesFast=async(t,e,o=100,a=void 0,s,i=0)=>{const r=await this.request(`${n}app/AppGetMessages`,"POST",{headers:[["Authorization",`Bearer ${this.getToken()}`],["Content-Type","application/json; charset=utf-8"]],body:JSON.stringify({tags:t,codicent:s||this.codicent,search:e,start:i,length:o})});let c=await r.json();if(c.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),a){const t=await this.getPublicFlow(a);c=c.concat(t),c.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime()))}return c},this.getMessages=async(t,e,o=10)=>{let n=[];const a=t.map((async t=>{const e=await window.Codicent.getMessages({search:`@${this.codicent} #${t}`,length:o});return"chat"===t&&e.forEach((t=>t.content=`#chat\n${t.content}`)),e}));if((await Promise.all(a)).forEach((t=>{n=n.concat(t)})),e)try{const t=await this.getPublicFlow(e);n=n.concat(t)}catch(t){console.warn("Error fetching public flow, PUBLIC_TAG missing in codicent?",t)}return n=n.filter(((t,e,o)=>e===o.findIndex((e=>e.id===t.id)))),n.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime())),n},this.registerUser=async(t,e,o,s)=>{const i=await fetch(`${n}app/RegisterAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${s}`]],body:JSON.stringify({nickname:t,email:e,userId:o})});if(!i.ok)return"";const r=await i.text();return window.Codicent.init({token:r,baseUrl:n,signalRHost:a}),r},this.loginUser=async(t,e)=>{try{const o=await fetch(`${n}app/LoginAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${e}`]],body:JSON.stringify({userId:t})});if(!o.ok)return 404===o.status||400===o.status?null:401===o.status?(this.handleUnauthorized(),null):"";const a=await o.text();return this.setToken(a),a}catch(t){return console.warn("Error logging in user:",t),""}},this.loginMicrosoftUser=async(t,e)=>{try{const o=await fetch(`${n}app/LoginMicrosoftUser`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${e}`]],body:JSON.stringify({userId:t})});if(!o.ok)return 404===o.status||400===o.status?null:401===o.status?(this.handleUnauthorized(),null):"";const a=await o.text();return this.setToken(a),a}catch(t){return console.warn("Error logging in Microsoft user:",t),""}},this.registerMicrosoftUser=async(t,e,o,a)=>{const s=await fetch(`${n}app/RegisterMicrosoftUser`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${a}`]],body:JSON.stringify({nickname:t,email:e,userId:o})});if(!s.ok)return"";return await s.text()},this.nicknameExists=async t=>{const e=await fetch(`${n}app/NicknameExists?nickname=${encodeURIComponent(t)}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"]]});if(!e.ok)return!1;return await e.json()},this.logout=()=>{this.setToken("")},this.isRegistered=()=>null!==localStorage.getItem("codicent_nickname"),this.getApps=async()=>{try{const t=await fetch(`${n}app/AppGetApps`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw t.status,new Error(`${t.statusText}`);const e=await t.json();return e.filter(((t,e,o)=>e===o.findIndex((e=>e.id===t.id))&&(this.options.APP_NAME||t.id.startsWith(this.options.APP_PREFIX))))}catch(t){return console.warn("Error fetching apps:",t),null}},this.addFollower=async(t,e)=>{const o=await fetch(`${n}app/AddFollower?nickname=${t}&followerNickname=${e}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText||"Failed to add follower!"}`);return await o.json()},this.cloneProject=async(t,e)=>{const o=await fetch(`${n}app/CloneProject?project=${t}&newProject=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText}`);let a=await o.json();if(a){const t='#data #app-theme \n{\n "textcolor": "#212121",\n "backgroundcolor": "#273044",\n "color": "#ffffff",\n "logo": "https://codicent.com/logo512.png",\n "title": "",\n "themeColor": "#581d71",\n "buttonColor": "#c0c0c0",\n "buttonTextColor": "#000000",\n "font": "Montserrat",\n "welcome": "Hej {{username}}!",\n "chatPlaceholder": "Tjena, Loociz här! Vad vill du?",\n "textPlaceholder": "Skriv det du vill spara, så tar jag (Loociz alltså) hand om det!",\n "transcriptionInstructions": "Tryck på knappen för att start och sedan stoppa ljudinspelning."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(a=!1)}catch{a=!1}if(a){const t='#data #app-button\n{\n "title": "Ta fram företagsinfo",\n "url": "/#/chat?text=Hej!%20Jag%20vill%20spara%20f%C3%B6retagsinfo.%20Guida%20mig%20steg%20f%C3%B6r%20steg%2C%20ett%20i%20taget%2C%20tills%20vi%20har%20all%20info%20om%20mitt%20f%C3%B6retag.%20Exempel%20p%C3%A5%20data%3A%20f%C3%B6retagsnamn%20eller%20id%C3%A9namn%2C%20org.nr.%2C%20%C3%A4gare%2C%20kontaktinformation%2C%20vision%2C%20aff%C3%A4rsid%C3%A9%2C%20mm."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(a=!1)}catch{a=!1}}}return a},this.getNickname=async()=>{try{const t=s.split(".")[1],e=atob(t),o=JSON.parse(e),a=o.sub||o.userId,i=await fetch(`${n}app/GetNickname?userId=${a}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!i.ok)throw 401===i.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${i.statusText}`);return await i.text()}catch{return""}},this.getChatInstructions=async()=>{try{const t=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:1});if(t.length>0)return t[0].content}catch{console.warn("Error fetching chat instructions")}return""},this.updateChatInstructions=async t=>{try{const e=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:100}),o=`@${this.codicent} #instructions\n${t}`;e.length>0?e[0].content!==o&&(console.log("updating instructions",o),await window.Codicent.postMessage({message:o,type:"text",parentId:e[0].id})):(console.log("new instructions",o),await window.Codicent.postMessage({message:o,type:"text"}))}catch{console.warn("Error updating chat instructions")}},this.getUserInfo=async(t,e=!1)=>{const o=await fetch(`${n}app/GetUserInfo?nickname=${t}${e?"&t="+Date.now():""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw 401===o.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${o.statusText}`);const a=await o.json(),{email:s,picture:i,description:r,followers:c,properties:h,owner:d}=a;return{nickname:t,email:s,name:r,picture:i,followers:c,properties:h,owner:d}},this.updateUserInfo=async({nickname:t,email:e,name:o,picture:a})=>{const s=await fetch(`${n}app/AddOrUpdateUser`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify({nickname:t,email:e,name:o,picture:a,description:""})});if(!s.ok)throw s.status,new Error(`${s.statusText}`);return await this.getUserInfo(t,!0)},this.requestInvite=async(t,e)=>{const o=await fetch(`${n}app/CreateInvitationOrRequest?forUserNickname=${t}&toProjectNickname=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!o.ok||(console.warn(`requestInvite() => ${o.statusText}`),!1)},this.getProjectInfo=this.getUserInfo,this.updateMembersAccess=async(t,e)=>{const o=await fetch(`${n}app/AddOrUpdateProjectProperty?project=${t}&key=APP_EDITORS&value=${e.join(",")}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!o.ok||(console.warn(`updateMembersAccess() => ${o.statusText}`),!1)},this.getMembersAccess=async t=>{const e=(await this.getProjectInfo(t,!0)).properties.find((t=>"APP_EDITORS"===t.name));return e&&e.value?e.value.split(","):[]},this.getMemberInfo=async(t,e)=>{const o=await fetch(`${n}app/GetMemberInfo?projectNickname=${encodeURIComponent(t)}&memberNickname=${encodeURIComponent(e)}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw 401===o.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${o.statusText}`);return await o.json()},this.setToken=t=>{s=t,s&&window.Codicent.init({token:s,baseUrl:n,signalRHost:a})},this.getToken=()=>s,this.checkPurchaseStatus=async()=>{const t=await fetch(`${n}payments/GetPaymentStatus`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw new Error("Failed to check purchase status");const{isPaid:e}=await t.json();return e},this.checkSubscriptionStatus=async()=>{if(!this.options.SUBSCRIPTION_NEEDED)return"active";const t=await fetch(`${n}payments/GetSubscriptionStatus?t=${Date.now()}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`],["Cache-Control","no-cache, no-store, must-revalidate"],["Pragma","no-cache"],["Expires","0"]]});if(!t.ok)throw new Error("Failed to check subscription status");const{status:e}=await t.json();return e},this.createCheckoutSession=async t=>{const e=this.options.STRIPE_SOURCE,o=this.options.STRIPE_TRIAL_PERIOD_DAYS,a={priceId:t,successUrl:window.location.href,cancelUrl:window.location.href};e&&(a.source=e),o&&o>0&&(a.trialPeriodDays=o);const s=await fetch(`${n}payments/CreateCheckoutSession`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify(a)});if(!s.ok)throw new Error("Failed to create checkout session");const{id:i}=await s.json();return i},this.redirectToCheckout=async e=>{const o=await t(this.options.STRIPE_PUBLIC_KEY);if(!o)throw new Error("Stripe failed to load");const n=await this.createCheckoutSession(e),{error:a}=await o.redirectToCheckout({sessionId:n});if(a)throw new Error(a.message)},this.getChatHistory=async t=>{const e=await fetch(`${n}api/GetMessageHistory?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get chat history");let o=await e.json();return o=o.filter((t=>!(t.content.includes("#function_result")||t.content.includes("#finish_reason_function_call")||t.content.includes("#function_results_batch")||t.content.includes("#finish_reason_tool_calls_batch")))),o},this.getPublicFlow=async t=>{const e=await fetch(`${n}app/GetPublicFlow?codicent=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get public flow");const o=await e.json();return o.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),o},this.getMessageContent=async t=>{const e=await fetch(`${n}app/GetMessageContent?id=${t}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(e.ok){const t=await e.json();return{content:t.content,url:t.url}}return{content:"",url:""}},this.logAction=async(t,e)=>{if(!this.options.APP_LOG_CODICENT)return"";const o={content:`@${this.options.APP_LOG_CODICENT} #debug #${e}\n${t}`,type:"text"},a=await fetch(`${n}app/AddChatMessage`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.options.APP_LOG_TOKEN}`]],body:JSON.stringify(o)});if(!a.ok)throw new Error(`${a.statusText||"Failed to post log message!"}`);return(await a.json()).id},this.createApp=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.APP_PREFIX}${t}`;if(!await this.nicknameExists(e)){if(await this.cloneProject(this.options.APP_TEMPLATE,e)){if(this.options.ANONYMOUS_TOKEN)try{const t=this.options.ANONYMOUS_TOKEN.split(".")[1],o=atob(t),n=JSON.parse(o).nickname;if(!await this.addFollower(e,n))throw new Error("Failed to add follower: "+n)}catch(t){console.error("Error extracting adding anonymous follower:",t)}return e}}}}catch(t){console.error("Error creating app:",t)}return null},this.findUsername=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.USER_PREFIX}${t}`;if(!await this.nicknameExists(e))return e}}catch(t){console.warn("Error finding username:",t)}return null},this.getForms=async()=>{const t=await this.request(`${n}app/GetForms?codicent=${this.codicent}`,"GET",{headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await t.json()},this.getFormById=async t=>{const e=await fetch(`${n}app/GetFormById?id=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await e.json()},this.getTodoStatus=async t=>{const e=await fetch(`${n}app/GetTodoStatus?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return e.ok?await e.text():(e.status,console.warn(`getTodoStatus() => ${e.statusText}`),"unknown")},this.updateTodoStatus=async(t,e)=>{const o=await fetch(`${n}app/UpdateTodoStatus?messageId=${t}&status=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)return console.warn(`updateTodoStatus() => ${o.statusText}`),!1;return await o.json()},this.codicent="",this.options=o,r(o.API_BASE_URL),o.PUBSUB_URL&&c(o.PUBSUB_URL)}async request(t,e,o={}){const n={};o.headers&&o.headers.forEach((([t,e])=>{n[t]=e}));const a=await fetch(t,{...o,method:e,headers:n});if(!a.ok)throw 401===a.status&&this.handleUnauthorized(),new Error(`${a.statusText}`);return a}handleUnauthorized(){this.onUnauthorized&&this.onUnauthorized()}async getRealtimeSessionToken(t="alloy",e="openai"){const o=`${n}realtime/session?voice=${t}&provider=${e}`,a=await fetch(o,{headers:{Authorization:`Bearer ${this.getToken()}`}});if(!a.ok)throw new Error(`Failed to fetch session token: ${a.statusText}`);const s=await a.json(),i=s.client_secret?.value??s.value;if(!i)throw new Error("No ephemeral key returned from session endpoint");return i}async getRealtimeConfig(t="openai"){try{const e=`${n}realtime/config?provider=${t}`,o=await fetch(e,{method:"GET",headers:{Authorization:`Bearer ${this.getToken()}`}});return o.ok?await o.json():null}catch(t){return console.warn("Failed to fetch realtime config:",t),null}}}o=l,l.getImageUrl=(t,e)=>`${n}app/GetImage?fileId=${t}&width=${e}`,l.getFileUrl=(t,e)=>`${n}app/DownloadFile?fileId=${t}${e?`&extension=${e}`:""}`,l.downloadFile=async t=>{fetch(o.getFileUrl(t.id)).then((t=>{if(t.headers.forEach(((t,e)=>{console.log(`${e}: ${t}`)})),t.ok)return t.blob();throw new Error("Network response was not ok.")})).then((e=>{const o=window.URL.createObjectURL(e),n=document.createElement("a");n.style.display="none",n.href=o,n.download=t.filename,document.body.appendChild(n),n.click(),window.URL.revokeObjectURL(o)})).catch((t=>{console.error("There was a problem with the fetch operation:",t)}))},l.getMiniChatReplyOld=async(t,e="codicent-mini",o)=>{let a={project:e,message:t};o&&(a.messageId=o);const i=await fetch(`${n}app/GetAi2ChatReply`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${s}`]],body:JSON.stringify(a)});if(!i.ok)return void i.status;return(await i.json()).content.replace("@codicent-mini","").trim()},l.getMiniChatReply=async(t,e="codicent-mini",o,a=3e5,i=2e3,r)=>{const c={project:e,message:t};let h;o&&(c.messageId=o),r&&(c.previousResponseId=r);try{const t=await fetch(`${n}app/StartAi2ChatAsync`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${s}`]],body:JSON.stringify(c)});if(!t.ok)return t.status,void console.error(`Failed to start AI chat: ${t.status}`);if(h=(await t.json()).promptMessageId,!h)return void console.error("No promptMessageId returned from server")}catch(t){return void console.error("Error starting AI chat:",t)}const d=Date.now();for(;Date.now()-d<a;)try{const t=await fetch(`${n}app/GetAi2ChatReplyStatus?promptMessageId=${h}`,{method:"GET",headers:[["Authorization",`Bearer ${s}`]]});if(202===t.status){await new Promise((t=>setTimeout(t,i)));continue}if(!t.ok)return void console.error(`Error polling AI chat status: ${t.status}`);const o=await t.json(),a=o.content??o.content??"";return{content:a.replace(`@${e}`,"").replace("@codicent-mini","").trim(),responseId:o.responseId??void 0}}catch(t){return void console.error("Error polling AI chat status:",t)}console.error("Polling timeout reached for AI chat")},l.getTranslations=async(t,e,o="codicent-mini")=>{if(!s||"-"===s)return{translation:t};const a=await fetch(`${n}app/GetTranslations`,{method:"POST",headers:{"Content-Type":"application/json; charset=utf-8",Authorization:`Bearer ${s}`},body:JSON.stringify({project:o,text:t,targetLanguage:e})});if(!a.ok)throw a.status,new Error(`Failed to get translations: ${a.statusText}`);return await a.json()};export{l as CodicentService,r as setBaseUrl,c as setSignalRHost};
@@ -1 +1 @@
1
- import e from"../node_modules/exceljs/excel.js";const t=async(t,o,n="export",r)=>{if(!t||0===t.length)return!1;const a=e=>Array.isArray(e)?e[0]:e,l=new e.Workbook,c=l.addWorksheet("Data");c.columns=o.map((e=>{const t=a(e.key);return{header:e.title||t,key:t,width:15}})),t.forEach((e=>{const t={};o.forEach((o=>{const n=a(o.key),l=e[n];null==l?t[n]="":"object"==typeof l?t[n]=JSON.stringify(l):"boolean"==typeof l?t[n]=(e=>r?r(e?"Yes":"No"):e?"Yes":"No")(l):l instanceof Date?t[n]=l.toISOString():t[n]=l})),c.addRow(t)}));c.columns.forEach((e=>{if(!e.eachCell)return;let t=e.header?e.header.length:10;e.eachCell({includeEmpty:!0},(e=>{t=Math.max(t,e.value?String(e.value).length:0)})),e.width=Math.min(t+2,50)})),c.getRow(1).font={bold:!0},c.getRow(1).fill={type:"pattern",pattern:"solid",fgColor:{argb:"FFD3D3D3"}};const d=await l.xlsx.writeBuffer(),i=new Blob([d],{type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}),s=window.URL.createObjectURL(i),h=document.createElement("a");return h.href=s,h.download=`${n}.xlsx`,document.body.appendChild(h),h.click(),document.body.removeChild(h),window.URL.revokeObjectURL(s),!0};export{t as exportToExcel};
1
+ import e from"exceljs";const t=async(t,o,n="export",r)=>{if(!t||0===t.length)return!1;const a=e=>Array.isArray(e)?e[0]:e,l=new e.Workbook,c=l.addWorksheet("Data");c.columns=o.map((e=>{const t=a(e.key);return{header:e.title||t,key:t,width:15}})),t.forEach((e=>{const t={};o.forEach((o=>{const n=a(o.key),l=e[n];null==l?t[n]="":"object"==typeof l?t[n]=JSON.stringify(l):"boolean"==typeof l?t[n]=(e=>r?r(e?"Yes":"No"):e?"Yes":"No")(l):l instanceof Date?t[n]=l.toISOString():t[n]=l})),c.addRow(t)}));c.columns.forEach((e=>{if(!e.eachCell)return;let t=e.header?e.header.length:10;e.eachCell({includeEmpty:!0},(e=>{t=Math.max(t,e.value?String(e.value).length:0)})),e.width=Math.min(t+2,50)})),c.getRow(1).font={bold:!0},c.getRow(1).fill={type:"pattern",pattern:"solid",fgColor:{argb:"FFD3D3D3"}};const d=await l.xlsx.writeBuffer(),i=new Blob([d],{type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}),s=window.URL.createObjectURL(i),h=document.createElement("a");return h.href=s,h.download=`${n}.xlsx`,document.body.appendChild(h),h.click(),document.body.removeChild(h),window.URL.revokeObjectURL(s),!0};export{t as exportToExcel};
package/dist/index.d.ts CHANGED
@@ -880,7 +880,7 @@ interface UserRole {
880
880
  role: string;
881
881
  claims?: string;
882
882
  }
883
- declare const useUserRoles: (service: CodicentService, currentNickname?: string) => {
883
+ declare const useUserRoles: (service: CodicentService, currentNickname?: string, currentCodicent?: string) => {
884
884
  userRoles: UserRole[];
885
885
  loading: boolean;
886
886
  error: string | null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codicent-app-sdk",
3
- "version": "0.5.5",
3
+ "version": "0.5.7",
4
4
  "description": "SDK for building AI-powered applications with Codicent",
5
5
  "type": "module",
6
6
  "main": "dist/cjs/index.js",
@@ -42,13 +42,13 @@
42
42
  },
43
43
  "peerDependencies": {
44
44
  "@fluentui/react-components": "^9.60.0",
45
+ "exceljs": "^4.4.0",
45
46
  "mermaid": "^11.3.0",
46
47
  "react": ">=16.8.0",
47
48
  "react-dom": ">=16.8.0",
48
49
  "react-router-dom": "^6.27.0"
49
50
  },
50
51
  "dependencies": {
51
- "exceljs": "^4.4.0",
52
52
  "jsqr": "^1.4.0",
53
53
  "lodash": "^4.17.21",
54
54
  "nosleep.js": "^0.12.0",