@fayz-ai/plugin-crm 0.22.0 → 0.24.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.
@@ -1 +1 @@
1
- {"version":3,"file":"mock.d.ts","sourceRoot":"","sources":["../../src/data/mock.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;AA2K9C,wBAAgB,qBAAqB,CAAC,OAAO,CAAC,EAAE;IAC9C,UAAU,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,WAAW,EAAE,MAAM,CAAA;KAAE,CAAC,CAAA;IACxE,aAAa,CAAC,EAAE,KAAK,CAAC;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAA;CACvE,GAAG,eAAe,CAiqClB"}
1
+ {"version":3,"file":"mock.d.ts","sourceRoot":"","sources":["../../src/data/mock.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;AA2K9C,wBAAgB,qBAAqB,CAAC,OAAO,CAAC,EAAE;IAC9C,UAAU,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,WAAW,EAAE,MAAM,CAAA;KAAE,CAAC,CAAA;IACxE,aAAa,CAAC,EAAE,KAAK,CAAC;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAA;CACvE,GAAG,eAAe,CAoqClB"}
@@ -1 +1 @@
1
- {"version":3,"file":"supabase.d.ts","sourceRoot":"","sources":["../../src/data/supabase.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;AA+Q9C,wBAAgB,yBAAyB,CAAC,OAAO,CAAC,EAAE;IAClD,gBAAgB,CAAC,EAAE;QAAE,aAAa,EAAE,MAAM,CAAC;QAAC,cAAc,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAA;IACtF,kFAAkF;IAClF,aAAa,CAAC,EAAE,KAAK,CAAC;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAA;CACvE,GAAG,eAAe,CAusElB"}
1
+ {"version":3,"file":"supabase.d.ts","sourceRoot":"","sources":["../../src/data/supabase.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;AA4S9C,wBAAgB,yBAAyB,CAAC,OAAO,CAAC,EAAE;IAClD,gBAAgB,CAAC,EAAE;QAAE,aAAa,EAAE,MAAM,CAAC;QAAC,cAAc,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAA;IACtF,kFAAkF;IAClF,aAAa,CAAC,EAAE,KAAK,CAAC;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAA;CACvE,GAAG,eAAe,CAouElB"}
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import React, { useState, useEffect, useMemo, useCallback, useRef } from 'react';
2
2
  import { tl, useTranslation, getSupabaseClientOptional, registerTranslations, registerMessageDefaults, createSafeDataProvider, getActiveTenantId, countByTenant, usePluginRuntimeOptional, useActiveTenantId, exportCSV, loadMessageOverrides, resolveMessages, useActiveUnitId } from '@fayz-ai/core';
3
- import { createPluginContext, useUnitBootstrap, useUnitStore, createCrudPage, PluginSettingsPanel, registerTimelineSource, dedup, useModuleNavigation, createViewRouter, ModuleActionBar, usePermissionOptional, PageActions, useTenantPluginSettings, SettingsGroup, ToggleRow, adminNavigateTo, useLimitGuard, OrderFormSkeleton, OrderFormBlock, OrderFormView, OrderFormItemsCard, OrderFormItemRow, OrderFormAddItemStep, formatCurrency, OrderDetailSkeleton, OrderDetailBlock, OrderDetailView, PersonLink, RightRailPage, KanbanBoard, invalidateLimit, useAccessOptional, useOrganizationStore, getRailPage, ContactPicker } from '@fayz-ai/admin';
3
+ import { createPluginContext, useUnitBootstrap, useUnitStore, createCrudPage, PluginSettingsPanel, registerTimelineSource, dedup, useModuleNavigation, createViewRouter, ModuleActionBar, usePermissionOptional, PageActions, useTenantPluginSettings, SettingsGroup, ToggleRow, adminNavigateTo, useLimitGuard, OrderFormSkeleton, OrderFormBlock, OrderFormView, OrderFormItemsCard, OrderFormItemRow, OrderFormAddItemStep, formatCurrency, useRecordVisit, OrderDetailSkeleton, OrderDetailBlock, OrderDetailView, PersonLink, RightRailPage, KanbanBoard, invalidateLimit, useAccessOptional, useOrganizationStore, getRailPage, ContactPicker } from '@fayz-ai/admin';
4
4
  import { Archive, FileX2, FileCheck2, Send, FilePlus2, XCircle, Trophy, PhoneCall, MoveRight, Target, ArrowRightLeft, UserPlus, MapPin, MessageCircle, CheckSquare, FileText, Users, Mail, Phone, ArrowUp, ArrowDown, X, Plus, Filter, Lock, Pencil, Trash2, Globe, Check, ChevronRight, Settings, Tag, User, Building2, Download, Inbox, Play, Clock, Sparkles, Calendar, ArrowRight, ChevronDown, Printer, CircleCheckBig, Ban, Receipt, Package, CalendarClock, Loader2, Network, Fingerprint, Link2, Star, MessageSquareQuote, Search, SignalHigh, CalendarRange, ChevronLeft, TrendingDown, ThumbsDown, UserCheck, AlertTriangle, Settings2, Repeat, Zap, Snowflake, Sun, Flame, Merge, Paperclip, ImageOff, CircleAlert, CircleDashed, CheckCircle2, CalendarDays, Clipboard, DollarSign, ThumbsUp } from 'lucide-react';
5
5
  import { Badge, Checkbox, toast, defineKpiWidget, defineChartWidget, defineCustomWidget, defineTableWidget, PageTransition, ModulePage, SubpageHeader, Button, TooltipProvider, Tooltip, TooltipTrigger, TooltipContent, Switch, ConfirmDialog, useIsWide, SegmentedControl, PageHeaderActions, FilterChip, MultiSelect, ListView, Modal, ModalContent, ModalHeader, ModalTitle, ModalBody, Input, Select, SelectTrigger, SelectValue, SelectContent, SelectItem, ModalFooter, useSaveBar, SearchSelect, DatePicker, DataTable, Breadcrumb, PhoneLink, SheetBody, SheetFooter, DashboardCanvas, ModalDescription, Card, CurrencyInput, HeaderTabs, Dropdown, DropdownTrigger, DropdownContent, DropdownLabel, DropdownSeparator, DropdownItem, Popover, PopoverTrigger, PopoverContent, getLucideIcon, DictateButton, normalizePhone, KpiCard, ChartWidget, CardHeader, CardTitle, CardContent, TableWidget } from '@fayz-ai/ui';
6
6
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
@@ -4284,6 +4284,20 @@ function LeadListView({ onNew, onEdit }) {
4284
4284
  )
4285
4285
  ] });
4286
4286
  }
