@hasna/microservices 0.0.3 → 0.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.
Files changed (68) hide show
  1. package/bin/index.js +63 -0
  2. package/bin/mcp.js +63 -0
  3. package/dist/index.js +63 -0
  4. package/microservices/microservice-ads/package.json +27 -0
  5. package/microservices/microservice-ads/src/cli/index.ts +605 -0
  6. package/microservices/microservice-ads/src/db/campaigns.ts +797 -0
  7. package/microservices/microservice-ads/src/db/database.ts +93 -0
  8. package/microservices/microservice-ads/src/db/migrations.ts +60 -0
  9. package/microservices/microservice-ads/src/index.ts +39 -0
  10. package/microservices/microservice-ads/src/mcp/index.ts +480 -0
  11. package/microservices/microservice-contracts/package.json +27 -0
  12. package/microservices/microservice-contracts/src/cli/index.ts +770 -0
  13. package/microservices/microservice-contracts/src/db/contracts.ts +925 -0
  14. package/microservices/microservice-contracts/src/db/database.ts +93 -0
  15. package/microservices/microservice-contracts/src/db/migrations.ts +141 -0
  16. package/microservices/microservice-contracts/src/index.ts +43 -0
  17. package/microservices/microservice-contracts/src/mcp/index.ts +617 -0
  18. package/microservices/microservice-domains/package.json +27 -0
  19. package/microservices/microservice-domains/src/cli/index.ts +691 -0
  20. package/microservices/microservice-domains/src/db/database.ts +93 -0
  21. package/microservices/microservice-domains/src/db/domains.ts +1164 -0
  22. package/microservices/microservice-domains/src/db/migrations.ts +60 -0
  23. package/microservices/microservice-domains/src/index.ts +65 -0
  24. package/microservices/microservice-domains/src/mcp/index.ts +536 -0
  25. package/microservices/microservice-hiring/package.json +27 -0
  26. package/microservices/microservice-hiring/src/cli/index.ts +741 -0
  27. package/microservices/microservice-hiring/src/db/database.ts +93 -0
  28. package/microservices/microservice-hiring/src/db/hiring.ts +1085 -0
  29. package/microservices/microservice-hiring/src/db/migrations.ts +89 -0
  30. package/microservices/microservice-hiring/src/index.ts +80 -0
  31. package/microservices/microservice-hiring/src/lib/scoring.ts +206 -0
  32. package/microservices/microservice-hiring/src/mcp/index.ts +709 -0
  33. package/microservices/microservice-payments/package.json +27 -0
  34. package/microservices/microservice-payments/src/cli/index.ts +609 -0
  35. package/microservices/microservice-payments/src/db/database.ts +93 -0
  36. package/microservices/microservice-payments/src/db/migrations.ts +81 -0
  37. package/microservices/microservice-payments/src/db/payments.ts +1204 -0
  38. package/microservices/microservice-payments/src/index.ts +51 -0
  39. package/microservices/microservice-payments/src/mcp/index.ts +683 -0
  40. package/microservices/microservice-payroll/package.json +27 -0
  41. package/microservices/microservice-payroll/src/cli/index.ts +643 -0
  42. package/microservices/microservice-payroll/src/db/database.ts +93 -0
  43. package/microservices/microservice-payroll/src/db/migrations.ts +95 -0
  44. package/microservices/microservice-payroll/src/db/payroll.ts +1377 -0
  45. package/microservices/microservice-payroll/src/index.ts +48 -0
  46. package/microservices/microservice-payroll/src/mcp/index.ts +666 -0
  47. package/microservices/microservice-shipping/package.json +27 -0
  48. package/microservices/microservice-shipping/src/cli/index.ts +606 -0
  49. package/microservices/microservice-shipping/src/db/database.ts +93 -0
  50. package/microservices/microservice-shipping/src/db/migrations.ts +69 -0
  51. package/microservices/microservice-shipping/src/db/shipping.ts +1093 -0
  52. package/microservices/microservice-shipping/src/index.ts +53 -0
  53. package/microservices/microservice-shipping/src/mcp/index.ts +533 -0
  54. package/microservices/microservice-social/package.json +27 -0
  55. package/microservices/microservice-social/src/cli/index.ts +689 -0
  56. package/microservices/microservice-social/src/db/database.ts +93 -0
  57. package/microservices/microservice-social/src/db/migrations.ts +88 -0
  58. package/microservices/microservice-social/src/db/social.ts +1046 -0
  59. package/microservices/microservice-social/src/index.ts +46 -0
  60. package/microservices/microservice-social/src/mcp/index.ts +655 -0
  61. package/microservices/microservice-subscriptions/package.json +27 -0
  62. package/microservices/microservice-subscriptions/src/cli/index.ts +715 -0
  63. package/microservices/microservice-subscriptions/src/db/database.ts +93 -0
  64. package/microservices/microservice-subscriptions/src/db/migrations.ts +125 -0
  65. package/microservices/microservice-subscriptions/src/db/subscriptions.ts +1256 -0
  66. package/microservices/microservice-subscriptions/src/index.ts +41 -0
  67. package/microservices/microservice-subscriptions/src/mcp/index.ts +631 -0
  68. package/package.json +1 -1
