@fayz-ai/plugin-conversations 0.37.0 → 0.39.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.
@@ -2,8 +2,8 @@ import { ConversationsContextProvider, useConversationsStore, assinarChegada, us
2
2
  import { providersApi } from './chunk-HMWUU5O7.js';
3
3
  import * as React7 from 'react';
4
4
  import React7__default from 'react';
5
- import { SquarePen, MessageSquare, LifeBuoy, Globe, Mail, Instagram, Phone, Search, Inbox, User, Archive, CheckCheck, ChevronLeft, MoreHorizontal, MailWarning, ArchiveRestore, X, Building2, MoreVertical, Loader2, Forward, AlertTriangle, Check, Clock, ExternalLink, Reply, FileText, Trash2, Paperclip, Square, Mic, Send, Snowflake, Sun, Flame, Ban, BarChart3, MapPin, UserRound, Copy, Download } from 'lucide-react';
6
- import { PageHeaderActions, cn, Button, Modal, ModalContent, ModalHeader, ModalTitle, ModalBody, Textarea, ModalFooter, Input, FilterChip, Skeleton, Dropdown, DropdownTrigger, DropdownContent, DropdownItem, toast } from '@fayz-ai/ui';
5
+ import { SquarePen, MessageSquare, LifeBuoy, Globe, Mail, Instagram, Phone, Search, Inbox, User, Archive, CheckCheck, ChevronLeft, MoreHorizontal, MailWarning, ArchiveRestore, X, Building2, Tag, Ban, ThumbsDown, PhoneMissed, MessageSquareOff, PhoneOff, MoreVertical, Loader2, Forward, AlertTriangle, Check, Clock, ExternalLink, Reply, FileText, Trash2, Paperclip, Square, Mic, Send, Snowflake, Sun, Flame, BarChart3, MapPin, UserRound, Copy, Download } from 'lucide-react';
6
+ import { PageHeaderActions, cn, Button, Modal, ModalContent, ModalHeader, ModalTitle, ModalBody, Textarea, ModalFooter, Input, FilterChip, Skeleton, Dropdown, DropdownTrigger, DropdownContent, DropdownItem, toast, DropdownSub, DropdownSubTrigger, DropdownSubContent, ModalDescription } from '@fayz-ai/ui';
7
7
  import { useRightRailStore, PageActions, useLimitGuard, ContactPicker, invalidateLimit, useConnectors } from '@fayz-ai/admin';
8
8
  import { currentAppPath, appHref, onAppPathChange, replaceApp, useTranslation, useActiveTenantId, errorMessage, getSupabaseClientOptional, getActiveTenantId } from '@fayz-ai/core';
9
9
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
@@ -935,6 +935,213 @@ function Composer({ canType, placeholder, sending, onSendText, onSendMedia, clea
935
935
  ] })
936
936
  ] });
937
937
  }