4287
+
4288
+ // src/lib/instagram.ts
4289
+ function normalizeInstagram(raw) {
4290
+ const v = String(raw ?? "").trim();
4291
+ if (!v) return void 0;
4292
+ const url = v.match(/(?:https?:\/\/)?(?:www\.)?instagram\.com\/([^/?#\s]+)/i);
4293
+ const handle = (url ? url[1] : v).replace(/^@+/, "").replace(/\/+$/, "").trim();
4294
+ return /^[A-Za-z0-9._]{1,30}$/.test(handle) ? handle : v;
4295
+ }
4296
+ function instagramUrl(handle) {
4297
+ const h = normalizeInstagram(handle);
4298
+ if (!h || !/^[A-Za-z0-9._]{1,30}$/.test(h)) return void 0;
4299
+ return `https://instagram.com/${h}`;
4300
+ }
4287
4301
  function LeadFormView({ onSaved }) {
4288
4302
  const t2 = useTranslation();
4289
4303
  const createLead = useCrmStore((s) => s.createLead);
@@ -4294,6 +4308,7 @@ function LeadFormView({ onSaved }) {
4294
4308
  const [name, setName] = useState("");
4295
4309
  const [email, setEmail] = useState("");
4296
4310
  const [phone, setPhone] = useState("");
4311
+ const [instagram, setInstagram] = useState("");
4297
4312
  const [company, setCompany] = useState("");
4298
4313
  const [notes, setNotes] = useState("");
4299
4314
  const [sourceId, setSourceId] = useState("");
@@ -4328,6 +4343,9 @@ function LeadFormView({ onSaved }) {
4328
4343
  name,
4329
4344
  email: email || void 0,
4330
4345
  phone: phone || void 0,
4346
+ // Normaliza na ESCRITA: `@casa`, `casa` e a URL inteira viram o mesmo
4347
+ // handle, senão a mesma casa aparece como quatro contatos ao cruzar.
4348
+ instagram: normalizeInstagram(instagram),
4331
4349
  company: company || void 0,
4332
4350
  notes: notes || void 0,
4333
4351
  sourceId: source?.id,
@@ -4368,6 +4386,10 @@ function LeadFormView({ onSaved }) {
4368
4386
  /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t2("crm.leadForm.phone") }),
4369
4387
  /* @__PURE__ */ jsx(Input, { type: "tel", className: "mt-1", value: phone, onChange: (e) => setPhone(e.target.value), placeholder: t2("crm.leadForm.phonePlaceholder") })
4370
4388
  ] }),
4389
+ /* @__PURE__ */ jsxs("div", { children: [
4390
+ /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t2("crm.leadForm.instagram") }),
4391
+ /* @__PURE__ */ jsx(Input, { className: "mt-1", value: instagram, onChange: (e) => setInstagram(e.target.value), placeholder: t2("crm.leadForm.instagramPlaceholder") })
4392
+ ] }),
4371
4393
  /* @__PURE__ */ jsxs("div", { children: [
4372
4394
  /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t2("crm.leadForm.notes") }),
4373
4395
  /* @__PURE__ */ jsx("textarea", { value: notes, onChange: (e) => setNotes(e.target.value), rows: 2, placeholder: t2("crm.leadForm.notesPlaceholder"), className: "w-full mt-1 rounded-input border border-input bg-card shadow-[inset_0_1px_0_rgb(0_0_0_/0.06)] px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring resize-none" })
@@ -5511,6 +5533,15 @@ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote, onOpenComp
5511
5533
  const canArchive = useCanArchive();
5512
5534
  const [archiving, setArchiving] = useState(false);
5513
5535
  const [lead, setLead] = useState(null);
5536
+ useRecordVisit(lead ? {
5537
+ id: lead.id,
5538
+ kind: "lead",
5539
+ kindLabel: t2("crm.leads.title"),
5540
+ label: lead.name,
5541
+ subtitle: lead.company || lead.email || void 0,
5542
+ archetype: "person",
5543
+ archetypeKind: "lead"
5544
+ } : null);
5514
5545
  const [deal, setDeal] = useState(null);
5515
5546
  const [quotes2, setQuotes] = useState([]);
5516
5547
  const [loading, setLoading] = useState(true);
@@ -5643,6 +5674,25 @@ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote, onOpenComp
5643
5674
  )
