@businesskit/agent 1.0.4 → 1.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/.cursor-plugin/plugin.json +25 -0
- package/.cursorrules +10 -0
- package/.superconsole-plugin/plugin.json +32 -0
- package/AGENTS.md +94 -63
- package/CLAUDE.md +11 -84
- package/GEMINI.md +11 -34
- package/README.md +106 -153
- package/assets/logo.svg +3 -0
- package/bin/businesskit.js +11 -17
- package/commands/add-contact.md +47 -0
- package/commands/add-inventory-from-invoice.md +80 -0
- package/commands/adjust-stock.md +46 -0
- package/commands/capabilities.md +33 -0
- package/commands/check-stock.md +43 -0
- package/commands/create-component.md +109 -0
- package/commands/create-invoice.md +69 -0
- package/commands/create-new-bill.md +65 -0
- package/commands/create-page.md +96 -0
- package/commands/list-components.md +41 -0
- package/commands/list-content.md +46 -0
- package/commands/list-pages.md +45 -0
- package/commands/publish-page.md +64 -0
- package/commands/send-invoice.md +42 -0
- package/commands/seo-audit.md +36 -0
- package/commands/update-contact.md +46 -0
- package/commands/update-content.md +47 -0
- package/commands/update-page.md +55 -0
- package/commands/update-price.md +47 -0
- package/commands/write-blog.md +52 -0
- package/commands/write-docs.md +84 -0
- package/commands/write-guide.md +46 -0
- package/commands/write-newsletter.md +46 -0
- package/mcp_config.json +8 -0
- package/package.json +34 -23
- package/plugin.json +32 -0
- package/scripts/setup.sh +134 -0
- package/scripts/setup.ts +92 -0
- package/server.json +21 -0
- package/skills/README.md +19 -27
- package/skills/billing/SKILL.md +64 -0
- package/skills/brand/SKILL.md +30 -86
- package/skills/copywriting/SKILL.md +1 -1
- package/skills/crm/SKILL.md +38 -0
- package/skills/docs-cms/SKILL.md +53 -0
- package/skills/docs-cms/references/how-to.md +383 -0
- package/skills/inbox/SKILL.md +49 -0
- package/skills/inventory/SKILL.md +69 -0
- package/skills/pages/SKILL.md +169 -0
- package/skills/pages/references/sections-catalog.json +950 -0
- package/skills/social/SKILL.md +1 -1
- package/templates/antigravity.json +8 -0
- package/templates/claude-code.mcp.json +8 -0
- package/templates/cursor.mcp.json +8 -0
- package/templates/vscode.mcp.json +9 -0
- package/.claude/commands/analytics.md +0 -7
- package/.claude/commands/blog-writer.md +0 -9
- package/.claude/commands/cbo.md +0 -7
- package/.claude/commands/ceo.md +0 -10
- package/.claude/commands/cmo.md +0 -7
- package/.claude/commands/compress.md +0 -73
- package/.claude/commands/coo.md +0 -11
- package/.claude/commands/copywriter.md +0 -15
- package/.claude/commands/course-creator.md +0 -9
- package/.claude/commands/crm.md +0 -591
- package/.claude/commands/deep.md +0 -50
- package/.claude/commands/docs-writer.md +0 -8
- package/.claude/commands/forms-builder.md +0 -10
- package/.claude/commands/ingest.md +0 -110
- package/.claude/commands/jobs-manager.md +0 -8
- package/.claude/commands/kb.md +0 -107
- package/.claude/commands/newsletter-writer.md +0 -9
- package/.claude/commands/preserve.md +0 -64
- package/.claude/commands/resume.md +0 -67
- package/.claude/commands/scheduler.md +0 -8
- package/.claude/commands/seo.md +0 -60
- package/.claude/commands/social.md +0 -51
- package/.claude/commands/store-manager.md +0 -11
- package/.claude/settings.json +0 -16
- package/.claude/settings.local.json +0 -11
- package/.env.example +0 -12
- package/.mcp.json +0 -3
- package/HEARTBEAT.md +0 -105
- package/PLAN.md +0 -345
- package/PRD-Agent-Composition.md +0 -149
- package/PRD-Agent-Harness.md +0 -316
- package/REFERENCE.md +0 -160
- package/SOUL.md +0 -148
- package/SYSTEM.md +0 -71
- package/agents/_base.ts +0 -371
- package/agents/analytics/SOUL.md +0 -11
- package/agents/analytics/analytics.ts +0 -405
- package/agents/business/SOUL.md +0 -11
- package/agents/business/business.ts +0 -109
- package/agents/ceo/SOUL.md +0 -15
- package/agents/ceo/ceo.ts +0 -146
- package/agents/content/SOUL.md +0 -11
- package/agents/content/content.ts +0 -379
- package/agents/copywriting/SOUL.md +0 -11
- package/agents/copywriting/copywriting.ts +0 -89
- package/agents/courses/SOUL.md +0 -11
- package/agents/courses/courses.ts +0 -451
- package/agents/docs/SOUL.md +0 -11
- package/agents/docs/docs.ts +0 -77
- package/agents/forms/SOUL.md +0 -11
- package/agents/forms/forms.ts +0 -364
- package/agents/hiring/SOUL.md +0 -11
- package/agents/hiring/hiring.ts +0 -314
- package/agents/marketing/SOUL.md +0 -15
- package/agents/marketing/marketing.ts +0 -109
- package/agents/newsletter/SOUL.md +0 -11
- package/agents/newsletter/newsletter.ts +0 -91
- package/agents/operations/SOUL.md +0 -11
- package/agents/operations/operations.ts +0 -157
- package/agents/sales/SOUL.md +0 -44
- package/agents/sales/sales.ts +0 -883
- package/agents/scheduler/SOUL.md +0 -11
- package/agents/scheduler/scheduler.ts +0 -68
- package/agents/seo/SOUL.md +0 -11
- package/agents/seo/seo.ts +0 -288
- package/agents/social/SOUL.md +0 -11
- package/agents/social/social.ts +0 -744
- package/agents/store/SOUL.md +0 -11
- package/agents/store/store.ts +0 -514
- package/cli.ts +0 -144
- package/context/about-me.md +0 -96
- package/context/brand-voice.md +0 -127
- package/context/brand.md +0 -80
- package/context/business.md +0 -66
- package/context/working-style.md +0 -87
- package/lib/analytics.ts +0 -81
- package/lib/cms.ts +0 -88
- package/lib/db.adapter.ts +0 -30
- package/lib/db.ts +0 -63
- package/lib/enums.ts +0 -25
- package/lib/groups.ts +0 -122
- package/lib/id.ts +0 -43
- package/lib/kb.ts +0 -337
- package/lib/memory.ts +0 -219
- package/lib/pattern-detector.ts +0 -169
- package/lib/profile.ts +0 -155
- package/lib/schema.ts +0 -2015
- package/lib/slug.ts +0 -30
- package/lib/validate.ts +0 -33
- package/setup.ts +0 -141
- package/skills/agents/SKILL.md +0 -56
- package/skills/analytics/SKILL.md +0 -52
- package/skills/blog-writer/SKILL.md +0 -452
- package/skills/ceo/SKILL.md +0 -25
- package/skills/cmo/SKILL.md +0 -8
- package/skills/schema/SKILL.md +0 -86
- package/skills/store/SKILL.md +0 -62
- package/tsconfig.json +0 -14
package/agents/sales/sales.ts
DELETED
|
@@ -1,883 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Sales (CRM) Agent — Agent-First CRM
|
|
3
|
-
*
|
|
4
|
-
* Reads crm_contacts.agent_context blob for per-contact memory.
|
|
5
|
-
* Drives the full outreach pipeline: research → enrich → DM draft → send → follow-up.
|
|
6
|
-
* Writes crm_activities as an append-only interaction log.
|
|
7
|
-
* Updates crm_analytics via DB triggers (defined app-side in crm.ts).
|
|
8
|
-
*
|
|
9
|
-
* agent_status lifecycle:
|
|
10
|
-
* pending → researching → enriched → outreach_ready → closed
|
|
11
|
-
*
|
|
12
|
-
* approval_status on activities:
|
|
13
|
-
* pending_approval → agent drafts, waits for user
|
|
14
|
-
* approved → user confirmed, agent sends
|
|
15
|
-
* auto_sent → auto_approve=1 on contact, sent without waiting
|
|
16
|
-
* rejected → user rejected the draft
|
|
17
|
-
*
|
|
18
|
-
* DB contract (must match app-side crm.ts):
|
|
19
|
-
* - Every mutation filters by profile_id (enforced here).
|
|
20
|
-
* - crm_activities is append-only — DELETE blocked by trigger; UPDATE allowed
|
|
21
|
-
* only on approval_status and read_at.
|
|
22
|
-
* - crm_analytics is trigger-managed; never written directly.
|
|
23
|
-
* - Groups: crm_contact_groups junction (via lib/groups.ts). Never LIKE '%grp_%'.
|
|
24
|
-
* - Idempotency: activities/tasks/notes/proposals/invoices have unique
|
|
25
|
-
* idempotency_key indexes; we write INSERT OR IGNORE on retries.
|
|
26
|
-
*/
|
|
27
|
-
|
|
28
|
-
import { BaseAgent, db, ulid, iso, now } from '../_base.ts'
|
|
29
|
-
import { CRM_DEAL_STAGE, type CRMDealStage } from '../../lib/enums.ts'
|
|
30
|
-
import { leadScore as vLeadScore, probability as vProbability, cents as vCents } from '../../lib/validate.ts'
|
|
31
|
-
import { addContactToGroup, getContactsByGroup, getGroupsForContact, removeContactFromGroup, hasGroupsJunction } from '../../lib/groups.ts'
|
|
32
|
-
import { generateIdempotencyKey } from '../../lib/id.ts'
|
|
33
|
-
|
|
34
|
-
// ── Types ─────────────────────────────────────────────────────────────────────
|
|
35
|
-
|
|
36
|
-
export type ContactStatus = 'lead' | 'prospect' | 'customer' | 'churned' | 'archived'
|
|
37
|
-
export type ActivityType = 'dm' | 'email' | 'call' | 'meeting' | 'note' | 'task_done' | 'purchase' | 'form_submission' | 'agent_action'
|
|
38
|
-
export type ActivityDirection = 'inbound' | 'outbound'
|
|
39
|
-
export type ActivitySender = 'agent' | 'you' | 'contact'
|
|
40
|
-
export type ApprovalStatus = 'pending_approval' | 'approved' | 'rejected' | 'auto_sent'
|
|
41
|
-
export type OutreachStatus =
|
|
42
|
-
| 'new' | 'dm_drafted' | 'dm_sent' | 'email_drafted' | 'email_sent'
|
|
43
|
-
| 'replied' | 'call_booked' | 'demo_done' | 'converted' | 'not_interested'
|
|
44
|
-
|
|
45
|
-
export interface Contact {
|
|
46
|
-
id: string
|
|
47
|
-
profile_id: string
|
|
48
|
-
first_name: string
|
|
49
|
-
last_name: string | null
|
|
50
|
-
email: string | null
|
|
51
|
-
platform: string | null
|
|
52
|
-
platform_username: string | null
|
|
53
|
-
platform_url: string | null
|
|
54
|
-
status: ContactStatus
|
|
55
|
-
outreach_status: OutreachStatus
|
|
56
|
-
lead_score: number
|
|
57
|
-
icp_match: string
|
|
58
|
-
agent_status: string
|
|
59
|
-
agent_context: Record<string, unknown>
|
|
60
|
-
auto_approve: number
|
|
61
|
-
suggested_dm: string | null
|
|
62
|
-
email_draft: string | null
|
|
63
|
-
is_duplicate: number
|
|
64
|
-
duplicate_of: string | null
|
|
65
|
-
archived: number
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
export interface CreateContactInput {
|
|
69
|
-
first_name: string
|
|
70
|
-
last_name?: string
|
|
71
|
-
email?: string
|
|
72
|
-
phone?: string
|
|
73
|
-
company?: string
|
|
74
|
-
job_title?: string
|
|
75
|
-
platform?: string
|
|
76
|
-
platform_username?: string
|
|
77
|
-
platform_url?: string
|
|
78
|
-
bio?: string
|
|
79
|
-
audience_size?: number
|
|
80
|
-
source?: 'manual' | 'form' | 'import' | 'subscriber' | 'purchase' | 'agent_research' | 'n8n_webhook'
|
|
81
|
-
source_id?: string
|
|
82
|
-
tags?: string[]
|
|
83
|
-
notes?: string
|
|
84
|
-
idempotency_key?: string
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
export class CRMAgent extends BaseAgent {
|
|
88
|
-
readonly name = 'Sales'
|
|
89
|
-
readonly title = 'Sales (CRM) Agent'
|
|
90
|
-
|
|
91
|
-
// ── Contacts ─────────────────────────────────────────────────────────────────
|
|
92
|
-
|
|
93
|
-
async createContact(input: CreateContactInput): Promise<string> {
|
|
94
|
-
await this.init()
|
|
95
|
-
const id = ulid()
|
|
96
|
-
const ts = now()
|
|
97
|
-
|
|
98
|
-
await db.write({
|
|
99
|
-
sql: `INSERT INTO crm_contacts
|
|
100
|
-
(id,profile_id,user_id,first_name,last_name,email,phone,company,
|
|
101
|
-
job_title,platform,platform_username,platform_url,bio,audience_size,
|
|
102
|
-
source,source_id,tags,notes,agent_status,agent_context,
|
|
103
|
-
created_at,updated_at)
|
|
104
|
-
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,'pending','{}',?,?)`,
|
|
105
|
-
args: [
|
|
106
|
-
id, this.profileId, this.userId,
|
|
107
|
-
input.first_name, input.last_name ?? null,
|
|
108
|
-
input.email ?? null, input.phone ?? null,
|
|
109
|
-
input.company ?? null, input.job_title ?? null,
|
|
110
|
-
input.platform ?? null, input.platform_username ?? null,
|
|
111
|
-
input.platform_url ?? null, input.bio ?? null,
|
|
112
|
-
input.audience_size ?? null,
|
|
113
|
-
input.source ?? 'manual', input.source_id ?? null,
|
|
114
|
-
input.tags ? JSON.stringify(input.tags) : '[]',
|
|
115
|
-
input.notes ?? null, ts, ts,
|
|
116
|
-
],
|
|
117
|
-
})
|
|
118
|
-
return id
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
async getContact(id: string): Promise<Contact> {
|
|
122
|
-
await this.init()
|
|
123
|
-
const { rows: [r] } = await db.execute({
|
|
124
|
-
sql: 'SELECT * FROM crm_contacts WHERE id=? AND profile_id=? LIMIT 1',
|
|
125
|
-
args: [id, this.profileId],
|
|
126
|
-
})
|
|
127
|
-
if (!r) throw new Error(`Contact not found: ${id}`)
|
|
128
|
-
return this.parseContact(r)
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
async listContacts(opts: {
|
|
132
|
-
status?: ContactStatus
|
|
133
|
-
outreach_status?: OutreachStatus
|
|
134
|
-
agent_status?: string
|
|
135
|
-
limit?: number
|
|
136
|
-
order_by?: 'lead_score' | 'created_at' | 'next_follow_up_at'
|
|
137
|
-
} = {}) {
|
|
138
|
-
await this.init()
|
|
139
|
-
const args: unknown[] = [this.profileId]
|
|
140
|
-
let where = 'WHERE profile_id=? AND archived=0'
|
|
141
|
-
|
|
142
|
-
if (opts.status) { where += ' AND status=?'; args.push(opts.status) }
|
|
143
|
-
if (opts.outreach_status) { where += ' AND outreach_status=?'; args.push(opts.outreach_status) }
|
|
144
|
-
if (opts.agent_status) { where += ' AND agent_status=?'; args.push(opts.agent_status) }
|
|
145
|
-
|
|
146
|
-
const orderMap = {
|
|
147
|
-
lead_score: 'lead_score DESC',
|
|
148
|
-
created_at: 'created_at DESC',
|
|
149
|
-
next_follow_up_at: 'next_follow_up_at ASC',
|
|
150
|
-
}
|
|
151
|
-
const order = orderMap[opts.order_by ?? 'created_at']
|
|
152
|
-
|
|
153
|
-
const { rows } = await db.execute({
|
|
154
|
-
sql: `SELECT id,first_name,last_name,email,platform,platform_username,
|
|
155
|
-
status,outreach_status,agent_status,lead_score,icp_match,
|
|
156
|
-
suggested_dm,next_follow_up_at,total_spent_cents,total_purchases,
|
|
157
|
-
is_duplicate,duplicate_of
|
|
158
|
-
FROM crm_contacts ${where} ORDER BY ${order} LIMIT ?`,
|
|
159
|
-
args: [...args, opts.limit ?? 50],
|
|
160
|
-
})
|
|
161
|
-
return rows
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
/** Soft-archive a contact (hidden from lists, never hard-deleted). */
|
|
165
|
-
async archiveContact(id: string): Promise<void> {
|
|
166
|
-
await this.init()
|
|
167
|
-
await db.write({
|
|
168
|
-
sql: `UPDATE crm_contacts SET archived=1,status='archived',updated_at=?
|
|
169
|
-
WHERE id=? AND profile_id=?`,
|
|
170
|
-
args: [now(), id, this.profileId],
|
|
171
|
-
})
|
|
172
|
-
await this.logActivity(id, 'agent_action', 'outbound', 'agent', 'Contact archived')
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
async disqualifyContact(id: string, reason: string): Promise<void> {
|
|
176
|
-
await this.init()
|
|
177
|
-
await db.write({
|
|
178
|
-
sql: `UPDATE crm_contacts SET disqualified=1,disqualified_reason=?,
|
|
179
|
-
agent_status='closed',updated_at=? WHERE id=? AND profile_id=?`,
|
|
180
|
-
args: [reason, now(), id, this.profileId],
|
|
181
|
-
})
|
|
182
|
-
await this.logActivity(id, 'agent_action', 'outbound', 'agent', `Disqualified: ${reason}`)
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
// ── Lead scoring + enrichment ─────────────────────────────────────────────
|
|
186
|
-
|
|
187
|
-
async scoreContact(id: string, score: number, reason: string, icpMatch: 'strong' | 'moderate' | 'weak') {
|
|
188
|
-
await this.init()
|
|
189
|
-
const bounded = vLeadScore(score) // P0-8: catches out-of-range before DB trigger
|
|
190
|
-
await db.write({
|
|
191
|
-
sql: `UPDATE crm_contacts SET
|
|
192
|
-
lead_score=?,lead_score_reason=?,icp_match=?,
|
|
193
|
-
agent_status='enriched',updated_at=? WHERE id=? AND profile_id=?`,
|
|
194
|
-
args: [bounded, reason, icpMatch, now(), id, this.profileId],
|
|
195
|
-
})
|
|
196
|
-
await this.logActivity(id, 'agent_action', 'outbound', 'agent',
|
|
197
|
-
`Scored: ${bounded}/100 (${icpMatch} ICP) — ${reason}`)
|
|
198
|
-
return this.getContact(id)
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
async enrichContact(id: string, enrichment: {
|
|
202
|
-
pain_point?: string
|
|
203
|
-
company_size?: string
|
|
204
|
-
industry?: string
|
|
205
|
-
business_model?: string
|
|
206
|
-
estimated_revenue?: string
|
|
207
|
-
recent_post?: string
|
|
208
|
-
recent_post_url?: string
|
|
209
|
-
enrichment_source?: string
|
|
210
|
-
}) {
|
|
211
|
-
await this.init()
|
|
212
|
-
const ts = now()
|
|
213
|
-
const sets: string[] = ['enriched_at=?', 'updated_at=?', "agent_status='enriched'"]
|
|
214
|
-
const args: unknown[] = [ts, ts]
|
|
215
|
-
|
|
216
|
-
const fieldMap: Record<string, string> = {
|
|
217
|
-
pain_point: 'pain_point', company_size: 'company_size',
|
|
218
|
-
industry: 'industry', business_model: 'business_model',
|
|
219
|
-
estimated_revenue: 'estimated_revenue',
|
|
220
|
-
recent_post: 'recent_post', recent_post_url: 'recent_post_url',
|
|
221
|
-
enrichment_source: 'enrichment_source',
|
|
222
|
-
}
|
|
223
|
-
for (const [k, col] of Object.entries(fieldMap)) {
|
|
224
|
-
if ((enrichment as any)[k] !== undefined) {
|
|
225
|
-
sets.push(`${col}=?`)
|
|
226
|
-
args.push((enrichment as any)[k])
|
|
227
|
-
}
|
|
228
|
-
}
|
|
229
|
-
args.push(id, this.profileId)
|
|
230
|
-
|
|
231
|
-
await db.write({
|
|
232
|
-
sql: `UPDATE crm_contacts SET ${sets.join(',')} WHERE id=? AND profile_id=?`,
|
|
233
|
-
args,
|
|
234
|
-
})
|
|
235
|
-
return this.getContact(id)
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
// ── Outreach ──────────────────────────────────────────────────────────────
|
|
239
|
-
|
|
240
|
-
/** Draft a DM. Stores in suggested_dm + creates a pending activity
|
|
241
|
-
* (or auto_sent if contact.auto_approve=1). */
|
|
242
|
-
async draftDM(id: string, message: string): Promise<void> {
|
|
243
|
-
await this.init()
|
|
244
|
-
const contact = await this.getContact(id)
|
|
245
|
-
|
|
246
|
-
await db.write({
|
|
247
|
-
sql: `UPDATE crm_contacts SET
|
|
248
|
-
suggested_dm=?,outreach_status='dm_drafted',
|
|
249
|
-
agent_status='outreach_ready',updated_at=? WHERE id=? AND profile_id=?`,
|
|
250
|
-
args: [message, now(), id, this.profileId],
|
|
251
|
-
})
|
|
252
|
-
|
|
253
|
-
const approval_status: ApprovalStatus = contact.auto_approve ? 'auto_sent' : 'pending_approval'
|
|
254
|
-
await this.logActivity(id, 'dm', 'outbound', 'agent', message, {
|
|
255
|
-
approval_status,
|
|
256
|
-
channel: contact.platform ?? 'dm',
|
|
257
|
-
})
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
/** Draft a cold email. */
|
|
261
|
-
async draftEmail(id: string, subject: string, body: string): Promise<void> {
|
|
262
|
-
await this.init()
|
|
263
|
-
const contact = await this.getContact(id)
|
|
264
|
-
|
|
265
|
-
await db.write({
|
|
266
|
-
sql: `UPDATE crm_contacts SET
|
|
267
|
-
email_subject=?,email_draft=?,outreach_status='email_drafted',
|
|
268
|
-
agent_status='outreach_ready',updated_at=? WHERE id=? AND profile_id=?`,
|
|
269
|
-
args: [subject, body, now(), id, this.profileId],
|
|
270
|
-
})
|
|
271
|
-
|
|
272
|
-
const approval_status: ApprovalStatus = contact.auto_approve ? 'auto_sent' : 'pending_approval'
|
|
273
|
-
await this.logActivity(id, 'email', 'outbound', 'agent', body, {
|
|
274
|
-
subject, approval_status,
|
|
275
|
-
})
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
/** Approve a pending activity. Flips approval_status → approved. */
|
|
279
|
-
async approveActivity(activityId: string): Promise<void> {
|
|
280
|
-
await this.init()
|
|
281
|
-
await db.write({
|
|
282
|
-
sql: `UPDATE crm_activities SET approval_status='approved',approved_at=?
|
|
283
|
-
WHERE id=? AND profile_id=? AND approval_status='pending_approval'`,
|
|
284
|
-
args: [now(), activityId, this.profileId],
|
|
285
|
-
})
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
/** Reject a pending activity. Flips approval_status → rejected. */
|
|
289
|
-
async rejectActivity(activityId: string): Promise<void> {
|
|
290
|
-
await this.init()
|
|
291
|
-
await db.write({
|
|
292
|
-
sql: `UPDATE crm_activities SET approval_status='rejected'
|
|
293
|
-
WHERE id=? AND profile_id=? AND approval_status='pending_approval'`,
|
|
294
|
-
args: [activityId, this.profileId],
|
|
295
|
-
})
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
/** Mark DM as sent (after user approves + actually sends). */
|
|
299
|
-
async markDMSent(id: string): Promise<void> {
|
|
300
|
-
await this.init()
|
|
301
|
-
const ts = now()
|
|
302
|
-
await db.write({
|
|
303
|
-
sql: `UPDATE crm_contacts SET
|
|
304
|
-
dm_sent=1,dm_sent_at=?,outreach_status='dm_sent',
|
|
305
|
-
outreach_attempts=outreach_attempts+1,last_contacted_at=?,updated_at=?
|
|
306
|
-
WHERE id=? AND profile_id=?`,
|
|
307
|
-
args: [ts, ts, ts, id, this.profileId],
|
|
308
|
-
})
|
|
309
|
-
}
|
|
310
|
-
|
|
311
|
-
/** Mark email as sent. */
|
|
312
|
-
async markEmailSent(id: string): Promise<void> {
|
|
313
|
-
await this.init()
|
|
314
|
-
const ts = now()
|
|
315
|
-
await db.write({
|
|
316
|
-
sql: `UPDATE crm_contacts SET
|
|
317
|
-
email_sent=1,email_sent_at=?,outreach_status='email_sent',
|
|
318
|
-
outreach_attempts=outreach_attempts+1,last_contacted_at=?,updated_at=?
|
|
319
|
-
WHERE id=? AND profile_id=?`,
|
|
320
|
-
args: [ts, ts, ts, id, this.profileId],
|
|
321
|
-
})
|
|
322
|
-
}
|
|
323
|
-
|
|
324
|
-
/** Log an inbound reply. Triggers increment total_replies + reply_rate_pct. */
|
|
325
|
-
async logReply(
|
|
326
|
-
id: string,
|
|
327
|
-
channel: 'dm' | 'email',
|
|
328
|
-
content: string,
|
|
329
|
-
sentiment: 'positive' | 'neutral' | 'negative',
|
|
330
|
-
) {
|
|
331
|
-
await this.init()
|
|
332
|
-
const ts = now()
|
|
333
|
-
await db.write({
|
|
334
|
-
sql: `UPDATE crm_contacts SET
|
|
335
|
-
outreach_status='replied',last_reply_at=?,last_reply_channel=?,
|
|
336
|
-
reply_sentiment=?,last_activity_at=?,updated_at=?
|
|
337
|
-
WHERE id=? AND profile_id=?`,
|
|
338
|
-
args: [ts, channel, sentiment, ts, ts, id, this.profileId],
|
|
339
|
-
})
|
|
340
|
-
await this.logActivity(id, channel === 'dm' ? 'dm' : 'email', 'inbound', 'contact', content)
|
|
341
|
-
}
|
|
342
|
-
|
|
343
|
-
/** Mark outreach status transitions that schema supports but weren't wired. */
|
|
344
|
-
async markCallBooked(id: string, note?: string): Promise<void> {
|
|
345
|
-
await this.setOutreachStatus(id, 'call_booked')
|
|
346
|
-
await this.logActivity(id, 'meeting', 'outbound', 'agent', note ?? 'Call booked')
|
|
347
|
-
}
|
|
348
|
-
|
|
349
|
-
async markConverted(id: string): Promise<void> {
|
|
350
|
-
await this.init()
|
|
351
|
-
const ts = now()
|
|
352
|
-
await db.write({
|
|
353
|
-
sql: `UPDATE crm_contacts SET
|
|
354
|
-
outreach_status='converted',status='customer',
|
|
355
|
-
agent_status='closed',updated_at=? WHERE id=? AND profile_id=?`,
|
|
356
|
-
args: [ts, id, this.profileId],
|
|
357
|
-
})
|
|
358
|
-
await this.logActivity(id, 'agent_action', 'outbound', 'agent', 'Converted to customer')
|
|
359
|
-
}
|
|
360
|
-
|
|
361
|
-
async markNotInterested(id: string, reason?: string): Promise<void> {
|
|
362
|
-
await this.setOutreachStatus(id, 'not_interested')
|
|
363
|
-
await this.logActivity(id, 'agent_action', 'outbound', 'agent',
|
|
364
|
-
reason ? `Not interested: ${reason}` : 'Not interested')
|
|
365
|
-
}
|
|
366
|
-
|
|
367
|
-
private async setOutreachStatus(id: string, status: OutreachStatus): Promise<void> {
|
|
368
|
-
await this.init()
|
|
369
|
-
await db.write({
|
|
370
|
-
sql: `UPDATE crm_contacts SET outreach_status=?,updated_at=?
|
|
371
|
-
WHERE id=? AND profile_id=?`,
|
|
372
|
-
args: [status, now(), id, this.profileId],
|
|
373
|
-
})
|
|
374
|
-
}
|
|
375
|
-
|
|
376
|
-
// ── Deals ──────────────────────────────────────────────────────────────────
|
|
377
|
-
|
|
378
|
-
async createDeal(contactId: string, input: {
|
|
379
|
-
title: string
|
|
380
|
-
value_cents: number
|
|
381
|
-
stage?: CRMDealStage
|
|
382
|
-
probability?: number
|
|
383
|
-
product_id?: string
|
|
384
|
-
expected_close_at?: number
|
|
385
|
-
}): Promise<string> {
|
|
386
|
-
await this.init()
|
|
387
|
-
// P0-5 + P0-8: validate enum + numeric bounds before DB trigger rejects
|
|
388
|
-
const stage = input.stage ?? 'new'
|
|
389
|
-
if (!CRM_DEAL_STAGE.includes(stage)) throw new Error(`Invalid deal stage: ${stage}`)
|
|
390
|
-
const value = vCents(input.value_cents)
|
|
391
|
-
const prob = vProbability(input.probability ?? 10)
|
|
392
|
-
|
|
393
|
-
const id = ulid()
|
|
394
|
-
const ts = now()
|
|
395
|
-
await db.write({
|
|
396
|
-
sql: `INSERT INTO crm_deals
|
|
397
|
-
(id,profile_id,contact_id,title,value_cents,stage,probability,product_id,
|
|
398
|
-
expected_close_at,created_at,updated_at)
|
|
399
|
-
VALUES (?,?,?,?,?,?,?,?,?,?,?)`,
|
|
400
|
-
args: [
|
|
401
|
-
id, this.profileId, contactId,
|
|
402
|
-
input.title, value, stage, prob,
|
|
403
|
-
input.product_id ?? null, input.expected_close_at ?? null,
|
|
404
|
-
ts, ts,
|
|
405
|
-
],
|
|
406
|
-
})
|
|
407
|
-
return id
|
|
408
|
-
}
|
|
409
|
-
|
|
410
|
-
async updateDealStage(dealId: string, stage: CRMDealStage, lostReason?: string) {
|
|
411
|
-
await this.init()
|
|
412
|
-
if (!CRM_DEAL_STAGE.includes(stage)) throw new Error(`Invalid deal stage: ${stage}`)
|
|
413
|
-
const ts = now()
|
|
414
|
-
const closedAt = stage === 'won' || stage === 'lost' ? ts : null
|
|
415
|
-
await db.write({
|
|
416
|
-
sql: `UPDATE crm_deals SET stage=?,lost_reason=?,closed_at=?,updated_at=?
|
|
417
|
-
WHERE id=? AND profile_id=?`,
|
|
418
|
-
args: [stage, lostReason ?? null, closedAt, ts, dealId, this.profileId],
|
|
419
|
-
})
|
|
420
|
-
}
|
|
421
|
-
|
|
422
|
-
async listDeals(opts: { stage?: CRMDealStage; contact_id?: string } = {}) {
|
|
423
|
-
await this.init()
|
|
424
|
-
let where = 'WHERE d.profile_id=?'
|
|
425
|
-
const args: unknown[] = [this.profileId]
|
|
426
|
-
if (opts.stage) { where += ' AND d.stage=?'; args.push(opts.stage) }
|
|
427
|
-
if (opts.contact_id) { where += ' AND d.contact_id=?'; args.push(opts.contact_id) }
|
|
428
|
-
|
|
429
|
-
const { rows } = await db.execute({
|
|
430
|
-
sql: `SELECT d.*,c.first_name,c.last_name,c.company
|
|
431
|
-
FROM crm_deals d
|
|
432
|
-
JOIN crm_contacts c ON c.id=d.contact_id
|
|
433
|
-
${where} ORDER BY d.created_at DESC`,
|
|
434
|
-
args,
|
|
435
|
-
})
|
|
436
|
-
return rows
|
|
437
|
-
}
|
|
438
|
-
|
|
439
|
-
// ── Tasks ─────────────────────────────────────────────────────────────────
|
|
440
|
-
|
|
441
|
-
async createTask(input: {
|
|
442
|
-
title: string
|
|
443
|
-
contact_id?: string
|
|
444
|
-
deal_id?: string
|
|
445
|
-
due_at?: number
|
|
446
|
-
priority?: 'low' | 'medium' | 'high'
|
|
447
|
-
description?: string
|
|
448
|
-
idempotency_key?: string
|
|
449
|
-
}): Promise<string> {
|
|
450
|
-
await this.init()
|
|
451
|
-
const id = ulid()
|
|
452
|
-
const ts = now()
|
|
453
|
-
const ikey = input.idempotency_key ?? generateIdempotencyKey()
|
|
454
|
-
|
|
455
|
-
await db.write({
|
|
456
|
-
sql: `INSERT OR IGNORE INTO crm_tasks
|
|
457
|
-
(id,profile_id,contact_id,deal_id,title,description,due_at,priority,
|
|
458
|
-
status,idempotency_key,created_at,updated_at)
|
|
459
|
-
VALUES (?,?,?,?,?,?,?,?,'open',?,?,?)`,
|
|
460
|
-
args: [
|
|
461
|
-
id, this.profileId,
|
|
462
|
-
input.contact_id ?? null, input.deal_id ?? null,
|
|
463
|
-
input.title, input.description ?? null,
|
|
464
|
-
input.due_at ?? null, input.priority ?? 'medium',
|
|
465
|
-
ikey, ts, ts,
|
|
466
|
-
],
|
|
467
|
-
})
|
|
468
|
-
return id
|
|
469
|
-
}
|
|
470
|
-
|
|
471
|
-
async completeTask(id: string) {
|
|
472
|
-
await this.init()
|
|
473
|
-
const ts = now()
|
|
474
|
-
await db.write({
|
|
475
|
-
sql: `UPDATE crm_tasks SET status='done',completed_at=?,updated_at=?
|
|
476
|
-
WHERE id=? AND profile_id=?`,
|
|
477
|
-
args: [ts, ts, id, this.profileId],
|
|
478
|
-
})
|
|
479
|
-
}
|
|
480
|
-
|
|
481
|
-
async listTasks(opts: { status?: 'open' | 'done'; due_today?: boolean } = {}) {
|
|
482
|
-
await this.init()
|
|
483
|
-
let where = 'WHERE t.profile_id=?'
|
|
484
|
-
const args: unknown[] = [this.profileId]
|
|
485
|
-
if (opts.status) { where += ' AND t.status=?'; args.push(opts.status) }
|
|
486
|
-
if (opts.due_today) {
|
|
487
|
-
const endOfDay = Math.floor(new Date().setHours(23, 59, 59, 999) / 1000)
|
|
488
|
-
where += " AND t.due_at<=? AND t.status='open'"
|
|
489
|
-
args.push(endOfDay)
|
|
490
|
-
}
|
|
491
|
-
const { rows } = await db.execute({
|
|
492
|
-
sql: `SELECT t.*,c.first_name,c.last_name FROM crm_tasks t
|
|
493
|
-
LEFT JOIN crm_contacts c ON c.id=t.contact_id
|
|
494
|
-
${where} ORDER BY due_at ASC NULLS LAST`,
|
|
495
|
-
args,
|
|
496
|
-
})
|
|
497
|
-
return rows
|
|
498
|
-
}
|
|
499
|
-
|
|
500
|
-
// ── Notes ─────────────────────────────────────────────────────────────────
|
|
501
|
-
|
|
502
|
-
async createNote(input: {
|
|
503
|
-
contact_id: string
|
|
504
|
-
body: string
|
|
505
|
-
deal_id?: string
|
|
506
|
-
pinned?: boolean
|
|
507
|
-
idempotency_key?: string
|
|
508
|
-
}): Promise<string> {
|
|
509
|
-
await this.init()
|
|
510
|
-
const id = ulid()
|
|
511
|
-
const ts = now()
|
|
512
|
-
const ikey = input.idempotency_key ?? generateIdempotencyKey()
|
|
513
|
-
|
|
514
|
-
await db.write({
|
|
515
|
-
sql: `INSERT OR IGNORE INTO crm_notes
|
|
516
|
-
(id,profile_id,contact_id,deal_id,body,pinned,idempotency_key,created_at,updated_at)
|
|
517
|
-
VALUES (?,?,?,?,?,?,?,?,?)`,
|
|
518
|
-
args: [id, this.profileId, input.contact_id, input.deal_id ?? null,
|
|
519
|
-
input.body, input.pinned ? 1 : 0, ikey, ts, ts],
|
|
520
|
-
})
|
|
521
|
-
return id
|
|
522
|
-
}
|
|
523
|
-
|
|
524
|
-
async listNotes(contactId: string) {
|
|
525
|
-
await this.init()
|
|
526
|
-
const { rows } = await db.execute({
|
|
527
|
-
sql: `SELECT * FROM crm_notes
|
|
528
|
-
WHERE contact_id=? AND profile_id=?
|
|
529
|
-
ORDER BY pinned DESC, created_at DESC`,
|
|
530
|
-
args: [contactId, this.profileId],
|
|
531
|
-
})
|
|
532
|
-
return rows
|
|
533
|
-
}
|
|
534
|
-
|
|
535
|
-
async pinNote(noteId: string, pinned = true) {
|
|
536
|
-
await this.init()
|
|
537
|
-
await db.write({
|
|
538
|
-
sql: `UPDATE crm_notes SET pinned=?,updated_at=? WHERE id=? AND profile_id=?`,
|
|
539
|
-
args: [pinned ? 1 : 0, now(), noteId, this.profileId],
|
|
540
|
-
})
|
|
541
|
-
}
|
|
542
|
-
|
|
543
|
-
// ── Templates ─────────────────────────────────────────────────────────────
|
|
544
|
-
|
|
545
|
-
async createTemplate(input: {
|
|
546
|
-
name: string
|
|
547
|
-
type: 'dm' | 'email' | 'follow_up' | 'proposal'
|
|
548
|
-
body: string
|
|
549
|
-
subject?: string
|
|
550
|
-
platform?: string
|
|
551
|
-
tags?: string[]
|
|
552
|
-
}): Promise<string> {
|
|
553
|
-
await this.init()
|
|
554
|
-
const id = ulid()
|
|
555
|
-
const ts = now()
|
|
556
|
-
await db.write({
|
|
557
|
-
sql: `INSERT INTO crm_templates
|
|
558
|
-
(id,profile_id,name,type,subject,body,platform,tags,created_at,updated_at)
|
|
559
|
-
VALUES (?,?,?,?,?,?,?,?,?,?)`,
|
|
560
|
-
args: [
|
|
561
|
-
id, this.profileId, input.name, input.type,
|
|
562
|
-
input.subject ?? null, input.body,
|
|
563
|
-
input.platform ?? null,
|
|
564
|
-
JSON.stringify(input.tags ?? []),
|
|
565
|
-
ts, ts,
|
|
566
|
-
],
|
|
567
|
-
})
|
|
568
|
-
return id
|
|
569
|
-
}
|
|
570
|
-
|
|
571
|
-
async listTemplates(type?: 'dm' | 'email' | 'follow_up' | 'proposal') {
|
|
572
|
-
await this.init()
|
|
573
|
-
const where = type ? 'AND type=?' : ''
|
|
574
|
-
const args: unknown[] = [this.profileId]
|
|
575
|
-
if (type) args.push(type)
|
|
576
|
-
const { rows } = await db.execute({
|
|
577
|
-
sql: `SELECT * FROM crm_templates WHERE profile_id=? ${where}
|
|
578
|
-
ORDER BY reply_rate_pct DESC, use_count DESC`,
|
|
579
|
-
args,
|
|
580
|
-
})
|
|
581
|
-
return rows
|
|
582
|
-
}
|
|
583
|
-
|
|
584
|
-
// ── Proposals (create / list only — sending + e-sign is app-side) ─────────
|
|
585
|
-
|
|
586
|
-
async createProposal(input: {
|
|
587
|
-
title: string
|
|
588
|
-
body: string
|
|
589
|
-
contact_id?: string
|
|
590
|
-
deal_id?: string
|
|
591
|
-
excerpt?: string
|
|
592
|
-
client_name?: string
|
|
593
|
-
client_email?: string
|
|
594
|
-
client_company?: string
|
|
595
|
-
payment_amount_cents?: number
|
|
596
|
-
payment_currency?: string
|
|
597
|
-
expires_at?: number
|
|
598
|
-
cta_label?: string
|
|
599
|
-
cta_url?: string
|
|
600
|
-
template_id?: string
|
|
601
|
-
ai_generated?: boolean
|
|
602
|
-
idempotency_key?: string
|
|
603
|
-
}): Promise<{ id: string; public_slug: string }> {
|
|
604
|
-
await this.init()
|
|
605
|
-
const id = ulid()
|
|
606
|
-
const public_slug = `${ulid().slice(0, 10)}-${Date.now().toString(36)}`
|
|
607
|
-
const ts = now()
|
|
608
|
-
const ikey = input.idempotency_key ?? generateIdempotencyKey()
|
|
609
|
-
const payAmount = input.payment_amount_cents !== undefined ? vCents(input.payment_amount_cents) : null
|
|
610
|
-
|
|
611
|
-
await db.write({
|
|
612
|
-
sql: `INSERT OR IGNORE INTO crm_proposals
|
|
613
|
-
(id,profile_id,contact_id,deal_id,title,body,excerpt,public_slug,
|
|
614
|
-
status,client_name,client_email,client_company,
|
|
615
|
-
payment_required,payment_amount_cents,payment_currency,
|
|
616
|
-
expires_at,cta_label,cta_url,template_id,ai_generated,
|
|
617
|
-
idempotency_key,created_at,updated_at)
|
|
618
|
-
VALUES (?,?,?,?,?,?,?,?,'draft',?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
|
|
619
|
-
args: [
|
|
620
|
-
id, this.profileId,
|
|
621
|
-
input.contact_id ?? null, input.deal_id ?? null,
|
|
622
|
-
input.title, input.body, input.excerpt ?? null, public_slug,
|
|
623
|
-
input.client_name ?? null, input.client_email ?? null, input.client_company ?? null,
|
|
624
|
-
payAmount !== null ? 1 : 0, payAmount, input.payment_currency ?? 'usd',
|
|
625
|
-
input.expires_at ?? null, input.cta_label ?? null, input.cta_url ?? null,
|
|
626
|
-
input.template_id ?? null, input.ai_generated ? 1 : 0,
|
|
627
|
-
ikey, ts, ts,
|
|
628
|
-
],
|
|
629
|
-
})
|
|
630
|
-
return { id, public_slug }
|
|
631
|
-
}
|
|
632
|
-
|
|
633
|
-
async listProposals(opts: { status?: string; contact_id?: string } = {}) {
|
|
634
|
-
await this.init()
|
|
635
|
-
let where = 'WHERE profile_id=? AND hidden=0'
|
|
636
|
-
const args: unknown[] = [this.profileId]
|
|
637
|
-
if (opts.status) { where += ' AND status=?'; args.push(opts.status) }
|
|
638
|
-
if (opts.contact_id) { where += ' AND contact_id=?'; args.push(opts.contact_id) }
|
|
639
|
-
const { rows } = await db.execute({
|
|
640
|
-
sql: `SELECT id,title,public_slug,status,client_name,client_email,
|
|
641
|
-
payment_amount_cents,email_opened_at,email_clicked_at,
|
|
642
|
-
viewed_at,view_count,paid_at,expires_at,created_at
|
|
643
|
-
FROM crm_proposals ${where} ORDER BY created_at DESC`,
|
|
644
|
-
args,
|
|
645
|
-
})
|
|
646
|
-
return rows
|
|
647
|
-
}
|
|
648
|
-
|
|
649
|
-
// ── Invoices (create / list only — sending is app-side) ───────────────────
|
|
650
|
-
|
|
651
|
-
async createInvoice(input: {
|
|
652
|
-
invoice_number: string
|
|
653
|
-
contact_id?: string
|
|
654
|
-
deal_id?: string
|
|
655
|
-
proposal_id?: string
|
|
656
|
-
line_items: Array<{ description: string; quantity: number; unit_price_cents: number; total_cents: number }>
|
|
657
|
-
client_name?: string
|
|
658
|
-
client_email?: string
|
|
659
|
-
client_company?: string
|
|
660
|
-
currency?: string
|
|
661
|
-
discount_cents?: number
|
|
662
|
-
tax_cents?: number
|
|
663
|
-
due_at?: number
|
|
664
|
-
notes?: string
|
|
665
|
-
idempotency_key?: string
|
|
666
|
-
}): Promise<{ id: string; public_slug: string }> {
|
|
667
|
-
await this.init()
|
|
668
|
-
const id = ulid()
|
|
669
|
-
const public_slug = `${ulid().slice(0, 10)}-${Date.now().toString(36)}`
|
|
670
|
-
const ts = now()
|
|
671
|
-
const ikey = input.idempotency_key ?? generateIdempotencyKey()
|
|
672
|
-
|
|
673
|
-
const subtotal = input.line_items.reduce((a, li) => a + vCents(li.total_cents), 0)
|
|
674
|
-
const discount = vCents(input.discount_cents ?? 0)
|
|
675
|
-
const tax = vCents(input.tax_cents ?? 0)
|
|
676
|
-
const total = Math.max(0, subtotal - discount + tax)
|
|
677
|
-
|
|
678
|
-
await db.write({
|
|
679
|
-
sql: `INSERT OR IGNORE INTO crm_invoices
|
|
680
|
-
(id,profile_id,contact_id,deal_id,proposal_id,invoice_number,public_slug,
|
|
681
|
-
status,client_name,client_email,client_company,line_items,
|
|
682
|
-
subtotal_cents,discount_cents,tax_cents,total_cents,currency,
|
|
683
|
-
issued_at,due_at,notes,idempotency_key,created_at,updated_at)
|
|
684
|
-
VALUES (?,?,?,?,?,?,?,'draft',?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
|
|
685
|
-
args: [
|
|
686
|
-
id, this.profileId,
|
|
687
|
-
input.contact_id ?? null, input.deal_id ?? null, input.proposal_id ?? null,
|
|
688
|
-
input.invoice_number, public_slug,
|
|
689
|
-
input.client_name ?? null, input.client_email ?? null, input.client_company ?? null,
|
|
690
|
-
JSON.stringify(input.line_items),
|
|
691
|
-
subtotal, discount, tax, total, input.currency ?? 'usd',
|
|
692
|
-
ts, input.due_at ?? null, input.notes ?? null,
|
|
693
|
-
ikey, ts, ts,
|
|
694
|
-
],
|
|
695
|
-
})
|
|
696
|
-
return { id, public_slug }
|
|
697
|
-
}
|
|
698
|
-
|
|
699
|
-
async listInvoices(opts: { status?: string; contact_id?: string } = {}) {
|
|
700
|
-
await this.init()
|
|
701
|
-
let where = 'WHERE profile_id=? AND hidden=0'
|
|
702
|
-
const args: unknown[] = [this.profileId]
|
|
703
|
-
if (opts.status) { where += ' AND status=?'; args.push(opts.status) }
|
|
704
|
-
if (opts.contact_id) { where += ' AND contact_id=?'; args.push(opts.contact_id) }
|
|
705
|
-
const { rows } = await db.execute({
|
|
706
|
-
sql: `SELECT id,invoice_number,public_slug,status,client_name,
|
|
707
|
-
total_cents,currency,due_at,issued_at,paid_at,
|
|
708
|
-
email_opened_at,email_clicked_at,created_at
|
|
709
|
-
FROM crm_invoices ${where} ORDER BY created_at DESC`,
|
|
710
|
-
args,
|
|
711
|
-
})
|
|
712
|
-
return rows
|
|
713
|
-
}
|
|
714
|
-
|
|
715
|
-
// ── Pipeline overview ─────────────────────────────────────────────────────
|
|
716
|
-
|
|
717
|
-
async pipelineSummary() {
|
|
718
|
-
await this.init()
|
|
719
|
-
const { rows: [stats] } = await db.execute({
|
|
720
|
-
sql: `SELECT * FROM crm_analytics WHERE profile_id=? LIMIT 1`,
|
|
721
|
-
args: [this.profileId],
|
|
722
|
-
})
|
|
723
|
-
|
|
724
|
-
const { rows: pendingApprovals } = await db.execute({
|
|
725
|
-
sql: `SELECT a.id,a.type,a.body,c.first_name,c.last_name,c.platform
|
|
726
|
-
FROM crm_activities a
|
|
727
|
-
JOIN crm_contacts c ON c.id=a.contact_id
|
|
728
|
-
WHERE a.profile_id=? AND a.approval_status='pending_approval'
|
|
729
|
-
ORDER BY a.occurred_at ASC LIMIT 10`,
|
|
730
|
-
args: [this.profileId],
|
|
731
|
-
})
|
|
732
|
-
|
|
733
|
-
const { rows: followUps } = await db.execute({
|
|
734
|
-
sql: `SELECT id,first_name,last_name,platform_username,outreach_status,next_follow_up_at
|
|
735
|
-
FROM crm_contacts
|
|
736
|
-
WHERE profile_id=? AND next_follow_up_at<=? AND archived=0
|
|
737
|
-
ORDER BY next_follow_up_at ASC LIMIT 10`,
|
|
738
|
-
args: [this.profileId, now()],
|
|
739
|
-
})
|
|
740
|
-
|
|
741
|
-
return { stats, pendingApprovals, followUps }
|
|
742
|
-
}
|
|
743
|
-
|
|
744
|
-
/** Top leads by score, ready for outreach */
|
|
745
|
-
async hotLeads(limit = 10) {
|
|
746
|
-
await this.init()
|
|
747
|
-
const { rows } = await db.execute({
|
|
748
|
-
sql: `SELECT id,first_name,last_name,platform,platform_username,
|
|
749
|
-
lead_score,icp_match,pain_point,audience_size,
|
|
750
|
-
outreach_status,agent_status
|
|
751
|
-
FROM crm_contacts
|
|
752
|
-
WHERE profile_id=? AND archived=0 AND agent_status IN ('enriched','outreach_ready')
|
|
753
|
-
ORDER BY lead_score DESC LIMIT ?`,
|
|
754
|
-
args: [this.profileId, limit],
|
|
755
|
-
})
|
|
756
|
-
return rows
|
|
757
|
-
}
|
|
758
|
-
|
|
759
|
-
// ── Groups (P0-4: junction table, never LIKE '%grp_x%') ───────────────────
|
|
760
|
-
|
|
761
|
-
/** Contacts in a group — indexed, no substring collision. */
|
|
762
|
-
async listContactsInGroup(groupId: string, limit = 50, offset = 0): Promise<unknown[]> {
|
|
763
|
-
await this.init()
|
|
764
|
-
if (!(await hasGroupsJunction())) {
|
|
765
|
-
throw new Error('crm_contact_groups table not present — upgrade BusinessKit to enable groups')
|
|
766
|
-
}
|
|
767
|
-
return getContactsByGroup(this.profileId, groupId, limit, offset)
|
|
768
|
-
}
|
|
769
|
-
|
|
770
|
-
/** Add contact to group — idempotent. */
|
|
771
|
-
async addToGroup(contactId: string, groupId: string): Promise<void> {
|
|
772
|
-
await this.init()
|
|
773
|
-
if (!(await hasGroupsJunction())) {
|
|
774
|
-
throw new Error('crm_contact_groups table not present — upgrade BusinessKit to enable groups')
|
|
775
|
-
}
|
|
776
|
-
await addContactToGroup(this.profileId, contactId, groupId)
|
|
777
|
-
}
|
|
778
|
-
|
|
779
|
-
/** Remove contact from group. */
|
|
780
|
-
async removeFromGroup(contactId: string, groupId: string): Promise<void> {
|
|
781
|
-
await this.init()
|
|
782
|
-
if (!(await hasGroupsJunction())) return
|
|
783
|
-
await removeContactFromGroup(this.profileId, contactId, groupId)
|
|
784
|
-
}
|
|
785
|
-
|
|
786
|
-
/** All groups for a contact. */
|
|
787
|
-
async groupsFor(contactId: string): Promise<unknown[]> {
|
|
788
|
-
await this.init()
|
|
789
|
-
if (!(await hasGroupsJunction())) return []
|
|
790
|
-
return getGroupsForContact(this.profileId, contactId)
|
|
791
|
-
}
|
|
792
|
-
|
|
793
|
-
// ── Agent context (per-contact scratchpad) ────────────────────────────────
|
|
794
|
-
|
|
795
|
-
async updateAgentContext(id: string, updates: Record<string, unknown>) {
|
|
796
|
-
await this.init()
|
|
797
|
-
const contact = await this.getContact(id)
|
|
798
|
-
const merged = { ...contact.agent_context, ...updates, updated_at: iso() }
|
|
799
|
-
await db.write({
|
|
800
|
-
sql: `UPDATE crm_contacts SET agent_context=?,updated_at=?
|
|
801
|
-
WHERE id=? AND profile_id=?`,
|
|
802
|
-
args: [JSON.stringify(merged), now(), id, this.profileId],
|
|
803
|
-
})
|
|
804
|
-
}
|
|
805
|
-
|
|
806
|
-
async setNextFollowUp(id: string, atUnix: number, note?: string) {
|
|
807
|
-
await this.init()
|
|
808
|
-
await db.write({
|
|
809
|
-
sql: `UPDATE crm_contacts SET next_follow_up_at=?,
|
|
810
|
-
follow_up_count=follow_up_count+1,updated_at=?
|
|
811
|
-
WHERE id=? AND profile_id=?`,
|
|
812
|
-
args: [atUnix, now(), id, this.profileId],
|
|
813
|
-
})
|
|
814
|
-
if (note) await this.logActivity(id, 'note', 'outbound', 'agent', note)
|
|
815
|
-
}
|
|
816
|
-
|
|
817
|
-
// ── Private helpers ───────────────────────────────────────────────────────
|
|
818
|
-
|
|
819
|
-
/**
|
|
820
|
-
* Writes an activity row. Idempotency_key dedupes retries across network
|
|
821
|
-
* flakes. Accepts optional subject + channel + dealId via `extra`.
|
|
822
|
-
*
|
|
823
|
-
* Safe to call multiple times with the same idempotency_key — the DB's
|
|
824
|
-
* unique partial index silently ignores duplicates.
|
|
825
|
-
*/
|
|
826
|
-
private async logActivity(
|
|
827
|
-
contactId: string,
|
|
828
|
-
type: ActivityType,
|
|
829
|
-
direction: ActivityDirection,
|
|
830
|
-
sender: ActivitySender,
|
|
831
|
-
body: string,
|
|
832
|
-
extra: {
|
|
833
|
-
approval_status?: ApprovalStatus
|
|
834
|
-
subject?: string
|
|
835
|
-
channel?: string
|
|
836
|
-
deal_id?: string
|
|
837
|
-
metadata?: Record<string, unknown>
|
|
838
|
-
idempotency_key?: string
|
|
839
|
-
} = {},
|
|
840
|
-
): Promise<string> {
|
|
841
|
-
await this.init()
|
|
842
|
-
const id = ulid()
|
|
843
|
-
const ts = now()
|
|
844
|
-
const approval = extra.approval_status ?? 'auto_sent'
|
|
845
|
-
const ikey = extra.idempotency_key ?? generateIdempotencyKey()
|
|
846
|
-
const metadata = {
|
|
847
|
-
...(extra.subject ? { subject: extra.subject } : {}),
|
|
848
|
-
...(extra.channel ? { channel: extra.channel } : {}),
|
|
849
|
-
...(extra.metadata ?? {}),
|
|
850
|
-
}
|
|
851
|
-
|
|
852
|
-
await db.write({
|
|
853
|
-
sql: `INSERT OR IGNORE INTO crm_activities
|
|
854
|
-
(id,profile_id,contact_id,deal_id,type,direction,sender,subject,body,
|
|
855
|
-
metadata,searchable_context,approval_status,
|
|
856
|
-
approval_requested_at,idempotency_key,occurred_at,created_at)
|
|
857
|
-
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
|
|
858
|
-
args: [
|
|
859
|
-
id, this.profileId, contactId, extra.deal_id ?? null,
|
|
860
|
-
type, direction, sender, extra.subject ?? null, body,
|
|
861
|
-
JSON.stringify(metadata),
|
|
862
|
-
`${type} ${direction} ${body.slice(0, 200)}`,
|
|
863
|
-
approval,
|
|
864
|
-
approval === 'pending_approval' ? ts : null,
|
|
865
|
-
ikey, ts, ts,
|
|
866
|
-
],
|
|
867
|
-
})
|
|
868
|
-
return id
|
|
869
|
-
}
|
|
870
|
-
|
|
871
|
-
private parseContact(r: Record<string, unknown>): Contact {
|
|
872
|
-
return {
|
|
873
|
-
...r,
|
|
874
|
-
agent_context: safeJSON(r.agent_context, {}),
|
|
875
|
-
} as unknown as Contact
|
|
876
|
-
}
|
|
877
|
-
}
|
|
878
|
-
|
|
879
|
-
const safeJSON = (v: unknown, fb: unknown) => {
|
|
880
|
-
try { return JSON.parse(v as string) } catch { return fb }
|
|
881
|
-
}
|
|
882
|
-
|
|
883
|
-
export const crmAgent = new CRMAgent()
|