@liftitapp/wa-conversations 0.10.1 → 0.12.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.
@@ -756,7 +756,7 @@ function dedupeByWamid(messages) {
756
756
  //#endregion
757
757
  //#region src/core/contract/operator-send.ts
758
758
  /** El payload del cable es entrada NO confiable: se mira como diccionario, no como tipo. */
759
- function asRecord$1(value) {
759
+ function asRecord$2(value) {
760
760
  return typeof value === "object" && value !== null ? value : {};
761
761
  }
762
762
  /** Un string útil, o `null`. El vacío es tan inútil como el ausente. */
@@ -833,7 +833,7 @@ function optimisticMessage(text, at, clientMessageId) {
833
833
  * hacerle perder al operador el mensaje que acaba de mandar.
834
834
  */
835
835
  function normalizeReplyMessage(payload) {
836
- const record = asRecord$1(payload);
836
+ const record = asRecord$2(payload);
837
837
  return {
838
838
  id: asNonEmptyString(record.wamid) ?? asNonEmptyString(record.id),
839
839
  at: asNonEmptyString(record.at) ?? asNonEmptyString(record.occurred_at),
@@ -868,8 +868,8 @@ const UNSTRUCTURED_ERROR_CODE = "unknown";
868
868
  * exactamente el atajo que en FlexOS terminaba mandando plantillas facturadas.
869
869
  */
870
870
  function readSendError(cause) {
871
- const fromError = asRecord$1(asRecord$1(cause).body);
872
- const direct = asRecord$1(cause);
871
+ const fromError = asRecord$2(asRecord$2(cause).body);
872
+ const direct = asRecord$2(cause);
873
873
  const body = typeof fromError.error_code === "string" ? fromError : typeof direct.error_code === "string" ? direct : {};
874
874
  const errorCode = asNonEmptyString(body.error_code);
875
875
  if (errorCode === null) return {
@@ -903,9 +903,119 @@ function sendFailureCopy(failure) {
903
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
905
  case "write_forbidden": return "No tienes permiso para responder en esta conversación.";
906
+ case "invalid_phone": return "El número de destino no es un celular válido en formato E.164.";
907
+ case "template_not_allowed": return "La plantilla no está habilitada para este número.";
908
+ case "invalid_template_params": return "Los parámetros no coinciden con la plantilla.";
906
909
  default: return failure.serverMessage ?? "No se pudo enviar el mensaje.";
907
910
  }
908
911
  }
912
+ function asRecord$1(value) {
913
+ return typeof value === "object" && value !== null ? value : {};
914
+ }
915
+ function asString$1(value) {
916
+ return typeof value === "string" ? value : "";
917
+ }
918
+ function asNullableString$1(value) {
919
+ return typeof value === "string" && value !== "" ? value : null;
920
+ }
921
+ /**
922
+ * Estrecha una plantilla del cable. Sin `name` o `language` no hay qué mandar: se descarta. Un
923
+ * `body_param_count` fuera de 0–10 o no entero también: ofrecerla sería un formulario que el store
924
+ * siempre rechaza.
925
+ */
926
+ function normalizeTemplate(value) {
927
+ const record = asRecord$1(value);
928
+ const name = asNullableString$1(record.name);
929
+ const language = asNullableString$1(record.language);
930
+ const count = record.body_param_count;
931
+ if (name === null || language === null) return null;
932
+ if (typeof count !== "number" || !Number.isInteger(count)) return null;
933
+ if (count < 0 || count > 10) return null;
934
+ return {
935
+ name,
936
+ language,
937
+ label: asNullableString$1(record.label),
938
+ body_param_count: count,
939
+ body_text: asNullableString$1(record.body_text)
940
+ };
941
+ }
942
+ /**
943
+ * El 200 de la lista. `can_start` es fail-closed (sólo el `true` literal), como `can_reply`.
944
+ */
945
+ function normalizeTemplates(payload) {
946
+ const record = asRecord$1(payload);
947
+ const items = Array.isArray(record.items) ? record.items.map(normalizeTemplate).filter((item) => item !== null) : [];
948
+ return {
949
+ phone_number_id: asString$1(record.phone_number_id),
950
+ can_start: record.can_start === true,
951
+ items
952
+ };
953
+ }
954
+ /** El 201/200 del envío: la burbuja es el MISMO `ThreadMessage` del hilo y de `/reply`. */
955
+ function normalizeStartResponse(payload) {
956
+ const record = asRecord$1(payload);
957
+ return {
958
+ phone_e164: asString$1(record.phone_e164),
959
+ phone_number_id: asString$1(record.phone_number_id),
960
+ message: normalizeReplyMessage(record.message)
961
+ };
962
+ }
963
+ /**
964
+ * ¿El rechazo del hilo dice «no hay conversación con este número»?
965
+ *
966
+ * El store responde 404 genérico a un par inexistente (no revela qué teléfonos existen). Se
967
+ * reconocen las dos formas que llegan hoy: `status === 404` (el `WaFetchError` del default-fetcher
968
+ * del entry `./element`, o cualquier error con `.status`) y la marca `code: 'wa_no_conversation'`
969
+ * del fetcher de `lms-web-app`. Cualquier otra cosa es un error de verdad y se pinta como tal.
970
+ */
971
+ function isNoThreadError(error) {
972
+ const record = asRecord$1(error);
973
+ return record.status === 404 || record.code === "wa_no_conversation";
974
+ }
975
+ /**
976
+ * La regla de cuándo se ofrece la plantilla (DEV-8758).
977
+ *
978
+ * 🔴 Sólo `closed` la abre: `unverified` NO. «No pudimos leer la ventana» no es «está cerrada», y
979
+ * ofrecer una plantilla —que Meta cobra— por un parpadeo de Postgres es exactamente el bug de
980
+ * FlexOS que el composer ya evita (`CLAUDE.md`).
981
+ *
982
+ * Con un hilo existente hace falta además `can_reply`: un operador de solo lectura ve el visor como
983
+ * siempre. Sin hilo no hay `can_reply` que leer, y quien decide es el `can_start` de la lista.
984
+ */
985
+ function templateOffer(input) {
986
+ if (!(input.noThread || input.canReply && input.windowState === "closed")) return "none";
987
+ const { templates } = input;
988
+ if (templates.status === "idle" || templates.status === "loading") return "loading";
989
+ if (templates.status === "error") return "unavailable";
990
+ if (!templates.canStart) return "read_only";
991
+ if (templates.itemCount === 0) return "no_templates";
992
+ return "form";
993
+ }
994
+ /**
995
+ * ¿Los parámetros que tipeó el operador pasan las reglas del contrato? Es la misma validación que
996
+ * hace el store (422 `invalid_template_params`) y se repite acá sólo para no habilitar «Enviar
997
+ * plantilla» con algo que va a volver rechazado. El store sigue siendo quien decide.
998
+ */
999
+ function templateParamsValid(params, expectedCount) {
1000
+ if (params.length !== expectedCount) return false;
1001
+ return params.every((raw) => {
1002
+ const value = raw.trim();
1003
+ if (value === "" || value.length > 1024) return false;
1004
+ if (/[\n\r\t]/.test(value)) return false;
1005
+ return !/ {5,}/.test(value);
1006
+ });
1007
+ }
1008
+ /**
1009
+ * La vista previa: el `body_text` aprobado con cada `{{n}}` reemplazado por su parámetro. Un
1010
+ * parámetro vacío deja el `{{n}}` a la vista, para que se note qué falta. Sin `body_text`, `null`.
1011
+ */
1012
+ function renderTemplatePreview(bodyText, params) {
1013
+ if (bodyText === null) return null;
1014
+ return bodyText.replace(/\{\{(\d+)\}\}/g, (match, index) => {
1015
+ const value = params[Number(index) - 1]?.trim() ?? "";
1016
+ return value === "" ? match : value;
1017
+ });
1018
+ }
909
1019
  //#endregion
910
1020
  //#region src/core/data/fetcher.ts
911
1021
  /**
@@ -1108,6 +1218,25 @@ async function loadConversations(fetcher, request = {}, options) {
1108
1218
  next_cursor: asNullableString(payload.next_cursor)
1109
1219
  };
1110
1220
  }
1221
+ /**
1222
+ * La lista de plantillas que se pueden mandar desde el número del host (DEV-8758). Coerción
1223
+ * defensiva como el resto: un payload deforme sale `can_start: false` e `items: []`. Los rechazos
1224
+ * se propagan tal cual: el panel decide qué pintar.
1225
+ */
1226
+ async function loadTemplates(fetcher, options) {
1227
+ return normalizeTemplates(await fetcher({ resource: "templates" }, options));
1228
+ }
1229
+ /**
1230
+ * Inicia la conversación con la plantilla (DEV-8758, 201 o 200 idempotente). Los rechazos se
1231
+ * propagan TAL CUAL y se leen con `readSendError` — el cuerpo plano `{error_code, retryable,
1232
+ * message}` es el mismo molde que el de `/reply`.
1233
+ */
1234
+ async function startConversation(fetcher, request, options) {
1235
+ return normalizeStartResponse(await fetcher({
1236
+ resource: "startConversation",
1237
+ ...request
1238
+ }, options));
1239
+ }
1111
1240
  //#endregion
1112
1241
  //#region src/core/usePolling.ts
1113
1242
  /**
@@ -1745,6 +1874,143 @@ function ConversationList({ fetcher, selectedPhone, onSelect, refreshIntervalMs,
1745
1874
  });
1746
1875
  }
1747
1876
  //#endregion
1877
+ //#region src/core/contract/save-document.ts
1878
+ /** El mensaje genérico de D-5: el visor no conoce los códigos de error del backoffice. */
1879
+ const GENERIC_SAVE_ERROR = "No se pudo guardar el documento. Intenta de nuevo.";
1880
+ /** Un alcance es válido si trae el dato que su `kind` exige (placa o nombre, no vacíos). */
1881
+ function isValidScope(scope) {
1882
+ if (scope.kind === "vehicle") return typeof scope.plate === "string" && scope.plate.trim() !== "";
1883
+ if (scope.kind === "person") return typeof scope.name === "string" && scope.name.trim() !== "";
1884
+ return false;
1885
+ }
1886
+ /**
1887
+ * Un tipo es válido si trae `code`/`name` no vacíos y al menos un alcance reconocido
1888
+ * (`vehicle`/`person`) en `scopes` — lo demás del cable es basura de la property JS del elemento,
1889
+ * que puede traer cualquier cosa, y se descarta en silencio (D-4).
1890
+ */
1891
+ function isValidType(type) {
1892
+ if (typeof type.code !== "string" || type.code.trim() === "") return false;
1893
+ if (typeof type.name !== "string" || type.name.trim() === "") return false;
1894
+ if (!Array.isArray(type.scopes)) return false;
1895
+ return type.scopes.some((kind) => kind === "vehicle" || kind === "person");
1896
+ }
1897
+ /**
1898
+ * Elegibilidad de la burbuja (D-3, T-no6-02): `direction === 'in'` EXACTO (fail-closed — una
1899
+ * dirección desconocida no ofrece la acción, aunque se pinte como entrante); `media_format`
1900
+ * `'image'` o `'pdf'` y NADA más — nunca la extensión de `file_name` ni `message_type`, el mismo
1901
+ * gate que `MediaAttachment` (T-05-01); `id` (wamid) y `media_id` no vacíos; el host tiene que
1902
+ * haber pasado al menos un tipo y un alcance válidos; y el mensaje no puede estar ya en `saved`
1903
+ * (ahí va la marca, no el botón).
1904
+ */
1905
+ function canSaveAsDocument(message, input) {
1906
+ if (input === void 0) return false;
1907
+ if (message.direction !== "in") return false;
1908
+ if (message.media_format !== "image" && message.media_format !== "pdf") return false;
1909
+ if (typeof message.id !== "string" || message.id === "") return false;
1910
+ if (typeof message.media_id !== "string" || message.media_id === "") return false;
1911
+ if (!Array.isArray(input.types) || !input.types.some(isValidType)) return false;
1912
+ if (!Array.isArray(input.scopes) || !input.scopes.some(isValidScope)) return false;
1913
+ const saved = input.saved;
1914
+ if (saved !== void 0 && saved !== null && message.id in saved) return false;
1915
+ return true;
1916
+ }
1917
+ /** Normaliza para la búsqueda del catálogo: sin tildes ni mayúsculas (D-4). */
1918
+ function normalizeSearch(value) {
1919
+ return value.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().trim();
1920
+ }
1921
+ /**
1922
+ * Los `requested` primero (en el orden del host), con el resto como catálogo filtrado por
1923
+ * `query` (sin tildes ni mayúsculas, sobre `name` y `code`). Descarta tipos inválidos y
1924
+ * duplicados por `code` — gana el PRIMERO en el orden del host (D-4).
1925
+ */
1926
+ function documentTypeOptions(types, query) {
1927
+ const valid = Array.isArray(types) ? types.filter(isValidType) : [];
1928
+ const seen = /* @__PURE__ */ new Set();
1929
+ const deduped = [];
1930
+ for (const type of valid) {
1931
+ if (seen.has(type.code)) continue;
1932
+ seen.add(type.code);
1933
+ deduped.push(type);
1934
+ }
1935
+ const requested = deduped.filter((type) => type.requested === true);
1936
+ const rest = deduped.filter((type) => type.requested !== true);
1937
+ const normalizedQuery = normalizeSearch(query);
1938
+ return {
1939
+ requested,
1940
+ catalog: normalizedQuery === "" ? rest : rest.filter((type) => normalizeSearch(`${type.name} ${type.code}`).includes(normalizedQuery)),
1941
+ selected: requested.length === 1 ? requested[0] : null
1942
+ };
1943
+ }
1944
+ /**
1945
+ * El tipo define el alcance (D-4): las opciones son los alcances VÁLIDOS del host (se descartan
1946
+ * los que no traen el dato que su `kind` exige); habilitadas sólo las que el tipo admite;
1947
+ * seleccionada la actual si sigue permitida, si no la primera permitida en el orden del host. Con
1948
+ * `type` null no se selecciona nada — no hay de qué derivar el alcance.
1949
+ */
1950
+ function resolveScope(type, scopes, current) {
1951
+ const options = (Array.isArray(scopes) ? scopes.filter(isValidScope) : []).map((scope) => ({
1952
+ scope,
1953
+ allowed: type !== null && type.scopes.includes(scope.kind)
1954
+ }));
1955
+ if (type === null) return {
1956
+ options,
1957
+ selected: null
1958
+ };
1959
+ const keepsCurrent = options.find((option) => option.scope === current && option.allowed);
1960
+ if (keepsCurrent !== void 0) return {
1961
+ options,
1962
+ selected: keepsCurrent.scope
1963
+ };
1964
+ const firstAllowed = options.find((option) => option.allowed);
1965
+ return {
1966
+ options,
1967
+ selected: firstAllowed !== void 0 ? firstAllowed.scope : null
1968
+ };
1969
+ }
1970
+ /**
1971
+ * La marca de la burbuja (D-6): sólo lee `saved[messageId]` — el visor no AFIRMA el guardado, lo
1972
+ * LEE (mismo principio que la barra de takeover, DEV-5190). Un `messageId` ausente o una entrada
1973
+ * sin `typeName` útil no pinta marca: es mejor no mostrar nada que inventar un «Guardado como».
1974
+ */
1975
+ function savedDocumentMark(message, input) {
1976
+ if (input === void 0) return null;
1977
+ const saved = input.saved;
1978
+ if (saved === void 0 || saved === null) return null;
1979
+ if (typeof message.id !== "string" || message.id === "") return null;
1980
+ const mark = saved[message.id];
1981
+ if (mark === void 0 || mark === null) return null;
1982
+ if (typeof mark.typeName !== "string" || mark.typeName.trim() === "") return null;
1983
+ return mark;
1984
+ }
1985
+ /** La hora HH:MM local de la marca (DEC-O: sin `Intl`, mismo criterio que `formatHour`). */
1986
+ function formatMarkHour(at) {
1987
+ if (typeof at !== "string") return null;
1988
+ const date = new Date(at);
1989
+ if (Number.isNaN(date.getTime())) return null;
1990
+ return `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
1991
+ }
1992
+ /**
1993
+ * «Guardado como {tipo} · {quién}, {hora}» (D-6). Sin `savedBy` cae el bloque «· …» entero —la
1994
+ * hora sola, sin quién, no cuenta la misma historia—; con `savedBy` pero sin `savedAt` que parsee,
1995
+ * cae sólo la hora.
1996
+ */
1997
+ function savedMarkLabel(mark) {
1998
+ const by = typeof mark.savedBy === "string" && mark.savedBy.trim() !== "" ? mark.savedBy.trim() : null;
1999
+ if (by === null) return `Guardado como ${mark.typeName}`;
2000
+ const hour = formatMarkHour(mark.savedAt);
2001
+ return hour !== null ? `Guardado como ${mark.typeName} · ${by}, ${hour}` : `Guardado como ${mark.typeName} · ${by}`;
2002
+ }
2003
+ /**
2004
+ * El texto del modal cuando el host rechaza (D-5): `Error.message` o un string no vacío,
2005
+ * VERBATIM — el visor no conoce los códigos de error del backoffice y no les inventa traducción;
2006
+ * eso es decisión del host (DEV-7665). Cualquier otra cosa cae al genérico.
2007
+ */
2008
+ function saveErrorMessage(reason) {
2009
+ if (reason instanceof Error && typeof reason.message === "string" && reason.message.trim() !== "") return reason.message;
2010
+ if (typeof reason === "string" && reason.trim() !== "") return reason;
2011
+ return GENERIC_SAVE_ERROR;
2012
+ }
2013
+ //#endregion
1748
2014
  //#region src/core/thread/Composer.tsx
1749
2015
  /**
1750
2016
  * El composer del operador — la mitad visible del takeover humano (DEV-4995).
@@ -1857,7 +2123,7 @@ function ReleaseToBot({ composer }) {
1857
2123
  ]
1858
2124
  });
1859
2125
  }
1860
- function Composer({ canReply, composer, onRetryWindow, prefill, locked = false, takeoverNotice = null, focusRequest = null }) {
2126
+ function Composer({ canReply, composer, onRetryWindow, prefill, locked = false, takeoverNotice = null, focusRequest = null, templateStart = null }) {
1861
2127
  /**
1862
2128
  * Lo que el operador tipeó, junto con **de qué precarga vino** (DEC-G).
1863
2129
  *
@@ -1906,6 +2172,14 @@ function Composer({ canReply, composer, onRetryWindow, prefill, locked = false,
1906
2172
  /** El id del aviso del pie, para que el lector de pantalla lo lea al enfocar el textarea. */
1907
2173
  const noticeId = useId();
1908
2174
  if (!canReply) return null;
2175
+ if (composer.windowState === "closed" && templateStart !== null) return /* @__PURE__ */ jsxs("div", {
2176
+ className: "wa-composer wa-composer--template",
2177
+ children: [
2178
+ /* @__PURE__ */ jsx(FailureNotice, { composer }),
2179
+ templateStart,
2180
+ /* @__PURE__ */ jsx(ReleaseToBot, { composer })
2181
+ ]
2182
+ });
1909
2183
  if (composer.windowState === "closed") return /* @__PURE__ */ jsxs("div", {
1910
2184
  className: "wa-composer wa-composer--closed",
1911
2185
  children: [
@@ -2530,7 +2804,7 @@ function formatHour(at) {
2530
2804
  if (Number.isNaN(date.getTime())) return null;
2531
2805
  return `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
2532
2806
  }
2533
- function MessageBubble({ message, optimistic = false, fetcher }) {
2807
+ function MessageBubble({ message, optimistic = false, fetcher, savedDocument = null, onSaveAsDocument }) {
2534
2808
  const direction = message.direction === "out" ? "out" : "in";
2535
2809
  const hour = formatHour(message.at);
2536
2810
  const ctas = threadCtas(message);
@@ -2571,6 +2845,35 @@ function MessageBubble({ message, optimistic = false, fetcher }) {
2571
2845
  message,
2572
2846
  fetcher
2573
2847
  }),
2848
+ savedDocument !== null ? /* @__PURE__ */ jsxs("span", {
2849
+ className: "wa-thread__saved-document",
2850
+ children: [/* @__PURE__ */ jsx("svg", {
2851
+ width: 13,
2852
+ height: 13,
2853
+ viewBox: "0 0 16 16",
2854
+ fill: "none",
2855
+ stroke: "currentColor",
2856
+ strokeWidth: 1.8,
2857
+ strokeLinecap: "round",
2858
+ strokeLinejoin: "round",
2859
+ "aria-hidden": "true",
2860
+ children: /* @__PURE__ */ jsx("polyline", { points: "2.5,8.5 6,12 13.5,4" })
2861
+ }), savedMarkLabel(savedDocument)]
2862
+ }) : onSaveAsDocument !== void 0 && /* @__PURE__ */ jsxs("button", {
2863
+ type: "button",
2864
+ className: "wa-thread__save-action",
2865
+ onClick: onSaveAsDocument,
2866
+ children: [/* @__PURE__ */ jsxs("svg", {
2867
+ width: 13,
2868
+ height: 13,
2869
+ viewBox: "0 0 16 16",
2870
+ fill: "none",
2871
+ stroke: "currentColor",
2872
+ strokeWidth: 1.3,
2873
+ "aria-hidden": "true",
2874
+ children: [/* @__PURE__ */ jsx("path", { d: "M4 1.5h5.5L12.5 4.5V14a.5.5 0 0 1-.5.5H4a.5.5 0 0 1-.5-.5v-12a.5.5 0 0 1 .5-.5Z" }), /* @__PURE__ */ jsx("path", { d: "M9.3 1.5V4.5h3" })]
2875
+ }), "Guardar como documento"]
2876
+ }),
2574
2877
  ctas.length > 0 && /* @__PURE__ */ jsx("div", {
2575
2878
  className: "wa-thread__ctas",
2576
2879
  children: ctas.map((cta, index) => isCtaLink(cta) ? /* @__PURE__ */ jsx("a", {
@@ -2609,6 +2912,386 @@ function MessageBubble({ message, optimistic = false, fetcher }) {
2609
2912
  });
2610
2913
  }
2611
2914
  //#endregion
2915
+ //#region src/core/thread/SaveDocumentDialog.tsx
2916
+ /**
2917
+ * El modal «Guardar como documento» (DEV-7664, tablero 21zzc). Interno del hilo — NO sale al
2918
+ * barrel, mismo criterio que `MessageBubble`. Controlado por `ConversationThread`: la decisión de
2919
+ * CUÁNDO se pinta vive en el padre (D-1, D-2, D-3); este componente sólo sabe guardar UN mensaje.
2920
+ *
2921
+ * Ganchos estables (no se tocan entre tareas, los usa `src/element/save-document.test.ts`):
2922
+ * `.wa-thread__save-dialog` con `role="dialog"`; radios de tipo `input[type=radio]` con `value` =
2923
+ * `code`; radios de alcance con `data-scope-kind`; envío `.wa-thread__save-submit`; error
2924
+ * `[role="alert"]`.
2925
+ *
2926
+ * 🔴 Todo texto que origina el host o el lifter (nombres de tipo, `detail`, placa, nombre,
2927
+ * `file_name`, el mensaje de error) entra como hijo de texto, que React escapa — nunca
2928
+ * `dangerouslySetInnerHTML` (T-no6-04).
2929
+ */
2930
+ /** `'image'` o `'pdf'` — lo que ya validó `canSaveAsDocument` antes de ofrecer la acción. */
2931
+ function mediaFormatOf(message) {
2932
+ return message.media_format === "image" ? "image" : "pdf";
2933
+ }
2934
+ /** El nombre del archivo o, sin él, un genérico según el formato (21zzc: «Imagen adjunta»). */
2935
+ function attachmentName(message) {
2936
+ if (typeof message.file_name === "string" && message.file_name !== "") return message.file_name;
2937
+ return mediaFormatOf(message) === "image" ? "Imagen adjunta" : "Documento PDF";
2938
+ }
2939
+ /** La hora HH:MM local (DEC-O, sin `Intl`) — mismo criterio que `formatHour` de `MessageBubble`. */
2940
+ function formatDialogHour(at) {
2941
+ const date = new Date(at);
2942
+ if (Number.isNaN(date.getTime())) return null;
2943
+ return `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
2944
+ }
2945
+ /** «Lo mandó el lifter por WhatsApp · hoy 09:09» / «· 15 de agosto de 2026 09:09» (21zzc). */
2946
+ function sentWhenLabel(at) {
2947
+ if (typeof at !== "string") return null;
2948
+ const hour = formatDialogHour(at);
2949
+ const key = dayKey(at);
2950
+ if (key === null) return hour;
2951
+ const day = key === dayKey((/* @__PURE__ */ new Date()).toISOString()) ? "hoy" : dayLabel(at);
2952
+ return hour !== null ? `${day} ${hour}` : day;
2953
+ }
2954
+ function DocumentGlyph() {
2955
+ return /* @__PURE__ */ jsxs("svg", {
2956
+ width: 20,
2957
+ height: 20,
2958
+ viewBox: "0 0 16 16",
2959
+ fill: "none",
2960
+ stroke: "currentColor",
2961
+ strokeWidth: 1.3,
2962
+ "aria-hidden": "true",
2963
+ children: [/* @__PURE__ */ jsx("path", { d: "M4 1.5h5.5L12.5 4.5V14a.5.5 0 0 1-.5.5H4a.5.5 0 0 1-.5-.5v-12a.5.5 0 0 1 .5-.5Z" }), /* @__PURE__ */ jsx("path", { d: "M9.3 1.5V4.5h3" })]
2964
+ });
2965
+ }
2966
+ function SearchGlyph() {
2967
+ return /* @__PURE__ */ jsxs("svg", {
2968
+ width: 14,
2969
+ height: 14,
2970
+ viewBox: "0 0 16 16",
2971
+ fill: "none",
2972
+ stroke: "currentColor",
2973
+ strokeWidth: 1.5,
2974
+ "aria-hidden": "true",
2975
+ children: [/* @__PURE__ */ jsx("circle", {
2976
+ cx: "7",
2977
+ cy: "7",
2978
+ r: "4.5"
2979
+ }), /* @__PURE__ */ jsx("path", { d: "M13.5 13.5 10.4 10.4" })]
2980
+ });
2981
+ }
2982
+ function VehicleGlyph() {
2983
+ return /* @__PURE__ */ jsxs("svg", {
2984
+ width: 16,
2985
+ height: 16,
2986
+ viewBox: "0 0 16 16",
2987
+ fill: "none",
2988
+ stroke: "currentColor",
2989
+ strokeWidth: 1.3,
2990
+ "aria-hidden": "true",
2991
+ children: [
2992
+ /* @__PURE__ */ jsx("path", { d: "M2 10.5V7l1.3-3.2A1 1 0 0 1 4.2 3.2h7.6a1 1 0 0 1 .9.6L14 7v3.5" }),
2993
+ /* @__PURE__ */ jsx("path", { d: "M2 10.5h12v1.8a.7.7 0 0 1-.7.7h-.6a.7.7 0 0 1-.7-.7v-.8H4v.8a.7.7 0 0 1-.7.7h-.6a.7.7 0 0 1-.7-.7v-1.8Z" }),
2994
+ /* @__PURE__ */ jsx("circle", {
2995
+ cx: "4.6",
2996
+ cy: "10.5",
2997
+ r: "1"
2998
+ }),
2999
+ /* @__PURE__ */ jsx("circle", {
3000
+ cx: "11.4",
3001
+ cy: "10.5",
3002
+ r: "1"
3003
+ })
3004
+ ]
3005
+ });
3006
+ }
3007
+ function PersonGlyph() {
3008
+ return /* @__PURE__ */ jsxs("svg", {
3009
+ width: 16,
3010
+ height: 16,
3011
+ viewBox: "0 0 16 16",
3012
+ fill: "none",
3013
+ stroke: "currentColor",
3014
+ strokeWidth: 1.3,
3015
+ "aria-hidden": "true",
3016
+ children: [/* @__PURE__ */ jsx("circle", {
3017
+ cx: "8",
3018
+ cy: "5.2",
3019
+ r: "2.7"
3020
+ }), /* @__PURE__ */ jsx("path", { d: "M2.8 13.5c.6-2.5 2.7-4 5.2-4s4.6 1.5 5.2 4" })]
3021
+ });
3022
+ }
3023
+ function InfoGlyph() {
3024
+ return /* @__PURE__ */ jsxs("svg", {
3025
+ width: 16,
3026
+ height: 16,
3027
+ viewBox: "0 0 16 16",
3028
+ fill: "none",
3029
+ stroke: "currentColor",
3030
+ strokeWidth: 1.3,
3031
+ "aria-hidden": "true",
3032
+ children: [
3033
+ /* @__PURE__ */ jsx("circle", {
3034
+ cx: "8",
3035
+ cy: "8",
3036
+ r: "6.5"
3037
+ }),
3038
+ /* @__PURE__ */ jsx("path", { d: "M8 7.3v4" }),
3039
+ /* @__PURE__ */ jsx("circle", {
3040
+ cx: "8",
3041
+ cy: "5.1",
3042
+ r: "0.25",
3043
+ fill: "currentColor",
3044
+ stroke: "none"
3045
+ })
3046
+ ]
3047
+ });
3048
+ }
3049
+ function SaveGlyph() {
3050
+ return /* @__PURE__ */ jsxs("svg", {
3051
+ width: 15,
3052
+ height: 15,
3053
+ viewBox: "0 0 16 16",
3054
+ fill: "none",
3055
+ stroke: "currentColor",
3056
+ strokeWidth: 1.6,
3057
+ "aria-hidden": "true",
3058
+ children: [/* @__PURE__ */ jsx("path", { d: "M3 2.5h8l2 2V13a.5.5 0 0 1-.5.5h-9a.5.5 0 0 1-.5-.5V3a.5.5 0 0 1 .5-.5Z" }), /* @__PURE__ */ jsx("path", { d: "M5.3 2.5V6h4.4V2.5M5.3 13v-3.5h5.4V13" })]
3059
+ });
3060
+ }
3061
+ function SaveDocumentDialog({ message, phone, input, onClose }) {
3062
+ const [type, setType] = useState(() => documentTypeOptions(input.types, "").selected);
3063
+ const [scope, setScope] = useState(null);
3064
+ const [search, setSearch] = useState("");
3065
+ const [submitting, setSubmitting] = useState(false);
3066
+ const [error, setError] = useState(null);
3067
+ const mountedRef = useRef(true);
3068
+ const containerRef = useRef(null);
3069
+ useEffect(() => {
3070
+ return () => {
3071
+ mountedRef.current = false;
3072
+ };
3073
+ }, []);
3074
+ useEffect(() => {
3075
+ containerRef.current?.focus();
3076
+ }, []);
3077
+ useEffect(() => {
3078
+ if (submitting) return;
3079
+ const handleKeyDown = (event) => {
3080
+ if (event.key !== "Escape") return;
3081
+ event.stopPropagation();
3082
+ onClose();
3083
+ };
3084
+ window.addEventListener("keydown", handleKeyDown, true);
3085
+ return () => window.removeEventListener("keydown", handleKeyDown, true);
3086
+ }, [submitting, onClose]);
3087
+ const { requested, catalog } = documentTypeOptions(input.types, search);
3088
+ const showCatalog = search.trim() !== "" || requested.length === 0;
3089
+ const { options: scopeOptions, selected: resolvedScope } = resolveScope(type, input.scopes, scope);
3090
+ const allowedScopeCount = scopeOptions.filter((option) => option.allowed).length;
3091
+ const handleTypeChange = (next) => {
3092
+ setType(next);
3093
+ };
3094
+ const handleSubmit = () => {
3095
+ if (type === null || resolvedScope === null || submitting) return;
3096
+ const request = {
3097
+ phone,
3098
+ messageId: message.id,
3099
+ mediaId: message.media_id,
3100
+ mediaFormat: mediaFormatOf(message),
3101
+ fileName: typeof message.file_name === "string" ? message.file_name : null,
3102
+ documentType: type,
3103
+ scope: resolvedScope
3104
+ };
3105
+ setSubmitting(true);
3106
+ setError(null);
3107
+ Promise.resolve().then(() => input.onSave(request)).then(() => {
3108
+ if (!mountedRef.current) return;
3109
+ onClose();
3110
+ }).catch((reason) => {
3111
+ if (!mountedRef.current) return;
3112
+ setSubmitting(false);
3113
+ setError(saveErrorMessage(reason));
3114
+ });
3115
+ };
3116
+ const handleOverlayClick = () => {
3117
+ if (submitting) return;
3118
+ onClose();
3119
+ };
3120
+ const sentWhen = sentWhenLabel(message.at);
3121
+ return /* @__PURE__ */ jsx("div", {
3122
+ className: "wa-thread__save-overlay",
3123
+ onClick: handleOverlayClick,
3124
+ children: /* @__PURE__ */ jsxs("div", {
3125
+ ref: containerRef,
3126
+ className: "wa-thread__save-dialog",
3127
+ role: "dialog",
3128
+ "aria-modal": "true",
3129
+ "aria-labelledby": "wa-thread-save-title",
3130
+ tabIndex: -1,
3131
+ onClick: (event) => event.stopPropagation(),
3132
+ children: [
3133
+ /* @__PURE__ */ jsxs("div", {
3134
+ className: "wa-thread__save-header",
3135
+ children: [/* @__PURE__ */ jsx("h2", {
3136
+ id: "wa-thread-save-title",
3137
+ className: "wa-thread__save-title",
3138
+ children: "Guardar como documento"
3139
+ }), /* @__PURE__ */ jsx("button", {
3140
+ type: "button",
3141
+ className: "wa-thread__save-close",
3142
+ onClick: onClose,
3143
+ disabled: submitting,
3144
+ "aria-label": "Cerrar",
3145
+ children: "×"
3146
+ })]
3147
+ }),
3148
+ /* @__PURE__ */ jsxs("div", {
3149
+ className: "wa-thread__save-file",
3150
+ children: [/* @__PURE__ */ jsx("span", {
3151
+ className: "wa-thread__save-file-icon",
3152
+ "aria-hidden": "true",
3153
+ children: /* @__PURE__ */ jsx(DocumentGlyph, {})
3154
+ }), /* @__PURE__ */ jsxs("span", {
3155
+ className: "wa-thread__save-file-text",
3156
+ children: [/* @__PURE__ */ jsx("span", {
3157
+ className: "wa-thread__save-file-name",
3158
+ children: attachmentName(message)
3159
+ }), sentWhen !== null && /* @__PURE__ */ jsxs("span", {
3160
+ className: "wa-thread__save-file-meta",
3161
+ children: ["Lo mandó el lifter por WhatsApp · ", sentWhen]
3162
+ })]
3163
+ })]
3164
+ }),
3165
+ /* @__PURE__ */ jsxs("fieldset", {
3166
+ className: "wa-thread__save-types",
3167
+ children: [
3168
+ /* @__PURE__ */ jsx("legend", { children: "Tipo de documento" }),
3169
+ requested.map((option) => /* @__PURE__ */ jsxs("label", {
3170
+ className: "wa-thread__save-type-option",
3171
+ "data-selected": type?.code === option.code || void 0,
3172
+ children: [
3173
+ /* @__PURE__ */ jsx("input", {
3174
+ type: "radio",
3175
+ name: "wa-save-document-type",
3176
+ value: option.code,
3177
+ checked: type?.code === option.code,
3178
+ onChange: () => handleTypeChange(option),
3179
+ disabled: submitting
3180
+ }),
3181
+ /* @__PURE__ */ jsxs("span", {
3182
+ className: "wa-thread__save-type-text",
3183
+ children: [/* @__PURE__ */ jsx("span", {
3184
+ className: "wa-thread__save-type-name",
3185
+ children: option.name
3186
+ }), typeof option.detail === "string" && option.detail !== "" && /* @__PURE__ */ jsx("span", {
3187
+ className: "wa-thread__save-type-detail",
3188
+ children: option.detail
3189
+ })]
3190
+ }),
3191
+ /* @__PURE__ */ jsx("span", {
3192
+ className: "wa-thread__save-badge",
3193
+ children: "Pedido · abierto"
3194
+ })
3195
+ ]
3196
+ }, option.code)),
3197
+ /* @__PURE__ */ jsxs("div", {
3198
+ className: "wa-thread__save-search",
3199
+ children: [/* @__PURE__ */ jsx("span", {
3200
+ "aria-hidden": "true",
3201
+ children: /* @__PURE__ */ jsx(SearchGlyph, {})
3202
+ }), /* @__PURE__ */ jsx("input", {
3203
+ type: "search",
3204
+ placeholder: "Otro tipo del catálogo…",
3205
+ value: search,
3206
+ onChange: (event) => setSearch(event.target.value),
3207
+ disabled: submitting
3208
+ })]
3209
+ }),
3210
+ showCatalog && catalog.map((option) => /* @__PURE__ */ jsxs("label", {
3211
+ className: "wa-thread__save-type-option",
3212
+ "data-selected": type?.code === option.code || void 0,
3213
+ children: [/* @__PURE__ */ jsx("input", {
3214
+ type: "radio",
3215
+ name: "wa-save-document-type",
3216
+ value: option.code,
3217
+ checked: type?.code === option.code,
3218
+ onChange: () => handleTypeChange(option),
3219
+ disabled: submitting
3220
+ }), /* @__PURE__ */ jsxs("span", {
3221
+ className: "wa-thread__save-type-text",
3222
+ children: [/* @__PURE__ */ jsx("span", {
3223
+ className: "wa-thread__save-type-name",
3224
+ children: option.name
3225
+ }), typeof option.detail === "string" && option.detail !== "" && /* @__PURE__ */ jsx("span", {
3226
+ className: "wa-thread__save-type-detail",
3227
+ children: option.detail
3228
+ })]
3229
+ })]
3230
+ }, option.code))
3231
+ ]
3232
+ }),
3233
+ /* @__PURE__ */ jsxs("fieldset", {
3234
+ className: "wa-thread__save-scopes",
3235
+ children: [
3236
+ /* @__PURE__ */ jsx("legend", { children: "De quién es" }),
3237
+ scopeOptions.map(({ scope: scopeOption, allowed }, index) => /* @__PURE__ */ jsxs("label", {
3238
+ className: "wa-thread__save-scope-option",
3239
+ "data-selected": resolvedScope === scopeOption || void 0,
3240
+ children: [
3241
+ /* @__PURE__ */ jsx("input", {
3242
+ type: "radio",
3243
+ name: "wa-save-document-scope",
3244
+ "data-scope-kind": scopeOption.kind,
3245
+ checked: resolvedScope === scopeOption,
3246
+ disabled: !allowed || submitting,
3247
+ onChange: () => setScope(scopeOption)
3248
+ }),
3249
+ /* @__PURE__ */ jsx("span", {
3250
+ "aria-hidden": "true",
3251
+ children: scopeOption.kind === "vehicle" ? /* @__PURE__ */ jsx(VehicleGlyph, {}) : /* @__PURE__ */ jsx(PersonGlyph, {})
3252
+ }),
3253
+ scopeOption.kind === "vehicle" ? `Vehículo · ${scopeOption.plate}` : `Persona · ${scopeOption.name}`
3254
+ ]
3255
+ }, index)),
3256
+ type !== null && /* @__PURE__ */ jsx("p", {
3257
+ className: "wa-thread__save-scope-explain",
3258
+ children: allowedScopeCount <= 1 ? `El tipo define el alcance: ${type.name} es ${resolvedScope?.kind === "person" ? "de la persona" : "del vehículo"}. Solo se puede cambiar en los tipos que admiten los dos.` : `${type.name} admite los dos alcances — elige de quién es este documento.`
3259
+ })
3260
+ ]
3261
+ }),
3262
+ /* @__PURE__ */ jsxs("div", {
3263
+ className: "wa-thread__save-notice",
3264
+ children: [/* @__PURE__ */ jsx("span", {
3265
+ "aria-hidden": "true",
3266
+ children: /* @__PURE__ */ jsx(InfoGlyph, {})
3267
+ }), /* @__PURE__ */ jsxs("span", { children: ["Se guarda en el expediente como carga manual, sin OCR, y queda pendiente de decisión.", type !== null && (type.requested === true ? ` Cumple la solicitud abierta de ${type.name} y queda a tu nombre.` : " Queda a tu nombre.")] })]
3268
+ }),
3269
+ error !== null && /* @__PURE__ */ jsx("p", {
3270
+ role: "alert",
3271
+ className: "wa-thread__save-error",
3272
+ children: error
3273
+ }),
3274
+ /* @__PURE__ */ jsxs("div", {
3275
+ className: "wa-thread__save-actions",
3276
+ children: [/* @__PURE__ */ jsx("button", {
3277
+ type: "button",
3278
+ className: "wa-thread__save-cancel",
3279
+ onClick: onClose,
3280
+ disabled: submitting,
3281
+ children: "Cancelar"
3282
+ }), /* @__PURE__ */ jsxs("button", {
3283
+ type: "button",
3284
+ className: "wa-thread__save-submit",
3285
+ onClick: handleSubmit,
3286
+ disabled: type === null || resolvedScope === null || submitting,
3287
+ children: [/* @__PURE__ */ jsx(SaveGlyph, {}), submitting ? "Guardando…" : "Guardar documento"]
3288
+ })]
3289
+ })
3290
+ ]
3291
+ })
3292
+ });
3293
+ }
3294
+ //#endregion
2612
3295
  //#region src/core/thread/service-state-labels.ts
2613
3296
  /**
2614
3297
  * Las etiquetas humanas de `service_state` para el HILO (DEV-5053 / P3, completada en DEV-5144).
@@ -3415,33 +4098,178 @@ const THREAD_CSS = `
3415
4098
  color: #52606d;
3416
4099
  }
3417
4100
 
3418
- /* El envío que no salió: el porqué y qué se puede hacer, junto a la caja donde se escribió. */
3419
- .wa-composer__failures {
3420
- display: flex;
3421
- flex-direction: column;
3422
- gap: 6px;
4101
+ /* DEV-8758 — «Iniciar con plantilla» (tableros 391/392): con la ventana cerrada o sin hilo, el
4102
+ composer es un formulario de plantilla. Mismo fondo y bordes que el composer de texto. */
4103
+ .wa-composer--template {
4104
+ gap: 10px;
3423
4105
  }
3424
- .wa-composer__failure {
4106
+ .wa-template {
3425
4107
  display: flex;
3426
- flex-wrap: wrap;
3427
- align-items: center;
3428
- justify-content: space-between;
3429
- gap: 8px;
3430
- padding: 8px 10px;
3431
- border: 1px solid #e5b9b6;
3432
- border-radius: 6px;
3433
- background: #fdf6f6;
4108
+ flex-direction: column;
4109
+ gap: 10px;
3434
4110
  }
3435
- .wa-composer__failure-text {
4111
+ .wa-template__notice {
3436
4112
  margin: 0;
4113
+ padding: 8px 12px;
4114
+ border: 1px solid #F5E7C8;
4115
+ border-radius: 8px;
3437
4116
  font-size: 12px;
3438
- color: #7d1f1a;
4117
+ color: #8A5A10;
4118
+ background: #FFFBF2;
3439
4119
  }
3440
- .wa-composer__failure-actions {
4120
+ .wa-template__route {
3441
4121
  display: flex;
3442
- gap: 6px;
3443
- }
3444
- .wa-composer__failure-actions button {
4122
+ flex-direction: column;
4123
+ gap: 2px;
4124
+ padding: 8px 12px;
4125
+ border-radius: 8px;
4126
+ font-size: 12px;
4127
+ color: #2D3340;
4128
+ background: #F4F5F7;
4129
+ }
4130
+ .wa-template__route-line {
4131
+ margin: 0;
4132
+ }
4133
+ .wa-template__route-key {
4134
+ font-weight: 600;
4135
+ color: #616e7c;
4136
+ }
4137
+ .wa-template__note {
4138
+ margin: 0;
4139
+ font-size: 12px;
4140
+ color: #8A91A0;
4141
+ }
4142
+ .wa-template__link {
4143
+ padding: 0;
4144
+ border: 0;
4145
+ font: inherit;
4146
+ color: #4F5AED;
4147
+ background: none;
4148
+ cursor: pointer;
4149
+ }
4150
+ .wa-template__form {
4151
+ display: flex;
4152
+ flex-direction: column;
4153
+ gap: 8px;
4154
+ }
4155
+ .wa-template__field {
4156
+ display: flex;
4157
+ flex-direction: column;
4158
+ gap: 4px;
4159
+ }
4160
+ .wa-template__label {
4161
+ font-size: 11px;
4162
+ font-weight: 600;
4163
+ color: #616e7c;
4164
+ }
4165
+ .wa-template__select,
4166
+ .wa-template__input {
4167
+ padding: 7px 10px;
4168
+ border: 1px solid #E4E7EE;
4169
+ border-radius: 8px;
4170
+ font: inherit;
4171
+ font-size: 13px;
4172
+ color: #2D3340;
4173
+ background: #F4F5F7;
4174
+ }
4175
+ .wa-template__select:focus,
4176
+ .wa-template__input:focus {
4177
+ border-color: #4F5AED;
4178
+ outline: 2px solid rgba(79, 90, 237, 0.25);
4179
+ outline-offset: 0;
4180
+ }
4181
+ /* La vista previa como burbuja de salida: es lo que va a leer la persona. */
4182
+ .wa-template__preview {
4183
+ align-self: flex-end;
4184
+ max-width: 85%;
4185
+ padding: 8px 12px;
4186
+ border-radius: 12px 12px 4px 12px;
4187
+ background: #EEF1FE;
4188
+ }
4189
+ .wa-template__preview-tag {
4190
+ display: block;
4191
+ margin-bottom: 4px;
4192
+ font-size: 10.5px;
4193
+ font-weight: 600;
4194
+ color: #4F5AED;
4195
+ }
4196
+ .wa-template__preview-body {
4197
+ margin: 0;
4198
+ font-size: 13px;
4199
+ color: #2D3340;
4200
+ white-space: pre-wrap;
4201
+ }
4202
+ .wa-template__error {
4203
+ display: flex;
4204
+ flex-wrap: wrap;
4205
+ align-items: center;
4206
+ justify-content: space-between;
4207
+ gap: 8px;
4208
+ padding: 8px 10px;
4209
+ border: 1px solid #e5b9b6;
4210
+ border-radius: 6px;
4211
+ background: #fdf6f6;
4212
+ }
4213
+ .wa-template__error-text {
4214
+ margin: 0;
4215
+ font-size: 12px;
4216
+ color: #7d1f1a;
4217
+ }
4218
+ .wa-template__retry {
4219
+ padding: 4px 12px;
4220
+ border: 1px solid #F0C9C5;
4221
+ border-radius: 999px;
4222
+ font: inherit;
4223
+ font-size: 12px;
4224
+ color: #D93025;
4225
+ background: #ffffff;
4226
+ cursor: pointer;
4227
+ }
4228
+ .wa-template__sent {
4229
+ margin: 0;
4230
+ font-size: 12px;
4231
+ color: #1E7F4F;
4232
+ }
4233
+ .wa-template__footer {
4234
+ display: flex;
4235
+ align-items: center;
4236
+ justify-content: space-between;
4237
+ gap: 8px;
4238
+ }
4239
+ .wa-template__hint {
4240
+ margin-right: auto;
4241
+ min-width: 0;
4242
+ font-size: 10.5px;
4243
+ color: #9AA1AE;
4244
+ }
4245
+
4246
+ /* El envío que no salió: el porqué y qué se puede hacer, junto a la caja donde se escribió. */
4247
+ .wa-composer__failures {
4248
+ display: flex;
4249
+ flex-direction: column;
4250
+ gap: 6px;
4251
+ }
4252
+ .wa-composer__failure {
4253
+ display: flex;
4254
+ flex-wrap: wrap;
4255
+ align-items: center;
4256
+ justify-content: space-between;
4257
+ gap: 8px;
4258
+ padding: 8px 10px;
4259
+ border: 1px solid #e5b9b6;
4260
+ border-radius: 6px;
4261
+ background: #fdf6f6;
4262
+ }
4263
+ .wa-composer__failure-text {
4264
+ margin: 0;
4265
+ font-size: 12px;
4266
+ color: #7d1f1a;
4267
+ }
4268
+ .wa-composer__failure-actions {
4269
+ display: flex;
4270
+ gap: 6px;
4271
+ }
4272
+ .wa-composer__failure-actions button {
3445
4273
  padding: 4px 10px;
3446
4274
  border: 1px solid #cbd2d9;
3447
4275
  border-radius: 4px;
@@ -3585,6 +4413,300 @@ const THREAD_CSS = `
3585
4413
  border-radius: 999px;
3586
4414
  color: #D93025;
3587
4415
  }
4416
+
4417
+ /* ─── «Guardar como documento» (DEV-7664, tableros 21zzc/21zzd) ──────────────────────────────
4418
+ Paleta reusada del archivo: índigo #4F5AED/#EEF1FE del acento y los CTAs, ámbar de la barra de
4419
+ takeover para el badge «Pedido · abierto», verde para la marca confirmada. Cero tokens nuevos. */
4420
+
4421
+ /* El botón de la burbuja: pill índigo suave, debajo del adjunto y antes de los CTAs (D-10). */
4422
+ .wa-thread__save-action {
4423
+ display: inline-flex;
4424
+ align-self: flex-start;
4425
+ align-items: center;
4426
+ gap: 6px;
4427
+ margin-top: 2px;
4428
+ padding: 5px 12px;
4429
+ border: 1px solid #C9D2F5;
4430
+ border-radius: 999px;
4431
+ font: inherit;
4432
+ font-size: 11.5px;
4433
+ font-weight: 600;
4434
+ color: #4F5AED;
4435
+ background: #EEF1FE;
4436
+ cursor: pointer;
4437
+ }
4438
+ .wa-thread__save-action:hover {
4439
+ background: #E2E7FD;
4440
+ }
4441
+
4442
+ /* La marca confirmada: pill verde, con check — reemplaza al botón (D-6). */
4443
+ .wa-thread__saved-document {
4444
+ display: inline-flex;
4445
+ align-self: flex-start;
4446
+ align-items: center;
4447
+ gap: 6px;
4448
+ margin-top: 2px;
4449
+ padding: 5px 12px;
4450
+ border: 1px solid #BFE3C9;
4451
+ border-radius: 999px;
4452
+ font-size: 11.5px;
4453
+ font-weight: 600;
4454
+ color: #1E7F43;
4455
+ background: #EAF7EE;
4456
+ }
4457
+
4458
+ /* El overlay y el modal: mismo molde que \`.wa-thread__lightbox\`, para que convivan sin pisarse
4459
+ (ninguno de los dos vive dentro de \`.wa-thread__messages\`, así que no compiten por z-index real;
4460
+ se repite el valor por claridad y porque los dos pueden coexistir en teoría — el lightbox se
4461
+ cierra solo al abrir el modal de guardado, nunca al revés). */
4462
+ .wa-thread__save-overlay {
4463
+ position: fixed;
4464
+ inset: 0;
4465
+ z-index: 1000;
4466
+ display: flex;
4467
+ align-items: center;
4468
+ justify-content: center;
4469
+ padding: 16px;
4470
+ background: rgba(31, 41, 51, 0.55);
4471
+ }
4472
+ .wa-thread__save-dialog {
4473
+ display: flex;
4474
+ width: min(560px, calc(100% - 32px));
4475
+ max-height: calc(100% - 32px);
4476
+ flex-direction: column;
4477
+ gap: 14px;
4478
+ overflow-y: auto;
4479
+ padding: 20px;
4480
+ border-radius: 16px;
4481
+ background: #ffffff;
4482
+ box-shadow: 0 20px 48px rgba(17, 24, 39, 0.28);
4483
+ }
4484
+ .wa-thread__save-dialog:focus {
4485
+ outline: none;
4486
+ }
4487
+ .wa-thread__save-header {
4488
+ display: flex;
4489
+ align-items: flex-start;
4490
+ justify-content: space-between;
4491
+ gap: 12px;
4492
+ }
4493
+ .wa-thread__save-title {
4494
+ margin: 0;
4495
+ font-size: 16px;
4496
+ font-weight: 700;
4497
+ color: #1f2933;
4498
+ }
4499
+ .wa-thread__save-close {
4500
+ flex: 0 0 auto;
4501
+ padding: 0 4px;
4502
+ border: none;
4503
+ font-size: 20px;
4504
+ line-height: 1;
4505
+ color: #8A91A0;
4506
+ background: none;
4507
+ cursor: pointer;
4508
+ }
4509
+ .wa-thread__save-close:hover {
4510
+ color: #2D3340;
4511
+ }
4512
+
4513
+ /* La tarjeta del archivo: icono + nombre + «Lo mandó el lifter por WhatsApp · …». */
4514
+ .wa-thread__save-file {
4515
+ display: flex;
4516
+ align-items: center;
4517
+ gap: 10px;
4518
+ padding: 10px 12px;
4519
+ border: 1px solid #EEF0F3;
4520
+ border-radius: 10px;
4521
+ background: #F7F6F2;
4522
+ }
4523
+ .wa-thread__save-file-icon {
4524
+ display: flex;
4525
+ flex: 0 0 auto;
4526
+ color: #6B7280;
4527
+ }
4528
+ .wa-thread__save-file-text {
4529
+ display: flex;
4530
+ min-width: 0;
4531
+ flex-direction: column;
4532
+ gap: 2px;
4533
+ }
4534
+ .wa-thread__save-file-name {
4535
+ overflow: hidden;
4536
+ font-size: 13px;
4537
+ font-weight: 600;
4538
+ color: #2D3340;
4539
+ text-overflow: ellipsis;
4540
+ white-space: nowrap;
4541
+ }
4542
+ .wa-thread__save-file-meta {
4543
+ font-size: 11.5px;
4544
+ color: #8A91A0;
4545
+ }
4546
+
4547
+ /* Los dos \`fieldset\` — tipo y alcance — comparten el mismo molde de tarjetas-radio. */
4548
+ .wa-thread__save-types,
4549
+ .wa-thread__save-scopes {
4550
+ display: flex;
4551
+ margin: 0;
4552
+ flex-direction: column;
4553
+ gap: 8px;
4554
+ padding: 0;
4555
+ border: 0;
4556
+ }
4557
+ .wa-thread__save-types legend,
4558
+ .wa-thread__save-scopes legend {
4559
+ padding: 0 0 2px;
4560
+ font-size: 11px;
4561
+ font-weight: 700;
4562
+ letter-spacing: 0.04em;
4563
+ text-transform: uppercase;
4564
+ color: #6B7280;
4565
+ }
4566
+ .wa-thread__save-type-option,
4567
+ .wa-thread__save-scope-option {
4568
+ display: flex;
4569
+ align-items: center;
4570
+ gap: 10px;
4571
+ padding: 10px 12px;
4572
+ border: 1px solid #E4E7EE;
4573
+ border-radius: 10px;
4574
+ cursor: pointer;
4575
+ }
4576
+ .wa-thread__save-type-option[data-selected='true'],
4577
+ .wa-thread__save-scope-option[data-selected='true'] {
4578
+ border-color: #4F5AED;
4579
+ background: #F4F5FF;
4580
+ }
4581
+ .wa-thread__save-type-option:has(input:disabled),
4582
+ .wa-thread__save-scope-option:has(input:disabled) {
4583
+ cursor: default;
4584
+ opacity: 0.55;
4585
+ }
4586
+ .wa-thread__save-type-text {
4587
+ display: flex;
4588
+ min-width: 0;
4589
+ flex: 1 1 auto;
4590
+ flex-direction: column;
4591
+ gap: 2px;
4592
+ }
4593
+ .wa-thread__save-type-name {
4594
+ font-size: 13px;
4595
+ font-weight: 600;
4596
+ color: #2D3340;
4597
+ }
4598
+ .wa-thread__save-type-detail {
4599
+ font-size: 11.5px;
4600
+ color: #8A91A0;
4601
+ }
4602
+ /* El badge «Pedido · abierto» (ámbar, misma paleta que la barra de takeover ajena). */
4603
+ .wa-thread__save-badge {
4604
+ flex: 0 0 auto;
4605
+ padding: 3px 9px;
4606
+ border-radius: 999px;
4607
+ font-size: 10.5px;
4608
+ font-weight: 700;
4609
+ color: #b7791f;
4610
+ background: #fff7e8;
4611
+ }
4612
+ .wa-thread__save-search {
4613
+ display: flex;
4614
+ align-items: center;
4615
+ gap: 8px;
4616
+ padding: 8px 12px;
4617
+ border: 1px solid #E4E7EE;
4618
+ border-radius: 10px;
4619
+ color: #8A91A0;
4620
+ background: #ffffff;
4621
+ }
4622
+ .wa-thread__save-search input {
4623
+ flex: 1 1 auto;
4624
+ border: none;
4625
+ font: inherit;
4626
+ font-size: 13px;
4627
+ color: #2D3340;
4628
+ background: none;
4629
+ outline: none;
4630
+ }
4631
+ .wa-thread__save-scope-explain {
4632
+ margin: 2px 0 0;
4633
+ font-size: 11.5px;
4634
+ color: #6B7280;
4635
+ }
4636
+
4637
+ /* El aviso informativo: carga manual, sin OCR, pendiente de decisión. */
4638
+ .wa-thread__save-notice {
4639
+ display: flex;
4640
+ align-items: flex-start;
4641
+ gap: 8px;
4642
+ padding: 10px 12px;
4643
+ border-radius: 10px;
4644
+ font-size: 11.5px;
4645
+ color: #4B5262;
4646
+ background: #F4F5FF;
4647
+ }
4648
+ .wa-thread__save-notice svg {
4649
+ flex: 0 0 auto;
4650
+ margin-top: 1px;
4651
+ color: #4F5AED;
4652
+ }
4653
+
4654
+ .wa-thread__save-error {
4655
+ margin: 0;
4656
+ padding: 8px 10px;
4657
+ border: 1px solid #F0C9C5;
4658
+ border-radius: 8px;
4659
+ font-size: 12px;
4660
+ color: #B3261E;
4661
+ background: #FDF6F6;
4662
+ }
4663
+
4664
+ .wa-thread__save-actions {
4665
+ display: flex;
4666
+ justify-content: flex-end;
4667
+ gap: 8px;
4668
+ }
4669
+ .wa-thread__save-cancel {
4670
+ padding: 8px 16px;
4671
+ border: 1px solid #cbd2d9;
4672
+ border-radius: 999px;
4673
+ font: inherit;
4674
+ font-size: 13px;
4675
+ color: #2D3340;
4676
+ background: #ffffff;
4677
+ cursor: pointer;
4678
+ }
4679
+ .wa-thread__save-cancel:hover:not(:disabled) {
4680
+ background: #f5f7fa;
4681
+ }
4682
+ .wa-thread__save-cancel:disabled {
4683
+ color: #9aa5b1;
4684
+ cursor: default;
4685
+ }
4686
+ .wa-thread__save-submit {
4687
+ display: inline-flex;
4688
+ align-items: center;
4689
+ gap: 6px;
4690
+ padding: 8px 18px;
4691
+ border: 1px solid #4F5AED;
4692
+ border-radius: 999px;
4693
+ font: inherit;
4694
+ font-size: 13px;
4695
+ font-weight: 600;
4696
+ color: #ffffff;
4697
+ background: #4F5AED;
4698
+ cursor: pointer;
4699
+ }
4700
+ .wa-thread__save-submit:hover:not(:disabled) {
4701
+ border-color: #3F49D6;
4702
+ background: #3F49D6;
4703
+ }
4704
+ .wa-thread__save-submit:disabled {
4705
+ border-color: #cbd2d9;
4706
+ color: #9aa5b1;
4707
+ background: #f5f7fa;
4708
+ cursor: default;
4709
+ }
3588
4710
  `;
3589
4711
  //#endregion
3590
4712
  //#region src/core/thread/useComposer.ts
@@ -4023,6 +5145,296 @@ function useSuggestion({ fetcher, phone, messages, outgoing = [], onPrefill }) {
4023
5145
  };
4024
5146
  }
4025
5147
  //#endregion
5148
+ //#region src/core/thread/TemplateStartPanel.tsx
5149
+ /**
5150
+ * «Iniciar con plantilla» (DEV-8758) — el composer cuando WhatsApp sólo deja escribir con una
5151
+ * plantilla aprobada: ventana de 24 h cerrada (tablero 391) o sin hilo (tablero 392).
5152
+ *
5153
+ * Presentacional: qué modo se pinta lo decide `templateOffer` y la red vive en `useTemplateStart`.
5154
+ * Interno del hilo — NO sale al barrel (mismo criterio que `Composer`).
5155
+ *
5156
+ * 🔴 Todo lo que viene del store (`label`, `body_text`) y el nombre del contacto entran como hijos
5157
+ * de texto, que React escapa. Nada de `dangerouslySetInnerHTML`.
5158
+ */
5159
+ /** El primer nombre para prellenar `{{1}}`: «Nelson Chaves» ⇒ «Nelson». */
5160
+ function firstName$1(name) {
5161
+ return (typeof name === "string" ? name.trim().split(/\s+/)[0] : "") ?? "";
5162
+ }
5163
+ function TemplateStartPanel({ mode, start, noThread, phone, contactName, senderLabel }) {
5164
+ const selectId = useId();
5165
+ const items = start.response?.items ?? [];
5166
+ const [selected, setSelected] = useState(0);
5167
+ /** Lo que tipeó el operador, por plantilla: cambiar de plantilla no mezcla parámetros. */
5168
+ const [typed, setTyped] = useState({});
5169
+ if (mode === "none") return null;
5170
+ const template = items[Math.min(selected, Math.max(items.length - 1, 0))] ?? null;
5171
+ const templateKey = template !== null ? `${template.name}#${template.language}` : "";
5172
+ const params = template === null ? [] : typed[templateKey] ?? Array.from({ length: template.body_param_count }, (_, index) => index === 0 ? firstName$1(contactName) : "");
5173
+ const sending = start.sendState === "sending";
5174
+ const canSend = mode === "form" && template !== null && !sending && templateParamsValid(params, template.body_param_count);
5175
+ const preview = template !== null ? renderTemplatePreview(template.body_text, params) : null;
5176
+ const setParam = (index, value) => {
5177
+ const next = [...params];
5178
+ next[index] = value;
5179
+ setTyped({
5180
+ ...typed,
5181
+ [templateKey]: next
5182
+ });
5183
+ };
5184
+ const submit = () => {
5185
+ if (!canSend || template === null) return;
5186
+ start.send(template.name, template.language, params);
5187
+ };
5188
+ return /* @__PURE__ */ jsxs("div", {
5189
+ className: "wa-template",
5190
+ "data-mode": mode,
5191
+ children: [
5192
+ noThread ? /* @__PURE__ */ jsxs("div", {
5193
+ className: "wa-template__route",
5194
+ children: [/* @__PURE__ */ jsxs("p", {
5195
+ className: "wa-template__route-line",
5196
+ children: [
5197
+ /* @__PURE__ */ jsx("span", {
5198
+ className: "wa-template__route-key",
5199
+ children: "Para:"
5200
+ }),
5201
+ " ",
5202
+ phone,
5203
+ contactName !== null && ` · ${contactName}`
5204
+ ]
5205
+ }), senderLabel !== null && /* @__PURE__ */ jsxs("p", {
5206
+ className: "wa-template__route-line",
5207
+ children: [
5208
+ /* @__PURE__ */ jsx("span", {
5209
+ className: "wa-template__route-key",
5210
+ children: "Desde:"
5211
+ }),
5212
+ " ",
5213
+ senderLabel
5214
+ ]
5215
+ })]
5216
+ }) : /* @__PURE__ */ jsx("p", {
5217
+ className: "wa-template__notice",
5218
+ role: "status",
5219
+ children: "La ventana de 24 h está cerrada: solo se puede escribir con una plantilla aprobada. Al enviarla, el bot se pausa."
5220
+ }),
5221
+ mode === "loading" && /* @__PURE__ */ jsx("p", {
5222
+ className: "wa-template__note",
5223
+ children: "Cargando plantillas…"
5224
+ }),
5225
+ mode === "unavailable" && /* @__PURE__ */ jsxs("div", {
5226
+ className: "wa-template__note",
5227
+ role: "alert",
5228
+ children: [
5229
+ "No se pudieron cargar las plantillas.",
5230
+ " ",
5231
+ /* @__PURE__ */ jsx("button", {
5232
+ type: "button",
5233
+ className: "wa-template__link",
5234
+ onClick: start.reloadTemplates,
5235
+ children: "Reintentar"
5236
+ })
5237
+ ]
5238
+ }),
5239
+ mode === "read_only" && /* @__PURE__ */ jsx("p", {
5240
+ className: "wa-template__note",
5241
+ children: "Tu rol puede ver conversaciones, pero no iniciarlas."
5242
+ }),
5243
+ mode === "no_templates" && /* @__PURE__ */ jsx("p", {
5244
+ className: "wa-template__note",
5245
+ children: "No hay plantillas habilitadas para este número."
5246
+ }),
5247
+ mode === "form" && template !== null && /* @__PURE__ */ jsxs("form", {
5248
+ className: "wa-template__form",
5249
+ onSubmit: (event) => {
5250
+ event.preventDefault();
5251
+ submit();
5252
+ },
5253
+ children: [
5254
+ /* @__PURE__ */ jsxs("label", {
5255
+ className: "wa-template__field",
5256
+ htmlFor: selectId,
5257
+ children: [/* @__PURE__ */ jsx("span", {
5258
+ className: "wa-template__label",
5259
+ children: "Plantilla"
5260
+ }), /* @__PURE__ */ jsx("select", {
5261
+ id: selectId,
5262
+ className: "wa-template__select",
5263
+ value: selected,
5264
+ disabled: sending,
5265
+ onChange: (event) => setSelected(Number(event.target.value)),
5266
+ children: items.map((item, index) => /* @__PURE__ */ jsx("option", {
5267
+ value: index,
5268
+ children: item.label ?? item.name
5269
+ }, `${item.name}#${item.language}`))
5270
+ })]
5271
+ }),
5272
+ params.map((value, index) => /* @__PURE__ */ jsxs("label", {
5273
+ className: "wa-template__field",
5274
+ children: [/* @__PURE__ */ jsxs("span", {
5275
+ className: "wa-template__label",
5276
+ children: [
5277
+ index === 0 ? "Nombre del lifter" : "Parámetro",
5278
+ " · ",
5279
+ `{{${index + 1}}}`
5280
+ ]
5281
+ }), /* @__PURE__ */ jsx("input", {
5282
+ className: "wa-template__input",
5283
+ value,
5284
+ maxLength: 1024,
5285
+ disabled: sending,
5286
+ onChange: (event) => setParam(index, event.target.value)
5287
+ })]
5288
+ }, index)),
5289
+ preview !== null && /* @__PURE__ */ jsxs("div", {
5290
+ className: "wa-template__preview",
5291
+ children: [/* @__PURE__ */ jsxs("span", {
5292
+ className: "wa-template__preview-tag",
5293
+ children: ["Plantilla · ", template.name]
5294
+ }), /* @__PURE__ */ jsx("p", {
5295
+ className: "wa-template__preview-body",
5296
+ children: preview
5297
+ })]
5298
+ }),
5299
+ start.sendState === "error" && start.failure !== null && /* @__PURE__ */ jsxs("div", {
5300
+ className: "wa-template__error",
5301
+ role: "alert",
5302
+ children: [/* @__PURE__ */ jsx("p", {
5303
+ className: "wa-template__error-text",
5304
+ children: sendFailureCopy(start.failure)
5305
+ }), start.failure.retryable && /* @__PURE__ */ jsx("button", {
5306
+ type: "button",
5307
+ className: "wa-template__retry",
5308
+ onClick: submit,
5309
+ children: "Reintentar"
5310
+ })]
5311
+ }),
5312
+ start.sendState === "sent" && /* @__PURE__ */ jsx("p", {
5313
+ className: "wa-template__sent",
5314
+ role: "status",
5315
+ children: "Plantilla enviada. El bot quedó en pausa."
5316
+ }),
5317
+ /* @__PURE__ */ jsxs("div", {
5318
+ className: "wa-template__footer",
5319
+ children: [/* @__PURE__ */ jsx("span", {
5320
+ className: "wa-template__hint",
5321
+ children: "Se envía a tu nombre · pausa el bot"
5322
+ }), /* @__PURE__ */ jsx("button", {
5323
+ type: "submit",
5324
+ className: "wa-composer__send",
5325
+ disabled: !canSend,
5326
+ children: sending ? "Enviando…" : "Enviar plantilla"
5327
+ })]
5328
+ })
5329
+ ]
5330
+ })
5331
+ ]
5332
+ });
5333
+ }
5334
+ //#endregion
5335
+ //#region src/core/thread/useTemplateStart.ts
5336
+ /**
5337
+ * El estado de «Iniciar con plantilla» (DEV-8758): la lista de plantillas del número y el envío.
5338
+ *
5339
+ * Mismo molde que `useThread`/`useComposer` (DEC-G): lo cargado se guarda JUNTO con de qué
5340
+ * consulta vino (`fetcher` + `phone`), y "estoy pidiendo otra cosa" se DERIVA en el render — nada
5341
+ * de `setState` síncrono dentro de un efecto.
5342
+ *
5343
+ * La lista se pide sólo con `active` (ventana cerrada con permiso de escritura, o sin hilo): con la
5344
+ * ventana abierta no hay por qué molestar al store.
5345
+ *
5346
+ * 🔴 Sin `console.*`: los parámetros llevan el nombre del lifter y el teléfono es dato personal.
5347
+ */
5348
+ function useTemplateStart({ fetcher, phone, active, onStarted }) {
5349
+ const [attempt, setAttempt] = useState(0);
5350
+ const [loaded, setLoaded] = useState(null);
5351
+ const [outcome, setOutcome] = useState(null);
5352
+ const onStartedRef = useRef(onStarted);
5353
+ useEffect(() => {
5354
+ onStartedRef.current = onStarted;
5355
+ }, [onStarted]);
5356
+ useEffect(() => {
5357
+ if (!active) return;
5358
+ const controller = new AbortController();
5359
+ loadTemplates(fetcher, { signal: controller.signal }).then((response) => {
5360
+ if (controller.signal.aborted) return;
5361
+ setLoaded({
5362
+ fetcher,
5363
+ phone,
5364
+ attempt,
5365
+ response,
5366
+ failed: false
5367
+ });
5368
+ }, () => {
5369
+ if (controller.signal.aborted) return;
5370
+ setLoaded({
5371
+ fetcher,
5372
+ phone,
5373
+ attempt,
5374
+ response: null,
5375
+ failed: true
5376
+ });
5377
+ });
5378
+ return () => controller.abort();
5379
+ }, [
5380
+ active,
5381
+ fetcher,
5382
+ phone,
5383
+ attempt
5384
+ ]);
5385
+ const current = loaded !== null && loaded.fetcher === fetcher && loaded.phone === phone && loaded.attempt === attempt ? loaded : null;
5386
+ let templates;
5387
+ if (!active) templates = { status: "idle" };
5388
+ else if (current === null) templates = { status: "loading" };
5389
+ else if (current.failed || current.response === null) templates = { status: "error" };
5390
+ else templates = {
5391
+ status: "ready",
5392
+ canStart: current.response.can_start,
5393
+ itemCount: current.response.items.length
5394
+ };
5395
+ const currentOutcome = outcome !== null && outcome.fetcher === fetcher && outcome.phone === phone ? outcome : null;
5396
+ const send = useCallback((templateName, language, bodyParams) => {
5397
+ const clientMessageId = newClientMessageId();
5398
+ setOutcome({
5399
+ fetcher,
5400
+ phone,
5401
+ state: "sending",
5402
+ failure: null
5403
+ });
5404
+ startConversation(fetcher, {
5405
+ phone,
5406
+ templateName,
5407
+ language,
5408
+ bodyParams: bodyParams.map((value) => value.trim()),
5409
+ clientMessageId
5410
+ }).then(() => {
5411
+ setOutcome({
5412
+ fetcher,
5413
+ phone,
5414
+ state: "sent",
5415
+ failure: null
5416
+ });
5417
+ onStartedRef.current?.();
5418
+ }, (cause) => {
5419
+ setOutcome({
5420
+ fetcher,
5421
+ phone,
5422
+ state: "error",
5423
+ failure: readSendError(cause)
5424
+ });
5425
+ });
5426
+ }, [fetcher, phone]);
5427
+ const reloadTemplates = useCallback(() => setAttempt((value) => value + 1), []);
5428
+ return {
5429
+ templates,
5430
+ response: templates.status === "ready" && current !== null ? current.response : null,
5431
+ sendState: currentOutcome?.state ?? "idle",
5432
+ failure: currentOutcome?.failure ?? null,
5433
+ send,
5434
+ reloadTemplates
5435
+ };
5436
+ }
5437
+ //#endregion
4026
5438
  //#region src/core/thread/useThread.ts
4027
5439
  /**
4028
5440
  * El estado del hilo de conversación: pide el hilo por el `fetcher` del host y sostiene los estados
@@ -4551,7 +5963,7 @@ function firstName(takenBy) {
4551
5963
  const first = typeof takenBy === "string" ? takenBy.trim().split(/\s+/)[0] : "";
4552
5964
  return first !== void 0 && first !== "" ? first : "Otra persona";
4553
5965
  }
4554
- function ConversationThread({ fetcher, phone, displayName, refreshIntervalMs, className }) {
5966
+ function ConversationThread({ fetcher, phone, displayName, refreshIntervalMs, saveDocument, senderLabel = null, className }) {
4555
5967
  const { messages: serverMessages, status, error, windowState, canReply, takenBy, takenUntil, takenByMe, takenAt, takenByRole, hasOlder, loadOlder, retry, refresh } = useThread({
4556
5968
  fetcher,
4557
5969
  phone,
@@ -4629,6 +6041,14 @@ function ConversationThread({ fetcher, phone, displayName, refreshIntervalMs, cl
4629
6041
  */
4630
6042
  const visible = messages.filter((message) => !isSuggestion(message) || message === suggestion.suggestion);
4631
6043
  /**
6044
+ * El mensaje que se está guardando (DEV-7664): estado LOCAL de este hilo, igual que
6045
+ * `writeAnyway` — guarda DE QUÉ conversación vino (DEC-G). El modal se pinta sólo si
6046
+ * `saveDocument` existe Y `saveTarget.phone === phone`: un cambio de conversación lo cierra SIN
6047
+ * efecto, derivado en el render.
6048
+ */
6049
+ const [saveTarget, setSaveTarget] = useState(null);
6050
+ const showSaveDialog = saveDocument !== void 0 && saveTarget !== null && saveTarget.phone === phone;
6051
+ /**
4632
6052
  * «Escribir igual» (DEV-6309): el operador eligió escribir encima de la toma de otra persona.
4633
6053
  *
4634
6054
  * Es estado LOCAL de este hilo y guarda **de qué consulta vino** (DEC-G, el patrón de
@@ -4681,6 +6101,33 @@ function ConversationThread({ fetcher, phone, displayName, refreshIntervalMs, cl
4681
6101
  * se ofrece; el bloqueo por ventana sigue mandando.
4682
6102
  */
4683
6103
  const hasComposer = canReply && composer.windowState !== "closed";
6104
+ /**
6105
+ * DEV-8758 — «Iniciar con plantilla». Sin hilo (el 404 genérico del store) o con la ventana
6106
+ * cerrada y permiso de escritura, WhatsApp sólo deja escribir con una plantilla. Tras el envío el
6107
+ * hilo se vuelve a leer: sin hilo, entero (`retry`, ahora sí existe); con hilo, el latido
6108
+ * (`refresh`), que trae la burbuja y la barra «Bot en pausa».
6109
+ */
6110
+ const noThread = status === "error" && serverMessages.length === 0 && isNoThreadError(error);
6111
+ const templateStart = useTemplateStart({
6112
+ fetcher,
6113
+ phone,
6114
+ active: noThread || canReply && composer.windowState === "closed",
6115
+ onStarted: noThread ? retry : refresh
6116
+ });
6117
+ const offer = templateOffer({
6118
+ noThread,
6119
+ windowState: composer.windowState,
6120
+ canReply,
6121
+ templates: templateStart.templates
6122
+ });
6123
+ const templatePanel = offer === "none" ? null : /* @__PURE__ */ jsx(TemplateStartPanel, {
6124
+ mode: offer,
6125
+ start: templateStart,
6126
+ noThread,
6127
+ phone,
6128
+ contactName: typeof displayName === "string" && displayName.trim() !== "" ? displayName : null,
6129
+ senderLabel
6130
+ });
4684
6131
  const messagesRef = useRef(null);
4685
6132
  /** De qué consulta ya se hizo el scroll inicial: una vez por hilo, no en cada página. */
4686
6133
  const scrolledForRef = useRef(null);
@@ -4739,7 +6186,7 @@ function ConversationThread({ fetcher, phone, displayName, refreshIntervalMs, cl
4739
6186
  className: "wa-thread__note",
4740
6187
  children: "Cargando conversación…"
4741
6188
  }),
4742
- error !== null && /* @__PURE__ */ jsxs("div", {
6189
+ error !== null && !noThread && /* @__PURE__ */ jsxs("div", {
4743
6190
  className: "wa-thread__error",
4744
6191
  role: "alert",
4745
6192
  children: [/* @__PURE__ */ jsxs("p", { children: ["No se pudo cargar la conversación: ", error.message] }), /* @__PURE__ */ jsx("button", {
@@ -4754,65 +6201,87 @@ function ConversationThread({ fetcher, phone, displayName, refreshIntervalMs, cl
4754
6201
  }),
4755
6202
  /* @__PURE__ */ jsxs("div", {
4756
6203
  className: "wa-thread__header",
4757
- children: [/* @__PURE__ */ jsxs("div", {
4758
- className: "wa-thread__identity",
4759
- children: [/* @__PURE__ */ jsx("span", {
4760
- className: "wa-thread__avatar",
4761
- "aria-hidden": "true",
4762
- children: initials(name, phone)
4763
- }), /* @__PURE__ */ jsxs("span", {
4764
- className: "wa-thread__who",
6204
+ children: [
6205
+ /* @__PURE__ */ jsxs("div", {
6206
+ className: "wa-thread__identity",
4765
6207
  children: [/* @__PURE__ */ jsx("span", {
4766
- className: "wa-thread__name",
4767
- children: name ?? phone
4768
- }), name !== null && /* @__PURE__ */ jsx("span", {
4769
- className: "wa-thread__phone",
4770
- children: phone
6208
+ className: "wa-thread__avatar",
6209
+ "aria-hidden": "true",
6210
+ children: initials(name, phone)
6211
+ }), /* @__PURE__ */ jsxs("span", {
6212
+ className: "wa-thread__who",
6213
+ children: [/* @__PURE__ */ jsx("span", {
6214
+ className: "wa-thread__name",
6215
+ children: name ?? phone
6216
+ }), name !== null && /* @__PURE__ */ jsx("span", {
6217
+ className: "wa-thread__phone",
6218
+ children: phone
6219
+ })]
4771
6220
  })]
4772
- })]
4773
- }), currentStep !== null && /* @__PURE__ */ jsx("div", {
4774
- className: "wa-thread__chips",
4775
- children: /* @__PURE__ */ jsxs("span", {
4776
- className: "wa-thread__step",
4777
- title: currentStep,
4778
- children: ["Paso: ", serviceStateLabel(currentStep)]
6221
+ }),
6222
+ noThread && /* @__PURE__ */ jsx("div", {
6223
+ className: "wa-thread__chips",
6224
+ children: /* @__PURE__ */ jsx("span", {
6225
+ className: "wa-thread__step",
6226
+ children: "Sin conversación"
6227
+ })
6228
+ }),
6229
+ currentStep !== null && /* @__PURE__ */ jsx("div", {
6230
+ className: "wa-thread__chips",
6231
+ children: /* @__PURE__ */ jsxs("span", {
6232
+ className: "wa-thread__step",
6233
+ title: currentStep,
6234
+ children: ["Paso: ", serviceStateLabel(currentStep)]
6235
+ })
4779
6236
  })
4780
- })]
6237
+ ]
4781
6238
  }),
4782
6239
  /* @__PURE__ */ jsxs("div", {
4783
6240
  className: "wa-thread__messages",
4784
6241
  ref: messagesRef,
4785
- children: [hasOlder && /* @__PURE__ */ jsx("button", {
4786
- ref: sentinel,
4787
- type: "button",
4788
- className: "wa-thread__older",
4789
- onClick: handleLoadOlder,
4790
- disabled: status === "loading-older",
4791
- children: status === "loading-older" ? "Cargando…" : "Cargar mensajes anteriores"
4792
- }), groups.map((group, groupIndex) => /* @__PURE__ */ jsxs("div", {
4793
- className: "wa-thread__group",
4794
- children: [group.label !== null && /* @__PURE__ */ jsx("div", {
4795
- className: "wa-thread__day",
4796
- children: group.label
4797
- }), group.items.map(({ message, position }) => /* @__PURE__ */ jsxs(Fragment, { children: [showServiceState[position] && typeof message.service_state === "string" && message.service_state !== "" && /* @__PURE__ */ jsxs("div", {
4798
- className: "wa-thread__flow-pill",
4799
- children: ["El flujo pasó a ", serviceStateLabel(message.service_state)]
4800
- }), isSuggestion(message) ? /* @__PURE__ */ jsx(SuggestionBubble, {
4801
- message,
4802
- canDiscard: canReply,
4803
- state: suggestion.state,
4804
- error: suggestion.error,
4805
- onDiscard: suggestion.discard,
4806
- canUse: canReply && composer.windowState !== "closed",
4807
- armed: suggestion.armed,
4808
- onUse: suggestion.use,
4809
- onDisarm: suggestion.disarm
4810
- }) : /* @__PURE__ */ jsx(MessageBubble, {
4811
- message,
4812
- optimistic: optimistic.has(message),
4813
- fetcher
4814
- })] }, message.id ?? `sin-wamid-${position}`))]
4815
- }, group.key ?? `sin-dia-${groupIndex}`))]
6242
+ children: [
6243
+ noThread && /* @__PURE__ */ jsx("p", {
6244
+ className: "wa-thread__note",
6245
+ children: "Todavía no hay conversación con este número."
6246
+ }),
6247
+ hasOlder && /* @__PURE__ */ jsx("button", {
6248
+ ref: sentinel,
6249
+ type: "button",
6250
+ className: "wa-thread__older",
6251
+ onClick: handleLoadOlder,
6252
+ disabled: status === "loading-older",
6253
+ children: status === "loading-older" ? "Cargando…" : "Cargar mensajes anteriores"
6254
+ }),
6255
+ groups.map((group, groupIndex) => /* @__PURE__ */ jsxs("div", {
6256
+ className: "wa-thread__group",
6257
+ children: [group.label !== null && /* @__PURE__ */ jsx("div", {
6258
+ className: "wa-thread__day",
6259
+ children: group.label
6260
+ }), group.items.map(({ message, position }) => /* @__PURE__ */ jsxs(Fragment, { children: [showServiceState[position] && typeof message.service_state === "string" && message.service_state !== "" && /* @__PURE__ */ jsxs("div", {
6261
+ className: "wa-thread__flow-pill",
6262
+ children: ["El flujo pasó a ", serviceStateLabel(message.service_state)]
6263
+ }), isSuggestion(message) ? /* @__PURE__ */ jsx(SuggestionBubble, {
6264
+ message,
6265
+ canDiscard: canReply,
6266
+ state: suggestion.state,
6267
+ error: suggestion.error,
6268
+ onDiscard: suggestion.discard,
6269
+ canUse: canReply && composer.windowState !== "closed",
6270
+ armed: suggestion.armed,
6271
+ onUse: suggestion.use,
6272
+ onDisarm: suggestion.disarm
6273
+ }) : /* @__PURE__ */ jsx(MessageBubble, {
6274
+ message,
6275
+ optimistic: optimistic.has(message),
6276
+ fetcher,
6277
+ savedDocument: savedDocumentMark(message, saveDocument),
6278
+ onSaveAsDocument: canSaveAsDocument(message, saveDocument) ? () => setSaveTarget({
6279
+ message,
6280
+ phone
6281
+ }) : void 0
6282
+ })] }, message.id ?? `sin-wamid-${position}`))]
6283
+ }, group.key ?? `sin-dia-${groupIndex}`))
6284
+ ]
4816
6285
  }),
4817
6286
  /* @__PURE__ */ jsx(TakeoverBar, {
4818
6287
  takenBy,
@@ -4832,7 +6301,18 @@ function ConversationThread({ fetcher, phone, displayName, refreshIntervalMs, cl
4832
6301
  prefill,
4833
6302
  locked: foreignLive && !unlocked,
4834
6303
  takeoverNotice: foreignLive && unlocked ? `${firstName(takenBy)} está atendiendo · el lifter verá a dos personas` : null,
4835
- focusRequest: unlocked && writeAnyway !== null ? writeAnyway.focus : null
6304
+ focusRequest: unlocked && writeAnyway !== null ? writeAnyway.focus : null,
6305
+ templateStart: !noThread && offer === "form" ? templatePanel : null
6306
+ }),
6307
+ noThread && templatePanel !== null && /* @__PURE__ */ jsx("div", {
6308
+ className: "wa-composer wa-composer--template",
6309
+ children: templatePanel
6310
+ }),
6311
+ showSaveDialog && saveDocument !== void 0 && saveTarget !== null && /* @__PURE__ */ jsx(SaveDocumentDialog, {
6312
+ message: saveTarget.message,
6313
+ phone,
6314
+ input: saveDocument,
6315
+ onClose: () => setSaveTarget(null)
4836
6316
  })
4837
6317
  ]
4838
6318
  });
@@ -4921,7 +6401,7 @@ const SHELL_CSS = `
4921
6401
  color: #8A91A0;
4922
6402
  }
4923
6403
  `;
4924
- function WaConversations({ fetcher, initialPhone, pinned = false, refreshIntervalMs, className }) {
6404
+ function WaConversations({ fetcher, initialPhone, pinned = false, refreshIntervalMs, saveDocument, contactName, senderLabel, className }) {
4925
6405
  /**
4926
6406
  * El layout lo decide el ancho de ESTE contenedor, no el del viewport: el visor va embebido
4927
6407
  * (en lms-web-app vive dentro del layout del LMS, no a pantalla completa).
@@ -4942,7 +6422,7 @@ function WaConversations({ fetcher, initialPhone, pinned = false, refreshInterva
4942
6422
  * `initialPhone` siembra SÓLO el teléfono: sin summary no hay nombre que sembrar y no se
4943
6423
  * inventa uno. El header cae al teléfono, como la fila de la lista.
4944
6424
  */
4945
- const [selectedName, setSelectedName] = useState(null);
6425
+ const [selectedName, setSelectedName] = useState(initialPhone !== void 0 && typeof contactName === "string" && contactName.trim() !== "" ? contactName : null);
4946
6426
  const rootClass = className ? `wa-conversations ${className}` : "wa-conversations";
4947
6427
  if (fetcher === void 0) return /* @__PURE__ */ jsx("div", {
4948
6428
  className: rootClass,
@@ -4978,7 +6458,9 @@ function WaConversations({ fetcher, initialPhone, pinned = false, refreshInterva
4978
6458
  fetcher,
4979
6459
  phone: selectedPhone,
4980
6460
  displayName: selectedName,
4981
- refreshIntervalMs
6461
+ refreshIntervalMs,
6462
+ saveDocument: anchored ? saveDocument : void 0,
6463
+ senderLabel: senderLabel ?? null
4982
6464
  })]
4983
6465
  }) : layout === "wide" && /* @__PURE__ */ jsx("p", {
4984
6466
  className: "wa-conversations__empty",
@@ -4996,5 +6478,16 @@ function WaConversations({ fetcher, initialPhone, pinned = false, refreshInterva
4996
6478
  * comparten: un tag hardcodeado en dos lugares es un tag que se desincroniza.
4997
6479
  */
4998
6480
  const WA_CONVERSATIONS_TAG = "wa-conversations";
6481
+ /**
6482
+ * «Guardar como documento» (DEV-7664): el contrato host↔visor para que la analista guarde en el
6483
+ * expediente la imagen o el PDF que mandó el lifter, sin que el visor llegue a conocer al
6484
+ * backoffice. Esto ES la API pública de `./react` (el tipo `SaveDocumentConfig`, vía la prop
6485
+ * `saveDocument` de `WaConversations`) y la del `CustomEvent` que despacha `./element`.
6486
+ *
6487
+ * Las funciones puras (`canSaveAsDocument`, `documentTypeOptions`, `resolveScope`,
6488
+ * `savedDocumentMark`, `savedMarkLabel`, `saveErrorMessage`) NO salen al barrel: son detalle de
6489
+ * `SaveDocumentDialog`/`MessageBubble`, y toda superficie pública se paga después.
6490
+ */
6491
+ const SAVE_DOCUMENT_EVENT = "wa-conversations:save-document";
4999
6492
  //#endregion
5000
- export { ConversationList, ConversationThread, DEFAULT_REFRESH_INTERVAL_MS, NARROW_MAX_WIDTH, REPLY_TEXT_MAX_LENGTH, SUGGESTION_STATUS, WA_CONVERSATIONS_TAG, WaConversations, WaFetchError, dedupeByWamid, discardSuggestion, isCtaLink, isSuggestion, loadConversations, loadThread, mergeThread, mergeThreadPage, newClientMessageId, normalizeReplyMessage, normalizeWindowState, readSendError, releaseConversation, sendFailureCopy, sendReply, threadCtas, useComposer, useContainerLayout, useConversations, useSuggestion, useThread };
6493
+ export { ConversationList, ConversationThread, DEFAULT_REFRESH_INTERVAL_MS, NARROW_MAX_WIDTH, REPLY_TEXT_MAX_LENGTH, SAVE_DOCUMENT_EVENT, SUGGESTION_STATUS, WA_CONVERSATIONS_TAG, WaConversations, WaFetchError, dedupeByWamid, discardSuggestion, isCtaLink, isNoThreadError, isSuggestion, loadConversations, loadTemplates, loadThread, mergeThread, mergeThreadPage, newClientMessageId, normalizeReplyMessage, normalizeStartResponse, normalizeTemplates, normalizeWindowState, readSendError, releaseConversation, renderTemplatePreview, sendFailureCopy, sendReply, startConversation, templateOffer, templateParamsValid, threadCtas, useComposer, useContainerLayout, useConversations, useSuggestion, useThread };