@webority/mobile-support 0.171.3 → 0.172.1

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 CHANGED
@@ -114,7 +114,7 @@ const NewSupportTicketScreen = ({ navigation, route }) => (
114
114
  - **NewSupportTicket**: category, subject, message and photos, checked against the limits the
115
115
  product sends in `GET /settings` before anything is uploaded. `defaultCategory` preselects a
116
116
  category the product lists (a draft's own category wins; one the product does not list starts
117
- unselected). The category list is the one `categories` list in `GET /settings`; the screen never
117
+ unselected). The category list is the `categories` in `GET /settings` whose `queue` is the form's `queue` prop (every category when no prop is given); the screen never
118
118
  asks for a desk and sends none. `appVersion` is recorded when the draft carries none, and the device
119
119
  line (`describeDevice()`) is recorded on every ticket. Once the subject has three characters and the
120
120
  person pauses, suggested answers from `GET {prefix}/suggestions?subject=` appear under the subject
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.useSupportUploadProgress=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"),_outbox=require("@webority/mobile-core/outbox"),_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),changedQueue=e=>{switch(e.type){case"changed":return e.queue;case"sent":case"failed":return e.entry.queue;case"progress":return null;default:return e}},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:u,maxAttachmentBytes:n,maxAttachmentsPerMessage:c,allowedContentTypes:p,subjectMaxLength:i,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(u)||"number"!=typeof n||"number"!=typeof c||!isStringArray(p)||"number"!=typeof i||"number"!=typeof l||"number"!=typeof f?null:{productName:t,supportEmail:r,supportName:o,supportPhone:s,supportHours:a,categories:u,maxAttachmentBytes:n,maxAttachmentsPerMessage:c,allowedContentTypes:p,subjectMaxLength:i,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[u,n]=(0,_react.useState)(null),[c,p]=(0,_react.useState)(null),[i,l]=(0,_react.useState)(!0),[f,S]=(0,_react.useState)(0),_=(0,_react.useRef)(new Map),y=(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)),n(r),p(null)}catch(e){const r=(0,_client.toSupportApiError)(e);if(p(r),"offline"===r.code||"network"===r.code){const e=await _mobileCore.Storage.getJson(t,parseSupportContactInfo);e&&n(e)}}finally{l(!1)}},[e]);(0,_react.useEffect)(()=>{_.current.clear(),y()},[y]);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]),b=(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||b()}),[t,b]);const m=(0,_react.useMemo)(()=>({client:e,outbox:t,config:u,configError:c,configLoading:i,reloadConfig:y,loadAttachment:d,openAttachment:g,timeZone:o,labels:s,revision:f,bumpRevision:b}),[e,t,u,c,i,y,d,g,o,s,f,b]);return(0,_jsxRuntime.jsx)(SupportContext.Provider,{value:m,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),[u,n]=(0,_react.useState)(""),[c,p]=(0,_react.useState)([]),[i,l]=(0,_react.useState)(null),[f,S]=(0,_react.useState)(0),[_,y]=(0,_react.useState)(0),[d,g]=(0,_react.useState)(!0),[b,m]=(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),P=(0,_react.useRef)(0),w=(0,_react.useRef)(!1),R=(0,_react.useRef)(null);(0,_react.useEffect)(()=>(A.current=!0,()=>{A.current=!1}),[]);const v=(0,_react.useCallback)(e=>{const r=u.trim();return{...s?{status:s}:{},...r?{search:r}:{},page:e,pageSize:t}},[s,u,t]),U=(0,_react.useCallback)(async e=>{P.current+=1;const t=P.current,current=()=>A.current&&t===P.current;w.current=!1,h(!1),"refresh"===e?m(!0):"replace"===e&&(g(!0),p([]));const o="replace"!==e||R.current!==r;try{const[e,t]=await Promise.all([r.listTickets(v(1)),o?r.getTicketCounts():null]);current()&&(p(e.items),S(e.page),y(e.totalPages),t&&(l(t),R.current=r),E(null),k(null))}catch(e){current()&&E((0,_client.toSupportApiError)(e))}finally{current()&&(g(!1),m(!1))}},[r,v]),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(w.current||d||b||!O)return;const e=P.current,current=()=>A.current&&e===P.current;w.current=!0,h(!0),k(null);try{const e=await r.listTickets(v(f+1));current()&&(p(t=>{const r=new Set(t.map(e=>e.id));return[...t,...e.items.filter(e=>!r.has(e.id))]}),S(e.page),y(e.totalPages))}catch(e){current()&&k((0,_client.toSupportApiError)(e))}finally{current()&&(w.current=!1,h(!1))}},[r,v,f,O,d,b]),M=(0,_react.useCallback)(()=>U("refresh"),[U]),j=useCreateSupportTicket();return{tickets:c,counts:i,status:s,search:u,setStatus:a,setSearch:n,loading:d,refreshing:b,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 useSupportUploadProgress=e=>(0,_outbox.useOutboxProgress)(useSupportContext().outbox,e);exports.useSupportUploadProgress=useSupportUploadProgress;const TICKET_REFRESH_MS=3e4,useSupportTicket=e=>{const{client:t,outbox:r,bumpRevision:o}=useSupportContext(),[s,a]=(0,_react.useState)(null),[u,n]=(0,_react.useState)(!0),[c,p]=(0,_react.useState)(null),[i,l]=(0,_react.useState)(null),[f,S]=(0,_react.useState)(!1),[_,y]=(0,_react.useState)([]),d=(0,_react.useRef)(!0),g=(0,_react.useRef)(!1),b=(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 m=(0,_react.useCallback)(async()=>{const e=await r.list(_types.SUPPORT_REPLY_QUEUE);d.current&&y(e.filter(e=>e.request.url===b))},[r,b]),x=(0,_react.useCallback)(async()=>{n(!0);try{const r=await t.getTicket(e);d.current&&(a(r),p(null))}catch(e){d.current&&p((0,_client.toSupportApiError)(e))}finally{d.current&&n(!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)(()=>(m(),r.subscribe(e=>{"sent"===e.type&&e.entry.queue===_types.SUPPORT_REPLY_QUEUE&&e.entry.request.url===b&&d.current&&(isSupportTicketDetail(e.data)?a(e.data):(_mobileCore.Logger.warn("[mobile-support] an outbox reply was not a ticket; refreshing"),h())),changedQueue(e)===_types.SUPPORT_REPLY_QUEUE&&m()})),[r,m,h,b]),(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=>{S(!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&&S(!1)}},[o]),E=(0,_react.useCallback)(async o=>{S(!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&&S(!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:u,error:c,actionError:i,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=>{changedQueue(t)===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;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.useSupportUploadProgress=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"),_outbox=require("@webority/mobile-core/outbox"),_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),changedQueue=e=>{switch(e.type){case"changed":return e.queue;case"sent":case"failed":return e.entry.queue;case"progress":return null;default:return e}},isRecord=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),isStringArray=e=>Array.isArray(e)&&e.every(e=>"string"==typeof e),isCategoryArray=e=>Array.isArray(e)&&e.every(e=>isRecord(e)&&"string"==typeof e.name&&"string"==typeof e.queue),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:u,categories:a,maxAttachmentBytes:n,maxAttachmentsPerMessage:c,allowedContentTypes:p,subjectMaxLength:i,bodyMaxLength:l,satisfactionCommentMaxLength:f}=e;return"string"!=typeof t||"string"!=typeof r||"string"!=typeof o||null!==s&&"string"!=typeof s||null!==u&&"string"!=typeof u||!isCategoryArray(a)||"number"!=typeof n||"number"!=typeof c||!isStringArray(p)||"number"!=typeof i||"number"!=typeof l||"number"!=typeof f?null:{productName:t,supportEmail:r,supportName:o,supportPhone:s,supportHours:u,categories:a,maxAttachmentBytes:n,maxAttachmentsPerMessage:c,allowedContentTypes:p,subjectMaxLength:i,bodyMaxLength:l,satisfactionCommentMaxLength:f}},SupportProvider=({client:e,outbox:t,openFile:r,timeZone:o,labels:s,children:u})=>{if(!t)throw new Error("[@webority/mobile-support] <SupportProvider> needs an outbox={...}, created with createOutbox from mobile-core.");const[a,n]=(0,_react.useState)(null),[c,p]=(0,_react.useState)(null),[i,l]=(0,_react.useState)(!0),[f,y]=(0,_react.useState)(0),S=(0,_react.useRef)(new Map),g=(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)),n(r),p(null)}catch(e){const r=(0,_client.toSupportApiError)(e);if(p(r),"offline"===r.code||"network"===r.code){const e=await _mobileCore.Storage.getJson(t,parseSupportContactInfo);e&&n(e)}}finally{l(!1)}},[e]);(0,_react.useEffect)(()=>{S.current.clear(),g()},[g]);const _=(0,_react.useCallback)(t=>{const r=S.current.get(t.id);if(void 0!==r)return r;const o=e.getAttachmentDataUri(t);return S.current.set(t.id,o),o.catch(()=>S.current.delete(t.id)),o},[e]),d=(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:a,configError:c,configLoading:i,reloadConfig:g,loadAttachment:_,openAttachment:d,timeZone:o,labels:s,revision:f,bumpRevision:m}),[e,t,a,c,i,g,_,d,o,s,f,m]);return(0,_jsxRuntime.jsx)(SupportContext.Provider,{value:b,children:u})};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,u]=(0,_react.useState)(null),[a,n]=(0,_react.useState)(""),[c,p]=(0,_react.useState)([]),[i,l]=(0,_react.useState)(null),[f,y]=(0,_react.useState)(0),[S,g]=(0,_react.useState)(0),[_,d]=(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),P=(0,_react.useRef)(0),v=(0,_react.useRef)(!1),w=(0,_react.useRef)(null);(0,_react.useEffect)(()=>(A.current=!0,()=>{A.current=!1}),[]);const R=(0,_react.useCallback)(e=>{const r=a.trim();return{...s?{status:s}:{},...r?{search:r}:{},page:e,pageSize:t}},[s,a,t]),U=(0,_react.useCallback)(async e=>{P.current+=1;const t=P.current,current=()=>A.current&&t===P.current;v.current=!1,h(!1),"refresh"===e?b(!0):"replace"===e&&(d(!0),p([]));const o="replace"!==e||w.current!==r;try{const[e,t]=await Promise.all([r.listTickets(R(1)),o?r.getTicketCounts():null]);current()&&(p(e.items),y(e.page),g(e.totalPages),t&&(l(t),w.current=r),E(null),k(null))}catch(e){current()&&E((0,_client.toSupportApiError)(e))}finally{current()&&(d(!1),b(!1))}},[r,R]),O=(0,_react.useRef)(o);(0,_react.useEffect)(()=>{const e=O.current===o?"replace":"quiet";O.current=o,U(e)},[U,o]);const L=f<S,q=(0,_react.useCallback)(async()=>{if(v.current||_||m||!L)return;const e=P.current,current=()=>A.current&&e===P.current;v.current=!0,h(!0),k(null);try{const e=await r.listTickets(R(f+1));current()&&(p(t=>{const r=new Set(t.map(e=>e.id));return[...t,...e.items.filter(e=>!r.has(e.id))]}),y(e.page),g(e.totalPages))}catch(e){current()&&k((0,_client.toSupportApiError)(e))}finally{current()&&(v.current=!1,h(!1))}},[r,R,f,L,_,m]),M=(0,_react.useCallback)(()=>U("refresh"),[U]),j=useCreateSupportTicket();return{tickets:c,counts:i,status:s,search:a,setStatus:u,setSearch:n,loading:_,refreshing:m,loadingMore:x,hasMore:L,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 useSupportUploadProgress=e=>(0,_outbox.useOutboxProgress)(useSupportContext().outbox,e);exports.useSupportUploadProgress=useSupportUploadProgress;const TICKET_REFRESH_MS=3e4,useSupportTicket=e=>{const{client:t,outbox:r,bumpRevision:o}=useSupportContext(),[s,u]=(0,_react.useState)(null),[a,n]=(0,_react.useState)(!0),[c,p]=(0,_react.useState)(null),[i,l]=(0,_react.useState)(null),[f,y]=(0,_react.useState)(!1),[S,g]=(0,_react.useState)([]),_=(0,_react.useRef)(!0),d=(0,_react.useRef)(!1),m=(0,_react.useMemo)(()=>(0,_client.supportRepliesUrl)(t.basePath,e),[t,e]);(0,_react.useEffect)(()=>{d.current=f},[f]),(0,_react.useEffect)(()=>(_.current=!0,()=>{_.current=!1}),[]);const b=(0,_react.useCallback)(async()=>{const e=await r.list(_types.SUPPORT_REPLY_QUEUE);_.current&&g(e.filter(e=>e.request.url===m))},[r,m]),x=(0,_react.useCallback)(async()=>{n(!0);try{const r=await t.getTicket(e);_.current&&(u(r),p(null))}catch(e){_.current&&p((0,_client.toSupportApiError)(e))}finally{_.current&&n(!1)}},[t,e]);(0,_react.useEffect)(()=>{x()},[x]);const h=(0,_react.useCallback)(async()=>{if(!d.current)try{const r=await t.getTicket(e);_.current&&u(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&&_.current&&(isSupportTicketDetail(e.data)?u(e.data):(_mobileCore.Logger.warn("[mobile-support] an outbox reply was not a ticket; refreshing"),h())),changedQueue(e)===_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 _.current&&u(t),o(),!0}catch(e){return _.current&&l((0,_client.toSupportApiError)(e)),!1}finally{_.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 _.current&&("Sent"===s.status&&u(s.ticket),"Failed"===s.status&&l(s.error)),s.status}finally{_.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:a,error:c,actionError:i,busy:f,pendingReplies:S,reload:x,reply:E,reopen:T,cancel:k,rate:A}};exports.useSupportTicket=useSupportTicket;const useSupportOutbox=e=>(0,_outbox.useOutboxEntries)(useSupportContext().outbox,e);exports.useSupportOutbox=useSupportOutbox;
@@ -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 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("queue",e.queue),...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
+ "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"]),parseCategory=(e,t)=>{const r=readObject(e,t);return{name:readString(r,"name",t),queue:readString(r,"queue",t)}},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:readList(r,"categories",t,parseCategory),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("queue",e.queue),...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.NewSupportTicket=void 0;var _mobileCore=require("@webority/mobile-core"),_mobileUi=require("@webority/mobile-ui"),_react=require("react"),_reactHookForm=require("react-hook-form"),_reactNative=require("react-native"),_client=require("../client.js"),_device=require("../device.js"),_labels=require("../labels.js"),_SupportProvider=require("../SupportProvider.js"),_subject=require("../subject.js"),_types=require("../types.js"),_validation=require("../validation.js"),_PhotoTray=require("./PhotoTray.js"),_SuggestedAnswers=require("./SuggestedAnswers.js"),_SupportUploadProgress=require("./SupportUploadProgress.js"),_jsxRuntime=require("react/jsx-runtime");const LABELS={intro:"Tell us what you need. We reply by email and in this ticket.",messageLabel:"Message",messagePlaceholder:"What happened, and what did you expect?",subjectLabel:"Subject",subjectPlaceholder:"A short summary",subjectHelper:"Filled in from your message. You can change it.",categoryLabel:"Category (optional)",categoryPlaceholder:"Choose a category",categoryHelper:"Not sure? Leave it empty and we will sort it.",screenshotLabel:"Screenshot",photosLabel:"Photos",photoLimit:"Add up to {count} photos.",cancel:"Cancel",send:"Send ticket",loading:"Loading",retry:"Try again",unavailable:"Support is not available right now."},SUGGESTION_PAUSE_MS=500,SUGGESTION_MIN_CHARS=3,TicketForm=({config:e,styles:t,onCreated:r,onQueued:o,onCancel:s,initialDraft:a,defaultCategory:i,appVersion:n,queue:l})=>{const u=(0,_SupportProvider.useSupportLabels)("newTicket",LABELS),c=(0,_SupportProvider.useSupportLabels)("shared",_labels.SHARED_LABELS),d=(0,_SupportProvider.useCreateSupportTicket)(),p=(0,_SupportProvider.useSupportClient)(),{isConnected:b,isInternetReachable:m}=(0,_mobileCore.useNetworkStatus)(),g=!b||!1===m,[_,j]=(0,_react.useState)([]),listed=t=>t&&e.categories.includes(t)?t:void 0,[h,x]=(0,_react.useState)([]),[y,S]=(0,_react.useState)(a?.screenshots??[]),[v,L]=(0,_react.useState)(null),[P,w]=(0,_react.useState)(null),T=(0,_react.useRef)(Boolean(a?.subject?.trim())&&a?.subject!==(0,_subject.subjectFromMessage)(a?.body??"",e.subjectMaxLength)),U=(0,_reactHookForm.useForm)({defaultValues:{category:listed(a?.category)??listed(i)??"",subject:a?.subject||(0,_subject.subjectFromMessage)(a?.body??"",e.subjectMaxLength),body:a?.body??""}}),R=U.handleSubmit(async t=>{const s=(0,_validation.validateFiles)([...y,...h],e,c);if(L(s??null),s)return;w(null);const i=a?.queue??l;try{const s=await d({category:t.category,subject:t.subject.trim()||(0,_subject.subjectFromMessage)(t.body,e.subjectMaxLength),body:t.body.trim(),pageUrl:a?.pageUrl,userAgent:a?.userAgent??(0,_device.describeDevice)(),appVersion:a?.appVersion??n,...void 0===i?{}:{queue:i},files:h,screenshots:y});"Sent"===s.status?r(s.ticket):"Queued"===s.status?o(s.entry):w(s.error.message)}catch(e){w((0,_client.toSupportApiError)(e).message)}}),f=U.formState.isSubmitting,C=(0,_SupportProvider.useSupportUploadProgress)(_types.SUPPORT_TICKET_QUEUE),A=(0,_mobileUi.useHookFormField)({control:U.control,name:"category",rules:{validate:t=>(0,_validation.validateCategory)(t,e,c)}}),k=(0,_mobileUi.useHookFormField)({control:U.control,name:"subject",rules:{validate:t=>""===t.trim()?void 0:(0,_validation.validateSubject)(t,e,c)}}),q=(0,_mobileUi.useHookFormField)({control:U.control,name:"body",rules:{validate:t=>(0,_validation.validateBody)(t,e,c)}}),F=y.length+h.length;(0,_react.useEffect)(()=>{v&&L((0,_validation.validateFiles)([...y,...h],e,c)??null)},[h,y,v,e,c]);const B=k.value.trim();return(0,_react.useEffect)(()=>{if(g||B.length<3)return void j([]);let e=!0;const t=setTimeout(async()=>{try{const t=await(p.getSuggestions?.(B))??[];e&&j(t)}catch{e&&j([])}},500);return()=>{e=!1,clearTimeout(t)}},[p,B,g]),(0,_jsxRuntime.jsxs)(_mobileUi.KeyboardAwareScrollView,{contentContainerStyle:t.content,safeAreaEdges:[],children:[(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"bodySmall",color:"secondary",children:u.intro}),(0,_jsxRuntime.jsx)(_mobileUi.Input,{label:u.messageLabel,placeholder:u.messagePlaceholder,required:!0,multiline:!0,maxLength:e.bodyMaxLength,value:q.value,onChangeText:t=>{q.onChangeText(t),T.current||U.setValue("subject",(0,_subject.subjectFromMessage)(t,e.subjectMaxLength))},onBlur:q.onBlur,error:q.error,testID:"support-new-body"}),(0,_jsxRuntime.jsx)(_mobileUi.Input,{label:u.subjectLabel,placeholder:u.subjectPlaceholder,helperText:u.subjectHelper,maxLength:e.subjectMaxLength,value:k.value,onChangeText:e=>{T.current=""!==e.trim(),k.onChangeText(e)},onBlur:k.onBlur,error:k.error,testID:"support-new-subject"}),_.length>0&&(0,_jsxRuntime.jsx)(_SuggestedAnswers.SuggestedAnswers,{articles:_,testID:"support-new-suggestions"}),(0,_jsxRuntime.jsx)(_mobileUi.Select,{label:u.categoryLabel,placeholder:u.categoryPlaceholder,helperText:u.categoryHelper,options:e.categories.map(e=>({label:e,value:e})),value:A.value||void 0,onChange:e=>A.onChange(String(e)),error:A.error,testID:"support-new-category"}),y.length>0&&(0,_jsxRuntime.jsx)(_PhotoTray.PhotoTray,{label:u.screenshotLabel,photos:y,onChange:S,remaining:0,allowAdd:!1,maxBytes:e.maxAttachmentBytes,disabled:f}),(0,_jsxRuntime.jsx)(_PhotoTray.PhotoTray,{label:u.photosLabel,helperText:(0,_labels.fillLabel)(u.photoLimit,{count:e.maxAttachmentsPerMessage}),photos:h,onChange:x,remaining:e.maxAttachmentsPerMessage-F,maxBytes:e.maxAttachmentBytes,disabled:f}),f&&(0,_jsxRuntime.jsx)(_SupportUploadProgress.SupportUploadProgress,{progress:C,testID:"support-new-progress"}),(v||P)&&(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"bodySmall",color:"danger",accessibilityLiveRegion:"polite",children:v??P}),(0,_jsxRuntime.jsxs)(_reactNative.View,{style:t.actions,children:[s&&(0,_jsxRuntime.jsx)(_mobileUi.Button,{label:u.cancel,variant:"ghost",tone:"neutral",onPress:s,disabled:f}),(0,_jsxRuntime.jsx)(_mobileUi.Button,{label:u.send,loading:f,disabled:f,onPress:()=>{R()},testID:"support-new-submit"})]})]})},NewSupportTicket=e=>{const t=(0,_SupportProvider.useSupportLabels)("newTicket",LABELS),r=(0,_mobileUi.useTheme)(),o=(0,_react.useMemo)(()=>buildStyles(r),[r]),{config:s,loading:a,error:i,reload:n}=(0,_SupportProvider.useSupportConfig)(),l=e.testID??"support-new-ticket";return s?(0,_jsxRuntime.jsxs)(_reactNative.View,{style:o.root,testID:l,children:[(0,_jsxRuntime.jsx)(_mobileUi.NetworkStatusBanner,{}),(0,_jsxRuntime.jsx)(TicketForm,{...e,config:s,styles:o})]}):(0,_jsxRuntime.jsx)(_reactNative.View,{style:o.center,testID:l,children:a?(0,_jsxRuntime.jsx)(_mobileUi.Spinner,{accessibilityLabel:t.loading}):(0,_jsxRuntime.jsxs)(_jsxRuntime.Fragment,{children:[(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"body",color:"danger",align:"center",children:i?.message??t.unavailable}),(0,_jsxRuntime.jsx)(_mobileUi.Button,{label:t.retry,variant:"ghost",onPress:()=>{n()}})]})})};exports.NewSupportTicket=NewSupportTicket;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},actions:{flexDirection:"row",justifyContent:"flex-end",gap:e.space.sm}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.NewSupportTicket=void 0;var _mobileCore=require("@webority/mobile-core"),_mobileUi=require("@webority/mobile-ui"),_react=require("react"),_reactHookForm=require("react-hook-form"),_reactNative=require("react-native"),_client=require("../client.js"),_device=require("../device.js"),_labels=require("../labels.js"),_SupportProvider=require("../SupportProvider.js"),_subject=require("../subject.js"),_types=require("../types.js"),_validation=require("../validation.js"),_PhotoTray=require("./PhotoTray.js"),_SuggestedAnswers=require("./SuggestedAnswers.js"),_SupportUploadProgress=require("./SupportUploadProgress.js"),_jsxRuntime=require("react/jsx-runtime");const LABELS={intro:"Tell us what you need. We reply by email and in this ticket.",messageLabel:"Message",messagePlaceholder:"What happened, and what did you expect?",subjectLabel:"Subject",subjectPlaceholder:"A short summary",subjectHelper:"Filled in from your message. You can change it.",categoryLabel:"Category (optional)",categoryPlaceholder:"Choose a category",categoryHelper:"Not sure? Leave it empty and we will sort it.",screenshotLabel:"Screenshot",photosLabel:"Photos",photoLimit:"Add up to {count} photos.",cancel:"Cancel",send:"Send ticket",loading:"Loading",retry:"Try again",unavailable:"Support is not available right now."},SUGGESTION_PAUSE_MS=500,SUGGESTION_MIN_CHARS=3,TicketForm=({config:e,styles:t,onCreated:r,onQueued:o,onCancel:s,initialDraft:a,defaultCategory:i,appVersion:n,queue:l})=>{const u=(0,_SupportProvider.useSupportLabels)("newTicket",LABELS),c=(0,_SupportProvider.useSupportLabels)("shared",_labels.SHARED_LABELS),d=(0,_SupportProvider.useCreateSupportTicket)(),p=(0,_SupportProvider.useSupportClient)(),{isConnected:m,isInternetReachable:b}=(0,_mobileCore.useNetworkStatus)(),g=!m||!1===b,[_,j]=(0,_react.useState)([]),listed=t=>t&&(0,_validation.categoryNames)(e,l).includes(t)?t:void 0,[h,x]=(0,_react.useState)([]),[y,S]=(0,_react.useState)(a?.screenshots??[]),[v,L]=(0,_react.useState)(null),[P,w]=(0,_react.useState)(null),T=(0,_react.useRef)(Boolean(a?.subject?.trim())&&a?.subject!==(0,_subject.subjectFromMessage)(a?.body??"",e.subjectMaxLength)),U=(0,_reactHookForm.useForm)({defaultValues:{category:listed(a?.category)??listed(i)??"",subject:a?.subject||(0,_subject.subjectFromMessage)(a?.body??"",e.subjectMaxLength),body:a?.body??""}}),R=U.handleSubmit(async t=>{const s=(0,_validation.validateFiles)([...y,...h],e,c);if(L(s??null),s)return;w(null);const i=a?.queue??l;try{const s=await d({category:t.category,subject:t.subject.trim()||(0,_subject.subjectFromMessage)(t.body,e.subjectMaxLength),body:t.body.trim(),pageUrl:a?.pageUrl,userAgent:a?.userAgent??(0,_device.describeDevice)(),appVersion:a?.appVersion??n,...void 0===i?{}:{queue:i},files:h,screenshots:y});"Sent"===s.status?r(s.ticket):"Queued"===s.status?o(s.entry):w(s.error.message)}catch(e){w((0,_client.toSupportApiError)(e).message)}}),f=U.formState.isSubmitting,C=(0,_SupportProvider.useSupportUploadProgress)(_types.SUPPORT_TICKET_QUEUE),A=(0,_mobileUi.useHookFormField)({control:U.control,name:"category",rules:{validate:t=>(0,_validation.validateCategory)(t,e,c,l)}}),k=(0,_mobileUi.useHookFormField)({control:U.control,name:"subject",rules:{validate:t=>""===t.trim()?void 0:(0,_validation.validateSubject)(t,e,c)}}),q=(0,_mobileUi.useHookFormField)({control:U.control,name:"body",rules:{validate:t=>(0,_validation.validateBody)(t,e,c)}}),F=y.length+h.length;(0,_react.useEffect)(()=>{v&&L((0,_validation.validateFiles)([...y,...h],e,c)??null)},[h,y,v,e,c]);const B=k.value.trim();return(0,_react.useEffect)(()=>{if(g||B.length<3)return void j([]);let e=!0;const t=setTimeout(async()=>{try{const t=await(p.getSuggestions?.(B))??[];e&&j(t)}catch{e&&j([])}},500);return()=>{e=!1,clearTimeout(t)}},[p,B,g]),(0,_jsxRuntime.jsxs)(_mobileUi.KeyboardAwareScrollView,{contentContainerStyle:t.content,safeAreaEdges:[],children:[(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"bodySmall",color:"secondary",children:u.intro}),(0,_jsxRuntime.jsx)(_mobileUi.Input,{label:u.messageLabel,placeholder:u.messagePlaceholder,required:!0,multiline:!0,maxLength:e.bodyMaxLength,value:q.value,onChangeText:t=>{q.onChangeText(t),T.current||U.setValue("subject",(0,_subject.subjectFromMessage)(t,e.subjectMaxLength))},onBlur:q.onBlur,error:q.error,testID:"support-new-body"}),(0,_jsxRuntime.jsx)(_mobileUi.Input,{label:u.subjectLabel,placeholder:u.subjectPlaceholder,helperText:u.subjectHelper,maxLength:e.subjectMaxLength,value:k.value,onChangeText:e=>{T.current=""!==e.trim(),k.onChangeText(e)},onBlur:k.onBlur,error:k.error,testID:"support-new-subject"}),_.length>0&&(0,_jsxRuntime.jsx)(_SuggestedAnswers.SuggestedAnswers,{articles:_,testID:"support-new-suggestions"}),(0,_jsxRuntime.jsx)(_mobileUi.Select,{label:u.categoryLabel,placeholder:u.categoryPlaceholder,helperText:u.categoryHelper,options:(0,_validation.categoryNames)(e,l).map(e=>({label:e,value:e})),value:A.value||void 0,onChange:e=>A.onChange(String(e)),error:A.error,testID:"support-new-category"}),y.length>0&&(0,_jsxRuntime.jsx)(_PhotoTray.PhotoTray,{label:u.screenshotLabel,photos:y,onChange:S,remaining:0,allowAdd:!1,maxBytes:e.maxAttachmentBytes,disabled:f}),(0,_jsxRuntime.jsx)(_PhotoTray.PhotoTray,{label:u.photosLabel,helperText:(0,_labels.fillLabel)(u.photoLimit,{count:e.maxAttachmentsPerMessage}),photos:h,onChange:x,remaining:e.maxAttachmentsPerMessage-F,maxBytes:e.maxAttachmentBytes,disabled:f}),f&&(0,_jsxRuntime.jsx)(_SupportUploadProgress.SupportUploadProgress,{progress:C,testID:"support-new-progress"}),(v||P)&&(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"bodySmall",color:"danger",accessibilityLiveRegion:"polite",children:v??P}),(0,_jsxRuntime.jsxs)(_reactNative.View,{style:t.actions,children:[s&&(0,_jsxRuntime.jsx)(_mobileUi.Button,{label:u.cancel,variant:"ghost",tone:"neutral",onPress:s,disabled:f}),(0,_jsxRuntime.jsx)(_mobileUi.Button,{label:u.send,loading:f,disabled:f,onPress:()=>{R()},testID:"support-new-submit"})]})]})},NewSupportTicket=e=>{const t=(0,_SupportProvider.useSupportLabels)("newTicket",LABELS),r=(0,_mobileUi.useTheme)(),o=(0,_react.useMemo)(()=>buildStyles(r),[r]),{config:s,loading:a,error:i,reload:n}=(0,_SupportProvider.useSupportConfig)(),l=e.testID??"support-new-ticket";return s?(0,_jsxRuntime.jsxs)(_reactNative.View,{style:o.root,testID:l,children:[(0,_jsxRuntime.jsx)(_mobileUi.NetworkStatusBanner,{}),(0,_jsxRuntime.jsx)(TicketForm,{...e,config:s,styles:o})]}):(0,_jsxRuntime.jsx)(_reactNative.View,{style:o.center,testID:l,children:a?(0,_jsxRuntime.jsx)(_mobileUi.Spinner,{accessibilityLabel:t.loading}):(0,_jsxRuntime.jsxs)(_jsxRuntime.Fragment,{children:[(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"body",color:"danger",align:"center",children:i?.message??t.unavailable}),(0,_jsxRuntime.jsx)(_mobileUi.Button,{label:t.retry,variant:"ghost",onPress:()=>{n()}})]})})};exports.NewSupportTicket=NewSupportTicket;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},actions:{flexDirection:"row",justifyContent:"flex-end",gap:e.space.sm}});
@@ -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"),_SupportUploadProgress=require("./SupportUploadProgress.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;switch(t.kind){case"json":{const e=t.value;return"object"==typeof e&&null!==e&&"body"in e&&"string"==typeof e.body?e.body:""}case"multipart":{const e=t.fields.find(e=>"body"===e.name);return e&&"value"in e?e.value:""}case"resumable":return"";default:return t}},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:r}=(0,_SupportProvider.useSupportConfig)(),l=(0,_SupportProvider.useSupportTimeZone)(),{ticket:d,loading:u,error:c,actionError:m,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=(0,_SupportProvider.useSupportUploadProgress)(_types.SUPPORT_REPLY_QUEUE),[v,S]=(0,_react.useState)(null),[T,w]=(0,_react.useState)(""),[U,f]=(0,_react.useState)([]),[D,L]=(0,_react.useState)(!1),[P,C]=(0,_react.useState)(null),[k,I]=(0,_react.useState)(null),[B,N]=(0,_react.useState)(""),[A,q]=(0,_react.useState)(!1);if(!d)return(0,_jsxRuntime.jsx)(_reactNative.View,{style:o.center,testID:i,children:u?(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:c?.message??s.notFound}),(0,_jsxRuntime.jsx)(_mobileUi.Button,{label:s.retry,variant:"ghost",onPress:()=>{x()}})]})});const z={Satisfied:s.satisfied,Unsatisfied:s.unsatisfied},O=d.mergedInto,M=d.messages.filter(e=>!e.isInternal),V=d.updatedDateTimeUtc!==d.createdDateTimeUtc,$=P??m?.message??null,E=Boolean(r)&&(D||U.length>0),Y=E||$||d.canReopen||p?(0,_jsxRuntime.jsxs)(_jsxRuntime.Fragment,{children:[p&&(0,_jsxRuntime.jsx)(_SupportUploadProgress.SupportUploadProgress,{progress:R,testID:"support-reply-progress"}),E&&r&&(0,_jsxRuntime.jsx)(_PhotoTray.PhotoTray,{photos:U,onChange:e=>{f(e),C(null)},remaining:r.maxAttachmentsPerMessage-U.length,maxBytes:r.maxAttachmentBytes,disabled:p}),$&&(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"bodySmall",color:"danger",accessibilityLiveRegion:"polite",children:$}),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:l})})}),V&&(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"caption",color:"tertiary",children:(0,_labels.fillLabel)(s.updated,{date:(0,_mobileCore.formatDateTime)(d.updatedDateTimeUtc,{zone:l})})})]})]}),O&&(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:O.number})}),t&&(0,_jsxRuntime.jsx)(_mobileUi.Button,{label:(0,_labels.fillLabel)(s.openMerged,{number:O.number}),variant:"link",size:"sm",onPress:()=>t(O.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:()=>q(!0),testID:"support-withdraw"}),(0,_jsxRuntime.jsx)(_mobileUi.Dialog,{open:A,onClose:()=>q(!1),title:s.withdrawTitle,message:s.withdrawMessage,tone:"danger",actions:[{label:s.withdrawCancel,onPress:()=>q(!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:z[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:B,onChangeText:N,multiline:!0,maxLength:r?.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:B})&&(I(null),N(""))})()},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:l,labels:s,onOpenImage:(e,t)=>S({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:l})},{label:s.detailLastUpdate,value:(0,_mobileCore.formatDateTime)(d.updatedDateTimeUtc,{zone:l})}]})]})]}),!O&&(0,_jsxRuntime.jsx)(_mobileUi.Composer,{value:T,onChangeText:e=>{w(e),C(null)},onSend:e=>{(async e=>{const t=e.trim(),i=r?(0,_validation.validateBody)(t,r,a)??(0,_validation.validateFiles)(U,r,a):t?void 0:s.writeMessage;if(i)return C(i),void w(e);"Failed"!==await _({body:t,files:U})?(f([]),L(!1)):w(e)})(e)},loading:p,maxLength:r?.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||!r,onPress:()=>L(e=>!e),testID:"support-reply-attach"}),above:Y,testID:"support-reply-composer"}),(0,_jsxRuntime.jsx)(_Attachments.ImageViewer,{image:v,onClose:()=>S(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"),_SupportUploadProgress=require("./SupportUploadProgress.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;switch(t.kind){case"json":{const e=t.value;return"object"==typeof e&&null!==e&&"body"in e&&"string"==typeof e.body?e.body:""}case"multipart":{const e=t.fields.find(e=>"body"===e.name);return e&&"value"in e?e.value:""}case"resumable":return"";default:return t}},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:r}=(0,_SupportProvider.useSupportConfig)(),l=(0,_SupportProvider.useSupportTimeZone)(),{ticket:d,loading:u,error:c,actionError:m,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=(0,_SupportProvider.useSupportUploadProgress)(_types.SUPPORT_REPLY_QUEUE),[v,S]=(0,_react.useState)(null),[T,w]=(0,_react.useState)(""),[U,f]=(0,_react.useState)([]),[D,L]=(0,_react.useState)(!1),[P,C]=(0,_react.useState)(null),[k,I]=(0,_react.useState)(null),[B,N]=(0,_react.useState)(""),[A,q]=(0,_react.useState)(!1);if(!d)return(0,_jsxRuntime.jsx)(_reactNative.View,{style:o.center,testID:i,children:u?(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:c?.message??s.notFound}),(0,_jsxRuntime.jsx)(_mobileUi.Button,{label:s.retry,variant:"ghost",onPress:()=>{x()}})]})});const z={Satisfied:s.satisfied,Unsatisfied:s.unsatisfied},O=d.mergedInto,M=d.messages.filter(e=>!e.isInternal),V=d.updatedDateTimeUtc!==d.createdDateTimeUtc,$=P??m?.message??h.error?.message??null,E=Boolean(r)&&(D||U.length>0),Y=E||$||d.canReopen||p?(0,_jsxRuntime.jsxs)(_jsxRuntime.Fragment,{children:[p&&(0,_jsxRuntime.jsx)(_SupportUploadProgress.SupportUploadProgress,{progress:R,testID:"support-reply-progress"}),E&&r&&(0,_jsxRuntime.jsx)(_PhotoTray.PhotoTray,{photos:U,onChange:e=>{f(e),C(null)},remaining:r.maxAttachmentsPerMessage-U.length,maxBytes:r.maxAttachmentBytes,disabled:p}),$&&(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"bodySmall",color:"danger",accessibilityLiveRegion:"polite",children:$}),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:l})})}),V&&(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"caption",color:"tertiary",children:(0,_labels.fillLabel)(s.updated,{date:(0,_mobileCore.formatDateTime)(d.updatedDateTimeUtc,{zone:l})})})]})]}),O&&(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:O.number})}),t&&(0,_jsxRuntime.jsx)(_mobileUi.Button,{label:(0,_labels.fillLabel)(s.openMerged,{number:O.number}),variant:"link",size:"sm",onPress:()=>t(O.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:()=>q(!0),testID:"support-withdraw"}),(0,_jsxRuntime.jsx)(_mobileUi.Dialog,{open:A,onClose:()=>q(!1),title:s.withdrawTitle,message:s.withdrawMessage,tone:"danger",actions:[{label:s.withdrawCancel,onPress:()=>q(!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:z[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:B,onChangeText:N,multiline:!0,maxLength:r?.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:B})&&(I(null),N(""))})()},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:l,labels:s,onOpenImage:(e,t)=>S({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:l})},{label:s.detailLastUpdate,value:(0,_mobileCore.formatDateTime)(d.updatedDateTimeUtc,{zone:l})}]})]})]}),!O&&(0,_jsxRuntime.jsx)(_mobileUi.Composer,{value:T,onChangeText:e=>{w(e),C(null)},onSend:e=>{(async e=>{const t=e.trim(),i=r?(0,_validation.validateBody)(t,r,a)??(0,_validation.validateFiles)(U,r,a):t?void 0:s.writeMessage;if(i)return C(i),void w(e);"Failed"!==await _({body:t,files:U})?(f([]),L(!1)):w(e)})(e)},loading:p,maxLength:r?.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||!r,onPress:()=>L(e=>!e),testID:"support-reply-attach"}),above:Y,testID:"support-reply-composer"}),(0,_jsxRuntime.jsx)(_Attachments.ImageViewer,{image:v,onClose:()=>S(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.statusFilterOptions=exports.SupportTicketList=exports.STATUS_TONES=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"),_jsxRuntime=require("react/jsx-runtime");const LABELS={outboxFailed:"We could not send this report. Try again.",waitingToSend:"Waiting to send",sendNow:"Send now",discard:"Discard",discardTitle:"Discard this report?",discardText:"It has not been sent.",updated:"Updated {date}",newTicket:"New ticket",retry:"Try again",searchPlaceholder:"Search by subject or ticket number",searchLabel:"Search tickets",filterLabel:"Filter by status",all:"All",ticketAccessibility:"{subject}, {status}, ticket {number}",chipAccessibility:"{label}, {count} tickets",loadingTickets:"Loading your tickets",emptyTitle:"No tickets yet",emptyText:"Raise a ticket and it will show here with its status.",noMatchTitle:"No tickets match",noMatchText:"Try another status or search.",loadingMore:"Loading more tickets",loadMore:"Load more"},STATUS_TONES=exports.STATUS_TONES={Open:"info",InProgress:"info",WaitingOnCustomer:"warning",Resolved:"success",Closed:"success",Cancelled:"neutral"},STATUS_FILTERS=[{value:"Open",label:"Open",count:"open"},{value:"NeedsReply",label:"Needs your reply",count:"needsReply"},{value:"Resolved",label:"Resolved",count:"resolved"},{value:"Withdrawn",label:"Withdrawn",count:"withdrawn"}],ALL="all",statusFilterOptions=(e,t,i=LABELS.all)=>[{value:ALL,label:i,count:e.total},...STATUS_FILTERS.filter(i=>e[i.count]>0||i.value===t).map(t=>({value:t.value,label:t.label,count:e[t.count]}))];exports.statusFilterOptions=statusFilterOptions;const chipLabel=e=>void 0===e.count?e.label:`${e.label} (${e.count})`,SEARCH_DEBOUNCE_MS=400,ticketKey=e=>e.id,OutboxRow=(0,_react.memo)(function OutboxRow({entry:e,onRetry:t,onDiscard:i,styles:s,t:a}){const r="Failed"===e.state;return(0,_jsxRuntime.jsxs)(_mobileUi.Card,{bodyStyle:s.card,testID:`support-outbox-${e.id}`,children:[(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"title",numberOfLines:2,children:e.label}),(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"bodySmall",color:r?"danger":"secondary",children:r?e.lastFailure?.message??a.outboxFailed:a.waitingToSend}),(0,_jsxRuntime.jsxs)(_reactNative.View,{style:s.outboxActions,children:[(0,_jsxRuntime.jsx)(_mobileUi.Button,{label:a.sendNow,size:"sm",variant:"ghost",onPress:()=>{t(e.id)},testID:`support-outbox-retry-${e.id}`}),(0,_jsxRuntime.jsx)(_mobileUi.Button,{label:a.discard,size:"sm",variant:"ghost",tone:"danger",onPress:()=>{i(e)},testID:`support-outbox-discard-${e.id}`})]})]})}),TicketRow=(0,_react.memo)(function TicketRow({item:e,timeZone:t,onOpen:i,styles:s,t:a}){return(0,_jsxRuntime.jsxs)(_mobileUi.Card,{onPress:()=>i(e),accessibilityLabel:(0,_labels.fillLabel)(a.ticketAccessibility,{subject:e.subject,status:e.statusLabel,number:e.number}),bodyStyle:s.card,testID:`support-ticket-${e.id}`,children:[(0,_jsxRuntime.jsxs)(_reactNative.View,{style:s.cardTop,children:[(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"caption",color:"tertiary",children:e.number}),(0,_jsxRuntime.jsx)(_mobileUi.StatusBadge,{label:e.statusLabel,tone:STATUS_TONES[e.status]??"neutral",size:"sm"})]}),(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"title",numberOfLines:2,children:e.subject}),(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"bodySmall",color:"secondary",children:e.category}),(0,_jsxRuntime.jsx)(_reactNative.View,{style:s.cardBottom,children:(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"caption",color:"tertiary",children:(0,_labels.fillLabel)(a.updated,{date:(0,_mobileCore.formatDateTime)(e.updatedDateTimeUtc,{zone:t})})})})]})}),SupportTicketList=({onOpenTicket:e,onNewTicket:t,header:i,pageSize:s,testID:a="support-ticket-list"})=>{const r=(0,_SupportProvider.useSupportLabels)("ticketList",LABELS),o=(0,_mobileUi.useTheme)(),l=(0,_react.useMemo)(()=>buildStyles(o),[o]),{tickets:n,counts:c,status:u,search:d,setStatus:m,setSearch:b,loading:x,refreshing:p,loadingMore:_,error:j,loadMoreError:y,refresh:h,loadMore:T}=(0,_SupportProvider.useSupportTickets)(void 0===s?{}:{pageSize:s}),R=(0,_SupportProvider.useSupportTimeZone)(),{entries:S,retry:v,discard:g}=(0,_SupportProvider.useSupportOutbox)(_types.SUPPORT_TICKET_QUEUE),L=(0,_react.useCallback)(async e=>{await(0,_mobileUi.confirm)({title:r.discardTitle,message:r.discardText,confirmLabel:r.discard,tone:"danger"})&&await g(e.id)},[g,r]),w=(0,_react.useCallback)(({item:t})=>(0,_jsxRuntime.jsx)(TicketRow,{item:t,timeZone:R,onOpen:e,styles:l,t:r}),[R,e,l,r]),f=(0,_react.useCallback)(()=>{T()},[T]),k=(0,_react.useCallback)(()=>{h()},[h]),U=(0,_react.useMemo)(()=>(0,_jsxRuntime.jsx)(_reactNative.RefreshControl,{refreshing:p,onRefresh:k}),[p,k]),N=(c?.total??0)>0,C=null!==u||""!==d.trim(),O=!x&&!j&&!N,E=(0,_jsxRuntime.jsxs)(_reactNative.View,{style:l.header,children:[t&&!O&&(0,_jsxRuntime.jsx)(_mobileUi.Button,{label:r.newTicket,leftIcon:"add",onPress:t,fullWidth:!0}),i,S.map(e=>(0,_jsxRuntime.jsx)(OutboxRow,{entry:e,onRetry:v,onDiscard:L,styles:l,t:r},e.id)),j&&(0,_jsxRuntime.jsxs)(_reactNative.View,{style:l.error,accessibilityLiveRegion:"polite",children:[(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"bodySmall",color:"danger",children:j.message}),(0,_jsxRuntime.jsx)(_mobileUi.Button,{label:r.retry,size:"sm",variant:"ghost",onPress:()=>{h()}})]}),c&&N&&(0,_jsxRuntime.jsxs)(_jsxRuntime.Fragment,{children:[(0,_jsxRuntime.jsx)(_mobileUi.SearchBar,{value:d,onChangeText:b,debounceMs:400,placeholder:r.searchPlaceholder,accessibilityLabel:r.searchLabel,testID:"support-ticket-search"}),(0,_jsxRuntime.jsx)(_reactNative.ScrollView,{horizontal:!0,showsHorizontalScrollIndicator:!1,contentContainerStyle:l.filters,accessibilityRole:"tablist",accessibilityLabel:r.filterLabel,children:statusFilterOptions(c,u,r.all).map(e=>(0,_jsxRuntime.jsx)(_mobileUi.Chip,{label:chipLabel(e),selected:(u??ALL)===e.value,onPress:()=>m(e.value===ALL?null:e.value),accessibilityLabel:void 0===e.count?e.label:(0,_labels.fillLabel)(r.chipAccessibility,{label:e.label,count:e.count}),testID:`support-filter-${e.value}`},e.value))})]})]});if(x&&null===c&&!j)return(0,_jsxRuntime.jsxs)(_reactNative.View,{style:[l.content,{flex:1}],testID:a,children:[S.map(e=>(0,_jsxRuntime.jsx)(OutboxRow,{entry:e,onRetry:v,onDiscard:L,styles:l,t:r},e.id)),(0,_jsxRuntime.jsx)(_reactNative.View,{style:l.center,children:(0,_jsxRuntime.jsx)(_mobileUi.Spinner,{accessibilityLabel:r.loadingTickets})})]});const A=_?(0,_jsxRuntime.jsx)(_reactNative.View,{style:l.footer,children:(0,_jsxRuntime.jsx)(_mobileUi.Spinner,{size:"sm",accessibilityLabel:r.loadingMore})}):y?(0,_jsxRuntime.jsxs)(_reactNative.View,{style:[l.footer,l.error],accessibilityLiveRegion:"polite",children:[(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"bodySmall",color:"danger",children:y.message}),(0,_jsxRuntime.jsx)(_mobileUi.Button,{label:r.loadMore,size:"sm",variant:"ghost",onPress:()=>{T()}})]}):void 0;return(0,_jsxRuntime.jsx)(_reactNative.FlatList,{testID:a,data:n,keyExtractor:ticketKey,contentContainerStyle:l.content,ListHeaderComponent:E,ListFooterComponent:A,onEndReached:f,onEndReachedThreshold:.5,refreshControl:U,ListEmptyComponent:x?(0,_jsxRuntime.jsx)(_reactNative.View,{style:l.footer,children:(0,_jsxRuntime.jsx)(_mobileUi.Spinner,{accessibilityLabel:r.loadingTickets})}):j?void 0:N?(0,_jsxRuntime.jsx)(_mobileUi.EmptyState,{title:r.noMatchTitle,description:C?r.noMatchText:void 0}):(0,_jsxRuntime.jsx)(_mobileUi.EmptyState,{title:r.emptyTitle,description:r.emptyText,action:t?{label:r.newTicket,onPress:t}:void 0}),renderItem:w})};exports.SupportTicketList=SupportTicketList;const buildStyles=e=>_reactNative.StyleSheet.create({content:{padding:e.space.md,gap:e.space.sm},header:{gap:e.space.sm,marginBottom:e.space.xs},filters:{gap:e.space.xs},error:{gap:e.space.xs,alignItems:"flex-start"},center:{flex:1,alignItems:"center",justifyContent:"center",padding:e.space.xl},footer:{paddingVertical:e.space.md,alignItems:"center"},card:{gap:e.space.xxs},outboxActions:{flexDirection:"row",gap:e.space.xs,marginTop:e.space.xxs},cardTop:{flexDirection:"row",justifyContent:"space-between",alignItems:"center"},cardBottom:{flexDirection:"row",justifyContent:"space-between",marginTop:e.space.xxs}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.statusFilterOptions=exports.SupportTicketList=exports.STATUS_TONES=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"),_jsxRuntime=require("react/jsx-runtime");const LABELS={outboxFailed:"We could not send this report. Try again.",waitingToSend:"Waiting to send",sendNow:"Send now",discard:"Discard",discardTitle:"Discard this report?",discardText:"It has not been sent.",updated:"Updated {date}",newTicket:"New ticket",retry:"Try again",searchPlaceholder:"Search by subject or ticket number",searchLabel:"Search tickets",filterLabel:"Filter by status",all:"All",ticketAccessibility:"{subject}, {status}, ticket {number}",chipAccessibility:"{label}, {count} tickets",loadingTickets:"Loading your tickets",emptyTitle:"No tickets yet",emptyText:"Raise a ticket and it will show here with its status.",noMatchTitle:"No tickets match",noMatchText:"Try another status or search.",loadingMore:"Loading more tickets",loadMore:"Load more"},STATUS_TONES=exports.STATUS_TONES={Open:"info",InProgress:"info",WaitingOnCustomer:"warning",Resolved:"success",Closed:"success",Cancelled:"neutral"},STATUS_FILTERS=[{value:"Open",label:"Open",count:"open"},{value:"NeedsReply",label:"Needs your reply",count:"needsReply"},{value:"Resolved",label:"Resolved",count:"resolved"},{value:"Withdrawn",label:"Withdrawn",count:"withdrawn"}],ALL="all",statusFilterOptions=(e,t,i=LABELS.all)=>[{value:ALL,label:i,count:e.total},...STATUS_FILTERS.filter(i=>e[i.count]>0||i.value===t).map(t=>({value:t.value,label:t.label,count:e[t.count]}))];exports.statusFilterOptions=statusFilterOptions;const chipLabel=e=>void 0===e.count?e.label:`${e.label} (${e.count})`,SEARCH_DEBOUNCE_MS=400,ticketKey=e=>e.id,TicketRow=(0,_react.memo)(function TicketRow({item:e,timeZone:t,onOpen:i,styles:s,t:r}){return(0,_jsxRuntime.jsxs)(_mobileUi.Card,{onPress:()=>i(e),accessibilityLabel:(0,_labels.fillLabel)(r.ticketAccessibility,{subject:e.subject,status:e.statusLabel,number:e.number}),bodyStyle:s.card,testID:`support-ticket-${e.id}`,children:[(0,_jsxRuntime.jsxs)(_reactNative.View,{style:s.cardTop,children:[(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"caption",color:"tertiary",children:e.number}),(0,_jsxRuntime.jsx)(_mobileUi.StatusBadge,{label:e.statusLabel,tone:STATUS_TONES[e.status]??"neutral",size:"sm"})]}),(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"title",numberOfLines:2,children:e.subject}),(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"bodySmall",color:"secondary",children:e.category}),(0,_jsxRuntime.jsx)(_reactNative.View,{style:s.cardBottom,children:(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"caption",color:"tertiary",children:(0,_labels.fillLabel)(r.updated,{date:(0,_mobileCore.formatDateTime)(e.updatedDateTimeUtc,{zone:t})})})})]})}),SupportTicketList=({onOpenTicket:e,onNewTicket:t,header:i,pageSize:s,testID:r="support-ticket-list"})=>{const a=(0,_SupportProvider.useSupportLabels)("ticketList",LABELS),l=(0,_mobileUi.useTheme)(),o=(0,_react.useMemo)(()=>buildStyles(l),[l]),{tickets:n,counts:c,status:u,search:d,setStatus:m,setSearch:p,loading:b,refreshing:x,loadingMore:_,error:j,loadMoreError:y,refresh:h,loadMore:T}=(0,_SupportProvider.useSupportTickets)(void 0===s?{}:{pageSize:s}),S=(0,_SupportProvider.useSupportTimeZone)(),{entries:v,error:R,retry:L,discard:g}=(0,_SupportProvider.useSupportOutbox)(_types.SUPPORT_TICKET_QUEUE),w=(0,_jsxRuntime.jsx)(_mobileUi.OutboxEntryList,{entries:v,error:R,onRetry:e=>{L(e)},onDiscard:e=>{g(e)},labels:{waiting:a.waitingToSend,failed:a.outboxFailed,sendNow:a.sendNow,discard:a.discard,discardTitle:a.discardTitle,discardText:a.discardText},testID:"support-outbox"}),k=(0,_react.useCallback)(({item:t})=>(0,_jsxRuntime.jsx)(TicketRow,{item:t,timeZone:S,onOpen:e,styles:o,t:a}),[S,e,o,a]),f=(0,_react.useCallback)(()=>{T()},[T]),U=(0,_react.useCallback)(()=>{h()},[h]),N=(0,_react.useMemo)(()=>(0,_jsxRuntime.jsx)(_reactNative.RefreshControl,{refreshing:x,onRefresh:U}),[x,U]),C=(c?.total??0)>0,E=null!==u||""!==d.trim(),O=!b&&!j&&!C,A=(0,_jsxRuntime.jsxs)(_reactNative.View,{style:o.header,children:[t&&!O&&(0,_jsxRuntime.jsx)(_mobileUi.Button,{label:a.newTicket,leftIcon:"add",onPress:t,fullWidth:!0}),i,w,j&&(0,_jsxRuntime.jsxs)(_reactNative.View,{style:o.error,accessibilityLiveRegion:"polite",children:[(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"bodySmall",color:"danger",children:j.message}),(0,_jsxRuntime.jsx)(_mobileUi.Button,{label:a.retry,size:"sm",variant:"ghost",onPress:()=>{h()}})]}),c&&C&&(0,_jsxRuntime.jsxs)(_jsxRuntime.Fragment,{children:[(0,_jsxRuntime.jsx)(_mobileUi.SearchBar,{value:d,onChangeText:p,debounceMs:400,placeholder:a.searchPlaceholder,accessibilityLabel:a.searchLabel,testID:"support-ticket-search"}),(0,_jsxRuntime.jsx)(_reactNative.ScrollView,{horizontal:!0,showsHorizontalScrollIndicator:!1,contentContainerStyle:o.filters,accessibilityRole:"tablist",accessibilityLabel:a.filterLabel,children:statusFilterOptions(c,u,a.all).map(e=>(0,_jsxRuntime.jsx)(_mobileUi.Chip,{label:chipLabel(e),selected:(u??ALL)===e.value,onPress:()=>m(e.value===ALL?null:e.value),accessibilityLabel:void 0===e.count?e.label:(0,_labels.fillLabel)(a.chipAccessibility,{label:e.label,count:e.count}),testID:`support-filter-${e.value}`},e.value))})]})]});if(b&&null===c&&!j)return(0,_jsxRuntime.jsxs)(_reactNative.View,{style:[o.content,{flex:1}],testID:r,children:[w,(0,_jsxRuntime.jsx)(_reactNative.View,{style:o.center,children:(0,_jsxRuntime.jsx)(_mobileUi.Spinner,{accessibilityLabel:a.loadingTickets})})]});const I=_?(0,_jsxRuntime.jsx)(_reactNative.View,{style:o.footer,children:(0,_jsxRuntime.jsx)(_mobileUi.Spinner,{size:"sm",accessibilityLabel:a.loadingMore})}):y?(0,_jsxRuntime.jsxs)(_reactNative.View,{style:[o.footer,o.error],accessibilityLiveRegion:"polite",children:[(0,_jsxRuntime.jsx)(_mobileUi.Text,{variant:"bodySmall",color:"danger",children:y.message}),(0,_jsxRuntime.jsx)(_mobileUi.Button,{label:a.loadMore,size:"sm",variant:"ghost",onPress:()=>{T()}})]}):void 0;return(0,_jsxRuntime.jsx)(_reactNative.FlatList,{testID:r,data:n,keyExtractor:ticketKey,contentContainerStyle:o.content,ListHeaderComponent:A,ListFooterComponent:I,onEndReached:f,onEndReachedThreshold:.5,refreshControl:N,ListEmptyComponent:b?(0,_jsxRuntime.jsx)(_reactNative.View,{style:o.footer,children:(0,_jsxRuntime.jsx)(_mobileUi.Spinner,{accessibilityLabel:a.loadingTickets})}):j?void 0:C?(0,_jsxRuntime.jsx)(_mobileUi.EmptyState,{title:a.noMatchTitle,description:E?a.noMatchText:void 0}):(0,_jsxRuntime.jsx)(_mobileUi.EmptyState,{title:a.emptyTitle,description:a.emptyText,action:t?{label:a.newTicket,onPress:t}:void 0}),renderItem:k})};exports.SupportTicketList=SupportTicketList;const buildStyles=e=>_reactNative.StyleSheet.create({content:{padding:e.space.md,gap:e.space.sm},header:{gap:e.space.sm,marginBottom:e.space.xs},filters:{gap:e.space.xs},error:{gap:e.space.xs,alignItems:"flex-start"},center:{flex:1,alignItems:"center",justifyContent:"center",padding:e.space.xl},footer:{paddingVertical:e.space.md,alignItems:"center"},card:{gap:e.space.xxs},cardTop:{flexDirection:"row",justifyContent:"space-between",alignItems:"center"},cardBottom:{flexDirection:"row",justifyContent:"space-between",marginTop:e.space.xxs}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.validateSubject=exports.validateFiles=exports.validateCategory=exports.validateBody=void 0;var _labels=require("./labels.js");const validateCategory=(e,t,a=_labels.SHARED_LABELS)=>!e||t.categories.includes(e)?void 0:a.categoryInvalid;exports.validateCategory=validateCategory;const validateSubject=(e,t,a=_labels.SHARED_LABELS)=>{const l=e.trim();return l?l.length>t.subjectMaxLength?(0,_labels.fillLabel)(a.subjectTooLong,{max:t.subjectMaxLength}):void 0:a.subjectRequired};exports.validateSubject=validateSubject;const validateBody=(e,t,a=_labels.SHARED_LABELS)=>{const l=e.trim();return l?l.length>t.bodyMaxLength?(0,_labels.fillLabel)(a.bodyTooLong,{max:t.bodyMaxLength}):void 0:a.bodyRequired};exports.validateBody=validateBody;const validateFiles=(e,t,a=_labels.SHARED_LABELS)=>{if(e.length>t.maxAttachmentsPerMessage)return(0,_labels.fillLabel)(a.tooManyPhotos,{max:t.maxAttachmentsPerMessage});for(const l of e){if(t.allowedContentTypes.length>0&&!t.allowedContentTypes.includes(l.type))return(0,_labels.fillLabel)(a.typeNotAllowed,{name:l.name});if(void 0!==l.size&&l.size>t.maxAttachmentBytes){const e=Math.floor(t.maxAttachmentBytes/1048576);return(0,_labels.fillLabel)(a.fileTooLarge,{name:l.name,mb:e})}}};exports.validateFiles=validateFiles;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.validateSubject=exports.validateFiles=exports.validateCategory=exports.validateBody=exports.categoryNames=void 0;var _labels=require("./labels.js");const categoryNames=(e,t)=>e.categories.filter(e=>void 0===t||e.queue===t).map(e=>e.name);exports.categoryNames=categoryNames;const validateCategory=(e,t,a=_labels.SHARED_LABELS,l)=>!e||categoryNames(t,l).includes(e)?void 0:a.categoryInvalid;exports.validateCategory=validateCategory;const validateSubject=(e,t,a=_labels.SHARED_LABELS)=>{const l=e.trim();return l?l.length>t.subjectMaxLength?(0,_labels.fillLabel)(a.subjectTooLong,{max:t.subjectMaxLength}):void 0:a.subjectRequired};exports.validateSubject=validateSubject;const validateBody=(e,t,a=_labels.SHARED_LABELS)=>{const l=e.trim();return l?l.length>t.bodyMaxLength?(0,_labels.fillLabel)(a.bodyTooLong,{max:t.bodyMaxLength}):void 0:a.bodyRequired};exports.validateBody=validateBody;const validateFiles=(e,t,a=_labels.SHARED_LABELS)=>{if(e.length>t.maxAttachmentsPerMessage)return(0,_labels.fillLabel)(a.tooManyPhotos,{max:t.maxAttachmentsPerMessage});for(const l of e){if(t.allowedContentTypes.length>0&&!t.allowedContentTypes.includes(l.type))return(0,_labels.fillLabel)(a.typeNotAllowed,{name:l.name});if(void 0!==l.size&&l.size>t.maxAttachmentBytes){const e=Math.floor(t.maxAttachmentBytes/1048576);return(0,_labels.fillLabel)(a.fileTooLarge,{name:l.name,mb:e})}}};exports.validateFiles=validateFiles;
@@ -1 +1 @@
1
- "use strict";import{Logger,Storage}from"@webority/mobile-core";import{useOutboxProgress}from"@webority/mobile-core/outbox";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),changedQueue=e=>{switch(e.type){case"changed":return e.queue;case"sent":case"failed":return e.entry.queue;case"progress":return null;default:return e}},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:n,categories:u,maxAttachmentBytes:a,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!==n&&"string"!=typeof n||!isStringArray(u)||"number"!=typeof a||"number"!=typeof c||!isStringArray(i)||"number"!=typeof p||"number"!=typeof l||"number"!=typeof f?null:{productName:t,supportEmail:r,supportName:o,supportPhone:s,supportHours:n,categories:u,maxAttachmentBytes:a,maxAttachmentsPerMessage:c,allowedContentTypes:i,subjectMaxLength:p,bodyMaxLength:l,satisfactionCommentMaxLength:f}};export const SupportProvider=({client:e,outbox:t,openFile:r,timeZone:o,labels:s,children:n})=>{if(!t)throw new Error("[@webority/mobile-support] <SupportProvider> needs an outbox={...}, created with createOutbox from mobile-core.");const[u,a]=useState(null),[c,i]=useState(null),[p,l]=useState(!0),[f,g]=useState(0),y=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)),a(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&&a(e)}}finally{l(!1)}},[e]);useEffect(()=>{y.current.clear(),d()},[d]);const m=useCallback(t=>{const r=y.current.get(t.id);if(r)return r;const o=e.getAttachmentDataUri(t);return y.current.set(t.id,o),o.catch(()=>y.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(()=>g(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:u,configError:c,configLoading:p,reloadConfig:d,loadAttachment:m,openAttachment:S,timeZone:o,labels:s,revision:f,bumpRevision:b}),[e,t,u,c,p,d,m,S,o,s,f,b]);return _jsx(SupportContext.Provider,{value:E,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(),[s,n]=useState(null),[u,a]=useState(""),[c,i]=useState([]),[p,l]=useState(null),[f,g]=useState(0),[y,d]=useState(0),[m,S]=useState(!0),[b,E]=useState(!1),[h,x]=useState(!1),[C,T]=useState(null),[k,A]=useState(null),P=useRef(!0),w=useRef(0),R=useRef(!1),U=useRef(null);useEffect(()=>(P.current=!0,()=>{P.current=!1}),[]);const v=useCallback(e=>{const r=u.trim();return{...s?{status:s}:{},...r?{search:r}:{},page:e,pageSize:t}},[s,u,t]),_=useCallback(async e=>{w.current+=1;const t=w.current,current=()=>P.current&&t===w.current;R.current=!1,x(!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),g(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<y,M=useCallback(async()=>{if(R.current||m||b||!O)return;const e=w.current,current=()=>P.current&&e===w.current;R.current=!0,x(!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))]}),g(e.page),d(e.totalPages))}catch(e){current()&&A(toSupportApiError(e))}finally{current()&&(R.current=!1,x(!1))}},[r,v,f,O,m,b]),I=useCallback(()=>_("refresh"),[_]),Q=useCreateSupportTicket();return{tickets:c,counts:p,status:s,search:u,setStatus:n,setSearch:a,loading:m,refreshing:b,loadingMore:h,hasMore:O,error:C,loadMoreError:k,refresh:I,loadMore:M,createTicket:Q}};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 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 SupportApiError(s.failure.code,s.failure.message,s.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])};export const useSupportUploadProgress=e=>useOutboxProgress(useSupportContext().outbox,e);const TICKET_REFRESH_MS=3e4;export const useSupportTicket=e=>{const{client:t,outbox:r,bumpRevision:o}=useSupportContext(),[s,n]=useState(null),[u,a]=useState(!0),[c,i]=useState(null),[p,l]=useState(null),[f,g]=useState(!1),[y,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()=>{a(!0);try{const r=await t.getTicket(e);m.current&&(n(r),i(null))}catch(e){m.current&&i(toSupportApiError(e))}finally{m.current&&a(!1)}},[t,e]);useEffect(()=>{h()},[h]);const x=useCallback(async()=>{if(!S.current)try{const r=await t.getTicket(e);m.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(()=>(E(),r.subscribe(e=>{"sent"===e.type&&e.entry.queue===SUPPORT_REPLY_QUEUE&&e.entry.request.url===b&&m.current&&(isSupportTicketDetail(e.data)?n(e.data):(Logger.warn("[mobile-support] an outbox reply was not a ticket; refreshing"),x())),changedQueue(e)===SUPPORT_REPLY_QUEUE&&E()})),[r,E,x,b]),useEffect(()=>{let e=null;const start=()=>{e??=setInterval(()=>{x()},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?(x(),start()):stop())});return()=>{r.remove(),stop()}},[x]);const C=useCallback(async e=>{g(!0),l(null);try{const t=await e();return m.current&&n(t),o(),!0}catch(e){return m.current&&l(toSupportApiError(e)),!1}finally{m.current&&g(!1)}},[o]),T=useCallback(async o=>{g(!0),l(null);try{const s=await sendThroughOutbox(r,SUPPORT_REPLY_QUEUE,o.body.slice(0,80),t.replyRequest(e,o));return m.current&&("Sent"===s.status&&n(s.ticket),"Failed"===s.status&&l(s.error)),s.status}finally{m.current&&g(!1)}},[r,t,e]),k=useCallback(()=>C(()=>t.reopen(e)),[C,t,e]),A=useCallback(()=>C(()=>t.cancel(e)),[C,t,e]),P=useCallback(r=>C(()=>t.rate(e,r)),[C,t,e]);return{ticket:s,loading:u,error:c,actionError:p,busy:f,pendingReplies:y,reload:h,reply:T,reopen:k,cancel:A,rate:P}};export const useSupportOutbox=e=>{const{outbox:t}=useSupportContext(),[r,o]=useState([]),s=useRef(!0);useEffect(()=>(s.current=!0,()=>{s.current=!1}),[]);const n=useCallback(async()=>{const r=await t.list(e);s.current&&o(r)},[t,e]);useEffect(()=>(n(),t.subscribe(t=>{changedQueue(t)===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{useOutboxEntries,useOutboxProgress}from"@webority/mobile-core/outbox";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),changedQueue=e=>{switch(e.type){case"changed":return e.queue;case"sent":case"failed":return e.entry.queue;case"progress":return null;default:return e}},isRecord=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),isStringArray=e=>Array.isArray(e)&&e.every(e=>"string"==typeof e),isCategoryArray=e=>Array.isArray(e)&&e.every(e=>isRecord(e)&&"string"==typeof e.name&&"string"==typeof e.queue),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:n,categories:u,maxAttachmentBytes:a,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!==n&&"string"!=typeof n||!isCategoryArray(u)||"number"!=typeof a||"number"!=typeof c||!isStringArray(i)||"number"!=typeof p||"number"!=typeof l||"number"!=typeof f?null:{productName:t,supportEmail:r,supportName:o,supportPhone:s,supportHours:n,categories:u,maxAttachmentBytes:a,maxAttachmentsPerMessage:c,allowedContentTypes:i,subjectMaxLength:p,bodyMaxLength:l,satisfactionCommentMaxLength:f}};export const SupportProvider=({client:e,outbox:t,openFile:r,timeZone:o,labels:s,children:n})=>{if(!t)throw new Error("[@webority/mobile-support] <SupportProvider> needs an outbox={...}, created with createOutbox from mobile-core.");const[u,a]=useState(null),[c,i]=useState(null),[p,l]=useState(!0),[f,g]=useState(0),y=useRef(new Map),m=useCallback(async()=>{l(!0);const t=`@webority/mobile-support/config:${e.basePath}`;try{const r=await e.getConfig();Storage.setItem(t,JSON.stringify(r)),a(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&&a(e)}}finally{l(!1)}},[e]);useEffect(()=>{y.current.clear(),m()},[m]);const d=useCallback(t=>{const r=y.current.get(t.id);if(void 0!==r)return r;const o=e.getAttachmentDataUri(t);return y.current.set(t.id,o),o.catch(()=>y.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(()=>g(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:u,configError:c,configLoading:p,reloadConfig:m,loadAttachment:d,openAttachment:S,timeZone:o,labels:s,revision:f,bumpRevision:b}),[e,t,u,c,p,m,d,S,o,s,f,b]);return _jsx(SupportContext.Provider,{value:E,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(),[s,n]=useState(null),[u,a]=useState(""),[c,i]=useState([]),[p,l]=useState(null),[f,g]=useState(0),[y,m]=useState(0),[d,S]=useState(!0),[b,E]=useState(!1),[h,x]=useState(!1),[C,T]=useState(null),[A,k]=useState(null),P=useRef(!0),R=useRef(0),U=useRef(!1),w=useRef(null);useEffect(()=>(P.current=!0,()=>{P.current=!1}),[]);const v=useCallback(e=>{const r=u.trim();return{...s?{status:s}:{},...r?{search:r}:{},page:e,pageSize:t}},[s,u,t]),_=useCallback(async e=>{R.current+=1;const t=R.current,current=()=>P.current&&t===R.current;U.current=!1,x(!1),"refresh"===e?E(!0):"replace"===e&&(S(!0),i([]));const o="replace"!==e||w.current!==r;try{const[e,t]=await Promise.all([r.listTickets(v(1)),o?r.getTicketCounts():null]);current()&&(i(e.items),g(e.page),m(e.totalPages),t&&(l(t),w.current=r),T(null),k(null))}catch(e){current()&&T(toSupportApiError(e))}finally{current()&&(S(!1),E(!1))}},[r,v]),O=useRef(o);useEffect(()=>{const e=O.current===o?"replace":"quiet";O.current=o,_(e)},[_,o]);const L=f<y,M=useCallback(async()=>{if(U.current||d||b||!L)return;const e=R.current,current=()=>P.current&&e===R.current;U.current=!0,x(!0),k(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))]}),g(e.page),m(e.totalPages))}catch(e){current()&&k(toSupportApiError(e))}finally{current()&&(U.current=!1,x(!1))}},[r,v,f,L,d,b]),q=useCallback(()=>_("refresh"),[_]),I=useCreateSupportTicket();return{tickets:c,counts:p,status:s,search:u,setStatus:n,setSearch:a,loading:d,refreshing:b,loadingMore:h,hasMore:L,error:C,loadMoreError:A,refresh:q,loadMore:M,createTicket:I}};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 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 SupportApiError(s.failure.code,s.failure.message,s.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])};export const useSupportUploadProgress=e=>useOutboxProgress(useSupportContext().outbox,e);const TICKET_REFRESH_MS=3e4;export const useSupportTicket=e=>{const{client:t,outbox:r,bumpRevision:o}=useSupportContext(),[s,n]=useState(null),[u,a]=useState(!0),[c,i]=useState(null),[p,l]=useState(null),[f,g]=useState(!1),[y,m]=useState([]),d=useRef(!0),S=useRef(!1),b=useMemo(()=>supportRepliesUrl(t.basePath,e),[t,e]);useEffect(()=>{S.current=f},[f]),useEffect(()=>(d.current=!0,()=>{d.current=!1}),[]);const E=useCallback(async()=>{const e=await r.list(SUPPORT_REPLY_QUEUE);d.current&&m(e.filter(e=>e.request.url===b))},[r,b]),h=useCallback(async()=>{a(!0);try{const r=await t.getTicket(e);d.current&&(n(r),i(null))}catch(e){d.current&&i(toSupportApiError(e))}finally{d.current&&a(!1)}},[t,e]);useEffect(()=>{h()},[h]);const x=useCallback(async()=>{if(!S.current)try{const r=await t.getTicket(e);d.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(()=>(E(),r.subscribe(e=>{"sent"===e.type&&e.entry.queue===SUPPORT_REPLY_QUEUE&&e.entry.request.url===b&&d.current&&(isSupportTicketDetail(e.data)?n(e.data):(Logger.warn("[mobile-support] an outbox reply was not a ticket; refreshing"),x())),changedQueue(e)===SUPPORT_REPLY_QUEUE&&E()})),[r,E,x,b]),useEffect(()=>{let e=null;const start=()=>{e??=setInterval(()=>{x()},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?(x(),start()):stop())});return()=>{r.remove(),stop()}},[x]);const C=useCallback(async e=>{g(!0),l(null);try{const t=await e();return d.current&&n(t),o(),!0}catch(e){return d.current&&l(toSupportApiError(e)),!1}finally{d.current&&g(!1)}},[o]),T=useCallback(async o=>{g(!0),l(null);try{const s=await sendThroughOutbox(r,SUPPORT_REPLY_QUEUE,o.body.slice(0,80),t.replyRequest(e,o));return d.current&&("Sent"===s.status&&n(s.ticket),"Failed"===s.status&&l(s.error)),s.status}finally{d.current&&g(!1)}},[r,t,e]),A=useCallback(()=>C(()=>t.reopen(e)),[C,t,e]),k=useCallback(()=>C(()=>t.cancel(e)),[C,t,e]),P=useCallback(r=>C(()=>t.rate(e,r)),[C,t,e]);return{ticket:s,loading:u,error:c,actionError:p,busy:f,pendingReplies:y,reload:h,reply:T,reopen:A,cancel:k,rate:P}};export const useSupportOutbox=e=>useOutboxEntries(useSupportContext().outbox,e);
@@ -1 +1 @@
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("queue",e.queue),...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
+ "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"]),parseCategory=(e,t)=>{const r=readObject(e,t);return{name:readString(r,"name",t),queue:readString(r,"queue",t)}},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:readList(r,"categories",t,parseCategory),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("queue",e.queue),...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{useNetworkStatus}from"@webority/mobile-core";import{Button,Input,KeyboardAwareScrollView,NetworkStatusBanner,Select,Spinner,Text,useHookFormField,useTheme}from"@webority/mobile-ui";import{useEffect,useMemo,useRef,useState}from"react";import{useForm}from"react-hook-form";import{StyleSheet,View}from"react-native";import{toSupportApiError}from"../client.js";import{describeDevice}from"../device.js";import{fillLabel,SHARED_LABELS}from"../labels.js";import{useCreateSupportTicket,useSupportClient,useSupportConfig,useSupportLabels,useSupportUploadProgress}from"../SupportProvider.js";import{subjectFromMessage}from"../subject.js";import{SUPPORT_TICKET_QUEUE}from"../types.js";import{validateBody,validateCategory,validateFiles,validateSubject}from"../validation.js";import{PhotoTray}from"./PhotoTray.js";import{SuggestedAnswers}from"./SuggestedAnswers.js";import{SupportUploadProgress}from"./SupportUploadProgress.js";import{jsx as _jsx,jsxs as _jsxs,Fragment as _Fragment}from"react/jsx-runtime";const LABELS={intro:"Tell us what you need. We reply by email and in this ticket.",messageLabel:"Message",messagePlaceholder:"What happened, and what did you expect?",subjectLabel:"Subject",subjectPlaceholder:"A short summary",subjectHelper:"Filled in from your message. You can change it.",categoryLabel:"Category (optional)",categoryPlaceholder:"Choose a category",categoryHelper:"Not sure? Leave it empty and we will sort it.",screenshotLabel:"Screenshot",photosLabel:"Photos",photoLimit:"Add up to {count} photos.",cancel:"Cancel",send:"Send ticket",loading:"Loading",retry:"Try again",unavailable:"Support is not available right now."},SUGGESTION_PAUSE_MS=500,SUGGESTION_MIN_CHARS=3,TicketForm=({config:e,styles:t,onCreated:o,onQueued:s,onCancel:r,initialDraft:a,defaultCategory:l,appVersion:n,queue:i})=>{const u=useSupportLabels("newTicket",LABELS),c=useSupportLabels("shared",SHARED_LABELS),p=useCreateSupportTicket(),d=useSupportClient(),{isConnected:g,isInternetReachable:m}=useNetworkStatus(),b=!g||!1===m,[h,y]=useState([]),listed=t=>t&&e.categories.includes(t)?t:void 0,[S,j]=useState([]),[x,f]=useState(a?.screenshots??[]),[v,L]=useState(null),[w,T]=useState(null),_=useRef(Boolean(a?.subject?.trim())&&a?.subject!==subjectFromMessage(a?.body??"",e.subjectMaxLength)),C=useForm({defaultValues:{category:listed(a?.category)??listed(l)??"",subject:a?.subject||subjectFromMessage(a?.body??"",e.subjectMaxLength),body:a?.body??""}}),P=C.handleSubmit(async t=>{const r=validateFiles([...x,...S],e,c);if(L(r??null),r)return;T(null);const l=a?.queue??i;try{const r=await p({category:t.category,subject:t.subject.trim()||subjectFromMessage(t.body,e.subjectMaxLength),body:t.body.trim(),pageUrl:a?.pageUrl,userAgent:a?.userAgent??describeDevice(),appVersion:a?.appVersion??n,...void 0===l?{}:{queue:l},files:S,screenshots:x});"Sent"===r.status?o(r.ticket):"Queued"===r.status?s(r.entry):T(r.error.message)}catch(e){T(toSupportApiError(e).message)}}),A=C.formState.isSubmitting,F=useSupportUploadProgress(SUPPORT_TICKET_QUEUE),B=useHookFormField({control:C.control,name:"category",rules:{validate:t=>validateCategory(t,e,c)}}),E=useHookFormField({control:C.control,name:"subject",rules:{validate:t=>""===t.trim()?void 0:validateSubject(t,e,c)}}),k=useHookFormField({control:C.control,name:"body",rules:{validate:t=>validateBody(t,e,c)}}),I=x.length+S.length;useEffect(()=>{v&&L(validateFiles([...x,...S],e,c)??null)},[S,x,v,e,c]);const M=E.value.trim();return useEffect(()=>{if(b||M.length<3)return void y([]);let e=!0;const t=setTimeout(async()=>{try{const t=await(d.getSuggestions?.(M))??[];e&&y(t)}catch{e&&y([])}},500);return()=>{e=!1,clearTimeout(t)}},[d,M,b]),_jsxs(KeyboardAwareScrollView,{contentContainerStyle:t.content,safeAreaEdges:[],children:[_jsx(Text,{variant:"bodySmall",color:"secondary",children:u.intro}),_jsx(Input,{label:u.messageLabel,placeholder:u.messagePlaceholder,required:!0,multiline:!0,maxLength:e.bodyMaxLength,value:k.value,onChangeText:t=>{k.onChangeText(t),_.current||C.setValue("subject",subjectFromMessage(t,e.subjectMaxLength))},onBlur:k.onBlur,error:k.error,testID:"support-new-body"}),_jsx(Input,{label:u.subjectLabel,placeholder:u.subjectPlaceholder,helperText:u.subjectHelper,maxLength:e.subjectMaxLength,value:E.value,onChangeText:e=>{_.current=""!==e.trim(),E.onChangeText(e)},onBlur:E.onBlur,error:E.error,testID:"support-new-subject"}),h.length>0&&_jsx(SuggestedAnswers,{articles:h,testID:"support-new-suggestions"}),_jsx(Select,{label:u.categoryLabel,placeholder:u.categoryPlaceholder,helperText:u.categoryHelper,options:e.categories.map(e=>({label:e,value:e})),value:B.value||void 0,onChange:e=>B.onChange(String(e)),error:B.error,testID:"support-new-category"}),x.length>0&&_jsx(PhotoTray,{label:u.screenshotLabel,photos:x,onChange:f,remaining:0,allowAdd:!1,maxBytes:e.maxAttachmentBytes,disabled:A}),_jsx(PhotoTray,{label:u.photosLabel,helperText:fillLabel(u.photoLimit,{count:e.maxAttachmentsPerMessage}),photos:S,onChange:j,remaining:e.maxAttachmentsPerMessage-I,maxBytes:e.maxAttachmentBytes,disabled:A}),A&&_jsx(SupportUploadProgress,{progress:F,testID:"support-new-progress"}),(v||w)&&_jsx(Text,{variant:"bodySmall",color:"danger",accessibilityLiveRegion:"polite",children:v??w}),_jsxs(View,{style:t.actions,children:[r&&_jsx(Button,{label:u.cancel,variant:"ghost",tone:"neutral",onPress:r,disabled:A}),_jsx(Button,{label:u.send,loading:A,disabled:A,onPress:()=>{P()},testID:"support-new-submit"})]})]})};export const NewSupportTicket=e=>{const t=useSupportLabels("newTicket",LABELS),o=useTheme(),s=useMemo(()=>buildStyles(o),[o]),{config:r,loading:a,error:l,reload:n}=useSupportConfig(),i=e.testID??"support-new-ticket";return r?_jsxs(View,{style:s.root,testID:i,children:[_jsx(NetworkStatusBanner,{}),_jsx(TicketForm,{...e,config:r,styles:s})]}):_jsx(View,{style:s.center,testID:i,children:a?_jsx(Spinner,{accessibilityLabel:t.loading}):_jsxs(_Fragment,{children:[_jsx(Text,{variant:"body",color:"danger",align:"center",children:l?.message??t.unavailable}),_jsx(Button,{label:t.retry,variant:"ghost",onPress:()=>{n()}})]})})};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},actions:{flexDirection:"row",justifyContent:"flex-end",gap:e.space.sm}});
1
+ "use strict";import{useNetworkStatus}from"@webority/mobile-core";import{Button,Input,KeyboardAwareScrollView,NetworkStatusBanner,Select,Spinner,Text,useHookFormField,useTheme}from"@webority/mobile-ui";import{useEffect,useMemo,useRef,useState}from"react";import{useForm}from"react-hook-form";import{StyleSheet,View}from"react-native";import{toSupportApiError}from"../client.js";import{describeDevice}from"../device.js";import{fillLabel,SHARED_LABELS}from"../labels.js";import{useCreateSupportTicket,useSupportClient,useSupportConfig,useSupportLabels,useSupportUploadProgress}from"../SupportProvider.js";import{subjectFromMessage}from"../subject.js";import{SUPPORT_TICKET_QUEUE}from"../types.js";import{categoryNames,validateBody,validateCategory,validateFiles,validateSubject}from"../validation.js";import{PhotoTray}from"./PhotoTray.js";import{SuggestedAnswers}from"./SuggestedAnswers.js";import{SupportUploadProgress}from"./SupportUploadProgress.js";import{jsx as _jsx,jsxs as _jsxs,Fragment as _Fragment}from"react/jsx-runtime";const LABELS={intro:"Tell us what you need. We reply by email and in this ticket.",messageLabel:"Message",messagePlaceholder:"What happened, and what did you expect?",subjectLabel:"Subject",subjectPlaceholder:"A short summary",subjectHelper:"Filled in from your message. You can change it.",categoryLabel:"Category (optional)",categoryPlaceholder:"Choose a category",categoryHelper:"Not sure? Leave it empty and we will sort it.",screenshotLabel:"Screenshot",photosLabel:"Photos",photoLimit:"Add up to {count} photos.",cancel:"Cancel",send:"Send ticket",loading:"Loading",retry:"Try again",unavailable:"Support is not available right now."},SUGGESTION_PAUSE_MS=500,SUGGESTION_MIN_CHARS=3,TicketForm=({config:e,styles:t,onCreated:o,onQueued:s,onCancel:r,initialDraft:a,defaultCategory:l,appVersion:n,queue:i})=>{const u=useSupportLabels("newTicket",LABELS),c=useSupportLabels("shared",SHARED_LABELS),p=useCreateSupportTicket(),d=useSupportClient(),{isConnected:g,isInternetReachable:m}=useNetworkStatus(),b=!g||!1===m,[h,y]=useState([]),listed=t=>t&&categoryNames(e,i).includes(t)?t:void 0,[S,j]=useState([]),[x,f]=useState(a?.screenshots??[]),[v,L]=useState(null),[w,T]=useState(null),_=useRef(Boolean(a?.subject?.trim())&&a?.subject!==subjectFromMessage(a?.body??"",e.subjectMaxLength)),C=useForm({defaultValues:{category:listed(a?.category)??listed(l)??"",subject:a?.subject||subjectFromMessage(a?.body??"",e.subjectMaxLength),body:a?.body??""}}),P=C.handleSubmit(async t=>{const r=validateFiles([...x,...S],e,c);if(L(r??null),r)return;T(null);const l=a?.queue??i;try{const r=await p({category:t.category,subject:t.subject.trim()||subjectFromMessage(t.body,e.subjectMaxLength),body:t.body.trim(),pageUrl:a?.pageUrl,userAgent:a?.userAgent??describeDevice(),appVersion:a?.appVersion??n,...void 0===l?{}:{queue:l},files:S,screenshots:x});"Sent"===r.status?o(r.ticket):"Queued"===r.status?s(r.entry):T(r.error.message)}catch(e){T(toSupportApiError(e).message)}}),A=C.formState.isSubmitting,F=useSupportUploadProgress(SUPPORT_TICKET_QUEUE),B=useHookFormField({control:C.control,name:"category",rules:{validate:t=>validateCategory(t,e,c,i)}}),E=useHookFormField({control:C.control,name:"subject",rules:{validate:t=>""===t.trim()?void 0:validateSubject(t,e,c)}}),k=useHookFormField({control:C.control,name:"body",rules:{validate:t=>validateBody(t,e,c)}}),I=x.length+S.length;useEffect(()=>{v&&L(validateFiles([...x,...S],e,c)??null)},[S,x,v,e,c]);const M=E.value.trim();return useEffect(()=>{if(b||M.length<3)return void y([]);let e=!0;const t=setTimeout(async()=>{try{const t=await(d.getSuggestions?.(M))??[];e&&y(t)}catch{e&&y([])}},500);return()=>{e=!1,clearTimeout(t)}},[d,M,b]),_jsxs(KeyboardAwareScrollView,{contentContainerStyle:t.content,safeAreaEdges:[],children:[_jsx(Text,{variant:"bodySmall",color:"secondary",children:u.intro}),_jsx(Input,{label:u.messageLabel,placeholder:u.messagePlaceholder,required:!0,multiline:!0,maxLength:e.bodyMaxLength,value:k.value,onChangeText:t=>{k.onChangeText(t),_.current||C.setValue("subject",subjectFromMessage(t,e.subjectMaxLength))},onBlur:k.onBlur,error:k.error,testID:"support-new-body"}),_jsx(Input,{label:u.subjectLabel,placeholder:u.subjectPlaceholder,helperText:u.subjectHelper,maxLength:e.subjectMaxLength,value:E.value,onChangeText:e=>{_.current=""!==e.trim(),E.onChangeText(e)},onBlur:E.onBlur,error:E.error,testID:"support-new-subject"}),h.length>0&&_jsx(SuggestedAnswers,{articles:h,testID:"support-new-suggestions"}),_jsx(Select,{label:u.categoryLabel,placeholder:u.categoryPlaceholder,helperText:u.categoryHelper,options:categoryNames(e,i).map(e=>({label:e,value:e})),value:B.value||void 0,onChange:e=>B.onChange(String(e)),error:B.error,testID:"support-new-category"}),x.length>0&&_jsx(PhotoTray,{label:u.screenshotLabel,photos:x,onChange:f,remaining:0,allowAdd:!1,maxBytes:e.maxAttachmentBytes,disabled:A}),_jsx(PhotoTray,{label:u.photosLabel,helperText:fillLabel(u.photoLimit,{count:e.maxAttachmentsPerMessage}),photos:S,onChange:j,remaining:e.maxAttachmentsPerMessage-I,maxBytes:e.maxAttachmentBytes,disabled:A}),A&&_jsx(SupportUploadProgress,{progress:F,testID:"support-new-progress"}),(v||w)&&_jsx(Text,{variant:"bodySmall",color:"danger",accessibilityLiveRegion:"polite",children:v??w}),_jsxs(View,{style:t.actions,children:[r&&_jsx(Button,{label:u.cancel,variant:"ghost",tone:"neutral",onPress:r,disabled:A}),_jsx(Button,{label:u.send,loading:A,disabled:A,onPress:()=>{P()},testID:"support-new-submit"})]})]})};export const NewSupportTicket=e=>{const t=useSupportLabels("newTicket",LABELS),o=useTheme(),s=useMemo(()=>buildStyles(o),[o]),{config:r,loading:a,error:l,reload:n}=useSupportConfig(),i=e.testID??"support-new-ticket";return r?_jsxs(View,{style:s.root,testID:i,children:[_jsx(NetworkStatusBanner,{}),_jsx(TicketForm,{...e,config:r,styles:s})]}):_jsx(View,{style:s.center,testID:i,children:a?_jsx(Spinner,{accessibilityLabel:t.loading}):_jsxs(_Fragment,{children:[_jsx(Text,{variant:"body",color:"danger",align:"center",children:l?.message??t.unavailable}),_jsx(Button,{label:t.retry,variant:"ghost",onPress:()=>{n()}})]})})};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},actions:{flexDirection:"row",justifyContent:"flex-end",gap:e.space.sm}});
@@ -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,useSupportUploadProgress}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{SupportUploadProgress}from"./SupportUploadProgress.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 o="Customer"===e.authorKind;return _jsx(View,{style:[t.bubbleRow,o?t.mineRow:t.theirsRow],testID:`support-message-${e.id}`,children:_jsxs(View,{style:[t.bubble,o?t.mine:t.theirs],children:[_jsx(Text,{variant:"label",color:o?"primary":"secondary",children:e.authorName??(o?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;switch(t.kind){case"json":{const e=t.value;return"object"==typeof e&&null!==e&&"body"in e&&"string"==typeof e.body?e.body:""}case"multipart":{const e=t.fields.find(e=>"body"===e.name);return e&&"value"in e?e.value:""}case"resumable":return"";default:return t}},PendingReplyBubble=({entry:e,styles:t,labels:s,onSendNow:a,onDiscard:i})=>{const o="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:o?"danger":"tertiary",accessibilityLiveRegion:"polite",children:o?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),o=useTheme(),r=useMemo(()=>buildStyles(o),[o]),{config:n}=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=useSupportUploadProgress(SUPPORT_REPLY_QUEUE),[T,_]=useState(null),[f,v]=useState(""),[D,L]=useState([]),[R,I]=useState(!1),[C,P]=useState(null),[k,B]=useState(null),[U,A]=useState(""),[E,O]=useState(!1);if(!d)return _jsx(View,{style:r.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 V={Satisfied:a.satisfied,Unsatisfied:a.unsatisfied},z=d.mergedInto,M=d.messages.filter(e=>!e.isInternal),$=d.updatedDateTimeUtc!==d.createdDateTimeUtc,F=C??u?.message??null,Y=Boolean(n)&&(R||D.length>0),N=Y||F||d.canReopen||m?_jsxs(_Fragment,{children:[m&&_jsx(SupportUploadProgress,{progress:w,testID:"support-reply-progress"}),Y&&n&&_jsx(PhotoTray,{photos:D,onChange:e=>{L(e),P(null)},remaining:n.maxAttachmentsPerMessage-D.length,maxBytes:n.maxAttachmentBytes,disabled:m}),F&&_jsx(Text,{variant:"bodySmall",color:"danger",accessibilityLiveRegion:"polite",children:F}),d.canReopen&&_jsx(Text,{variant:"caption",color:"secondary",children:a.replyReopens})]}):void 0;return _jsxs(View,{style:r.root,testID:s,children:[_jsxs(KeyboardAwareScrollView,{contentContainerStyle:r.content,safeAreaEdges:[],children:[_jsxs(View,{style:r.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:r.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})})}),$&&_jsx(Text,{variant:"caption",color:"tertiary",children:fillLabel(a.updated,{date:formatDateTime(d.updatedDateTimeUtc,{zone:l})})})]})]}),z&&_jsxs(Card,{variant:"outline",bodyStyle:r.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:r.section,testID:"support-waiting",children:_jsx(Text,{variant:"bodySmall",children:a.waitingText})}),d.canReopen&&_jsxs(Card,{variant:"outline",bodyStyle:r.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:r.section,children:[_jsx(Button,{label:a.withdraw,variant:"outline",size:"sm",loading:m,disabled:m,onPress:()=>O(!0),testID:"support-withdraw"}),_jsx(Dialog,{open:E,onClose:()=>O(!1),title:a.withdrawTitle,message:a.withdrawMessage,tone:"danger",actions:[{label:a.withdrawCancel,onPress:()=>O(!1),tone:"neutral"},{label:a.withdrawConfirm,onPress:()=>{x()},tone:"danger"}]})]}),d.satisfaction?_jsxs(Card,{variant:"outline",bodyStyle:r.section,testID:"support-rating",children:[_jsx(Text,{variant:"bodySmall",accessibilityLiveRegion:"polite",children:V[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:r.section,testID:"support-rating",children:[_jsx(Text,{variant:"label",children:a.ratingQuestion}),_jsxs(View,{style:r.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:U,onChangeText:A,multiline:!0,maxLength:n?.satisfactionCommentMaxLength,testID:"support-rating-comment"}),_jsx(Button,{label:a.sendAnswer,size:"sm",loading:m,disabled:m,onPress:()=>{(async()=>{k&&await S({satisfaction:k,comment:U})&&(B(null),A(""))})()},testID:"support-rating-send"})]})]}):null,_jsxs(View,{style:r.thread,accessibilityLabel:a.conversation,children:[M.map(e=>_jsx(MessageBubble,{message:e,styles:r,timeZone:l,labels:a,onOpenImage:(e,t)=>_({uri:e,name:t})},e.id)),b.map(e=>_jsx(PendingReplyBubble,{entry:e,styles:r,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:r.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:r.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=>{v(e),P(null)},onSend:e=>{(async e=>{const t=e.trim(),s=n?validateBody(t,n,i)??validateFiles(D,n,i):t?void 0:a.writeMessage;if(s)return P(s),void v(e);"Failed"!==await g({body:t,files:D})?(L([]),I(!1)):v(e)})(e)},loading:m,maxLength:n?.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||!n,onPress:()=>I(e=>!e),testID:"support-reply-attach"}),above:N,testID:"support-reply-composer"}),_jsx(ImageViewer,{image:T,onClose:()=>_(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,useSupportUploadProgress}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{SupportUploadProgress}from"./SupportUploadProgress.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 o="Customer"===e.authorKind;return _jsx(View,{style:[t.bubbleRow,o?t.mineRow:t.theirsRow],testID:`support-message-${e.id}`,children:_jsxs(View,{style:[t.bubble,o?t.mine:t.theirs],children:[_jsx(Text,{variant:"label",color:o?"primary":"secondary",children:e.authorName??(o?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;switch(t.kind){case"json":{const e=t.value;return"object"==typeof e&&null!==e&&"body"in e&&"string"==typeof e.body?e.body:""}case"multipart":{const e=t.fields.find(e=>"body"===e.name);return e&&"value"in e?e.value:""}case"resumable":return"";default:return t}},PendingReplyBubble=({entry:e,styles:t,labels:s,onSendNow:a,onDiscard:i})=>{const o="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:o?"danger":"tertiary",accessibilityLiveRegion:"polite",children:o?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),o=useTheme(),r=useMemo(()=>buildStyles(o),[o]),{config:n}=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=useSupportUploadProgress(SUPPORT_REPLY_QUEUE),[T,_]=useState(null),[f,v]=useState(""),[D,L]=useState([]),[R,I]=useState(!1),[C,P]=useState(null),[k,B]=useState(null),[U,A]=useState(""),[E,O]=useState(!1);if(!d)return _jsx(View,{style:r.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 V={Satisfied:a.satisfied,Unsatisfied:a.unsatisfied},z=d.mergedInto,M=d.messages.filter(e=>!e.isInternal),$=d.updatedDateTimeUtc!==d.createdDateTimeUtc,F=C??u?.message??j.error?.message??null,Y=Boolean(n)&&(R||D.length>0),N=Y||F||d.canReopen||m?_jsxs(_Fragment,{children:[m&&_jsx(SupportUploadProgress,{progress:w,testID:"support-reply-progress"}),Y&&n&&_jsx(PhotoTray,{photos:D,onChange:e=>{L(e),P(null)},remaining:n.maxAttachmentsPerMessage-D.length,maxBytes:n.maxAttachmentBytes,disabled:m}),F&&_jsx(Text,{variant:"bodySmall",color:"danger",accessibilityLiveRegion:"polite",children:F}),d.canReopen&&_jsx(Text,{variant:"caption",color:"secondary",children:a.replyReopens})]}):void 0;return _jsxs(View,{style:r.root,testID:s,children:[_jsxs(KeyboardAwareScrollView,{contentContainerStyle:r.content,safeAreaEdges:[],children:[_jsxs(View,{style:r.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:r.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})})}),$&&_jsx(Text,{variant:"caption",color:"tertiary",children:fillLabel(a.updated,{date:formatDateTime(d.updatedDateTimeUtc,{zone:l})})})]})]}),z&&_jsxs(Card,{variant:"outline",bodyStyle:r.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:r.section,testID:"support-waiting",children:_jsx(Text,{variant:"bodySmall",children:a.waitingText})}),d.canReopen&&_jsxs(Card,{variant:"outline",bodyStyle:r.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:r.section,children:[_jsx(Button,{label:a.withdraw,variant:"outline",size:"sm",loading:m,disabled:m,onPress:()=>O(!0),testID:"support-withdraw"}),_jsx(Dialog,{open:E,onClose:()=>O(!1),title:a.withdrawTitle,message:a.withdrawMessage,tone:"danger",actions:[{label:a.withdrawCancel,onPress:()=>O(!1),tone:"neutral"},{label:a.withdrawConfirm,onPress:()=>{x()},tone:"danger"}]})]}),d.satisfaction?_jsxs(Card,{variant:"outline",bodyStyle:r.section,testID:"support-rating",children:[_jsx(Text,{variant:"bodySmall",accessibilityLiveRegion:"polite",children:V[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:r.section,testID:"support-rating",children:[_jsx(Text,{variant:"label",children:a.ratingQuestion}),_jsxs(View,{style:r.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:U,onChangeText:A,multiline:!0,maxLength:n?.satisfactionCommentMaxLength,testID:"support-rating-comment"}),_jsx(Button,{label:a.sendAnswer,size:"sm",loading:m,disabled:m,onPress:()=>{(async()=>{k&&await S({satisfaction:k,comment:U})&&(B(null),A(""))})()},testID:"support-rating-send"})]})]}):null,_jsxs(View,{style:r.thread,accessibilityLabel:a.conversation,children:[M.map(e=>_jsx(MessageBubble,{message:e,styles:r,timeZone:l,labels:a,onOpenImage:(e,t)=>_({uri:e,name:t})},e.id)),b.map(e=>_jsx(PendingReplyBubble,{entry:e,styles:r,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:r.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:r.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=>{v(e),P(null)},onSend:e=>{(async e=>{const t=e.trim(),s=n?validateBody(t,n,i)??validateFiles(D,n,i):t?void 0:a.writeMessage;if(s)return P(s),void v(e);"Failed"!==await g({body:t,files:D})?(L([]),I(!1)):v(e)})(e)},loading:m,maxLength:n?.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||!n,onPress:()=>I(e=>!e),testID:"support-reply-attach"}),above:N,testID:"support-reply-composer"}),_jsx(ImageViewer,{image:T,onClose:()=>_(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{formatDateTime}from"@webority/mobile-core";import{Button,Card,Chip,confirm,EmptyState,SearchBar,Spinner,StatusBadge,Text,useTheme}from"@webority/mobile-ui";import{memo,useCallback,useMemo}from"react";import{FlatList,RefreshControl,ScrollView,StyleSheet,View}from"react-native";import{fillLabel}from"../labels.js";import{useSupportLabels,useSupportOutbox,useSupportTickets,useSupportTimeZone}from"../SupportProvider.js";import{SUPPORT_TICKET_QUEUE}from"../types.js";import{jsx as _jsx,jsxs as _jsxs,Fragment as _Fragment}from"react/jsx-runtime";const LABELS={outboxFailed:"We could not send this report. Try again.",waitingToSend:"Waiting to send",sendNow:"Send now",discard:"Discard",discardTitle:"Discard this report?",discardText:"It has not been sent.",updated:"Updated {date}",newTicket:"New ticket",retry:"Try again",searchPlaceholder:"Search by subject or ticket number",searchLabel:"Search tickets",filterLabel:"Filter by status",all:"All",ticketAccessibility:"{subject}, {status}, ticket {number}",chipAccessibility:"{label}, {count} tickets",loadingTickets:"Loading your tickets",emptyTitle:"No tickets yet",emptyText:"Raise a ticket and it will show here with its status.",noMatchTitle:"No tickets match",noMatchText:"Try another status or search.",loadingMore:"Loading more tickets",loadMore:"Load more"};export const STATUS_TONES={Open:"info",InProgress:"info",WaitingOnCustomer:"warning",Resolved:"success",Closed:"success",Cancelled:"neutral"};const STATUS_FILTERS=[{value:"Open",label:"Open",count:"open"},{value:"NeedsReply",label:"Needs your reply",count:"needsReply"},{value:"Resolved",label:"Resolved",count:"resolved"},{value:"Withdrawn",label:"Withdrawn",count:"withdrawn"}],ALL="all";export const statusFilterOptions=(e,t,s=LABELS.all)=>[{value:ALL,label:s,count:e.total},...STATUS_FILTERS.filter(s=>e[s.count]>0||s.value===t).map(t=>({value:t.value,label:t.label,count:e[t.count]}))];const chipLabel=e=>void 0===e.count?e.label:`${e.label} (${e.count})`,SEARCH_DEBOUNCE_MS=400,ticketKey=e=>e.id,OutboxRow=memo(function OutboxRow({entry:e,onRetry:t,onDiscard:s,styles:i,t:a}){const o="Failed"===e.state;return _jsxs(Card,{bodyStyle:i.card,testID:`support-outbox-${e.id}`,children:[_jsx(Text,{variant:"title",numberOfLines:2,children:e.label}),_jsx(Text,{variant:"bodySmall",color:o?"danger":"secondary",children:o?e.lastFailure?.message??a.outboxFailed:a.waitingToSend}),_jsxs(View,{style:i.outboxActions,children:[_jsx(Button,{label:a.sendNow,size:"sm",variant:"ghost",onPress:()=>{t(e.id)},testID:`support-outbox-retry-${e.id}`}),_jsx(Button,{label:a.discard,size:"sm",variant:"ghost",tone:"danger",onPress:()=>{s(e)},testID:`support-outbox-discard-${e.id}`})]})]})}),TicketRow=memo(function TicketRow({item:e,timeZone:t,onOpen:s,styles:i,t:a}){return _jsxs(Card,{onPress:()=>s(e),accessibilityLabel:fillLabel(a.ticketAccessibility,{subject:e.subject,status:e.statusLabel,number:e.number}),bodyStyle:i.card,testID:`support-ticket-${e.id}`,children:[_jsxs(View,{style:i.cardTop,children:[_jsx(Text,{variant:"caption",color:"tertiary",children:e.number}),_jsx(StatusBadge,{label:e.statusLabel,tone:STATUS_TONES[e.status]??"neutral",size:"sm"})]}),_jsx(Text,{variant:"title",numberOfLines:2,children:e.subject}),_jsx(Text,{variant:"bodySmall",color:"secondary",children:e.category}),_jsx(View,{style:i.cardBottom,children:_jsx(Text,{variant:"caption",color:"tertiary",children:fillLabel(a.updated,{date:formatDateTime(e.updatedDateTimeUtc,{zone:t})})})})]})});export const SupportTicketList=({onOpenTicket:e,onNewTicket:t,header:s,pageSize:i,testID:a="support-ticket-list"})=>{const o=useSupportLabels("ticketList",LABELS),r=useTheme(),l=useMemo(()=>buildStyles(r),[r]),{tickets:n,counts:c,status:d,search:u,setStatus:p,setSearch:b,loading:m,refreshing:x,loadingMore:y,error:h,loadMoreError:T,refresh:S,loadMore:g}=useSupportTickets(void 0===i?{}:{pageSize:i}),j=useSupportTimeZone(),{entries:_,retry:f,discard:L}=useSupportOutbox(SUPPORT_TICKET_QUEUE),w=useCallback(async e=>{await confirm({title:o.discardTitle,message:o.discardText,confirmLabel:o.discard,tone:"danger"})&&await L(e.id)},[L,o]),v=useCallback(({item:t})=>_jsx(TicketRow,{item:t,timeZone:j,onOpen:e,styles:l,t:o}),[j,e,l,o]),k=useCallback(()=>{g()},[g]),C=useCallback(()=>{S()},[S]),R=useMemo(()=>_jsx(RefreshControl,{refreshing:x,onRefresh:C}),[x,C]),E=(c?.total??0)>0,I=null!==d||""!==u.trim(),O=!m&&!h&&!E,D=_jsxs(View,{style:l.header,children:[t&&!O&&_jsx(Button,{label:o.newTicket,leftIcon:"add",onPress:t,fullWidth:!0}),s,_.map(e=>_jsx(OutboxRow,{entry:e,onRetry:f,onDiscard:w,styles:l,t:o},e.id)),h&&_jsxs(View,{style:l.error,accessibilityLiveRegion:"polite",children:[_jsx(Text,{variant:"bodySmall",color:"danger",children:h.message}),_jsx(Button,{label:o.retry,size:"sm",variant:"ghost",onPress:()=>{S()}})]}),c&&E&&_jsxs(_Fragment,{children:[_jsx(SearchBar,{value:u,onChangeText:b,debounceMs:400,placeholder:o.searchPlaceholder,accessibilityLabel:o.searchLabel,testID:"support-ticket-search"}),_jsx(ScrollView,{horizontal:!0,showsHorizontalScrollIndicator:!1,contentContainerStyle:l.filters,accessibilityRole:"tablist",accessibilityLabel:o.filterLabel,children:statusFilterOptions(c,d,o.all).map(e=>_jsx(Chip,{label:chipLabel(e),selected:(d??ALL)===e.value,onPress:()=>p(e.value===ALL?null:e.value),accessibilityLabel:void 0===e.count?e.label:fillLabel(o.chipAccessibility,{label:e.label,count:e.count}),testID:`support-filter-${e.value}`},e.value))})]})]});if(m&&null===c&&!h)return _jsxs(View,{style:[l.content,{flex:1}],testID:a,children:[_.map(e=>_jsx(OutboxRow,{entry:e,onRetry:f,onDiscard:w,styles:l,t:o},e.id)),_jsx(View,{style:l.center,children:_jsx(Spinner,{accessibilityLabel:o.loadingTickets})})]});const A=y?_jsx(View,{style:l.footer,children:_jsx(Spinner,{size:"sm",accessibilityLabel:o.loadingMore})}):T?_jsxs(View,{style:[l.footer,l.error],accessibilityLiveRegion:"polite",children:[_jsx(Text,{variant:"bodySmall",color:"danger",children:T.message}),_jsx(Button,{label:o.loadMore,size:"sm",variant:"ghost",onPress:()=>{g()}})]}):void 0;return _jsx(FlatList,{testID:a,data:n,keyExtractor:ticketKey,contentContainerStyle:l.content,ListHeaderComponent:D,ListFooterComponent:A,onEndReached:k,onEndReachedThreshold:.5,refreshControl:R,ListEmptyComponent:m?_jsx(View,{style:l.footer,children:_jsx(Spinner,{accessibilityLabel:o.loadingTickets})}):h?void 0:_jsx(EmptyState,E?{title:o.noMatchTitle,description:I?o.noMatchText:void 0}:{title:o.emptyTitle,description:o.emptyText,action:t?{label:o.newTicket,onPress:t}:void 0}),renderItem:v})};const buildStyles=e=>StyleSheet.create({content:{padding:e.space.md,gap:e.space.sm},header:{gap:e.space.sm,marginBottom:e.space.xs},filters:{gap:e.space.xs},error:{gap:e.space.xs,alignItems:"flex-start"},center:{flex:1,alignItems:"center",justifyContent:"center",padding:e.space.xl},footer:{paddingVertical:e.space.md,alignItems:"center"},card:{gap:e.space.xxs},outboxActions:{flexDirection:"row",gap:e.space.xs,marginTop:e.space.xxs},cardTop:{flexDirection:"row",justifyContent:"space-between",alignItems:"center"},cardBottom:{flexDirection:"row",justifyContent:"space-between",marginTop:e.space.xxs}});
1
+ "use strict";import{formatDateTime}from"@webority/mobile-core";import{Button,Card,Chip,EmptyState,OutboxEntryList,SearchBar,Spinner,StatusBadge,Text,useTheme}from"@webority/mobile-ui";import{memo,useCallback,useMemo}from"react";import{FlatList,RefreshControl,ScrollView,StyleSheet,View}from"react-native";import{fillLabel}from"../labels.js";import{useSupportLabels,useSupportOutbox,useSupportTickets,useSupportTimeZone}from"../SupportProvider.js";import{SUPPORT_TICKET_QUEUE}from"../types.js";import{jsx as _jsx,jsxs as _jsxs,Fragment as _Fragment}from"react/jsx-runtime";const LABELS={outboxFailed:"We could not send this report. Try again.",waitingToSend:"Waiting to send",sendNow:"Send now",discard:"Discard",discardTitle:"Discard this report?",discardText:"It has not been sent.",updated:"Updated {date}",newTicket:"New ticket",retry:"Try again",searchPlaceholder:"Search by subject or ticket number",searchLabel:"Search tickets",filterLabel:"Filter by status",all:"All",ticketAccessibility:"{subject}, {status}, ticket {number}",chipAccessibility:"{label}, {count} tickets",loadingTickets:"Loading your tickets",emptyTitle:"No tickets yet",emptyText:"Raise a ticket and it will show here with its status.",noMatchTitle:"No tickets match",noMatchText:"Try another status or search.",loadingMore:"Loading more tickets",loadMore:"Load more"};export const STATUS_TONES={Open:"info",InProgress:"info",WaitingOnCustomer:"warning",Resolved:"success",Closed:"success",Cancelled:"neutral"};const STATUS_FILTERS=[{value:"Open",label:"Open",count:"open"},{value:"NeedsReply",label:"Needs your reply",count:"needsReply"},{value:"Resolved",label:"Resolved",count:"resolved"},{value:"Withdrawn",label:"Withdrawn",count:"withdrawn"}],ALL="all";export const statusFilterOptions=(e,t,s=LABELS.all)=>[{value:ALL,label:s,count:e.total},...STATUS_FILTERS.filter(s=>e[s.count]>0||s.value===t).map(t=>({value:t.value,label:t.label,count:e[t.count]}))];const chipLabel=e=>void 0===e.count?e.label:`${e.label} (${e.count})`,SEARCH_DEBOUNCE_MS=400,ticketKey=e=>e.id,TicketRow=memo(function TicketRow({item:e,timeZone:t,onOpen:s,styles:i,t:a}){return _jsxs(Card,{onPress:()=>s(e),accessibilityLabel:fillLabel(a.ticketAccessibility,{subject:e.subject,status:e.statusLabel,number:e.number}),bodyStyle:i.card,testID:`support-ticket-${e.id}`,children:[_jsxs(View,{style:i.cardTop,children:[_jsx(Text,{variant:"caption",color:"tertiary",children:e.number}),_jsx(StatusBadge,{label:e.statusLabel,tone:STATUS_TONES[e.status]??"neutral",size:"sm"})]}),_jsx(Text,{variant:"title",numberOfLines:2,children:e.subject}),_jsx(Text,{variant:"bodySmall",color:"secondary",children:e.category}),_jsx(View,{style:i.cardBottom,children:_jsx(Text,{variant:"caption",color:"tertiary",children:fillLabel(a.updated,{date:formatDateTime(e.updatedDateTimeUtc,{zone:t})})})})]})});export const SupportTicketList=({onOpenTicket:e,onNewTicket:t,header:s,pageSize:i,testID:a="support-ticket-list"})=>{const r=useSupportLabels("ticketList",LABELS),o=useTheme(),l=useMemo(()=>buildStyles(o),[o]),{tickets:n,counts:c,status:d,search:u,setStatus:p,setSearch:b,loading:m,refreshing:h,loadingMore:x,error:y,loadMoreError:T,refresh:S,loadMore:L}=useSupportTickets(void 0===i?{}:{pageSize:i}),g=useSupportTimeZone(),{entries:j,error:f,retry:_,discard:w}=useSupportOutbox(SUPPORT_TICKET_QUEUE),k=_jsx(OutboxEntryList,{entries:j,error:f,onRetry:e=>{_(e)},onDiscard:e=>{w(e)},labels:{waiting:r.waitingToSend,failed:r.outboxFailed,sendNow:r.sendNow,discard:r.discard,discardTitle:r.discardTitle,discardText:r.discardText},testID:"support-outbox"}),v=useCallback(({item:t})=>_jsx(TicketRow,{item:t,timeZone:g,onOpen:e,styles:l,t:r}),[g,e,l,r]),C=useCallback(()=>{L()},[L]),E=useCallback(()=>{S()},[S]),R=useMemo(()=>_jsx(RefreshControl,{refreshing:h,onRefresh:E}),[h,E]),I=(c?.total??0)>0,O=null!==d||""!==u.trim(),A=!m&&!y&&!I,D=_jsxs(View,{style:l.header,children:[t&&!A&&_jsx(Button,{label:r.newTicket,leftIcon:"add",onPress:t,fullWidth:!0}),s,k,y&&_jsxs(View,{style:l.error,accessibilityLiveRegion:"polite",children:[_jsx(Text,{variant:"bodySmall",color:"danger",children:y.message}),_jsx(Button,{label:r.retry,size:"sm",variant:"ghost",onPress:()=>{S()}})]}),c&&I&&_jsxs(_Fragment,{children:[_jsx(SearchBar,{value:u,onChangeText:b,debounceMs:400,placeholder:r.searchPlaceholder,accessibilityLabel:r.searchLabel,testID:"support-ticket-search"}),_jsx(ScrollView,{horizontal:!0,showsHorizontalScrollIndicator:!1,contentContainerStyle:l.filters,accessibilityRole:"tablist",accessibilityLabel:r.filterLabel,children:statusFilterOptions(c,d,r.all).map(e=>_jsx(Chip,{label:chipLabel(e),selected:(d??ALL)===e.value,onPress:()=>p(e.value===ALL?null:e.value),accessibilityLabel:void 0===e.count?e.label:fillLabel(r.chipAccessibility,{label:e.label,count:e.count}),testID:`support-filter-${e.value}`},e.value))})]})]});if(m&&null===c&&!y)return _jsxs(View,{style:[l.content,{flex:1}],testID:a,children:[k,_jsx(View,{style:l.center,children:_jsx(Spinner,{accessibilityLabel:r.loadingTickets})})]});const M=x?_jsx(View,{style:l.footer,children:_jsx(Spinner,{size:"sm",accessibilityLabel:r.loadingMore})}):T?_jsxs(View,{style:[l.footer,l.error],accessibilityLiveRegion:"polite",children:[_jsx(Text,{variant:"bodySmall",color:"danger",children:T.message}),_jsx(Button,{label:r.loadMore,size:"sm",variant:"ghost",onPress:()=>{L()}})]}):void 0;return _jsx(FlatList,{testID:a,data:n,keyExtractor:ticketKey,contentContainerStyle:l.content,ListHeaderComponent:D,ListFooterComponent:M,onEndReached:C,onEndReachedThreshold:.5,refreshControl:R,ListEmptyComponent:m?_jsx(View,{style:l.footer,children:_jsx(Spinner,{accessibilityLabel:r.loadingTickets})}):y?void 0:_jsx(EmptyState,I?{title:r.noMatchTitle,description:O?r.noMatchText:void 0}:{title:r.emptyTitle,description:r.emptyText,action:t?{label:r.newTicket,onPress:t}:void 0}),renderItem:v})};const buildStyles=e=>StyleSheet.create({content:{padding:e.space.md,gap:e.space.sm},header:{gap:e.space.sm,marginBottom:e.space.xs},filters:{gap:e.space.xs},error:{gap:e.space.xs,alignItems:"flex-start"},center:{flex:1,alignItems:"center",justifyContent:"center",padding:e.space.xl},footer:{paddingVertical:e.space.md,alignItems:"center"},card:{gap:e.space.xxs},cardTop:{flexDirection:"row",justifyContent:"space-between",alignItems:"center"},cardBottom:{flexDirection:"row",justifyContent:"space-between",marginTop:e.space.xxs}});
@@ -1 +1 @@
1
- "use strict";import{fillLabel,SHARED_LABELS}from"./labels.js";export const validateCategory=(e,t,o=SHARED_LABELS)=>!e||t.categories.includes(e)?void 0:o.categoryInvalid;export const validateSubject=(e,t,o=SHARED_LABELS)=>{const a=e.trim();return a?a.length>t.subjectMaxLength?fillLabel(o.subjectTooLong,{max:t.subjectMaxLength}):void 0:o.subjectRequired};export const validateBody=(e,t,o=SHARED_LABELS)=>{const a=e.trim();return a?a.length>t.bodyMaxLength?fillLabel(o.bodyTooLong,{max:t.bodyMaxLength}):void 0:o.bodyRequired};export const validateFiles=(e,t,o=SHARED_LABELS)=>{if(e.length>t.maxAttachmentsPerMessage)return fillLabel(o.tooManyPhotos,{max:t.maxAttachmentsPerMessage});for(const a of e){if(t.allowedContentTypes.length>0&&!t.allowedContentTypes.includes(a.type))return fillLabel(o.typeNotAllowed,{name:a.name});if(void 0!==a.size&&a.size>t.maxAttachmentBytes){const e=Math.floor(t.maxAttachmentBytes/1048576);return fillLabel(o.fileTooLarge,{name:a.name,mb:e})}}};
1
+ "use strict";import{fillLabel,SHARED_LABELS}from"./labels.js";export const categoryNames=(e,t)=>e.categories.filter(e=>void 0===t||e.queue===t).map(e=>e.name);export const validateCategory=(e,t,o=SHARED_LABELS,a)=>!e||categoryNames(t,a).includes(e)?void 0:o.categoryInvalid;export const validateSubject=(e,t,o=SHARED_LABELS)=>{const a=e.trim();return a?a.length>t.subjectMaxLength?fillLabel(o.subjectTooLong,{max:t.subjectMaxLength}):void 0:o.subjectRequired};export const validateBody=(e,t,o=SHARED_LABELS)=>{const a=e.trim();return a?a.length>t.bodyMaxLength?fillLabel(o.bodyTooLong,{max:t.bodyMaxLength}):void 0:o.bodyRequired};export const validateFiles=(e,t,o=SHARED_LABELS)=>{if(e.length>t.maxAttachmentsPerMessage)return fillLabel(o.tooManyPhotos,{max:t.maxAttachmentsPerMessage});for(const a of e){if(t.allowedContentTypes.length>0&&!t.allowedContentTypes.includes(a.type))return fillLabel(o.typeNotAllowed,{name:a.name});if(void 0!==a.size&&a.size>t.maxAttachmentBytes){const e=Math.floor(t.maxAttachmentBytes/1048576);return fillLabel(o.fileTooLarge,{name:a.name,mb:e})}}};
@@ -1,5 +1,5 @@
1
1
  import { type ZoneOption } from "@webority/mobile-core";
2
- import type { Outbox, OutboxEntry, OutboxProgress } from "@webority/mobile-core/outbox";
2
+ import type { Outbox, OutboxEntriesState, OutboxEntry, OutboxProgress } from "@webority/mobile-core/outbox";
3
3
  import type React from "react";
4
4
  import { SupportApiError, type SupportClient } from "./client";
5
5
  import type { SupportLabelOverrides } from "./labels";
@@ -97,10 +97,6 @@ export interface SupportTicketState {
97
97
  rate: (input: SupportRatingInput) => Promise<boolean>;
98
98
  }
99
99
  export declare const useSupportTicket: (id: string) => SupportTicketState;
100
- export declare const useSupportOutbox: (queue: string) => {
101
- entries: OutboxEntry[];
102
- retry: (id: string) => Promise<void>;
103
- discard: (id: string) => Promise<void>;
104
- };
100
+ export declare const useSupportOutbox: (queue: string) => OutboxEntriesState;
105
101
  export {};
106
102
  //# sourceMappingURL=SupportProvider.d.ts.map
@@ -12,13 +12,18 @@ export type SupportTicketPriority = "Low" | "Normal" | "High" | "Urgent";
12
12
  export type SupportMessageAuthorKind = "Customer" | "Agent" | "System" | "Assistant";
13
13
  export type SupportAttachmentKind = "Screenshot" | "File";
14
14
  export type SupportSatisfaction = "Satisfied" | "Unsatisfied";
15
+ /** A category a customer may pick and the key of the support queue it is worked in. */
16
+ export interface SupportContactCategory {
17
+ name: string;
18
+ queue: string;
19
+ }
15
20
  export interface SupportContactInfo {
16
21
  productName: string;
17
22
  supportEmail: string;
18
23
  supportName: string;
19
24
  supportPhone: string | null;
20
25
  supportHours: string | null;
21
- categories: string[];
26
+ categories: SupportContactCategory[];
22
27
  maxAttachmentBytes: number;
23
28
  maxAttachmentsPerMessage: number;
24
29
  allowedContentTypes: string[];
@@ -1,6 +1,8 @@
1
1
  import { SHARED_LABELS } from "./labels";
2
2
  import type { SupportContactInfo, SupportFilePart } from "./types";
3
- export declare const validateCategory: (category: string, config: SupportContactInfo, labels?: typeof SHARED_LABELS) => string | undefined;
3
+ /** The category names a form lists: those of `queue` when one is given, every category otherwise. */
4
+ export declare const categoryNames: (config: SupportContactInfo, queue?: string) => string[];
5
+ export declare const validateCategory: (category: string, config: SupportContactInfo, labels?: typeof SHARED_LABELS, queue?: string) => string | undefined;
4
6
  /** Limits come from GET /settings, so the product's own values are the only copy. */
5
7
  type Limits = Pick<SupportContactInfo, "subjectMaxLength" | "bodyMaxLength">;
6
8
  export declare const validateSubject: (subject: string, limits: Limits, labels?: typeof SHARED_LABELS) => string | undefined;
@@ -1,5 +1,5 @@
1
1
  import { type ZoneOption } from "@webority/mobile-core";
2
- import type { Outbox, OutboxEntry, OutboxProgress } from "@webority/mobile-core/outbox";
2
+ import type { Outbox, OutboxEntriesState, OutboxEntry, OutboxProgress } from "@webority/mobile-core/outbox";
3
3
  import type React from "react";
4
4
  import { SupportApiError, type SupportClient } from "./client.js";
5
5
  import type { SupportLabelOverrides } from "./labels.js";
@@ -97,10 +97,6 @@ export interface SupportTicketState {
97
97
  rate: (input: SupportRatingInput) => Promise<boolean>;
98
98
  }
99
99
  export declare const useSupportTicket: (id: string) => SupportTicketState;
100
- export declare const useSupportOutbox: (queue: string) => {
101
- entries: OutboxEntry[];
102
- retry: (id: string) => Promise<void>;
103
- discard: (id: string) => Promise<void>;
104
- };
100
+ export declare const useSupportOutbox: (queue: string) => OutboxEntriesState;
105
101
  export {};
106
102
  //# sourceMappingURL=SupportProvider.d.ts.map
@@ -12,13 +12,18 @@ export type SupportTicketPriority = "Low" | "Normal" | "High" | "Urgent";
12
12
  export type SupportMessageAuthorKind = "Customer" | "Agent" | "System" | "Assistant";
13
13
  export type SupportAttachmentKind = "Screenshot" | "File";
14
14
  export type SupportSatisfaction = "Satisfied" | "Unsatisfied";
15
+ /** A category a customer may pick and the key of the support queue it is worked in. */
16
+ export interface SupportContactCategory {
17
+ name: string;
18
+ queue: string;
19
+ }
15
20
  export interface SupportContactInfo {
16
21
  productName: string;
17
22
  supportEmail: string;
18
23
  supportName: string;
19
24
  supportPhone: string | null;
20
25
  supportHours: string | null;
21
- categories: string[];
26
+ categories: SupportContactCategory[];
22
27
  maxAttachmentBytes: number;
23
28
  maxAttachmentsPerMessage: number;
24
29
  allowedContentTypes: string[];
@@ -1,6 +1,8 @@
1
1
  import { SHARED_LABELS } from "./labels.js";
2
2
  import type { SupportContactInfo, SupportFilePart } from "./types.js";
3
- export declare const validateCategory: (category: string, config: SupportContactInfo, labels?: typeof SHARED_LABELS) => string | undefined;
3
+ /** The category names a form lists: those of `queue` when one is given, every category otherwise. */
4
+ export declare const categoryNames: (config: SupportContactInfo, queue?: string) => string[];
5
+ export declare const validateCategory: (category: string, config: SupportContactInfo, labels?: typeof SHARED_LABELS, queue?: string) => string | undefined;
4
6
  /** Limits come from GET /settings, so the product's own values are the only copy. */
5
7
  type Limits = Pick<SupportContactInfo, "subjectMaxLength" | "bodyMaxLength">;
6
8
  export declare const validateSubject: (subject: string, limits: Limits, labels?: typeof SHARED_LABELS) => string | undefined;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webority/mobile-support",
3
- "version": "0.171.3",
3
+ "version": "0.172.1",
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.171.3",
66
- "@webority/mobile-ui": "0.171.3",
65
+ "@webority/mobile-core": "0.172.1",
66
+ "@webority/mobile-ui": "0.172.1",
67
67
  "expo": ">=58.0.0",
68
68
  "expo-file-system": ">=58.0.0",
69
69
  "expo-image-manipulator": ">=58.0.0",
@@ -125,9 +125,9 @@
125
125
  "@testing-library/react-native": "14.1.0",
126
126
  "@types/jest": "29.5.14",
127
127
  "@types/react": "19.3.0",
128
- "@webority/mobile-core": "0.171.3",
128
+ "@webority/mobile-core": "0.172.1",
129
129
  "@webority/mobile-dev": "0.0.0",
130
- "@webority/mobile-ui": "0.171.3",
130
+ "@webority/mobile-ui": "0.172.1",
131
131
  "expo": "58.0.23",
132
132
  "expo-file-system": "58.0.13",
133
133
  "expo-image-manipulator": "58.0.16",