938
+
939
+ // src/lib/contact-disposition.ts
940
+ var DISPOSITION_ACTIONS = [
941
+ "wrong_number",
942
+ "no_whatsapp",
943
+ "no_answer",
944
+ "not_interested",
945
+ "stop_campaigns"
946
+ ];
947
+ var DISPOSITION_PLAN = {
948
+ wrong_number: { phoneStatus: "wrong_number", stopReason: "wrong_number" },
949
+ no_whatsapp: { phoneStatus: "no_whatsapp", stopReason: null },
950
+ no_answer: { phoneStatus: "no_answer", stopReason: null },
951
+ not_interested: { phoneStatus: null, stopReason: "not_interested" },
952
+ stop_campaigns: { phoneStatus: null, stopReason: "seller_stopped" }
953
+ };
954
+ var dispositionLabelKey = (a) => `conversations.disposition.action.${a}`;
955
+ var phoneStatusLabelKey = (s) => `conversations.disposition.phoneStatus.${s}`;
956
+ var stopReasonLabelKey = (r) => `conversations.disposition.stopReason.${r}`;
957
+ var PHONE_STATUSES = /* @__PURE__ */ new Set(["ok", "wrong_number", "no_whatsapp", "no_answer", "invalid"]);
958
+ var STOP_REASONS = /* @__PURE__ */ new Set(["opted_out", "replied", "wrong_number", "not_interested", "no_response", "converted", "seller_stopped"]);
959
+ function asPhoneStatus(v) {
960
+ return typeof v === "string" && PHONE_STATUSES.has(v) ? v : null;
961
+ }
962
+ function asStopReason(v) {
963
+ return typeof v === "string" && STOP_REASONS.has(v) ? v : null;
964
+ }
965
+ function isBadPhoneStatus(s) {
966
+ return !!s && s !== "ok";
967
+ }
968
+ function phoneE164(raw) {
969
+ const d = String(raw ?? "").replace(/\D/g, "");
970
+ if (!d) return null;
971
+ if (d.length === 10 || d.length === 11) return `+55${d}`;
972
+ if ((d.length === 12 || d.length === 13) && d.startsWith("55")) return `+${d}`;
973
+ return null;
974
+ }
975
+ function dispositionCalls(action, ctx) {
976
+ const plan = DISPOSITION_PLAN[action];
977
+ const phone = phoneE164(ctx.phone);
978
+ const note = ctx.note?.trim() || null;
979
+ const personId = ctx.personId || null;
980
+ const calls = [];
981
+ if (plan.phoneStatus && phone) {
982
+ calls.push({
983
+ fn: "crm_set_phone_status",
984
+ args: { p_phone: phone, p_status: plan.phoneStatus, p_reason: note, p_source: "seller", p_person: personId }
985
+ });
986
+ }
987
+ if (plan.stopReason && (personId || phone)) {
988
+ calls.push({
989
+ fn: "conversations_stop_journeys",
990
+ args: { p_person: personId, p_phone: phone, p_reason: plan.stopReason, p_note: note }
991
+ });
992
+ }
993
+ return calls;
994
+ }
995
+ var ICON = {
996
+ wrong_number: PhoneOff,
997
+ no_whatsapp: MessageSquareOff,
998
+ no_answer: PhoneMissed,
999
+ not_interested: ThumbsDown,
1000
+ stop_campaigns: Ban
1001
+ };
1002
+ var CHANGED = "fayz:conversations:contact-disposition";
1003
+ function notifyChanged() {
1004
+ if (typeof window !== "undefined") window.dispatchEvent(new Event(CHANGED));
1005
+ }
1006
+ function useContactDisposition(personId, phone) {
1007
+ const [state, setState] = React7__default.useState({ phone: null, stopped: null });
1008
+ const [version, setVersion] = React7__default.useState(0);
1009
+ React7__default.useEffect(() => {
1010
+ const bump = () => setVersion((v) => v + 1);
1011
+ window.addEventListener(CHANGED, bump);
1012
+ return () => window.removeEventListener(CHANGED, bump);
1013
+ }, []);
1014
+ React7__default.useEffect(() => {
1015
+ let alive = true;
1016
+ const sb = getSupabaseClientOptional();
1017
+ const tenantId = getActiveTenantId();
1018
+ const e164 = phoneE164(phone);
1019
+ if (!sb || !tenantId || !personId && !e164) {
1020
+ setState({ phone: null, stopped: null });
1021
+ return;
1022
+ }
1023
+ (async () => {
1024
+ const [ph, st] = await Promise.all([
1025
+ e164 ? sb.from("plg_crm_phone_status").select("status, reason, set_by_name, updated_at").eq("tenant_id", tenantId).eq("phone_e164", e164).maybeSingle().then((r) => r.data, () => null) : null,
1026
+ personId ? sb.from("plg_conversations_campaign_enrollments").select("stop_reason, state_reason, stopped_by_name, stopped_at").eq("tenant_id", tenantId).eq("person_id", personId).eq("state", "stopped").order("stopped_at", { ascending: false }).limit(1).maybeSingle().then((r) => r.data, () => null) : null
1027
+ ]);
1028
+ if (!alive) return;
1029
+ const status = asPhoneStatus(ph?.status);
1030
+ const reason = asStopReason(st?.stop_reason);
1031
+ setState({
1032
+ phone: status ? { status, reason: ph.reason ?? null, setByName: ph.set_by_name ?? null, at: ph.updated_at } : null,
1033
+ stopped: reason ? { reason, note: st.state_reason ?? null, byName: st.stopped_by_name ?? null, at: st.stopped_at ?? null } : null
1034
+ });
1035
+ })();
1036
+ return () => {
1037
+ alive = false;
1038
+ };
1039
+ }, [personId, phone, version]);
1040
+ return state;
1041
+ }
1042
+ async function applyDisposition(action, ctx) {
1043
+ const sb = getSupabaseClientOptional();
1044
+ if (!sb) throw new Error("no database client");
1045
+ let stopped = 0;
1046
+ for (const call of dispositionCalls(action, ctx)) {
1047
+ const { data, error } = await sb.rpc(call.fn, call.args);
1048
+ if (error) throw new Error(error.message);
1049
+ if (call.fn === "conversations_stop_journeys") stopped += Number(data ?? 0);
1050
+ }
1051
+ notifyChanged();
1052
+ return { stopped };
1053
+ }
1054
+ function DispositionMenu({ onPick, phone }) {
1055
+ const t = useTranslation();
1056
+ const hasPhone = !!phoneE164(phone);
1057
+ return /* @__PURE__ */ jsxs(DropdownSub, { children: [
1058
+ /* @__PURE__ */ jsxs(DropdownSubTrigger, { children: [
1059
+ /* @__PURE__ */ jsx(Tag, { className: "mr-2 h-3.5 w-3.5" }),
1060
+ " ",
1061
+ t("conversations.disposition.menu")
1062
+ ] }),
1063
+ /* @__PURE__ */ jsx(DropdownSubContent, { children: DISPOSITION_ACTIONS.map((a) => {
1064
+ const Icon = ICON[a];
1065
+ const needsPhone = a === "wrong_number" || a === "no_whatsapp" || a === "no_answer";
1066
+ return /* @__PURE__ */ jsxs(DropdownItem, { disabled: needsPhone && !hasPhone, onSelect: () => onPick(a), children: [
1067
+ /* @__PURE__ */ jsx(Icon, { className: "mr-2 h-3.5 w-3.5" }),
1068
+ " ",
1069
+ t(dispositionLabelKey(a))
1070
+ ] }, a);
1071
+ }) })
1072
+ ] });
1073
+ }
1074
+ function DispositionDialog({ action, personId, phone, onClose, onDone }) {
1075
+ const t = useTranslation();
1076
+ const [note, setNote] = React7__default.useState("");
1077
+ const [saving, setSaving] = React7__default.useState(false);
1078
+ React7__default.useEffect(() => {
1079
+ if (action) setNote("");
1080
+ }, [action]);
1081
+ const confirm = async () => {
1082
+ if (!action) return;
1083
+ setSaving(true);
1084
+ try {
1085
+ const { stopped } = await applyDisposition(action, { personId, phone, note });
1086
+ toast.success(t(dispositionLabelKey(action)), {
1087
+ description: stopped > 0 ? t("conversations.disposition.toastStopped", { count: String(stopped) }) : t("conversations.disposition.toastSaved")
1088
+ });
1089
+ onDone?.();
1090
+ onClose();
1091
+ } catch (e) {
1092
+ toast.error(t("conversations.disposition.toastError"), { description: e instanceof Error ? e.message : void 0 });
1093
+ } finally {
1094
+ setSaving(false);
1095
+ }
1096
+ };
1097
+ return /* @__PURE__ */ jsx(Modal, { open: !!action, onOpenChange: (o) => {
1098
+ if (!o && !saving) onClose();
1099
+ }, children: /* @__PURE__ */ jsxs(ModalContent, { size: "sm", children: [
1100
+ /* @__PURE__ */ jsxs(ModalHeader, { children: [
1101
+ /* @__PURE__ */ jsx(ModalTitle, { children: action ? t(dispositionLabelKey(action)) : "" }),
1102
+ action && /* @__PURE__ */ jsx(ModalDescription, { children: t(`conversations.disposition.explain.${action}`) })
1103
+ ] }),
1104
+ /* @__PURE__ */ jsx(ModalBody, { children: /* @__PURE__ */ jsx(
1105
+ Textarea,
1106
+ {
1107
+ value: note,
1108
+ onChange: (e) => setNote(e.target.value),
1109
+ placeholder: t("conversations.disposition.notePlaceholder"),
1110
+ "aria-label": t("conversations.disposition.note"),
1111
+ rows: 3
1112
+ }
1113
+ ) }),
1114
+ /* @__PURE__ */ jsxs(ModalFooter, { children: [
1115
+ /* @__PURE__ */ jsx(Button, { variant: "outline", onClick: onClose, disabled: saving, children: t("conversations.disposition.cancel") }),
1116
+ /* @__PURE__ */ jsx(Button, { onClick: () => void confirm(), disabled: saving, children: t("conversations.disposition.confirm") })
1117
+ ] })
1118
+ ] }) });
1119
+ }
1120
+ function PhoneStatusChip({ status, className, title }) {
1121
+ const t = useTranslation();
1122
+ if (!isBadPhoneStatus(status)) return null;
1123
+ return /* @__PURE__ */ jsx(
1124
+ "span",
1125
+ {
1126
+ title,
1127
+ className: cn("shrink-0 rounded-full bg-destructive-soft px-1.5 text-[10px] font-medium text-destructive-soft-foreground", className),
1128
+ children: t(phoneStatusLabelKey(status))
1129
+ }
1130
+ );
1131
+ }
1132
+ function attribution(t, who, at) {
1133
+ const date = at ? new Date(at).toLocaleDateString("pt-BR") : null;
1134
+ if (who && date) return t("conversations.disposition.byOn", { who, date });
1135
+ if (who) return t("conversations.disposition.by", { who });
1136
+ if (date) return t("conversations.disposition.onDate", { date });
1137
+ return null;
1138
+ }
1139
+ function phoneStatusLine(t, info) {
1140
+ return [t(phoneStatusLabelKey(info.status)), attribution(t, info.setByName, info.at), info.reason].filter(Boolean).join(" \u2014 ");
1141
+ }
1142
+ function stoppedJourneyLine(t, info) {
1143
+ return [t(stopReasonLabelKey(info.reason)), attribution(t, info.byName, info.at), info.note].filter(Boolean).join(" \u2014 ");
1144
+ }
938
1145
  var URL_RE = /(https?:\/\/[^\s<]+[^\s<.,;:!?)\]'"])/gu;