5644
5675
  }
5645
5676
  ) }),
5677
+ /* @__PURE__ */ jsx("div", { className: "px-5 md:border-b md:last:border-b-0", children: /* @__PURE__ */ jsx(
5678
+ FieldRow,
5679
+ {
5680
+ label: t2("crm.leadDetail.instagram"),
5681
+ value: lead.instagram ? instagramUrl(lead.instagram) ? /* @__PURE__ */ jsxs(
5682
+ "a",
5683
+ {
5684
+ href: instagramUrl(lead.instagram),
5685
+ target: "_blank",
5686
+ rel: "noreferrer",
5687
+ className: "text-primary hover:underline",
5688
+ children: [
5689
+ "@",
5690
+ normalizeInstagram(lead.instagram)
5691
+ ]
5692
+ }
5693
+ ) : /* @__PURE__ */ jsx("span", { children: lead.instagram }) : null
5694
+ }
5695
+ ) }),
5646
5696
  /* @__PURE__ */ jsx("div", { className: "px-5 md:border-b md:last:border-b-0", children: /* @__PURE__ */ jsx(FieldRow, { label: t2("crm.leadDetail.source"), value: lead.sourceName }) })
5647
5697
  ] }) })
5648
5698
  ] }),
@@ -5901,6 +5951,7 @@ function CompanyFormView({ companyId, onSaved }) {
5901
5951
  const [email, setEmail] = useState("");
5902
5952
  const [phone, setPhone] = useState("");
5903
5953
  const [website, setWebsite] = useState("");
5954
+ const [instagram, setInstagram] = useState("");
5904
5955
  const [city, setCity] = useState("");
5905
5956
  const [state, setState] = useState("");
5906
5957
  const [notes, setNotes] = useState("");
@@ -5917,6 +5968,7 @@ function CompanyFormView({ companyId, onSaved }) {
5917
5968
  setEmail(c.email ?? "");
5918
5969
  setPhone(c.phone ?? "");
5919
5970
  setWebsite(c.website ?? "");
5971
+ setInstagram(c.instagram ?? "");
5920
5972
  setCity(c.city ?? "");
5921
5973
  setState(c.state ?? "");
5922
5974
  setNotes(c.notes ?? "");
@@ -5953,6 +6005,8 @@ function CompanyFormView({ companyId, onSaved }) {
5953
6005
  email: email.trim() || void 0,
5954
6006
  phone: phone.trim() || void 0,
5955
6007
  website: website.trim() || void 0,
6008
+ // Normaliza na escrita — ver lib/instagram.
6009
+ instagram: normalizeInstagram(instagram),
5956
6010
  city: city.trim() || void 0,
5957
6011
  state: state.trim() || void 0,
5958
6012
  notes: notes.trim() || void 0
@@ -6027,9 +6081,24 @@ function CompanyFormView({ companyId, onSaved }) {
6027
6081
  /* @__PURE__ */ jsx("input", { type: "tel", value: phone, onChange: (e) => setPhone(e.target.value), className: inputClass })
6028
6082
  ] })
6029
6083
  ] }),
