-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathseed-modeling-demo.ts
More file actions
344 lines (324 loc) · 11.3 KB
/
Copy pathseed-modeling-demo.ts
File metadata and controls
344 lines (324 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
#!/usr/bin/env bun
/**
* Demo-сид вертикали «Модельное агентство» — тенант «ModelingAgency Demo» с
* воронкой из шаблона "modeling" (intake→casting→offer→contract→show), лидами
* по всем стадиям и диалогами с сообщениями.
*
* Создаёт:
* - тенант modeling-demo (active)
* - администратор (пароль: test1234):
* lena@demo.io — «Лена Скаут» (superadmin / владелец)
* casting@demo.io — «Кастинг Директор» (manager)
* - воронку из шаблона "modeling"
* - ~10 лидов по стадиям с диалогами
*
* Идемпотентно: при повторном запуске пере-создаёт демо-данные тенанта.
*
* DATABASE_URL=postgres://lead:lead@localhost:5434/lead_engine \
* bun run apps/api/scripts/seed-modeling-demo.ts
*/
import { withTenant } from "@chatman-media/conversation-engine";
import {
admins,
channels,
contacts,
conversations,
leads,
llmProviderConfigs,
messages,
stageDefinitions,
tenants,
} from "@chatman-media/storage";
import { eq } from "drizzle-orm";
import { drizzle } from "drizzle-orm/postgres-js";
import postgres from "postgres";
import { hashPassword } from "../src/lib/auth.ts";
import { seedFunnelByKey } from "../src/routes/admin-funnel.ts";
const SLUG = "modeling-demo";
const url = process.env.DATABASE_URL ?? "postgres://lead:lead@localhost:5434/lead_engine";
const client = postgres(url, { max: 2, prepare: false });
// biome-ignore lint/suspicious/noExplicitAny: seed script
const db = drizzle(client) as any;
const now = Math.floor(Date.now() / 1000);
type Msg = { role: "user" | "assistant" | "human"; text: string };
type LeadSpec = {
stage: string;
name: string;
operator?: boolean;
msgs: Msg[];
};
const SAMPLE: LeadSpec[] = [
{
stage: "intake",
name: "Алина Смирнова",
msgs: [
{ role: "user", text: "Добрый день, хочу попробовать себя в модельном бизнесе" },
{
role: "assistant",
text: "Привет, Алина! Отлично 🌟 Расскажи немного — сколько лет, какой рост и откуда ты?",
},
],
},
{
stage: "intake",
name: "Карина Попова",
msgs: [
{ role: "user", text: "Меня интересует работа в Дубае, это возможно?" },
{
role: "assistant",
text: "Привет! Да, мы работаем с Дубаем и Стамбулом. Заполни анкету — это первый шаг 👇",
},
],
},
{
stage: "portfolio_review",
name: "Дарья Иванова",
msgs: [
{ role: "user", text: "Анкету заполнила, когда ответите?" },
{
role: "assistant",
text: "Даша, анкету получили! Теперь пришли 3–5 фото (лицо + полный рост) и короткое видео 30–60 сек.",
},
{ role: "user", text: "Хорошо, скину сегодня вечером" },
],
},
{
stage: "portfolio_review",
name: "Виктория Козлова",
msgs: [
{ role: "user", text: "Вот мои фото" },
{
role: "assistant",
text: "Получила, спасибо 🙌 Передаю кастинг-директору — ответим в течение 2–3 дней.",
},
],
},
{
stage: "go_see",
name: "Полина Медведева",
msgs: [
{ role: "user", text: "Отлично, когда кастинг?" },
{
role: "assistant",
text: "Кастинг в пятницу 14 июня в 15:00, офис на Патонге, ул. Рат Утит 200 Пай. Возьми паспорт.",
},
{ role: "user", text: "Буду!" },
],
},
{
stage: "go_see",
name: "Анастасия Фёдорова",
operator: true,
msgs: [
{ role: "user", text: "Мне 17 лет, можно участвовать?" },
{
role: "assistant",
text: "Да, с 16 лет. Для несовершеннолетних нужно согласие родителей. Передаю кастинг-директору.",
},
{
role: "human",
text: "Анастасия, здравствуйте! Пришлите, пожалуйста, контакт родителя — обсудим формат участия.",
},
],
},
{
stage: "contract",
name: "Марина Орлова",
msgs: [
{ role: "user", text: "Кастинг прошла, что дальше?" },
{
role: "assistant",
text: "Поздравляем! 🎉 Кастинг-директор одобрил. Готовим контракт — пришлю для ознакомления.",
},
],
},
{
stage: "active_representation",
name: "Юлия Белова",
msgs: [
{ role: "user", text: "Контракт подписала!" },
{
role: "assistant",
text: "Добро пожаловать в агентство, Юля! 🌟 Первый показ — 20 июня в Dubai Mall. Детали пришлём отдельно.",
},
],
},
{
stage: "not_suitable",
name: "Светлана Громова",
msgs: [
{ role: "user", text: "Мне 14 лет, берёте?" },
{
role: "assistant",
text: "Привет! К сожалению, минимальный возраст — 16 лет. Можем вернуться к разговору через 2 года 🙏",
},
],
},
];
async function upsertTenant(): Promise<number> {
const [existing] = await db
.select({ id: tenants.id })
.from(tenants)
.where(eq(tenants.slug, SLUG));
if (existing) return existing.id as number;
const [t] = await db
.insert(tenants)
.values({
slug: SLUG,
plan: "free",
status: "active",
llmBillingMode: "byok",
createdAt: now,
updatedAt: now,
})
.returning({ id: tenants.id });
return t!.id as number;
}
async function upsertAdmin(
tenantId: number,
email: string,
name: string,
role: "superadmin" | "manager",
): Promise<number> {
const passwordHash = await hashPassword("test1234");
const [existing] = await db.select({ id: admins.id }).from(admins).where(eq(admins.email, email));
if (existing) {
await db
.update(admins)
.set({ name, role, tenantId, passwordHash })
.where(eq(admins.id, existing.id));
return existing.id as number;
}
const [a] = await db
.insert(admins)
.values({ tenantId, email, name, role, passwordHash, createdAt: now })
.returning({ id: admins.id });
return a!.id as number;
}
async function main() {
const tenantId = await upsertTenant();
console.log(`[seed] tenant ${SLUG} → id=${tenantId}`);
const lenaId = await upsertAdmin(tenantId, "lena@demo.io", "Лена Скаут", "superadmin");
const castingId = await upsertAdmin(tenantId, "casting@demo.io", "Кастинг Директор", "manager");
console.log(`[seed] admins: lena=${lenaId} casting=${castingId}`);
await withTenant(db, tenantId, async (tx: any) => {
await tx
.insert(channels)
.values({
tenantId,
kind: "web",
externalId: SLUG,
status: "active",
createdAt: now,
updatedAt: now,
})
.onConflictDoNothing();
await tx
.insert(llmProviderConfigs)
.values({
tenantId,
purpose: "chat",
provider: "openai",
model: "gpt-4o-mini",
createdAt: now,
updatedAt: now,
})
.onConflictDoNothing();
});
// Чистим прежние демо-данные тенанта.
await withTenant(db, tenantId, async (tx: any) => {
await tx.delete(contacts).where(eq(contacts.tenantId, tenantId));
});
// Воронка из шаблона "modeling".
const seeded = await seedFunnelByKey(db, tenantId, "modeling", lenaId);
if ("error" in seeded) throw new Error(`seedFunnel: ${seeded.error}`);
console.log(`[seed] modeling funnel: ${seeded.stagesCreated} стадий`);
const stageRows = await withTenant(db, tenantId, async (tx: any) =>
tx
.select({ id: stageDefinitions.id, slug: stageDefinitions.slug })
.from(stageDefinitions)
.where(eq(stageDefinitions.funnelId, seeded.funnelId)),
);
const stageId = new Map<string, number>(
stageRows.map((s: { id: number; slug: string }) => [s.slug, s.id]),
);
let leadCount = 0;
let msgCount = 0;
await withTenant(db, tenantId, async (tx: any) => {
for (let i = 0; i < SAMPLE.length; i++) {
const spec = SAMPLE[i]!;
const sid = stageId.get(spec.stage);
if (!sid) {
console.warn(`[seed] нет стадии "${spec.stage}", пропуск ${spec.name}`);
continue;
}
const createdAt = now - (SAMPLE.length - i) * 3600;
const [ct] = await tx
.insert(contacts)
.values({
tenantId,
displayName: spec.name,
attributesJson: "{}",
createdAt,
updatedAt: createdAt,
})
.returning({ id: contacts.id });
const contactId = ct!.id as number;
const [ld] = await tx
.insert(leads)
.values({
tenantId,
userId: contactId,
state: spec.stage,
stageDefinitionId: sid,
createdAt,
updatedAt: createdAt,
})
.returning({ id: leads.id });
const _leadId = ld!.id as number;
leadCount++;
const last = spec.msgs[spec.msgs.length - 1]!;
const lastAt = createdAt + (spec.msgs.length - 1) * 120;
const onOperator = spec.operator === true;
const [cv] = await tx
.insert(conversations)
.values({
tenantId,
userId: contactId,
source: "bot",
mode: onOperator ? "human" : "ai",
status: onOperator ? "pending" : "open",
unreadCount: last.role === "user" ? 1 : 0,
lastMessageText: last.text,
lastMessageAt: lastAt,
currentStage: spec.stage,
assignedAdminId: onOperator ? castingId : null,
escalatedAt: onOperator ? createdAt + 60 : null,
createdAt,
})
.returning({ id: conversations.id });
const convId = cv!.id as number;
for (let j = 0; j < spec.msgs.length; j++) {
const m = spec.msgs[j]!;
await tx.insert(messages).values({
tenantId,
conversationId: convId,
role: m.role,
text: m.text,
stage: spec.stage,
createdAt: createdAt + j * 120,
});
msgCount++;
}
}
});
console.log(`[seed] готово: ${leadCount} лидов, ${msgCount} сообщений`);
console.log("\nЛогины (пароль: test1234):");
console.log(" Лена Скаут → lena@demo.io (владелец)");
console.log(" Кастинг Директор → casting@demo.io (оператор)");
await client.end({ timeout: 0 });
}
main().catch((err) => {
console.error("[seed] FAILED:", err instanceof Error ? err.message : err);
process.exit(1);
});