@@ -0,0 +1,1085 @@
1
+ /**
2
+ * Hiring CRUD operations — jobs, applicants, interviews
3
+ */
4
+
5
+ import { getDatabase } from "./database.js";
6
+
7
+ // ---- Types ----
8
+
9
+ export interface Job {
10
+ id: string;
11
+ title: string;
12
+ department: string | null;
13
+ location: string | null;
14
+ type: "full-time" | "part-time" | "contract";
15
+ status: "open" | "closed" | "paused";
16
+ description: string | null;
17
+ requirements: string[];
18
+ salary_range: string | null;
19
+ posted_at: string | null;
20
+ closed_at: string | null;
21
+ created_at: string;
22
+ updated_at: string;
23
+ }
24
+
25
+ interface JobRow {
26
+ id: string;
27
+ title: string;
28
+ department: string | null;
29
+ location: string | null;
30
+ type: string;
31
+ status: string;
32
+ description: string | null;
33
+ requirements: string;
34
+ salary_range: string | null;
35
+ posted_at: string | null;
36
+ closed_at: string | null;
37
+ created_at: string;
38
+ updated_at: string;
39
+ }
40
+
41
+ export interface Applicant {
42
+ id: string;
43
+ job_id: string;
44
+ name: string;
45
+ email: string | null;
46
+ phone: string | null;
47
+ resume_url: string | null;
48
+ status: "applied" | "screening" | "interviewing" | "offered" | "hired" | "rejected";
49
+ stage: string | null;
50
+ rating: number | null;
51
+ notes: string | null;
52
+ source: string | null;
53
+ applied_at: string;
54
+ metadata: Record<string, unknown>;
55
+ created_at: string;
56
+ updated_at: string;
57
+ }
58
+
59
+ interface ApplicantRow {
60
+ id: string;
61
+ job_id: string;
62
+ name: string;
63
+ email: string | null;
64
+ phone: string | null;
65
+ resume_url: string | null;
66
+ status: string;
67
+ stage: string | null;
68
+ rating: number | null;
69
+ notes: string | null;
70
+ source: string | null;
71
+ applied_at: string;
72
+ metadata: string;
73
+ created_at: string;
74
+ updated_at: string;
75
+ }
76
+
77
+ export interface Interview {
78
+ id: string;
79
+ applicant_id: string;
80
+ interviewer: string | null;
81
+ scheduled_at: string | null;
82
+ duration_min: number | null;
83
+ type: "phone" | "video" | "onsite";
84
+ status: "scheduled" | "completed" | "canceled";
85
+ feedback: string | null;
86
+ rating: number | null;
87
+ created_at: string;
88
+ }
89
+
90
+ // ---- Row converters ----
91
+
92
+ function rowToJob(row: JobRow): Job {
93
+ return {
94
+ ...row,
95
+ type: row.type as Job["type"],
96
+ status: row.status as Job["status"],
97
+ requirements: JSON.parse(row.requirements || "[]"),
98
+ };
99
+ }
100
+
101
+ function rowToApplicant(row: ApplicantRow): Applicant {
102
+ return {
103
+ ...row,
104
+ status: row.status as Applicant["status"],
105
+ metadata: JSON.parse(row.metadata || "{}"),
106
+ };
107
+ }
108
+
109
+ // ---- Jobs ----
110
+
111
+ export interface CreateJobInput {
112
+ title: string;
113
+ department?: string;
114
+ location?: string;
115
+ type?: "full-time" | "part-time" | "contract";
116
+ description?: string;
117
+ requirements?: string[];
118
+ salary_range?: string;
119
+ posted_at?: string;
120
+ }
121
+
122
+ export function createJob(input: CreateJobInput): Job {
123
+ const db = getDatabase();
124
+ const id = crypto.randomUUID();
125
+ const requirements = JSON.stringify(input.requirements || []);
126
+
127
+ db.prepare(
128
+ `INSERT INTO jobs (id, title, department, location, type, description, requirements, salary_range, posted_at)
129
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`
130
+ ).run(
131
+ id,
132
+ input.title,
133
+ input.department || null,
134
+ input.location || null,
135
+ input.type || "full-time",
136
+ input.description || null,
137
+ requirements,
138
+ input.salary_range || null,
139
+ input.posted_at || null
140
+ );
141
+
142
+ return getJob(id)!;
143
+ }
144
+
145
+ export function getJob(id: string): Job | null {
146
+ const db = getDatabase();
147
+ const row = db.prepare("SELECT * FROM jobs WHERE id = ?").get(id) as JobRow | null;
148
+ return row ? rowToJob(row) : null;
149
+ }
150
+
151
+ export interface ListJobsOptions {
152
+ status?: string;
153
+ department?: string;
154
+ type?: string;
155
+ limit?: number;
156
+ offset?: number;
157
+ }
158
+
159
+ export function listJobs(options: ListJobsOptions = {}): Job[] {
160
+ const db = getDatabase();
161
+ const conditions: string[] = [];
162
+ const params: unknown[] = [];
163
+
164
+ if (options.status) {
165
+ conditions.push("status = ?");
166
+ params.push(options.status);
167
+ }
168
+ if (options.department) {
169
+ conditions.push("department = ?");
170
+ params.push(options.department);
171
+ }
172
+ if (options.type) {
173
+ conditions.push("type = ?");
174
+ params.push(options.type);
175
+ }
176
+
177
+ let sql = "SELECT * FROM jobs";
178
+ if (conditions.length > 0) {
179
+ sql += " WHERE " + conditions.join(" AND ");
180
+ }
181
+ sql += " ORDER BY created_at DESC";
182
+
183
+ if (options.limit) {
184
+ sql += " LIMIT ?";
185
+ params.push(options.limit);
186
+ }
187
+ if (options.offset) {
188
+ sql += " OFFSET ?";
189
+ params.push(options.offset);
190
+ }
191
+
192
+ const rows = db.prepare(sql).all(...params) as JobRow[];
193
+ return rows.map(rowToJob);
194
+ }
195
+
196
+ export interface UpdateJobInput {
197
+ title?: string;
198
+ department?: string;
199
+ location?: string;
200
+ type?: "full-time" | "part-time" | "contract";
201
+ status?: "open" | "closed" | "paused";
202
+ description?: string;
203
+ requirements?: string[];
204
+ salary_range?: string;
205
+ posted_at?: string;
206
+ closed_at?: string;
207
+ }
208
+
209
+ export function updateJob(id: string, input: UpdateJobInput): Job | null {
210
+ const db = getDatabase();
211
+ const existing = getJob(id);
212
+ if (!existing) return null;
213
+
214
+ const sets: string[] = [];
215
+ const params: unknown[] = [];
216
+
217
+ if (input.title !== undefined) { sets.push("title = ?"); params.push(input.title); }
218
+ if (input.department !== undefined) { sets.push("department = ?"); params.push(input.department); }
219
+ if (input.location !== undefined) { sets.push("location = ?"); params.push(input.location); }
220
+ if (input.type !== undefined) { sets.push("type = ?"); params.push(input.type); }
221
+ if (input.status !== undefined) { sets.push("status = ?"); params.push(input.status); }
222
+ if (input.description !== undefined) { sets.push("description = ?"); params.push(input.description); }
223
+ if (input.requirements !== undefined) { sets.push("requirements = ?"); params.push(JSON.stringify(input.requirements)); }
224
+ if (input.salary_range !== undefined) { sets.push("salary_range = ?"); params.push(input.salary_range); }
225
+ if (input.posted_at !== undefined) { sets.push("posted_at = ?"); params.push(input.posted_at); }
226
+ if (input.closed_at !== undefined) { sets.push("closed_at = ?"); params.push(input.closed_at); }
227
+
228
+ if (sets.length === 0) return existing;
229
+
230
+ sets.push("updated_at = datetime('now')");
231
+ params.push(id);
232
+
233
+ db.prepare(`UPDATE jobs SET ${sets.join(", ")} WHERE id = ?`).run(...params);
234
+ return getJob(id);
235
+ }
236
+
237
+ export function closeJob(id: string): Job | null {
238
+ return updateJob(id, { status: "closed", closed_at: new Date().toISOString() });
239
+ }
240
+
241
+ export function deleteJob(id: string): boolean {
242
+ const db = getDatabase();
243
+ const result = db.prepare("DELETE FROM jobs WHERE id = ?").run(id);
244
+ return result.changes > 0;
245
+ }
246
+
247
+ // ---- Applicants ----
248
+
249
+ export interface CreateApplicantInput {
250
+ job_id: string;
251
+ name: string;
252
+ email?: string;
253
+ phone?: string;
254
+ resume_url?: string;
255
+ status?: Applicant["status"];
256
+ stage?: string;
257
+ rating?: number;
258
+ notes?: string;
259
+ source?: string;
260
+ metadata?: Record<string, unknown>;
261
+ }
262
+
263
+ export function createApplicant(input: CreateApplicantInput): Applicant {
264
+ const db = getDatabase();
265
+ const id = crypto.randomUUID();
266
+ const metadata = JSON.stringify(input.metadata || {});
267
+
268
+ db.prepare(
269
+ `INSERT INTO applicants (id, job_id, name, email, phone, resume_url, status, stage, rating, notes, source, metadata)
270
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
271
+ ).run(
272
+ id,
273
+ input.job_id,
274
+ input.name,
275
+ input.email || null,
276
+ input.phone || null,
277
+ input.resume_url || null,
278
+ input.status || "applied",
279
+ input.stage || null,
280
+ input.rating ?? null,
281
+ input.notes || null,
282
+ input.source || null,
283
+ metadata
284
+ );
285
+
286
+ return getApplicant(id)!;
287
+ }
288
+
289
+ export function getApplicant(id: string): Applicant | null {
290
+ const db = getDatabase();
291
+ const row = db.prepare("SELECT * FROM applicants WHERE id = ?").get(id) as ApplicantRow | null;
292
+ return row ? rowToApplicant(row) : null;
293
+ }
294
+
295
+ export interface ListApplicantsOptions {
296
+ job_id?: string;
297
+ status?: string;
298
+ source?: string;
299
+ limit?: number;
300
+ offset?: number;
301
+ }
302
+
303
+ export function listApplicants(options: ListApplicantsOptions = {}): Applicant[] {
304
+ const db = getDatabase();
305
+ const conditions: string[] = [];
306
+ const params: unknown[] = [];
307
+
308
+ if (options.job_id) {
309
+ conditions.push("job_id = ?");
310
+ params.push(options.job_id);
311
+ }
312
+ if (options.status) {
313
+ conditions.push("status = ?");
314
+ params.push(options.status);
315
+ }
316
+ if (options.source) {
317
+ conditions.push("source = ?");
318
+ params.push(options.source);
319
+ }
320
+
321
+ let sql = "SELECT * FROM applicants";
322
+ if (conditions.length > 0) {
323
+ sql += " WHERE " + conditions.join(" AND ");
324
+ }
325
+ sql += " ORDER BY applied_at DESC";
326
+
327
+ if (options.limit) {
328
+ sql += " LIMIT ?";
329
+ params.push(options.limit);
330
+ }
331
+ if (options.offset) {
332
+ sql += " OFFSET ?";
333
+ params.push(options.offset);
334
+ }
335
+
336
+ const rows = db.prepare(sql).all(...params) as ApplicantRow[];
337
+ return rows.map(rowToApplicant);
338
+ }
339
+
340
+ export interface UpdateApplicantInput {
341
+ name?: string;
342
+ email?: string;
343
+ phone?: string;
344
+ resume_url?: string;
345
+ status?: Applicant["status"];
346
+ stage?: string;
347
+ rating?: number;
348
+ notes?: string;
349
+ source?: string;
350
+ metadata?: Record<string, unknown>;
351
+ }
352
+
353
+ export function updateApplicant(id: string, input: UpdateApplicantInput): Applicant | null {
354
+ const db = getDatabase();
355
+ const existing = getApplicant(id);
356
+ if (!existing) return null;
357
+
358
+ const sets: string[] = [];
359
+ const params: unknown[] = [];
360
+
361
+ if (input.name !== undefined) { sets.push("name = ?"); params.push(input.name); }
362
+ if (input.email !== undefined) { sets.push("email = ?"); params.push(input.email); }
363
+ if (input.phone !== undefined) { sets.push("phone = ?"); params.push(input.phone); }
364
+ if (input.resume_url !== undefined) { sets.push("resume_url = ?"); params.push(input.resume_url); }
365
+ if (input.status !== undefined) { sets.push("status = ?"); params.push(input.status); }
366
+ if (input.stage !== undefined) { sets.push("stage = ?"); params.push(input.stage); }
367
+ if (input.rating !== undefined) { sets.push("rating = ?"); params.push(input.rating); }
368
+ if (input.notes !== undefined) { sets.push("notes = ?"); params.push(input.notes); }
369
+ if (input.source !== undefined) { sets.push("source = ?"); params.push(input.source); }
370
+ if (input.metadata !== undefined) { sets.push("metadata = ?"); params.push(JSON.stringify(input.metadata)); }
371
+
372
+ if (sets.length === 0) return existing;
373
+
374
+ sets.push("updated_at = datetime('now')");
375
+ params.push(id);
376
+
377
+ db.prepare(`UPDATE applicants SET ${sets.join(", ")} WHERE id = ?`).run(...params);
378
+ return getApplicant(id);
379
+ }
380
+
381
+ export function advanceApplicant(id: string, newStatus: Applicant["status"]): Applicant | null {
382
+ return updateApplicant(id, { status: newStatus });
383
+ }
384
+
385
+ export function rejectApplicant(id: string, reason?: string): Applicant | null {
386
+ const input: UpdateApplicantInput = { status: "rejected" };
387
+ if (reason) input.notes = reason;
388
+ return updateApplicant(id, input);
389
+ }
390
+
391
+ export function deleteApplicant(id: string): boolean {
392
+ const db = getDatabase();
393
+ const result = db.prepare("DELETE FROM applicants WHERE id = ?").run(id);
394
+ return result.changes > 0;
395
+ }
396
+
397
+ export function searchApplicants(query: string): Applicant[] {
398
+ const db = getDatabase();
399
+ const q = `%${query}%`;
400
+ const rows = db
401
+ .prepare(
402
+ "SELECT * FROM applicants WHERE name LIKE ? OR email LIKE ? OR notes LIKE ? OR source LIKE ? ORDER BY applied_at DESC"
403
+ )
404
+ .all(q, q, q, q) as ApplicantRow[];
405
+ return rows.map(rowToApplicant);
406
+ }
407
+
408
+ export function listByStage(stage: string): Applicant[] {
409
+ const db = getDatabase();
410
+ const rows = db
411
+ .prepare("SELECT * FROM applicants WHERE stage = ? ORDER BY applied_at DESC")
412
+ .all(stage) as ApplicantRow[];
413
+ return rows.map(rowToApplicant);
414
+ }
415
+
416
+ export interface PipelineEntry {
417
+ status: string;
418
+ count: number;
419
+ }
420
+
421
+ export function getPipeline(jobId: string): PipelineEntry[] {
422
+ const db = getDatabase();
423
+ const rows = db
424
+ .prepare(
425
+ "SELECT status, COUNT(*) as count FROM applicants WHERE job_id = ? GROUP BY status ORDER BY CASE status WHEN 'applied' THEN 1 WHEN 'screening' THEN 2 WHEN 'interviewing' THEN 3 WHEN 'offered' THEN 4 WHEN 'hired' THEN 5 WHEN 'rejected' THEN 6 END"
426
+ )
427
+ .all(jobId) as PipelineEntry[];
428
+ return rows;
429
+ }
430
+
431
+ export interface HiringStats {
432
+ total_jobs: number;
433
+ open_jobs: number;
434
+ total_applicants: number;
435
+ applicants_by_status: PipelineEntry[];
436
+ total_interviews: number;
437
+ avg_rating: number | null;
438
+ }
439
+
440
+ export function getHiringStats(): HiringStats {
441
+ const db = getDatabase();
442
+
443
+ const jobCount = db.prepare("SELECT COUNT(*) as count FROM jobs").get() as { count: number };
444
+ const openJobs = db.prepare("SELECT COUNT(*) as count FROM jobs WHERE status = 'open'").get() as { count: number };
445
+ const applicantCount = db.prepare("SELECT COUNT(*) as count FROM applicants").get() as { count: number };
446
+ const interviewCount = db.prepare("SELECT COUNT(*) as count FROM interviews").get() as { count: number };
447
+ const avgRating = db.prepare("SELECT AVG(rating) as avg FROM applicants WHERE rating IS NOT NULL").get() as { avg: number | null };
448
+
449
+ const byStatus = db
450
+ .prepare("SELECT status, COUNT(*) as count FROM applicants GROUP BY status")
451
+ .all() as PipelineEntry[];
452
+
453
+ return {
454
+ total_jobs: jobCount.count,
455
+ open_jobs: openJobs.count,
456
+ total_applicants: applicantCount.count,
457
+ applicants_by_status: byStatus,
458
+ total_interviews: interviewCount.count,
459
+ avg_rating: avgRating.avg ? Math.round(avgRating.avg * 10) / 10 : null,
460
+ };
461
+ }
462
+
463
+ // ---- Interviews ----
464
+
465
+ export interface CreateInterviewInput {
466
+ applicant_id: string;
467
+ interviewer?: string;
468
+ scheduled_at?: string;
469
+ duration_min?: number;
470
+ type?: "phone" | "video" | "onsite";
471
+ status?: "scheduled" | "completed" | "canceled";
472
+ }
473
+
474
+ export function createInterview(input: CreateInterviewInput): Interview {
475
+ const db = getDatabase();
476
+ const id = crypto.randomUUID();
477
+
478
+ db.prepare(
479
+ `INSERT INTO interviews (id, applicant_id, interviewer, scheduled_at, duration_min, type, status)
480
+ VALUES (?, ?, ?, ?, ?, ?, ?)`
481
+ ).run(
482
+ id,
483
+ input.applicant_id,
484
+ input.interviewer || null,
485
+ input.scheduled_at || null,
486
+ input.duration_min ?? null,
487
+ input.type || "phone",
488
+ input.status || "scheduled"
489
+ );
490
+
491
+ return getInterview(id)!;
492
+ }
493
+
494
+ export function getInterview(id: string): Interview | null {
495
+ const db = getDatabase();
496
+ const row = db.prepare("SELECT * FROM interviews WHERE id = ?").get(id) as Interview | null;
497
+ return row || null;
498
+ }
499
+
500
+ export interface ListInterviewsOptions {
501
+ applicant_id?: string;
502
+ status?: string;
503
+ type?: string;
504
+ limit?: number;
505
+ }
506
+
507
+ export function listInterviews(options: ListInterviewsOptions = {}): Interview[] {
508
+ const db = getDatabase();
509
+ const conditions: string[] = [];
510
+ const params: unknown[] = [];
511
+
512
+ if (options.applicant_id) {
513
+ conditions.push("applicant_id = ?");
514
+ params.push(options.applicant_id);
515
+ }
516
+ if (options.status) {
517
+ conditions.push("status = ?");
518
+ params.push(options.status);
519
+ }
520
+ if (options.type) {
521
+ conditions.push("type = ?");
522
+ params.push(options.type);
523
+ }
524
+
525
+ let sql = "SELECT * FROM interviews";
526
+ if (conditions.length > 0) {
527
+ sql += " WHERE " + conditions.join(" AND ");
528
+ }
529
+ sql += " ORDER BY scheduled_at DESC";
530
+
531
+ if (options.limit) {
532
+ sql += " LIMIT ?";
533
+ params.push(options.limit);
534
+ }
535
+
536
+ return db.prepare(sql).all(...params) as Interview[];
537
+ }
538
+
539
+ export interface UpdateInterviewInput {
540
+ interviewer?: string;
541
+ scheduled_at?: string;
542
+ duration_min?: number;
543
+ type?: "phone" | "video" | "onsite";
544
+ status?: "scheduled" | "completed" | "canceled";
545
+ feedback?: string;
546
+ rating?: number;
547
+ }
548
+
549
+ export function updateInterview(id: string, input: UpdateInterviewInput): Interview | null {
550
+ const db = getDatabase();
551
+ const existing = getInterview(id);
552
+ if (!existing) return null;
553
+
554
+ const sets: string[] = [];
555
+ const params: unknown[] = [];
556
+
557
+ if (input.interviewer !== undefined) { sets.push("interviewer = ?"); params.push(input.interviewer); }
558
+ if (input.scheduled_at !== undefined) { sets.push("scheduled_at = ?"); params.push(input.scheduled_at); }
559
+ if (input.duration_min !== undefined) { sets.push("duration_min = ?"); params.push(input.duration_min); }
560
+ if (input.type !== undefined) { sets.push("type = ?"); params.push(input.type); }
561
+ if (input.status !== undefined) { sets.push("status = ?"); params.push(input.status); }
562
+ if (input.feedback !== undefined) { sets.push("feedback = ?"); params.push(input.feedback); }
563
+ if (input.rating !== undefined) { sets.push("rating = ?"); params.push(input.rating); }
564
+
565
+ if (sets.length === 0) return existing;
566
+
567
+ params.push(id);
568
+ db.prepare(`UPDATE interviews SET ${sets.join(", ")} WHERE id = ?`).run(...params);
569
+ return getInterview(id);
570
+ }
571
+
572
+ export function addInterviewFeedback(id: string, feedback: string, rating?: number): Interview | null {
573
+ const input: UpdateInterviewInput = { feedback, status: "completed" };
574
+ if (rating !== undefined) input.rating = rating;
575
+ return updateInterview(id, input);
576
+ }
577
+
578
+ export function deleteInterview(id: string): boolean {
579
+ const db = getDatabase();
580
+ const result = db.prepare("DELETE FROM interviews WHERE id = ?").run(id);
581
+ return result.changes > 0;
582
+ }
583
+
584
+ // ---- Bulk Import ----
585
+
586
+ export interface BulkImportResult {
587
+ imported: number;
588
+ skipped: number;
589
+ errors: string[];
590
+ }
591
+
592
+ export function bulkImportApplicants(csvData: string): BulkImportResult {
593
+ const lines = csvData.trim().split("\n");
594
+ if (lines.length < 2) {
595
+ return { imported: 0, skipped: 0, errors: ["CSV must have a header row and at least one data row"] };
596
+ }
597
+
598
+ const header = lines[0].split(",").map((h) => h.trim().toLowerCase());
599
+ const requiredCols = ["name"];
600
+ for (const col of requiredCols) {
601
+ if (!header.includes(col)) {
602
+ return { imported: 0, skipped: 0, errors: [`Missing required column: ${col}`] };
603
+ }
604
+ }
605
+
606
+ const nameIdx = header.indexOf("name");
607
+ const emailIdx = header.indexOf("email");
608
+ const phoneIdx = header.indexOf("phone");
609
+ const jobIdIdx = header.indexOf("job_id");
610
+ const sourceIdx = header.indexOf("source");
611
+ const resumeUrlIdx = header.indexOf("resume_url");
612
+
613
+ let imported = 0;
614
+ let skipped = 0;
615
+ const errors: string[] = [];
616
+
617
+ for (let i = 1; i < lines.length; i++) {
618
+ const line = lines[i].trim();
619
+ if (!line) { skipped++; continue; }
620
+
621
+ const cols = parseCsvLine(line);
622
+ const name = cols[nameIdx]?.trim();
623
+
624
+ if (!name) {
625
+ errors.push(`Row ${i + 1}: missing name`);
626
+ skipped++;
627
+ continue;
628
+ }
629
+
630
+ const jobId = jobIdIdx >= 0 ? cols[jobIdIdx]?.trim() : undefined;
631
+ if (!jobId) {
632
+ errors.push(`Row ${i + 1}: missing job_id`);
633
+ skipped++;
634
+ continue;
635
+ }
636
+
637
+ // Verify job exists
638
+ const job = getJob(jobId);
639
+ if (!job) {
640
+ errors.push(`Row ${i + 1}: job '${jobId}' not found`);
641
+ skipped++;
642
+ continue;
643
+ }
644
+
645
+ try {
646
+ createApplicant({
647
+ name,
648
+ job_id: jobId,
649
+ email: emailIdx >= 0 ? cols[emailIdx]?.trim() || undefined : undefined,
650
+ phone: phoneIdx >= 0 ? cols[phoneIdx]?.trim() || undefined : undefined,
651
+ source: sourceIdx >= 0 ? cols[sourceIdx]?.trim() || undefined : undefined,
652
+ resume_url: resumeUrlIdx >= 0 ? cols[resumeUrlIdx]?.trim() || undefined : undefined,
653
+ });
654
+ imported++;
655
+ } catch (err) {
656
+ errors.push(`Row ${i + 1}: ${err instanceof Error ? err.message : String(err)}`);
657
+ skipped++;
658
+ }
659
+ }
660
+
661
+ return { imported, skipped, errors };
662
+ }
663
+
664
+ /** Simple CSV line parser that handles quoted fields */
665
+ function parseCsvLine(line: string): string[] {
666
+ const result: string[] = [];
667
+ let current = "";
668
+ let inQuotes = false;
669
+
670
+ for (let i = 0; i < line.length; i++) {
671
+ const ch = line[i];
672
+ if (inQuotes) {
673
+ if (ch === '"') {
674
+ if (i + 1 < line.length && line[i + 1] === '"') {
675
+ current += '"';
676
+ i++;
677
+ } else {
678
+ inQuotes = false;
679
+ }
680
+ } else {
681
+ current += ch;
682
+ }
683
+ } else {
684
+ if (ch === '"') {
685
+ inQuotes = true;
686
+ } else if (ch === ",") {
687
+ result.push(current);
688
+ current = "";
689
+ } else {
690
+ current += ch;
691
+ }
692
+ }
693
+ }
694
+ result.push(current);
695
+ return result;
696
+ }
697
+
698
+ // ---- Offer Letter Generation ----
699
+
700
+ export interface OfferDetails {
701
+ salary: number;
702
+ start_date: string;
703
+ position_title?: string;
704
+ department?: string;
705
+ benefits?: string;
706
+ equity?: string;
707
+ signing_bonus?: number;
708
+ }
709
+
710
+ export function generateOffer(applicantId: string, details: OfferDetails): string {
711
+ const applicant = getApplicant(applicantId);
712
+ if (!applicant) throw new Error(`Applicant '${applicantId}' not found`);
713
+
714
+ const job = getJob(applicant.job_id);
715
+ if (!job) throw new Error(`Job '${applicant.job_id}' not found`);
716
+
717
+ const title = details.position_title || job.title;
718
+ const dept = details.department || job.department || "the team";
719
+ const salary = details.salary.toLocaleString("en-US", { style: "currency", currency: "USD", maximumFractionDigits: 0 });
720
+
721
+ let letter = `# Offer Letter
722
+
723
+ **Date:** ${new Date().toISOString().split("T")[0]}
724
+
725
+ Dear **${applicant.name}**,
726
+
727
+ We are pleased to extend an offer of employment for the position of **${title}** in **${dept}**.
728
+
729
+ ## Terms of Employment
730
+
731
+ | Detail | Value |
732
+ |--------|-------|
733
+ | **Position** | ${title} |
734
+ | **Department** | ${dept} |
735
+ | **Annual Salary** | ${salary} |
736
+ | **Start Date** | ${details.start_date} |
737
+ | **Employment Type** | ${job.type} |`;
738
+
739
+ if (details.signing_bonus) {
740
+ const bonus = details.signing_bonus.toLocaleString("en-US", { style: "currency", currency: "USD", maximumFractionDigits: 0 });
741
+ letter += `\n| **Signing Bonus** | ${bonus} |`;
742
+ }
743
+
744
+ if (details.equity) {
745
+ letter += `\n| **Equity** | ${details.equity} |`;
746
+ }
747
+
748
+ if (details.benefits) {
749
+ letter += `\n\n## Benefits\n\n${details.benefits}`;
750
+ }
751
+
752
+ letter += `
753
+
754
+ ## Next Steps
755
+
756
+ Please review this offer carefully. To accept, please sign and return this letter by **${getResponseDeadline(details.start_date)}**.
757
+
758
+ We are excited to have you join ${dept} and look forward to your contributions.
759
+
760
+ Sincerely,
761
+ **Hiring Team**
762
+ `;
763
+
764
+ // Store offer in applicant metadata
765
+ const metadata = {
766
+ ...applicant.metadata,
767
+ offer: { ...details, generated_at: new Date().toISOString() },
768
+ };
769
+ updateApplicant(applicantId, { metadata, status: "offered" });
770
+
771
+ return letter;
772
+ }
773
+
774
+ function getResponseDeadline(startDate: string): string {
775
+ const start = new Date(startDate);
776
+ const deadline = new Date(start.getTime() - 14 * 24 * 60 * 60 * 1000);
777
+ return deadline.toISOString().split("T")[0];
778
+ }
779
+
780
+ // ---- Pipeline Velocity / Hiring Forecast ----
781
+
782
+ export interface HiringForecast {
783
+ job_id: string;
784
+ job_title: string;
785
+ total_applicants: number;
786
+ current_pipeline: PipelineEntry[];
787
+ avg_days_per_stage: Record<string, number>;
788
+ estimated_days_to_fill: number | null;
789
+ conversion_rates: Record<string, number>;
790
+ }
791
+
792
+ export function getHiringForecast(jobId: string): HiringForecast {
793
+ const db = getDatabase();
794
+ const job = getJob(jobId);
795
+ if (!job) throw new Error(`Job '${jobId}' not found`);
796
+
797
+ const pipeline = getPipeline(jobId);
798
+ const applicants = listApplicants({ job_id: jobId });
799
+
800
+ // Calculate stage transition times from applicant update timestamps
801
+ const stages = ["applied", "screening", "interviewing", "offered", "hired"];
802
+ const stageDurations: Record<string, number[]> = {};
803
+
804
+ for (const applicant of applicants) {
805
+ // Use created_at and updated_at to estimate stage duration
806
+ if (applicant.status !== "applied" && applicant.status !== "rejected") {
807
+ const created = new Date(applicant.created_at).getTime();
808
+ const updated = new Date(applicant.updated_at).getTime();
809
+ const days = (updated - created) / (1000 * 60 * 60 * 24);
810
+ if (days > 0) {
811
+ const key = `applied->${applicant.status}`;
812
+ if (!stageDurations[key]) stageDurations[key] = [];
813
+ stageDurations[key].push(days);
814
+ }
815
+ }
816
+ }
817
+
818
+ const avgDaysPerStage: Record<string, number> = {};
819
+ for (const [key, durations] of Object.entries(stageDurations)) {
820
+ avgDaysPerStage[key] = Math.round((durations.reduce((a, b) => a + b, 0) / durations.length) * 10) / 10;
821
+ }
822
+
823
+ // Calculate conversion rates between stages
824
+ const conversionRates: Record<string, number> = {};
825
+ const statusCounts: Record<string, number> = {};
826
+ for (const p of pipeline) {
827
+ statusCounts[p.status] = p.count;
828
+ }
829
+
830
+ const total = applicants.length;
831
+ if (total > 0) {
832
+ for (const stage of stages) {
833
+ const atOrPast = applicants.filter((a) => {
834
+ const idx = stages.indexOf(a.status);
835
+ const stageIdx = stages.indexOf(stage);
836
+ return idx >= stageIdx && a.status !== "rejected";
837
+ }).length;
838
+ conversionRates[stage] = Math.round((atOrPast / total) * 100);
839
+ }
840
+ }
841
+
842
+ // Estimate days to fill: sum of avg days per stage transition for the full pipeline
843
+ let estimatedDays: number | null = null;
844
+ if (Object.keys(avgDaysPerStage).length > 0) {
845
+ // Use the longest observed transition as an estimate
846
+ const values = Object.values(avgDaysPerStage);
847
+ estimatedDays = Math.round(values.reduce((a, b) => Math.max(a, b), 0) * 1.2);
848
+ } else if (applicants.length > 0) {
849
+ // Fallback: estimate based on overall pipeline age
850
+ const oldest = applicants.reduce((oldest, a) => {
851
+ const t = new Date(a.created_at).getTime();
852
+ return t < oldest ? t : oldest;
853
+ }, Date.now());
854
+ const daysSinceFirst = (Date.now() - oldest) / (1000 * 60 * 60 * 24);
855
+ const hiredCount = statusCounts["hired"] || 0;
856
+ if (hiredCount > 0) {
857
+ estimatedDays = Math.round(daysSinceFirst / hiredCount);
858
+ } else {
859
+ estimatedDays = Math.round(daysSinceFirst * 2);
860
+ }
861
+ }
862
+
863
+ return {
864
+ job_id: jobId,
865
+ job_title: job.title,
866
+ total_applicants: total,
867
+ current_pipeline: pipeline,
868
+ avg_days_per_stage: avgDaysPerStage,
869
+ estimated_days_to_fill: estimatedDays,
870
+ conversion_rates: conversionRates,
871
+ };
872
+ }
873
+
874
+ // ---- Structured Interview Feedback ----
875
+
876
+ export interface StructuredFeedback {
877
+ technical?: number;
878
+ communication?: number;
879
+ culture_fit?: number;
880
+ problem_solving?: number;
881
+ leadership?: number;
882
+ overall?: number;
883
+ notes?: string;
884
+ }
885
+
886
+ export function submitStructuredFeedback(
887
+ interviewId: string,
888
+ scores: StructuredFeedback,
889
+ feedbackText?: string
890
+ ): Interview | null {
891
+ const interview = getInterview(interviewId);
892
+ if (!interview) return null;
893
+
894
+ // Build feedback JSON with scores and text
895
+ const feedbackData = {
896
+ scores,
897
+ text: feedbackText || interview.feedback || "",
898
+ submitted_at: new Date().toISOString(),
899
+ };
900
+
901
+ // Calculate average score from provided dimensions
902
+ const scoreValues = [
903
+ scores.technical,
904
+ scores.communication,
905
+ scores.culture_fit,
906
+ scores.problem_solving,
907
+ scores.leadership,
908
+ scores.overall,
909
+ ].filter((v): v is number => v !== undefined);
910
+
911
+ const avgRating = scoreValues.length > 0
912
+ ? Math.round((scoreValues.reduce((a, b) => a + b, 0) / scoreValues.length) * 10) / 10
913
+ : undefined;
914
+
915
+ return updateInterview(interviewId, {
916
+ feedback: JSON.stringify(feedbackData),
917
+ rating: avgRating,
918
+ status: "completed",
919
+ });
920
+ }
921
+
922
+ // ---- Bulk Rejection ----
923
+
924
+ export interface BulkRejectResult {
925
+ rejected: number;
926
+ applicant_ids: string[];
927
+ }
928
+
929
+ export function bulkReject(
930
+ jobId: string,
931
+ status: Applicant["status"],
932
+ reason?: string
933
+ ): BulkRejectResult {
934
+ const applicants = listApplicants({ job_id: jobId, status });
935
+ const rejected: string[] = [];
936
+
937
+ for (const applicant of applicants) {
938
+ const result = rejectApplicant(applicant.id, reason);
939
+ if (result) rejected.push(applicant.id);
940
+ }
941
+
942
+ return { rejected: rejected.length, applicant_ids: rejected };
943
+ }
944
+
945
+ // ---- Referral Stats ----
946
+
947
+ export interface ReferralStats {
948
+ source: string;
949
+ total: number;
950
+ hired: number;
951
+ rejected: number;
952
+ in_progress: number;
953
+ conversion_rate: number;
954
+ }
955
+
956
+ export function getReferralStats(): ReferralStats[] {
957
+ const db = getDatabase();
958
+
959
+ const rows = db.prepare(`
960
+ SELECT
961
+ COALESCE(source, 'unknown') as source,
962
+ COUNT(*) as total,
963
+ SUM(CASE WHEN status = 'hired' THEN 1 ELSE 0 END) as hired,
964
+ SUM(CASE WHEN status = 'rejected' THEN 1 ELSE 0 END) as rejected,
965
+ SUM(CASE WHEN status NOT IN ('hired', 'rejected') THEN 1 ELSE 0 END) as in_progress
966
+ FROM applicants
967
+ GROUP BY COALESCE(source, 'unknown')
968
+ ORDER BY total DESC
969
+ `).all() as Array<{
970
+ source: string;
971
+ total: number;
972
+ hired: number;
973
+ rejected: number;
974
+ in_progress: number;
975
+ }>;
976
+
977
+ return rows.map((r) => ({
978
+ ...r,
979
+ conversion_rate: r.total > 0 ? Math.round((r.hired / r.total) * 100 * 10) / 10 : 0,
980
+ }));
981
+ }
982
+
983
+ // ---- Job Templates ----
984
+
985
+ export interface JobTemplate {
986
+ id: string;
987
+ name: string;
988
+ title: string;
989
+ department: string | null;
990
+ location: string | null;
991
+ type: "full-time" | "part-time" | "contract";
992
+ description: string | null;
993
+ requirements: string[];
994
+ salary_range: string | null;
995
+ created_at: string;
996
+ updated_at: string;
997
+ }
998
+
999
+ interface JobTemplateRow {
1000
+ id: string;
1001
+ name: string;
1002
+ title: string;
1003
+ department: string | null;
1004
+ location: string | null;
1005
+ type: string;
1006
+ description: string | null;
1007
+ requirements: string;
1008
+ salary_range: string | null;
1009
+ created_at: string;
1010
+ updated_at: string;
1011
+ }
1012
+
1013
+ function rowToJobTemplate(row: JobTemplateRow): JobTemplate {
1014
+ return {
1015
+ ...row,
1016
+ type: row.type as JobTemplate["type"],
1017
+ requirements: JSON.parse(row.requirements || "[]"),
1018
+ };
1019
+ }
1020
+
1021
+ export function saveJobAsTemplate(jobId: string, templateName: string): JobTemplate {
1022
+ const db = getDatabase();
1023
+ const job = getJob(jobId);
1024
+ if (!job) throw new Error(`Job '${jobId}' not found`);
1025
+
1026
+ const id = crypto.randomUUID();
1027
+ const requirements = JSON.stringify(job.requirements);
1028
+
1029
+ db.prepare(
1030
+ `INSERT INTO job_templates (id, name, title, department, location, type, description, requirements, salary_range)
1031
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`
1032
+ ).run(
1033
+ id,
1034
+ templateName,
1035
+ job.title,
1036
+ job.department,
1037
+ job.location,
1038
+ job.type,
1039
+ job.description,
1040
+ requirements,
1041
+ job.salary_range
1042
+ );
1043
+
1044
+ return getJobTemplate(id)!;
1045
+ }
1046
+
1047
+ export function getJobTemplate(id: string): JobTemplate | null {
1048
+ const db = getDatabase();
1049
+ const row = db.prepare("SELECT * FROM job_templates WHERE id = ?").get(id) as JobTemplateRow | null;
1050
+ return row ? rowToJobTemplate(row) : null;
1051
+ }
1052
+
1053
+ export function getJobTemplateByName(name: string): JobTemplate | null {
1054
+ const db = getDatabase();
1055
+ const row = db.prepare("SELECT * FROM job_templates WHERE name = ?").get(name) as JobTemplateRow | null;
1056
+ return row ? rowToJobTemplate(row) : null;
1057
+ }
1058
+
1059
+ export function listJobTemplates(): JobTemplate[] {
1060
+ const db = getDatabase();
1061
+ const rows = db.prepare("SELECT * FROM job_templates ORDER BY name ASC").all() as JobTemplateRow[];
1062
+ return rows.map(rowToJobTemplate);
1063
+ }
1064
+
1065
+ export function createJobFromTemplate(templateName: string, overrides?: Partial<CreateJobInput>): Job {
1066
+ const template = getJobTemplateByName(templateName);
1067
+ if (!template) throw new Error(`Template '${templateName}' not found`);
1068
+
1069
+ return createJob({
1070
+ title: overrides?.title || template.title,
1071
+ department: overrides?.department || template.department || undefined,
1072
+ location: overrides?.location || template.location || undefined,
1073
+ type: overrides?.type || template.type,
1074
+ description: overrides?.description || template.description || undefined,
1075
+ requirements: overrides?.requirements || template.requirements,
1076
+ salary_range: overrides?.salary_range || template.salary_range || undefined,
1077
+ posted_at: overrides?.posted_at,
1078
+ });
1079
+ }
1080
+
1081
+ export function deleteJobTemplate(id: string): boolean {
1082
+ const db = getDatabase();
1083
+ const result = db.prepare("DELETE FROM job_templates WHERE id = ?").run(id);
1084
+ return result.changes > 0;
1085
+ }