@hasna/microservices 0.0.16 → 0.0.17

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 (293) hide show
  1. package/README.md +143 -23
  2. package/bin/index.js +711 -13998
  3. package/bin/mcp.js +228 -10987
  4. package/dist/index.js +166 -10056
  5. package/package.json +25 -25
  6. package/microservices/microservice-ads/package.json +0 -28
  7. package/microservices/microservice-ads/src/cli/index.ts +0 -605
  8. package/microservices/microservice-ads/src/db/campaigns.ts +0 -797
  9. package/microservices/microservice-ads/src/db/database.ts +0 -91
  10. package/microservices/microservice-ads/src/db/migrations.ts +0 -60
  11. package/microservices/microservice-ads/src/index.ts +0 -39
  12. package/microservices/microservice-ads/src/mcp/index.ts +0 -480
  13. package/microservices/microservice-analytics/package.json +0 -28
  14. package/microservices/microservice-analytics/src/cli/index.ts +0 -373
  15. package/microservices/microservice-analytics/src/db/analytics.ts +0 -564
  16. package/microservices/microservice-analytics/src/db/database.ts +0 -91
  17. package/microservices/microservice-analytics/src/db/migrations.ts +0 -50
  18. package/microservices/microservice-analytics/src/index.ts +0 -37
  19. package/microservices/microservice-analytics/src/mcp/index.ts +0 -334
  20. package/microservices/microservice-assets/package.json +0 -28
  21. package/microservices/microservice-assets/src/cli/index.ts +0 -375
  22. package/microservices/microservice-assets/src/db/assets.ts +0 -370
  23. package/microservices/microservice-assets/src/db/database.ts +0 -91
  24. package/microservices/microservice-assets/src/db/migrations.ts +0 -51
  25. package/microservices/microservice-assets/src/index.ts +0 -32
  26. package/microservices/microservice-assets/src/mcp/index.ts +0 -346
  27. package/microservices/microservice-bookkeeping/package.json +0 -28
  28. package/microservices/microservice-bookkeeping/src/cli/index.ts +0 -386
  29. package/microservices/microservice-bookkeeping/src/db/bookkeeping.ts +0 -591
  30. package/microservices/microservice-bookkeeping/src/db/database.ts +0 -91
  31. package/microservices/microservice-bookkeeping/src/db/migrations.ts +0 -52
  32. package/microservices/microservice-bookkeeping/src/index.ts +0 -32
  33. package/microservices/microservice-bookkeeping/src/mcp/index.ts +0 -284
  34. package/microservices/microservice-calendar/package.json +0 -28
  35. package/microservices/microservice-calendar/src/cli/index.ts +0 -287
  36. package/microservices/microservice-calendar/src/db/calendar.ts +0 -328
  37. package/microservices/microservice-calendar/src/db/database.ts +0 -91
  38. package/microservices/microservice-calendar/src/db/migrations.ts +0 -47
  39. package/microservices/microservice-calendar/src/index.ts +0 -24
  40. package/microservices/microservice-calendar/src/mcp/index.ts +0 -226
  41. package/microservices/microservice-company/package.json +0 -28
  42. package/microservices/microservice-company/src/cli/index.ts +0 -1126
  43. package/microservices/microservice-company/src/db/company.ts +0 -854
  44. package/microservices/microservice-company/src/db/database.ts +0 -91
  45. package/microservices/microservice-company/src/db/migrations.ts +0 -214
  46. package/microservices/microservice-company/src/db/workflow-migrations.ts +0 -44
  47. package/microservices/microservice-company/src/index.ts +0 -60
  48. package/microservices/microservice-company/src/lib/audit.ts +0 -168
  49. package/microservices/microservice-company/src/lib/finance.ts +0 -299
  50. package/microservices/microservice-company/src/lib/settings.ts +0 -85
  51. package/microservices/microservice-company/src/lib/workflows.ts +0 -698
  52. package/microservices/microservice-company/src/mcp/index.ts +0 -991
  53. package/microservices/microservice-compliance/package.json +0 -28
  54. package/microservices/microservice-compliance/src/cli/index.ts +0 -467
  55. package/microservices/microservice-compliance/src/db/compliance.ts +0 -633
  56. package/microservices/microservice-compliance/src/db/database.ts +0 -91
  57. package/microservices/microservice-compliance/src/db/migrations.ts +0 -63
  58. package/microservices/microservice-compliance/src/index.ts +0 -46
  59. package/microservices/microservice-compliance/src/mcp/index.ts +0 -438
  60. package/microservices/microservice-contacts/package.json +0 -28
  61. package/microservices/microservice-contacts/src/cli/index.ts +0 -393
  62. package/microservices/microservice-contacts/src/db/companies.ts +0 -167
  63. package/microservices/microservice-contacts/src/db/contacts.ts +0 -249
  64. package/microservices/microservice-contacts/src/db/database.ts +0 -91
  65. package/microservices/microservice-contacts/src/db/migrations.ts +0 -71
  66. package/microservices/microservice-contacts/src/db/relationships.ts +0 -53
  67. package/microservices/microservice-contacts/src/index.ts +0 -42
  68. package/microservices/microservice-contacts/src/mcp/index.ts +0 -303
  69. package/microservices/microservice-contracts/package.json +0 -28
  70. package/microservices/microservice-contracts/src/cli/index.ts +0 -770
  71. package/microservices/microservice-contracts/src/db/contracts.ts +0 -925
  72. package/microservices/microservice-contracts/src/db/database.ts +0 -91
  73. package/microservices/microservice-contracts/src/db/migrations.ts +0 -141
  74. package/microservices/microservice-contracts/src/index.ts +0 -43
  75. package/microservices/microservice-contracts/src/mcp/index.ts +0 -617
  76. package/microservices/microservice-crm/package.json +0 -28
  77. package/microservices/microservice-crm/src/cli/index.ts +0 -396
  78. package/microservices/microservice-crm/src/db/database.ts +0 -91
  79. package/microservices/microservice-crm/src/db/migrations.ts +0 -66
  80. package/microservices/microservice-crm/src/db/pipeline.ts +0 -397
  81. package/microservices/microservice-crm/src/index.ts +0 -34
  82. package/microservices/microservice-crm/src/mcp/index.ts +0 -294
  83. package/microservices/microservice-documents/package.json +0 -28
  84. package/microservices/microservice-documents/src/cli/index.ts +0 -246
  85. package/microservices/microservice-documents/src/db/database.ts +0 -91
  86. package/microservices/microservice-documents/src/db/documents.ts +0 -316
  87. package/microservices/microservice-documents/src/db/migrations.ts +0 -49
  88. package/microservices/microservice-documents/src/index.ts +0 -24
  89. package/microservices/microservice-documents/src/mcp/index.ts +0 -202
  90. package/microservices/microservice-domains/package.json +0 -28
  91. package/microservices/microservice-domains/src/cli/index.ts +0 -1111
  92. package/microservices/microservice-domains/src/db/database.ts +0 -91
  93. package/microservices/microservice-domains/src/db/domains.ts +0 -1164
  94. package/microservices/microservice-domains/src/db/migrations.ts +0 -60
  95. package/microservices/microservice-domains/src/index.ts +0 -65
  96. package/microservices/microservice-domains/src/lib/brandsight.ts +0 -350
  97. package/microservices/microservice-domains/src/lib/godaddy.ts +0 -338
  98. package/microservices/microservice-domains/src/lib/namecheap.ts +0 -262
  99. package/microservices/microservice-domains/src/lib/registrar.ts +0 -355
  100. package/microservices/microservice-domains/src/mcp/index.ts +0 -781
  101. package/microservices/microservice-expenses/package.json +0 -28
  102. package/microservices/microservice-expenses/src/cli/index.ts +0 -267
  103. package/microservices/microservice-expenses/src/db/database.ts +0 -91
  104. package/microservices/microservice-expenses/src/db/expenses.ts +0 -345
  105. package/microservices/microservice-expenses/src/db/migrations.ts +0 -45
  106. package/microservices/microservice-expenses/src/index.ts +0 -25
  107. package/microservices/microservice-expenses/src/mcp/index.ts +0 -196
  108. package/microservices/microservice-habits/package.json +0 -28
  109. package/microservices/microservice-habits/src/cli/index.ts +0 -315
  110. package/microservices/microservice-habits/src/db/database.ts +0 -91
  111. package/microservices/microservice-habits/src/db/habits.ts +0 -451
  112. package/microservices/microservice-habits/src/db/migrations.ts +0 -46
  113. package/microservices/microservice-habits/src/index.ts +0 -31
  114. package/microservices/microservice-habits/src/mcp/index.ts +0 -313
  115. package/microservices/microservice-health/package.json +0 -28
  116. package/microservices/microservice-health/src/cli/index.ts +0 -484
  117. package/microservices/microservice-health/src/db/database.ts +0 -91
  118. package/microservices/microservice-health/src/db/health.ts +0 -708
  119. package/microservices/microservice-health/src/db/migrations.ts +0 -70
  120. package/microservices/microservice-health/src/index.ts +0 -63
  121. package/microservices/microservice-health/src/mcp/index.ts +0 -437
  122. package/microservices/microservice-hiring/package.json +0 -28
  123. package/microservices/microservice-hiring/src/cli/index.ts +0 -741
  124. package/microservices/microservice-hiring/src/db/database.ts +0 -91
  125. package/microservices/microservice-hiring/src/db/hiring.ts +0 -1085
  126. package/microservices/microservice-hiring/src/db/migrations.ts +0 -89
  127. package/microservices/microservice-hiring/src/index.ts +0 -80
  128. package/microservices/microservice-hiring/src/lib/scoring.ts +0 -206
  129. package/microservices/microservice-hiring/src/mcp/index.ts +0 -709
  130. package/microservices/microservice-inventory/package.json +0 -28
  131. package/microservices/microservice-inventory/src/cli/index.ts +0 -365
  132. package/microservices/microservice-inventory/src/db/database.ts +0 -91
  133. package/microservices/microservice-inventory/src/db/inventory.ts +0 -393
  134. package/microservices/microservice-inventory/src/db/migrations.ts +0 -54
  135. package/microservices/microservice-inventory/src/index.ts +0 -28
  136. package/microservices/microservice-inventory/src/mcp/index.ts +0 -250
  137. package/microservices/microservice-invoices/dashboard/index.html +0 -12
  138. package/microservices/microservice-invoices/dashboard/package.json +0 -29
  139. package/microservices/microservice-invoices/dashboard/tsconfig.json +0 -14
  140. package/microservices/microservice-invoices/dashboard/vite.config.ts +0 -15
  141. package/microservices/microservice-invoices/package.json +0 -31
  142. package/microservices/microservice-invoices/src/cli/index.ts +0 -308
  143. package/microservices/microservice-invoices/src/db/business.ts +0 -241
  144. package/microservices/microservice-invoices/src/db/clients.ts +0 -127
  145. package/microservices/microservice-invoices/src/db/database.ts +0 -91
  146. package/microservices/microservice-invoices/src/db/invoices.ts +0 -345
  147. package/microservices/microservice-invoices/src/db/migrations.ts +0 -184
  148. package/microservices/microservice-invoices/src/index.ts +0 -56
  149. package/microservices/microservice-invoices/src/mcp/index.ts +0 -242
  150. package/microservices/microservice-invoices/src/server/index.ts +0 -162
  151. package/microservices/microservice-leads/package.json +0 -28
  152. package/microservices/microservice-leads/src/cli/index.ts +0 -596
  153. package/microservices/microservice-leads/src/db/database.ts +0 -91
  154. package/microservices/microservice-leads/src/db/leads.ts +0 -520
  155. package/microservices/microservice-leads/src/db/lists.ts +0 -151
  156. package/microservices/microservice-leads/src/db/migrations.ts +0 -93
  157. package/microservices/microservice-leads/src/index.ts +0 -65
  158. package/microservices/microservice-leads/src/lib/enrichment.ts +0 -202
  159. package/microservices/microservice-leads/src/lib/scoring.ts +0 -134
  160. package/microservices/microservice-leads/src/mcp/index.ts +0 -533
  161. package/microservices/microservice-notes/package.json +0 -28
  162. package/microservices/microservice-notes/src/cli/index.ts +0 -63
  163. package/microservices/microservice-notes/src/db/database.ts +0 -91
  164. package/microservices/microservice-notes/src/db/migrations.ts +0 -40
  165. package/microservices/microservice-notes/src/db/notes.ts +0 -114
  166. package/microservices/microservice-notes/src/index.ts +0 -2
  167. package/microservices/microservice-notes/src/mcp/index.ts +0 -37
  168. package/microservices/microservice-notifications/package.json +0 -28
  169. package/microservices/microservice-notifications/src/cli/index.ts +0 -349
  170. package/microservices/microservice-notifications/src/db/database.ts +0 -91
  171. package/microservices/microservice-notifications/src/db/migrations.ts +0 -62
  172. package/microservices/microservice-notifications/src/db/notifications.ts +0 -509
  173. package/microservices/microservice-notifications/src/index.ts +0 -41
  174. package/microservices/microservice-notifications/src/mcp/index.ts +0 -422
  175. package/microservices/microservice-payments/package.json +0 -28
  176. package/microservices/microservice-payments/src/cli/index.ts +0 -609
  177. package/microservices/microservice-payments/src/db/database.ts +0 -91
  178. package/microservices/microservice-payments/src/db/migrations.ts +0 -81
  179. package/microservices/microservice-payments/src/db/payments.ts +0 -1204
  180. package/microservices/microservice-payments/src/index.ts +0 -51
  181. package/microservices/microservice-payments/src/mcp/index.ts +0 -683
  182. package/microservices/microservice-payroll/package.json +0 -28
  183. package/microservices/microservice-payroll/src/cli/index.ts +0 -643
  184. package/microservices/microservice-payroll/src/db/database.ts +0 -91
  185. package/microservices/microservice-payroll/src/db/migrations.ts +0 -95
  186. package/microservices/microservice-payroll/src/db/payroll.ts +0 -1377
  187. package/microservices/microservice-payroll/src/index.ts +0 -48
  188. package/microservices/microservice-payroll/src/mcp/index.ts +0 -666
  189. package/microservices/microservice-products/package.json +0 -28
  190. package/microservices/microservice-products/src/cli/index.ts +0 -416
  191. package/microservices/microservice-products/src/db/categories.ts +0 -154
  192. package/microservices/microservice-products/src/db/database.ts +0 -91
  193. package/microservices/microservice-products/src/db/migrations.ts +0 -58
  194. package/microservices/microservice-products/src/db/pricing-tiers.ts +0 -66
  195. package/microservices/microservice-products/src/db/products.ts +0 -452
  196. package/microservices/microservice-products/src/index.ts +0 -53
  197. package/microservices/microservice-products/src/mcp/index.ts +0 -453
  198. package/microservices/microservice-projects/package.json +0 -28
  199. package/microservices/microservice-projects/src/cli/index.ts +0 -480
  200. package/microservices/microservice-projects/src/db/database.ts +0 -91
  201. package/microservices/microservice-projects/src/db/migrations.ts +0 -65
  202. package/microservices/microservice-projects/src/db/projects.ts +0 -715
  203. package/microservices/microservice-projects/src/index.ts +0 -57
  204. package/microservices/microservice-projects/src/mcp/index.ts +0 -501
  205. package/microservices/microservice-proposals/package.json +0 -28
  206. package/microservices/microservice-proposals/src/cli/index.ts +0 -400
  207. package/microservices/microservice-proposals/src/db/database.ts +0 -91
  208. package/microservices/microservice-proposals/src/db/migrations.ts +0 -52
  209. package/microservices/microservice-proposals/src/db/proposals.ts +0 -532
  210. package/microservices/microservice-proposals/src/index.ts +0 -37
  211. package/microservices/microservice-proposals/src/mcp/index.ts +0 -375
  212. package/microservices/microservice-reading/package.json +0 -28
  213. package/microservices/microservice-reading/src/cli/index.ts +0 -464
  214. package/microservices/microservice-reading/src/db/database.ts +0 -91
  215. package/microservices/microservice-reading/src/db/migrations.ts +0 -59
  216. package/microservices/microservice-reading/src/db/reading.ts +0 -524
  217. package/microservices/microservice-reading/src/index.ts +0 -51
  218. package/microservices/microservice-reading/src/mcp/index.ts +0 -368
  219. package/microservices/microservice-shipping/package.json +0 -28
  220. package/microservices/microservice-shipping/src/cli/index.ts +0 -606
  221. package/microservices/microservice-shipping/src/db/database.ts +0 -91
  222. package/microservices/microservice-shipping/src/db/migrations.ts +0 -69
  223. package/microservices/microservice-shipping/src/db/shipping.ts +0 -1093
  224. package/microservices/microservice-shipping/src/index.ts +0 -53
  225. package/microservices/microservice-shipping/src/mcp/index.ts +0 -533
  226. package/microservices/microservice-social/package.json +0 -29
  227. package/microservices/microservice-social/src/cli/index.ts +0 -1583
  228. package/microservices/microservice-social/src/db/database.ts +0 -91
  229. package/microservices/microservice-social/src/db/migrations.ts +0 -160
  230. package/microservices/microservice-social/src/db/social.ts +0 -1076
  231. package/microservices/microservice-social/src/index.ts +0 -46
  232. package/microservices/microservice-social/src/lib/audience.ts +0 -353
  233. package/microservices/microservice-social/src/lib/content-ai.ts +0 -278
  234. package/microservices/microservice-social/src/lib/media.ts +0 -311
  235. package/microservices/microservice-social/src/lib/mentions.ts +0 -434
  236. package/microservices/microservice-social/src/lib/metrics-sync.ts +0 -264
  237. package/microservices/microservice-social/src/lib/publisher.ts +0 -377
  238. package/microservices/microservice-social/src/lib/scheduler.ts +0 -229
  239. package/microservices/microservice-social/src/lib/sentiment.ts +0 -256
  240. package/microservices/microservice-social/src/lib/threads.ts +0 -291
  241. package/microservices/microservice-social/src/mcp/index.ts +0 -1425
  242. package/microservices/microservice-social/src/server/index.ts +0 -441
  243. package/microservices/microservice-subscriptions/package.json +0 -28
  244. package/microservices/microservice-subscriptions/src/cli/index.ts +0 -715
  245. package/microservices/microservice-subscriptions/src/db/database.ts +0 -91
  246. package/microservices/microservice-subscriptions/src/db/migrations.ts +0 -125
  247. package/microservices/microservice-subscriptions/src/db/subscriptions.ts +0 -1256
  248. package/microservices/microservice-subscriptions/src/index.ts +0 -41
  249. package/microservices/microservice-subscriptions/src/mcp/index.ts +0 -631
  250. package/microservices/microservice-timesheets/package.json +0 -28
  251. package/microservices/microservice-timesheets/src/cli/index.ts +0 -373
  252. package/microservices/microservice-timesheets/src/db/database.ts +0 -91
  253. package/microservices/microservice-timesheets/src/db/locale.ts +0 -217
  254. package/microservices/microservice-timesheets/src/db/migrations.ts +0 -74
  255. package/microservices/microservice-timesheets/src/db/timesheets.ts +0 -447
  256. package/microservices/microservice-timesheets/src/index.ts +0 -44
  257. package/microservices/microservice-timesheets/src/mcp/index.ts +0 -269
  258. package/microservices/microservice-transcriber/package.json +0 -29
  259. package/microservices/microservice-transcriber/src/cli/index.ts +0 -1593
  260. package/microservices/microservice-transcriber/src/db/annotations.ts +0 -37
  261. package/microservices/microservice-transcriber/src/db/comments.ts +0 -166
  262. package/microservices/microservice-transcriber/src/db/database.ts +0 -91
  263. package/microservices/microservice-transcriber/src/db/migrations.ts +0 -118
  264. package/microservices/microservice-transcriber/src/db/proofread.ts +0 -119
  265. package/microservices/microservice-transcriber/src/db/transcripts.ts +0 -395
  266. package/microservices/microservice-transcriber/src/index.ts +0 -43
  267. package/microservices/microservice-transcriber/src/lib/config.ts +0 -77
  268. package/microservices/microservice-transcriber/src/lib/diff.ts +0 -91
  269. package/microservices/microservice-transcriber/src/lib/downloader.ts +0 -638
  270. package/microservices/microservice-transcriber/src/lib/feeds.ts +0 -62
  271. package/microservices/microservice-transcriber/src/lib/live.ts +0 -94
  272. package/microservices/microservice-transcriber/src/lib/notion.ts +0 -129
  273. package/microservices/microservice-transcriber/src/lib/proofread.ts +0 -296
  274. package/microservices/microservice-transcriber/src/lib/providers.ts +0 -713
  275. package/microservices/microservice-transcriber/src/lib/summarizer.ts +0 -147
  276. package/microservices/microservice-transcriber/src/lib/translator.ts +0 -75
  277. package/microservices/microservice-transcriber/src/lib/webhook.ts +0 -37
  278. package/microservices/microservice-transcriber/src/mcp/index.ts +0 -1330
  279. package/microservices/microservice-transcriber/src/server/index.ts +0 -199
  280. package/microservices/microservice-travel/package.json +0 -28
  281. package/microservices/microservice-travel/src/cli/index.ts +0 -505
  282. package/microservices/microservice-travel/src/db/database.ts +0 -91
  283. package/microservices/microservice-travel/src/db/migrations.ts +0 -77
  284. package/microservices/microservice-travel/src/db/travel.ts +0 -802
  285. package/microservices/microservice-travel/src/index.ts +0 -60
  286. package/microservices/microservice-travel/src/mcp/index.ts +0 -495
  287. package/microservices/microservice-wiki/package.json +0 -28
  288. package/microservices/microservice-wiki/src/cli/index.ts +0 -345
  289. package/microservices/microservice-wiki/src/db/database.ts +0 -91
  290. package/microservices/microservice-wiki/src/db/migrations.ts +0 -55
  291. package/microservices/microservice-wiki/src/db/wiki.ts +0 -395
  292. package/microservices/microservice-wiki/src/index.ts +0 -32
  293. package/microservices/microservice-wiki/src/mcp/index.ts +0 -344
@@ -1,1085 +0,0 @@
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
- }