@liftitapp/wa-conversations 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +55 -0
- package/dist/element/index.js +75 -5
- package/dist/react/index.d.ts +90 -0
- package/dist/react/index.js +247 -8
- package/package.json +6 -3
package/README.md
CHANGED
|
@@ -274,3 +274,58 @@ con él, esa compatibilidad se pierde. `scripts/verify-externals.mjs` lo asserta
|
|
|
274
274
|
```bash
|
|
275
275
|
source ~/.nvm/nvm.sh && nvm use && pnpm install --prefer-offline
|
|
276
276
|
```
|
|
277
|
+
|
|
278
|
+
## Publicar
|
|
279
|
+
|
|
280
|
+
**Se publica a mano, desde tu máquina.** No hay workflow de release, y no es un olvido: hubo uno
|
|
281
|
+
basado en el Trusted Publishing de npm (OIDC desde GitHub Actions) y se sacó. Exigía un paso de
|
|
282
|
+
registro en npmjs.com que nunca se hizo, así que los dos intentos —`v0.4.0` y `v0.5.0`— corrieron
|
|
283
|
+
el pipeline entero y murieron en el `npm publish` con `ENEEDAUTH`. Un pipeline que sólo puede
|
|
284
|
+
fallar es peor que no tenerlo: entrena a ignorar el rojo. Es además lo que ya hace el otro paquete
|
|
285
|
+
publicable de la org, `lms-http-client`.
|
|
286
|
+
|
|
287
|
+
```bash
|
|
288
|
+
source ~/.nvm/nvm.sh && nvm use
|
|
289
|
+
npm login # una vez por máquina
|
|
290
|
+
npm version minor # bumpea package.json y crea el tag vX.Y.Z
|
|
291
|
+
npm publish # prepublishOnly corre los cinco gates
|
|
292
|
+
git push --follow-tags
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
`prepublishOnly` encadena **typecheck → lint → test → build → verify:tarball**, y ninguno de los
|
|
296
|
+
cinco es decorativo. Los dos últimos son los que atrapan lo irreversible:
|
|
297
|
+
|
|
298
|
+
- `pnpm build` corre `publint`, `attw` y `verify-externals` — que React quede afuera de
|
|
299
|
+
`dist/react/` y adentro de `dist/element/`, y que los dos entries tengan sus `.d.ts`.
|
|
300
|
+
- `pnpm verify:tarball` asserta que **no viaje nada fuera de `dist/`**. `contract/thread-v0.fixture.json`
|
|
301
|
+
lleva teléfonos y nombres reales y `.planning/` es documentación interna: esto va a un registry
|
|
302
|
+
**público**. También frena una prerelease que fuera a publicarse bajo `latest`.
|
|
303
|
+
|
|
304
|
+
⚠️ **npm sólo deja despublicar dentro de las 72 horas y sin dependientes.** Lo que suba es
|
|
305
|
+
prácticamente permanente — de ahí que los gates fallen en vez de avisar.
|
|
306
|
+
|
|
307
|
+
### Prereleases
|
|
308
|
+
|
|
309
|
+
Una versión con guion (`1.0.0-rc.1`) tiene que ir al dist-tag `next`, nunca a `latest`:
|
|
310
|
+
|
|
311
|
+
```bash
|
|
312
|
+
npm publish --tag next
|
|
313
|
+
```
|
|
314
|
+
|
|
315
|
+
`latest` es lo que se lleva quien haga `npm i @liftitapp/wa-conversations` sin pedir versión, así
|
|
316
|
+
que publicar un rc ahí lo convierte en la versión por defecto de todos los consumidores. El gate
|
|
317
|
+
lo impide y te dice el comando correcto.
|
|
318
|
+
|
|
319
|
+
### Si alguna vez se vuelve a publicar desde CI
|
|
320
|
+
|
|
321
|
+
Hace falta registrar el **Trusted Publisher** en npmjs.com (paquete → Settings → Trusted
|
|
322
|
+
Publisher, org `Liftitapp`, repo `wa-conversations`, el workflow que publique). Ojo con una
|
|
323
|
+
trampa que la doc de npm no cubre: no está documentado cómo registrarlo para un paquete que
|
|
324
|
+
**todavía no existe en el registry**, así que es probable que el primer publish necesite hacerse
|
|
325
|
+
igual a mano y que el OIDC tome el relevo recién después.
|
|
326
|
+
|
|
327
|
+
Lo que **no** hay que hacer es meter un `NPM_TOKEN` en los secretos del repo. `npm publish`
|
|
328
|
+
encadena `prepublishOnly`, así que eslint, vitest, tsc, tsdown y las transitivas de las devDeps
|
|
329
|
+
correrían con un token de **escritura** al scope en `process.env`. Si no queda otra, que sea un
|
|
330
|
+
token granular acotado exclusivamente a `@liftitapp/wa-conversations` y publicando con
|
|
331
|
+
`--ignore-scripts`.
|
package/dist/element/index.js
CHANGED
|
@@ -56,7 +56,7 @@ Error generating stack: `+e.message+`
|
|
|
56
56
|
* This source code is licensed under the MIT license found in the
|
|
57
57
|
* LICENSE file in the root directory of this source tree.
|
|
58
58
|
*/
|
|
59
|
-
var b=e((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),x=e(((e,t)=>{t.exports=b()}))();function ee({item:e,selected:t,onSelect:n}){return(0,x.jsx)(`li`,{className:`wa-list__item`,children:(0,x.jsxs)(`button`,{type:`button`,className:`wa-list__row`,"aria-current":t?`true`:void 0,onClick:()=>n(e),children:[(0,x.jsx)(`span`,{className:`wa-list__avatar`,"aria-hidden":`true`,children:f(e.name,e.phone)}),(0,x.jsxs)(`span`,{className:`wa-list__middle`,children:[(0,x.jsxs)(`span`,{className:`wa-list__head`,children:[(0,x.jsx)(`span`,{className:`wa-list__title`,children:e.name??e.phone}),(0,x.jsx)(`time`,{className:`wa-list__time`,dateTime:e.last_message_at,title:e.last_message_at,children:y(e.last_message_at)})]}),e.name!==null&&(0,x.jsx)(`span`,{className:`wa-list__phone`,children:e.phone}),e.last_message!==null&&(0,x.jsx)(`span`,{className:`wa-list__preview`,children:e.last_message}),e.service_state!==null&&(0,x.jsx)(`span`,{className:`wa-list__state`,title:e.service_state,children:e.service_state})]})]})})}function S(e,t=520){let[n,r]=(0,l.useState)(`wide`);return(0,l.useEffect)(()=>{if(typeof ResizeObserver>`u`)return;let n=e.current;if(n===null)return;let i=new ResizeObserver(e=>{for(let n of e)r(n.contentRect.width<=t?`narrow`:`wide`)});return i.observe(n),()=>i.disconnect()},[e,t]),n}function C(e){return e===`open`||e===`closed`?e:`unverified`}function te(e,t){let n=new Set(e.map(e=>e.id).filter(e=>typeof e==`string`&&e!==``)),r=new Set(e.map(e=>e.client_message_id).filter(e=>typeof e==`string`&&e!==``)),i=t.filter(e=>{if(e.direction!==`out`)return!1;let t=typeof e.client_message_id==`string`&&e.client_message_id!==``?e.client_message_id:null;if(t!==null&&r.has(t))return!1;let i=typeof e.id==`string`&&e.id!==``?e.id:null;return i===null||!n.has(i)});return ne([...e,...i])}function ne(e){let t=[],n=new Map;for(let r of e){let e=typeof r.id==`string`&&r.id!==``?r.id:null;if(e===null){t.push(r);continue}let i=n.get(e);i===void 0?(n.set(e,t.length),t.push(r)):t[i]=r}return t}function re(e){return typeof e==`object`&&e?e:{}}function w(e){return typeof e==`string`&&e!==``?e:null}const ie=4096;function ae(){let e=globalThis.crypto;return typeof e?.randomUUID==`function`?e.randomUUID():`cmid-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function oe(e,t,n){return{direction:`out`,body:e,at:t,status:`pending`,id:null,client_message_id:n,message_type:`text`,media_id:null,sent_by_name:null}}function se(e){let t=re(e);return{id:w(t.wamid)??w(t.id),at:w(t.at)??w(t.occurred_at),client_message_id:w(t.client_message_id),direction:`out`,body:typeof t.body==`string`?t.body:null,status:w(t.status),message_type:w(t.message_type)??`text`,media_id:w(t.media_id),media_url:w(t.media_url),media_format:w(t.media_format),media_mime_type:w(t.media_mime_type),sent_by_name:w(t.sent_by_name),service_state:w(t.service_state)}}function ce(e){let t=re(re(e).body),n=re(e),r=typeof t.error_code==`string`?t:typeof n.error_code==`string`?n:{},i=w(r.error_code);return i===null?{errorCode:`unknown`,retryable:!0,windowState:null,serverMessage:null}:{errorCode:i,retryable:r.retryable===!0,windowState:r.window_state===void 0||r.window_state===null?null:C(r.window_state),serverMessage:w(r.message)}}function le(e){switch(e.errorCode){case`window_closed`:return`La ventana de 24 h se cerró: no podemos escribirle hasta que la persona vuelva a escribir.`;case`window_unverified`:return`No pudimos verificar la ventana de 24 h, así que no se envió nada. Reintentá: reintentar no envía ningún mensaje cobrado.`;case`takeover_unavailable`:return`No se pudo pausar el bot, así que el mensaje no se envió. Reintentá en un momento.`;case`send_failed`:return`WhatsApp rechazó el envío. El mensaje quedó registrado en el hilo como no entregado.`;case`write_forbidden`:return`No tenés permiso para responder en esta conversación.`;default:return e.serverMessage??`No se pudo enviar el mensaje.`}}var ue=class extends Error{status;body;constructor(e,t,n){super(t),this.name=`WaFetchError`,this.status=e,this.body=n}};function T(e){return typeof e==`object`&&e?e:{}}function E(e){return typeof e==`string`?e:``}function de(e){return typeof e==`string`?e:null}async function fe(e,t,n){let r=T(await e({resource:`thread`,...t},n)),i=Array.isArray(r.messages)?r.messages:[];return{phone_e164:E(r.phone_e164),messages:ne(i),older_cursor:de(r.older_cursor),window_open:r.window_open===!0,window_state:C(de(r.window_state)),window_expires_at:de(r.window_expires_at),phone_number_id:E(r.phone_number_id),service:E(r.service),can_reply:r.can_reply===!0}}async function pe(e,t,n){return se(await e({resource:`reply`,...t},n))}async function me(e,t,n){let r=T(await e({resource:`release`,...t},n));return{status:E(r.status),released_at:de(r.released_at),window_state:de(r.window_state)}}async function D(e,t,n){let r=T(await e({resource:`media`,...t},n));return{url:E(r.url),media_format:de(r.media_format)}}async function O(e,t={},n){let r=T(await e({resource:`conversations`,...t},n));return{items:Array.isArray(r.items)?r.items:[],next_cursor:de(r.next_cursor)}}const he={};function ge(e){return e instanceof Error?e:Error(String(e))}function _e(e,t){let n=new Set(e.map(e=>e.phone));return[...e,...t.filter(e=>!n.has(e.phone))]}function ve({fetcher:e,filters:t=he}){let[n,r]=(0,l.useState)(null),[i,a]=(0,l.useState)(0),o=(0,l.useRef)(null),s=(0,l.useCallback)(()=>{o.current?.abort();let e=new AbortController;return o.current=e,e},[]),c=(0,l.useCallback)(e=>{o.current===e&&(o.current=null)},[]);(0,l.useEffect)(()=>{let n=s();return O(e,t,{signal:n.signal}).then(i=>{n.signal.aborted||(c(n),r({fetcher:e,filters:t,items:i.items,cursor:i.next_cursor,status:i.items.length>0?`ready`:`empty`,error:null,autoPages:0}))},i=>{n.signal.aborted||(c(n),r({fetcher:e,filters:t,items:[],cursor:null,status:`error`,error:ge(i),autoPages:0}))}),()=>n.abort()},[e,t,i,s,c]);let u=n!==null&&n.fetcher===e&&n.filters===t?n:null,d=(0,l.useCallback)((n=!1)=>{if(u===null||u.cursor===null||o.current!==null||n&&u.autoPages>=20)return;let i=u.cursor,a={...u,status:`loading-more`,error:null,autoPages:u.autoPages+ +!!n};r(a);let l=s();O(e,{...t,cursor:i},{signal:l.signal}).then(e=>{l.signal.aborted||(c(l),r({...a,items:_e(a.items,e.items),cursor:e.next_cursor,status:`ready`,error:null}))},e=>{l.signal.aborted||(c(l),r({...a,status:`error`,error:ge(e)}))})},[e,t,u,s,c]),f=(0,l.useCallback)(()=>{if(u!==null&&u.items.length>0){d();return}r(null),a(e=>e+1)},[u,d]);return{items:u?.items??[],status:u?.status??`loading`,error:u?.error??null,hasMore:u!==null&&u.cursor!==null,loadMore:d,retry:f,autoLoadExhausted:u!==null&&u.autoPages>=20}}const ye={};function be(e){let t=e=>`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`,n=new Date;return{from:t(new Date(n.getFullYear(),n.getMonth(),n.getDate()-(e-1))),to:t(n)}}function xe({fetcher:e,selectedPhone:t,onSelect:n,className:r}){let i=(0,l.useId)(),a=(0,l.useRef)(null),o=S(a),[s,c]=(0,l.useState)(``),[u,d]=(0,l.useState)(``),[f,p]=(0,l.useState)(``),[m,h]=(0,l.useState)(null),[g,_]=(0,l.useState)(ye),{items:v,status:y,error:b,hasMore:C,loadMore:te,retry:ne,autoLoadExhausted:re}=ve({fetcher:e,filters:g}),w=Object.keys(g).length>0,ie=(0,l.useCallback)(e=>{n?.(e)},[n]),ae=e=>{e.preventDefault();let t={};s.trim()!==``&&(t.phone=s),u!==``&&(t.from=u),f!==``&&(t.to=f),_(t)},oe=(e,t)=>{h(e);let n=be(t);d(n.from),p(n.to);let r={};s.trim()!==``&&(r.phone=s),r.from=n.from,r.to=n.to,_(r)},se=(e,t)=>{h(`range`),d(e),p(t);let n={};s.trim()!==``&&(n.phone=s),e!==``&&(n.from=e),t!==``&&(n.to=t),_(n)},ce=()=>{c(``),d(``),p(``),h(null),_(ye)},le=(0,l.useRef)(null);return(0,l.useEffect)(()=>{if(typeof IntersectionObserver>`u`)return;let e=le.current;if(e===null||!C||re)return;let t=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&te(!0)});return t.observe(e),()=>t.disconnect()},[C,re,te]),(0,x.jsxs)(`div`,{ref:a,className:r?`wa-list ${r}`:`wa-list`,"data-layout":o,children:[(0,x.jsx)(`style`,{children:`
|
|
59
|
+
var b=e((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),x=e(((e,t)=>{t.exports=b()}))();function ee({item:e,selected:t,onSelect:n}){return(0,x.jsx)(`li`,{className:`wa-list__item`,children:(0,x.jsxs)(`button`,{type:`button`,className:`wa-list__row`,"aria-current":t?`true`:void 0,onClick:()=>n(e),children:[(0,x.jsx)(`span`,{className:`wa-list__avatar`,"aria-hidden":`true`,children:f(e.name,e.phone)}),(0,x.jsxs)(`span`,{className:`wa-list__middle`,children:[(0,x.jsxs)(`span`,{className:`wa-list__head`,children:[(0,x.jsx)(`span`,{className:`wa-list__title`,children:e.name??e.phone}),(0,x.jsx)(`time`,{className:`wa-list__time`,dateTime:e.last_message_at,title:e.last_message_at,children:y(e.last_message_at)})]}),e.name!==null&&(0,x.jsx)(`span`,{className:`wa-list__phone`,children:e.phone}),e.last_message!==null&&(0,x.jsx)(`span`,{className:`wa-list__preview`,children:e.last_message}),e.service_state!==null&&(0,x.jsx)(`span`,{className:`wa-list__state`,title:e.service_state,children:e.service_state}),typeof e.taken_by==`string`&&e.taken_by!==``&&(0,x.jsx)(`span`,{className:`wa-list__taken`,"data-mine":e.taken_by_me===!0||void 0,title:`Tomada por ${e.taken_by}`,children:e.taken_by_me===!0?`La tomaste tú`:`Tomada por ${e.taken_by}`})]})]})})}function S(e,t=520){let[n,r]=(0,l.useState)(`wide`);return(0,l.useEffect)(()=>{if(typeof ResizeObserver>`u`)return;let n=e.current;if(n===null)return;let i=new ResizeObserver(e=>{for(let n of e)r(n.contentRect.width<=t?`narrow`:`wide`)});return i.observe(n),()=>i.disconnect()},[e,t]),n}function C(e){return e===`open`||e===`closed`?e:`unverified`}function te(e,t){let n=new Set(e.map(e=>e.id).filter(e=>typeof e==`string`&&e!==``)),r=new Set(e.map(e=>e.client_message_id).filter(e=>typeof e==`string`&&e!==``)),i=t.filter(e=>{if(e.direction!==`out`)return!1;let t=typeof e.client_message_id==`string`&&e.client_message_id!==``?e.client_message_id:null;if(t!==null&&r.has(t))return!1;let i=typeof e.id==`string`&&e.id!==``?e.id:null;return i===null||!n.has(i)});return ne([...e,...i])}function ne(e){let t=[],n=new Map;for(let r of e){let e=typeof r.id==`string`&&r.id!==``?r.id:null;if(e===null){t.push(r);continue}let i=n.get(e);i===void 0?(n.set(e,t.length),t.push(r)):t[i]=r}return t}function re(e){return typeof e==`object`&&e?e:{}}function w(e){return typeof e==`string`&&e!==``?e:null}const ie=4096;function ae(){let e=globalThis.crypto;return typeof e?.randomUUID==`function`?e.randomUUID():`cmid-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function oe(e,t,n){return{direction:`out`,body:e,at:t,status:`pending`,id:null,client_message_id:n,message_type:`text`,media_id:null,sent_by_name:null}}function se(e){let t=re(e);return{id:w(t.wamid)??w(t.id),at:w(t.at)??w(t.occurred_at),client_message_id:w(t.client_message_id),direction:`out`,body:typeof t.body==`string`?t.body:null,status:w(t.status),message_type:w(t.message_type)??`text`,media_id:w(t.media_id),media_url:w(t.media_url),media_format:w(t.media_format),media_mime_type:w(t.media_mime_type),sent_by_name:w(t.sent_by_name),service_state:w(t.service_state)}}function ce(e){let t=re(re(e).body),n=re(e),r=typeof t.error_code==`string`?t:typeof n.error_code==`string`?n:{},i=w(r.error_code);return i===null?{errorCode:`unknown`,retryable:!0,windowState:null,serverMessage:null}:{errorCode:i,retryable:r.retryable===!0,windowState:r.window_state===void 0||r.window_state===null?null:C(r.window_state),serverMessage:w(r.message)}}function le(e){switch(e.errorCode){case`window_closed`:return`La ventana de 24 h se cerró: no podemos escribirle hasta que la persona vuelva a escribir.`;case`window_unverified`:return`No pudimos verificar la ventana de 24 h, así que no se envió nada. Reintentá: reintentar no envía ningún mensaje cobrado.`;case`takeover_unavailable`:return`No se pudo pausar el bot, así que el mensaje no se envió. Reintentá en un momento.`;case`send_failed`:return`WhatsApp rechazó el envío. El mensaje quedó registrado en el hilo como no entregado.`;case`write_forbidden`:return`No tenés permiso para responder en esta conversación.`;default:return e.serverMessage??`No se pudo enviar el mensaje.`}}var ue=class extends Error{status;body;constructor(e,t,n){super(t),this.name=`WaFetchError`,this.status=e,this.body=n}};function T(e){return typeof e==`object`&&e?e:{}}function E(e){return typeof e==`string`?e:``}function de(e){return typeof e==`string`?e:null}async function fe(e,t,n){let r=T(await e({resource:`thread`,...t},n)),i=Array.isArray(r.messages)?r.messages:[];return{phone_e164:E(r.phone_e164),messages:ne(i),older_cursor:de(r.older_cursor),window_open:r.window_open===!0,window_state:C(de(r.window_state)),window_expires_at:de(r.window_expires_at),phone_number_id:E(r.phone_number_id),service:E(r.service),can_reply:r.can_reply===!0,taken_by:de(r.taken_by),taken_until:de(r.taken_until),taken_by_me:r.taken_by_me===!0}}async function pe(e,t,n){return se(await e({resource:`reply`,...t},n))}async function me(e,t,n){let r=T(await e({resource:`release`,...t},n));return{status:E(r.status),released_at:de(r.released_at),window_state:de(r.window_state)}}async function D(e,t,n){let r=T(await e({resource:`media`,...t},n));return{url:E(r.url),media_format:de(r.media_format)}}async function O(e,t={},n){let r=T(await e({resource:`conversations`,...t},n));return{items:Array.isArray(r.items)?r.items:[],next_cursor:de(r.next_cursor)}}const he={};function ge(e){return e instanceof Error?e:Error(String(e))}function _e(e,t){let n=new Set(e.map(e=>e.phone));return[...e,...t.filter(e=>!n.has(e.phone))]}function ve({fetcher:e,filters:t=he}){let[n,r]=(0,l.useState)(null),[i,a]=(0,l.useState)(0),o=(0,l.useRef)(null),s=(0,l.useCallback)(()=>{o.current?.abort();let e=new AbortController;return o.current=e,e},[]),c=(0,l.useCallback)(e=>{o.current===e&&(o.current=null)},[]);(0,l.useEffect)(()=>{let n=s();return O(e,t,{signal:n.signal}).then(i=>{n.signal.aborted||(c(n),r({fetcher:e,filters:t,items:i.items,cursor:i.next_cursor,status:i.items.length>0?`ready`:`empty`,error:null,autoPages:0}))},i=>{n.signal.aborted||(c(n),r({fetcher:e,filters:t,items:[],cursor:null,status:`error`,error:ge(i),autoPages:0}))}),()=>n.abort()},[e,t,i,s,c]);let u=n!==null&&n.fetcher===e&&n.filters===t?n:null,d=(0,l.useCallback)((n=!1)=>{if(u===null||u.cursor===null||o.current!==null||n&&u.autoPages>=20)return;let i=u.cursor,a={...u,status:`loading-more`,error:null,autoPages:u.autoPages+ +!!n};r(a);let l=s();O(e,{...t,cursor:i},{signal:l.signal}).then(e=>{l.signal.aborted||(c(l),r({...a,items:_e(a.items,e.items),cursor:e.next_cursor,status:`ready`,error:null}))},e=>{l.signal.aborted||(c(l),r({...a,status:`error`,error:ge(e)}))})},[e,t,u,s,c]),f=(0,l.useCallback)(()=>{if(u!==null&&u.items.length>0){d();return}r(null),a(e=>e+1)},[u,d]);return{items:u?.items??[],status:u?.status??`loading`,error:u?.error??null,hasMore:u!==null&&u.cursor!==null,loadMore:d,retry:f,autoLoadExhausted:u!==null&&u.autoPages>=20}}const ye={};function be(e){let t=e=>`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`,n=new Date;return{from:t(new Date(n.getFullYear(),n.getMonth(),n.getDate()-(e-1))),to:t(n)}}function xe({fetcher:e,selectedPhone:t,onSelect:n,className:r}){let i=(0,l.useId)(),a=(0,l.useRef)(null),o=S(a),[s,c]=(0,l.useState)(``),[u,d]=(0,l.useState)(``),[f,p]=(0,l.useState)(``),[m,h]=(0,l.useState)(null),[g,_]=(0,l.useState)(ye),{items:v,status:y,error:b,hasMore:C,loadMore:te,retry:ne,autoLoadExhausted:re}=ve({fetcher:e,filters:g}),w=Object.keys(g).length>0,ie=(0,l.useCallback)(e=>{n?.(e)},[n]),ae=e=>{e.preventDefault();let t={};s.trim()!==``&&(t.phone=s),u!==``&&(t.from=u),f!==``&&(t.to=f),_(t)},oe=(e,t)=>{h(e);let n=be(t);d(n.from),p(n.to);let r={};s.trim()!==``&&(r.phone=s),r.from=n.from,r.to=n.to,_(r)},se=(e,t)=>{h(`range`),d(e),p(t);let n={};s.trim()!==``&&(n.phone=s),e!==``&&(n.from=e),t!==``&&(n.to=t),_(n)},ce=()=>{c(``),d(``),p(``),h(null),_(ye)},le=(0,l.useRef)(null);return(0,l.useEffect)(()=>{if(typeof IntersectionObserver>`u`)return;let e=le.current;if(e===null||!C||re)return;let t=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&te(!0)});return t.observe(e),()=>t.disconnect()},[C,re,te]),(0,x.jsxs)(`div`,{ref:a,className:r?`wa-list ${r}`:`wa-list`,"data-layout":o,children:[(0,x.jsx)(`style`,{children:`
|
|
60
60
|
.wa-list {
|
|
61
61
|
box-sizing: border-box;
|
|
62
62
|
display: flex;
|
|
@@ -366,6 +366,30 @@ var b=e((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.
|
|
|
366
366
|
word-break: break-word;
|
|
367
367
|
}
|
|
368
368
|
|
|
369
|
+
/* DEV-5061 — el chip «Tomada» de la fila. Mismo par de tonos que la barra del hilo: ambar cuando
|
|
370
|
+
la tiene otro (aviso) y anil cuando es tuya. Que las dos vistas usen la MISMA pareja no es
|
|
371
|
+
coincidencia — el operador tiene que reconocer el estado sin releer. */
|
|
372
|
+
.wa-list__taken {
|
|
373
|
+
align-self: flex-start;
|
|
374
|
+
margin-top: 2px;
|
|
375
|
+
padding: 1px 8px;
|
|
376
|
+
border-radius: 999px;
|
|
377
|
+
background: #fff7e8;
|
|
378
|
+
color: #b7791f;
|
|
379
|
+
font-size: 11px;
|
|
380
|
+
font-weight: 600;
|
|
381
|
+
/* El nombre de un operador puede ser largo y la fila es angosta: se recorta en vez de
|
|
382
|
+
empujar la columna. El completo queda en el \`title\`. */
|
|
383
|
+
max-width: 100%;
|
|
384
|
+
overflow: hidden;
|
|
385
|
+
text-overflow: ellipsis;
|
|
386
|
+
white-space: nowrap;
|
|
387
|
+
}
|
|
388
|
+
.wa-list__taken[data-mine='true'] {
|
|
389
|
+
background: #f4f5ff;
|
|
390
|
+
color: #4f5aed;
|
|
391
|
+
}
|
|
392
|
+
|
|
369
393
|
/* Angosto: sólo se deja envolver el texto. El \`display: contents\` que antes sacaba al agrupador
|
|
370
394
|
del flujo ya no hace falta — la columna .wa-list__middle apila por sí sola. */
|
|
371
395
|
.wa-list[data-layout='narrow'] .wa-list__preview,
|
|
@@ -395,7 +419,7 @@ var b=e((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.
|
|
|
395
419
|
background: #ffffff;
|
|
396
420
|
cursor: pointer;
|
|
397
421
|
}
|
|
398
|
-
`}),(0,x.jsxs)(`form`,{className:`wa-list__filters`,onSubmit:ae,children:[(0,x.jsxs)(`div`,{className:`wa-list__search`,children:[(0,x.jsx)(`label`,{className:`wa-list__sr-only`,htmlFor:`${i}-phone`,children:`Buscar por nombre o teléfono`}),(0,x.jsxs)(`svg`,{className:`wa-list__search-icon`,viewBox:`0 0 16 16`,width:`14`,height:`14`,"aria-hidden":`true`,focusable:`false`,children:[(0,x.jsx)(`circle`,{cx:`7`,cy:`7`,r:`4.5`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`}),(0,x.jsx)(`path`,{d:`M10.5 10.5 14 14`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`})]}),(0,x.jsx)(`input`,{id:`${i}-phone`,type:`search`,placeholder:`Buscar por nombre o teléfono`,value:s,onChange:e=>c(e.target.value)})]}),(0,x.jsxs)(`div`,{className:`wa-list__presets`,role:`group`,"aria-label":`Filtrar por fecha`,children:[(0,x.jsx)(`button`,{type:`button`,className:`wa-list__preset`,"aria-pressed":m===`today`,onClick:()=>oe(`today`,1),children:`Hoy`}),(0,x.jsx)(`button`,{type:`button`,className:`wa-list__preset`,"aria-pressed":m===`7d`,onClick:()=>oe(`7d`,7),children:`7 días`}),(0,x.jsx)(`button`,{type:`button`,className:`wa-list__preset`,"aria-pressed":m===`30d`,onClick:()=>oe(`30d`,30),children:`30 días`}),(0,x.jsx)(`button`,{type:`button`,className:`wa-list__preset`,"aria-pressed":m===`range`,onClick:()=>h(`range`),children:`Rango…`})]}),m===`range`&&(0,x.jsxs)(`div`,{className:`wa-list__range`,children:[(0,x.jsx)(`label`,{className:`wa-list__sr-only`,htmlFor:`${i}-from`,children:`Desde`}),(0,x.jsx)(`input`,{id:`${i}-from`,type:`date`,className:`wa-list__date`,value:u,onChange:e=>se(e.target.value,f)}),(0,x.jsx)(`span`,{className:`wa-list__range-sep`,"aria-hidden":`true`,children:`→`}),(0,x.jsx)(`label`,{className:`wa-list__sr-only`,htmlFor:`${i}-to`,children:`Hasta`}),(0,x.jsx)(`input`,{id:`${i}-to`,type:`date`,className:`wa-list__date`,value:f,onChange:e=>se(u,e.target.value)})]}),w&&(0,x.jsx)(`button`,{type:`button`,className:`wa-list__clear`,onClick:ce,children:`Limpiar filtros`})]}),y===`loading`&&(0,x.jsx)(`p`,{className:`wa-list__note`,children:`Cargando conversaciones…`}),b!==null&&(0,x.jsxs)(`div`,{className:`wa-list__error`,role:`alert`,children:[(0,x.jsxs)(`p`,{children:[`No se pudieron cargar las conversaciones: `,b.message]}),(0,x.jsx)(`button`,{type:`button`,onClick:ne,children:`Reintentar`})]}),y===`empty`&&(0,x.jsx)(`p`,{className:`wa-list__note`,children:w?`No hay conversaciones con ese filtro.`:`No hay conversaciones todavía.`}),(0,x.jsx)(`ul`,{className:`wa-list__items`,children:v.map(e=>(0,x.jsx)(ee,{item:e,selected:e.phone===t,onSelect:ie},e.phone))}),C&&(0,x.jsx)(`button`,{ref:le,type:`button`,className:`wa-list__more`,onClick:()=>te(),disabled:y===`loading-more`,children:y===`loading-more`?`Cargando…`:`Cargar más`})]})}function Se({composer:e}){return e.failures.length===0?null:(0,x.jsx)(`div`,{className:`wa-composer__failures`,role:`alert`,children:e.failures.map(t=>(0,x.jsxs)(`div`,{className:`wa-composer__failure`,children:[(0,x.jsx)(`p`,{className:`wa-composer__failure-text`,children:t.failure===null?`No se pudo enviar el mensaje.`:le(t.failure)}),(0,x.jsxs)(`div`,{className:`wa-composer__failure-actions`,children:[t.failure?.retryable===!0&&(0,x.jsx)(`button`,{type:`button`,className:`wa-composer__failure-retry`,onClick:()=>e.retry(t.clientMessageId),children:`Reintentar`}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>e.dismiss(t.clientMessageId),children:`Descartar`})]})]},t.clientMessageId))})}function Ce({composer:e}){return e.releaseState===`released`?(0,x.jsx)(`p`,{className:`wa-composer__released`,role:`status`,children:`Listo: la conversación volvió al bot. La ventana sigue cerrada — se abre cuando la persona responda. Si necesitás retomarla en frío, la plantilla se manda desde el header del drawer del embudo.`}):(0,x.jsxs)(`div`,{className:`wa-composer__release`,children:[(0,x.jsxs)(`p`,{className:`wa-composer__release-explain`,children:[`Podés devolver la conversación al bot: se suelta el control y el bot vuelve a manejarla.`,` `,(0,x.jsx)(`strong`,{children:`No se le manda ningún mensaje a la persona y no te habilita a vos para seguir escribiendo`}),` — si responde, la ventana se abre y el composer vuelve solo. Para retomarla en frío con una plantilla, usá la acción del header del drawer del embudo.`]}),e.releaseState===`error`&&e.releaseFailure!==null&&(0,x.jsx)(`p`,{className:`wa-composer__release-error`,role:`alert`,children:le(e.releaseFailure)}),(e.releaseState!==`error`||e.releaseFailure?.retryable===!0)&&(0,x.jsx)(`button`,{type:`button`,className:`wa-composer__release-button`,onClick:e.release,disabled:e.releaseState===`releasing`,children:e.releaseState===`releasing`?`Devolviendo la conversación al bot…`:`Devolver la conversación al bot`})]})}function we({canReply:e,composer:t,onRetryWindow:n}){let[r,i]=(0,l.useState)(``);if(!e)return null;if(t.windowState===`closed`)return(0,x.jsxs)(`div`,{className:`wa-composer wa-composer--closed`,children:[(0,x.jsx)(Se,{composer:t}),(0,x.jsx)(`span`,{className:`wa-composer__lock`,children:(0,x.jsxs)(`svg`,{width:20,height:20,viewBox:`0 0 20 20`,fill:`none`,stroke:`#8A91A0`,strokeWidth:1.6,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":`true`,children:[(0,x.jsx)(`rect`,{x:`4.5`,y:`9`,width:`11`,height:`7.5`,rx:`1.5`}),(0,x.jsx)(`path`,{d:`M7 9V6.5a3 3 0 0 1 6 0V9`})]})}),(0,x.jsxs)(`div`,{role:`status`,children:[(0,x.jsx)(`p`,{className:`wa-composer__cold-title`,children:`La ventana de 24 horas está cerrada`}),(0,x.jsx)(`p`,{className:`wa-composer__cold-explain`,children:`WhatsApp solo permite responder hasta 24 h después del último mensaje del lifter. Se reabre cuando vuelva a escribir.`})]}),(0,x.jsx)(Ce,{composer:t})]});let a=()=>{let e=r.trim();e!==``&&(t.send(e),i(``))};return(0,x.jsxs)(`div`,{className:`wa-composer`,children:[t.windowState===`unverified`&&(0,x.jsxs)(`div`,{className:`wa-composer__unverified`,role:`status`,children:[(0,x.jsxs)(`div`,{className:`wa-composer__unverified-text`,children:[(0,x.jsx)(`p`,{className:`wa-composer__unverified-title`,children:`No pudimos verificar si se puede responder`}),(0,x.jsx)(`p`,{className:`wa-composer__unverified-explain`,children:`Es un error temporal, no una ventana cerrada.`})]}),n!==void 0&&(0,x.jsx)(`button`,{type:`button`,className:`wa-composer__retry-window`,onClick:n,children:`Reintentar`})]}),(0,x.jsx)(Se,{composer:t}),(0,x.jsxs)(`form`,{className:`wa-composer__form`,onSubmit:e=>{e.preventDefault(),a()},children:[(0,x.jsx)(`textarea`,{className:`wa-composer__input`,maxLength:ie,rows:2,value:r,placeholder:`Escribí tu respuesta…`,"aria-label":`Mensaje para la persona`,onChange:e=>i(e.target.value),onKeyDown:e=>{e.key!==`Enter`||e.shiftKey||e.nativeEvent.isComposing||(e.preventDefault(),a())}}),(0,x.jsxs)(`div`,{className:`wa-composer__hint-row`,children:[(0,x.jsx)(`span`,{className:`wa-composer__hint`,children:`Al enviar, el bot se pausa 2 h y la conversación queda tomada por ti`}),(0,x.jsxs)(`span`,{className:`wa-composer__counter`,children:[r.length,`/`,ie]}),(0,x.jsx)(`button`,{type:`submit`,className:`wa-composer__send`,disabled:r.trim()===``,children:`Enviar`})]})]})]})}const Te=[`enero`,`febrero`,`marzo`,`abril`,`mayo`,`junio`,`julio`,`agosto`,`septiembre`,`octubre`,`noviembre`,`diciembre`];function Ee(e){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}function De(e){if(typeof e!=`string`)return null;let t=Ee(e);return t===null?null:`${t.getFullYear()}-${t.getMonth()+1}-${t.getDate()}`}function Oe(e){let t=Ee(e);return t===null?``:`${t.getDate()} de ${Te[t.getMonth()]} de ${t.getFullYear()}`}const ke=new Set([`quick_reply`,`location`]),Ae=new Set([`http:`,`https:`]);function je(e){return(Array.isArray(e.ctas)?e.ctas:e.cta?[e.cta]:[]).filter(e=>e!=null&&typeof e.text==`string`&&e.text.trim()!==``)}function Me(e){if(typeof e.kind==`string`&&ke.has(e.kind))return!1;let t=typeof e.url==`string`?e.url.trim():``;if(t===``)return!1;try{return Ae.has(new URL(t).protocol)}catch{return!1}}function Ne(e){return e===`image`?`image`:e===`pdf`?`pdf`:`other`}function Pe(e,t){return typeof e.file_name==`string`&&e.file_name!==``?e.file_name:t}function Fe(){return(0,x.jsx)(`span`,{className:`wa-thread__media-unavailable`,children:`Adjunto no disponible`})}function Ie(){return(0,x.jsxs)(`svg`,{width:16,height:16,viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:1.5,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":`true`,children:[(0,x.jsx)(`path`,{d:`M8 2.5v7.5`}),(0,x.jsx)(`polyline`,{points:`4.5,6.8 8,10.3 11.5,6.8`}),(0,x.jsx)(`path`,{d:`M2.5 13.5h11`})]})}function Le({message:e,fetcher:t,mediaId:n}){let[r,i]=(0,l.useState)(()=>typeof e.media_url==`string`&&e.media_url!==``?{kind:`ready`,url:e.media_url}:{kind:`loading`}),[a,o]=(0,l.useState)(!1),s=(0,l.useRef)(!1),c=(0,l.useRef)(!1),u=(0,l.useRef)(!0);(0,l.useEffect)(()=>()=>{u.current=!1},[]),(0,l.useEffect)(()=>{if(s.current||(s.current=!0,typeof e.media_url==`string`&&e.media_url!==``))return;let r=!1;return D(t,{mediaId:n}).then(e=>{r||!u.current||i(e.url===``?{kind:`unavailable`}:{kind:`ready`,url:e.url})}).catch(()=>{!r&&u.current&&i({kind:`unavailable`})}),()=>{r=!0}},[t,n,e.media_url]),(0,l.useEffect)(()=>{if(!a)return;let e=e=>{e.key===`Escape`&&o(!1)};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[a]);let d=()=>{if(c.current){i({kind:`unavailable`});return}c.current=!0,i({kind:`loading`}),D(t,{mediaId:n}).then(e=>{u.current&&i(e.url===``?{kind:`unavailable`}:{kind:`ready`,url:e.url})}).catch(()=>{u.current&&i({kind:`unavailable`})})};if(r.kind===`loading`)return(0,x.jsx)(`span`,{className:`wa-thread__media-loading`,children:`Cargando adjunto…`});if(r.kind===`unavailable`)return(0,x.jsx)(Fe,{});let f=Pe(e,`Imagen adjunta`);return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`button`,{type:`button`,className:`wa-thread__media-button`,onClick:()=>o(!0),"aria-label":`Ampliar imagen adjunta`,children:(0,x.jsx)(`img`,{className:`wa-thread__media-img`,src:r.url,alt:f,onError:d})}),(0,x.jsxs)(`div`,{className:`wa-thread__media-file`,children:[(0,x.jsx)(`span`,{className:`wa-thread__media-name`,children:Pe(e,`Imagen adjunta`)}),(0,x.jsx)(Re,{message:e,fetcher:t,mediaId:n,variant:`icon`})]}),a&&(0,x.jsx)(`div`,{className:`wa-thread__lightbox`,role:`dialog`,"aria-label":`Imagen ampliada`,onClick:()=>o(!1),children:(0,x.jsx)(`img`,{className:`wa-thread__lightbox-img`,src:r.url,alt:f})})]})}function Re({message:e,fetcher:t,mediaId:n,variant:r=`label`}){let[i,a]=(0,l.useState)(!1),o=(0,l.useRef)(null),s=(0,l.useRef)(!1),c=(0,l.useRef)(!0);(0,l.useEffect)(()=>()=>{c.current=!1},[]);let u=e=>{if(s.current){s.current=!1;return}e.preventDefault(),D(t,{mediaId:n}).then(e=>{if(!c.current)return;let t=o.current;if(t!==null){if(e.url===``){a(!0);return}t.href=e.url,s.current=!0,t.click()}}).catch(()=>{c.current&&a(!0)})};return i?(0,x.jsx)(Fe,{}):r===`icon`?(0,x.jsx)(`a`,{ref:o,className:`wa-thread__media-download wa-thread__media-download--icon`,href:`#`,download:!0,target:`_blank`,rel:`noopener noreferrer`,onClick:u,"aria-label":`Descargar ${typeof e.file_name==`string`&&e.file_name!==``?e.file_name:`adjunto`}`,children:(0,x.jsx)(Ie,{})}):(0,x.jsx)(`a`,{ref:o,className:`wa-thread__media-download`,href:`#`,download:!0,target:`_blank`,rel:`noopener noreferrer`,onClick:u,children:Pe(e,`Descargar adjunto`)})}function ze({message:e,fetcher:t}){let n=e.media_id;if(n===null)return null;let r=(()=>{switch(Ne(e.media_format)){case`image`:return(0,x.jsx)(Le,{message:e,fetcher:t,mediaId:n});case`pdf`:return(0,x.jsx)(Re,{message:e,fetcher:t,mediaId:n});default:return(0,x.jsx)(Re,{message:e,fetcher:t,mediaId:n})}})();return(0,x.jsx)(`div`,{className:`wa-thread__media`,children:r})}function Be(e){switch(e){case`pending`:return{kind:`clock`,label:`Pendiente`};case`sent`:return{kind:`check`,label:`Enviado`};case`delivered`:return{kind:`check-check`,label:`Entregado`};case`read`:return{kind:`check-check`,label:`Leído`};default:return null}}function Ve({kind:e}){return e===`clock`?(0,x.jsx)(x.Fragment,{children:`◷`}):(0,x.jsxs)(`svg`,{width:16,height:16,viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:1.8,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":`true`,children:[(0,x.jsx)(`polyline`,{points:`2.5,8.5 6,12 13,4.5`}),e===`check-check`&&(0,x.jsx)(`polyline`,{points:`7,10.2 8.7,12 15.3,4.8`})]})}function He(e){if(typeof e!=`string`)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`}function Ue({message:e,optimistic:t=!1,fetcher:n}){let r=e.direction===`out`?`out`:`in`,i=He(e.at),a=je(e),o=r===`out`?Be(e.status):null,s=r===`out`&&e.status===`failed`,c=typeof e.sent_by_name==`string`&&e.sent_by_name.trim()!==``?e.sent_by_name:null,l=r===`out`?c!==null||t?`operator`:`bot`:void 0,u=e.body===null&&e.message_type===`location`?e.location_name??`Ubicación compartida`:null;return(0,x.jsxs)(`div`,{className:`wa-thread__bubble`,"data-direction":r,"data-author":l,"data-failed":s||void 0,children:[c!==null&&(0,x.jsx)(`span`,{className:`wa-thread__author`,children:c}),e.body!==null&&(0,x.jsx)(`p`,{className:`wa-thread__body`,children:e.body}),u!==null&&(0,x.jsx)(`p`,{className:`wa-thread__body`,children:u}),e.media_id!==null&&(0,x.jsx)(ze,{message:e,fetcher:n}),a.length>0&&(0,x.jsx)(`div`,{className:`wa-thread__ctas`,children:a.map((e,t)=>Me(e)?(0,x.jsx)(`a`,{className:`wa-thread__cta wa-thread__cta--link`,href:e.url??void 0,target:`_blank`,rel:`noopener noreferrer`,children:e.text},`${t}-${e.text}`):(0,x.jsx)(`span`,{className:`wa-thread__cta wa-thread__cta--inert`,children:e.text},`${t}-${e.text}`))}),(0,x.jsxs)(`span`,{className:`wa-thread__meta`,children:[i!==null&&e.at!==null&&(0,x.jsx)(`time`,{className:`wa-thread__hour`,dateTime:e.at,title:e.at,children:i}),s?(0,x.jsx)(`span`,{className:`wa-thread__failed`,children:`No entregado`}):o!==null&&(0,x.jsx)(`span`,{className:`wa-thread__tick`,"data-status":e.status,title:o.label,"aria-label":o.label,children:(0,x.jsx)(Ve,{kind:o.kind})})]})]})}const We={collecting_vehicle_plate:`Placa del vehículo`,collecting_vehicle_documents:`Documentos del vehículo`,collecting_documents:`Documentos personales`,existing_user_menu:`Menú de usuario registrado`,activated:`Cuenta activada`};function Ge(e){return Object.prototype.hasOwnProperty.call(We,e)?We[e]:e}function Ke(e,t){return{fetcher:e,phone:t,outgoing:[],windowStateOverride:null,releaseState:`idle`,releaseFailure:null}}function qe({fetcher:e,phone:t,windowState:n}){let[r,i]=(0,l.useState)(null),a=r!==null&&r.fetcher===e&&r.phone===t?r:null,o=(0,l.useCallback)(n=>{i(r=>r===null||r.fetcher!==e||r.phone!==t?r:n(r))},[e,t]),s=(0,l.useCallback)((e,t)=>{o(n=>({...n,outgoing:n.outgoing.map(n=>n.clientMessageId===e?t(n):n)}))},[o]),c=(0,l.useCallback)(n=>{pe(e,{phone:t,text:n.text,clientMessageId:n.clientMessageId}).then(e=>{s(n.clientMessageId,t=>({...t,status:`sent`,message:e,failure:null})),o(e=>({...e,windowStateOverride:`open`}))},e=>{let t=ce(e);s(n.clientMessageId,e=>({...e,status:`failed`,message:{...e.message,status:`failed`},failure:t})),t.windowState!==null&&o(e=>({...e,windowStateOverride:t.windowState}))})},[e,t,o,s]),u=(0,l.useCallback)(n=>{let r=n.trim();if(r===``||r.length>4096)return;let a=ae(),o={clientMessageId:a,text:r,status:`pending`,message:oe(r,new Date().toISOString(),a),failure:null};i(n=>{let r=n!==null&&n.fetcher===e&&n.phone===t?n:Ke(e,t);return{...r,outgoing:[...r.outgoing,o]}}),c(o)},[c,e,t]),d=(0,l.useCallback)(e=>{let t=a?.outgoing.find(t=>t.clientMessageId===e);if(t===void 0||t.status!==`failed`||t.failure!==null&&!t.failure.retryable)return;let n={...t,status:`pending`,message:{...t.message,status:`pending`},failure:null};s(e,()=>n),c(n)},[a,c,s]),f=(0,l.useCallback)(e=>{o(t=>({...t,outgoing:t.outgoing.filter(t=>t.clientMessageId!==e)}))},[o]),p=(0,l.useCallback)(()=>{a?.releaseState!==`releasing`&&(i(n=>({...n!==null&&n.fetcher===e&&n.phone===t?n:Ke(e,t),releaseState:`releasing`,releaseFailure:null})),me(e,{phone:t}).then(()=>{o(e=>({...e,releaseState:`released`,releaseFailure:null,windowStateOverride:`closed`}))},e=>{o(t=>({...t,releaseState:`error`,releaseFailure:ce(e)}))}))},[a,e,o,t]),m=a?.outgoing??[];return{outgoing:m,localMessages:m.map(e=>e.message),optimisticMessages:m.filter(e=>e.status!==`sent`).map(e=>e.message),failures:m.filter(e=>e.status===`failed`),windowState:a?.windowStateOverride??n,sending:m.some(e=>e.status===`pending`),send:u,retry:d,dismiss:f,releaseState:a?.releaseState??`idle`,releaseFailure:a?.releaseFailure??null,release:p}}function Je(e){return e instanceof Error?e:Error(String(e))}function Ye(e){if(typeof e!=`string`)return 1/0;let t=Date.parse(e);return Number.isNaN(t)?1/0:t}function Xe(e){return e.map((e,t)=>({message:e,index:t,key:Ye(e.at)})).sort((e,t)=>e.key===t.key?e.index-t.index:e.key<t.key?-1:1).map(e=>e.message)}function Ze({fetcher:e,phone:t}){let[n,r]=(0,l.useState)(null),[i,a]=(0,l.useState)(0),o=(0,l.useRef)(null),s=(0,l.useCallback)(()=>{o.current?.abort();let e=new AbortController;return o.current=e,e},[]),c=(0,l.useCallback)(e=>{o.current===e&&(o.current=null)},[]);(0,l.useEffect)(()=>{let n=s();return fe(e,{phone:t},{signal:n.signal}).then(i=>{if(n.signal.aborted)return;c(n);let a=Xe(i.messages);r({fetcher:e,phone:t,messages:a,windowState:C(i.window_state),canReply:i.can_reply===!0,status:a.length>0?`ready`:`empty`,error:null,olderCursor:i.older_cursor,hasOlder:i.older_cursor!==null})},i=>{n.signal.aborted||(c(n),r({fetcher:e,phone:t,messages:[],windowState:`unverified`,canReply:!1,status:`error`,error:Je(i),olderCursor:null,hasOlder:!1}))}),()=>n.abort()},[e,t,i,s,c]);let u=n!==null&&n.fetcher===e&&n.phone===t?n:null,d=(0,l.useCallback)(()=>{if(u===null||!u.hasOlder||o.current!==null)return;let n=u.olderCursor;if(n===null)return;let i={...u,status:`loading-older`,error:null};r(i);let a=s();fe(e,{phone:t,cursor:n},{signal:a.signal}).then(e=>{if(a.signal.aborted)return;c(a);let t=new Set(i.messages.map(e=>e.id).filter(e=>typeof e==`string`&&e!==``));if(!e.messages.some(e=>typeof e.id==`string`&&e.id!==``&&!t.has(e.id))){r({...i,status:`ready`,error:null,hasOlder:!1});return}let n=Xe(ne([...e.messages,...i.messages]));r({...i,messages:n,status:`ready`,error:null,olderCursor:e.older_cursor,hasOlder:e.older_cursor!==null})},e=>{a.signal.aborted||(c(a),r({...i,status:`error`,error:Je(e)}))})},[e,t,u,s,c]),f=(0,l.useCallback)(()=>{if(u!==null&&u.status===`error`&&u.messages.length>0){d();return}r(null),a(e=>e+1)},[u,d]);return{messages:u?.messages??[],status:u?.status??`loading`,error:u?.error??null,windowState:u?.windowState??`unverified`,canReply:u?.canReply??!1,hasOlder:u?.hasOlder??!1,loadOlder:d,retry:f}}function Qe(e){let t=[];return e.forEach((e,n)=>{let r=De(e.at),i=t.length>0?t[t.length-1]:null;if(r===null&&i!==null){i.items.push({message:e,position:n});return}if(i!==null&&i.key===r){i.items.push({message:e,position:n});return}t.push({key:r,label:r!==null&&e.at!==null?Oe(e.at):null,items:[{message:e,position:n}]})}),t}function $e(e){let t=null;return e.map(e=>{let n=typeof e.service_state==`string`&&e.service_state!==``?e.service_state:null;return n===null||n===t?!1:(t=n,!0)})}function et(e){for(let t=e.length-1;t>=0;--t){let n=e[t].service_state;if(typeof n==`string`&&n!==``)return n}return null}function tt({fetcher:e,phone:t,displayName:n,className:r}){let{messages:i,status:a,error:o,windowState:s,canReply:c,hasOlder:u,loadOlder:d,retry:p}=Ze({fetcher:e,phone:t}),m=qe({fetcher:e,phone:t,windowState:s}),h=Xe(te(i,m.localMessages)),g=new Set(m.optimisticMessages),_=(0,l.useRef)(null),v=(0,l.useRef)(null),y=(0,l.useRef)(null);(0,l.useLayoutEffect)(()=>{let e=_.current;e!==null&&h.length!==0&&v.current!==t&&(v.current=t,e.scrollTop=e.scrollHeight)},[t,h]);let b=(0,l.useCallback)(()=>{let e=_.current;y.current=e===null?null:{scrollTop:e.scrollTop,scrollHeight:e.scrollHeight},d()},[d]);(0,l.useLayoutEffect)(()=>{if(a===`loading-older`)return;let e=y.current,t=_.current;y.current=null,e!==null&&t!==null&&(t.scrollTop=e.scrollTop+(t.scrollHeight-e.scrollHeight))},[a,h]);let ee=(0,l.useRef)(null);(0,l.useEffect)(()=>{if(typeof IntersectionObserver>`u`)return;let e=ee.current;if(e===null||!u)return;let t=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&b()});return t.observe(e),()=>t.disconnect()},[u,b]);let S=Qe(h),C=$e(h),ne=et(h),re=typeof n==`string`&&n.trim()!==``?n:null;return(0,x.jsxs)(`div`,{className:r?`wa-thread ${r}`:`wa-thread`,children:[(0,x.jsx)(`style`,{children:`
|
|
422
|
+
`}),(0,x.jsxs)(`form`,{className:`wa-list__filters`,onSubmit:ae,children:[(0,x.jsxs)(`div`,{className:`wa-list__search`,children:[(0,x.jsx)(`label`,{className:`wa-list__sr-only`,htmlFor:`${i}-phone`,children:`Buscar por nombre o teléfono`}),(0,x.jsxs)(`svg`,{className:`wa-list__search-icon`,viewBox:`0 0 16 16`,width:`14`,height:`14`,"aria-hidden":`true`,focusable:`false`,children:[(0,x.jsx)(`circle`,{cx:`7`,cy:`7`,r:`4.5`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`}),(0,x.jsx)(`path`,{d:`M10.5 10.5 14 14`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`})]}),(0,x.jsx)(`input`,{id:`${i}-phone`,type:`search`,placeholder:`Buscar por nombre o teléfono`,value:s,onChange:e=>c(e.target.value)})]}),(0,x.jsxs)(`div`,{className:`wa-list__presets`,role:`group`,"aria-label":`Filtrar por fecha`,children:[(0,x.jsx)(`button`,{type:`button`,className:`wa-list__preset`,"aria-pressed":m===`today`,onClick:()=>oe(`today`,1),children:`Hoy`}),(0,x.jsx)(`button`,{type:`button`,className:`wa-list__preset`,"aria-pressed":m===`7d`,onClick:()=>oe(`7d`,7),children:`7 días`}),(0,x.jsx)(`button`,{type:`button`,className:`wa-list__preset`,"aria-pressed":m===`30d`,onClick:()=>oe(`30d`,30),children:`30 días`}),(0,x.jsx)(`button`,{type:`button`,className:`wa-list__preset`,"aria-pressed":m===`range`,onClick:()=>h(`range`),children:`Rango…`})]}),m===`range`&&(0,x.jsxs)(`div`,{className:`wa-list__range`,children:[(0,x.jsx)(`label`,{className:`wa-list__sr-only`,htmlFor:`${i}-from`,children:`Desde`}),(0,x.jsx)(`input`,{id:`${i}-from`,type:`date`,className:`wa-list__date`,value:u,onChange:e=>se(e.target.value,f)}),(0,x.jsx)(`span`,{className:`wa-list__range-sep`,"aria-hidden":`true`,children:`→`}),(0,x.jsx)(`label`,{className:`wa-list__sr-only`,htmlFor:`${i}-to`,children:`Hasta`}),(0,x.jsx)(`input`,{id:`${i}-to`,type:`date`,className:`wa-list__date`,value:f,onChange:e=>se(u,e.target.value)})]}),w&&(0,x.jsx)(`button`,{type:`button`,className:`wa-list__clear`,onClick:ce,children:`Limpiar filtros`})]}),y===`loading`&&(0,x.jsx)(`p`,{className:`wa-list__note`,children:`Cargando conversaciones…`}),b!==null&&(0,x.jsxs)(`div`,{className:`wa-list__error`,role:`alert`,children:[(0,x.jsxs)(`p`,{children:[`No se pudieron cargar las conversaciones: `,b.message]}),(0,x.jsx)(`button`,{type:`button`,onClick:ne,children:`Reintentar`})]}),y===`empty`&&(0,x.jsx)(`p`,{className:`wa-list__note`,children:w?`No hay conversaciones con ese filtro.`:`No hay conversaciones todavía.`}),(0,x.jsx)(`ul`,{className:`wa-list__items`,children:v.map(e=>(0,x.jsx)(ee,{item:e,selected:e.phone===t,onSelect:ie},e.phone))}),C&&(0,x.jsx)(`button`,{ref:le,type:`button`,className:`wa-list__more`,onClick:()=>te(),disabled:y===`loading-more`,children:y===`loading-more`?`Cargando…`:`Cargar más`})]})}function Se({composer:e}){return e.failures.length===0?null:(0,x.jsx)(`div`,{className:`wa-composer__failures`,role:`alert`,children:e.failures.map(t=>(0,x.jsxs)(`div`,{className:`wa-composer__failure`,children:[(0,x.jsx)(`p`,{className:`wa-composer__failure-text`,children:t.failure===null?`No se pudo enviar el mensaje.`:le(t.failure)}),(0,x.jsxs)(`div`,{className:`wa-composer__failure-actions`,children:[t.failure?.retryable===!0&&(0,x.jsx)(`button`,{type:`button`,className:`wa-composer__failure-retry`,onClick:()=>e.retry(t.clientMessageId),children:`Reintentar`}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>e.dismiss(t.clientMessageId),children:`Descartar`})]})]},t.clientMessageId))})}function Ce({composer:e}){return e.releaseState===`released`?(0,x.jsx)(`p`,{className:`wa-composer__released`,role:`status`,children:`Listo: la conversación volvió al bot. La ventana sigue cerrada — se abre cuando la persona responda. Si necesitás retomarla en frío, la plantilla se manda desde el header del drawer del embudo.`}):(0,x.jsxs)(`div`,{className:`wa-composer__release`,children:[(0,x.jsxs)(`p`,{className:`wa-composer__release-explain`,children:[`Podés devolver la conversación al bot: se suelta el control y el bot vuelve a manejarla.`,` `,(0,x.jsx)(`strong`,{children:`No se le manda ningún mensaje a la persona y no te habilita a vos para seguir escribiendo`}),` — si responde, la ventana se abre y el composer vuelve solo. Para retomarla en frío con una plantilla, usá la acción del header del drawer del embudo.`]}),e.releaseState===`error`&&e.releaseFailure!==null&&(0,x.jsx)(`p`,{className:`wa-composer__release-error`,role:`alert`,children:le(e.releaseFailure)}),(e.releaseState!==`error`||e.releaseFailure?.retryable===!0)&&(0,x.jsx)(`button`,{type:`button`,className:`wa-composer__release-button`,onClick:e.release,disabled:e.releaseState===`releasing`,children:e.releaseState===`releasing`?`Devolviendo la conversación al bot…`:`Devolver la conversación al bot`})]})}function we({canReply:e,composer:t,onRetryWindow:n}){let[r,i]=(0,l.useState)(``);if(!e)return null;if(t.windowState===`closed`)return(0,x.jsxs)(`div`,{className:`wa-composer wa-composer--closed`,children:[(0,x.jsx)(Se,{composer:t}),(0,x.jsx)(`span`,{className:`wa-composer__lock`,children:(0,x.jsxs)(`svg`,{width:20,height:20,viewBox:`0 0 20 20`,fill:`none`,stroke:`#8A91A0`,strokeWidth:1.6,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":`true`,children:[(0,x.jsx)(`rect`,{x:`4.5`,y:`9`,width:`11`,height:`7.5`,rx:`1.5`}),(0,x.jsx)(`path`,{d:`M7 9V6.5a3 3 0 0 1 6 0V9`})]})}),(0,x.jsxs)(`div`,{role:`status`,children:[(0,x.jsx)(`p`,{className:`wa-composer__cold-title`,children:`La ventana de 24 horas está cerrada`}),(0,x.jsx)(`p`,{className:`wa-composer__cold-explain`,children:`WhatsApp solo permite responder hasta 24 h después del último mensaje del lifter. Se reabre cuando vuelva a escribir.`})]}),(0,x.jsx)(Ce,{composer:t})]});let a=()=>{let e=r.trim();e!==``&&(t.send(e),i(``))};return(0,x.jsxs)(`div`,{className:`wa-composer`,children:[t.windowState===`unverified`&&(0,x.jsxs)(`div`,{className:`wa-composer__unverified`,role:`status`,children:[(0,x.jsxs)(`div`,{className:`wa-composer__unverified-text`,children:[(0,x.jsx)(`p`,{className:`wa-composer__unverified-title`,children:`No pudimos verificar si se puede responder`}),(0,x.jsx)(`p`,{className:`wa-composer__unverified-explain`,children:`Es un error temporal, no una ventana cerrada.`})]}),n!==void 0&&(0,x.jsx)(`button`,{type:`button`,className:`wa-composer__retry-window`,onClick:n,children:`Reintentar`})]}),(0,x.jsx)(Se,{composer:t}),(0,x.jsxs)(`form`,{className:`wa-composer__form`,onSubmit:e=>{e.preventDefault(),a()},children:[(0,x.jsx)(`textarea`,{className:`wa-composer__input`,maxLength:ie,rows:2,value:r,placeholder:`Escribí tu respuesta…`,"aria-label":`Mensaje para la persona`,onChange:e=>i(e.target.value),onKeyDown:e=>{e.key!==`Enter`||e.shiftKey||e.nativeEvent.isComposing||(e.preventDefault(),a())}}),(0,x.jsxs)(`div`,{className:`wa-composer__hint-row`,children:[(0,x.jsx)(`span`,{className:`wa-composer__hint`,children:`Al enviar, el bot se pausa 2 h y la conversación queda tomada por ti`}),(0,x.jsxs)(`span`,{className:`wa-composer__counter`,children:[r.length,`/`,ie]}),(0,x.jsx)(`button`,{type:`submit`,className:`wa-composer__send`,disabled:r.trim()===``,children:`Enviar`})]})]})]})}const Te=[`enero`,`febrero`,`marzo`,`abril`,`mayo`,`junio`,`julio`,`agosto`,`septiembre`,`octubre`,`noviembre`,`diciembre`];function Ee(e){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}function De(e){if(typeof e!=`string`)return null;let t=Ee(e);return t===null?null:`${t.getFullYear()}-${t.getMonth()+1}-${t.getDate()}`}function Oe(e){let t=Ee(e);return t===null?``:`${t.getDate()} de ${Te[t.getMonth()]} de ${t.getFullYear()}`}const ke=new Set([`quick_reply`,`location`]),Ae=new Set([`http:`,`https:`]);function je(e){return(Array.isArray(e.ctas)?e.ctas:e.cta?[e.cta]:[]).filter(e=>e!=null&&typeof e.text==`string`&&e.text.trim()!==``)}function Me(e){if(typeof e.kind==`string`&&ke.has(e.kind))return!1;let t=typeof e.url==`string`?e.url.trim():``;if(t===``)return!1;try{return Ae.has(new URL(t).protocol)}catch{return!1}}function Ne(e){return e===`image`?`image`:e===`pdf`?`pdf`:`other`}function Pe(e,t){return typeof e.file_name==`string`&&e.file_name!==``?e.file_name:t}function Fe(){return(0,x.jsx)(`span`,{className:`wa-thread__media-unavailable`,children:`Adjunto no disponible`})}function Ie(){return(0,x.jsxs)(`svg`,{width:16,height:16,viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:1.5,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":`true`,children:[(0,x.jsx)(`path`,{d:`M8 2.5v7.5`}),(0,x.jsx)(`polyline`,{points:`4.5,6.8 8,10.3 11.5,6.8`}),(0,x.jsx)(`path`,{d:`M2.5 13.5h11`})]})}function Le({message:e,fetcher:t,mediaId:n}){let[r,i]=(0,l.useState)(()=>typeof e.media_url==`string`&&e.media_url!==``?{kind:`ready`,url:e.media_url}:{kind:`loading`}),[a,o]=(0,l.useState)(!1),s=(0,l.useRef)(!1),c=(0,l.useRef)(!1),u=(0,l.useRef)(!0);(0,l.useEffect)(()=>()=>{u.current=!1},[]),(0,l.useEffect)(()=>{if(s.current||(s.current=!0,typeof e.media_url==`string`&&e.media_url!==``))return;let r=!1;return D(t,{mediaId:n}).then(e=>{r||!u.current||i(e.url===``?{kind:`unavailable`}:{kind:`ready`,url:e.url})}).catch(()=>{!r&&u.current&&i({kind:`unavailable`})}),()=>{r=!0}},[t,n,e.media_url]),(0,l.useEffect)(()=>{if(!a)return;let e=e=>{e.key===`Escape`&&o(!1)};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[a]);let d=()=>{if(c.current){i({kind:`unavailable`});return}c.current=!0,i({kind:`loading`}),D(t,{mediaId:n}).then(e=>{u.current&&i(e.url===``?{kind:`unavailable`}:{kind:`ready`,url:e.url})}).catch(()=>{u.current&&i({kind:`unavailable`})})};if(r.kind===`loading`)return(0,x.jsx)(`span`,{className:`wa-thread__media-loading`,children:`Cargando adjunto…`});if(r.kind===`unavailable`)return(0,x.jsx)(Fe,{});let f=Pe(e,`Imagen adjunta`);return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`button`,{type:`button`,className:`wa-thread__media-button`,onClick:()=>o(!0),"aria-label":`Ampliar imagen adjunta`,children:(0,x.jsx)(`img`,{className:`wa-thread__media-img`,src:r.url,alt:f,onError:d})}),(0,x.jsxs)(`div`,{className:`wa-thread__media-file`,children:[(0,x.jsx)(`span`,{className:`wa-thread__media-name`,children:Pe(e,`Imagen adjunta`)}),(0,x.jsx)(Re,{message:e,fetcher:t,mediaId:n,variant:`icon`})]}),a&&(0,x.jsx)(`div`,{className:`wa-thread__lightbox`,role:`dialog`,"aria-label":`Imagen ampliada`,onClick:()=>o(!1),children:(0,x.jsx)(`img`,{className:`wa-thread__lightbox-img`,src:r.url,alt:f})})]})}function Re({message:e,fetcher:t,mediaId:n,variant:r=`label`}){let[i,a]=(0,l.useState)(!1),o=(0,l.useRef)(null),s=(0,l.useRef)(!1),c=(0,l.useRef)(!0);(0,l.useEffect)(()=>()=>{c.current=!1},[]);let u=e=>{if(s.current){s.current=!1;return}e.preventDefault(),D(t,{mediaId:n}).then(e=>{if(!c.current)return;let t=o.current;if(t!==null){if(e.url===``){a(!0);return}t.href=e.url,s.current=!0,t.click()}}).catch(()=>{c.current&&a(!0)})};return i?(0,x.jsx)(Fe,{}):r===`icon`?(0,x.jsx)(`a`,{ref:o,className:`wa-thread__media-download wa-thread__media-download--icon`,href:`#`,download:!0,target:`_blank`,rel:`noopener noreferrer`,onClick:u,"aria-label":`Descargar ${typeof e.file_name==`string`&&e.file_name!==``?e.file_name:`adjunto`}`,children:(0,x.jsx)(Ie,{})}):(0,x.jsx)(`a`,{ref:o,className:`wa-thread__media-download`,href:`#`,download:!0,target:`_blank`,rel:`noopener noreferrer`,onClick:u,children:Pe(e,`Descargar adjunto`)})}function ze({message:e,fetcher:t}){let n=e.media_id;if(n===null)return null;let r=(()=>{switch(Ne(e.media_format)){case`image`:return(0,x.jsx)(Le,{message:e,fetcher:t,mediaId:n});case`pdf`:return(0,x.jsx)(Re,{message:e,fetcher:t,mediaId:n});default:return(0,x.jsx)(Re,{message:e,fetcher:t,mediaId:n})}})();return(0,x.jsx)(`div`,{className:`wa-thread__media`,children:r})}const Be={131047:`Pasaron más de 24 h sin respuesta: hay que enviar una plantilla`,131026:`El número no puede recibir mensajes de WhatsApp`,131049:`Meta no lo entregó para cuidar la experiencia del usuario`,131e3:`Error interno de Meta`,131008:`Falta un parámetro obligatorio en el envío`,131031:`La cuenta de WhatsApp está bloqueada`,131042:`Problema de facturación en la cuenta de WhatsApp`,131051:`Tipo de mensaje no soportado`,132e3:`La plantilla no coincide con la cantidad de parámetros enviados`,132001:`La plantilla no existe o no está aprobada para este idioma`,132005:`El texto de la plantilla quedó demasiado largo`,132007:`La plantilla viola la política de formato`,132012:`Un parámetro de la plantilla no tiene el formato esperado`,132015:`La plantilla está pausada por baja calidad`,132016:`La plantilla está deshabilitada`};function Ve(e,t){if(typeof e==`number`&&Object.prototype.hasOwnProperty.call(Be,e))return Be[e];let n=typeof t==`string`?t.trim():``;return n===``?null:n}function He(e){switch(e){case`pending`:return{kind:`clock`,label:`Pendiente`};case`sent`:return{kind:`check`,label:`Enviado`};case`delivered`:return{kind:`check-check`,label:`Entregado`};case`read`:return{kind:`check-check`,label:`Leído`};default:return null}}function Ue({kind:e}){return e===`clock`?(0,x.jsx)(x.Fragment,{children:`◷`}):(0,x.jsxs)(`svg`,{width:16,height:16,viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:1.8,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":`true`,children:[(0,x.jsx)(`polyline`,{points:`2.5,8.5 6,12 13,4.5`}),e===`check-check`&&(0,x.jsx)(`polyline`,{points:`7,10.2 8.7,12 15.3,4.8`})]})}function We(e){if(typeof e!=`string`)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`}function Ge({message:e,optimistic:t=!1,fetcher:n}){let r=e.direction===`out`?`out`:`in`,i=We(e.at),a=je(e),o=r===`out`?He(e.status):null,s=r===`out`&&e.status===`failed`,c=s?Ve(e.error_code,e.error_title):null,l=typeof e.sent_by_name==`string`&&e.sent_by_name.trim()!==``?e.sent_by_name:null,u=r===`out`?l!==null||t?`operator`:`bot`:void 0,d=e.body===null&&e.message_type===`location`?e.location_name??`Ubicación compartida`:null;return(0,x.jsxs)(`div`,{className:`wa-thread__bubble`,"data-direction":r,"data-author":u,"data-failed":s||void 0,children:[l!==null&&(0,x.jsx)(`span`,{className:`wa-thread__author`,children:l}),e.body!==null&&(0,x.jsx)(`p`,{className:`wa-thread__body`,children:e.body}),d!==null&&(0,x.jsx)(`p`,{className:`wa-thread__body`,children:d}),e.media_id!==null&&(0,x.jsx)(ze,{message:e,fetcher:n}),a.length>0&&(0,x.jsx)(`div`,{className:`wa-thread__ctas`,children:a.map((e,t)=>Me(e)?(0,x.jsx)(`a`,{className:`wa-thread__cta wa-thread__cta--link`,href:e.url??void 0,target:`_blank`,rel:`noopener noreferrer`,children:e.text},`${t}-${e.text}`):(0,x.jsx)(`span`,{className:`wa-thread__cta wa-thread__cta--inert`,children:e.text},`${t}-${e.text}`))}),(0,x.jsxs)(`span`,{className:`wa-thread__meta`,children:[i!==null&&e.at!==null&&(0,x.jsx)(`time`,{className:`wa-thread__hour`,dateTime:e.at,title:e.at,children:i}),s?(0,x.jsxs)(`span`,{className:`wa-thread__failed`,children:[`No entregado`,c!==null&&(0,x.jsxs)(`span`,{className:`wa-thread__failed-reason`,children:[` · `,c]})]}):o!==null&&(0,x.jsx)(`span`,{className:`wa-thread__tick`,"data-status":e.status,title:o.label,"aria-label":o.label,children:(0,x.jsx)(Ue,{kind:o.kind})})]})]})}const Ke={collecting_vehicle_plate:`Placa del vehículo`,collecting_vehicle_documents:`Documentos del vehículo`,collecting_documents:`Documentos personales`,existing_user_menu:`Menú de usuario registrado`,activated:`Cuenta activada`};function qe(e){return Object.prototype.hasOwnProperty.call(Ke,e)?Ke[e]:e}function Je(e,t){return{fetcher:e,phone:t,outgoing:[],windowStateOverride:null,releaseState:`idle`,releaseFailure:null}}function Ye({fetcher:e,phone:t,windowState:n}){let[r,i]=(0,l.useState)(null),a=r!==null&&r.fetcher===e&&r.phone===t?r:null,o=(0,l.useCallback)(n=>{i(r=>r===null||r.fetcher!==e||r.phone!==t?r:n(r))},[e,t]),s=(0,l.useCallback)((e,t)=>{o(n=>({...n,outgoing:n.outgoing.map(n=>n.clientMessageId===e?t(n):n)}))},[o]),c=(0,l.useCallback)(n=>{pe(e,{phone:t,text:n.text,clientMessageId:n.clientMessageId}).then(e=>{s(n.clientMessageId,t=>({...t,status:`sent`,message:e,failure:null})),o(e=>({...e,windowStateOverride:`open`}))},e=>{let t=ce(e);s(n.clientMessageId,e=>({...e,status:`failed`,message:{...e.message,status:`failed`},failure:t})),t.windowState!==null&&o(e=>({...e,windowStateOverride:t.windowState}))})},[e,t,o,s]),u=(0,l.useCallback)(n=>{let r=n.trim();if(r===``||r.length>4096)return;let a=ae(),o={clientMessageId:a,text:r,status:`pending`,message:oe(r,new Date().toISOString(),a),failure:null};i(n=>{let r=n!==null&&n.fetcher===e&&n.phone===t?n:Je(e,t);return{...r,outgoing:[...r.outgoing,o]}}),c(o)},[c,e,t]),d=(0,l.useCallback)(e=>{let t=a?.outgoing.find(t=>t.clientMessageId===e);if(t===void 0||t.status!==`failed`||t.failure!==null&&!t.failure.retryable)return;let n={...t,status:`pending`,message:{...t.message,status:`pending`},failure:null};s(e,()=>n),c(n)},[a,c,s]),f=(0,l.useCallback)(e=>{o(t=>({...t,outgoing:t.outgoing.filter(t=>t.clientMessageId!==e)}))},[o]),p=(0,l.useCallback)(()=>{a?.releaseState!==`releasing`&&(i(n=>({...n!==null&&n.fetcher===e&&n.phone===t?n:Je(e,t),releaseState:`releasing`,releaseFailure:null})),me(e,{phone:t}).then(()=>{o(e=>({...e,releaseState:`released`,releaseFailure:null,windowStateOverride:`closed`}))},e=>{o(t=>({...t,releaseState:`error`,releaseFailure:ce(e)}))}))},[a,e,o,t]),m=a?.outgoing??[];return{outgoing:m,localMessages:m.map(e=>e.message),optimisticMessages:m.filter(e=>e.status!==`sent`).map(e=>e.message),failures:m.filter(e=>e.status===`failed`),windowState:a?.windowStateOverride??n,sending:m.some(e=>e.status===`pending`),send:u,retry:d,dismiss:f,releaseState:a?.releaseState??`idle`,releaseFailure:a?.releaseFailure??null,release:p}}function Xe(e){return e instanceof Error?e:Error(String(e))}function Ze(e){if(typeof e!=`string`)return 1/0;let t=Date.parse(e);return Number.isNaN(t)?1/0:t}function Qe(e){return e.map((e,t)=>({message:e,index:t,key:Ze(e.at)})).sort((e,t)=>e.key===t.key?e.index-t.index:e.key<t.key?-1:1).map(e=>e.message)}function $e({fetcher:e,phone:t}){let[n,r]=(0,l.useState)(null),[i,a]=(0,l.useState)(0),o=(0,l.useRef)(null),s=(0,l.useCallback)(()=>{o.current?.abort();let e=new AbortController;return o.current=e,e},[]),c=(0,l.useCallback)(e=>{o.current===e&&(o.current=null)},[]);(0,l.useEffect)(()=>{let n=s();return fe(e,{phone:t},{signal:n.signal}).then(i=>{if(n.signal.aborted)return;c(n);let a=Qe(i.messages);r({fetcher:e,phone:t,messages:a,windowState:C(i.window_state),canReply:i.can_reply===!0,takenBy:i.taken_by??null,takenUntil:i.taken_until??null,takenByMe:i.taken_by_me===!0,status:a.length>0?`ready`:`empty`,error:null,olderCursor:i.older_cursor,hasOlder:i.older_cursor!==null})},i=>{n.signal.aborted||(c(n),r({fetcher:e,phone:t,messages:[],windowState:`unverified`,canReply:!1,takenBy:null,takenUntil:null,takenByMe:!1,status:`error`,error:Xe(i),olderCursor:null,hasOlder:!1}))}),()=>n.abort()},[e,t,i,s,c]);let u=n!==null&&n.fetcher===e&&n.phone===t?n:null,d=(0,l.useCallback)(()=>{if(u===null||!u.hasOlder||o.current!==null)return;let n=u.olderCursor;if(n===null)return;let i={...u,status:`loading-older`,error:null};r(i);let a=s();fe(e,{phone:t,cursor:n},{signal:a.signal}).then(e=>{if(a.signal.aborted)return;c(a);let t=new Set(i.messages.map(e=>e.id).filter(e=>typeof e==`string`&&e!==``));if(!e.messages.some(e=>typeof e.id==`string`&&e.id!==``&&!t.has(e.id))){r({...i,status:`ready`,error:null,hasOlder:!1});return}let n=Qe(ne([...e.messages,...i.messages]));r({...i,messages:n,status:`ready`,error:null,olderCursor:e.older_cursor,hasOlder:e.older_cursor!==null})},e=>{a.signal.aborted||(c(a),r({...i,status:`error`,error:Xe(e)}))})},[e,t,u,s,c]),f=(0,l.useCallback)(()=>{if(u!==null&&u.status===`error`&&u.messages.length>0){d();return}r(null),a(e=>e+1)},[u,d]);return{messages:u?.messages??[],status:u?.status??`loading`,error:u?.error??null,windowState:u?.windowState??`unverified`,canReply:u?.canReply??!1,takenBy:u?.takenBy??null,takenUntil:u?.takenUntil??null,takenByMe:u?.takenByMe??!1,hasOlder:u?.hasOlder??!1,loadOlder:d,retry:f}}function et(e,t=Date.now()){if(typeof e!=`string`)return null;let n=Date.parse(e);if(Number.isNaN(n))return null;let r=n-t;if(r<=0)return null;let i=Math.max(1,Math.ceil(r/6e4)),a=Math.floor(i/60),o=i%60;return a===0?`${o} m`:o===0?`${a} h`:`${a} h ${o} m`}function tt(e){let t=[];return e.forEach((e,n)=>{let r=De(e.at),i=t.length>0?t[t.length-1]:null;if(r===null&&i!==null){i.items.push({message:e,position:n});return}if(i!==null&&i.key===r){i.items.push({message:e,position:n});return}t.push({key:r,label:r!==null&&e.at!==null?Oe(e.at):null,items:[{message:e,position:n}]})}),t}function nt(e){let t=null;return e.map(e=>{let n=typeof e.service_state==`string`&&e.service_state!==``?e.service_state:null;return n===null||n===t?!1:(t=n,!0)})}function rt(e){for(let t=e.length-1;t>=0;--t){let n=e[t].service_state;if(typeof n==`string`&&n!==``)return n}return null}function it({takenBy:e,takenUntil:t,takenByMe:n,composer:r}){if(r.releaseState===`released`)return null;let i=et(t);return e===null&&i===null?null:(0,x.jsxs)(`div`,{className:`wa-thread__takeover`,"data-mine":n||void 0,role:`status`,children:[(0,x.jsxs)(`span`,{className:`wa-thread__takeover-text`,children:[n?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`strong`,{children:`Bot en pausa`}),` — la tomaste tú`]}):(0,x.jsxs)(x.Fragment,{children:[`Tomada por `,(0,x.jsx)(`strong`,{children:e??`otro operador`})]}),i!==null&&` · se libera en ${i}`]}),n&&(0,x.jsx)(`button`,{type:`button`,className:`wa-thread__takeover-button`,onClick:r.release,disabled:r.releaseState===`releasing`,children:r.releaseState===`releasing`?`Reactivando…`:`Reactivar bot`})]})}function at({fetcher:e,phone:t,displayName:n,className:r}){let{messages:i,status:a,error:o,windowState:s,canReply:c,takenBy:u,takenUntil:d,takenByMe:p,hasOlder:m,loadOlder:h,retry:g}=$e({fetcher:e,phone:t}),_=Ye({fetcher:e,phone:t,windowState:s}),v=Qe(te(i,_.localMessages)),y=new Set(_.optimisticMessages),b=(0,l.useRef)(null),ee=(0,l.useRef)(null),S=(0,l.useRef)(null);(0,l.useLayoutEffect)(()=>{let e=b.current;e!==null&&v.length!==0&&ee.current!==t&&(ee.current=t,e.scrollTop=e.scrollHeight)},[t,v]);let C=(0,l.useCallback)(()=>{let e=b.current;S.current=e===null?null:{scrollTop:e.scrollTop,scrollHeight:e.scrollHeight},h()},[h]);(0,l.useLayoutEffect)(()=>{if(a===`loading-older`)return;let e=S.current,t=b.current;S.current=null,e!==null&&t!==null&&(t.scrollTop=e.scrollTop+(t.scrollHeight-e.scrollHeight))},[a,v]);let ne=(0,l.useRef)(null);(0,l.useEffect)(()=>{if(typeof IntersectionObserver>`u`)return;let e=ne.current;if(e===null||!m)return;let t=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&C()});return t.observe(e),()=>t.disconnect()},[m,C]);let re=tt(v),w=nt(v),ie=rt(v),ae=typeof n==`string`&&n.trim()!==``?n:null;return(0,x.jsxs)(`div`,{className:r?`wa-thread ${r}`:`wa-thread`,children:[(0,x.jsx)(`style`,{children:`
|
|
399
423
|
.wa-thread {
|
|
400
424
|
box-sizing: border-box;
|
|
401
425
|
display: flex;
|
|
@@ -542,6 +566,52 @@ var b=e((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.
|
|
|
542
566
|
border-color: #e5b9b6;
|
|
543
567
|
background: #fdf6f6;
|
|
544
568
|
}
|
|
569
|
+
/* DEV-5065: el motivo, dentro del mismo bloque rojo que «No entregado». Peso normal para que la
|
|
570
|
+
jerarquía se lea —el titular manda, el motivo explica— y sin ancho fijo: los textos crudos de
|
|
571
|
+
Meta que caen por el fallback verbatim pueden ser largos y tienen que poder envolver. */
|
|
572
|
+
.wa-thread__failed-reason {
|
|
573
|
+
font-weight: 400;
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
/* DEV-5061 — la barra de takeover, entre el header y el scroller. Ámbar cuando la tiene otro
|
|
577
|
+
(es un aviso: no escribas encima) y añil cuando es tuya (es tu control, con su acción). Los
|
|
578
|
+
dos tonos son los de la paleta que fijó DEV-5053. */
|
|
579
|
+
.wa-thread__takeover {
|
|
580
|
+
display: flex;
|
|
581
|
+
align-items: center;
|
|
582
|
+
justify-content: space-between;
|
|
583
|
+
gap: 12px;
|
|
584
|
+
flex-wrap: wrap;
|
|
585
|
+
padding: 8px 12px;
|
|
586
|
+
border-bottom: 1px solid #e4e7ee;
|
|
587
|
+
background: #fff7e8;
|
|
588
|
+
color: #b7791f;
|
|
589
|
+
font-size: 13px;
|
|
590
|
+
}
|
|
591
|
+
.wa-thread__takeover[data-mine='true'] {
|
|
592
|
+
background: #f4f5ff;
|
|
593
|
+
color: #4f5aed;
|
|
594
|
+
}
|
|
595
|
+
.wa-thread__takeover-text {
|
|
596
|
+
min-width: 0;
|
|
597
|
+
}
|
|
598
|
+
/* Pill, el mismo molde que el Reintentar de DEV-5053 P7. \`currentColor\` es lo que hace que el
|
|
599
|
+
botón siga al tono de la barra sin duplicar la regla por variante. */
|
|
600
|
+
.wa-thread__takeover-button {
|
|
601
|
+
flex: none;
|
|
602
|
+
padding: 4px 12px;
|
|
603
|
+
border: 1px solid currentColor;
|
|
604
|
+
border-radius: 999px;
|
|
605
|
+
background: #fff;
|
|
606
|
+
color: inherit;
|
|
607
|
+
font: inherit;
|
|
608
|
+
font-weight: 600;
|
|
609
|
+
cursor: pointer;
|
|
610
|
+
}
|
|
611
|
+
.wa-thread__takeover-button:disabled {
|
|
612
|
+
opacity: 0.6;
|
|
613
|
+
cursor: default;
|
|
614
|
+
}
|
|
545
615
|
|
|
546
616
|
/* El operador que escribió la saliente, sobre la burbuja. */
|
|
547
617
|
.wa-thread__author {
|
|
@@ -1009,7 +1079,7 @@ var b=e((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.
|
|
|
1009
1079
|
.wa-composer__failure-actions button.wa-composer__failure-retry:hover {
|
|
1010
1080
|
background: #FDF6F6;
|
|
1011
1081
|
}
|
|
1012
|
-
`}),a===`loading`&&(0,x.jsx)(`p`,{className:`wa-thread__note`,children:`Cargando conversación…`}),o!==null&&(0,x.jsxs)(`div`,{className:`wa-thread__error`,role:`alert`,children:[(0,x.jsxs)(`p`,{children:[`No se pudo cargar la conversación: `,o.message]}),(0,x.jsx)(`button`,{type:`button`,onClick:
|
|
1082
|
+
`}),a===`loading`&&(0,x.jsx)(`p`,{className:`wa-thread__note`,children:`Cargando conversación…`}),o!==null&&(0,x.jsxs)(`div`,{className:`wa-thread__error`,role:`alert`,children:[(0,x.jsxs)(`p`,{children:[`No se pudo cargar la conversación: `,o.message]}),(0,x.jsx)(`button`,{type:`button`,onClick:g,children:`Reintentar`})]}),a===`empty`&&(0,x.jsx)(`p`,{className:`wa-thread__note`,children:`Sin mensajes en esta conversación.`}),(0,x.jsxs)(`div`,{className:`wa-thread__header`,children:[(0,x.jsxs)(`div`,{className:`wa-thread__identity`,children:[(0,x.jsx)(`span`,{className:`wa-thread__avatar`,"aria-hidden":`true`,children:f(ae,t)}),(0,x.jsxs)(`span`,{className:`wa-thread__who`,children:[(0,x.jsx)(`span`,{className:`wa-thread__name`,children:ae??t}),ae!==null&&(0,x.jsx)(`span`,{className:`wa-thread__phone`,children:t})]})]}),ie!==null&&(0,x.jsx)(`div`,{className:`wa-thread__chips`,children:(0,x.jsxs)(`span`,{className:`wa-thread__step`,title:ie,children:[`Paso: `,qe(ie)]})})]}),(0,x.jsx)(it,{takenBy:u,takenUntil:d,takenByMe:p,composer:_}),(0,x.jsxs)(`div`,{className:`wa-thread__messages`,ref:b,children:[m&&(0,x.jsx)(`button`,{ref:ne,type:`button`,className:`wa-thread__older`,onClick:C,disabled:a===`loading-older`,children:a===`loading-older`?`Cargando…`:`Cargar mensajes anteriores`}),re.map((t,n)=>(0,x.jsxs)(`div`,{className:`wa-thread__group`,children:[t.label!==null&&(0,x.jsx)(`div`,{className:`wa-thread__day`,children:t.label}),t.items.map(({message:t,position:n})=>(0,x.jsxs)(l.Fragment,{children:[w[n]&&typeof t.service_state==`string`&&t.service_state!==``&&(0,x.jsxs)(`div`,{className:`wa-thread__flow-pill`,children:[`El flujo pasó a `,qe(t.service_state)]}),(0,x.jsx)(Ge,{message:t,optimistic:y.has(t),fetcher:e})]},t.id??`sin-wamid-${n}`))]},t.key??`sin-dia-${n}`))]}),(0,x.jsx)(we,{canReply:c,composer:_,onRetryWindow:g})]})}function ot({fetcher:e,initialPhone:t,pinned:n=!1,className:r}){let i=(0,l.useRef)(null),a=S(i),[o,s]=(0,l.useState)(t??null),[c,u]=(0,l.useState)(null),d=r?`wa-conversations ${r}`:`wa-conversations`;if(e===void 0)return(0,x.jsx)(`div`,{className:d,children:(0,x.jsx)(`p`,{children:`Visor de conversaciones de WhatsApp — falta el fetcher del host.`})});let f=n&&o!==null;return(0,x.jsxs)(`div`,{ref:i,className:d,"data-layout":a,children:[(0,x.jsx)(`style`,{children:`
|
|
1013
1083
|
.wa-conversations {
|
|
1014
1084
|
box-sizing: border-box;
|
|
1015
1085
|
display: flex;
|
|
@@ -1067,7 +1137,7 @@ var b=e((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.
|
|
|
1067
1137
|
font-size: 13px;
|
|
1068
1138
|
color: #8A91A0;
|
|
1069
1139
|
}
|
|
1070
|
-
`}),!f&&(a===`wide`||o===null)&&(0,x.jsx)(xe,{fetcher:e,selectedPhone:o,onSelect:e=>{s(e.phone),u(e.name)}}),o===null?a===`wide`&&(0,x.jsx)(`p`,{className:`wa-conversations__empty`,children:`Selecciona una conversación`}):(0,x.jsxs)(`div`,{className:`wa-conversations__thread`,children:[a===`narrow`&&!f&&(0,x.jsx)(`button`,{type:`button`,className:`wa-conversations__back`,onClick:()=>{s(null),u(null)},children:`Volver`}),(0,x.jsx)(
|
|
1140
|
+
`}),!f&&(a===`wide`||o===null)&&(0,x.jsx)(xe,{fetcher:e,selectedPhone:o,onSelect:e=>{s(e.phone),u(e.name)}}),o===null?a===`wide`&&(0,x.jsx)(`p`,{className:`wa-conversations__empty`,children:`Selecciona una conversación`}):(0,x.jsxs)(`div`,{className:`wa-conversations__thread`,children:[a===`narrow`&&!f&&(0,x.jsx)(`button`,{type:`button`,className:`wa-conversations__back`,onClick:()=>{s(null),u(null)},children:`Volver`}),(0,x.jsx)(at,{fetcher:e,phone:o,displayName:c})]})]})}function st(e){let t;try{t=new URL(e)}catch{throw Error(`api-url inválida: no es una URL absoluta`)}if(t.protocol!==`http:`&&t.protocol!==`https:`)throw Error(`api-url inválida: esquema no permitido (${t.protocol})`)}function ct(e,t,n){if(n.resource===`media`)return{url:new URL(`${e}/conversations/media/${encodeURIComponent(n.mediaId)}`),init:{}};if(n.resource===`thread`){let r=new URL(`${e}/conversations/${t}/${encodeURIComponent(n.phone)}/thread`);return n.cursor!==void 0&&r.searchParams.set(`cursor`,n.cursor),n.limit!==void 0&&r.searchParams.set(`limit`,String(n.limit)),{url:r,init:{}}}if(n.resource===`reply`)return{url:new URL(`${e}/conversations/${t}/${encodeURIComponent(n.phone)}/reply`),init:{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:n.text,client_message_id:n.clientMessageId})}};if(n.resource===`release`)return{url:new URL(`${e}/conversations/${t}/${encodeURIComponent(n.phone)}/release`),init:{method:`POST`}};let r=new URL(`${e}/conversations`);return r.searchParams.set(`phone_number_id`,t),n.phone!==void 0&&r.searchParams.set(`phone`,n.phone),n.from!==void 0&&r.searchParams.set(`from`,n.from),n.to!==void 0&&r.searchParams.set(`to`,n.to),n.cursor!==void 0&&r.searchParams.set(`cursor`,n.cursor),n.limit!==void 0&&r.searchParams.set(`limit`,String(n.limit)),{url:r,init:{}}}async function lt(e){let t;try{t=await e.text()}catch{return{text:``,body:null}}try{return{text:t,body:JSON.parse(t)}}catch{return{text:t,body:null}}}function ut(e,t){return async(n,r)=>{let i=!1;for(;;){let a=e.getAttribute(`api-url`)??``,o=e.getAttribute(`phone-number-id`)??``;st(a);let{url:s,init:c}=ct(a,o,n),l=e.getAttribute(`token`)??``,u=await fetch(s,{...c,headers:{...c.headers,authorization:`Bearer ${l}`},signal:r?.signal});if(!(u.status===401&&t!==void 0&&!i&&(i=!0,(e.getAttribute(`token`)??``)!==l||!t.pending()&&(e.dispatchEvent(new CustomEvent(`wa-conversations:unauthorized`,{bubbles:!0,composed:!0,detail:{status:401}})),(e.getAttribute(`token`)??``)!==l)||await t()))){if(!u.ok){let{text:e,body:t}=await lt(u);throw new ue(u.status,`${u.status} ${e}`,t)}return u.json()}}}}var dt=`:host {
|
|
1071
1141
|
height: 100%;
|
|
1072
1142
|
display: block;
|
|
1073
1143
|
}
|
|
@@ -1115,4 +1185,4 @@ var b=e((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.
|
|
|
1115
1185
|
color: #5d6b76;
|
|
1116
1186
|
margin: 0;
|
|
1117
1187
|
}
|
|
1118
|
-
`;const
|
|
1188
|
+
`;const ft=[`phone-number-id`,`api-url`,`token`];let pt;function mt(){return pt||(pt=new CSSStyleSheet,pt.replaceSync(dt)),pt}function ht(){if(typeof HTMLElement>`u`||typeof customElements>`u`||customElements.get(`wa-conversations`))return;class e extends HTMLElement{static observedAttributes=[...ft,`phone`,`pinned`];#e=null;#t;#n;#r=null;get fetcher(){return this.#t}set fetcher(e){this.#t=e,this.#e!==null&&this.#c()}connectedCallback(){this.#i(`fetcher`);let e=this.shadowRoot??this.attachShadow({mode:`open`});e.adoptedStyleSheets=[mt()],this.#e??=(0,u.createRoot)(e),this.#c()}attributeChangedCallback(e,t,n){t!==n&&(e===`token`&&n!==null&&this.#o(!0),this.#e!==null&&this.#c())}#i(e){if(Object.prototype.hasOwnProperty.call(this,e)){let t=this,n=t[e];delete t[e],this[e]=n}}#a=Object.assign((e=3e3)=>{if(this.#r===null){let t,n=new Promise(e=>{t=e}),r=setTimeout(()=>this.#o(!1),e);this.#r={promise:n,resolve:t,timer:r}}return this.#r.promise},{pending:()=>this.#r!==null});#o(e){let t=this.#r;t!==null&&(this.#r=null,clearTimeout(t.timer),t.resolve(e))}#s(){return this.#t===void 0?ft.some(e=>{let t=this.getAttribute(e);return t===null||t===``})?null:(this.#n??=ut(this,this.#a),this.#n):this.#t}#c(){if(this.#e===null)return;let e=this.#s();if(e===null){this.#e.render(null),this.#u();return}this.#d();let t=this.getAttribute(`phone`),n=this.hasAttribute(`pinned`)&&this.getAttribute(`pinned`)!==`false`,r=`${this.getAttribute(`phone-number-id`)??``}#${this.getAttribute(`api-url`)??``}#${t??``}#${n}`;this.#e.render((0,l.createElement)(ot,{key:r,fetcher:e,initialPhone:t??void 0,pinned:n}))}#l=null;#u(){this.#d();let e=this.shadowRoot;if(e===null)return;let t=document.createElement(`div`);t.className=`wa-config-panel`;let n=document.createElement(`p`);n.className=`wa-config-panel__title`,n.textContent=`Visor de conversaciones — configuración incompleta`,t.appendChild(n);let r=document.createElement(`p`);r.className=`wa-config-panel__intro`,r.textContent=`Para montar el visor faltan estos atributos:`,t.appendChild(r);let i=document.createElement(`ul`);i.className=`wa-config-panel__list`;for(let e of ft){let t=this.getAttribute(e);if(t!==null&&t!==``)continue;let n=document.createElement(`li`),r=document.createElement(`code`);r.textContent=e,n.appendChild(r),i.appendChild(n)}t.appendChild(i);let a=document.createElement(`p`);a.className=`wa-config-panel__hint`;let o=document.createElement(`code`);o.textContent=`@liftitapp/wa-conversations`;let s=document.createElement(`code`);s.textContent=`fetcher`,a.append(`Consulta el README de `,o,` — o asigna la property `,s,` desde JavaScript.`),t.appendChild(a),e.appendChild(t),this.#l=t}#d(){this.#l?.remove(),this.#l=null}disconnectedCallback(){queueMicrotask(()=>{this.isConnected||(this.#e?.unmount(),this.#e=null)})}}customElements.define(`wa-conversations`,e)}ht();
|
package/dist/react/index.d.ts
CHANGED
|
@@ -132,6 +132,26 @@ interface ThreadMessage {
|
|
|
132
132
|
flow_files?: unknown[];
|
|
133
133
|
/** Presente en el fixture, ausente del apéndice B. Lo origina el lifter: es entrada no confiable. */
|
|
134
134
|
file_name?: string | null;
|
|
135
|
+
/**
|
|
136
|
+
* Por qué falló la entrega — **DEV-5065**, aditivo. Sólo tiene valor cuando `status` es
|
|
137
|
+
* `failed`, y ni siquiera siempre: un `failed` de un emisor que no reporta el motivo, o
|
|
138
|
+
* anterior al cambio, llega en `null`.
|
|
139
|
+
*
|
|
140
|
+
* Para qué existe: un tick rojo que sólo dice «falló» no le sirve al operador. Los tres motivos
|
|
141
|
+
* frecuentes se resuelven de forma **distinta** — número inválido (el dato está mal), ventana de
|
|
142
|
+
* 24 h cerrada (hay que mandar plantilla) y plantilla rechazada (hay que arreglar la plantilla)—
|
|
143
|
+
* y sin el motivo los tres se ven idénticos.
|
|
144
|
+
*
|
|
145
|
+
* `error_code` es el código numérico de Meta y es lo que se mapea a español. `error_title` es su
|
|
146
|
+
* texto de sistema (`"Re-engagement message"`), y es el **fallback verbatim** cuando el código no
|
|
147
|
+
* está en el mapa: mismo criterio que `service_state` en DEV-5053, mostrar el valor crudo antes
|
|
148
|
+
* que no mostrar nada.
|
|
149
|
+
*
|
|
150
|
+
* ⚠️ El store guarda estos dos campos y **no** el `errors[]` crudo de Meta, a propósito: varios
|
|
151
|
+
* códigos traen `error_data.details` con el número de la persona adentro. No pedir el crudo.
|
|
152
|
+
*/
|
|
153
|
+
error_code?: number | null;
|
|
154
|
+
error_title?: string | null;
|
|
135
155
|
}
|
|
136
156
|
/** El sobre del hilo: los mensajes más el estado de la ventana de 24h. */
|
|
137
157
|
interface LeadThreadResponse {
|
|
@@ -158,6 +178,34 @@ interface LeadThreadResponse {
|
|
|
158
178
|
* en `loadThread`, no acá.
|
|
159
179
|
*/
|
|
160
180
|
can_reply?: boolean;
|
|
181
|
+
/**
|
|
182
|
+
* **DEV-5061** — quién tiene tomada la conversación, si es que alguien la tiene.
|
|
183
|
+
*
|
|
184
|
+
* El store ya guardaba el takeover y el bot ya se calla cuando un operador toma, pero nada de
|
|
185
|
+
* eso llegaba al visor: una conversación atendida por un compañero se veía **idéntica** a una
|
|
186
|
+
* libre. El operador entraba, escribía, y recién ahí se enteraba — o no se enteraba y dos
|
|
187
|
+
* personas respondían el mismo hilo.
|
|
188
|
+
*
|
|
189
|
+
* `taken_by` es el **nombre** del operador y jamás su email: el servidor no lo emite ni bajo
|
|
190
|
+
* otra clave, misma regla que `sent_by_name`.
|
|
191
|
+
*
|
|
192
|
+
* `taken_until` es un **instante ISO-8601**, no «minutos restantes». Un relativo calculado en el
|
|
193
|
+
* servidor queda viejo apenas el visor lo tiene en pantalla; el conteo hacia atrás lo hace el
|
|
194
|
+
* front desde el instante, igual que con `window_expires_at`.
|
|
195
|
+
*
|
|
196
|
+
* `taken_by_me` lo decide el **servidor** comparando identidades, no nombres — dos operadores
|
|
197
|
+
* pueden llamarse igual, y confundirlos le daría a uno el botón «Reactivar bot» del otro. No
|
|
198
|
+
* intentar derivarlo acá comparando `taken_by`.
|
|
199
|
+
*
|
|
200
|
+
* Un takeover **vencido llega como libre**: el servidor compara contra su reloj antes de
|
|
201
|
+
* emitirlo, así que `taken_until` nunca viene en el pasado y no hay que filtrarlo acá.
|
|
202
|
+
*
|
|
203
|
+
* Los tres son opcionales —como se hizo con `can_reply`— para que un backend viejo que no los
|
|
204
|
+
* emita no rompa al visor. Ausente se lee como «libre».
|
|
205
|
+
*/
|
|
206
|
+
taken_by?: string | null;
|
|
207
|
+
taken_until?: string | null;
|
|
208
|
+
taken_by_me?: boolean;
|
|
161
209
|
/** E2 — el bot dueño de la conversación. La unicidad es `(phone_number_id, phone)`, nunca el teléfono solo. */
|
|
162
210
|
phone_number_id: string;
|
|
163
211
|
/** E2 — qué servicio la originó (`self_onboarding_whatsapp`, y los que vengan). */
|
|
@@ -249,6 +297,34 @@ interface ConversationSummary {
|
|
|
249
297
|
* simplemente no se muestra.
|
|
250
298
|
*/
|
|
251
299
|
service_state: string | null;
|
|
300
|
+
/**
|
|
301
|
+
* **DEV-5061** — quién tiene tomada la conversación, si es que alguien la tiene.
|
|
302
|
+
*
|
|
303
|
+
* El store ya guardaba el takeover y el bot ya se calla cuando un operador toma, pero nada de
|
|
304
|
+
* eso llegaba al visor: una conversación atendida por un compañero se veía **idéntica** a una
|
|
305
|
+
* libre. El operador entraba, escribía, y recién ahí se enteraba — o no se enteraba y dos
|
|
306
|
+
* personas respondían el mismo hilo.
|
|
307
|
+
*
|
|
308
|
+
* `taken_by` es el **nombre** del operador y jamás su email: el servidor no lo emite ni bajo
|
|
309
|
+
* otra clave, misma regla que `sent_by_name`.
|
|
310
|
+
*
|
|
311
|
+
* `taken_until` es un **instante ISO-8601**, no «minutos restantes». Un relativo calculado en el
|
|
312
|
+
* servidor queda viejo apenas el visor lo tiene en pantalla; el conteo hacia atrás lo hace el
|
|
313
|
+
* front desde el instante, igual que con `window_expires_at`.
|
|
314
|
+
*
|
|
315
|
+
* `taken_by_me` lo decide el **servidor** comparando identidades, no nombres — dos operadores
|
|
316
|
+
* pueden llamarse igual, y confundirlos le daría a uno el botón «Reactivar bot» del otro. No
|
|
317
|
+
* intentar derivarlo acá comparando `taken_by`.
|
|
318
|
+
*
|
|
319
|
+
* Un takeover **vencido llega como libre**: el servidor compara contra su reloj antes de
|
|
320
|
+
* emitirlo, así que `taken_until` nunca viene en el pasado y no hay que filtrarlo acá.
|
|
321
|
+
*
|
|
322
|
+
* Los tres son opcionales —como se hizo con `can_reply`— para que un backend viejo que no los
|
|
323
|
+
* emita no rompa al visor. Ausente se lee como «libre».
|
|
324
|
+
*/
|
|
325
|
+
taken_by?: string | null;
|
|
326
|
+
taken_until?: string | null;
|
|
327
|
+
taken_by_me?: boolean;
|
|
252
328
|
}
|
|
253
329
|
/**
|
|
254
330
|
* El sobre de la lista.
|
|
@@ -722,6 +798,20 @@ interface UseThreadResult {
|
|
|
722
798
|
* el visor exactamente como hoy en vez de escribir un mensaje entero para enterarse al enviar.
|
|
723
799
|
*/
|
|
724
800
|
canReply: boolean;
|
|
801
|
+
/**
|
|
802
|
+
* El takeover del sobre (DEV-5061): quién tiene tomada la conversación, hasta cuándo, y si es
|
|
803
|
+
* quien está mirando.
|
|
804
|
+
*
|
|
805
|
+
* `takenUntil` llega como el instante ISO **verbatim** del servidor: el conteo hacia atrás lo
|
|
806
|
+
* hace la vista, porque un relativo calculado una vez queda viejo en pantalla.
|
|
807
|
+
*
|
|
808
|
+
* `takenByMe` es **fail-closed** por el motivo contrario a `canReply`: sólo el `true` del
|
|
809
|
+
* servidor ofrece «Reactivar bot». Ausente ⇒ `false` ⇒ no se ofrece, que es lo inofensivo; el
|
|
810
|
+
* opuesto le daría a un operador el botón de otro.
|
|
811
|
+
*/
|
|
812
|
+
takenBy: string | null;
|
|
813
|
+
takenUntil: string | null;
|
|
814
|
+
takenByMe: boolean;
|
|
725
815
|
/**
|
|
726
816
|
* Hay página anterior que pedir (DEC-M): lo dice el `older_cursor` del servidor (DEV-4983),
|
|
727
817
|
* `null` = hilo agotado. Se apaga PERMANENTE al agotar el hilo.
|
package/dist/react/index.js
CHANGED
|
@@ -48,8 +48,8 @@ function initials(name, phone) {
|
|
|
48
48
|
* **No se exporta desde el barrel del core.** Es detalle interno de la fila; lo que sale del barrel
|
|
49
49
|
* es API pública del entry `./react` y renombrarlo rompería el import de `lms-web-app` (PKG-04).
|
|
50
50
|
*/
|
|
51
|
-
const MINUTE = 6e4;
|
|
52
|
-
const HOUR = 60 * MINUTE;
|
|
51
|
+
const MINUTE$1 = 6e4;
|
|
52
|
+
const HOUR = 60 * MINUTE$1;
|
|
53
53
|
const DAY = 24 * HOUR;
|
|
54
54
|
const WEEK = 7 * DAY;
|
|
55
55
|
/** Aproximaciones a propósito: es una distancia legible, no un cálculo de calendario. */
|
|
@@ -70,8 +70,8 @@ function relativeTime(iso, now = Date.now()) {
|
|
|
70
70
|
const at = Date.parse(iso);
|
|
71
71
|
if (Number.isNaN(at)) return "";
|
|
72
72
|
const elapsed = now - at;
|
|
73
|
-
if (elapsed < MINUTE) return "ahora";
|
|
74
|
-
if (elapsed < HOUR) return `hace ${Math.floor(elapsed / MINUTE)} min`;
|
|
73
|
+
if (elapsed < MINUTE$1) return "ahora";
|
|
74
|
+
if (elapsed < HOUR) return `hace ${Math.floor(elapsed / MINUTE$1)} min`;
|
|
75
75
|
if (elapsed < DAY) return `hace ${Math.floor(elapsed / HOUR)} h`;
|
|
76
76
|
if (elapsed < WEEK) return `hace ${Math.floor(elapsed / DAY)} d`;
|
|
77
77
|
if (elapsed < MONTH) return `hace ${Math.floor(elapsed / WEEK)} sem`;
|
|
@@ -119,6 +119,12 @@ function ConversationRow({ item, selected, onSelect }) {
|
|
|
119
119
|
className: "wa-list__state",
|
|
120
120
|
title: item.service_state,
|
|
121
121
|
children: item.service_state
|
|
122
|
+
}),
|
|
123
|
+
typeof item.taken_by === "string" && item.taken_by !== "" && /* @__PURE__ */ jsx("span", {
|
|
124
|
+
className: "wa-list__taken",
|
|
125
|
+
"data-mine": item.taken_by_me === true || void 0,
|
|
126
|
+
title: `Tomada por ${item.taken_by}`,
|
|
127
|
+
children: item.taken_by_me === true ? "La tomaste tú" : `Tomada por ${item.taken_by}`
|
|
122
128
|
})
|
|
123
129
|
]
|
|
124
130
|
})]
|
|
@@ -462,6 +468,30 @@ const LIST_CSS = `
|
|
|
462
468
|
word-break: break-word;
|
|
463
469
|
}
|
|
464
470
|
|
|
471
|
+
/* DEV-5061 — el chip «Tomada» de la fila. Mismo par de tonos que la barra del hilo: ambar cuando
|
|
472
|
+
la tiene otro (aviso) y anil cuando es tuya. Que las dos vistas usen la MISMA pareja no es
|
|
473
|
+
coincidencia — el operador tiene que reconocer el estado sin releer. */
|
|
474
|
+
.wa-list__taken {
|
|
475
|
+
align-self: flex-start;
|
|
476
|
+
margin-top: 2px;
|
|
477
|
+
padding: 1px 8px;
|
|
478
|
+
border-radius: 999px;
|
|
479
|
+
background: #fff7e8;
|
|
480
|
+
color: #b7791f;
|
|
481
|
+
font-size: 11px;
|
|
482
|
+
font-weight: 600;
|
|
483
|
+
/* El nombre de un operador puede ser largo y la fila es angosta: se recorta en vez de
|
|
484
|
+
empujar la columna. El completo queda en el \`title\`. */
|
|
485
|
+
max-width: 100%;
|
|
486
|
+
overflow: hidden;
|
|
487
|
+
text-overflow: ellipsis;
|
|
488
|
+
white-space: nowrap;
|
|
489
|
+
}
|
|
490
|
+
.wa-list__taken[data-mine='true'] {
|
|
491
|
+
background: #f4f5ff;
|
|
492
|
+
color: #4f5aed;
|
|
493
|
+
}
|
|
494
|
+
|
|
465
495
|
/* Angosto: sólo se deja envolver el texto. El \`display: contents\` que antes sacaba al agrupador
|
|
466
496
|
del flujo ya no hace falta — la columna .wa-list__middle apila por sí sola. */
|
|
467
497
|
.wa-list[data-layout='narrow'] .wa-list__preview,
|
|
@@ -890,7 +920,10 @@ async function loadThread(fetcher, request, options) {
|
|
|
890
920
|
window_expires_at: asNullableString(payload.window_expires_at),
|
|
891
921
|
phone_number_id: asString(payload.phone_number_id),
|
|
892
922
|
service: asString(payload.service),
|
|
893
|
-
can_reply: payload.can_reply === true
|
|
923
|
+
can_reply: payload.can_reply === true,
|
|
924
|
+
taken_by: asNullableString(payload.taken_by),
|
|
925
|
+
taken_until: asNullableString(payload.taken_until),
|
|
926
|
+
taken_by_me: payload.taken_by_me === true
|
|
894
927
|
};
|
|
895
928
|
}
|
|
896
929
|
/**
|
|
@@ -2018,6 +2051,64 @@ function MediaAttachment({ message, fetcher }) {
|
|
|
2018
2051
|
});
|
|
2019
2052
|
}
|
|
2020
2053
|
//#endregion
|
|
2054
|
+
//#region src/core/thread/failure-reason-labels.ts
|
|
2055
|
+
/**
|
|
2056
|
+
* Los motivos de fallo de Meta en español (DEV-5065). Interno del hilo — NO sale al barrel.
|
|
2057
|
+
*
|
|
2058
|
+
* Por qué existe: un tick rojo que sólo dice «No entregado» no le sirve al operador. Los tres
|
|
2059
|
+
* motivos frecuentes se resuelven de forma **distinta** —número inválido (el dato está mal),
|
|
2060
|
+
* ventana de 24 h cerrada (hay que mandar plantilla) y plantilla rechazada (hay que arreglar la
|
|
2061
|
+
* plantilla)— y sin el motivo los tres se ven idénticos. Por eso las etiquetas dicen QUÉ HACER y
|
|
2062
|
+
* no sólo qué pasó: «El número no recibe WhatsApp» es accionable, «Message undeliverable» no.
|
|
2063
|
+
*
|
|
2064
|
+
* ⚠️ **FALLBACK VERBATIM**, la misma regla de seguridad que `service-state-labels.ts`: un código
|
|
2065
|
+
* que no esté en la tabla cae al `error_title` que mandó Meta, EXACTAMENTE como llegó. Meta agrega
|
|
2066
|
+
* y renombra códigos sin avisar, y mostrar el texto crudo siempre es mejor que ocultarlo o
|
|
2067
|
+
* adivinarlo. Si tampoco hay título, no se pinta nada: el «No entregado» ya está.
|
|
2068
|
+
*
|
|
2069
|
+
* ⚠️ La tabla es CONSERVADORA a propósito: sólo códigos de entrega documentados por la Cloud API
|
|
2070
|
+
* de Meta. Ante la duda, no se agrega la entrada — el fallback verbatim ya cubre el caso, y una
|
|
2071
|
+
* traducción equivocada es peor que el texto original en inglés porque el operador no puede
|
|
2072
|
+
* sospecharla. Conviene revisarla contra los `failed` reales que aparezcan en QA.
|
|
2073
|
+
*
|
|
2074
|
+
* ⚠️ La etiqueta entra SOLO como hijo de texto, que React escapa: jamás en className, style o
|
|
2075
|
+
* selector (T-03-02). El `error_title` lo origina un tercero.
|
|
2076
|
+
*/
|
|
2077
|
+
/**
|
|
2078
|
+
* La tabla es-CO, indexada por el código numérico de Meta. Se consulta SÓLO por clave propia:
|
|
2079
|
+
* nada del prototipo puede colarse (un `error_code` es un número, pero la lectura pasa por
|
|
2080
|
+
* `hasOwnProperty` igual — la disciplina no se relaja según el tipo).
|
|
2081
|
+
*/
|
|
2082
|
+
const FAILURE_REASON_LABELS = {
|
|
2083
|
+
131047: "Pasaron más de 24 h sin respuesta: hay que enviar una plantilla",
|
|
2084
|
+
131026: "El número no puede recibir mensajes de WhatsApp",
|
|
2085
|
+
131049: "Meta no lo entregó para cuidar la experiencia del usuario",
|
|
2086
|
+
131e3: "Error interno de Meta",
|
|
2087
|
+
131008: "Falta un parámetro obligatorio en el envío",
|
|
2088
|
+
131031: "La cuenta de WhatsApp está bloqueada",
|
|
2089
|
+
131042: "Problema de facturación en la cuenta de WhatsApp",
|
|
2090
|
+
131051: "Tipo de mensaje no soportado",
|
|
2091
|
+
132e3: "La plantilla no coincide con la cantidad de parámetros enviados",
|
|
2092
|
+
132001: "La plantilla no existe o no está aprobada para este idioma",
|
|
2093
|
+
132005: "El texto de la plantilla quedó demasiado largo",
|
|
2094
|
+
132007: "La plantilla viola la política de formato",
|
|
2095
|
+
132012: "Un parámetro de la plantilla no tiene el formato esperado",
|
|
2096
|
+
132015: "La plantilla está pausada por baja calidad",
|
|
2097
|
+
132016: "La plantilla está deshabilitada"
|
|
2098
|
+
};
|
|
2099
|
+
/**
|
|
2100
|
+
* El motivo humano de un `failed`, o `null` si no hay nada que decir.
|
|
2101
|
+
*
|
|
2102
|
+
* Precedencia: la tabla por código, después el `error_title` VERBATIM, después nada. Un título
|
|
2103
|
+
* que llega vacío o en blanco cuenta como nada — pintar una línea vacía debajo de «No entregado»
|
|
2104
|
+
* es peor que no pintarla.
|
|
2105
|
+
*/
|
|
2106
|
+
function failureReasonLabel(code, title) {
|
|
2107
|
+
if (typeof code === "number" && Object.prototype.hasOwnProperty.call(FAILURE_REASON_LABELS, code)) return FAILURE_REASON_LABELS[code];
|
|
2108
|
+
const verbatim = typeof title === "string" ? title.trim() : "";
|
|
2109
|
+
return verbatim === "" ? null : verbatim;
|
|
2110
|
+
}
|
|
2111
|
+
//#endregion
|
|
2021
2112
|
//#region src/core/thread/MessageBubble.tsx
|
|
2022
2113
|
/**
|
|
2023
2114
|
* El tick de una saliente. El vocabulario conocido y nada más: lo desconocido devuelve `null` y la
|
|
@@ -2080,6 +2171,7 @@ function MessageBubble({ message, optimistic = false, fetcher }) {
|
|
|
2080
2171
|
const ctas = threadCtas(message);
|
|
2081
2172
|
const tick = direction === "out" ? tickFor(message.status) : null;
|
|
2082
2173
|
const failed = direction === "out" && message.status === "failed";
|
|
2174
|
+
const failureReason = failed ? failureReasonLabel(message.error_code, message.error_title) : null;
|
|
2083
2175
|
const author = typeof message.sent_by_name === "string" && message.sent_by_name.trim() !== "" ? message.sent_by_name : null;
|
|
2084
2176
|
/**
|
|
2085
2177
|
* COMP-03: quién habló, de un golpe. Una saliente **con** `sent_by_name` la escribió una persona;
|
|
@@ -2134,9 +2226,12 @@ function MessageBubble({ message, optimistic = false, fetcher }) {
|
|
|
2134
2226
|
dateTime: message.at,
|
|
2135
2227
|
title: message.at,
|
|
2136
2228
|
children: hour
|
|
2137
|
-
}), failed ? /* @__PURE__ */
|
|
2229
|
+
}), failed ? /* @__PURE__ */ jsxs("span", {
|
|
2138
2230
|
className: "wa-thread__failed",
|
|
2139
|
-
children: "No entregado"
|
|
2231
|
+
children: ["No entregado", failureReason !== null && /* @__PURE__ */ jsxs("span", {
|
|
2232
|
+
className: "wa-thread__failed-reason",
|
|
2233
|
+
children: [" · ", failureReason]
|
|
2234
|
+
})]
|
|
2140
2235
|
}) : tick !== null && /* @__PURE__ */ jsx("span", {
|
|
2141
2236
|
className: "wa-thread__tick",
|
|
2142
2237
|
"data-status": message.status,
|
|
@@ -2345,6 +2440,52 @@ const THREAD_CSS = `
|
|
|
2345
2440
|
border-color: #e5b9b6;
|
|
2346
2441
|
background: #fdf6f6;
|
|
2347
2442
|
}
|
|
2443
|
+
/* DEV-5065: el motivo, dentro del mismo bloque rojo que «No entregado». Peso normal para que la
|
|
2444
|
+
jerarquía se lea —el titular manda, el motivo explica— y sin ancho fijo: los textos crudos de
|
|
2445
|
+
Meta que caen por el fallback verbatim pueden ser largos y tienen que poder envolver. */
|
|
2446
|
+
.wa-thread__failed-reason {
|
|
2447
|
+
font-weight: 400;
|
|
2448
|
+
}
|
|
2449
|
+
|
|
2450
|
+
/* DEV-5061 — la barra de takeover, entre el header y el scroller. Ámbar cuando la tiene otro
|
|
2451
|
+
(es un aviso: no escribas encima) y añil cuando es tuya (es tu control, con su acción). Los
|
|
2452
|
+
dos tonos son los de la paleta que fijó DEV-5053. */
|
|
2453
|
+
.wa-thread__takeover {
|
|
2454
|
+
display: flex;
|
|
2455
|
+
align-items: center;
|
|
2456
|
+
justify-content: space-between;
|
|
2457
|
+
gap: 12px;
|
|
2458
|
+
flex-wrap: wrap;
|
|
2459
|
+
padding: 8px 12px;
|
|
2460
|
+
border-bottom: 1px solid #e4e7ee;
|
|
2461
|
+
background: #fff7e8;
|
|
2462
|
+
color: #b7791f;
|
|
2463
|
+
font-size: 13px;
|
|
2464
|
+
}
|
|
2465
|
+
.wa-thread__takeover[data-mine='true'] {
|
|
2466
|
+
background: #f4f5ff;
|
|
2467
|
+
color: #4f5aed;
|
|
2468
|
+
}
|
|
2469
|
+
.wa-thread__takeover-text {
|
|
2470
|
+
min-width: 0;
|
|
2471
|
+
}
|
|
2472
|
+
/* Pill, el mismo molde que el Reintentar de DEV-5053 P7. \`currentColor\` es lo que hace que el
|
|
2473
|
+
botón siga al tono de la barra sin duplicar la regla por variante. */
|
|
2474
|
+
.wa-thread__takeover-button {
|
|
2475
|
+
flex: none;
|
|
2476
|
+
padding: 4px 12px;
|
|
2477
|
+
border: 1px solid currentColor;
|
|
2478
|
+
border-radius: 999px;
|
|
2479
|
+
background: #fff;
|
|
2480
|
+
color: inherit;
|
|
2481
|
+
font: inherit;
|
|
2482
|
+
font-weight: 600;
|
|
2483
|
+
cursor: pointer;
|
|
2484
|
+
}
|
|
2485
|
+
.wa-thread__takeover-button:disabled {
|
|
2486
|
+
opacity: 0.6;
|
|
2487
|
+
cursor: default;
|
|
2488
|
+
}
|
|
2348
2489
|
|
|
2349
2490
|
/* El operador que escribió la saliente, sobre la burbuja. */
|
|
2350
2491
|
.wa-thread__author {
|
|
@@ -3100,6 +3241,9 @@ function useThread({ fetcher, phone }) {
|
|
|
3100
3241
|
messages,
|
|
3101
3242
|
windowState: normalizeWindowState(thread.window_state),
|
|
3102
3243
|
canReply: thread.can_reply === true,
|
|
3244
|
+
takenBy: thread.taken_by ?? null,
|
|
3245
|
+
takenUntil: thread.taken_until ?? null,
|
|
3246
|
+
takenByMe: thread.taken_by_me === true,
|
|
3103
3247
|
status: messages.length > 0 ? "ready" : "empty",
|
|
3104
3248
|
error: null,
|
|
3105
3249
|
olderCursor: thread.older_cursor,
|
|
@@ -3114,6 +3258,9 @@ function useThread({ fetcher, phone }) {
|
|
|
3114
3258
|
messages: [],
|
|
3115
3259
|
windowState: "unverified",
|
|
3116
3260
|
canReply: false,
|
|
3261
|
+
takenBy: null,
|
|
3262
|
+
takenUntil: null,
|
|
3263
|
+
takenByMe: false,
|
|
3117
3264
|
status: "error",
|
|
3118
3265
|
error: toError(cause),
|
|
3119
3266
|
olderCursor: null,
|
|
@@ -3201,12 +3348,58 @@ function useThread({ fetcher, phone }) {
|
|
|
3201
3348
|
error: current?.error ?? null,
|
|
3202
3349
|
windowState: current?.windowState ?? "unverified",
|
|
3203
3350
|
canReply: current?.canReply ?? false,
|
|
3351
|
+
takenBy: current?.takenBy ?? null,
|
|
3352
|
+
takenUntil: current?.takenUntil ?? null,
|
|
3353
|
+
takenByMe: current?.takenByMe ?? false,
|
|
3204
3354
|
hasOlder: current?.hasOlder ?? false,
|
|
3205
3355
|
loadOlder,
|
|
3206
3356
|
retry
|
|
3207
3357
|
};
|
|
3208
3358
|
}
|
|
3209
3359
|
//#endregion
|
|
3360
|
+
//#region src/core/thread/takeover-countdown.ts
|
|
3361
|
+
/**
|
|
3362
|
+
* Cuánto le queda a un takeover, en español (DEV-5061). Interno del hilo — NO sale al barrel.
|
|
3363
|
+
*
|
|
3364
|
+
* El servidor manda un **instante** (`taken_until`) y no «minutos restantes», y este módulo es la
|
|
3365
|
+
* razón: un relativo calculado en el servidor queda viejo apenas viaja, mientras que el instante
|
|
3366
|
+
* sigue siendo verdad y el conteo se hace acá, contra el reloj de quien mira.
|
|
3367
|
+
*
|
|
3368
|
+
* `now` es un parámetro y no una lectura de `Date.now()` adentro, por lo mismo que en
|
|
3369
|
+
* `relative-time.ts`: para que el test pase su propio reloj sin contagiar timers falsos al resto
|
|
3370
|
+
* del archivo.
|
|
3371
|
+
*
|
|
3372
|
+
* ⚠️ **No se recalcula solo.** El valor se computa en el render y se queda quieto hasta el
|
|
3373
|
+
* siguiente — igual que la hora relativa de la fila del inbox. Un timer acá obligaría a un
|
|
3374
|
+
* re-render periódico del hilo entero para ganar precisión de minuto en un dato que ya es
|
|
3375
|
+
* aproximado, y el hilo se re-renderiza seguido por su cuenta. Es una decisión, no un olvido.
|
|
3376
|
+
*/
|
|
3377
|
+
const MINUTE = 6e4;
|
|
3378
|
+
/**
|
|
3379
|
+
* «1 h 42 m», «22 m», o `null` si no hay nada que contar.
|
|
3380
|
+
*
|
|
3381
|
+
* Devuelve `null` en los tres casos degenerados, y ninguno es teórico:
|
|
3382
|
+
*
|
|
3383
|
+
* - **`iso` nulo o que no parsea** — la conversación no está tomada, o el backend mandó basura.
|
|
3384
|
+
* - **Ya vencido** — el servidor filtra los vencidos contra SU reloj, pero el del operador puede
|
|
3385
|
+
* ir adelantado. «se libera en -3 m» es peor que no decir nada.
|
|
3386
|
+
* - **Menos de un minuto** — se redondea a `1 m` en vez de mostrar `0 m`, que se lee como si el
|
|
3387
|
+
* dato faltara. Ese sí devuelve texto: es el único de los tres que no es un error.
|
|
3388
|
+
*/
|
|
3389
|
+
function takeoverCountdown(iso, now = Date.now()) {
|
|
3390
|
+
if (typeof iso !== "string") return null;
|
|
3391
|
+
const until = Date.parse(iso);
|
|
3392
|
+
if (Number.isNaN(until)) return null;
|
|
3393
|
+
const left = until - now;
|
|
3394
|
+
if (left <= 0) return null;
|
|
3395
|
+
const totalMinutes = Math.max(1, Math.ceil(left / MINUTE));
|
|
3396
|
+
const hours = Math.floor(totalMinutes / 60);
|
|
3397
|
+
const minutes = totalMinutes % 60;
|
|
3398
|
+
if (hours === 0) return `${minutes} m`;
|
|
3399
|
+
if (minutes === 0) return `${hours} h`;
|
|
3400
|
+
return `${hours} h ${minutes} m`;
|
|
3401
|
+
}
|
|
3402
|
+
//#endregion
|
|
3210
3403
|
//#region src/core/thread/ConversationThread.tsx
|
|
3211
3404
|
/**
|
|
3212
3405
|
* El panel del hilo de conversación — la mitad derecha del visor (DEV-4987).
|
|
@@ -3288,8 +3481,48 @@ function currentServiceState(messages) {
|
|
|
3288
3481
|
}
|
|
3289
3482
|
return null;
|
|
3290
3483
|
}
|
|
3484
|
+
/**
|
|
3485
|
+
* La barra de takeover del hilo (DEV-5061).
|
|
3486
|
+
*
|
|
3487
|
+
* El problema que resuelve: el store ya guardaba quién tomó la conversación y el bot ya se callaba,
|
|
3488
|
+
* pero nada de eso llegaba acá. Una conversación atendida por un compañero se veía **idéntica** a
|
|
3489
|
+
* una libre — el operador entraba, escribía, y recién ahí se enteraba. O no se enteraba, y dos
|
|
3490
|
+
* personas respondían el mismo hilo.
|
|
3491
|
+
*
|
|
3492
|
+
* Dos ramas, deliberadamente distintas:
|
|
3493
|
+
*
|
|
3494
|
+
* - **La tomaste vos** — se ofrece «Reactivar bot», porque es tuya y podés soltarla.
|
|
3495
|
+
* - **La tomó otro** — se dice quién y hasta cuándo, y NO se ofrece el botón. Robarle el turno a
|
|
3496
|
+
* un compañero desde un botón que parece inofensivo es peor que la ambigüedad que esta barra
|
|
3497
|
+
* vino a arreglar; quien quiera hacerlo puede responder, que renueva la toma a su nombre.
|
|
3498
|
+
*
|
|
3499
|
+
* `takenByMe` viene del SERVIDOR y no se deriva comparando `takenBy` con nadie: dos operadores
|
|
3500
|
+
* pueden llamarse igual, y confundirlos es exactamente darle a uno el botón del otro.
|
|
3501
|
+
*
|
|
3502
|
+
* El nombre entra sólo como hijo de texto, que React escapa (T-03-02).
|
|
3503
|
+
*/
|
|
3504
|
+
function TakeoverBar({ takenBy, takenUntil, takenByMe, composer }) {
|
|
3505
|
+
if (composer.releaseState === "released") return null;
|
|
3506
|
+
const left = takeoverCountdown(takenUntil);
|
|
3507
|
+
if (takenBy === null && left === null) return null;
|
|
3508
|
+
return /* @__PURE__ */ jsxs("div", {
|
|
3509
|
+
className: "wa-thread__takeover",
|
|
3510
|
+
"data-mine": takenByMe || void 0,
|
|
3511
|
+
role: "status",
|
|
3512
|
+
children: [/* @__PURE__ */ jsxs("span", {
|
|
3513
|
+
className: "wa-thread__takeover-text",
|
|
3514
|
+
children: [takenByMe ? /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx("strong", { children: "Bot en pausa" }), " — la tomaste tú"] }) : /* @__PURE__ */ jsxs(Fragment$1, { children: ["Tomada por ", /* @__PURE__ */ jsx("strong", { children: takenBy ?? "otro operador" })] }), left !== null && ` · se libera en ${left}`]
|
|
3515
|
+
}), takenByMe && /* @__PURE__ */ jsx("button", {
|
|
3516
|
+
type: "button",
|
|
3517
|
+
className: "wa-thread__takeover-button",
|
|
3518
|
+
onClick: composer.release,
|
|
3519
|
+
disabled: composer.releaseState === "releasing",
|
|
3520
|
+
children: composer.releaseState === "releasing" ? "Reactivando…" : "Reactivar bot"
|
|
3521
|
+
})]
|
|
3522
|
+
});
|
|
3523
|
+
}
|
|
3291
3524
|
function ConversationThread({ fetcher, phone, displayName, className }) {
|
|
3292
|
-
const { messages: serverMessages, status, error, windowState, canReply, hasOlder, loadOlder, retry } = useThread({
|
|
3525
|
+
const { messages: serverMessages, status, error, windowState, canReply, takenBy, takenUntil, takenByMe, hasOlder, loadOlder, retry } = useThread({
|
|
3293
3526
|
fetcher,
|
|
3294
3527
|
phone
|
|
3295
3528
|
});
|
|
@@ -3412,6 +3645,12 @@ function ConversationThread({ fetcher, phone, displayName, className }) {
|
|
|
3412
3645
|
})
|
|
3413
3646
|
})]
|
|
3414
3647
|
}),
|
|
3648
|
+
/* @__PURE__ */ jsx(TakeoverBar, {
|
|
3649
|
+
takenBy,
|
|
3650
|
+
takenUntil,
|
|
3651
|
+
takenByMe,
|
|
3652
|
+
composer
|
|
3653
|
+
}),
|
|
3415
3654
|
/* @__PURE__ */ jsxs("div", {
|
|
3416
3655
|
className: "wa-thread__messages",
|
|
3417
3656
|
ref: messagesRef,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@liftitapp/wa-conversations",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "Visor de conversaciones de WhatsApp del ecosistema Liftit: lista, hilo, media y composer.",
|
|
5
5
|
"author": "Liftit",
|
|
6
6
|
"license": "UNLICENSED",
|
|
@@ -29,7 +29,9 @@
|
|
|
29
29
|
"files: ['dist'] es lo único que impide que contract/thread-v0.fixture.json y .planning/ viajen",
|
|
30
30
|
"al tarball: sin 'files', npm empaqueta todo lo no-gitignored. Es una precondición dura de",
|
|
31
31
|
"publicar en un registry público — npm sólo deja despublicar dentro de las 72 horas y sin",
|
|
32
|
-
"dependientes, así que un tarball equivocado es prácticamente permanente.",
|
|
32
|
+
"dependientes, así que un tarball equivocado es prácticamente permanente. Que siga acotado lo",
|
|
33
|
+
"asserta scripts/verify-tarball.mjs, encadenado en prepublishOnly: acá se publica A MANO desde",
|
|
34
|
+
"la máquina del dev, así que un gate que solo viviera en CI no protegería nada.",
|
|
33
35
|
"",
|
|
34
36
|
"sideEffects: el entry ./element registra el custom element POR EFECTO SECUNDARIO. Si un",
|
|
35
37
|
"bundler lo tree-shakea porque 'no se usa ningún export', el elemento nunca queda registrado.",
|
|
@@ -94,7 +96,8 @@
|
|
|
94
96
|
"test:watch": "vitest",
|
|
95
97
|
"demo": "pnpm build && node scripts/demo-server.mjs",
|
|
96
98
|
"verify:externals": "node scripts/verify-externals.mjs",
|
|
97
|
-
"
|
|
99
|
+
"verify:tarball": "node scripts/verify-tarball.mjs",
|
|
100
|
+
"prepublishOnly": "pnpm typecheck && pnpm lint && pnpm test && pnpm build && pnpm verify:tarball"
|
|
98
101
|
},
|
|
99
102
|
"peerDependencies": {
|
|
100
103
|
"react": ">=18",
|