6030
- /* @__PURE__ */ jsxs("div", { children: [
6031
- /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t2("crm.companyForm.website") }),
6032
- /* @__PURE__ */ jsx("input", { type: "text", value: website, onChange: (e) => setWebsite(e.target.value), className: inputClass })
6084
+ /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-3", children: [
6085
+ /* @__PURE__ */ jsxs("div", { children: [
6086
+ /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t2("crm.companyForm.website") }),
6087
+ /* @__PURE__ */ jsx("input", { type: "text", value: website, onChange: (e) => setWebsite(e.target.value), className: inputClass })
6088
+ ] }),
6089
+ /* @__PURE__ */ jsxs("div", { children: [
6090
+ /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t2("crm.companyForm.instagram") }),
6091
+ /* @__PURE__ */ jsx(
6092
+ "input",
6093
+ {
6094
+ type: "text",
6095
+ value: instagram,
6096
+ onChange: (e) => setInstagram(e.target.value),
6097
+ placeholder: "@casa",
6098
+ className: inputClass
6099
+ }
6100
+ )
6101
+ ] })
6033
6102
  ] }),
6034
6103
  /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-3 gap-3", children: [
6035
6104
  /* @__PURE__ */ jsxs("div", { className: "col-span-2", children: [
@@ -6236,6 +6305,16 @@ function CompanyDetailView({
6236
6305
  const archiveCompany = useCrmStore((s) => s.archiveCompany);
6237
6306
  const unlinkCompanyPerson = useCrmStore((s) => s.unlinkCompanyPerson);
6238
6307
  const [company, setCompany] = useState(null);
6308
+ useRecordVisit(company ? {
6309
+ id: company.id,
6310
+ kind: "company",
6311
+ kindLabel: t2("crm.companies.title"),
6312
+ label: company.name || company.legalName || "",
6313
+ // Só quando DIZ outra coisa. A razão social costuma ser igual ao nome
6314
+ // fantasia, e um subtítulo que repete o título é ruído.
6315
+ subtitle: company.legalName && company.legalName !== company.name ? company.legalName : void 0,
6316
+ archetype: "company"
6317
+ } : null);
6239
6318
  const [receita, setReceita] = useState(null);
6240
6319
  const [people, setPeople] = useState([]);
6241
6320
  const [deals, setDeals] = useState([]);
@@ -6251,11 +6330,11 @@ function CompanyDetailView({
6251
6330
  provider.getCompanyPeople(companyId),
6252
6331
  // Todos os negócios da casa, não só os abertos: o histórico é metade do
6253
6332
  // que faz uma ficha de empresa valer alguma coisa.
6254
- provider.getDeals({ pageSize: 200 })
6333
+ provider.getDeals({ companyId, pageSize: 200 })
6255
6334
  ]);
6256
6335
  setCompany(c);
6257
6336
  setPeople(p);
6258
- setDeals(d.data.filter((x) => x.companyId === companyId));
6337
+ setDeals(d.data);
6259
6338
  } finally {
6260
6339
  setLoading(false);
6261
6340
  }
@@ -6339,6 +6418,25 @@ function CompanyDetailView({
6339
6418
  label: t2("crm.companyDetail.location"),
6340
6419
  value: [company.city, company.state].filter(Boolean).join(" / ") || null
6341
6420
  }
6421
+ ) }),
6422
+ /* @__PURE__ */ jsx("div", { className: "px-5 md:border-b md:last:border-b-0", children: /* @__PURE__ */ jsx(
6423
+ FieldRow2,
6424
+ {
6425
+ label: t2("crm.companyDetail.instagram"),
6426
+ value: company.instagram ? instagramUrl(company.instagram) ? /* @__PURE__ */ jsxs(
6427
+ "a",
6428
+ {
6429
+ href: instagramUrl(company.instagram),
6430
+ target: "_blank",
6431
+ rel: "noreferrer",
6432
+ className: "text-primary hover:underline",
6433
+ children: [
6434
+ "@",
6435
+ normalizeInstagram(company.instagram)
6436
+ ]
6437
+ }
6438
+ ) : /* @__PURE__ */ jsx("span", { children: company.instagram }) : null
6439
+ }
6342
6440
  ) })
6343
6441
  ] }) })