939
1146
  function RichText({ text, outbound }) {
940
1147
  const linkCls = outbound ? "underline text-white" : "text-[hsl(var(--info))] underline";
@@ -1175,6 +1382,9 @@ function MessageThread({ selected, onTogglePanel, panelOpen, onBack, backAlways,
1175
1382
  const win = useSendWindow(selected.id, selected.channel === "whatsapp" ? selected.contactHandle : void 0);
1176
1383
  const canType = win.mode.kind === "free";
1177
1384
  const threadRef = React7__default.useRef(null);
1385
+ const contactPhone = selected.channel === "whatsapp" ? selected.contactHandle : null;
1386
+ const disposition = useContactDisposition(selected.contactPersonId, contactPhone);
1387
+ const [dispositionAction, setDispositionAction] = React7__default.useState(null);
1178
1388
  React7__default.useEffect(() => {
1179
1389
  threadRef.current?.scrollTo({ top: threadRef.current.scrollHeight, behavior: "smooth" });
1180
1390
  }, [messages.length, selected.id]);
@@ -1244,6 +1454,13 @@ function MessageThread({ selected, onTogglePanel, panelOpen, onBack, backAlways,
1244
1454
  className: "shrink-0 rounded-full bg-muted px-1.5 text-[10px] font-normal text-muted-foreground",
1245
1455
  children: selected.provider === "tyxter" ? "n\xFAmero oficial" : "n\xFAmero do dia a dia"
1246
1456
  }
1457
+ ),
1458
+ /* @__PURE__ */ jsx(
1459
+ PhoneStatusChip,
1460
+ {
1461
+ status: disposition.phone?.status,
1462
+ title: disposition.phone ? phoneStatusLine(t, disposition.phone) : void 0
1463
+ }
1247
1464
  )
1248
1465
  ] }),
