@webority/mobile-support 0.148.0 → 0.150.0
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.
- package/README.md +0 -5
- package/lib/commonjs/SupportProvider.js +1 -1
- package/lib/commonjs/client.js +1 -1
- package/lib/commonjs/components/SupportTicketDetail.js +1 -1
- package/lib/commonjs/share/index.js +1 -1
- package/lib/module/SupportProvider.js +1 -1
- package/lib/module/client.js +1 -1
- package/lib/module/components/SupportTicketDetail.js +1 -1
- package/lib/module/share/index.js +1 -1
- package/lib/typescript/commonjs/client.d.ts +4 -10
- package/lib/typescript/module/client.d.ts +4 -10
- package/package.json +7 -7
package/README.md
CHANGED
|
@@ -193,11 +193,6 @@ The client no longer has `createTicket` or `reply`. Its `ticketRequest(input)` a
|
|
|
193
193
|
resolves to `Sent` with the ticket, or `Queued` with the outbox entry when the device is offline.
|
|
194
194
|
`useSupportTicket(id)` returns `pendingReplies`, the replies still in the outbox for that ticket.
|
|
195
195
|
|
|
196
|
-
`client.confirmAction(token)` sends the person's yes to a support action an assistant prepared
|
|
197
|
-
(raise a ticket, reply on one, reopen one) as `POST {base}/actions/confirm`. Only this call
|
|
198
|
-
completes the action. It resolves to the ticket it acted on; an expired or unknown token rejects
|
|
199
|
-
with the code `action_expired`.
|
|
200
|
-
|
|
201
196
|
## Attachments
|
|
202
197
|
|
|
203
198
|
Attachment files need the bearer token, so thumbnails are fetched through the client you passed
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.useSupportTimeZone=exports.useSupportTickets=exports.useSupportTicket=exports.useSupportOutbox=exports.useSupportLabels=exports.useSupportConfig=exports.useSupportClient=exports.useCreateSupportTicket=exports.useAttachmentOpener=exports.useAttachmentLoader=exports.SupportProvider=void 0;var _mobileCore=require("@webority/mobile-core"),_react=require("react"),_reactNative=require("react-native"),_client=require("./client.js"),_files=require("./files.js"),_types=require("./types.js"),_jsxRuntime=require("react/jsx-runtime");const SupportContext=(0,_react.createContext)(null),SupportProvider=({client:e,outbox:t,openFile:r,timeZone:u,labels:a,children:s})=>{if(!t)throw new Error("[@webority/mobile-support] <SupportProvider> needs an outbox={...}, created with createOutbox from mobile-core.");const[c,o]=(0,_react.useState)(null),[n,i]=(0,_react.useState)(null),[p,l]=(0,_react.useState)(!0),[_,S]=(0,_react.useState)(0),f=(0,_react.useRef)(new Map),d=(0,_react.useCallback)(async()=>{l(!0);const t=`@webority/mobile-support/config:${e.basePath}`;try{const r=await e.getConfig();_mobileCore.Storage.setItem(t,JSON.stringify(r)),o(r),i(null)}catch(e){const r=(0,_client.toSupportApiError)(e);if(i(r),"offline"===r.code||"network"===r.code){const e=await _mobileCore.Storage.getJson(t);e&&o(e)}}finally{l(!1)}},[e]);(0,_react.useEffect)(()=>{f.current.clear(),d()},[d]);const b=(0,_react.useCallback)(t=>{const r=f.current.get(t.id);if(r)return r;const u=e.getAttachmentDataUri(t);return f.current.set(t.id,u),u.catch(()=>f.current.delete(t.id)),u},[e]),y=(0,_react.useMemo)(()=>r?async t=>{const u=await(0,_files.saveAttachmentToCache)(t,()=>e.getAttachmentBytes(t.id));await r({uri:u,name:t.fileName,contentType:t.contentType})}:null,[e,r]),x=(0,_react.useCallback)(()=>S(e=>e+1),[]);(0,_react.useEffect)(()=>t.subscribe(e=>{"sent"!==e.type||e.entry.queue!==_types.SUPPORT_TICKET_QUEUE&&e.entry.queue!==_types.SUPPORT_REPLY_QUEUE||x()}),[t,x]);const C=(0,_react.useMemo)(()=>({client:e,outbox:t,config:c,configError:n,configLoading:p,reloadConfig:d,loadAttachment:b,openAttachment:y,timeZone:u,labels:a,revision:_,bumpRevision:x}),[e,t,c,n,p,d,b,y,u,a,_,x]);return(0,_jsxRuntime.jsx)(SupportContext.Provider,{value:C,children:s})};exports.SupportProvider=SupportProvider;const useSupportContext=()=>{const e=(0,_react.useContext)(SupportContext);if(!e)throw new Error("[@webority/mobile-support] Support screens and hooks need a <SupportProvider client={...}> above them.");return e},useSupportClient=()=>useSupportContext().client;exports.useSupportClient=useSupportClient;const useAttachmentLoader=()=>useSupportContext().loadAttachment;exports.useAttachmentLoader=useAttachmentLoader;const useAttachmentOpener=()=>useSupportContext().openAttachment;exports.useAttachmentOpener=useAttachmentOpener;const useSupportTimeZone=()=>useSupportContext().timeZone;exports.useSupportTimeZone=useSupportTimeZone;const useSupportLabels=(e,t)=>{const r=useSupportContext().labels?.[e];return(0,_react.useMemo)(()=>r?{...t,...r}:t,[r,t])};exports.useSupportLabels=useSupportLabels;const useSupportConfig=()=>{const{config:e,configLoading:t,configError:r,reloadConfig:u}=useSupportContext();return{config:e,loading:t,error:r,reload:u}};exports.useSupportConfig=useSupportConfig;const DEFAULT_PAGE_SIZE=20,useSupportTickets=(e={})=>{const t=e.pageSize??20,{client:r,revision:u}=useSupportContext(),[a,s]=(0,_react.useState)(null),[c,o]=(0,_react.useState)(""),[n,i]=(0,_react.useState)([]),[p,l]=(0,_react.useState)(null),[_,S]=(0,_react.useState)(0),[f,d]=(0,_react.useState)(0),[b,y]=(0,_react.useState)(!0),[x,C]=(0,_react.useState)(!1),[m,E]=(0,_react.useState)(!1),[g,h]=(0,_react.useState)(null),[k,T]=(0,_react.useState)(null),w=(0,_react.useRef)(!0),P=(0,_react.useRef)(0),R=(0,_react.useRef)(!1),v=(0,_react.useRef)(null);(0,_react.useEffect)(()=>(w.current=!0,()=>{w.current=!1}),[]);const A=(0,_react.useCallback)(e=>({status:a??void 0,search:c.trim()||void 0,page:e,pageSize:t}),[a,c,t]),U=(0,_react.useCallback)(async e=>{P.current+=1;const t=P.current,current=()=>w.current&&t===P.current;R.current=!1,E(!1),"refresh"===e?C(!0):"replace"===e&&(y(!0),i([]));const u="replace"!==e||v.current!==r;try{const[e,t]=await Promise.all([r.listTickets(A(1)),u?r.getTicketCounts():null]);current()&&(i(e.items),S(e.page),d(e.totalPages),t&&(l(t),v.current=r),h(null),T(null))}catch(e){current()&&h((0,_client.toSupportApiError)(e))}finally{current()&&(y(!1),C(!1))}},[r,A]),O=(0,_react.useRef)(u);(0,_react.useEffect)(()=>{const e=O.current===u?"replace":"quiet";O.current=u,U(e)},[U,u]);const q=_<f,L=(0,_react.useCallback)(async()=>{if(R.current||b||x||!q)return;const e=P.current,current=()=>w.current&&e===P.current;R.current=!0,E(!0),T(null);try{const e=await r.listTickets(A(_+1));current()&&(i(t=>{const r=new Set(t.map(e=>e.id));return[...t,...e.items.filter(e=>!r.has(e.id))]}),S(e.page),d(e.totalPages))}catch(e){current()&&T((0,_client.toSupportApiError)(e))}finally{current()&&(R.current=!1,E(!1))}},[r,A,_,q,b,x]),M=(0,_react.useCallback)(()=>U("refresh"),[U]),j=useCreateSupportTicket();return{tickets:n,counts:p,status:a,search:c,setStatus:s,setSearch:o,loading:b,refreshing:x,loadingMore:m,hasMore:q,error:g,loadMoreError:k,refresh:M,loadMore:L,createTicket:j}};exports.useSupportTickets=useSupportTickets;const sendThroughOutbox=async(e,t,r,u)=>{try{const a=await e.send({queue:t,label:r,request:u});return"Sent"===a.status?{status:"Sent",ticket:a.data}:"Queued"===a.status?{status:"Queued",entry:a.entry}:{status:"Failed",error:new _client.SupportApiError(a.failure.code,a.failure.message,a.failure.status)}}catch(e){if(e instanceof Error&&"OutboxFullError"===e.name)return{status:"Failed",error:new _client.SupportApiError("outbox_full",e.message,null)};if(e instanceof Error&&"OutboxSignedOutError"===e.name)return{status:"Failed",error:new _client.SupportApiError("signed_out",e.message,null)};throw e}},useCreateSupportTicket=()=>{const{client:e,outbox:t}=useSupportContext();return(0,_react.useCallback)(r=>sendThroughOutbox(t,_types.SUPPORT_TICKET_QUEUE,r.subject,e.ticketRequest(r)),[e,t])};exports.useCreateSupportTicket=useCreateSupportTicket;const TICKET_REFRESH_MS=3e4,useSupportTicket=e=>{const{client:t,outbox:r,bumpRevision:u}=useSupportContext(),[a,s]=(0,_react.useState)(null),[c,o]=(0,_react.useState)(!0),[n,i]=(0,_react.useState)(null),[p,l]=(0,_react.useState)(null),[_,S]=(0,_react.useState)(!1),[f,d]=(0,_react.useState)([]),b=(0,_react.useRef)(!0),y=(0,_react.useRef)(!1),x=(0,_react.useMemo)(()=>(0,_client.supportRepliesUrl)(t.basePath,e),[t,e]);(0,_react.useEffect)(()=>{y.current=_},[_]),(0,_react.useEffect)(()=>(b.current=!0,()=>{b.current=!1}),[]);const C=(0,_react.useCallback)(async()=>{const e=await r.list(_types.SUPPORT_REPLY_QUEUE);b.current&&d(e.filter(e=>e.request.url===x))},[r,x]);(0,_react.useEffect)(()=>(C(),r.subscribe(e=>{"sent"===e.type&&e.entry.queue===_types.SUPPORT_REPLY_QUEUE&&e.entry.request.url===x&&b.current&&s(e.data),("changed"===e.type?e.queue:e.entry.queue)===_types.SUPPORT_REPLY_QUEUE&&C()})),[r,C,x]);const m=(0,_react.useCallback)(async()=>{o(!0);try{const r=await t.getTicket(e);b.current&&(s(r),i(null))}catch(e){b.current&&i((0,_client.toSupportApiError)(e))}finally{b.current&&o(!1)}},[t,e]);(0,_react.useEffect)(()=>{m()},[m]);const E=(0,_react.useCallback)(async()=>{if(!y.current)try{const r=await t.getTicket(e);b.current&&s(e=>!e||Date.parse(r.updatedDateTimeUtc)>=Date.parse(e.updatedDateTimeUtc)?r:e)}catch(e){_mobileCore.Logger.warn("[@webority/mobile-support] background refresh of the support ticket failed",e)}},[t,e]);(0,_react.useEffect)(()=>{let e=null;const start=()=>{e??=setInterval(()=>{E()},3e4)},stop=()=>{null!==e&&(clearInterval(e),e=null)};let t="active"===_reactNative.AppState.currentState;t&&start();const r=_reactNative.AppState.addEventListener("change",e=>{const r="active"===e;r!==t&&(t=r,r?(E(),start()):stop())});return()=>{r.remove(),stop()}},[E]);const g=(0,_react.useCallback)(async e=>{S(!0),l(null);try{const t=await e();return b.current&&s(t),u(),!0}catch(e){return b.current&&l((0,_client.toSupportApiError)(e)),!1}finally{b.current&&S(!1)}},[u]),h=(0,_react.useCallback)(async u=>{S(!0),l(null);try{const a=await sendThroughOutbox(r,_types.SUPPORT_REPLY_QUEUE,u.body.slice(0,80),t.replyRequest(e,u));return b.current&&("Sent"===a.status&&s(a.ticket),"Failed"===a.status&&l(a.error)),a.status}finally{b.current&&S(!1)}},[r,t,e]),k=(0,_react.useCallback)(()=>g(()=>t.reopen(e)),[g,t,e]),T=(0,_react.useCallback)(()=>g(()=>t.cancel(e)),[g,t,e]),w=(0,_react.useCallback)(r=>g(()=>t.rate(e,r)),[g,t,e]);return{ticket:a,loading:c,error:n,actionError:p,busy:_,pendingReplies:f,reload:m,reply:h,reopen:k,cancel:T,rate:w}};exports.useSupportTicket=useSupportTicket;const useSupportOutbox=e=>{const{outbox:t}=useSupportContext(),[r,u]=(0,_react.useState)([]),a=(0,_react.useRef)(!0);(0,_react.useEffect)(()=>(a.current=!0,()=>{a.current=!1}),[]);const s=(0,_react.useCallback)(async()=>{const r=await t.list(e);a.current&&u(r)},[t,e]);(0,_react.useEffect)(()=>(s(),t.subscribe(t=>{("changed"===t.type?t.queue:t.entry.queue)===e&&s()})),[t,e,s]);return{entries:r,retry:(0,_react.useCallback)(async e=>{await t.retry(e),await s()},[t,s]),discard:(0,_react.useCallback)(async e=>{await t.discard(e),await s()},[t,s])}};exports.useSupportOutbox=useSupportOutbox;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.useSupportTimeZone=exports.useSupportTickets=exports.useSupportTicket=exports.useSupportOutbox=exports.useSupportLabels=exports.useSupportConfig=exports.useSupportClient=exports.useCreateSupportTicket=exports.useAttachmentOpener=exports.useAttachmentLoader=exports.SupportProvider=void 0;var _mobileCore=require("@webority/mobile-core"),_react=require("react"),_reactNative=require("react-native"),_client=require("./client.js"),_files=require("./files.js"),_types=require("./types.js"),_jsxRuntime=require("react/jsx-runtime");const SupportContext=(0,_react.createContext)(null),isRecord=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),isStringArray=e=>Array.isArray(e)&&e.every(e=>"string"==typeof e),isSupportTicketDetail=e=>{if(!isRecord(e))return!1;const nullableString=e=>null===e||"string"==typeof e,nullableNumber=e=>null===e||"number"==typeof e,isLink=e=>isRecord(e)&&"string"==typeof e.id&&"string"==typeof e.number&&"string"==typeof e.subject;return"string"==typeof e.id&&"string"==typeof e.number&&"string"==typeof e.queue&&nullableNumber(e.accountId)&&nullableString(e.realm)&&"string"==typeof e.category&&"string"==typeof e.subject&&"string"==typeof e.status&&"string"==typeof e.statusLabel&&nullableString(e.priority)&&"string"==typeof e.reporterName&&(void 0===e.reporterPlace||"string"==typeof e.reporterPlace)&&"string"==typeof e.reporterEmail&&nullableNumber(e.assignedAgentUserId)&&nullableString(e.assignedAgentName)&&"boolean"==typeof e.isOverdue&&nullableString(e.pageUrl)&&nullableString(e.userAgent)&&nullableString(e.appVersion)&&nullableString(e.satisfaction)&&nullableString(e.satisfactionComment)&&"boolean"==typeof e.canReopen&&"boolean"==typeof e.canRate&&"boolean"==typeof e.canCancel&&"string"==typeof e.createdDateTimeUtc&&"string"==typeof e.updatedDateTimeUtc&&nullableString(e.resolvedDateTimeUtc)&&nullableString(e.closedDateTimeUtc)&&Array.isArray(e.messages)&&"string"==typeof e.version&&(void 0===e.mergedInto||isLink(e.mergedInto))&&(void 0===e.mergedTickets||Array.isArray(e.mergedTickets)&&e.mergedTickets.every(isLink))},parseSupportContactInfo=e=>{if(!isRecord(e))return null;const{productName:t,supportEmail:r,supportName:o,supportPhone:s,supportHours:a,categories:n,maxAttachmentBytes:u,maxAttachmentsPerMessage:c,allowedContentTypes:i,subjectMaxLength:p,bodyMaxLength:l,satisfactionCommentMaxLength:f}=e;return"string"!=typeof t||"string"!=typeof r||"string"!=typeof o||null!==s&&"string"!=typeof s||null!==a&&"string"!=typeof a||!isStringArray(n)||"number"!=typeof u||"number"!=typeof c||!isStringArray(i)||"number"!=typeof p||"number"!=typeof l||"number"!=typeof f?null:{productName:t,supportEmail:r,supportName:o,supportPhone:s,supportHours:a,categories:n,maxAttachmentBytes:u,maxAttachmentsPerMessage:c,allowedContentTypes:i,subjectMaxLength:p,bodyMaxLength:l,satisfactionCommentMaxLength:f}},SupportProvider=({client:e,outbox:t,openFile:r,timeZone:o,labels:s,children:a})=>{if(!t)throw new Error("[@webority/mobile-support] <SupportProvider> needs an outbox={...}, created with createOutbox from mobile-core.");const[n,u]=(0,_react.useState)(null),[c,i]=(0,_react.useState)(null),[p,l]=(0,_react.useState)(!0),[f,y]=(0,_react.useState)(0),_=(0,_react.useRef)(new Map),S=(0,_react.useCallback)(async()=>{l(!0);const t=`@webority/mobile-support/config:${e.basePath}`;try{const r=await e.getConfig();_mobileCore.Storage.setItem(t,JSON.stringify(r)),u(r),i(null)}catch(e){const r=(0,_client.toSupportApiError)(e);if(i(r),"offline"===r.code||"network"===r.code){const e=await _mobileCore.Storage.getJson(t,parseSupportContactInfo);e&&u(e)}}finally{l(!1)}},[e]);(0,_react.useEffect)(()=>{_.current.clear(),S()},[S]);const d=(0,_react.useCallback)(t=>{const r=_.current.get(t.id);if(r)return r;const o=e.getAttachmentDataUri(t);return _.current.set(t.id,o),o.catch(()=>_.current.delete(t.id)),o},[e]),g=(0,_react.useMemo)(()=>r?async t=>{const o=await(0,_files.saveAttachmentToCache)(t,()=>e.getAttachmentBytes(t.id));await r({uri:o,name:t.fileName,contentType:t.contentType})}:null,[e,r]),m=(0,_react.useCallback)(()=>y(e=>e+1),[]);(0,_react.useEffect)(()=>t.subscribe(e=>{"sent"!==e.type||e.entry.queue!==_types.SUPPORT_TICKET_QUEUE&&e.entry.queue!==_types.SUPPORT_REPLY_QUEUE||m()}),[t,m]);const b=(0,_react.useMemo)(()=>({client:e,outbox:t,config:n,configError:c,configLoading:p,reloadConfig:S,loadAttachment:d,openAttachment:g,timeZone:o,labels:s,revision:f,bumpRevision:m}),[e,t,n,c,p,S,d,g,o,s,f,m]);return(0,_jsxRuntime.jsx)(SupportContext.Provider,{value:b,children:a})};exports.SupportProvider=SupportProvider;const useSupportContext=()=>{const e=(0,_react.useContext)(SupportContext);if(!e)throw new Error("[@webority/mobile-support] Support screens and hooks need a <SupportProvider client={...}> above them.");return e},useSupportClient=()=>useSupportContext().client;exports.useSupportClient=useSupportClient;const useAttachmentLoader=()=>useSupportContext().loadAttachment;exports.useAttachmentLoader=useAttachmentLoader;const useAttachmentOpener=()=>useSupportContext().openAttachment;exports.useAttachmentOpener=useAttachmentOpener;const useSupportTimeZone=()=>useSupportContext().timeZone;exports.useSupportTimeZone=useSupportTimeZone;const useSupportLabels=(e,t)=>{const r=useSupportContext().labels?.[e];return(0,_react.useMemo)(()=>r?{...t,...r}:t,[r,t])};exports.useSupportLabels=useSupportLabels;const useSupportConfig=()=>{const{config:e,configLoading:t,configError:r,reloadConfig:o}=useSupportContext();return{config:e,loading:t,error:r,reload:o}};exports.useSupportConfig=useSupportConfig;const DEFAULT_PAGE_SIZE=20,useSupportTickets=(e={})=>{const t=e.pageSize??20,{client:r,revision:o}=useSupportContext(),[s,a]=(0,_react.useState)(null),[n,u]=(0,_react.useState)(""),[c,i]=(0,_react.useState)([]),[p,l]=(0,_react.useState)(null),[f,y]=(0,_react.useState)(0),[_,S]=(0,_react.useState)(0),[d,g]=(0,_react.useState)(!0),[m,b]=(0,_react.useState)(!1),[x,h]=(0,_react.useState)(!1),[C,E]=(0,_react.useState)(null),[T,k]=(0,_react.useState)(null),A=(0,_react.useRef)(!0),w=(0,_react.useRef)(0),P=(0,_react.useRef)(!1),v=(0,_react.useRef)(null);(0,_react.useEffect)(()=>(A.current=!0,()=>{A.current=!1}),[]);const R=(0,_react.useCallback)(e=>({status:s??void 0,search:n.trim()||void 0,page:e,pageSize:t}),[s,n,t]),U=(0,_react.useCallback)(async e=>{w.current+=1;const t=w.current,current=()=>A.current&&t===w.current;P.current=!1,h(!1),"refresh"===e?b(!0):"replace"===e&&(g(!0),i([]));const o="replace"!==e||v.current!==r;try{const[e,t]=await Promise.all([r.listTickets(R(1)),o?r.getTicketCounts():null]);current()&&(i(e.items),y(e.page),S(e.totalPages),t&&(l(t),v.current=r),E(null),k(null))}catch(e){current()&&E((0,_client.toSupportApiError)(e))}finally{current()&&(g(!1),b(!1))}},[r,R]),L=(0,_react.useRef)(o);(0,_react.useEffect)(()=>{const e=L.current===o?"replace":"quiet";L.current=o,U(e)},[U,o]);const O=f<_,q=(0,_react.useCallback)(async()=>{if(P.current||d||m||!O)return;const e=w.current,current=()=>A.current&&e===w.current;P.current=!0,h(!0),k(null);try{const e=await r.listTickets(R(f+1));current()&&(i(t=>{const r=new Set(t.map(e=>e.id));return[...t,...e.items.filter(e=>!r.has(e.id))]}),y(e.page),S(e.totalPages))}catch(e){current()&&k((0,_client.toSupportApiError)(e))}finally{current()&&(P.current=!1,h(!1))}},[r,R,f,O,d,m]),M=(0,_react.useCallback)(()=>U("refresh"),[U]),j=useCreateSupportTicket();return{tickets:c,counts:p,status:s,search:n,setStatus:a,setSearch:u,loading:d,refreshing:m,loadingMore:x,hasMore:O,error:C,loadMoreError:T,refresh:M,loadMore:q,createTicket:j}};exports.useSupportTickets=useSupportTickets;const sendThroughOutbox=async(e,t,r,o)=>{try{const s=await e.send({queue:t,label:r,request:o});if("Sent"===s.status){const{data:e}=s;return isSupportTicketDetail(e)?{status:"Sent",ticket:e}:{status:"Failed",error:new _client.SupportApiError("invalid-reply","The support desk sent a reply this app could not read. Try again.",null)}}return"Queued"===s.status?{status:"Queued",entry:s.entry}:{status:"Failed",error:new _client.SupportApiError(s.failure.code,s.failure.message,s.failure.status)}}catch(e){if(e instanceof Error&&"OutboxFullError"===e.name)return{status:"Failed",error:new _client.SupportApiError("outbox_full",e.message,null)};if(e instanceof Error&&"OutboxSignedOutError"===e.name)return{status:"Failed",error:new _client.SupportApiError("signed_out",e.message,null)};throw e}},useCreateSupportTicket=()=>{const{client:e,outbox:t}=useSupportContext();return(0,_react.useCallback)(r=>sendThroughOutbox(t,_types.SUPPORT_TICKET_QUEUE,r.subject,e.ticketRequest(r)),[e,t])};exports.useCreateSupportTicket=useCreateSupportTicket;const TICKET_REFRESH_MS=3e4,useSupportTicket=e=>{const{client:t,outbox:r,bumpRevision:o}=useSupportContext(),[s,a]=(0,_react.useState)(null),[n,u]=(0,_react.useState)(!0),[c,i]=(0,_react.useState)(null),[p,l]=(0,_react.useState)(null),[f,y]=(0,_react.useState)(!1),[_,S]=(0,_react.useState)([]),d=(0,_react.useRef)(!0),g=(0,_react.useRef)(!1),m=(0,_react.useMemo)(()=>(0,_client.supportRepliesUrl)(t.basePath,e),[t,e]);(0,_react.useEffect)(()=>{g.current=f},[f]),(0,_react.useEffect)(()=>(d.current=!0,()=>{d.current=!1}),[]);const b=(0,_react.useCallback)(async()=>{const e=await r.list(_types.SUPPORT_REPLY_QUEUE);d.current&&S(e.filter(e=>e.request.url===m))},[r,m]),x=(0,_react.useCallback)(async()=>{u(!0);try{const r=await t.getTicket(e);d.current&&(a(r),i(null))}catch(e){d.current&&i((0,_client.toSupportApiError)(e))}finally{d.current&&u(!1)}},[t,e]);(0,_react.useEffect)(()=>{x()},[x]);const h=(0,_react.useCallback)(async()=>{if(!g.current)try{const r=await t.getTicket(e);d.current&&a(e=>!e||Date.parse(r.updatedDateTimeUtc)>=Date.parse(e.updatedDateTimeUtc)?r:e)}catch(e){_mobileCore.Logger.warn("[@webority/mobile-support] background refresh of the support ticket failed",e)}},[t,e]);(0,_react.useEffect)(()=>(b(),r.subscribe(e=>{"sent"===e.type&&e.entry.queue===_types.SUPPORT_REPLY_QUEUE&&e.entry.request.url===m&&d.current&&(isSupportTicketDetail(e.data)?a(e.data):(_mobileCore.Logger.warn("[mobile-support] an outbox reply was not a ticket; refreshing"),h())),("changed"===e.type?e.queue:e.entry.queue)===_types.SUPPORT_REPLY_QUEUE&&b()})),[r,b,h,m]),(0,_react.useEffect)(()=>{let e=null;const start=()=>{e??=setInterval(()=>{h()},3e4)},stop=()=>{null!==e&&(clearInterval(e),e=null)};let t="active"===_reactNative.AppState.currentState;t&&start();const r=_reactNative.AppState.addEventListener("change",e=>{const r="active"===e;r!==t&&(t=r,r?(h(),start()):stop())});return()=>{r.remove(),stop()}},[h]);const C=(0,_react.useCallback)(async e=>{y(!0),l(null);try{const t=await e();return d.current&&a(t),o(),!0}catch(e){return d.current&&l((0,_client.toSupportApiError)(e)),!1}finally{d.current&&y(!1)}},[o]),E=(0,_react.useCallback)(async o=>{y(!0),l(null);try{const s=await sendThroughOutbox(r,_types.SUPPORT_REPLY_QUEUE,o.body.slice(0,80),t.replyRequest(e,o));return d.current&&("Sent"===s.status&&a(s.ticket),"Failed"===s.status&&l(s.error)),s.status}finally{d.current&&y(!1)}},[r,t,e]),T=(0,_react.useCallback)(()=>C(()=>t.reopen(e)),[C,t,e]),k=(0,_react.useCallback)(()=>C(()=>t.cancel(e)),[C,t,e]),A=(0,_react.useCallback)(r=>C(()=>t.rate(e,r)),[C,t,e]);return{ticket:s,loading:n,error:c,actionError:p,busy:f,pendingReplies:_,reload:x,reply:E,reopen:T,cancel:k,rate:A}};exports.useSupportTicket=useSupportTicket;const useSupportOutbox=e=>{const{outbox:t}=useSupportContext(),[r,o]=(0,_react.useState)([]),s=(0,_react.useRef)(!0);(0,_react.useEffect)(()=>(s.current=!0,()=>{s.current=!1}),[]);const a=(0,_react.useCallback)(async()=>{const r=await t.list(e);s.current&&o(r)},[t,e]);(0,_react.useEffect)(()=>(a(),t.subscribe(t=>{("changed"===t.type?t.queue:t.entry.queue)===e&&a()})),[t,e,a]);return{entries:r,retry:(0,_react.useCallback)(async e=>{await t.retry(e),await a()},[t,a]),discard:(0,_react.useCallback)(async e=>{await t.discard(e),await a()},[t,a])}};exports.useSupportOutbox=useSupportOutbox;
|
package/lib/commonjs/client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.toSupportApiError=exports.supportRepliesUrl=exports.createSupportClient=exports.SupportApiError=exports.OFFLINE_MESSAGE=exports.GENERIC_MESSAGE=void 0;var _mobileCore=require("@webority/mobile-core");const OFFLINE_MESSAGE=exports.OFFLINE_MESSAGE="You are offline. Check your connection and try again.",GENERIC_MESSAGE=exports.GENERIC_MESSAGE="Something went wrong. Try again in a moment.";class SupportApiError extends Error{constructor(e,t,r){super(t),this.name="SupportApiError",this.code=e,this.status=r}}exports.SupportApiError=SupportApiError;const toSupportApiError=e=>{if(e instanceof SupportApiError)return e;const t=e??{};if("RequestOfflineError"===t.name)return new SupportApiError("offline",OFFLINE_MESSAGE,null);const r="number"==typeof t.response?.status?t.response.status:null,o=t.response?.data,s="string"==typeof o?.code?o.code:"unknown";return o&&"string"==typeof o.detail&&o.detail.trim()?new SupportApiError(s,o.detail,r):t.response?new SupportApiError(s,GENERIC_MESSAGE,r):new SupportApiError("network",OFFLINE_MESSAGE,null)};exports.toSupportApiError=toSupportApiError;const UPLOAD_TIMEOUT_MS=3e5,textFields=(e,t)=>void 0!==t&&""!==t?[{name:e,value:t}]:[],fileFields=(e,t)=>(t??[]).map(t=>({name:e,file:{uri:t.uri,name:t.name,type:t.type}})),multipartRequest=(e,t)=>({method:"POST",url:e,headers:{"Content-Type":"multipart/form-data","Idempotency-Key":(0,_mobileCore.newIdempotencyKey)()},body:{kind:"multipart",fields:t},timeoutMs:3e5}),supportRepliesUrl=(e,t)=>`${e}/tickets/${encodeURIComponent(t)}/replies`;exports.supportRepliesUrl=supportRepliesUrl;const queryString=e=>{const t=[],add=(e,r)=>{void 0!==r&&""!==r&&t.push(`${e}=${encodeURIComponent(String(r))}`)};return add("status",e.status),add("search",e.search?.trim()),add("queue",e.queue?.trim()),add("page",e.page),add("pageSize",e.pageSize),t.length>0?`?${t.join("&")}`:""},createSupportClient=(e,t="/api/support",r)=>{const o=t.replace(/\/+$/,""),ticketUrl=e=>`${o}/tickets/${encodeURIComponent(e)}`,call=async e=>{try{return(await e()).data}catch(e){throw toSupportApiError(e)}},getBytes=t=>call(()=>e.get(`${o}/attachments/${encodeURIComponent(t)}`,{responseType:"arraybuffer"})),s=r?.replace(/\/+$/,"");return{basePath:o,helpCentre:void 0===s?void 0:{settings:t=>call(()=>e.get(`${s}/settings`,{signal:t?.signal})),list:(t={},r)=>call(()=>e.get(`${s}/articles${queryString(t)}`,{signal:r?.signal})),get:(t,r)=>call(()=>e.get(`${s}/articles/${encodeURIComponent(t)}`,{signal:r?.signal})),search:(t,r)=>call(()=>e.get(`${s}/search?q=${encodeURIComponent(t)}`,{signal:r?.signal}))},getConfig:()=>call(()=>e.get(`${o}/settings`)),listTickets:(t={})=>call(()=>e.get(`${o}/tickets${queryString(t)}`)),getTicketCounts:()=>call(()=>e.get(`${o}/tickets/counts`)),getTicket:t=>call(()=>e.get(ticketUrl(t))),ticketRequest:e=>multipartRequest(`${o}/tickets`,[{name:"category",value:e.category},{name:"subject",value:e.subject},{name:"body",value:e.body},...textFields("pageUrl",e.pageUrl),...textFields("userAgent",e.userAgent),...textFields("appVersion",e.appVersion),...fileFields("files",e.files),...fileFields("screenshots",e.screenshots)]),getSuggestions:t=>call(()=>e.get(`${o}/suggestions?subject=${encodeURIComponent(t)}`)),replyRequest:(e,t)=>multipartRequest(supportRepliesUrl(o,e),[{name:"body",value:t.body},...fileFields("files",t.files),...fileFields("screenshots",t.screenshots)]),reopen:t=>call(()=>e.post(`${ticketUrl(t)}/reopen`)),cancel:t=>call(()=>e.post(`${ticketUrl(t)}/cancel`)),rate:(t,r)=>call(()=>e.post(`${ticketUrl(t)}/rating`,{satisfaction:r.satisfaction,comment:r.comment?.trim()?r.comment.trim():null})),getAttachmentBytes:getBytes,getAttachmentDataUri:async e=>{const t=await getBytes(e.id);return`data:${e.contentType};base64,${(0,_mobileCore.encodeBase64)(t)}`},confirmAction:t=>call(()=>e.post(`${o}/actions/confirm`,{token:t}))}};exports.createSupportClient=createSupportClient;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.toSupportApiError=exports.supportRepliesUrl=exports.createSupportClient=exports.SupportApiError=exports.OFFLINE_MESSAGE=exports.GENERIC_MESSAGE=void 0;var _mobileCore=require("@webority/mobile-core");const isJsonObject=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),reject=(e,t)=>{throw new Error(`${e} must be ${t}`)},readObject=(e,t)=>isJsonObject(e)?e:reject(t,"an object"),readString=(e,t,r)=>{const a=e[t];return"string"==typeof a?a:reject(`${r}.${t}`,"a string")},readNumber=(e,t,r)=>{const a=e[t];return"number"==typeof a&&Number.isFinite(a)?a:reject(`${r}.${t}`,"a number")},readBoolean=(e,t,r)=>{const a=e[t];return"boolean"==typeof a?a:reject(`${r}.${t}`,"true or false")},readNullable=(e,t,r,a)=>null===e[t]?null:a(e,t,r),readOptional=(e,t,r,a)=>void 0===e[t]?void 0:a(e,t,r),oneOf=e=>(t,r,a)=>{const s=readString(t,r,a);return e.find(e=>e===s)??reject(`${a}.${r}`,`one of ${e.join(", ")}`)},nested=e=>(t,r,a)=>e(t[r],`${a}.${r}`),parseList=(e,t,r)=>Array.isArray(e)?e.map((e,a)=>r(e,`${t}[${a}]`)):reject(t,"a list"),readList=(e,t,r,a)=>parseList(e[t],`${r}.${t}`,a),parseText=(e,t)=>"string"==typeof e?e:reject(t,"a string"),readStrings=(e,t,r)=>readList(e,t,r,parseText),readTicketStatus=oneOf(["Open","InProgress","WaitingOnCustomer","Resolved","Closed","Cancelled"]),readPriority=oneOf(["Low","Normal","High","Urgent"]),readSatisfaction=oneOf(["Satisfied","Unsatisfied"]),readAuthorKind=oneOf(["Customer","Agent","System","Assistant"]),readAttachmentKind=oneOf(["Screenshot","File"]),parseSupportContactInfo=(e,t="SupportContactInfo")=>{const r=readObject(e,t);return{productName:readString(r,"productName",t),supportEmail:readString(r,"supportEmail",t),supportName:readString(r,"supportName",t),supportPhone:readNullable(r,"supportPhone",t,readString),supportHours:readNullable(r,"supportHours",t,readString),categories:readStrings(r,"categories",t),maxAttachmentBytes:readNumber(r,"maxAttachmentBytes",t),maxAttachmentsPerMessage:readNumber(r,"maxAttachmentsPerMessage",t),allowedContentTypes:readStrings(r,"allowedContentTypes",t),subjectMaxLength:readNumber(r,"subjectMaxLength",t),bodyMaxLength:readNumber(r,"bodyMaxLength",t),satisfactionCommentMaxLength:readNumber(r,"satisfactionCommentMaxLength",t)}},parseSupportTicketSummary=(e,t="SupportTicketSummary")=>{const r=readObject(e,t);return{id:readString(r,"id",t),number:readString(r,"number",t),category:readString(r,"category",t),subject:readString(r,"subject",t),status:readTicketStatus(r,"status",t),statusLabel:readString(r,"statusLabel",t),messageCount:readNumber(r,"messageCount",t),awaitingCustomer:readBoolean(r,"awaitingCustomer",t),queue:readString(r,"queue",t),createdDateTimeUtc:readString(r,"createdDateTimeUtc",t),updatedDateTimeUtc:readString(r,"updatedDateTimeUtc",t)}},parseSupportAttachmentView=(e,t="SupportAttachmentView")=>{const r=readObject(e,t);return{id:readString(r,"id",t),fileName:readString(r,"fileName",t),contentType:readString(r,"contentType",t),sizeBytes:readNumber(r,"sizeBytes",t),kind:readAttachmentKind(r,"kind",t)}},parseSupportMessageView=(e,t="SupportMessageView")=>{const r=readObject(e,t);return{id:readString(r,"id",t),authorKind:readAuthorKind(r,"authorKind",t),authorName:readNullable(r,"authorName",t,readString),body:readString(r,"body",t),isInternal:readBoolean(r,"isInternal",t),createdDateTimeUtc:readString(r,"createdDateTimeUtc",t),attachments:readList(r,"attachments",t,parseSupportAttachmentView)}},parseSupportTicketLink=(e,t="SupportTicketLink")=>{const r=readObject(e,t);return{id:readString(r,"id",t),number:readString(r,"number",t),subject:readString(r,"subject",t)}},parseSupportTicketDetail=(e,t="SupportTicketDetail")=>{const r=readObject(e,t);return{id:readString(r,"id",t),number:readString(r,"number",t),queue:readString(r,"queue",t),accountId:readNullable(r,"accountId",t,readNumber),realm:readNullable(r,"realm",t,readString),category:readString(r,"category",t),subject:readString(r,"subject",t),status:readTicketStatus(r,"status",t),statusLabel:readString(r,"statusLabel",t),priority:readNullable(r,"priority",t,readPriority),reporterName:readString(r,"reporterName",t),reporterPlace:readOptional(r,"reporterPlace",t,readString),reporterEmail:readString(r,"reporterEmail",t),assignedAgentUserId:readNullable(r,"assignedAgentUserId",t,readNumber),assignedAgentName:readNullable(r,"assignedAgentName",t,readString),isOverdue:readBoolean(r,"isOverdue",t),pageUrl:readNullable(r,"pageUrl",t,readString),userAgent:readNullable(r,"userAgent",t,readString),appVersion:readNullable(r,"appVersion",t,readString),satisfaction:readNullable(r,"satisfaction",t,readSatisfaction),satisfactionComment:readNullable(r,"satisfactionComment",t,readString),canReopen:readBoolean(r,"canReopen",t),canRate:readBoolean(r,"canRate",t),canCancel:readBoolean(r,"canCancel",t),createdDateTimeUtc:readString(r,"createdDateTimeUtc",t),updatedDateTimeUtc:readString(r,"updatedDateTimeUtc",t),resolvedDateTimeUtc:readNullable(r,"resolvedDateTimeUtc",t,readString),closedDateTimeUtc:readNullable(r,"closedDateTimeUtc",t,readString),messages:readList(r,"messages",t,parseSupportMessageView),version:readString(r,"version",t),mergedInto:readOptional(r,"mergedInto",t,nested(parseSupportTicketLink)),mergedTickets:readOptional(r,"mergedTickets",t,(e,t,r)=>readList(e,t,r,parseSupportTicketLink))}},parseSupportPage=(e,t)=>(r,a=t)=>{const s=readObject(r,a);return{items:readList(s,"items",a,e),page:readNumber(s,"page",a),pageSize:readNumber(s,"pageSize",a),totalCount:readNumber(s,"totalCount",a),totalPages:readNumber(s,"totalPages",a)}},parseSupportTicketPage=parseSupportPage(parseSupportTicketSummary,"SupportPage<SupportTicketSummary>"),parseSupportTicketCounts=(e,t="SupportTicketCounts")=>{const r=readObject(e,t);return{open:readNumber(r,"open",t),needsReply:readNumber(r,"needsReply",t),resolved:readNumber(r,"resolved",t),withdrawn:readNumber(r,"withdrawn",t),total:readNumber(r,"total",t),oldestAwaitingAgentDateTimeUtc:readNullable(r,"oldestAwaitingAgentDateTimeUtc",t,readString)}},parseSupportSuggestedArticle=(e,t="SupportSuggestedArticle")=>{const r=readObject(e,t);return{title:readString(r,"title",t),summary:readString(r,"summary",t)}},parseSupportSuggestedArticles=(e,t="SupportSuggestedArticle[]")=>parseList(e,t,parseSupportSuggestedArticle),parseHelpCentreSettings=(e,t="HelpCentreSettings")=>{const r=readObject(e,t);return{publicUrl:readString(r,"publicUrl",t),searchAvailable:readBoolean(r,"searchAvailable",t)}},parseHelpArticleSummary=(e,t="HelpArticleSummary")=>{const r=readObject(e,t);return{id:readString(r,"id",t),slug:readString(r,"slug",t),title:readString(r,"title",t),summary:readString(r,"summary",t),publishedDateTimeUtc:readNullable(r,"publishedDateTimeUtc",t,readString),updatedDateTimeUtc:readString(r,"updatedDateTimeUtc",t)}},parseHelpArticlePage=parseSupportPage(parseHelpArticleSummary,"SupportPage<HelpArticleSummary>"),parseHelpArticleView=(e,t="HelpArticleView")=>{const r=readObject(e,t);return{...parseHelpArticleSummary(r,t),bodyMarkdown:readString(r,"bodyMarkdown",t)}},parseHelpArticleSummaries=(e,t="HelpArticleSummary[]")=>parseList(e,t,parseHelpArticleSummary),parseArrayBuffer=(e,t="ArrayBuffer")=>e instanceof ArrayBuffer?e:reject(t,"the attachment bytes"),OFFLINE_MESSAGE=exports.OFFLINE_MESSAGE="You are offline. Check your connection and try again.",GENERIC_MESSAGE=exports.GENERIC_MESSAGE="Something went wrong. Try again in a moment.";class SupportApiError extends Error{constructor(e,t,r){super(t),this.name="SupportApiError",this.code=e,this.status=r}}exports.SupportApiError=SupportApiError;const toSupportApiError=e=>{if(e instanceof SupportApiError)return e;const t="object"==typeof e&&null!==e?e:{};if("RequestOfflineError"===t.name)return new SupportApiError("offline",OFFLINE_MESSAGE,null);const r="number"==typeof t.response?.status?t.response.status:null,a=t.response?.data,s="object"==typeof a&&null!==a?a:void 0,i="string"==typeof s?.code?s.code:"unknown";return s&&"string"==typeof s.detail&&s.detail.trim()?new SupportApiError(i,s.detail,r):t.response?new SupportApiError(i,GENERIC_MESSAGE,r):new SupportApiError("network",OFFLINE_MESSAGE,null)};exports.toSupportApiError=toSupportApiError;const UPLOAD_TIMEOUT_MS=3e5,textFields=(e,t)=>void 0!==t&&""!==t?[{name:e,value:t}]:[],fileFields=(e,t)=>(t??[]).map(t=>({name:e,file:{uri:t.uri,name:t.name,type:t.type}})),multipartRequest=(e,t)=>({method:"POST",url:e,headers:{"Content-Type":"multipart/form-data","Idempotency-Key":(0,_mobileCore.newIdempotencyKey)()},body:{kind:"multipart",fields:t},timeoutMs:3e5}),supportRepliesUrl=(e,t)=>`${e}/tickets/${encodeURIComponent(t)}/replies`;exports.supportRepliesUrl=supportRepliesUrl;const queryString=e=>{const t=[],add=(e,r)=>{void 0!==r&&""!==r&&t.push(`${e}=${encodeURIComponent(String(r))}`)};return add("status",e.status),add("search",e.search?.trim()),add("queue",e.queue?.trim()),add("page",e.page),add("pageSize",e.pageSize),t.length>0?`?${t.join("&")}`:""},createSupportClient=(e,t="/api/support",r)=>{const a=t.replace(/\/+$/,""),ticketUrl=e=>`${a}/tickets/${encodeURIComponent(e)}`,call=async(e,t,r)=>{let a;try{a=(await t()).data}catch(e){throw toSupportApiError(e)}try{return r(a)}catch(t){throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`,{cause:t})}},getBytes=t=>call("GET /attachments/{id}",()=>e.get(`${a}/attachments/${encodeURIComponent(t)}`,{responseType:"arraybuffer"}),parseArrayBuffer),s=r?.replace(/\/+$/,"");return{basePath:a,helpCentre:void 0===s?void 0:{settings:t=>call("GET help /settings",()=>e.get(`${s}/settings`,{signal:t?.signal}),parseHelpCentreSettings),list:(t={},r)=>call("GET help /articles",()=>e.get(`${s}/articles${queryString(t)}`,{signal:r?.signal}),parseHelpArticlePage),get:(t,r)=>call("GET help /articles/{slug}",()=>e.get(`${s}/articles/${encodeURIComponent(t)}`,{signal:r?.signal}),parseHelpArticleView),search:(t,r)=>call("GET help /search",()=>e.get(`${s}/search?q=${encodeURIComponent(t)}`,{signal:r?.signal}),parseHelpArticleSummaries)},getConfig:()=>call("GET /settings",()=>e.get(`${a}/settings`),parseSupportContactInfo),listTickets:(t={})=>call("GET /tickets",()=>e.get(`${a}/tickets${queryString(t)}`),parseSupportTicketPage),getTicketCounts:()=>call("GET /tickets/counts",()=>e.get(`${a}/tickets/counts`),parseSupportTicketCounts),getTicket:t=>call("GET /tickets/{id}",()=>e.get(ticketUrl(t)),parseSupportTicketDetail),ticketRequest:e=>multipartRequest(`${a}/tickets`,[{name:"category",value:e.category},{name:"subject",value:e.subject},{name:"body",value:e.body},...textFields("pageUrl",e.pageUrl),...textFields("userAgent",e.userAgent),...textFields("appVersion",e.appVersion),...fileFields("files",e.files),...fileFields("screenshots",e.screenshots)]),getSuggestions:t=>call("GET /suggestions",()=>e.get(`${a}/suggestions?subject=${encodeURIComponent(t)}`),parseSupportSuggestedArticles),replyRequest:(e,t)=>multipartRequest(supportRepliesUrl(a,e),[{name:"body",value:t.body},...fileFields("files",t.files),...fileFields("screenshots",t.screenshots)]),reopen:t=>call("POST /tickets/{id}/reopen",()=>e.post(`${ticketUrl(t)}/reopen`),parseSupportTicketDetail),cancel:t=>call("POST /tickets/{id}/cancel",()=>e.post(`${ticketUrl(t)}/cancel`),parseSupportTicketDetail),rate:(t,r)=>call("POST /tickets/{id}/rating",()=>e.post(`${ticketUrl(t)}/rating`,{satisfaction:r.satisfaction,comment:r.comment?.trim()?r.comment.trim():null}),parseSupportTicketDetail),getAttachmentBytes:getBytes,getAttachmentDataUri:async e=>{const t=await getBytes(e.id);return`data:${e.contentType};base64,${(0,_mobileCore.encodeBase64)(t)}`}}};exports.createSupportClient=createSupportClient;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SupportTicketDetail=void 0;var _mobileCore=require("@webority/mobile-core"),_mobileUi=require("@webority/mobile-ui"),_react=require("react"),_reactNative=require("react-native"),_labels=require("../labels.js"),_SupportProvider=require("../SupportProvider.js"),_types=require("../types.js"),_validation=require("../validation.js"),_Attachments=require("./Attachments.js"),_PhotoTray=require("./PhotoTray.js"),_SupportTicketList=require("./SupportTicketList.js"),_jsxRuntime=require("react/jsx-runtime");const LABELS={sendNow:"Send now",discard:"Discard",loading:"Loading the ticket",retry:"Try again",replyReopens:"Replying reopens this ticket.",opened:"Opened {date}",updated:"Updated {date}",merged:"This ticket was merged into {number}. The conversation carries on there.",openMerged:"Open {number}",resolvedNote:"This ticket is {status}. Reopen it if you still need help.",reopen:"Reopen ticket",withdraw:"Withdraw request",withdrawTitle:"Withdraw this request?",withdrawMessage:"Our team will stop working on this ticket. You can open a new ticket later if you still need help.",withdrawConfirm:"Withdraw request",withdrawCancel:"Keep request",yourComment:"Your comment: {comment}",solved:"Yes, it is solved",notSolved:"No, it is not",commentLabel:"Anything to add? (optional)",commentHelper:"Your comment goes to the support team.",sendAnswer:"Send answer",conversation:"Conversation",mergedBadge:"Merged into this ticket",replyPlaceholder:"Write a reply to the support team",replyLabel:"Your reply",attachPhoto:"Attach a photo",sendReply:"Send reply",you:"You",writeMessage:"Write a message.",supportTeam:"Support team",replyFailed:"Your reply did not send. Please try again.",waitingToSend:"Waiting to send",notFound:"That ticket could not be found.",discardTitle:"Discard this report?",discardMessage:"It has not been sent.",statusAccessibility:"Status: {label}",waitingText:"We need your answer to carry on. Reply below and the ticket goes back to our team.",satisfied:"You told us this solved your problem.",unsatisfied:"You told us this did not solve your problem.",ratingQuestion:"Did this solve your problem?",detailsTitle:"Ticket details",detailStatus:"Status",detailCategory:"Category",detailTicket:"Ticket",detailOpened:"Opened",detailLastUpdate:"Last update"},MessageBubble=({message:e,styles:t,timeZone:i,labels:s,onOpenImage:a})=>{if("System"===e.authorKind)return(0,_jsxRuntime.jsx)(_reactNative.View,{style:t.system,testID:`support-message-${e.id}`,children:(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"caption",color:"tertiary",align:"center",children:`${e.body}, ${(0,_mobileCore.formatDateTime)(e.createdDateTimeUtc,{zone:i})}`})});const n="Customer"===e.authorKind;return(0,_jsxRuntime.jsx)(_reactNative.View,{style:[t.bubbleRow,n?t.mineRow:t.theirsRow],testID:`support-message-${e.id}`,children:(0,_jsxRuntime.jsxs)(_reactNative.View,{style:[t.bubble,n?t.mine:t.theirs],children:[(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"label",color:n?"primary":"secondary",children:e.authorName??(n?s.you:s.supportTeam)}),(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"body",selectable:!0,children:e.body}),(0,_jsxRuntime.jsx)(_Attachments.AttachmentList,{attachments:e.attachments,onOpenImage:a}),(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"caption",color:"tertiary",children:(0,_mobileCore.formatDateTime)(e.createdDateTimeUtc,{zone:i})})]})})},pendingReplyBody=e=>{const{body:t}=e.request;if("json"===t.kind){const e=t.value;return"string"==typeof e?.body?e.body:""}const i=t.fields.find(e=>"body"===e.name);return i&&"value"in i?i.value:""},PendingReplyBubble=({entry:e,styles:t,labels:i,onSendNow:s,onDiscard:a})=>{const n="Failed"===e.state;return(0,_jsxRuntime.jsx)(_reactNative.View,{style:[t.bubbleRow,t.mineRow],testID:`support-pending-${e.id}`,children:(0,_jsxRuntime.jsxs)(_reactNative.View,{style:[t.bubble,t.mine],children:[(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"label",color:"primary",children:i.you}),(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"body",selectable:!0,children:pendingReplyBody(e)}),(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"caption",color:n?"danger":"tertiary",accessibilityLiveRegion:"polite",children:n?i.replyFailed:i.waitingToSend}),(0,_jsxRuntime.jsxs)(_reactNative.View,{style:t.ratingRow,children:[(0,_jsxRuntime.jsx)(_mobileUi.Button,{label:i.sendNow,size:"sm",variant:"outline",onPress:()=>s(e.id),testID:`support-pending-send-${e.id}`}),(0,_jsxRuntime.jsx)(_mobileUi.Button,{label:i.discard,size:"sm",variant:"ghost",onPress:()=>a(e.id),testID:`support-pending-discard-${e.id}`})]})]})})},SupportTicketDetail=({ticketId:e,onOpenTicket:t,testID:i="support-ticket-detail"})=>{const s=(0,_SupportProvider.useSupportLabels)("ticketDetail",LABELS),a=(0,_SupportProvider.useSupportLabels)("shared",_labels.SHARED_LABELS),n=(0,_mobileUi.useTheme)(),o=(0,_react.useMemo)(()=>buildStyles(n),[n]),{config:l}=(0,_SupportProvider.useSupportConfig)(),r=(0,_SupportProvider.useSupportTimeZone)(),{ticket:d,loading:c,error:m,actionError:u,busy:p,pendingReplies:b,reload:x,reply:_,reopen:y,cancel:j,rate:g}=(0,_SupportProvider.useSupportTicket)(e),h=(0,_SupportProvider.useSupportOutbox)(_types.SUPPORT_REPLY_QUEUE),[R,v]=(0,_react.useState)(null),[S,T]=(0,_react.useState)(""),[w,U]=(0,_react.useState)([]),[f,D]=(0,_react.useState)(!1),[L,C]=(0,_react.useState)(null),[k,I]=(0,_react.useState)(null),[P,B]=(0,_react.useState)(""),[N,A]=(0,_react.useState)(!1);if(!d)return(0,_jsxRuntime.jsx)(_reactNative.View,{style:o.center,testID:i,children:c?(0,_jsxRuntime.jsx)(_mobileUi.Spinner,{accessibilityLabel:s.loading}):(0,_jsxRuntime.jsxs)(_jsxRuntime.Fragment,{children:[(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"body",color:"danger",align:"center",children:m?.message??s.notFound}),(0,_jsxRuntime.jsx)(_mobileUi.Button,{label:s.retry,variant:"ghost",onPress:()=>{x()}})]})});const q={Satisfied:s.satisfied,Unsatisfied:s.unsatisfied},z=d.mergedInto,M=d.messages.filter(e=>!e.isInternal),O=d.updatedDateTimeUtc!==d.createdDateTimeUtc,V=L??u?.message??null,$=Boolean(l)&&(f||w.length>0),E=$||V||d.canReopen?(0,_jsxRuntime.jsxs)(_jsxRuntime.Fragment,{children:[$&&l&&(0,_jsxRuntime.jsx)(_PhotoTray.PhotoTray,{photos:w,onChange:e=>{U(e),C(null)},remaining:l.maxAttachmentsPerMessage-w.length,maxBytes:l.maxAttachmentBytes,disabled:p}),V&&(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"bodySmall",color:"danger",accessibilityLiveRegion:"polite",children:V}),d.canReopen&&(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"caption",color:"secondary",children:s.replyReopens})]}):void 0;return(0,_jsxRuntime.jsxs)(_reactNative.View,{style:o.root,testID:i,children:[(0,_jsxRuntime.jsxs)(_mobileUi.KeyboardAwareScrollView,{contentContainerStyle:o.content,safeAreaEdges:[],children:[(0,_jsxRuntime.jsxs)(_reactNative.View,{style:o.head,children:[(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"h3",accessibilityRole:"header",children:d.subject}),(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"bodySmall",color:"secondary",children:`${d.number}, ${d.category}`}),(0,_jsxRuntime.jsxs)(_reactNative.View,{style:o.headRow,children:[(0,_jsxRuntime.jsx)(_mobileUi.StatusBadge,{label:d.statusLabel,tone:_SupportTicketList.STATUS_TONES[d.status]??"neutral",accessibilityLabel:(0,_labels.fillLabel)(s.statusAccessibility,{label:d.statusLabel})}),(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"caption",color:"tertiary",children:(0,_labels.fillLabel)(s.opened,{date:(0,_mobileCore.formatDateTime)(d.createdDateTimeUtc,{zone:r})})}),O&&(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"caption",color:"tertiary",children:(0,_labels.fillLabel)(s.updated,{date:(0,_mobileCore.formatDateTime)(d.updatedDateTimeUtc,{zone:r})})})]})]}),z&&(0,_jsxRuntime.jsxs)(_mobileUi.Card,{variant:"outline",bodyStyle:o.section,testID:"support-merged-into",children:[(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"bodySmall",accessibilityLiveRegion:"polite",children:(0,_labels.fillLabel)(s.merged,{number:z.number})}),t&&(0,_jsxRuntime.jsx)(_mobileUi.Button,{label:(0,_labels.fillLabel)(s.openMerged,{number:z.number}),variant:"link",size:"sm",onPress:()=>t(z.id),testID:"support-merged-into-open"})]}),"WaitingOnCustomer"===d.status&&(0,_jsxRuntime.jsx)(_mobileUi.Card,{variant:"outline",bodyStyle:o.section,testID:"support-waiting",children:(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"bodySmall",children:s.waitingText})}),d.canReopen&&(0,_jsxRuntime.jsxs)(_mobileUi.Card,{variant:"outline",bodyStyle:o.section,children:[(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"bodySmall",children:(0,_labels.fillLabel)(s.resolvedNote,{status:d.statusLabel.toLowerCase()})}),(0,_jsxRuntime.jsx)(_mobileUi.Button,{label:s.reopen,variant:"outline",size:"sm",loading:p,disabled:p,onPress:()=>{y()},testID:"support-reopen"})]}),d.canCancel&&(0,_jsxRuntime.jsxs)(_mobileUi.Card,{variant:"outline",bodyStyle:o.section,children:[(0,_jsxRuntime.jsx)(_mobileUi.Button,{label:s.withdraw,variant:"outline",size:"sm",loading:p,disabled:p,onPress:()=>A(!0),testID:"support-withdraw"}),(0,_jsxRuntime.jsx)(_mobileUi.Dialog,{open:N,onClose:()=>A(!1),title:s.withdrawTitle,message:s.withdrawMessage,tone:"danger",actions:[{label:s.withdrawCancel,onPress:()=>A(!1),tone:"neutral"},{label:s.withdrawConfirm,onPress:()=>{j()},tone:"danger"}]})]}),d.satisfaction?(0,_jsxRuntime.jsxs)(_mobileUi.Card,{variant:"outline",bodyStyle:o.section,testID:"support-rating",children:[(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"bodySmall",accessibilityLiveRegion:"polite",children:q[d.satisfaction]}),d.satisfactionComment?(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"bodySmall",color:"secondary",children:(0,_labels.fillLabel)(s.yourComment,{comment:d.satisfactionComment})}):null]}):d.canRate?(0,_jsxRuntime.jsxs)(_mobileUi.Card,{variant:"outline",bodyStyle:o.section,testID:"support-rating",children:[(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"label",children:s.ratingQuestion}),(0,_jsxRuntime.jsxs)(_reactNative.View,{style:o.ratingRow,children:[(0,_jsxRuntime.jsx)(_mobileUi.Button,{label:s.solved,size:"sm",leftIcon:"like",variant:"Satisfied"===k?"solid":"outline",tone:"success",accessibilityState:{selected:"Satisfied"===k},"aria-selected":"Satisfied"===k,onPress:()=>I("Satisfied"),testID:"support-rate-satisfied"}),(0,_jsxRuntime.jsx)(_mobileUi.Button,{label:s.notSolved,size:"sm",leftIcon:"dislike",variant:"Unsatisfied"===k?"solid":"outline",tone:"danger",accessibilityState:{selected:"Unsatisfied"===k},"aria-selected":"Unsatisfied"===k,onPress:()=>I("Unsatisfied"),testID:"support-rate-unsatisfied"})]}),k&&(0,_jsxRuntime.jsxs)(_jsxRuntime.Fragment,{children:[(0,_jsxRuntime.jsx)(_mobileUi.Input,{label:s.commentLabel,helperText:s.commentHelper,value:P,onChangeText:B,multiline:!0,maxLength:l?.satisfactionCommentMaxLength,testID:"support-rating-comment"}),(0,_jsxRuntime.jsx)(_mobileUi.Button,{label:s.sendAnswer,size:"sm",loading:p,disabled:p,onPress:()=>{(async()=>{k&&await g({satisfaction:k,comment:P})&&(I(null),B(""))})()},testID:"support-rating-send"})]})]}):null,(0,_jsxRuntime.jsxs)(_reactNative.View,{style:o.thread,accessibilityLabel:s.conversation,children:[M.map(e=>(0,_jsxRuntime.jsx)(MessageBubble,{message:e,styles:o,timeZone:r,labels:s,onOpenImage:(e,t)=>v({uri:e,name:t})},e.id)),b.map(e=>(0,_jsxRuntime.jsx)(PendingReplyBubble,{entry:e,styles:o,labels:s,onSendNow:e=>{h.retry(e)},onDiscard:e=>{(async e=>{await(0,_mobileUi.confirm)({title:s.discardTitle,message:s.discardMessage,confirmLabel:s.discard,tone:"danger"})&&await h.discard(e)})(e)}},e.id))]}),d.mergedTickets&&d.mergedTickets.length>0&&(0,_jsxRuntime.jsxs)(_reactNative.View,{style:o.section,testID:"support-merged-tickets",children:[(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"label",accessibilityRole:"header",children:s.mergedBadge}),d.mergedTickets.map(e=>t?(0,_jsxRuntime.jsx)(_mobileUi.Button,{label:`${e.number}: ${e.subject}`,variant:"link",size:"sm",onPress:()=>t(e.id),testID:`support-merged-ticket-${e.id}`},e.id):(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"bodySmall",testID:`support-merged-ticket-${e.id}`,children:`${e.number}: ${e.subject}`},e.id))]}),(0,_jsxRuntime.jsxs)(_mobileUi.Card,{variant:"outline",bodyStyle:o.section,testID:"support-details",accessibilityRole:"summary",children:[(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"label",children:s.detailsTitle}),(0,_jsxRuntime.jsx)(_mobileUi.Descriptions,{items:[{label:s.detailStatus,value:(0,_jsxRuntime.jsx)(_mobileUi.StatusBadge,{label:d.statusLabel,tone:_SupportTicketList.STATUS_TONES[d.status]??"neutral",accessibilityLabel:(0,_labels.fillLabel)(s.statusAccessibility,{label:d.statusLabel})})},{label:s.detailCategory,value:d.category||"-"},{label:s.detailTicket,value:d.number},{label:s.detailOpened,value:(0,_mobileCore.formatDateTime)(d.createdDateTimeUtc,{zone:r})},{label:s.detailLastUpdate,value:(0,_mobileCore.formatDateTime)(d.updatedDateTimeUtc,{zone:r})}]})]})]}),!z&&(0,_jsxRuntime.jsx)(_mobileUi.Composer,{value:S,onChangeText:e=>{T(e),C(null)},onSend:e=>{(async e=>{const t=e.trim(),i=l?(0,_validation.validateBody)(t,l,a)??(0,_validation.validateFiles)(w,l,a):t?void 0:s.writeMessage;if(i)return C(i),void T(e);"Failed"!==await _({body:t,files:w})?(U([]),D(!1)):T(e)})(e)},loading:p,maxLength:l?.bodyMaxLength,placeholder:s.replyPlaceholder,accessibilityLabel:s.replyLabel,labels:{send:s.sendReply,message:s.replyLabel},leading:(0,_jsxRuntime.jsx)(_mobileUi.IconButton,{icon:"paperclip",size:"md",accessibilityLabel:s.attachPhoto,disabled:p||!l,onPress:()=>D(e=>!e),testID:"support-reply-attach"}),above:E,testID:"support-reply-composer"}),(0,_jsxRuntime.jsx)(_Attachments.ImageViewer,{image:R,onClose:()=>v(null)})]})};exports.SupportTicketDetail=SupportTicketDetail;const buildStyles=e=>_reactNative.StyleSheet.create({root:{flex:1},content:{padding:e.space.md,gap:e.space.md},center:{flex:1,alignItems:"center",justifyContent:"center",padding:e.space.xl,gap:e.space.sm},head:{gap:e.space.xxs},headRow:{flexDirection:"row",alignItems:"center",gap:e.space.sm,marginTop:e.space.xs},section:{gap:e.space.sm},ratingRow:{flexDirection:"row",flexWrap:"wrap",gap:e.space.sm},thread:{gap:e.space.sm},system:{paddingHorizontal:e.space.lg,paddingVertical:e.space.xxs},bubbleRow:{flexDirection:"row"},mineRow:{justifyContent:"flex-end"},theirsRow:{justifyContent:"flex-start"},bubble:{maxWidth:"85%",borderRadius:e.radius.lg,padding:e.space.sm,gap:e.space.xxs},mine:{backgroundColor:e.colors["primary-soft"]},theirs:{backgroundColor:e.colors["bg-subtle"]}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SupportTicketDetail=void 0;var _mobileCore=require("@webority/mobile-core"),_mobileUi=require("@webority/mobile-ui"),_react=require("react"),_reactNative=require("react-native"),_labels=require("../labels.js"),_SupportProvider=require("../SupportProvider.js"),_types=require("../types.js"),_validation=require("../validation.js"),_Attachments=require("./Attachments.js"),_PhotoTray=require("./PhotoTray.js"),_SupportTicketList=require("./SupportTicketList.js"),_jsxRuntime=require("react/jsx-runtime");const LABELS={sendNow:"Send now",discard:"Discard",loading:"Loading the ticket",retry:"Try again",replyReopens:"Replying reopens this ticket.",opened:"Opened {date}",updated:"Updated {date}",merged:"This ticket was merged into {number}. The conversation carries on there.",openMerged:"Open {number}",resolvedNote:"This ticket is {status}. Reopen it if you still need help.",reopen:"Reopen ticket",withdraw:"Withdraw request",withdrawTitle:"Withdraw this request?",withdrawMessage:"Our team will stop working on this ticket. You can open a new ticket later if you still need help.",withdrawConfirm:"Withdraw request",withdrawCancel:"Keep request",yourComment:"Your comment: {comment}",solved:"Yes, it is solved",notSolved:"No, it is not",commentLabel:"Anything to add? (optional)",commentHelper:"Your comment goes to the support team.",sendAnswer:"Send answer",conversation:"Conversation",mergedBadge:"Merged into this ticket",replyPlaceholder:"Write a reply to the support team",replyLabel:"Your reply",attachPhoto:"Attach a photo",sendReply:"Send reply",you:"You",writeMessage:"Write a message.",supportTeam:"Support team",replyFailed:"Your reply did not send. Please try again.",waitingToSend:"Waiting to send",notFound:"That ticket could not be found.",discardTitle:"Discard this report?",discardMessage:"It has not been sent.",statusAccessibility:"Status: {label}",waitingText:"We need your answer to carry on. Reply below and the ticket goes back to our team.",satisfied:"You told us this solved your problem.",unsatisfied:"You told us this did not solve your problem.",ratingQuestion:"Did this solve your problem?",detailsTitle:"Ticket details",detailStatus:"Status",detailCategory:"Category",detailTicket:"Ticket",detailOpened:"Opened",detailLastUpdate:"Last update"},MessageBubble=({message:e,styles:t,timeZone:i,labels:s,onOpenImage:a})=>{if("System"===e.authorKind)return(0,_jsxRuntime.jsx)(_reactNative.View,{style:t.system,testID:`support-message-${e.id}`,children:(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"caption",color:"tertiary",align:"center",children:`${e.body}, ${(0,_mobileCore.formatDateTime)(e.createdDateTimeUtc,{zone:i})}`})});const n="Customer"===e.authorKind;return(0,_jsxRuntime.jsx)(_reactNative.View,{style:[t.bubbleRow,n?t.mineRow:t.theirsRow],testID:`support-message-${e.id}`,children:(0,_jsxRuntime.jsxs)(_reactNative.View,{style:[t.bubble,n?t.mine:t.theirs],children:[(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"label",color:n?"primary":"secondary",children:e.authorName??(n?s.you:s.supportTeam)}),(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"body",selectable:!0,children:e.body}),(0,_jsxRuntime.jsx)(_Attachments.AttachmentList,{attachments:e.attachments,onOpenImage:a}),(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"caption",color:"tertiary",children:(0,_mobileCore.formatDateTime)(e.createdDateTimeUtc,{zone:i})})]})})},pendingReplyBody=e=>{const{body:t}=e.request;if("json"===t.kind){const e=t.value;return"object"==typeof e&&null!==e&&"body"in e&&"string"==typeof e.body?e.body:""}const i=t.fields.find(e=>"body"===e.name);return i&&"value"in i?i.value:""},PendingReplyBubble=({entry:e,styles:t,labels:i,onSendNow:s,onDiscard:a})=>{const n="Failed"===e.state;return(0,_jsxRuntime.jsx)(_reactNative.View,{style:[t.bubbleRow,t.mineRow],testID:`support-pending-${e.id}`,children:(0,_jsxRuntime.jsxs)(_reactNative.View,{style:[t.bubble,t.mine],children:[(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"label",color:"primary",children:i.you}),(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"body",selectable:!0,children:pendingReplyBody(e)}),(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"caption",color:n?"danger":"tertiary",accessibilityLiveRegion:"polite",children:n?i.replyFailed:i.waitingToSend}),(0,_jsxRuntime.jsxs)(_reactNative.View,{style:t.ratingRow,children:[(0,_jsxRuntime.jsx)(_mobileUi.Button,{label:i.sendNow,size:"sm",variant:"outline",onPress:()=>s(e.id),testID:`support-pending-send-${e.id}`}),(0,_jsxRuntime.jsx)(_mobileUi.Button,{label:i.discard,size:"sm",variant:"ghost",onPress:()=>a(e.id),testID:`support-pending-discard-${e.id}`})]})]})})},SupportTicketDetail=({ticketId:e,onOpenTicket:t,testID:i="support-ticket-detail"})=>{const s=(0,_SupportProvider.useSupportLabels)("ticketDetail",LABELS),a=(0,_SupportProvider.useSupportLabels)("shared",_labels.SHARED_LABELS),n=(0,_mobileUi.useTheme)(),o=(0,_react.useMemo)(()=>buildStyles(n),[n]),{config:l}=(0,_SupportProvider.useSupportConfig)(),r=(0,_SupportProvider.useSupportTimeZone)(),{ticket:d,loading:c,error:m,actionError:u,busy:p,pendingReplies:b,reload:x,reply:_,reopen:y,cancel:j,rate:g}=(0,_SupportProvider.useSupportTicket)(e),h=(0,_SupportProvider.useSupportOutbox)(_types.SUPPORT_REPLY_QUEUE),[R,v]=(0,_react.useState)(null),[S,T]=(0,_react.useState)(""),[w,U]=(0,_react.useState)([]),[f,D]=(0,_react.useState)(!1),[L,C]=(0,_react.useState)(null),[k,I]=(0,_react.useState)(null),[P,B]=(0,_react.useState)(""),[N,A]=(0,_react.useState)(!1);if(!d)return(0,_jsxRuntime.jsx)(_reactNative.View,{style:o.center,testID:i,children:c?(0,_jsxRuntime.jsx)(_mobileUi.Spinner,{accessibilityLabel:s.loading}):(0,_jsxRuntime.jsxs)(_jsxRuntime.Fragment,{children:[(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"body",color:"danger",align:"center",children:m?.message??s.notFound}),(0,_jsxRuntime.jsx)(_mobileUi.Button,{label:s.retry,variant:"ghost",onPress:()=>{x()}})]})});const q={Satisfied:s.satisfied,Unsatisfied:s.unsatisfied},z=d.mergedInto,M=d.messages.filter(e=>!e.isInternal),O=d.updatedDateTimeUtc!==d.createdDateTimeUtc,V=L??u?.message??null,$=Boolean(l)&&(f||w.length>0),E=$||V||d.canReopen?(0,_jsxRuntime.jsxs)(_jsxRuntime.Fragment,{children:[$&&l&&(0,_jsxRuntime.jsx)(_PhotoTray.PhotoTray,{photos:w,onChange:e=>{U(e),C(null)},remaining:l.maxAttachmentsPerMessage-w.length,maxBytes:l.maxAttachmentBytes,disabled:p}),V&&(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"bodySmall",color:"danger",accessibilityLiveRegion:"polite",children:V}),d.canReopen&&(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"caption",color:"secondary",children:s.replyReopens})]}):void 0;return(0,_jsxRuntime.jsxs)(_reactNative.View,{style:o.root,testID:i,children:[(0,_jsxRuntime.jsxs)(_mobileUi.KeyboardAwareScrollView,{contentContainerStyle:o.content,safeAreaEdges:[],children:[(0,_jsxRuntime.jsxs)(_reactNative.View,{style:o.head,children:[(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"h3",accessibilityRole:"header",children:d.subject}),(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"bodySmall",color:"secondary",children:`${d.number}, ${d.category}`}),(0,_jsxRuntime.jsxs)(_reactNative.View,{style:o.headRow,children:[(0,_jsxRuntime.jsx)(_mobileUi.StatusBadge,{label:d.statusLabel,tone:_SupportTicketList.STATUS_TONES[d.status]??"neutral",accessibilityLabel:(0,_labels.fillLabel)(s.statusAccessibility,{label:d.statusLabel})}),(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"caption",color:"tertiary",children:(0,_labels.fillLabel)(s.opened,{date:(0,_mobileCore.formatDateTime)(d.createdDateTimeUtc,{zone:r})})}),O&&(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"caption",color:"tertiary",children:(0,_labels.fillLabel)(s.updated,{date:(0,_mobileCore.formatDateTime)(d.updatedDateTimeUtc,{zone:r})})})]})]}),z&&(0,_jsxRuntime.jsxs)(_mobileUi.Card,{variant:"outline",bodyStyle:o.section,testID:"support-merged-into",children:[(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"bodySmall",accessibilityLiveRegion:"polite",children:(0,_labels.fillLabel)(s.merged,{number:z.number})}),t&&(0,_jsxRuntime.jsx)(_mobileUi.Button,{label:(0,_labels.fillLabel)(s.openMerged,{number:z.number}),variant:"link",size:"sm",onPress:()=>t(z.id),testID:"support-merged-into-open"})]}),"WaitingOnCustomer"===d.status&&(0,_jsxRuntime.jsx)(_mobileUi.Card,{variant:"outline",bodyStyle:o.section,testID:"support-waiting",children:(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"bodySmall",children:s.waitingText})}),d.canReopen&&(0,_jsxRuntime.jsxs)(_mobileUi.Card,{variant:"outline",bodyStyle:o.section,children:[(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"bodySmall",children:(0,_labels.fillLabel)(s.resolvedNote,{status:d.statusLabel.toLowerCase()})}),(0,_jsxRuntime.jsx)(_mobileUi.Button,{label:s.reopen,variant:"outline",size:"sm",loading:p,disabled:p,onPress:()=>{y()},testID:"support-reopen"})]}),d.canCancel&&(0,_jsxRuntime.jsxs)(_mobileUi.Card,{variant:"outline",bodyStyle:o.section,children:[(0,_jsxRuntime.jsx)(_mobileUi.Button,{label:s.withdraw,variant:"outline",size:"sm",loading:p,disabled:p,onPress:()=>A(!0),testID:"support-withdraw"}),(0,_jsxRuntime.jsx)(_mobileUi.Dialog,{open:N,onClose:()=>A(!1),title:s.withdrawTitle,message:s.withdrawMessage,tone:"danger",actions:[{label:s.withdrawCancel,onPress:()=>A(!1),tone:"neutral"},{label:s.withdrawConfirm,onPress:()=>{j()},tone:"danger"}]})]}),d.satisfaction?(0,_jsxRuntime.jsxs)(_mobileUi.Card,{variant:"outline",bodyStyle:o.section,testID:"support-rating",children:[(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"bodySmall",accessibilityLiveRegion:"polite",children:q[d.satisfaction]}),d.satisfactionComment?(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"bodySmall",color:"secondary",children:(0,_labels.fillLabel)(s.yourComment,{comment:d.satisfactionComment})}):null]}):d.canRate?(0,_jsxRuntime.jsxs)(_mobileUi.Card,{variant:"outline",bodyStyle:o.section,testID:"support-rating",children:[(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"label",children:s.ratingQuestion}),(0,_jsxRuntime.jsxs)(_reactNative.View,{style:o.ratingRow,children:[(0,_jsxRuntime.jsx)(_mobileUi.Button,{label:s.solved,size:"sm",leftIcon:"like",variant:"Satisfied"===k?"solid":"outline",tone:"success",accessibilityState:{selected:"Satisfied"===k},"aria-selected":"Satisfied"===k,onPress:()=>I("Satisfied"),testID:"support-rate-satisfied"}),(0,_jsxRuntime.jsx)(_mobileUi.Button,{label:s.notSolved,size:"sm",leftIcon:"dislike",variant:"Unsatisfied"===k?"solid":"outline",tone:"danger",accessibilityState:{selected:"Unsatisfied"===k},"aria-selected":"Unsatisfied"===k,onPress:()=>I("Unsatisfied"),testID:"support-rate-unsatisfied"})]}),k&&(0,_jsxRuntime.jsxs)(_jsxRuntime.Fragment,{children:[(0,_jsxRuntime.jsx)(_mobileUi.Input,{label:s.commentLabel,helperText:s.commentHelper,value:P,onChangeText:B,multiline:!0,maxLength:l?.satisfactionCommentMaxLength,testID:"support-rating-comment"}),(0,_jsxRuntime.jsx)(_mobileUi.Button,{label:s.sendAnswer,size:"sm",loading:p,disabled:p,onPress:()=>{(async()=>{k&&await g({satisfaction:k,comment:P})&&(I(null),B(""))})()},testID:"support-rating-send"})]})]}):null,(0,_jsxRuntime.jsxs)(_reactNative.View,{style:o.thread,accessibilityLabel:s.conversation,children:[M.map(e=>(0,_jsxRuntime.jsx)(MessageBubble,{message:e,styles:o,timeZone:r,labels:s,onOpenImage:(e,t)=>v({uri:e,name:t})},e.id)),b.map(e=>(0,_jsxRuntime.jsx)(PendingReplyBubble,{entry:e,styles:o,labels:s,onSendNow:e=>{h.retry(e)},onDiscard:e=>{(async e=>{await(0,_mobileUi.confirm)({title:s.discardTitle,message:s.discardMessage,confirmLabel:s.discard,tone:"danger"})&&await h.discard(e)})(e)}},e.id))]}),d.mergedTickets&&d.mergedTickets.length>0&&(0,_jsxRuntime.jsxs)(_reactNative.View,{style:o.section,testID:"support-merged-tickets",children:[(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"label",accessibilityRole:"header",children:s.mergedBadge}),d.mergedTickets.map(e=>t?(0,_jsxRuntime.jsx)(_mobileUi.Button,{label:`${e.number}: ${e.subject}`,variant:"link",size:"sm",onPress:()=>t(e.id),testID:`support-merged-ticket-${e.id}`},e.id):(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"bodySmall",testID:`support-merged-ticket-${e.id}`,children:`${e.number}: ${e.subject}`},e.id))]}),(0,_jsxRuntime.jsxs)(_mobileUi.Card,{variant:"outline",bodyStyle:o.section,testID:"support-details",accessibilityRole:"summary",children:[(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"label",children:s.detailsTitle}),(0,_jsxRuntime.jsx)(_mobileUi.Descriptions,{items:[{label:s.detailStatus,value:(0,_jsxRuntime.jsx)(_mobileUi.StatusBadge,{label:d.statusLabel,tone:_SupportTicketList.STATUS_TONES[d.status]??"neutral",accessibilityLabel:(0,_labels.fillLabel)(s.statusAccessibility,{label:d.statusLabel})})},{label:s.detailCategory,value:d.category||"-"},{label:s.detailTicket,value:d.number},{label:s.detailOpened,value:(0,_mobileCore.formatDateTime)(d.createdDateTimeUtc,{zone:r})},{label:s.detailLastUpdate,value:(0,_mobileCore.formatDateTime)(d.updatedDateTimeUtc,{zone:r})}]})]})]}),!z&&(0,_jsxRuntime.jsx)(_mobileUi.Composer,{value:S,onChangeText:e=>{T(e),C(null)},onSend:e=>{(async e=>{const t=e.trim(),i=l?(0,_validation.validateBody)(t,l,a)??(0,_validation.validateFiles)(w,l,a):t?void 0:s.writeMessage;if(i)return C(i),void T(e);"Failed"!==await _({body:t,files:w})?(U([]),D(!1)):T(e)})(e)},loading:p,maxLength:l?.bodyMaxLength,placeholder:s.replyPlaceholder,accessibilityLabel:s.replyLabel,labels:{send:s.sendReply,message:s.replyLabel},leading:(0,_jsxRuntime.jsx)(_mobileUi.IconButton,{icon:"paperclip",size:"md",accessibilityLabel:s.attachPhoto,disabled:p||!l,onPress:()=>D(e=>!e),testID:"support-reply-attach"}),above:E,testID:"support-reply-composer"}),(0,_jsxRuntime.jsx)(_Attachments.ImageViewer,{image:R,onClose:()=>v(null)})]})};exports.SupportTicketDetail=SupportTicketDetail;const buildStyles=e=>_reactNative.StyleSheet.create({root:{flex:1},content:{padding:e.space.md,gap:e.space.md},center:{flex:1,alignItems:"center",justifyContent:"center",padding:e.space.xl,gap:e.space.sm},head:{gap:e.space.xxs},headRow:{flexDirection:"row",alignItems:"center",gap:e.space.sm,marginTop:e.space.xs},section:{gap:e.space.sm},ratingRow:{flexDirection:"row",flexWrap:"wrap",gap:e.space.sm},thread:{gap:e.space.sm},system:{paddingHorizontal:e.space.lg,paddingVertical:e.space.xxs},bubbleRow:{flexDirection:"row"},mineRow:{justifyContent:"flex-end"},theirsRow:{justifyContent:"flex-start"},bubble:{maxWidth:"85%",borderRadius:e.radius.lg,padding:e.space.sm,gap:e.space.xxs},mine:{backgroundColor:e.colors["primary-soft"]},theirs:{backgroundColor:e.colors["bg-subtle"]}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.shareSupportFile=exports.SupportShareUnavailableError=void 0;var _share=require("@webority/mobile-core/share");class SupportShareUnavailableError extends Error{constructor(){super("Opening files is not available on this device."),this.name="SupportShareUnavailableError"}}exports.SupportShareUnavailableError=SupportShareUnavailableError;const shareSupportFile=async r=>{try{await(0,_share.shareFile)(r.uri,{mimeType:r.contentType,dialogTitle:r.name})}catch(r){
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.shareSupportFile=exports.SupportShareUnavailableError=void 0;var _share=require("@webority/mobile-core/share");class SupportShareUnavailableError extends Error{constructor(){super("Opening files is not available on this device."),this.name="SupportShareUnavailableError"}}function isShareUnavailable(r){return"object"==typeof r&&null!==r&&"name"in r&&"code"in r&&"ShareError"===r.name&&"unavailable"===r.code}exports.SupportShareUnavailableError=SupportShareUnavailableError;const shareSupportFile=async r=>{try{await(0,_share.shareFile)(r.uri,{mimeType:r.contentType,dialogTitle:r.name})}catch(r){if(isShareUnavailable(r))throw new SupportShareUnavailableError;throw r}};exports.shareSupportFile=shareSupportFile;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import{Logger,Storage}from"@webority/mobile-core";import{createContext,useCallback,useContext,useEffect,useMemo,useRef,useState}from"react";import{AppState}from"react-native";import{SupportApiError,supportRepliesUrl,toSupportApiError}from"./client.js";import{saveAttachmentToCache}from"./files.js";import{SUPPORT_REPLY_QUEUE,SUPPORT_TICKET_QUEUE}from"./types.js";import{jsx as _jsx}from"react/jsx-runtime";const SupportContext=createContext(null);export const SupportProvider=({client:e,outbox:t,openFile:r,timeZone:o,labels:u,children:n})=>{if(!t)throw new Error("[@webority/mobile-support] <SupportProvider> needs an outbox={...}, created with createOutbox from mobile-core.");const[s,a]=useState(null),[c,l]=useState(null),[i,p]=useState(!0),[S,f]=useState(0),d=useRef(new Map),E=useCallback(async()=>{p(!0);const t=`@webority/mobile-support/config:${e.basePath}`;try{const r=await e.getConfig();Storage.setItem(t,JSON.stringify(r)),a(r),l(null)}catch(e){const r=toSupportApiError(e);if(l(r),"offline"===r.code||"network"===r.code){const e=await Storage.getJson(t);e&&a(e)}}finally{p(!1)}},[e]);useEffect(()=>{d.current.clear(),E()},[E]);const b=useCallback(t=>{const r=d.current.get(t.id);if(r)return r;const o=e.getAttachmentDataUri(t);return d.current.set(t.id,o),o.catch(()=>d.current.delete(t.id)),o},[e]),m=useMemo(()=>r?async t=>{const o=await saveAttachmentToCache(t,()=>e.getAttachmentBytes(t.id));await r({uri:o,name:t.fileName,contentType:t.contentType})}:null,[e,r]),g=useCallback(()=>f(e=>e+1),[]);useEffect(()=>t.subscribe(e=>{"sent"!==e.type||e.entry.queue!==SUPPORT_TICKET_QUEUE&&e.entry.queue!==SUPPORT_REPLY_QUEUE||g()}),[t,g]);const y=useMemo(()=>({client:e,outbox:t,config:s,configError:c,configLoading:i,reloadConfig:E,loadAttachment:b,openAttachment:m,timeZone:o,labels:u,revision:S,bumpRevision:g}),[e,t,s,c,i,E,b,m,o,u,S,g]);return _jsx(SupportContext.Provider,{value:y,children:n})};const useSupportContext=()=>{const e=useContext(SupportContext);if(!e)throw new Error("[@webority/mobile-support] Support screens and hooks need a <SupportProvider client={...}> above them.");return e};export const useSupportClient=()=>useSupportContext().client;export const useAttachmentLoader=()=>useSupportContext().loadAttachment;export const useAttachmentOpener=()=>useSupportContext().openAttachment;export const useSupportTimeZone=()=>useSupportContext().timeZone;export const useSupportLabels=(e,t)=>{const r=useSupportContext().labels?.[e];return useMemo(()=>r?{...t,...r}:t,[r,t])};export const useSupportConfig=()=>{const{config:e,configLoading:t,configError:r,reloadConfig:o}=useSupportContext();return{config:e,loading:t,error:r,reload:o}};const DEFAULT_PAGE_SIZE=20;export const useSupportTickets=(e={})=>{const t=e.pageSize??20,{client:r,revision:o}=useSupportContext(),[u,n]=useState(null),[s,a]=useState(""),[c,l]=useState([]),[i,p]=useState(null),[S,f]=useState(0),[d,E]=useState(0),[b,m]=useState(!0),[g,y]=useState(!1),[C,h]=useState(!1),[x,k]=useState(null),[T,w]=useState(null),P=useRef(!0),R=useRef(0),U=useRef(!1),_=useRef(null);useEffect(()=>(P.current=!0,()=>{P.current=!1}),[]);const A=useCallback(e=>({status:u??void 0,search:s.trim()||void 0,page:e,pageSize:t}),[u,s,t]),v=useCallback(async e=>{R.current+=1;const t=R.current,current=()=>P.current&&t===R.current;U.current=!1,h(!1),"refresh"===e?y(!0):"replace"===e&&(m(!0),l([]));const o="replace"!==e||_.current!==r;try{const[e,t]=await Promise.all([r.listTickets(A(1)),o?r.getTicketCounts():null]);current()&&(l(e.items),f(e.page),E(e.totalPages),t&&(p(t),_.current=r),k(null),w(null))}catch(e){current()&&k(toSupportApiError(e))}finally{current()&&(m(!1),y(!1))}},[r,A]),O=useRef(o);useEffect(()=>{const e=O.current===o?"replace":"quiet";O.current=o,v(e)},[v,o]);const q=S<d,L=useCallback(async()=>{if(U.current||b||g||!q)return;const e=R.current,current=()=>P.current&&e===R.current;U.current=!0,h(!0),w(null);try{const e=await r.listTickets(A(S+1));current()&&(l(t=>{const r=new Set(t.map(e=>e.id));return[...t,...e.items.filter(e=>!r.has(e.id))]}),f(e.page),E(e.totalPages))}catch(e){current()&&w(toSupportApiError(e))}finally{current()&&(U.current=!1,h(!1))}},[r,A,S,q,b,g]),M=useCallback(()=>v("refresh"),[v]),Q=useCreateSupportTicket();return{tickets:c,counts:i,status:u,search:s,setStatus:n,setSearch:a,loading:b,refreshing:g,loadingMore:C,hasMore:q,error:x,loadMoreError:T,refresh:M,loadMore:L,createTicket:Q}};const sendThroughOutbox=async(e,t,r,o)=>{try{const u=await e.send({queue:t,label:r,request:o});return"Sent"===u.status?{status:"Sent",ticket:u.data}:"Queued"===u.status?{status:"Queued",entry:u.entry}:{status:"Failed",error:new SupportApiError(u.failure.code,u.failure.message,u.failure.status)}}catch(e){if(e instanceof Error&&"OutboxFullError"===e.name)return{status:"Failed",error:new SupportApiError("outbox_full",e.message,null)};if(e instanceof Error&&"OutboxSignedOutError"===e.name)return{status:"Failed",error:new SupportApiError("signed_out",e.message,null)};throw e}};export const useCreateSupportTicket=()=>{const{client:e,outbox:t}=useSupportContext();return useCallback(r=>sendThroughOutbox(t,SUPPORT_TICKET_QUEUE,r.subject,e.ticketRequest(r)),[e,t])};const TICKET_REFRESH_MS=3e4;export const useSupportTicket=e=>{const{client:t,outbox:r,bumpRevision:o}=useSupportContext(),[u,n]=useState(null),[s,a]=useState(!0),[c,l]=useState(null),[i,p]=useState(null),[S,f]=useState(!1),[d,E]=useState([]),b=useRef(!0),m=useRef(!1),g=useMemo(()=>supportRepliesUrl(t.basePath,e),[t,e]);useEffect(()=>{m.current=S},[S]),useEffect(()=>(b.current=!0,()=>{b.current=!1}),[]);const y=useCallback(async()=>{const e=await r.list(SUPPORT_REPLY_QUEUE);b.current&&E(e.filter(e=>e.request.url===g))},[r,g]);useEffect(()=>(y(),r.subscribe(e=>{"sent"===e.type&&e.entry.queue===SUPPORT_REPLY_QUEUE&&e.entry.request.url===g&&b.current&&n(e.data),("changed"===e.type?e.queue:e.entry.queue)===SUPPORT_REPLY_QUEUE&&y()})),[r,y,g]);const C=useCallback(async()=>{a(!0);try{const r=await t.getTicket(e);b.current&&(n(r),l(null))}catch(e){b.current&&l(toSupportApiError(e))}finally{b.current&&a(!1)}},[t,e]);useEffect(()=>{C()},[C]);const h=useCallback(async()=>{if(!m.current)try{const r=await t.getTicket(e);b.current&&n(e=>!e||Date.parse(r.updatedDateTimeUtc)>=Date.parse(e.updatedDateTimeUtc)?r:e)}catch(e){Logger.warn("[@webority/mobile-support] background refresh of the support ticket failed",e)}},[t,e]);useEffect(()=>{let e=null;const start=()=>{e??=setInterval(()=>{h()},3e4)},stop=()=>{null!==e&&(clearInterval(e),e=null)};let t="active"===AppState.currentState;t&&start();const r=AppState.addEventListener("change",e=>{const r="active"===e;r!==t&&(t=r,r?(h(),start()):stop())});return()=>{r.remove(),stop()}},[h]);const x=useCallback(async e=>{f(!0),p(null);try{const t=await e();return b.current&&n(t),o(),!0}catch(e){return b.current&&p(toSupportApiError(e)),!1}finally{b.current&&f(!1)}},[o]),k=useCallback(async o=>{f(!0),p(null);try{const u=await sendThroughOutbox(r,SUPPORT_REPLY_QUEUE,o.body.slice(0,80),t.replyRequest(e,o));return b.current&&("Sent"===u.status&&n(u.ticket),"Failed"===u.status&&p(u.error)),u.status}finally{b.current&&f(!1)}},[r,t,e]),T=useCallback(()=>x(()=>t.reopen(e)),[x,t,e]),w=useCallback(()=>x(()=>t.cancel(e)),[x,t,e]),P=useCallback(r=>x(()=>t.rate(e,r)),[x,t,e]);return{ticket:u,loading:s,error:c,actionError:i,busy:S,pendingReplies:d,reload:C,reply:k,reopen:T,cancel:w,rate:P}};export const useSupportOutbox=e=>{const{outbox:t}=useSupportContext(),[r,o]=useState([]),u=useRef(!0);useEffect(()=>(u.current=!0,()=>{u.current=!1}),[]);const n=useCallback(async()=>{const r=await t.list(e);u.current&&o(r)},[t,e]);useEffect(()=>(n(),t.subscribe(t=>{("changed"===t.type?t.queue:t.entry.queue)===e&&n()})),[t,e,n]);return{entries:r,retry:useCallback(async e=>{await t.retry(e),await n()},[t,n]),discard:useCallback(async e=>{await t.discard(e),await n()},[t,n])}};
|
|
1
|
+
"use strict";import{Logger,Storage}from"@webority/mobile-core";import{createContext,useCallback,useContext,useEffect,useMemo,useRef,useState}from"react";import{AppState}from"react-native";import{SupportApiError,supportRepliesUrl,toSupportApiError}from"./client.js";import{saveAttachmentToCache}from"./files.js";import{SUPPORT_REPLY_QUEUE,SUPPORT_TICKET_QUEUE}from"./types.js";import{jsx as _jsx}from"react/jsx-runtime";const SupportContext=createContext(null),isRecord=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),isStringArray=e=>Array.isArray(e)&&e.every(e=>"string"==typeof e),isSupportTicketDetail=e=>{if(!isRecord(e))return!1;const nullableString=e=>null===e||"string"==typeof e,nullableNumber=e=>null===e||"number"==typeof e,isLink=e=>isRecord(e)&&"string"==typeof e.id&&"string"==typeof e.number&&"string"==typeof e.subject;return"string"==typeof e.id&&"string"==typeof e.number&&"string"==typeof e.queue&&nullableNumber(e.accountId)&&nullableString(e.realm)&&"string"==typeof e.category&&"string"==typeof e.subject&&"string"==typeof e.status&&"string"==typeof e.statusLabel&&nullableString(e.priority)&&"string"==typeof e.reporterName&&(void 0===e.reporterPlace||"string"==typeof e.reporterPlace)&&"string"==typeof e.reporterEmail&&nullableNumber(e.assignedAgentUserId)&&nullableString(e.assignedAgentName)&&"boolean"==typeof e.isOverdue&&nullableString(e.pageUrl)&&nullableString(e.userAgent)&&nullableString(e.appVersion)&&nullableString(e.satisfaction)&&nullableString(e.satisfactionComment)&&"boolean"==typeof e.canReopen&&"boolean"==typeof e.canRate&&"boolean"==typeof e.canCancel&&"string"==typeof e.createdDateTimeUtc&&"string"==typeof e.updatedDateTimeUtc&&nullableString(e.resolvedDateTimeUtc)&&nullableString(e.closedDateTimeUtc)&&Array.isArray(e.messages)&&"string"==typeof e.version&&(void 0===e.mergedInto||isLink(e.mergedInto))&&(void 0===e.mergedTickets||Array.isArray(e.mergedTickets)&&e.mergedTickets.every(isLink))},parseSupportContactInfo=e=>{if(!isRecord(e))return null;const{productName:t,supportEmail:r,supportName:o,supportPhone:n,supportHours:s,categories:a,maxAttachmentBytes:u,maxAttachmentsPerMessage:c,allowedContentTypes:i,subjectMaxLength:p,bodyMaxLength:l,satisfactionCommentMaxLength:f}=e;return"string"!=typeof t||"string"!=typeof r||"string"!=typeof o||null!==n&&"string"!=typeof n||null!==s&&"string"!=typeof s||!isStringArray(a)||"number"!=typeof u||"number"!=typeof c||!isStringArray(i)||"number"!=typeof p||"number"!=typeof l||"number"!=typeof f?null:{productName:t,supportEmail:r,supportName:o,supportPhone:n,supportHours:s,categories:a,maxAttachmentBytes:u,maxAttachmentsPerMessage:c,allowedContentTypes:i,subjectMaxLength:p,bodyMaxLength:l,satisfactionCommentMaxLength:f}};export const SupportProvider=({client:e,outbox:t,openFile:r,timeZone:o,labels:n,children:s})=>{if(!t)throw new Error("[@webority/mobile-support] <SupportProvider> needs an outbox={...}, created with createOutbox from mobile-core.");const[a,u]=useState(null),[c,i]=useState(null),[p,l]=useState(!0),[f,y]=useState(0),g=useRef(new Map),d=useCallback(async()=>{l(!0);const t=`@webority/mobile-support/config:${e.basePath}`;try{const r=await e.getConfig();Storage.setItem(t,JSON.stringify(r)),u(r),i(null)}catch(e){const r=toSupportApiError(e);if(i(r),"offline"===r.code||"network"===r.code){const e=await Storage.getJson(t,parseSupportContactInfo);e&&u(e)}}finally{l(!1)}},[e]);useEffect(()=>{g.current.clear(),d()},[d]);const m=useCallback(t=>{const r=g.current.get(t.id);if(r)return r;const o=e.getAttachmentDataUri(t);return g.current.set(t.id,o),o.catch(()=>g.current.delete(t.id)),o},[e]),S=useMemo(()=>r?async t=>{const o=await saveAttachmentToCache(t,()=>e.getAttachmentBytes(t.id));await r({uri:o,name:t.fileName,contentType:t.contentType})}:null,[e,r]),b=useCallback(()=>y(e=>e+1),[]);useEffect(()=>t.subscribe(e=>{"sent"!==e.type||e.entry.queue!==SUPPORT_TICKET_QUEUE&&e.entry.queue!==SUPPORT_REPLY_QUEUE||b()}),[t,b]);const E=useMemo(()=>({client:e,outbox:t,config:a,configError:c,configLoading:p,reloadConfig:d,loadAttachment:m,openAttachment:S,timeZone:o,labels:n,revision:f,bumpRevision:b}),[e,t,a,c,p,d,m,S,o,n,f,b]);return _jsx(SupportContext.Provider,{value:E,children:s})};const useSupportContext=()=>{const e=useContext(SupportContext);if(!e)throw new Error("[@webority/mobile-support] Support screens and hooks need a <SupportProvider client={...}> above them.");return e};export const useSupportClient=()=>useSupportContext().client;export const useAttachmentLoader=()=>useSupportContext().loadAttachment;export const useAttachmentOpener=()=>useSupportContext().openAttachment;export const useSupportTimeZone=()=>useSupportContext().timeZone;export const useSupportLabels=(e,t)=>{const r=useSupportContext().labels?.[e];return useMemo(()=>r?{...t,...r}:t,[r,t])};export const useSupportConfig=()=>{const{config:e,configLoading:t,configError:r,reloadConfig:o}=useSupportContext();return{config:e,loading:t,error:r,reload:o}};const DEFAULT_PAGE_SIZE=20;export const useSupportTickets=(e={})=>{const t=e.pageSize??20,{client:r,revision:o}=useSupportContext(),[n,s]=useState(null),[a,u]=useState(""),[c,i]=useState([]),[p,l]=useState(null),[f,y]=useState(0),[g,d]=useState(0),[m,S]=useState(!0),[b,E]=useState(!1),[h,C]=useState(!1),[x,T]=useState(null),[k,A]=useState(null),w=useRef(!0),P=useRef(0),R=useRef(!1),U=useRef(null);useEffect(()=>(w.current=!0,()=>{w.current=!1}),[]);const v=useCallback(e=>({status:n??void 0,search:a.trim()||void 0,page:e,pageSize:t}),[n,a,t]),_=useCallback(async e=>{P.current+=1;const t=P.current,current=()=>w.current&&t===P.current;R.current=!1,C(!1),"refresh"===e?E(!0):"replace"===e&&(S(!0),i([]));const o="replace"!==e||U.current!==r;try{const[e,t]=await Promise.all([r.listTickets(v(1)),o?r.getTicketCounts():null]);current()&&(i(e.items),y(e.page),d(e.totalPages),t&&(l(t),U.current=r),T(null),A(null))}catch(e){current()&&T(toSupportApiError(e))}finally{current()&&(S(!1),E(!1))}},[r,v]),L=useRef(o);useEffect(()=>{const e=L.current===o?"replace":"quiet";L.current=o,_(e)},[_,o]);const O=f<g,M=useCallback(async()=>{if(R.current||m||b||!O)return;const e=P.current,current=()=>w.current&&e===P.current;R.current=!0,C(!0),A(null);try{const e=await r.listTickets(v(f+1));current()&&(i(t=>{const r=new Set(t.map(e=>e.id));return[...t,...e.items.filter(e=>!r.has(e.id))]}),y(e.page),d(e.totalPages))}catch(e){current()&&A(toSupportApiError(e))}finally{current()&&(R.current=!1,C(!1))}},[r,v,f,O,m,b]),q=useCallback(()=>_("refresh"),[_]),I=useCreateSupportTicket();return{tickets:c,counts:p,status:n,search:a,setStatus:s,setSearch:u,loading:m,refreshing:b,loadingMore:h,hasMore:O,error:x,loadMoreError:k,refresh:q,loadMore:M,createTicket:I}};const sendThroughOutbox=async(e,t,r,o)=>{try{const n=await e.send({queue:t,label:r,request:o});if("Sent"===n.status){const{data:e}=n;return isSupportTicketDetail(e)?{status:"Sent",ticket:e}:{status:"Failed",error:new SupportApiError("invalid-reply","The support desk sent a reply this app could not read. Try again.",null)}}return"Queued"===n.status?{status:"Queued",entry:n.entry}:{status:"Failed",error:new SupportApiError(n.failure.code,n.failure.message,n.failure.status)}}catch(e){if(e instanceof Error&&"OutboxFullError"===e.name)return{status:"Failed",error:new SupportApiError("outbox_full",e.message,null)};if(e instanceof Error&&"OutboxSignedOutError"===e.name)return{status:"Failed",error:new SupportApiError("signed_out",e.message,null)};throw e}};export const useCreateSupportTicket=()=>{const{client:e,outbox:t}=useSupportContext();return useCallback(r=>sendThroughOutbox(t,SUPPORT_TICKET_QUEUE,r.subject,e.ticketRequest(r)),[e,t])};const TICKET_REFRESH_MS=3e4;export const useSupportTicket=e=>{const{client:t,outbox:r,bumpRevision:o}=useSupportContext(),[n,s]=useState(null),[a,u]=useState(!0),[c,i]=useState(null),[p,l]=useState(null),[f,y]=useState(!1),[g,d]=useState([]),m=useRef(!0),S=useRef(!1),b=useMemo(()=>supportRepliesUrl(t.basePath,e),[t,e]);useEffect(()=>{S.current=f},[f]),useEffect(()=>(m.current=!0,()=>{m.current=!1}),[]);const E=useCallback(async()=>{const e=await r.list(SUPPORT_REPLY_QUEUE);m.current&&d(e.filter(e=>e.request.url===b))},[r,b]),h=useCallback(async()=>{u(!0);try{const r=await t.getTicket(e);m.current&&(s(r),i(null))}catch(e){m.current&&i(toSupportApiError(e))}finally{m.current&&u(!1)}},[t,e]);useEffect(()=>{h()},[h]);const C=useCallback(async()=>{if(!S.current)try{const r=await t.getTicket(e);m.current&&s(e=>!e||Date.parse(r.updatedDateTimeUtc)>=Date.parse(e.updatedDateTimeUtc)?r:e)}catch(e){Logger.warn("[@webority/mobile-support] background refresh of the support ticket failed",e)}},[t,e]);useEffect(()=>(E(),r.subscribe(e=>{"sent"===e.type&&e.entry.queue===SUPPORT_REPLY_QUEUE&&e.entry.request.url===b&&m.current&&(isSupportTicketDetail(e.data)?s(e.data):(Logger.warn("[mobile-support] an outbox reply was not a ticket; refreshing"),C())),("changed"===e.type?e.queue:e.entry.queue)===SUPPORT_REPLY_QUEUE&&E()})),[r,E,C,b]),useEffect(()=>{let e=null;const start=()=>{e??=setInterval(()=>{C()},3e4)},stop=()=>{null!==e&&(clearInterval(e),e=null)};let t="active"===AppState.currentState;t&&start();const r=AppState.addEventListener("change",e=>{const r="active"===e;r!==t&&(t=r,r?(C(),start()):stop())});return()=>{r.remove(),stop()}},[C]);const x=useCallback(async e=>{y(!0),l(null);try{const t=await e();return m.current&&s(t),o(),!0}catch(e){return m.current&&l(toSupportApiError(e)),!1}finally{m.current&&y(!1)}},[o]),T=useCallback(async o=>{y(!0),l(null);try{const n=await sendThroughOutbox(r,SUPPORT_REPLY_QUEUE,o.body.slice(0,80),t.replyRequest(e,o));return m.current&&("Sent"===n.status&&s(n.ticket),"Failed"===n.status&&l(n.error)),n.status}finally{m.current&&y(!1)}},[r,t,e]),k=useCallback(()=>x(()=>t.reopen(e)),[x,t,e]),A=useCallback(()=>x(()=>t.cancel(e)),[x,t,e]),w=useCallback(r=>x(()=>t.rate(e,r)),[x,t,e]);return{ticket:n,loading:a,error:c,actionError:p,busy:f,pendingReplies:g,reload:h,reply:T,reopen:k,cancel:A,rate:w}};export const useSupportOutbox=e=>{const{outbox:t}=useSupportContext(),[r,o]=useState([]),n=useRef(!0);useEffect(()=>(n.current=!0,()=>{n.current=!1}),[]);const s=useCallback(async()=>{const r=await t.list(e);n.current&&o(r)},[t,e]);useEffect(()=>(s(),t.subscribe(t=>{("changed"===t.type?t.queue:t.entry.queue)===e&&s()})),[t,e,s]);return{entries:r,retry:useCallback(async e=>{await t.retry(e),await s()},[t,s]),discard:useCallback(async e=>{await t.discard(e),await s()},[t,s])}};
|
package/lib/module/client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import{encodeBase64,newIdempotencyKey}from"@webority/mobile-core";export const OFFLINE_MESSAGE="You are offline. Check your connection and try again.";export const GENERIC_MESSAGE="Something went wrong. Try again in a moment.";export class SupportApiError extends Error{constructor(e,t,n){super(t),this.name="SupportApiError",this.code=e,this.status=n}}export const toSupportApiError=e=>{if(e instanceof SupportApiError)return e;const t=e??{};if("RequestOfflineError"===t.name)return new SupportApiError("offline",OFFLINE_MESSAGE,null);const n="number"==typeof t.response?.status?t.response.status:null,r=t.response?.data,o="string"==typeof r?.code?r.code:"unknown";return r&&"string"==typeof r.detail&&r.detail.trim()?new SupportApiError(o,r.detail,n):t.response?new SupportApiError(o,GENERIC_MESSAGE,n):new SupportApiError("network",OFFLINE_MESSAGE,null)};const UPLOAD_TIMEOUT_MS=3e5,textFields=(e,t)=>void 0!==t&&""!==t?[{name:e,value:t}]:[],fileFields=(e,t)=>(t??[]).map(t=>({name:e,file:{uri:t.uri,name:t.name,type:t.type}})),multipartRequest=(e,t)=>({method:"POST",url:e,headers:{"Content-Type":"multipart/form-data","Idempotency-Key":newIdempotencyKey()},body:{kind:"multipart",fields:t},timeoutMs:3e5});export const supportRepliesUrl=(e,t)=>`${e}/tickets/${encodeURIComponent(t)}/replies`;const queryString=e=>{const t=[],add=(e,n)=>{void 0!==n&&""!==n&&t.push(`${e}=${encodeURIComponent(String(n))}`)};return add("status",e.status),add("search",e.search?.trim()),add("queue",e.queue?.trim()),add("page",e.page),add("pageSize",e.pageSize),t.length>0?`?${t.join("&")}`:""};export const createSupportClient=(e,t="/api/support",n)=>{const r=t.replace(/\/+$/,""),ticketUrl=e=>`${r}/tickets/${encodeURIComponent(e)}`,call=async e=>{try{return(await e()).data}catch(e){throw toSupportApiError(e)}},getBytes=t=>call(()=>e.get(`${r}/attachments/${encodeURIComponent(t)}`,{responseType:"arraybuffer"})),o=n?.replace(/\/+$/,"");return{basePath:r,helpCentre:void 0===o?void 0:{settings:t=>call(()=>e.get(`${o}/settings`,{signal:t?.signal})),list:(t={},n)=>call(()=>e.get(`${o}/articles${queryString(t)}`,{signal:n?.signal})),get:(t,n)=>call(()=>e.get(`${o}/articles/${encodeURIComponent(t)}`,{signal:n?.signal})),search:(t,n)=>call(()=>e.get(`${o}/search?q=${encodeURIComponent(t)}`,{signal:n?.signal}))},getConfig:()=>call(()=>e.get(`${r}/settings`)),listTickets:(t={})=>call(()=>e.get(`${r}/tickets${queryString(t)}`)),getTicketCounts:()=>call(()=>e.get(`${r}/tickets/counts`)),getTicket:t=>call(()=>e.get(ticketUrl(t))),ticketRequest:e=>multipartRequest(`${r}/tickets`,[{name:"category",value:e.category},{name:"subject",value:e.subject},{name:"body",value:e.body},...textFields("pageUrl",e.pageUrl),...textFields("userAgent",e.userAgent),...textFields("appVersion",e.appVersion),...fileFields("files",e.files),...fileFields("screenshots",e.screenshots)]),getSuggestions:t=>call(()=>e.get(`${r}/suggestions?subject=${encodeURIComponent(t)}`)),replyRequest:(e,t)=>multipartRequest(supportRepliesUrl(r,e),[{name:"body",value:t.body},...fileFields("files",t.files),...fileFields("screenshots",t.screenshots)]),reopen:t=>call(()=>e.post(`${ticketUrl(t)}/reopen`)),cancel:t=>call(()=>e.post(`${ticketUrl(t)}/cancel`)),rate:(t,n)=>call(()=>e.post(`${ticketUrl(t)}/rating`,{satisfaction:n.satisfaction,comment:n.comment?.trim()?n.comment.trim():null})),getAttachmentBytes:getBytes,getAttachmentDataUri:async e=>{const t=await getBytes(e.id);return`data:${e.contentType};base64,${encodeBase64(t)}`},confirmAction:t=>call(()=>e.post(`${r}/actions/confirm`,{token:t}))}};
|
|
1
|
+
"use strict";import{encodeBase64,newIdempotencyKey}from"@webority/mobile-core";const isJsonObject=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),reject=(e,t)=>{throw new Error(`${e} must be ${t}`)},readObject=(e,t)=>isJsonObject(e)?e:reject(t,"an object"),readString=(e,t,r)=>{const a=e[t];return"string"==typeof a?a:reject(`${r}.${t}`,"a string")},readNumber=(e,t,r)=>{const a=e[t];return"number"==typeof a&&Number.isFinite(a)?a:reject(`${r}.${t}`,"a number")},readBoolean=(e,t,r)=>{const a=e[t];return"boolean"==typeof a?a:reject(`${r}.${t}`,"true or false")},readNullable=(e,t,r,a)=>null===e[t]?null:a(e,t,r),readOptional=(e,t,r,a)=>void 0===e[t]?void 0:a(e,t,r),oneOf=e=>(t,r,a)=>{const n=readString(t,r,a);return e.find(e=>e===n)??reject(`${a}.${r}`,`one of ${e.join(", ")}`)},nested=e=>(t,r,a)=>e(t[r],`${a}.${r}`),parseList=(e,t,r)=>Array.isArray(e)?e.map((e,a)=>r(e,`${t}[${a}]`)):reject(t,"a list"),readList=(e,t,r,a)=>parseList(e[t],`${r}.${t}`,a),parseText=(e,t)=>"string"==typeof e?e:reject(t,"a string"),readStrings=(e,t,r)=>readList(e,t,r,parseText),readTicketStatus=oneOf(["Open","InProgress","WaitingOnCustomer","Resolved","Closed","Cancelled"]),readPriority=oneOf(["Low","Normal","High","Urgent"]),readSatisfaction=oneOf(["Satisfied","Unsatisfied"]),readAuthorKind=oneOf(["Customer","Agent","System","Assistant"]),readAttachmentKind=oneOf(["Screenshot","File"]),parseSupportContactInfo=(e,t="SupportContactInfo")=>{const r=readObject(e,t);return{productName:readString(r,"productName",t),supportEmail:readString(r,"supportEmail",t),supportName:readString(r,"supportName",t),supportPhone:readNullable(r,"supportPhone",t,readString),supportHours:readNullable(r,"supportHours",t,readString),categories:readStrings(r,"categories",t),maxAttachmentBytes:readNumber(r,"maxAttachmentBytes",t),maxAttachmentsPerMessage:readNumber(r,"maxAttachmentsPerMessage",t),allowedContentTypes:readStrings(r,"allowedContentTypes",t),subjectMaxLength:readNumber(r,"subjectMaxLength",t),bodyMaxLength:readNumber(r,"bodyMaxLength",t),satisfactionCommentMaxLength:readNumber(r,"satisfactionCommentMaxLength",t)}},parseSupportTicketSummary=(e,t="SupportTicketSummary")=>{const r=readObject(e,t);return{id:readString(r,"id",t),number:readString(r,"number",t),category:readString(r,"category",t),subject:readString(r,"subject",t),status:readTicketStatus(r,"status",t),statusLabel:readString(r,"statusLabel",t),messageCount:readNumber(r,"messageCount",t),awaitingCustomer:readBoolean(r,"awaitingCustomer",t),queue:readString(r,"queue",t),createdDateTimeUtc:readString(r,"createdDateTimeUtc",t),updatedDateTimeUtc:readString(r,"updatedDateTimeUtc",t)}},parseSupportAttachmentView=(e,t="SupportAttachmentView")=>{const r=readObject(e,t);return{id:readString(r,"id",t),fileName:readString(r,"fileName",t),contentType:readString(r,"contentType",t),sizeBytes:readNumber(r,"sizeBytes",t),kind:readAttachmentKind(r,"kind",t)}},parseSupportMessageView=(e,t="SupportMessageView")=>{const r=readObject(e,t);return{id:readString(r,"id",t),authorKind:readAuthorKind(r,"authorKind",t),authorName:readNullable(r,"authorName",t,readString),body:readString(r,"body",t),isInternal:readBoolean(r,"isInternal",t),createdDateTimeUtc:readString(r,"createdDateTimeUtc",t),attachments:readList(r,"attachments",t,parseSupportAttachmentView)}},parseSupportTicketLink=(e,t="SupportTicketLink")=>{const r=readObject(e,t);return{id:readString(r,"id",t),number:readString(r,"number",t),subject:readString(r,"subject",t)}},parseSupportTicketDetail=(e,t="SupportTicketDetail")=>{const r=readObject(e,t);return{id:readString(r,"id",t),number:readString(r,"number",t),queue:readString(r,"queue",t),accountId:readNullable(r,"accountId",t,readNumber),realm:readNullable(r,"realm",t,readString),category:readString(r,"category",t),subject:readString(r,"subject",t),status:readTicketStatus(r,"status",t),statusLabel:readString(r,"statusLabel",t),priority:readNullable(r,"priority",t,readPriority),reporterName:readString(r,"reporterName",t),reporterPlace:readOptional(r,"reporterPlace",t,readString),reporterEmail:readString(r,"reporterEmail",t),assignedAgentUserId:readNullable(r,"assignedAgentUserId",t,readNumber),assignedAgentName:readNullable(r,"assignedAgentName",t,readString),isOverdue:readBoolean(r,"isOverdue",t),pageUrl:readNullable(r,"pageUrl",t,readString),userAgent:readNullable(r,"userAgent",t,readString),appVersion:readNullable(r,"appVersion",t,readString),satisfaction:readNullable(r,"satisfaction",t,readSatisfaction),satisfactionComment:readNullable(r,"satisfactionComment",t,readString),canReopen:readBoolean(r,"canReopen",t),canRate:readBoolean(r,"canRate",t),canCancel:readBoolean(r,"canCancel",t),createdDateTimeUtc:readString(r,"createdDateTimeUtc",t),updatedDateTimeUtc:readString(r,"updatedDateTimeUtc",t),resolvedDateTimeUtc:readNullable(r,"resolvedDateTimeUtc",t,readString),closedDateTimeUtc:readNullable(r,"closedDateTimeUtc",t,readString),messages:readList(r,"messages",t,parseSupportMessageView),version:readString(r,"version",t),mergedInto:readOptional(r,"mergedInto",t,nested(parseSupportTicketLink)),mergedTickets:readOptional(r,"mergedTickets",t,(e,t,r)=>readList(e,t,r,parseSupportTicketLink))}},parseSupportPage=(e,t)=>(r,a=t)=>{const n=readObject(r,a);return{items:readList(n,"items",a,e),page:readNumber(n,"page",a),pageSize:readNumber(n,"pageSize",a),totalCount:readNumber(n,"totalCount",a),totalPages:readNumber(n,"totalPages",a)}},parseSupportTicketPage=parseSupportPage(parseSupportTicketSummary,"SupportPage<SupportTicketSummary>"),parseSupportTicketCounts=(e,t="SupportTicketCounts")=>{const r=readObject(e,t);return{open:readNumber(r,"open",t),needsReply:readNumber(r,"needsReply",t),resolved:readNumber(r,"resolved",t),withdrawn:readNumber(r,"withdrawn",t),total:readNumber(r,"total",t),oldestAwaitingAgentDateTimeUtc:readNullable(r,"oldestAwaitingAgentDateTimeUtc",t,readString)}},parseSupportSuggestedArticle=(e,t="SupportSuggestedArticle")=>{const r=readObject(e,t);return{title:readString(r,"title",t),summary:readString(r,"summary",t)}},parseSupportSuggestedArticles=(e,t="SupportSuggestedArticle[]")=>parseList(e,t,parseSupportSuggestedArticle),parseHelpCentreSettings=(e,t="HelpCentreSettings")=>{const r=readObject(e,t);return{publicUrl:readString(r,"publicUrl",t),searchAvailable:readBoolean(r,"searchAvailable",t)}},parseHelpArticleSummary=(e,t="HelpArticleSummary")=>{const r=readObject(e,t);return{id:readString(r,"id",t),slug:readString(r,"slug",t),title:readString(r,"title",t),summary:readString(r,"summary",t),publishedDateTimeUtc:readNullable(r,"publishedDateTimeUtc",t,readString),updatedDateTimeUtc:readString(r,"updatedDateTimeUtc",t)}},parseHelpArticlePage=parseSupportPage(parseHelpArticleSummary,"SupportPage<HelpArticleSummary>"),parseHelpArticleView=(e,t="HelpArticleView")=>{const r=readObject(e,t);return{...parseHelpArticleSummary(r,t),bodyMarkdown:readString(r,"bodyMarkdown",t)}},parseHelpArticleSummaries=(e,t="HelpArticleSummary[]")=>parseList(e,t,parseHelpArticleSummary),parseArrayBuffer=(e,t="ArrayBuffer")=>e instanceof ArrayBuffer?e:reject(t,"the attachment bytes");export const OFFLINE_MESSAGE="You are offline. Check your connection and try again.";export const GENERIC_MESSAGE="Something went wrong. Try again in a moment.";export class SupportApiError extends Error{constructor(e,t,r){super(t),this.name="SupportApiError",this.code=e,this.status=r}}export const toSupportApiError=e=>{if(e instanceof SupportApiError)return e;const t="object"==typeof e&&null!==e?e:{};if("RequestOfflineError"===t.name)return new SupportApiError("offline",OFFLINE_MESSAGE,null);const r="number"==typeof t.response?.status?t.response.status:null,a=t.response?.data,n="object"==typeof a&&null!==a?a:void 0,s="string"==typeof n?.code?n.code:"unknown";return n&&"string"==typeof n.detail&&n.detail.trim()?new SupportApiError(s,n.detail,r):t.response?new SupportApiError(s,GENERIC_MESSAGE,r):new SupportApiError("network",OFFLINE_MESSAGE,null)};const UPLOAD_TIMEOUT_MS=3e5,textFields=(e,t)=>void 0!==t&&""!==t?[{name:e,value:t}]:[],fileFields=(e,t)=>(t??[]).map(t=>({name:e,file:{uri:t.uri,name:t.name,type:t.type}})),multipartRequest=(e,t)=>({method:"POST",url:e,headers:{"Content-Type":"multipart/form-data","Idempotency-Key":newIdempotencyKey()},body:{kind:"multipart",fields:t},timeoutMs:3e5});export const supportRepliesUrl=(e,t)=>`${e}/tickets/${encodeURIComponent(t)}/replies`;const queryString=e=>{const t=[],add=(e,r)=>{void 0!==r&&""!==r&&t.push(`${e}=${encodeURIComponent(String(r))}`)};return add("status",e.status),add("search",e.search?.trim()),add("queue",e.queue?.trim()),add("page",e.page),add("pageSize",e.pageSize),t.length>0?`?${t.join("&")}`:""};export const createSupportClient=(e,t="/api/support",r)=>{const a=t.replace(/\/+$/,""),ticketUrl=e=>`${a}/tickets/${encodeURIComponent(e)}`,call=async(e,t,r)=>{let a;try{a=(await t()).data}catch(e){throw toSupportApiError(e)}try{return r(a)}catch(t){throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`,{cause:t})}},getBytes=t=>call("GET /attachments/{id}",()=>e.get(`${a}/attachments/${encodeURIComponent(t)}`,{responseType:"arraybuffer"}),parseArrayBuffer),n=r?.replace(/\/+$/,"");return{basePath:a,helpCentre:void 0===n?void 0:{settings:t=>call("GET help /settings",()=>e.get(`${n}/settings`,{signal:t?.signal}),parseHelpCentreSettings),list:(t={},r)=>call("GET help /articles",()=>e.get(`${n}/articles${queryString(t)}`,{signal:r?.signal}),parseHelpArticlePage),get:(t,r)=>call("GET help /articles/{slug}",()=>e.get(`${n}/articles/${encodeURIComponent(t)}`,{signal:r?.signal}),parseHelpArticleView),search:(t,r)=>call("GET help /search",()=>e.get(`${n}/search?q=${encodeURIComponent(t)}`,{signal:r?.signal}),parseHelpArticleSummaries)},getConfig:()=>call("GET /settings",()=>e.get(`${a}/settings`),parseSupportContactInfo),listTickets:(t={})=>call("GET /tickets",()=>e.get(`${a}/tickets${queryString(t)}`),parseSupportTicketPage),getTicketCounts:()=>call("GET /tickets/counts",()=>e.get(`${a}/tickets/counts`),parseSupportTicketCounts),getTicket:t=>call("GET /tickets/{id}",()=>e.get(ticketUrl(t)),parseSupportTicketDetail),ticketRequest:e=>multipartRequest(`${a}/tickets`,[{name:"category",value:e.category},{name:"subject",value:e.subject},{name:"body",value:e.body},...textFields("pageUrl",e.pageUrl),...textFields("userAgent",e.userAgent),...textFields("appVersion",e.appVersion),...fileFields("files",e.files),...fileFields("screenshots",e.screenshots)]),getSuggestions:t=>call("GET /suggestions",()=>e.get(`${a}/suggestions?subject=${encodeURIComponent(t)}`),parseSupportSuggestedArticles),replyRequest:(e,t)=>multipartRequest(supportRepliesUrl(a,e),[{name:"body",value:t.body},...fileFields("files",t.files),...fileFields("screenshots",t.screenshots)]),reopen:t=>call("POST /tickets/{id}/reopen",()=>e.post(`${ticketUrl(t)}/reopen`),parseSupportTicketDetail),cancel:t=>call("POST /tickets/{id}/cancel",()=>e.post(`${ticketUrl(t)}/cancel`),parseSupportTicketDetail),rate:(t,r)=>call("POST /tickets/{id}/rating",()=>e.post(`${ticketUrl(t)}/rating`,{satisfaction:r.satisfaction,comment:r.comment?.trim()?r.comment.trim():null}),parseSupportTicketDetail),getAttachmentBytes:getBytes,getAttachmentDataUri:async e=>{const t=await getBytes(e.id);return`data:${e.contentType};base64,${encodeBase64(t)}`}}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import{formatDateTime}from"@webority/mobile-core";import{Button,Card,Composer,confirm,Descriptions,Dialog,IconButton,Input,KeyboardAwareScrollView,Spinner,StatusBadge,Text,useTheme}from"@webority/mobile-ui";import{useMemo,useState}from"react";import{StyleSheet,View}from"react-native";import{fillLabel,SHARED_LABELS}from"../labels.js";import{useSupportConfig,useSupportLabels,useSupportOutbox,useSupportTicket,useSupportTimeZone}from"../SupportProvider.js";import{SUPPORT_REPLY_QUEUE}from"../types.js";import{validateBody,validateFiles}from"../validation.js";import{AttachmentList,ImageViewer}from"./Attachments.js";import{PhotoTray}from"./PhotoTray.js";import{STATUS_TONES}from"./SupportTicketList.js";import{jsx as _jsx,jsxs as _jsxs,Fragment as _Fragment}from"react/jsx-runtime";const LABELS={sendNow:"Send now",discard:"Discard",loading:"Loading the ticket",retry:"Try again",replyReopens:"Replying reopens this ticket.",opened:"Opened {date}",updated:"Updated {date}",merged:"This ticket was merged into {number}. The conversation carries on there.",openMerged:"Open {number}",resolvedNote:"This ticket is {status}. Reopen it if you still need help.",reopen:"Reopen ticket",withdraw:"Withdraw request",withdrawTitle:"Withdraw this request?",withdrawMessage:"Our team will stop working on this ticket. You can open a new ticket later if you still need help.",withdrawConfirm:"Withdraw request",withdrawCancel:"Keep request",yourComment:"Your comment: {comment}",solved:"Yes, it is solved",notSolved:"No, it is not",commentLabel:"Anything to add? (optional)",commentHelper:"Your comment goes to the support team.",sendAnswer:"Send answer",conversation:"Conversation",mergedBadge:"Merged into this ticket",replyPlaceholder:"Write a reply to the support team",replyLabel:"Your reply",attachPhoto:"Attach a photo",sendReply:"Send reply",you:"You",writeMessage:"Write a message.",supportTeam:"Support team",replyFailed:"Your reply did not send. Please try again.",waitingToSend:"Waiting to send",notFound:"That ticket could not be found.",discardTitle:"Discard this report?",discardMessage:"It has not been sent.",statusAccessibility:"Status: {label}",waitingText:"We need your answer to carry on. Reply below and the ticket goes back to our team.",satisfied:"You told us this solved your problem.",unsatisfied:"You told us this did not solve your problem.",ratingQuestion:"Did this solve your problem?",detailsTitle:"Ticket details",detailStatus:"Status",detailCategory:"Category",detailTicket:"Ticket",detailOpened:"Opened",detailLastUpdate:"Last update"},MessageBubble=({message:e,styles:t,timeZone:s,labels:a,onOpenImage:i})=>{if("System"===e.authorKind)return _jsx(View,{style:t.system,testID:`support-message-${e.id}`,children:_jsx(Text,{variant:"caption",color:"tertiary",align:"center",children:`${e.body}, ${formatDateTime(e.createdDateTimeUtc,{zone:s})}`})});const n="Customer"===e.authorKind;return _jsx(View,{style:[t.bubbleRow,n?t.mineRow:t.theirsRow],testID:`support-message-${e.id}`,children:_jsxs(View,{style:[t.bubble,n?t.mine:t.theirs],children:[_jsx(Text,{variant:"label",color:n?"primary":"secondary",children:e.authorName??(n?a.you:a.supportTeam)}),_jsx(Text,{variant:"body",selectable:!0,children:e.body}),_jsx(AttachmentList,{attachments:e.attachments,onOpenImage:i}),_jsx(Text,{variant:"caption",color:"tertiary",children:formatDateTime(e.createdDateTimeUtc,{zone:s})})]})})},pendingReplyBody=e=>{const{body:t}=e.request;if("json"===t.kind){const e=t.value;return"string"==typeof e?.body?e.body:""}const s=t.fields.find(e=>"body"===e.name);return s&&"value"in s?s.value:""},PendingReplyBubble=({entry:e,styles:t,labels:s,onSendNow:a,onDiscard:i})=>{const n="Failed"===e.state;return _jsx(View,{style:[t.bubbleRow,t.mineRow],testID:`support-pending-${e.id}`,children:_jsxs(View,{style:[t.bubble,t.mine],children:[_jsx(Text,{variant:"label",color:"primary",children:s.you}),_jsx(Text,{variant:"body",selectable:!0,children:pendingReplyBody(e)}),_jsx(Text,{variant:"caption",color:n?"danger":"tertiary",accessibilityLiveRegion:"polite",children:n?s.replyFailed:s.waitingToSend}),_jsxs(View,{style:t.ratingRow,children:[_jsx(Button,{label:s.sendNow,size:"sm",variant:"outline",onPress:()=>a(e.id),testID:`support-pending-send-${e.id}`}),_jsx(Button,{label:s.discard,size:"sm",variant:"ghost",onPress:()=>i(e.id),testID:`support-pending-discard-${e.id}`})]})]})})};export const SupportTicketDetail=({ticketId:e,onOpenTicket:t,testID:s="support-ticket-detail"})=>{const a=useSupportLabels("ticketDetail",LABELS),i=useSupportLabels("shared",SHARED_LABELS),n=useTheme(),o=useMemo(()=>buildStyles(n),[n]),{config:r}=useSupportConfig(),l=useSupportTimeZone(),{ticket:d,loading:c,error:p,actionError:u,busy:m,pendingReplies:b,reload:y,reply:g,reopen:h,cancel:x,rate:S}=useSupportTicket(e),w=useSupportOutbox(SUPPORT_REPLY_QUEUE),[T,j]=useState(null),[f,_]=useState(""),[v,D]=useState([]),[L,R]=useState(!1),[I,C]=useState(null),[k,B]=useState(null),[P,U]=useState(""),[A,V]=useState(!1);if(!d)return _jsx(View,{style:o.center,testID:s,children:c?_jsx(Spinner,{accessibilityLabel:a.loading}):_jsxs(_Fragment,{children:[_jsx(Text,{variant:"body",color:"danger",align:"center",children:p?.message??a.notFound}),_jsx(Button,{label:a.retry,variant:"ghost",onPress:()=>{y()}})]})});const O={Satisfied:a.satisfied,Unsatisfied:a.unsatisfied},z=d.mergedInto,E=d.messages.filter(e=>!e.isInternal),M=d.updatedDateTimeUtc!==d.createdDateTimeUtc,$=I??u?.message??null,F=Boolean(r)&&(L||v.length>0),N=F||$||d.canReopen?_jsxs(_Fragment,{children:[F&&r&&_jsx(PhotoTray,{photos:v,onChange:e=>{D(e),C(null)},remaining:r.maxAttachmentsPerMessage-v.length,maxBytes:r.maxAttachmentBytes,disabled:m}),$&&_jsx(Text,{variant:"bodySmall",color:"danger",accessibilityLiveRegion:"polite",children:$}),d.canReopen&&_jsx(Text,{variant:"caption",color:"secondary",children:a.replyReopens})]}):void 0;return _jsxs(View,{style:o.root,testID:s,children:[_jsxs(KeyboardAwareScrollView,{contentContainerStyle:o.content,safeAreaEdges:[],children:[_jsxs(View,{style:o.head,children:[_jsx(Text,{variant:"h3",accessibilityRole:"header",children:d.subject}),_jsx(Text,{variant:"bodySmall",color:"secondary",children:`${d.number}, ${d.category}`}),_jsxs(View,{style:o.headRow,children:[_jsx(StatusBadge,{label:d.statusLabel,tone:STATUS_TONES[d.status]??"neutral",accessibilityLabel:fillLabel(a.statusAccessibility,{label:d.statusLabel})}),_jsx(Text,{variant:"caption",color:"tertiary",children:fillLabel(a.opened,{date:formatDateTime(d.createdDateTimeUtc,{zone:l})})}),M&&_jsx(Text,{variant:"caption",color:"tertiary",children:fillLabel(a.updated,{date:formatDateTime(d.updatedDateTimeUtc,{zone:l})})})]})]}),z&&_jsxs(Card,{variant:"outline",bodyStyle:o.section,testID:"support-merged-into",children:[_jsx(Text,{variant:"bodySmall",accessibilityLiveRegion:"polite",children:fillLabel(a.merged,{number:z.number})}),t&&_jsx(Button,{label:fillLabel(a.openMerged,{number:z.number}),variant:"link",size:"sm",onPress:()=>t(z.id),testID:"support-merged-into-open"})]}),"WaitingOnCustomer"===d.status&&_jsx(Card,{variant:"outline",bodyStyle:o.section,testID:"support-waiting",children:_jsx(Text,{variant:"bodySmall",children:a.waitingText})}),d.canReopen&&_jsxs(Card,{variant:"outline",bodyStyle:o.section,children:[_jsx(Text,{variant:"bodySmall",children:fillLabel(a.resolvedNote,{status:d.statusLabel.toLowerCase()})}),_jsx(Button,{label:a.reopen,variant:"outline",size:"sm",loading:m,disabled:m,onPress:()=>{h()},testID:"support-reopen"})]}),d.canCancel&&_jsxs(Card,{variant:"outline",bodyStyle:o.section,children:[_jsx(Button,{label:a.withdraw,variant:"outline",size:"sm",loading:m,disabled:m,onPress:()=>V(!0),testID:"support-withdraw"}),_jsx(Dialog,{open:A,onClose:()=>V(!1),title:a.withdrawTitle,message:a.withdrawMessage,tone:"danger",actions:[{label:a.withdrawCancel,onPress:()=>V(!1),tone:"neutral"},{label:a.withdrawConfirm,onPress:()=>{x()},tone:"danger"}]})]}),d.satisfaction?_jsxs(Card,{variant:"outline",bodyStyle:o.section,testID:"support-rating",children:[_jsx(Text,{variant:"bodySmall",accessibilityLiveRegion:"polite",children:O[d.satisfaction]}),d.satisfactionComment?_jsx(Text,{variant:"bodySmall",color:"secondary",children:fillLabel(a.yourComment,{comment:d.satisfactionComment})}):null]}):d.canRate?_jsxs(Card,{variant:"outline",bodyStyle:o.section,testID:"support-rating",children:[_jsx(Text,{variant:"label",children:a.ratingQuestion}),_jsxs(View,{style:o.ratingRow,children:[_jsx(Button,{label:a.solved,size:"sm",leftIcon:"like",variant:"Satisfied"===k?"solid":"outline",tone:"success",accessibilityState:{selected:"Satisfied"===k},"aria-selected":"Satisfied"===k,onPress:()=>B("Satisfied"),testID:"support-rate-satisfied"}),_jsx(Button,{label:a.notSolved,size:"sm",leftIcon:"dislike",variant:"Unsatisfied"===k?"solid":"outline",tone:"danger",accessibilityState:{selected:"Unsatisfied"===k},"aria-selected":"Unsatisfied"===k,onPress:()=>B("Unsatisfied"),testID:"support-rate-unsatisfied"})]}),k&&_jsxs(_Fragment,{children:[_jsx(Input,{label:a.commentLabel,helperText:a.commentHelper,value:P,onChangeText:U,multiline:!0,maxLength:r?.satisfactionCommentMaxLength,testID:"support-rating-comment"}),_jsx(Button,{label:a.sendAnswer,size:"sm",loading:m,disabled:m,onPress:()=>{(async()=>{k&&await S({satisfaction:k,comment:P})&&(B(null),U(""))})()},testID:"support-rating-send"})]})]}):null,_jsxs(View,{style:o.thread,accessibilityLabel:a.conversation,children:[E.map(e=>_jsx(MessageBubble,{message:e,styles:o,timeZone:l,labels:a,onOpenImage:(e,t)=>j({uri:e,name:t})},e.id)),b.map(e=>_jsx(PendingReplyBubble,{entry:e,styles:o,labels:a,onSendNow:e=>{w.retry(e)},onDiscard:e=>{(async e=>{await confirm({title:a.discardTitle,message:a.discardMessage,confirmLabel:a.discard,tone:"danger"})&&await w.discard(e)})(e)}},e.id))]}),d.mergedTickets&&d.mergedTickets.length>0&&_jsxs(View,{style:o.section,testID:"support-merged-tickets",children:[_jsx(Text,{variant:"label",accessibilityRole:"header",children:a.mergedBadge}),d.mergedTickets.map(e=>t?_jsx(Button,{label:`${e.number}: ${e.subject}`,variant:"link",size:"sm",onPress:()=>t(e.id),testID:`support-merged-ticket-${e.id}`},e.id):_jsx(Text,{variant:"bodySmall",testID:`support-merged-ticket-${e.id}`,children:`${e.number}: ${e.subject}`},e.id))]}),_jsxs(Card,{variant:"outline",bodyStyle:o.section,testID:"support-details",accessibilityRole:"summary",children:[_jsx(Text,{variant:"label",children:a.detailsTitle}),_jsx(Descriptions,{items:[{label:a.detailStatus,value:_jsx(StatusBadge,{label:d.statusLabel,tone:STATUS_TONES[d.status]??"neutral",accessibilityLabel:fillLabel(a.statusAccessibility,{label:d.statusLabel})})},{label:a.detailCategory,value:d.category||"-"},{label:a.detailTicket,value:d.number},{label:a.detailOpened,value:formatDateTime(d.createdDateTimeUtc,{zone:l})},{label:a.detailLastUpdate,value:formatDateTime(d.updatedDateTimeUtc,{zone:l})}]})]})]}),!z&&_jsx(Composer,{value:f,onChangeText:e=>{_(e),C(null)},onSend:e=>{(async e=>{const t=e.trim(),s=r?validateBody(t,r,i)??validateFiles(v,r,i):t?void 0:a.writeMessage;if(s)return C(s),void _(e);"Failed"!==await g({body:t,files:v})?(D([]),R(!1)):_(e)})(e)},loading:m,maxLength:r?.bodyMaxLength,placeholder:a.replyPlaceholder,accessibilityLabel:a.replyLabel,labels:{send:a.sendReply,message:a.replyLabel},leading:_jsx(IconButton,{icon:"paperclip",size:"md",accessibilityLabel:a.attachPhoto,disabled:m||!r,onPress:()=>R(e=>!e),testID:"support-reply-attach"}),above:N,testID:"support-reply-composer"}),_jsx(ImageViewer,{image:T,onClose:()=>j(null)})]})};const buildStyles=e=>StyleSheet.create({root:{flex:1},content:{padding:e.space.md,gap:e.space.md},center:{flex:1,alignItems:"center",justifyContent:"center",padding:e.space.xl,gap:e.space.sm},head:{gap:e.space.xxs},headRow:{flexDirection:"row",alignItems:"center",gap:e.space.sm,marginTop:e.space.xs},section:{gap:e.space.sm},ratingRow:{flexDirection:"row",flexWrap:"wrap",gap:e.space.sm},thread:{gap:e.space.sm},system:{paddingHorizontal:e.space.lg,paddingVertical:e.space.xxs},bubbleRow:{flexDirection:"row"},mineRow:{justifyContent:"flex-end"},theirsRow:{justifyContent:"flex-start"},bubble:{maxWidth:"85%",borderRadius:e.radius.lg,padding:e.space.sm,gap:e.space.xxs},mine:{backgroundColor:e.colors["primary-soft"]},theirs:{backgroundColor:e.colors["bg-subtle"]}});
|
|
1
|
+
"use strict";import{formatDateTime}from"@webority/mobile-core";import{Button,Card,Composer,confirm,Descriptions,Dialog,IconButton,Input,KeyboardAwareScrollView,Spinner,StatusBadge,Text,useTheme}from"@webority/mobile-ui";import{useMemo,useState}from"react";import{StyleSheet,View}from"react-native";import{fillLabel,SHARED_LABELS}from"../labels.js";import{useSupportConfig,useSupportLabels,useSupportOutbox,useSupportTicket,useSupportTimeZone}from"../SupportProvider.js";import{SUPPORT_REPLY_QUEUE}from"../types.js";import{validateBody,validateFiles}from"../validation.js";import{AttachmentList,ImageViewer}from"./Attachments.js";import{PhotoTray}from"./PhotoTray.js";import{STATUS_TONES}from"./SupportTicketList.js";import{jsx as _jsx,jsxs as _jsxs,Fragment as _Fragment}from"react/jsx-runtime";const LABELS={sendNow:"Send now",discard:"Discard",loading:"Loading the ticket",retry:"Try again",replyReopens:"Replying reopens this ticket.",opened:"Opened {date}",updated:"Updated {date}",merged:"This ticket was merged into {number}. The conversation carries on there.",openMerged:"Open {number}",resolvedNote:"This ticket is {status}. Reopen it if you still need help.",reopen:"Reopen ticket",withdraw:"Withdraw request",withdrawTitle:"Withdraw this request?",withdrawMessage:"Our team will stop working on this ticket. You can open a new ticket later if you still need help.",withdrawConfirm:"Withdraw request",withdrawCancel:"Keep request",yourComment:"Your comment: {comment}",solved:"Yes, it is solved",notSolved:"No, it is not",commentLabel:"Anything to add? (optional)",commentHelper:"Your comment goes to the support team.",sendAnswer:"Send answer",conversation:"Conversation",mergedBadge:"Merged into this ticket",replyPlaceholder:"Write a reply to the support team",replyLabel:"Your reply",attachPhoto:"Attach a photo",sendReply:"Send reply",you:"You",writeMessage:"Write a message.",supportTeam:"Support team",replyFailed:"Your reply did not send. Please try again.",waitingToSend:"Waiting to send",notFound:"That ticket could not be found.",discardTitle:"Discard this report?",discardMessage:"It has not been sent.",statusAccessibility:"Status: {label}",waitingText:"We need your answer to carry on. Reply below and the ticket goes back to our team.",satisfied:"You told us this solved your problem.",unsatisfied:"You told us this did not solve your problem.",ratingQuestion:"Did this solve your problem?",detailsTitle:"Ticket details",detailStatus:"Status",detailCategory:"Category",detailTicket:"Ticket",detailOpened:"Opened",detailLastUpdate:"Last update"},MessageBubble=({message:e,styles:t,timeZone:s,labels:a,onOpenImage:i})=>{if("System"===e.authorKind)return _jsx(View,{style:t.system,testID:`support-message-${e.id}`,children:_jsx(Text,{variant:"caption",color:"tertiary",align:"center",children:`${e.body}, ${formatDateTime(e.createdDateTimeUtc,{zone:s})}`})});const n="Customer"===e.authorKind;return _jsx(View,{style:[t.bubbleRow,n?t.mineRow:t.theirsRow],testID:`support-message-${e.id}`,children:_jsxs(View,{style:[t.bubble,n?t.mine:t.theirs],children:[_jsx(Text,{variant:"label",color:n?"primary":"secondary",children:e.authorName??(n?a.you:a.supportTeam)}),_jsx(Text,{variant:"body",selectable:!0,children:e.body}),_jsx(AttachmentList,{attachments:e.attachments,onOpenImage:i}),_jsx(Text,{variant:"caption",color:"tertiary",children:formatDateTime(e.createdDateTimeUtc,{zone:s})})]})})},pendingReplyBody=e=>{const{body:t}=e.request;if("json"===t.kind){const e=t.value;return"object"==typeof e&&null!==e&&"body"in e&&"string"==typeof e.body?e.body:""}const s=t.fields.find(e=>"body"===e.name);return s&&"value"in s?s.value:""},PendingReplyBubble=({entry:e,styles:t,labels:s,onSendNow:a,onDiscard:i})=>{const n="Failed"===e.state;return _jsx(View,{style:[t.bubbleRow,t.mineRow],testID:`support-pending-${e.id}`,children:_jsxs(View,{style:[t.bubble,t.mine],children:[_jsx(Text,{variant:"label",color:"primary",children:s.you}),_jsx(Text,{variant:"body",selectable:!0,children:pendingReplyBody(e)}),_jsx(Text,{variant:"caption",color:n?"danger":"tertiary",accessibilityLiveRegion:"polite",children:n?s.replyFailed:s.waitingToSend}),_jsxs(View,{style:t.ratingRow,children:[_jsx(Button,{label:s.sendNow,size:"sm",variant:"outline",onPress:()=>a(e.id),testID:`support-pending-send-${e.id}`}),_jsx(Button,{label:s.discard,size:"sm",variant:"ghost",onPress:()=>i(e.id),testID:`support-pending-discard-${e.id}`})]})]})})};export const SupportTicketDetail=({ticketId:e,onOpenTicket:t,testID:s="support-ticket-detail"})=>{const a=useSupportLabels("ticketDetail",LABELS),i=useSupportLabels("shared",SHARED_LABELS),n=useTheme(),o=useMemo(()=>buildStyles(n),[n]),{config:r}=useSupportConfig(),l=useSupportTimeZone(),{ticket:d,loading:c,error:p,actionError:u,busy:m,pendingReplies:b,reload:y,reply:g,reopen:h,cancel:x,rate:S}=useSupportTicket(e),j=useSupportOutbox(SUPPORT_REPLY_QUEUE),[w,T]=useState(null),[f,_]=useState(""),[v,D]=useState([]),[L,R]=useState(!1),[I,C]=useState(null),[k,B]=useState(null),[P,U]=useState(""),[A,V]=useState(!1);if(!d)return _jsx(View,{style:o.center,testID:s,children:c?_jsx(Spinner,{accessibilityLabel:a.loading}):_jsxs(_Fragment,{children:[_jsx(Text,{variant:"body",color:"danger",align:"center",children:p?.message??a.notFound}),_jsx(Button,{label:a.retry,variant:"ghost",onPress:()=>{y()}})]})});const O={Satisfied:a.satisfied,Unsatisfied:a.unsatisfied},z=d.mergedInto,E=d.messages.filter(e=>!e.isInternal),M=d.updatedDateTimeUtc!==d.createdDateTimeUtc,$=I??u?.message??null,F=Boolean(r)&&(L||v.length>0),N=F||$||d.canReopen?_jsxs(_Fragment,{children:[F&&r&&_jsx(PhotoTray,{photos:v,onChange:e=>{D(e),C(null)},remaining:r.maxAttachmentsPerMessage-v.length,maxBytes:r.maxAttachmentBytes,disabled:m}),$&&_jsx(Text,{variant:"bodySmall",color:"danger",accessibilityLiveRegion:"polite",children:$}),d.canReopen&&_jsx(Text,{variant:"caption",color:"secondary",children:a.replyReopens})]}):void 0;return _jsxs(View,{style:o.root,testID:s,children:[_jsxs(KeyboardAwareScrollView,{contentContainerStyle:o.content,safeAreaEdges:[],children:[_jsxs(View,{style:o.head,children:[_jsx(Text,{variant:"h3",accessibilityRole:"header",children:d.subject}),_jsx(Text,{variant:"bodySmall",color:"secondary",children:`${d.number}, ${d.category}`}),_jsxs(View,{style:o.headRow,children:[_jsx(StatusBadge,{label:d.statusLabel,tone:STATUS_TONES[d.status]??"neutral",accessibilityLabel:fillLabel(a.statusAccessibility,{label:d.statusLabel})}),_jsx(Text,{variant:"caption",color:"tertiary",children:fillLabel(a.opened,{date:formatDateTime(d.createdDateTimeUtc,{zone:l})})}),M&&_jsx(Text,{variant:"caption",color:"tertiary",children:fillLabel(a.updated,{date:formatDateTime(d.updatedDateTimeUtc,{zone:l})})})]})]}),z&&_jsxs(Card,{variant:"outline",bodyStyle:o.section,testID:"support-merged-into",children:[_jsx(Text,{variant:"bodySmall",accessibilityLiveRegion:"polite",children:fillLabel(a.merged,{number:z.number})}),t&&_jsx(Button,{label:fillLabel(a.openMerged,{number:z.number}),variant:"link",size:"sm",onPress:()=>t(z.id),testID:"support-merged-into-open"})]}),"WaitingOnCustomer"===d.status&&_jsx(Card,{variant:"outline",bodyStyle:o.section,testID:"support-waiting",children:_jsx(Text,{variant:"bodySmall",children:a.waitingText})}),d.canReopen&&_jsxs(Card,{variant:"outline",bodyStyle:o.section,children:[_jsx(Text,{variant:"bodySmall",children:fillLabel(a.resolvedNote,{status:d.statusLabel.toLowerCase()})}),_jsx(Button,{label:a.reopen,variant:"outline",size:"sm",loading:m,disabled:m,onPress:()=>{h()},testID:"support-reopen"})]}),d.canCancel&&_jsxs(Card,{variant:"outline",bodyStyle:o.section,children:[_jsx(Button,{label:a.withdraw,variant:"outline",size:"sm",loading:m,disabled:m,onPress:()=>V(!0),testID:"support-withdraw"}),_jsx(Dialog,{open:A,onClose:()=>V(!1),title:a.withdrawTitle,message:a.withdrawMessage,tone:"danger",actions:[{label:a.withdrawCancel,onPress:()=>V(!1),tone:"neutral"},{label:a.withdrawConfirm,onPress:()=>{x()},tone:"danger"}]})]}),d.satisfaction?_jsxs(Card,{variant:"outline",bodyStyle:o.section,testID:"support-rating",children:[_jsx(Text,{variant:"bodySmall",accessibilityLiveRegion:"polite",children:O[d.satisfaction]}),d.satisfactionComment?_jsx(Text,{variant:"bodySmall",color:"secondary",children:fillLabel(a.yourComment,{comment:d.satisfactionComment})}):null]}):d.canRate?_jsxs(Card,{variant:"outline",bodyStyle:o.section,testID:"support-rating",children:[_jsx(Text,{variant:"label",children:a.ratingQuestion}),_jsxs(View,{style:o.ratingRow,children:[_jsx(Button,{label:a.solved,size:"sm",leftIcon:"like",variant:"Satisfied"===k?"solid":"outline",tone:"success",accessibilityState:{selected:"Satisfied"===k},"aria-selected":"Satisfied"===k,onPress:()=>B("Satisfied"),testID:"support-rate-satisfied"}),_jsx(Button,{label:a.notSolved,size:"sm",leftIcon:"dislike",variant:"Unsatisfied"===k?"solid":"outline",tone:"danger",accessibilityState:{selected:"Unsatisfied"===k},"aria-selected":"Unsatisfied"===k,onPress:()=>B("Unsatisfied"),testID:"support-rate-unsatisfied"})]}),k&&_jsxs(_Fragment,{children:[_jsx(Input,{label:a.commentLabel,helperText:a.commentHelper,value:P,onChangeText:U,multiline:!0,maxLength:r?.satisfactionCommentMaxLength,testID:"support-rating-comment"}),_jsx(Button,{label:a.sendAnswer,size:"sm",loading:m,disabled:m,onPress:()=>{(async()=>{k&&await S({satisfaction:k,comment:P})&&(B(null),U(""))})()},testID:"support-rating-send"})]})]}):null,_jsxs(View,{style:o.thread,accessibilityLabel:a.conversation,children:[E.map(e=>_jsx(MessageBubble,{message:e,styles:o,timeZone:l,labels:a,onOpenImage:(e,t)=>T({uri:e,name:t})},e.id)),b.map(e=>_jsx(PendingReplyBubble,{entry:e,styles:o,labels:a,onSendNow:e=>{j.retry(e)},onDiscard:e=>{(async e=>{await confirm({title:a.discardTitle,message:a.discardMessage,confirmLabel:a.discard,tone:"danger"})&&await j.discard(e)})(e)}},e.id))]}),d.mergedTickets&&d.mergedTickets.length>0&&_jsxs(View,{style:o.section,testID:"support-merged-tickets",children:[_jsx(Text,{variant:"label",accessibilityRole:"header",children:a.mergedBadge}),d.mergedTickets.map(e=>t?_jsx(Button,{label:`${e.number}: ${e.subject}`,variant:"link",size:"sm",onPress:()=>t(e.id),testID:`support-merged-ticket-${e.id}`},e.id):_jsx(Text,{variant:"bodySmall",testID:`support-merged-ticket-${e.id}`,children:`${e.number}: ${e.subject}`},e.id))]}),_jsxs(Card,{variant:"outline",bodyStyle:o.section,testID:"support-details",accessibilityRole:"summary",children:[_jsx(Text,{variant:"label",children:a.detailsTitle}),_jsx(Descriptions,{items:[{label:a.detailStatus,value:_jsx(StatusBadge,{label:d.statusLabel,tone:STATUS_TONES[d.status]??"neutral",accessibilityLabel:fillLabel(a.statusAccessibility,{label:d.statusLabel})})},{label:a.detailCategory,value:d.category||"-"},{label:a.detailTicket,value:d.number},{label:a.detailOpened,value:formatDateTime(d.createdDateTimeUtc,{zone:l})},{label:a.detailLastUpdate,value:formatDateTime(d.updatedDateTimeUtc,{zone:l})}]})]})]}),!z&&_jsx(Composer,{value:f,onChangeText:e=>{_(e),C(null)},onSend:e=>{(async e=>{const t=e.trim(),s=r?validateBody(t,r,i)??validateFiles(v,r,i):t?void 0:a.writeMessage;if(s)return C(s),void _(e);"Failed"!==await g({body:t,files:v})?(D([]),R(!1)):_(e)})(e)},loading:m,maxLength:r?.bodyMaxLength,placeholder:a.replyPlaceholder,accessibilityLabel:a.replyLabel,labels:{send:a.sendReply,message:a.replyLabel},leading:_jsx(IconButton,{icon:"paperclip",size:"md",accessibilityLabel:a.attachPhoto,disabled:m||!r,onPress:()=>R(e=>!e),testID:"support-reply-attach"}),above:N,testID:"support-reply-composer"}),_jsx(ImageViewer,{image:w,onClose:()=>T(null)})]})};const buildStyles=e=>StyleSheet.create({root:{flex:1},content:{padding:e.space.md,gap:e.space.md},center:{flex:1,alignItems:"center",justifyContent:"center",padding:e.space.xl,gap:e.space.sm},head:{gap:e.space.xxs},headRow:{flexDirection:"row",alignItems:"center",gap:e.space.sm,marginTop:e.space.xs},section:{gap:e.space.sm},ratingRow:{flexDirection:"row",flexWrap:"wrap",gap:e.space.sm},thread:{gap:e.space.sm},system:{paddingHorizontal:e.space.lg,paddingVertical:e.space.xxs},bubbleRow:{flexDirection:"row"},mineRow:{justifyContent:"flex-end"},theirsRow:{justifyContent:"flex-start"},bubble:{maxWidth:"85%",borderRadius:e.radius.lg,padding:e.space.sm,gap:e.space.xxs},mine:{backgroundColor:e.colors["primary-soft"]},theirs:{backgroundColor:e.colors["bg-subtle"]}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import{shareFile}from"@webority/mobile-core/share";export class SupportShareUnavailableError extends Error{constructor(){super("Opening files is not available on this device."),this.name="SupportShareUnavailableError"}}export const shareSupportFile=async
|
|
1
|
+
"use strict";import{shareFile}from"@webority/mobile-core/share";export class SupportShareUnavailableError extends Error{constructor(){super("Opening files is not available on this device."),this.name="SupportShareUnavailableError"}}function isShareUnavailable(e){return"object"==typeof e&&null!==e&&"name"in e&&"code"in e&&"ShareError"===e.name&&"unavailable"===e.code}export const shareSupportFile=async e=>{try{await shareFile(e.uri,{mimeType:e.contentType,dialogTitle:e.name})}catch(e){if(isShareUnavailable(e))throw new SupportShareUnavailableError;throw e}};
|
|
@@ -14,11 +14,11 @@ export interface SupportHttpRequestConfig {
|
|
|
14
14
|
signal?: AbortSignal;
|
|
15
15
|
}
|
|
16
16
|
export interface SupportHttpClient {
|
|
17
|
-
get
|
|
18
|
-
data:
|
|
17
|
+
get(url: string, config?: SupportHttpRequestConfig): Promise<{
|
|
18
|
+
data: unknown;
|
|
19
19
|
}>;
|
|
20
|
-
post
|
|
21
|
-
data:
|
|
20
|
+
post(url: string, body?: unknown, config?: SupportHttpRequestConfig): Promise<{
|
|
21
|
+
data: unknown;
|
|
22
22
|
}>;
|
|
23
23
|
}
|
|
24
24
|
export declare const OFFLINE_MESSAGE = "You are offline. Check your connection and try again.";
|
|
@@ -78,12 +78,6 @@ export interface SupportClient {
|
|
|
78
78
|
* the same authenticated client as every other call.
|
|
79
79
|
*/
|
|
80
80
|
getAttachmentDataUri(attachment: Pick<SupportAttachmentView, "id" | "contentType">): Promise<string>;
|
|
81
|
-
/**
|
|
82
|
-
* The person's yes to a support action an assistant prepared (raise a ticket, reply on
|
|
83
|
-
* one, reopen one). Only this call completes it. Resolves to the ticket it acted on; an
|
|
84
|
-
* expired or unknown token rejects with the code `action_expired`.
|
|
85
|
-
*/
|
|
86
|
-
confirmAction(token: string): Promise<SupportTicketDetail>;
|
|
87
81
|
}
|
|
88
82
|
export declare const createSupportClient: (http: SupportHttpClient, basePath?: string, helpCentreBaseUrl?: string) => SupportClient;
|
|
89
83
|
//# sourceMappingURL=client.d.ts.map
|
|
@@ -14,11 +14,11 @@ export interface SupportHttpRequestConfig {
|
|
|
14
14
|
signal?: AbortSignal;
|
|
15
15
|
}
|
|
16
16
|
export interface SupportHttpClient {
|
|
17
|
-
get
|
|
18
|
-
data:
|
|
17
|
+
get(url: string, config?: SupportHttpRequestConfig): Promise<{
|
|
18
|
+
data: unknown;
|
|
19
19
|
}>;
|
|
20
|
-
post
|
|
21
|
-
data:
|
|
20
|
+
post(url: string, body?: unknown, config?: SupportHttpRequestConfig): Promise<{
|
|
21
|
+
data: unknown;
|
|
22
22
|
}>;
|
|
23
23
|
}
|
|
24
24
|
export declare const OFFLINE_MESSAGE = "You are offline. Check your connection and try again.";
|
|
@@ -78,12 +78,6 @@ export interface SupportClient {
|
|
|
78
78
|
* the same authenticated client as every other call.
|
|
79
79
|
*/
|
|
80
80
|
getAttachmentDataUri(attachment: Pick<SupportAttachmentView, "id" | "contentType">): Promise<string>;
|
|
81
|
-
/**
|
|
82
|
-
* The person's yes to a support action an assistant prepared (raise a ticket, reply on
|
|
83
|
-
* one, reopen one). Only this call completes it. Resolves to the ticket it acted on; an
|
|
84
|
-
* expired or unknown token rejects with the code `action_expired`.
|
|
85
|
-
*/
|
|
86
|
-
confirmAction(token: string): Promise<SupportTicketDetail>;
|
|
87
81
|
}
|
|
88
82
|
export declare const createSupportClient: (http: SupportHttpClient, basePath?: string, helpCentreBaseUrl?: string) => SupportClient;
|
|
89
83
|
//# sourceMappingURL=client.d.ts.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webority/mobile-support",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.150.0",
|
|
4
4
|
"description": "Customer support tickets for Webority React Native apps: the support API client, hooks, ticket screens, contact card and a report-an-issue button that attaches a screenshot.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"react-native",
|
|
@@ -62,8 +62,8 @@
|
|
|
62
62
|
"!**/*.map"
|
|
63
63
|
],
|
|
64
64
|
"peerDependencies": {
|
|
65
|
-
"@webority/mobile-core": "0.
|
|
66
|
-
"@webority/mobile-ui": "0.
|
|
65
|
+
"@webority/mobile-core": "0.150.0",
|
|
66
|
+
"@webority/mobile-ui": "0.150.0",
|
|
67
67
|
"expo": ">=58.0.0",
|
|
68
68
|
"expo-file-system": ">=58.0.0",
|
|
69
69
|
"expo-image-manipulator": ">=58.0.0",
|
|
@@ -73,7 +73,7 @@
|
|
|
73
73
|
"react": "^19.3.0",
|
|
74
74
|
"react-hook-form": "^7.55.0",
|
|
75
75
|
"react-native": ">=0.88.0",
|
|
76
|
-
"react-native-gesture-handler": "^
|
|
76
|
+
"react-native-gesture-handler": "^3.3.0",
|
|
77
77
|
"react-native-view-shot": ">=4.0.0"
|
|
78
78
|
},
|
|
79
79
|
"peerDependenciesMeta": {
|
|
@@ -124,9 +124,9 @@
|
|
|
124
124
|
"@react-native/metro-config": "0.88.1",
|
|
125
125
|
"@testing-library/react-native": "12.9.0",
|
|
126
126
|
"@types/react": "19.3.0",
|
|
127
|
-
"@webority/mobile-core": "0.
|
|
127
|
+
"@webority/mobile-core": "0.150.0",
|
|
128
128
|
"@webority/mobile-dev": "0.0.0",
|
|
129
|
-
"@webority/mobile-ui": "0.
|
|
129
|
+
"@webority/mobile-ui": "0.150.0",
|
|
130
130
|
"expo": "58.0.23",
|
|
131
131
|
"expo-file-system": "58.0.13",
|
|
132
132
|
"expo-image-manipulator": "58.0.16",
|
|
@@ -137,7 +137,7 @@
|
|
|
137
137
|
"react-native-builder-bob": "0.43.0",
|
|
138
138
|
"react-native-gesture-handler": "3.3.0",
|
|
139
139
|
"react-test-renderer": "19.3.0",
|
|
140
|
-
"typescript": "
|
|
140
|
+
"typescript": "7.0.2"
|
|
141
141
|
},
|
|
142
142
|
"scripts": {
|
|
143
143
|
"build": "bob build && node ../mobile-dev/scripts/minify-lib.mjs",
|