6344
6442
  ] }),
@@ -9119,6 +9217,9 @@ function createMockCrmProvider(options) {
9119
9217
  let results = [...store.deals];
9120
9218
  if (query.pipelineId) results = results.filter((d) => d.pipelineId === query.pipelineId);
9121
9219
  if (query.stageId) results = results.filter((d) => d.stageId === query.stageId);
9220
+ if (query.companyId) results = results.filter((d) => d.companyId === query.companyId);
9221
+ if (query.assignedToId === "none") results = results.filter((d) => !d.assignedToId);
9222
+ else if (query.assignedToId) results = results.filter((d) => d.assignedToId === query.assignedToId);
9122
9223
  if (query.status) {
9123
9224
  const statuses = Array.isArray(query.status) ? query.status : [query.status];
9124
9225
  results = results.filter((d) => statuses.includes(d.status));
@@ -10160,6 +10261,7 @@ function toCompany(r) {
10160
10261
  email: r.email ?? void 0,
10161
10262
  phone: r.phone ?? void 0,
10162
10263
  website: r.website ?? void 0,
10264
+ instagram: r.instagram ?? void 0,
10163
10265
  address: r.address ?? void 0,
10164
10266
  city: r.city ?? void 0,
10165
10267
  state: r.state ?? void 0,
@@ -10314,6 +10416,21 @@ async function mergePersonMetadata(personId, patch) {
10314
10416
  const current = row?.metadata ?? {};
10315
10417
  await core.from("people").update({ metadata: { ...current, ...patch } }).eq("id", personId);
10316
10418
  }
10419
+ async function sincronizarDonoNaPessoa(dealId, userId) {
10420
+ try {
10421
+ const { pub, core } = getClients();
10422
+ const { data: negocio } = await pub.from(T.deals).select("lead_id, contact_id").eq("id", dealId).maybeSingle();
10423
+ const pessoaId = negocio?.lead_id ?? negocio?.contact_id;
10424
+ if (!pessoaId) return;
10425
+ const { data: pessoa } = await core.from("people").select("metadata").eq("id", pessoaId).maybeSingle();
10426
+ const metadata = { ...pessoa?.metadata ?? {} };
10427
+ if (userId) metadata.assignedToId = userId;
10428
+ else delete metadata.assignedToId;
10429
+ await core.from("people").update({ metadata }).eq("id", pessoaId);
10430
+ } catch (e) {
10431
+ console.error("[crm] o negocio mudou de dono, a pessoa nao:", e);
10432
+ }
10433
+ }
10317
10434
  function createSupabaseCrmProvider(options) {
10318
10435
  async function logEvent(input) {
10319
10436
  try {
@@ -10420,6 +10537,7 @@ function createSupabaseCrmProvider(options) {
10420
10537
  name: r.name,
10421
10538
  email: r.email,
10422
10539
  phone: r.phone,
10540
+ instagram: r.instagram ?? void 0,
10423
10541
  company: r.company,
10424
10542
  companyId: r.company_id ?? void 0,
10425
10543
  companyName: r.company_name ?? void 0,
@@ -10456,6 +10574,7 @@ function createSupabaseCrmProvider(options) {
10456
10574
  name: r.name,
10457
10575
  email: r.email,
10458
10576
  phone: r.phone,
10577
+ instagram: r.instagram ?? void 0,
10459
10578
  company: r.company,
10460
10579
  companyId: r.company_id ?? void 0,
10461
10580
  companyName: r.company_name ?? void 0,
@@ -10489,6 +10608,7 @@ function createSupabaseCrmProvider(options) {
10489
10608
  name: input.name,
10490
10609
  email: input.email,
10491
10610
  phone: input.phone,
10611
+ instagram: input.instagram || null,
10492
10612
  notes: input.notes,
10493
10613
  tags: input.tags ?? [],
10494
10614
  is_active: true,
@@ -10556,6 +10676,9 @@ function createSupabaseCrmProvider(options) {
10556
10676
  }
10557
10677
  if (query.pipelineId) qb = qb.eq("pipeline_id", query.pipelineId);
10558
10678
  if (query.stageId) qb = qb.eq("stage_id", query.stageId);
10679
+ if (query.companyId) qb = qb.eq("company_id", query.companyId);
10680
+ if (query.assignedToId === "none") qb = qb.is("assigned_to_id", null);
10681
+ else if (query.assignedToId) qb = qb.eq("assigned_to_id", query.assignedToId);
10559
10682
  const page = query.page ?? 1;
10560
10683
  const pageSize = query.pageSize ?? 50;
10561
10684
  qb = qb.range((page - 1) * pageSize, page * pageSize - 1).order("created_at", { ascending: false });
@@ -10672,6 +10795,9 @@ function createSupabaseCrmProvider(options) {
10672
10795
  const { error } = await pub.from(T.deals).update(row).eq("id", id);
10673
10796
  if (error) throw new Error(error.message);
10674
10797
  }
10798
+ if (partial.assignedToId !== void 0) {
10799
+ await sincronizarDonoNaPessoa(id, partial.assignedToId ?? null);
10800
+ }
10675
10801
  return await provider.getDealById(id);
10676
10802
  },
10677
10803
  async moveDealToStage(dealId, stageId) {
@@ -25227,6 +25353,109 @@ CREATE OR REPLACE VIEW public.v_leads WITH (security_invoker = true) AS
25227
25353
  FROM plg_crm_deals d
25228
25354
  WHERE d.status = 'open'::text AND d.contact_id IS NOT NULL));
25229
25355
  `;
25356
+ var MIGRATION_048_A_EMPRESA_TAMBEM_TEM_UM_ARROBA = `-- ---------------------------------------------------------------------------
25357
+ -- 048_a_empresa_tambem_tem_um_arroba.sql
25358
+ --
25359
+ -- O par da 117 do lado da empresa. A pessoa ganhou \`instagram\` na espinha; a
25360
+ -- empresa ganha aqui, porque \`plg_crm_companies\` \xE9 tabela deste plugin.
25361
+ --
25362
+ -- E na empresa ele vale ainda mais do que na pessoa: num restaurante o perfil
25363
+ -- da CASA \xE9 o que tem os posts, o p\xFAblico e a prova de que ela existe \u2014 muitas
25364
+ -- vezes \xE9 a \xFAnica presen\xE7a digital que h\xE1. \`website\` est\xE1 vazio em quase toda
25365
+ -- a base da feira; o Instagram n\xE3o.
25366
+ --
25367
+ -- Mesmo racioc\xEDnio da 117 quanto \xE0 forma: texto simples, sem CHECK. Quem digita
25368
+ -- escreve \`@casa\`, \`casa\`, \`instagram.com/casa\`. Recusar tr\xEAs dessas formas faz
25369
+ -- o vendedor parar de preencher, que \xE9 o \xFAnico jeito de este campo falhar.
25370
+ -- ---------------------------------------------------------------------------
25371
+
25372
+ ALTER TABLE public.plg_crm_companies
25373
+ ADD COLUMN IF NOT EXISTS instagram text;
25374
+
25375
+ COMMENT ON COLUMN public.plg_crm_companies.instagram IS
25376
+ 'O @ da casa, preenchido \xE0 m\xE3o. Costuma ser a \xFAnica presen\xE7a digital que existe \u2014 \`website\` est\xE1 vazio em quase toda a base (048).';
25377
+ `;
25378
+ var MIGRATION_049_O_ARROBA_CHEGA_ATE_A_LISTA = `-- ---------------------------------------------------------------------------
25379
+ -- 049_o_arroba_chega_ate_a_lista.sql
25380
+ --
25381
+ -- A 117 criou \`people.instagram\` e a 048 o da empresa. A lista de leads n\xE3o l\xEA
25382
+ -- \`people\` \u2014 l\xEA \`v_crm_leads\` \u2014, e coluna nova numa tabela n\xE3o aparece sozinha
25383
+ -- numa view: ela tem de ser dita.
25384
+ --
25385
+ -- \u2500\u2500 e N\xC3O se diz na \`v_leads\` \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
25386
+ --
25387
+ -- A primeira vers\xE3o desta migration alargava \`v_leads\` e deixava \`v_crm_leads\`
25388
+ -- herdar por \`l.*\`. Parecia o caminho curto e quebrou o db-from-zero:
25389
+ --
25390
+ -- 023_o_contato_diz_de_que_empresa_ele_e.sql \u2026 FAILED
25391
+ -- ERROR: cannot drop columns from view
25392
+ --
25393
+ -- A 023 cria a \`v_leads\` com \`CREATE OR REPLACE\` e colunas NOMEADAS, sem DROP
25394
+ -- antes. No replay ela roda de novo \u2014 agora sobre a view j\xE1 alargada \u2014 e o
25395
+ -- Postgres recusa, porque a lista dela \xE9 menor. Ou seja: quem alarga a
25396
+ -- \`v_leads\` quebra a migration que a criou.
25397
+ --
25398
+ -- A \`v_crm_leads\` n\xE3o tem esse problema: a 013 a DERRUBA antes de criar. \xC9 por
25399
+ -- isso que o alargamento mora aqui, e a coluna vem da tabela e n\xE3o da view
25400
+ -- intermedi\xE1ria.
25401
+ --
25402
+ -- \u2500\u2500 a defini\xE7\xE3o vem do banco \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
25403
+ --
25404
+ -- Como na 047: esta view foi alargada por migrations posteriores \xE0 que a criou,
25405
+ -- e reescrev\xEA-la a partir da origem devolveria a forma antiga.
25406
+ -- ---------------------------------------------------------------------------
25407
+
25408
+ DROP VIEW IF EXISTS public.v_crm_leads;
25409
+ CREATE VIEW public.v_crm_leads WITH (security_invoker = true) AS
25410
+ SELECT l.id,
25411
+ l.tenant_id,
25412
+ l.name,
25413
+ l.email,
25414
+ l.phone,
25415
+ l.notes,
25416
+ l.tags,
25417
+ l.is_active,
25418
+ l.company,
25419
+ l.source_id,
25420
+ l.source_name,
25421
+ l.lead_status,
25422
+ l.lead_value,
25423
+ l.assigned_to_id,
25424
+ l.created_at,
25425
+ l.updated_at,
25426
+ l.form_id,
25427
+ l.custom_fields,
25428
+ l.utm,
25429
+ l.status,
25430
+ l.attachments,
25431
+ cp.company_id,
25432
+ cp.role AS company_role,
25433
+ c.name AS company_name,
25434
+ c.legal_name AS company_legal_name,
25435
+ c.document_number AS company_document,
25436
+ -- 049: o @ vem direto de \`people\`, e N\xC3O de \`v_leads\`.
25437
+ --
25438
+ -- A \`v_leads\` \xE9 criada pela 023 com \`CREATE OR REPLACE\` e colunas
25439
+ -- nomeadas, sem DROP antes. Acrescentar uma coluna l\xE1 faz o REPLAY da
25440
+ -- 023 falhar com \`cannot drop columns from view\` \u2014 ela roda de novo, com
25441
+ -- a lista antiga, sobre a view j\xE1 alargada. Foi o que o db-from-zero
25442
+ -- pegou.
25443
+ --
25444
+ -- Esta view n\xE3o tem esse problema: a 013 a derruba antes de criar. Ent\xE3o
25445
+ -- o lugar certo de alargar \xE9 aqui, e a fonte \xE9 a tabela.
25446
+ pess.instagram
25447
+ FROM v_leads l
25448
+ LEFT JOIN people pess ON pess.id = l.id
25449
+ LEFT JOIN LATERAL ( SELECT x.company_id,
25450
+ x.role
25451
+ FROM plg_crm_company_people x
25452
+ WHERE x.person_id = l.id
25453
+ ORDER BY x.is_primary DESC, x.created_at
25454
+ LIMIT 1) cp ON true
25455
+ LEFT JOIN plg_crm_companies c ON c.id = cp.company_id;
25456
+
25457
+ GRANT SELECT ON public.v_crm_leads TO authenticated, service_role;
25458
+ `;
25230
25459
  var MIGRATIONS = [
25231
25460
  { id: "000_baseline", sql: MIGRATION_000_BASELINE },
25232
25461
  { id: "001_de_onde_veio_e_quem_indicou", sql: MIGRATION_001_DE_ONDE_VEIO_E_QUEM_INDICOU },
@@ -25274,7 +25503,9 @@ var MIGRATIONS = [
25274
25503
  { id: "044_o_status_nao_e_um_acontecimento", sql: MIGRATION_044_O_STATUS_NAO_E_UM_ACONTECIMENTO },
25275
25504
  { id: "045_contato_feito_e_contato_que_alguem_fez", sql: MIGRATION_045_CONTATO_FEITO_E_CONTATO_QUE_ALGUEM_FEZ },
25276
25505
  { id: "046_a_pastilha_do_card_so_fala_quando_tem_o_que_dizer", sql: MIGRATION_046_A_PASTILHA_DO_CARD_SO_FALA_QUANDO_TEM_O_QUE_DIZER },
25277
- { id: "047_o_dono_do_lead_tem_um_lugar_so", sql: MIGRATION_047_O_DONO_DO_LEAD_TEM_UM_LUGAR_SO }
25506
+ { id: "047_o_dono_do_lead_tem_um_lugar_so", sql: MIGRATION_047_O_DONO_DO_LEAD_TEM_UM_LUGAR_SO },
25507
+ { id: "048_a_empresa_tambem_tem_um_arroba", sql: MIGRATION_048_A_EMPRESA_TAMBEM_TEM_UM_ARROBA },
25508
+ { id: "049_o_arroba_chega_ate_a_lista", sql: MIGRATION_049_O_ARROBA_CHEGA_ATE_A_LISTA }
25278
25509
  ];
25279
25510
 
25280
25511
  // src/locales/en.ts
@@ -25396,6 +25627,11 @@ var en = {
25396
25627
  "crm.leadForm.namePlaceholder": "Contact name",
25397
25628
  "crm.leadForm.notes": "Notes",
25398
25629
  "crm.leadForm.notesPlaceholder": "Additional notes...",
25630
+ "crm.leadForm.instagram": "Instagram",
25631
+ "crm.leadForm.instagramPlaceholder": "@handle or link",
25632
+ "crm.leadDetail.instagram": "Instagram",
25633
+ "crm.companyForm.instagram": "Instagram",
25634
+ "crm.companyDetail.instagram": "Instagram",
25399
25635
  "crm.leadForm.phone": "Phone",
25400
25636
  "crm.leadForm.phonePlaceholder": "+55 11 99999-9999",
25401
25637
  "crm.leadForm.source": "Source",
@@ -26186,6 +26422,11 @@ var ptBR = {
26186
26422
  "crm.leadForm.namePlaceholder": "Nome do contato",
26187
26423
  "crm.leadForm.notes": "Observa\xE7\xF5es",
26188
26424
  "crm.leadForm.notesPlaceholder": "Observa\xE7\xF5es adicionais...",
26425
+ "crm.leadForm.instagram": "Instagram",
26426
+ "crm.leadForm.instagramPlaceholder": "@perfil ou link",
26427
+ "crm.leadDetail.instagram": "Instagram",
26428
+ "crm.companyForm.instagram": "Instagram",
26429
+ "crm.companyDetail.instagram": "Instagram",
26189
26430
  "crm.leadForm.phone": "Telefone",
26190
26431
  "crm.leadForm.phonePlaceholder": "+55 11 99999-9999",
26191
26432
  "crm.leadForm.source": "Origem",