1249
1466
  !panelOpen && /* @__PURE__ */ jsxs("p", { className: "flex items-center gap-1.5 text-xs text-muted-foreground", children: [
@@ -1252,24 +1469,36 @@ function MessageThread({ selected, onTogglePanel, panelOpen, onBack, backAlways,
1252
1469
  ] })
1253
1470
  ] })
1254
1471
  ] }),
1255
- /* @__PURE__ */ jsx("div", { className: "flex shrink-0 items-center gap-1.5", onClick: (e) => e.stopPropagation(), onKeyDown: (e) => e.stopPropagation(), children: /* @__PURE__ */ jsxs(Dropdown, { children: [
1256
- /* @__PURE__ */ jsx(DropdownTrigger, { asChild: true, children: /* @__PURE__ */ jsx(Button, { variant: "ghost", size: "icon", "aria-label": t("conversations.thread.more"), children: /* @__PURE__ */ jsx(MoreHorizontal, { className: "h-4 w-4" }) }) }),
1257
- /* @__PURE__ */ jsxs(DropdownContent, { align: "end", children: [
1258
- /* @__PURE__ */ jsxs(DropdownItem, { onSelect: () => void markUnread(selected.id), children: [
1259
- /* @__PURE__ */ jsx(MailWarning, { className: "mr-2 h-3.5 w-3.5" }),
1260
- " Marcar como n\xE3o lida"
1261
- ] }),
1262
- selected.status === "closed" ? /* @__PURE__ */ jsxs(DropdownItem, { onSelect: () => setStatus("open"), children: [
1263
- /* @__PURE__ */ jsx(ArchiveRestore, { className: "mr-2 h-3.5 w-3.5" }),
1264
- " ",
1265
- t("conversations.thread.unarchive")
1266
- ] }) : /* @__PURE__ */ jsxs(DropdownItem, { onSelect: () => setStatus("closed"), children: [
1267
- /* @__PURE__ */ jsx(Archive, { className: "mr-2 h-3.5 w-3.5" }),
1268
- " ",
1269
- t("conversations.thread.archive")
1472
+ /* @__PURE__ */ jsxs("div", { className: "flex shrink-0 items-center gap-1.5", onClick: (e) => e.stopPropagation(), onKeyDown: (e) => e.stopPropagation(), children: [
1473
+ /* @__PURE__ */ jsxs(Dropdown, { children: [
1474
+ /* @__PURE__ */ jsx(DropdownTrigger, { asChild: true, children: /* @__PURE__ */ jsx(Button, { variant: "ghost", size: "icon", "aria-label": t("conversations.thread.more"), children: /* @__PURE__ */ jsx(MoreHorizontal, { className: "h-4 w-4" }) }) }),
1475
+ /* @__PURE__ */ jsxs(DropdownContent, { align: "end", children: [
1476
+ /* @__PURE__ */ jsxs(DropdownItem, { onSelect: () => void markUnread(selected.id), children: [
1477
+ /* @__PURE__ */ jsx(MailWarning, { className: "mr-2 h-3.5 w-3.5" }),
1478
+ " Marcar como n\xE3o lida"
1479
+ ] }),
1480
+ /* @__PURE__ */ jsx(DispositionMenu, { phone: contactPhone, onPick: setDispositionAction }),
1481
+ selected.status === "closed" ? /* @__PURE__ */ jsxs(DropdownItem, { onSelect: () => setStatus("open"), children: [
1482
+ /* @__PURE__ */ jsx(ArchiveRestore, { className: "mr-2 h-3.5 w-3.5" }),
1483
+ " ",
1484
+ t("conversations.thread.unarchive")
1485
+ ] }) : /* @__PURE__ */ jsxs(DropdownItem, { onSelect: () => setStatus("closed"), children: [
1486
+ /* @__PURE__ */ jsx(Archive, { className: "mr-2 h-3.5 w-3.5" }),
1487
+ " ",
1488
+ t("conversations.thread.archive")
1489
+ ] })
1270
1490
  ] })
1271
- ] })
1272
- ] }) })
1491
+ ] }),
1492
+ /* @__PURE__ */ jsx(
1493
+ DispositionDialog,
1494
+ {
1495
+ action: dispositionAction,
1496
+ personId: selected.contactPersonId,
1497
+ phone: contactPhone,
1498
+ onClose: () => setDispositionAction(null)
1499
+ }
1500
+ )
1501
+ ] })
1273
1502
  ]
1274
1503
  }
1275
1504
  ),
