@liftitapp/wa-conversations 0.8.2 → 0.10.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.
@@ -206,6 +206,19 @@ interface LeadThreadResponse {
206
206
  taken_by?: string | null;
207
207
  taken_until?: string | null;
208
208
  taken_by_me?: boolean;
209
+ /**
210
+ * **DEV-6309 / DEV-6399** — desde cuándo está tomada y con qué rol, para la barra ámbar
211
+ * «La tiene Paula Castaño (operadora) · 12 m».
212
+ *
213
+ * `taken_at` es un **instante ISO-8601** (mismo motivo que `taken_until`: el transcurrido lo
214
+ * cuenta el front contra su reloj). `taken_by_role` es texto libre para pintar entre paréntesis:
215
+ * se tipa abierto (`string`) porque es un rótulo, no un enum que el visor interprete.
216
+ *
217
+ * Opcionales y nullables: el servidor todavía no los emite (los agrega DEV-6399). Ausentes, la
218
+ * barra cae a «· se libera en N» y sin paréntesis — exactamente lo de antes.
219
+ */
220
+ taken_at?: string | null;
221
+ taken_by_role?: string | null;
209
222
  /** E2 — el bot dueño de la conversación. La unicidad es `(phone_number_id, phone)`, nunca el teléfono solo. */
210
223
  phone_number_id: string;
211
224
  /** E2 — qué servicio la originó (`self_onboarding_whatsapp`, y los que vengan). */
@@ -325,6 +338,13 @@ interface ConversationSummary {
325
338
  taken_by?: string | null;
326
339
  taken_until?: string | null;
327
340
  taken_by_me?: boolean;
341
+ /**
342
+ * **DEV-6309 / DEV-6399** — el mismo par que en `LeadThreadResponse` (`taken_at` ISO-8601,
343
+ * `taken_by_role` rótulo libre), opcionales y nullables. La fila de la lista todavía no los
344
+ * pinta: entran al tipo para que el contrato de los dos sobres no se desvíe.
345
+ */
346
+ taken_at?: string | null;
347
+ taken_by_role?: string | null;
328
348
  }
329
349
  /**
330
350
  * El sobre de la lista.
@@ -351,7 +371,13 @@ interface ThreadRequest {
351
371
  /** Qué trozo de la lista de inbox se pide. Todo opcional: sin filtros es "la primera página". */
352
372
  interface ConversationsRequest {
353
373
  phone?: string;
374
+ /**
375
+ * Cota inferior INCLUSIVA sobre `last_message_at`: un instante ISO 8601 en UTC (`…Z`). Desde
376
+ * DEV-6425 la lista manda el inicio del primer día LOCAL del operador (00:00:00.000), no la
377
+ * fecha sola — el servicio leería `YYYY-MM-DD` como 00:00 UTC.
378
+ */
354
379
  from?: string;
380
+ /** Cota superior INCLUSIVA: el fin del último día local (23:59:59.999), en ISO 8601 UTC. */
355
381
  to?: string;
356
382
  cursor?: string;
357
383
  limit?: number;
@@ -974,6 +1000,13 @@ interface UseThreadResult {
974
1000
  takenBy: string | null;
975
1001
  takenUntil: string | null;
976
1002
  takenByMe: boolean;
1003
+ /**
1004
+ * DEV-6309 — el instante de la toma (`taken_at`, ISO verbatim) y el rol de quien la tiene
1005
+ * (`taken_by_role`). Opcionales en el cable: hasta que DEV-6399 los emita llegan `null` y la
1006
+ * barra cae a «se libera en N». Un error de red también los deja en `null`.
1007
+ */
1008
+ takenAt: string | null;
1009
+ takenByRole: string | null;
977
1010
  /**
978
1011
  * Hay página anterior que pedir (DEC-M): lo dice el `older_cursor` del servidor (DEV-4983),
979
1012
  * `null` = hilo agotado. Se apaga PERMANENTE al agotar el hilo.
@@ -899,10 +899,10 @@ function readSendError(cause) {
899
899
  function sendFailureCopy(failure) {
900
900
  switch (failure.errorCode) {
901
901
  case "window_closed": return "La ventana de 24 h se cerró: no podemos escribirle hasta que la persona vuelva a escribir.";
902
- 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.";
903
- case "takeover_unavailable": return "No se pudo pausar el bot, así que el mensaje no se envió. Reintentá en un momento.";
902
+ case "window_unverified": return "No pudimos verificar la ventana de 24 h, así que no se envió nada. Reintenta: reintentar no envía ningún mensaje cobrado.";
903
+ case "takeover_unavailable": return "No se pudo pausar el bot, así que el mensaje no se envió. Reintenta en un momento.";
904
904
  case "send_failed": return "WhatsApp rechazó el envío. El mensaje quedó registrado en el hilo como no entregado.";
905
- case "write_forbidden": return "No tenés permiso para responder en esta conversación.";
905
+ case "write_forbidden": return "No tienes permiso para responder en esta conversación.";
906
906
  default: return failure.serverMessage ?? "No se pudo enviar el mensaje.";
907
907
  }
908
908
  }
@@ -1002,7 +1002,9 @@ async function loadThread(fetcher, request, options) {
1002
1002
  can_reply: payload.can_reply === true,
1003
1003
  taken_by: asNullableString(payload.taken_by),
1004
1004
  taken_until: asNullableString(payload.taken_until),
1005
- taken_by_me: payload.taken_by_me === true
1005
+ taken_by_me: payload.taken_by_me === true,
1006
+ taken_at: asNullableString(payload.taken_at),
1007
+ taken_by_role: asNullableString(payload.taken_by_role)
1006
1008
  };
1007
1009
  }
1008
1010
  /**
@@ -1441,8 +1443,8 @@ const NO_FILTERS = {};
1441
1443
  * El rango local `YYYY-MM-DD` de un preset: `to` = hoy, `from` = hoy − (days − 1) — el rango
1442
1444
  * INCLUYE hoy («7 días» son siete fechas contando la de hoy). Fechas locales con
1443
1445
  * `getFullYear/getMonth/getDate` + padStart, sin Intl (coherente con DEC-K/DEC-O). El formato es
1444
- * el MISMO que ya producían los `<input type="date">`, así que DEC-J (los valores viajan tal
1445
- * cual al descriptor) no cambia.
1446
+ * el MISMO que producen los `<input type="date">`: es el estado del FORMULARIO. Lo que viaja al
1447
+ * descriptor es otra cosa — ver `dayBound`.
1446
1448
  */
1447
1449
  function presetRange(days) {
1448
1450
  const format = (date) => `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
@@ -1452,6 +1454,48 @@ function presetRange(days) {
1452
1454
  to: format(now)
1453
1455
  };
1454
1456
  }
1457
+ const LOCAL_DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
1458
+ /**
1459
+ * Una fecha local `YYYY-MM-DD` convertida al INSTANTE que la limita, en ISO 8601 UTC (DEV-6425).
1460
+ *
1461
+ * El servicio filtra `from <= last_message_at <= to` sobre `timestamptz` y a una fecha sola la lee
1462
+ * como las 00:00 **UTC** de ese día (`_assume_utc` de `app/routes/conversations.py`). Mandar
1463
+ * `to=2026-09-25` dejaba afuera TODO lo de hoy, y el corte ni siquiera era la medianoche del
1464
+ * operador. Por eso el día local se traduce acá a sus dos bordes:
1465
+ *
1466
+ * - `'start'` ⇒ 00:00:00.000 local de ese día;
1467
+ * - `'end'` ⇒ 23:59:59.999 local de ese día (el rango del servicio es INCLUSIVO).
1468
+ *
1469
+ * Sale con `Z` (vía `toISOString`) y no con el offset local a propósito: un `-05:00` viaja bien,
1470
+ * pero un `+01:00` armado a mano en una query string se decodifica como espacio y el servicio
1471
+ * responde 422. Con `Z` no hay signo que codificar, cualquiera sea el fetcher del host.
1472
+ *
1473
+ * Los componentes se pasan al constructor de `Date` en hora local, así que un día de 23 o 25 horas
1474
+ * (cambio de horario) queda bien sin aritmética de milisegundos. Algo que no sea `YYYY-MM-DD` viaja
1475
+ * tal cual: no se adivina un formato que no es el del formulario.
1476
+ */
1477
+ function dayBound(value, edge) {
1478
+ const match = LOCAL_DATE.exec(value);
1479
+ if (match === null) return value;
1480
+ const [year, month, day] = [
1481
+ Number(match[1]),
1482
+ Number(match[2]) - 1,
1483
+ Number(match[3])
1484
+ ];
1485
+ return (edge === "start" ? new Date(year, month, day, 0, 0, 0, 0) : new Date(year, month, day, 23, 59, 59, 999)).toISOString();
1486
+ }
1487
+ /**
1488
+ * La consulta que sale del formulario — UN solo lugar para los tres caminos (submit, presets y
1489
+ * «Rango…»). El teléfono viaja tal cual; lo vacío se omite, para que el descriptor no lleve claves
1490
+ * que el host tendría que aprender a ignorar; las fechas pasan por `dayBound`.
1491
+ */
1492
+ function buildFilters(phone, from, to) {
1493
+ const next = {};
1494
+ if (phone.trim() !== "") next.phone = phone;
1495
+ if (from !== "") next.from = dayBound(from, "start");
1496
+ if (to !== "") next.to = dayBound(to, "end");
1497
+ return next;
1498
+ }
1455
1499
  function ConversationList({ fetcher, selectedPhone, onSelect, refreshIntervalMs, className }) {
1456
1500
  const fieldId = useId();
1457
1501
  /**
@@ -1482,11 +1526,7 @@ function ConversationList({ fetcher, selectedPhone, onSelect, refreshIntervalMs,
1482
1526
  }, [onSelect]);
1483
1527
  const applyFilters = (event) => {
1484
1528
  event.preventDefault();
1485
- const next = {};
1486
- if (phone.trim() !== "") next.phone = phone;
1487
- if (from !== "") next.from = from;
1488
- if (to !== "") next.to = to;
1489
- setFilters(next);
1529
+ setFilters(buildFilters(phone, from, to));
1490
1530
  };
1491
1531
  /**
1492
1532
  * Un preset ≠ «Rango…» aplica AL CLIC: calcula el rango, sincroniza los date inputs (por si el
@@ -1498,11 +1538,7 @@ function ConversationList({ fetcher, selectedPhone, onSelect, refreshIntervalMs,
1498
1538
  const range = presetRange(days);
1499
1539
  setFrom(range.from);
1500
1540
  setTo(range.to);
1501
- const next = {};
1502
- if (phone.trim() !== "") next.phone = phone;
1503
- next.from = range.from;
1504
- next.to = range.to;
1505
- setFilters(next);
1541
+ setFilters(buildFilters(phone, range.from, range.to));
1506
1542
  };
1507
1543
  /**
1508
1544
  * El rango aplica al cambiar cualquiera de las dos fechas, sin botón de confirmación. Recibe los
@@ -1516,11 +1552,7 @@ function ConversationList({ fetcher, selectedPhone, onSelect, refreshIntervalMs,
1516
1552
  setDatePreset("range");
1517
1553
  setFrom(nextFrom);
1518
1554
  setTo(nextTo);
1519
- const next = {};
1520
- if (phone.trim() !== "") next.phone = phone;
1521
- if (nextFrom !== "") next.from = nextFrom;
1522
- if (nextTo !== "") next.to = nextTo;
1523
- setFilters(next);
1555
+ setFilters(buildFilters(phone, nextFrom, nextTo));
1524
1556
  };
1525
1557
  const clearFilters = () => {
1526
1558
  setPhone("");
@@ -1743,7 +1775,8 @@ function ConversationList({ fetcher, selectedPhone, onSelect, refreshIntervalMs,
1743
1775
  *
1744
1776
  * El relanzamiento **en frío con plantilla** existe, pero **no en este visor**: vive en el
1745
1777
  * header del drawer del embudo de `lms-mf-lifters`, que es donde el MF ya tiene cargado el
1746
- * detalle del embudo. Acá se menciona para que el operador sepa a dónde ir — nunca se ejecuta.
1778
+ * detalle del embudo. Este visor no lo menciona (DEV-6309: también monta en la pantalla 13
1779
+ * del caso, que no tiene embudo) — ni lo nombra ni lo ejecuta.
1747
1780
  */
1748
1781
  /**
1749
1782
  * El aviso de los envíos que no salieron.
@@ -1787,14 +1820,15 @@ function FailureNotice({ composer }) {
1787
1820
  * conversación» rompe COMP-06 aunque el código siga funcionando — y ahora además sería falso: el
1788
1821
  * endpoint ya no reactiva nada.
1789
1822
  *
1790
- * La última frase apunta a dónde SÍ se relanza en frío (el header del drawer del embudo), porque
1791
- * el operador que llega hasta acá con la ventana cerrada suele estar buscando exactamente eso.
1823
+ * No menciona plantillas ni cómo retomarla en frío (DEV-6309, decisión de David): el visor monta en
1824
+ * hosts distintos, «el header del drawer del embudo» mandaba al analista de la pantalla 13 a un
1825
+ * lugar que ahí no existe, y hablar de plantillas sugería construir algo que no se va a hacer.
1792
1826
  */
1793
1827
  function ReleaseToBot({ composer }) {
1794
1828
  if (composer.releaseState === "released") return /* @__PURE__ */ jsx("p", {
1795
1829
  className: "wa-composer__released",
1796
1830
  role: "status",
1797
- 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."
1831
+ children: "Listo: la conversación volvió al bot. La ventana sigue cerrada — se abre cuando la persona responda."
1798
1832
  });
1799
1833
  return /* @__PURE__ */ jsxs("div", {
1800
1834
  className: "wa-composer__release",
@@ -1802,10 +1836,10 @@ function ReleaseToBot({ composer }) {
1802
1836
  /* @__PURE__ */ jsxs("p", {
1803
1837
  className: "wa-composer__release-explain",
1804
1838
  children: [
1805
- "Podés devolver la conversación al bot: se suelta el control y el bot vuelve a manejarla.",
1839
+ "Puedes devolver la conversación al bot: se suelta el control y el bot vuelve a manejarla.",
1806
1840
  " ",
1807
- /* @__PURE__ */ jsx("strong", { children: "No se le manda ningún mensaje a la persona y no te habilita a vos para seguir escribiendo" }),
1808
- " — 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."
1841
+ /* @__PURE__ */ jsx("strong", { children: "No se le manda ningún mensaje a la persona y no te habilita para seguir escribiendo" }),
1842
+ " — si responde, la ventana se abre y el composer vuelve solo."
1809
1843
  ]
1810
1844
  }),
1811
1845
  composer.releaseState === "error" && composer.releaseFailure !== null && /* @__PURE__ */ jsx("p", {
@@ -1823,7 +1857,7 @@ function ReleaseToBot({ composer }) {
1823
1857
  ]
1824
1858
  });
1825
1859
  }
1826
- function Composer({ canReply, composer, onRetryWindow, prefill }) {
1860
+ function Composer({ canReply, composer, onRetryWindow, prefill, locked = false, takeoverNotice = null, focusRequest = null }) {
1827
1861
  /**
1828
1862
  * Lo que el operador tipeó, junto con **de qué precarga vino** (DEC-G).
1829
1863
  *
@@ -1865,6 +1899,12 @@ function Composer({ canReply, composer, onRetryWindow, prefill }) {
1865
1899
  if (prefill === null || prefill === void 0) return;
1866
1900
  inputRef.current?.focus();
1867
1901
  }, [prefill]);
1902
+ useEffect(() => {
1903
+ if (focusRequest === null) return;
1904
+ inputRef.current?.focus();
1905
+ }, [focusRequest]);
1906
+ /** El id del aviso del pie, para que el lector de pantalla lo lea al enfocar el textarea. */
1907
+ const noticeId = useId();
1868
1908
  if (!canReply) return null;
1869
1909
  if (composer.windowState === "closed") return /* @__PURE__ */ jsxs("div", {
1870
1910
  className: "wa-composer wa-composer--closed",
@@ -1905,6 +1945,7 @@ function Composer({ canReply, composer, onRetryWindow, prefill }) {
1905
1945
  ]
1906
1946
  });
1907
1947
  const send = () => {
1948
+ if (locked) return;
1908
1949
  const text = draft.trim();
1909
1950
  if (text === "") return;
1910
1951
  composer.send(text);
@@ -1945,8 +1986,10 @@ function Composer({ canReply, composer, onRetryWindow, prefill }) {
1945
1986
  maxLength: REPLY_TEXT_MAX_LENGTH,
1946
1987
  rows: 2,
1947
1988
  value: draft,
1948
- placeholder: "Escribí tu respuesta…",
1989
+ placeholder: "Escribe tu respuesta…",
1949
1990
  "aria-label": "Mensaje para la persona",
1991
+ disabled: locked,
1992
+ "aria-describedby": takeoverNotice !== null || locked ? noticeId : void 0,
1950
1993
  onChange: (event) => setDraft(event.target.value),
1951
1994
  onKeyDown: (event) => {
1952
1995
  if (event.key !== "Enter" || event.shiftKey || event.nativeEvent.isComposing) return;
@@ -1956,7 +1999,17 @@ function Composer({ canReply, composer, onRetryWindow, prefill }) {
1956
1999
  }), /* @__PURE__ */ jsxs("div", {
1957
2000
  className: "wa-composer__hint-row",
1958
2001
  children: [
1959
- /* @__PURE__ */ jsx("span", {
2002
+ takeoverNotice !== null ? /* @__PURE__ */ jsx("span", {
2003
+ className: "wa-composer__hint",
2004
+ "data-takeover": "true",
2005
+ id: noticeId,
2006
+ children: takeoverNotice
2007
+ }) : locked ? /* @__PURE__ */ jsx("span", {
2008
+ className: "wa-composer__hint",
2009
+ "data-locked": "true",
2010
+ id: noticeId,
2011
+ children: "Pulsa «Escribir igual» para responder"
2012
+ }) : /* @__PURE__ */ jsx("span", {
1960
2013
  className: "wa-composer__hint",
1961
2014
  children: "Al enviar, el bot se pausa y la conversación queda tomada por ti"
1962
2015
  }),
@@ -1971,7 +2024,7 @@ function Composer({ canReply, composer, onRetryWindow, prefill }) {
1971
2024
  /* @__PURE__ */ jsx("button", {
1972
2025
  type: "submit",
1973
2026
  className: "wa-composer__send",
1974
- disabled: draft.trim() === "",
2027
+ disabled: locked || draft.trim() === "",
1975
2028
  children: "Enviar"
1976
2029
  })
1977
2030
  ]
@@ -2865,17 +2918,18 @@ const THREAD_CSS = `
2865
2918
  font-weight: 400;
2866
2919
  }
2867
2920
 
2868
- /* DEV-5061 — la barra de takeover, entre el header y el scroller. Ámbar cuando la tiene otro
2869
- (es un aviso: no escribas encima) y añil cuando es tuya (es tu control, con su acción). Los
2870
- dos tonos son los de la paleta que fijó DEV-5053. */
2921
+ /* DEV-5061 — la barra de takeover. Ámbar cuando la tiene otro (es un aviso: no escribas encima)
2922
+ y añil cuando es tuya (es tu control, con su acción). Los dos tonos son los de la paleta que
2923
+ fijó DEV-5053. Desde DEV-6309 va ENCIMA del composer, de ancho completo: el borde pasa arriba. */
2871
2924
  .wa-thread__takeover {
2872
2925
  display: flex;
2926
+ flex: 0 0 auto;
2873
2927
  align-items: center;
2874
2928
  justify-content: space-between;
2875
2929
  gap: 12px;
2876
2930
  flex-wrap: wrap;
2877
2931
  padding: 8px 12px;
2878
- border-bottom: 1px solid #e4e7ee;
2932
+ border-top: 1px solid #e4e7ee;
2879
2933
  background: #fff7e8;
2880
2934
  color: #b7791f;
2881
2935
  font-size: 13px;
@@ -2885,12 +2939,24 @@ const THREAD_CSS = `
2885
2939
  color: #4f5aed;
2886
2940
  }
2887
2941
  .wa-thread__takeover-text {
2942
+ display: inline-flex;
2943
+ align-items: center;
2944
+ gap: 6px;
2888
2945
  min-width: 0;
2889
2946
  }
2947
+ /* DEV-6309: el icono de persona de la toma ajena. flex: none para que un nombre largo no lo
2948
+ aplaste; el texto es el que envuelve. */
2949
+ .wa-thread__takeover-icon {
2950
+ flex: none;
2951
+ }
2890
2952
  /* Pill, el mismo molde que el Reintentar de DEV-5053 P7. \`currentColor\` es lo que hace que el
2891
2953
  botón siga al tono de la barra sin duplicar la regla por variante. */
2892
2954
  .wa-thread__takeover-button {
2955
+ display: inline-flex;
2893
2956
  flex: none;
2957
+ align-items: center;
2958
+ gap: 6px;
2959
+ white-space: nowrap;
2894
2960
  padding: 4px 12px;
2895
2961
  border: 1px solid currentColor;
2896
2962
  border-radius: 999px;
@@ -3172,6 +3238,13 @@ const THREAD_CSS = `
3172
3238
  outline: 2px solid rgba(79, 90, 237, 0.25);
3173
3239
  outline-offset: 0;
3174
3240
  }
3241
+ /* DEV-6309: bloqueado por la toma de otra persona. Atenuado y sin cursor de texto: que se vea que
3242
+ no es un campo roto sino uno que espera «Escribir igual». */
3243
+ .wa-composer__input:disabled {
3244
+ color: #9AA1AE;
3245
+ cursor: not-allowed;
3246
+ opacity: 0.7;
3247
+ }
3175
3248
  /* DEV-5053 P2: hint del takeover a la izquierda; contador y Enviar a la derecha. */
3176
3249
  .wa-composer__hint-row {
3177
3250
  display: flex;
@@ -3188,6 +3261,10 @@ const THREAD_CSS = `
3188
3261
  font-size: 10.5px;
3189
3262
  color: #9AA1AE;
3190
3263
  }
3264
+ /* DEV-6309: el aviso de «Escribir igual» — ámbar como la barra de la que es consecuencia. */
3265
+ .wa-composer__hint[data-takeover='true'] {
3266
+ color: #b7791f;
3267
+ }
3191
3268
  .wa-composer__counter {
3192
3269
  flex: 0 0 auto;
3193
3270
  font-size: 10.5px;
@@ -4026,6 +4103,8 @@ function useThread({ fetcher, phone, refreshIntervalMs = DEFAULT_REFRESH_INTERVA
4026
4103
  takenBy: thread.taken_by ?? null,
4027
4104
  takenUntil: thread.taken_until ?? null,
4028
4105
  takenByMe: thread.taken_by_me === true,
4106
+ takenAt: thread.taken_at ?? null,
4107
+ takenByRole: thread.taken_by_role ?? null,
4029
4108
  status: messages.length > 0 ? "ready" : "empty",
4030
4109
  error: null,
4031
4110
  olderCursor: thread.older_cursor,
@@ -4043,6 +4122,8 @@ function useThread({ fetcher, phone, refreshIntervalMs = DEFAULT_REFRESH_INTERVA
4043
4122
  takenBy: null,
4044
4123
  takenUntil: null,
4045
4124
  takenByMe: false,
4125
+ takenAt: null,
4126
+ takenByRole: null,
4046
4127
  status: "error",
4047
4128
  error: toError(cause),
4048
4129
  olderCursor: null,
@@ -4161,6 +4242,8 @@ function useThread({ fetcher, phone, refreshIntervalMs = DEFAULT_REFRESH_INTERVA
4161
4242
  takenBy: thread.taken_by ?? null,
4162
4243
  takenUntil: thread.taken_until ?? null,
4163
4244
  takenByMe: thread.taken_by_me === true,
4245
+ takenAt: thread.taken_at ?? null,
4246
+ takenByRole: thread.taken_by_role ?? null,
4164
4247
  status: messages.length > 0 ? "ready" : "empty",
4165
4248
  error: null
4166
4249
  };
@@ -4194,6 +4277,8 @@ function useThread({ fetcher, phone, refreshIntervalMs = DEFAULT_REFRESH_INTERVA
4194
4277
  takenBy: current?.takenBy ?? null,
4195
4278
  takenUntil: current?.takenUntil ?? null,
4196
4279
  takenByMe: current?.takenByMe ?? false,
4280
+ takenAt: current?.takenAt ?? null,
4281
+ takenByRole: current?.takenByRole ?? null,
4197
4282
  hasOlder: current?.hasOlder ?? false,
4198
4283
  loadOlder,
4199
4284
  retry,
@@ -4236,7 +4321,36 @@ function takeoverCountdown(iso, now = Date.now()) {
4236
4321
  if (Number.isNaN(until)) return null;
4237
4322
  const left = until - now;
4238
4323
  if (left <= 0) return null;
4239
- const totalMinutes = Math.max(1, Math.ceil(left / MINUTE));
4324
+ return formatMinutes(Math.max(1, Math.ceil(left / MINUTE)));
4325
+ }
4326
+ /**
4327
+ * Cuánto hace que se tomó la conversación (DEV-6309): «12 m», «1 h 5 m», o `null` si `taken_at`
4328
+ * no está o no parsea.
4329
+ *
4330
+ * Mismo formato corto que `takeoverCountdown` a propósito: la barra muestra uno u otro según lo
4331
+ * que mande el servidor, y dos formatos para la misma magnitud se leerían como dos datos
4332
+ * distintos. Se redondea hacia ABAJO (son minutos cumplidos) con piso de `1 m`: «0 m» se lee como
4333
+ * dato faltante, y un reloj del operador atrasado —que daría negativo— significa «recién».
4334
+ */
4335
+ function takeoverElapsed(iso, now = Date.now()) {
4336
+ if (typeof iso !== "string") return null;
4337
+ const since = Date.parse(iso);
4338
+ if (Number.isNaN(since)) return null;
4339
+ return formatMinutes(Math.max(1, Math.floor((now - since) / MINUTE)));
4340
+ }
4341
+ /**
4342
+ * ¿La toma ya venció contra el reloj de quien mira? (DEV-6309)
4343
+ *
4344
+ * `true` SÓLO si `taken_until` es un instante válido y ya pasó. Ausente o basura NO es «vencida»:
4345
+ * es «no sé hasta cuándo», y ahí manda el `taken_by` del servidor — tratar un dato deforme como
4346
+ * vencimiento desbloquearía el composer sobre una conversación que alguien sí está atendiendo.
4347
+ */
4348
+ function takeoverExpired(iso, now = Date.now()) {
4349
+ if (typeof iso !== "string") return false;
4350
+ const until = Date.parse(iso);
4351
+ return !Number.isNaN(until) && until <= now;
4352
+ }
4353
+ function formatMinutes(totalMinutes) {
4240
4354
  const hours = Math.floor(totalMinutes / 60);
4241
4355
  const minutes = totalMinutes % 60;
4242
4356
  if (hours === 0) return `${minutes} m`;
@@ -4326,7 +4440,7 @@ function currentServiceState(messages) {
4326
4440
  return null;
4327
4441
  }
4328
4442
  /**
4329
- * La barra de takeover del hilo (DEV-5061).
4443
+ * La barra de takeover del hilo (DEV-5061, rediseñada para la toma ajena en DEV-6309).
4330
4444
  *
4331
4445
  * El problema que resuelve: el store ya guardaba quién tomó la conversación y el bot ya se callaba,
4332
4446
  * pero nada de eso llegaba acá. Una conversación atendida por un compañero se veía **idéntica** a
@@ -4335,28 +4449,86 @@ function currentServiceState(messages) {
4335
4449
  *
4336
4450
  * Dos ramas, deliberadamente distintas:
4337
4451
  *
4338
- * - **La tomaste vos** — se ofrece «Reactivar bot», porque es tuya y podés soltarla.
4339
- * - **La tomó otro** — se dice quién y hasta cuándo, y NO se ofrece el botón. Robarle el turno a
4340
- * un compañero desde un botón que parece inofensivo es peor que la ambigüedad que esta barra
4341
- * vino a arreglar; quien quiera hacerlo puede responder, que renueva la toma a su nombre.
4452
+ * - **La tomaste vos** — se ofrece «Reactivar bot», porque es tuya y podés soltarla. Igual que en
4453
+ * DEV-5061: DEV-6309 sólo la cambió de lugar.
4454
+ * - **La tiene otra persona** (DEV-6309) — barra ámbar «La tiene ‹nombre› (‹rol›) · ‹tiempo›» y el
4455
+ * composer BLOQUEADO. Escribir encima de un compañero pasa a ser una decisión explícita
4456
+ * («Escribir igual»), no un accidente: antes el composer dejaba escribir y el envío le robaba la
4457
+ * toma a su nombre sin que nadie lo hubiera decidido. El botón NO es «Reactivar bot»: soltar la
4458
+ * toma de otro sigue sin ofrecerse.
4342
4459
  *
4343
4460
  * `takenByMe` viene del SERVIDOR y no se deriva comparando `takenBy` con nadie: dos operadores
4344
4461
  * pueden llamarse igual, y confundirlos es exactamente darle a uno el botón del otro.
4345
4462
  *
4346
- * El nombre entra sólo como hijo de texto, que React escapa (T-03-02).
4463
+ * El nombre y el rol entran sólo como hijos de texto, que React escapa (T-03-02).
4347
4464
  */
4348
- function TakeoverBar({ takenBy, takenUntil, takenByMe, composer }) {
4465
+ function TakeoverBar({ takenBy, takenUntil, takenByMe, takenAt, takenByRole, foreignLive, offerWriteAnyway, onWriteAnyway, composer }) {
4349
4466
  if (composer.releaseState === "released") return null;
4350
4467
  const left = takeoverCountdown(takenUntil);
4468
+ if (!takenByMe) {
4469
+ if (!foreignLive) return null;
4470
+ const role = typeof takenByRole === "string" ? takenByRole.trim() : "";
4471
+ const elapsed = takeoverElapsed(takenAt);
4472
+ const when = elapsed !== null ? elapsed : left !== null ? `se libera en ${left}` : null;
4473
+ return /* @__PURE__ */ jsxs("div", {
4474
+ className: "wa-thread__takeover",
4475
+ role: "status",
4476
+ children: [/* @__PURE__ */ jsxs("span", {
4477
+ className: "wa-thread__takeover-text",
4478
+ children: [/* @__PURE__ */ jsxs("svg", {
4479
+ className: "wa-thread__takeover-icon",
4480
+ width: 14,
4481
+ height: 14,
4482
+ viewBox: "0 0 16 16",
4483
+ fill: "none",
4484
+ stroke: "currentColor",
4485
+ strokeWidth: 1.5,
4486
+ strokeLinecap: "round",
4487
+ strokeLinejoin: "round",
4488
+ "aria-hidden": "true",
4489
+ children: [/* @__PURE__ */ jsx("circle", {
4490
+ cx: "8",
4491
+ cy: "5.5",
4492
+ r: "2.75"
4493
+ }), /* @__PURE__ */ jsx("path", { d: "M2.75 14c.6-2.6 2.7-4.25 5.25-4.25s4.65 1.65 5.25 4.25" })]
4494
+ }), /* @__PURE__ */ jsxs("span", { children: [
4495
+ "La tiene",
4496
+ " ",
4497
+ /* @__PURE__ */ jsxs("strong", { children: [takenBy ?? "otro operador", role !== "" && ` (${role})`] }),
4498
+ when !== null && ` · ${when}`
4499
+ ] })]
4500
+ }), offerWriteAnyway && /* @__PURE__ */ jsxs("button", {
4501
+ type: "button",
4502
+ className: "wa-thread__takeover-button",
4503
+ onClick: onWriteAnyway,
4504
+ children: [/* @__PURE__ */ jsx("svg", {
4505
+ width: 12,
4506
+ height: 12,
4507
+ viewBox: "0 0 16 16",
4508
+ fill: "none",
4509
+ stroke: "currentColor",
4510
+ strokeWidth: 1.5,
4511
+ strokeLinecap: "round",
4512
+ strokeLinejoin: "round",
4513
+ "aria-hidden": "true",
4514
+ children: /* @__PURE__ */ jsx("path", { d: "M11 2.5l2.5 2.5L5.5 13H3v-2.5z" })
4515
+ }), "Escribir igual"]
4516
+ })]
4517
+ });
4518
+ }
4351
4519
  if (takenBy === null && left === null) return null;
4352
4520
  return /* @__PURE__ */ jsxs("div", {
4353
4521
  className: "wa-thread__takeover",
4354
- "data-mine": takenByMe || void 0,
4522
+ "data-mine": "true",
4355
4523
  role: "status",
4356
4524
  children: [/* @__PURE__ */ jsxs("span", {
4357
4525
  className: "wa-thread__takeover-text",
4358
- 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}`]
4359
- }), takenByMe && /* @__PURE__ */ jsx("button", {
4526
+ children: [
4527
+ /* @__PURE__ */ jsx("strong", { children: "Bot en pausa" }),
4528
+ " — la tomaste tú",
4529
+ left !== null && ` · se libera en ${left}`
4530
+ ]
4531
+ }), /* @__PURE__ */ jsx("button", {
4360
4532
  type: "button",
4361
4533
  className: "wa-thread__takeover-button",
4362
4534
  onClick: composer.release,
@@ -4365,8 +4537,17 @@ function TakeoverBar({ takenBy, takenUntil, takenByMe, composer }) {
4365
4537
  })]
4366
4538
  });