@@ -1509,6 +1738,10 @@ function day(iso) {
1509
1738
  function ContactPanel({ contact, onClose, className }) {
1510
1739
  const t = useTranslation();
1511
1740
  const profile = useContactProfile(contact.contactPersonId, contact.contactHandle);
1741
+ const disposition = useContactDisposition(
1742
+ contact.contactPersonId ?? profile?.id ?? null,
1743
+ contact.channel === "whatsapp" ? contact.contactHandle : profile?.phone ?? null
1744
+ );
1512
1745
  return /* @__PURE__ */ jsxs("aside", { className: cn("flex shrink-0 flex-col overflow-y-auto border-l border-border bg-muted/20 pb-4", className), children: [
1513
1746
  /* @__PURE__ */ jsxs("div", { className: "sticky top-0 z-10 flex items-center justify-between border-b border-border bg-card px-3 py-2", children: [
1514
1747
  /* @__PURE__ */ jsx("span", { className: "text-sm font-semibold text-foreground", children: t("conversations.contact.details") }),
@@ -1529,6 +1762,10 @@ function ContactPanel({ contact, onClose, className }) {
1529
1762
  profile === void 0 && /* @__PURE__ */ jsx("p", { className: "px-4 pt-4 text-xs text-muted-foreground", children: t("conversations.profile.loading") }),
1530
1763
  profile === null && /* @__PURE__ */ jsx("p", { className: "px-4 pt-4 text-xs text-muted-foreground", children: t("conversations.profile.notInCrm") }),
1531
1764
  profile && /* @__PURE__ */ jsx(ProfileSections, { profile }),
1765
+ (disposition.phone || disposition.stopped) && /* @__PURE__ */ jsx(Section, { title: t("conversations.disposition.section"), children: /* @__PURE__ */ jsx(Rows, { rows: [
1766
+ [t("conversations.disposition.phoneStatusRow"), disposition.phone ? /* @__PURE__ */ jsx("span", { className: disposition.phone.status === "ok" ? void 0 : "text-destructive", children: phoneStatusLine(t, disposition.phone) }) : null],
1767
+ [t("conversations.disposition.stoppedRow"), disposition.stopped ? stoppedJourneyLine(t, disposition.stopped) : null]
1768
+ ] }) }),
1532
1769
  /* @__PURE__ */ jsx(Section, { title: t("conversations.profile.conversation"), children: /* @__PURE__ */ jsx(Rows, { rows: [
1533
1770
  [t("conversations.contact.channel"), channelLabel(contact.channel)],
1534
1771
  [t("conversations.contact.status"), t(`conversations.status.${contact.status}`)],
@@ -1901,5 +2138,5 @@ function ConversationsPage({ store, config }) {
1901
2138
  }
1902
2139
 
1903
2140
  export { ConversationsPage, conversationIdFromPath };
1904
- //# sourceMappingURL=ConversationsPage-KCKQMEVL.js.map
1905
- //# sourceMappingURL=ConversationsPage-KCKQMEVL.js.map
2141
+ //# sourceMappingURL=ConversationsPage-P6U7BNZO.js.map
2142
+ //# sourceMappingURL=ConversationsPage-P6U7BNZO.js.map