4367
4539
  }
4540
+ /**
4541
+ * El primer nombre para el aviso del pie («Paula está atendiendo…», DEV-6309), como el diseño.
4542
+ * Partir por espacios puede quedarse corto con un nombre compuesto («María José» ⇒ «María»), y se
4543
+ * acepta: el nombre COMPLETO está en la barra, una línea más arriba. Sin nombre, un genérico.
4544
+ */
4545
+ function firstName(takenBy) {
4546
+ const first = typeof takenBy === "string" ? takenBy.trim().split(/\s+/)[0] : "";
4547
+ return first !== void 0 && first !== "" ? first : "Otra persona";
4548
+ }
4368
4549
  function ConversationThread({ fetcher, phone, displayName, refreshIntervalMs, className }) {
4369
- const { messages: serverMessages, status, error, windowState, canReply, takenBy, takenUntil, takenByMe, hasOlder, loadOlder, retry, refresh } = useThread({
4550
+ const { messages: serverMessages, status, error, windowState, canReply, takenBy, takenUntil, takenByMe, takenAt, takenByRole, hasOlder, loadOlder, retry, refresh } = useThread({
4370
4551
  fetcher,
4371
4552
  phone,
4372
4553
  refreshIntervalMs
@@ -4442,6 +4623,59 @@ function ConversationThread({ fetcher, phone, displayName, refreshIntervalMs, cl
4442
4623
  * sola. La comparación es por identidad de objeto — son literalmente las mismas filas.
4443
4624
  */
4444
4625
  const visible = messages.filter((message) => !isSuggestion(message) || message === suggestion.suggestion);
4626
+ /**
4627
+ * «Escribir igual» (DEV-6309): el operador eligió escribir encima de la toma de otra persona.
4628
+ *
4629
+ * Es estado LOCAL de este hilo y guarda **de qué consulta vino** (DEC-G, el patrón de
4630
+ * `useThread`/`useComposer`): cambiar de conversación lo invalida en el render mismo, sin un
4631
+ * efecto que lo resetee, y remontar lo pierde. Dura mientras esta conversación siga abierta:
4632
+ * volver a preguntarlo en cada latido sería un botón que se enciende solo cada 10 s.
4633
+ *
4634
+ * `focus` es una caja nueva por clic: el disparador del foco del composer (ver `focusRequest`).
4635
+ *
4636
+ * DEV-6419: además de la conversación, el desbloqueo guarda **a qué toma** se le dijo que sí —
4637
+ * `taken_by` + `taken_at`—. El operador aceptó escribir encima de Paula, no de quien venga
4638
+ * después: si en la misma sesión la toma pasa de Paula a Carlos, el sobre trae otra identidad y
4639
+ * el composer vuelve a bloquearse hasta un nuevo «Escribir igual». Un latido que renueva la
4640
+ * misma toma no la cambia: el servicio no mueve `taken_at` cuando quien escribe es quien ya la
4641
+ * tiene (`record_takeover`), así que la comparación es estable entre refetches. Si la toma se
4642
+ * libera o pasa a ser mía, `foreignLive` se apaga y mandan esos estados, no este.
4643
+ */
4644
+ const [writeAnyway, setWriteAnyway] = useState(null);
4645
+ const unlocked = writeAnyway !== null && writeAnyway.fetcher === fetcher && writeAnyway.phone === phone && writeAnyway.takenBy === takenBy && writeAnyway.takenAt === takenAt;
4646
+ const handleWriteAnyway = useCallback(() => setWriteAnyway({
4647
+ fetcher,
4648
+ phone,
4649
+ takenBy,
4650
+ takenAt,
4651
+ focus: {}
4652
+ }), [
4653
+ fetcher,
4654
+ phone,
4655
+ takenBy,
4656
+ takenAt
4657
+ ]);
4658
+ /**
4659
+ * ¿Hay una toma AJENA vigente? (DEV-6309) De esto dependen a la vez la barra ámbar, el bloqueo
4660
+ * del composer y el aviso del pie — por eso se decide una sola vez, acá.
4661
+ *
4662
+ * - `takenByMe` manda: si el servidor dice que es mía (p. ej. tras enviar), no hay nada ajeno.
4663
+ * - Recién liberada por este operador (`released`), el guard de siempre la tapa.
4664
+ * - Vencida contra el reloj de quien mira ⇒ ya no es de nadie: se va la barra y se desbloquea.
4665
+ * Ausente o basura NO es vencida (`takeoverExpired`).
4666
+ * - Con sólo el nombre o sólo el tiempo alcanza: media verdad sobre una toma sigue siendo mejor
4667
+ * que hacerla pasar por libre (DEV-5061).
4668
+ *
4669
+ * No hay timer para el vencimiento, igual que para la cuenta regresiva: se recalcula en cada
4670
+ * render, y el latido del hilo re-renderiza cada 10 s en producción.
4671
+ */
4672
+ const foreignLive = !takenByMe && composer.releaseState !== "released" && !takeoverExpired(takenUntil) && (takenBy !== null || takeoverCountdown(takenUntil) !== null);
4673
+ /**
4674
+ * Hay dónde escribir: con `can_reply` y la ventana no cerrada. Con `closed` el panel frío
4675
+ * REEMPLAZA al composer (COMP-04), así que «Escribir igual» no tendría nada que desbloquear y no
4676
+ * se ofrece; el bloqueo por ventana sigue mandando.
4677
+ */
4678
+ const hasComposer = canReply && composer.windowState !== "closed";
4445
4679
  const messagesRef = useRef(null);
4446
4680
  /** De qué consulta ya se hizo el scroll inicial: una vez por hilo, no en cada página. */
4447
4681
  const scrolledForRef = useRef(null);
@@ -4540,12 +4774,6 @@ function ConversationThread({ fetcher, phone, displayName, refreshIntervalMs, cl
4540
4774
  })
4541
4775
  })]
4542
4776
  }),
4543
- /* @__PURE__ */ jsx(TakeoverBar, {
4544
- takenBy,
4545
- takenUntil,
4546
- takenByMe,
4547
- composer
4548
- }),
4549
4777
  /* @__PURE__ */ jsxs("div", {
4550
4778
  className: "wa-thread__messages",
4551
4779
  ref: messagesRef,
@@ -4581,11 +4809,25 @@ function ConversationThread({ fetcher, phone, displayName, refreshIntervalMs, cl
4581
4809
  })] }, message.id ?? `sin-wamid-${position}`))]
4582
4810
  }, group.key ?? `sin-dia-${groupIndex}`))]
4583
4811
  }),
4812
+ /* @__PURE__ */ jsx(TakeoverBar, {
4813
+ takenBy,
4814
+ takenUntil,
4815
+ takenByMe,
4816
+ takenAt,
4817
+ takenByRole,
4818
+ foreignLive,
4819
+ offerWriteAnyway: hasComposer && !unlocked,
4820
+ onWriteAnyway: handleWriteAnyway,
4821
+ composer
4822
+ }),
4584
4823
  /* @__PURE__ */ jsx(Composer, {
4585
4824
  canReply,
4586
4825
  composer,
4587
4826
  onRetryWindow: retry,
4588
- prefill
4827
+ prefill,
4828
+ locked: foreignLive && !unlocked,
4829
+ takeoverNotice: foreignLive && unlocked ? `${firstName(takenBy)} está atendiendo · el lifter verá a dos personas` : null,
4830
+ focusRequest: unlocked && writeAnyway !== null ? writeAnyway.focus : null
4589
4831
  })
4590
4832
  ]
4591
4833
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@liftitapp/wa-conversations",
3
- "version": "0.8.2",
3
+ "version": "0.10.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",