@hasna/microservices 0.0.15 → 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 (296) hide show
  1. package/README.md +120 -138
  2. package/bin/index.js +703 -12728
  3. package/bin/mcp.js +250 -9726
  4. package/dist/index.js +170 -9407
  5. package/package.json +25 -25
  6. package/microservices/microservice-ads/package.json +0 -27
  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 -93
  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 -27
  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 -93
  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 -27
  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 -93
  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 -27
  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 -93
  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 -27
  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 -82
  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 -27
  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 -93
  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 -27
  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 -93
  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 -27
  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 -93
  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 -27
  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 -93
  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 -27
  77. package/microservices/microservice-crm/src/cli/index.ts +0 -396
  78. package/microservices/microservice-crm/src/db/database.ts +0 -82
  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 -27
  84. package/microservices/microservice-documents/src/cli/index.ts +0 -246
  85. package/microservices/microservice-documents/src/db/database.ts +0 -82
  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 -27
  91. package/microservices/microservice-domains/src/cli/index.ts +0 -1111
  92. package/microservices/microservice-domains/src/db/database.ts +0 -93
  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 -27
  102. package/microservices/microservice-expenses/src/cli/index.ts +0 -267
  103. package/microservices/microservice-expenses/src/db/database.ts +0 -82
  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 -27
  109. package/microservices/microservice-habits/src/cli/index.ts +0 -315
  110. package/microservices/microservice-habits/src/db/database.ts +0 -93
  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 -27
  116. package/microservices/microservice-health/src/cli/index.ts +0 -484
  117. package/microservices/microservice-health/src/db/database.ts +0 -93
  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 -27
  123. package/microservices/microservice-hiring/src/cli/index.ts +0 -741
  124. package/microservices/microservice-hiring/src/db/database.ts +0 -93
  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 -27
  131. package/microservices/microservice-inventory/src/cli/index.ts +0 -365
  132. package/microservices/microservice-inventory/src/db/database.ts +0 -82
  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/dist/assets/index-Bngq7FNM.css +0 -1
  138. package/microservices/microservice-invoices/dashboard/dist/assets/index-aHW4ARZR.js +0 -124
  139. package/microservices/microservice-invoices/dashboard/dist/index.html +0 -13
  140. package/microservices/microservice-invoices/dashboard/index.html +0 -12
  141. package/microservices/microservice-invoices/dashboard/package.json +0 -29
  142. package/microservices/microservice-invoices/dashboard/tsconfig.json +0 -14
  143. package/microservices/microservice-invoices/dashboard/vite.config.ts +0 -15
  144. package/microservices/microservice-invoices/package.json +0 -30
  145. package/microservices/microservice-invoices/src/cli/index.ts +0 -308
  146. package/microservices/microservice-invoices/src/db/business.ts +0 -241
  147. package/microservices/microservice-invoices/src/db/clients.ts +0 -127
  148. package/microservices/microservice-invoices/src/db/database.ts +0 -82
  149. package/microservices/microservice-invoices/src/db/invoices.ts +0 -345
  150. package/microservices/microservice-invoices/src/db/migrations.ts +0 -184
  151. package/microservices/microservice-invoices/src/index.ts +0 -56
  152. package/microservices/microservice-invoices/src/mcp/index.ts +0 -242
  153. package/microservices/microservice-invoices/src/server/index.ts +0 -162
  154. package/microservices/microservice-leads/package.json +0 -27
  155. package/microservices/microservice-leads/src/cli/index.ts +0 -596
  156. package/microservices/microservice-leads/src/db/database.ts +0 -93
  157. package/microservices/microservice-leads/src/db/leads.ts +0 -520
  158. package/microservices/microservice-leads/src/db/lists.ts +0 -151
  159. package/microservices/microservice-leads/src/db/migrations.ts +0 -93
  160. package/microservices/microservice-leads/src/index.ts +0 -65
  161. package/microservices/microservice-leads/src/lib/enrichment.ts +0 -202
  162. package/microservices/microservice-leads/src/lib/scoring.ts +0 -134
  163. package/microservices/microservice-leads/src/mcp/index.ts +0 -533
  164. package/microservices/microservice-notes/package.json +0 -27
  165. package/microservices/microservice-notes/src/cli/index.ts +0 -63
  166. package/microservices/microservice-notes/src/db/database.ts +0 -93
  167. package/microservices/microservice-notes/src/db/migrations.ts +0 -40
  168. package/microservices/microservice-notes/src/db/notes.ts +0 -114
  169. package/microservices/microservice-notes/src/index.ts +0 -2
  170. package/microservices/microservice-notes/src/mcp/index.ts +0 -37
  171. package/microservices/microservice-notifications/package.json +0 -27
  172. package/microservices/microservice-notifications/src/cli/index.ts +0 -349
  173. package/microservices/microservice-notifications/src/db/database.ts +0 -93
  174. package/microservices/microservice-notifications/src/db/migrations.ts +0 -62
  175. package/microservices/microservice-notifications/src/db/notifications.ts +0 -509
  176. package/microservices/microservice-notifications/src/index.ts +0 -41
  177. package/microservices/microservice-notifications/src/mcp/index.ts +0 -422
  178. package/microservices/microservice-payments/package.json +0 -27
  179. package/microservices/microservice-payments/src/cli/index.ts +0 -609
  180. package/microservices/microservice-payments/src/db/database.ts +0 -93
  181. package/microservices/microservice-payments/src/db/migrations.ts +0 -81
  182. package/microservices/microservice-payments/src/db/payments.ts +0 -1204
  183. package/microservices/microservice-payments/src/index.ts +0 -51
  184. package/microservices/microservice-payments/src/mcp/index.ts +0 -683
  185. package/microservices/microservice-payroll/package.json +0 -27
  186. package/microservices/microservice-payroll/src/cli/index.ts +0 -643
  187. package/microservices/microservice-payroll/src/db/database.ts +0 -93
  188. package/microservices/microservice-payroll/src/db/migrations.ts +0 -95
  189. package/microservices/microservice-payroll/src/db/payroll.ts +0 -1377
  190. package/microservices/microservice-payroll/src/index.ts +0 -48
  191. package/microservices/microservice-payroll/src/mcp/index.ts +0 -666
  192. package/microservices/microservice-products/package.json +0 -27
  193. package/microservices/microservice-products/src/cli/index.ts +0 -416
  194. package/microservices/microservice-products/src/db/categories.ts +0 -154
  195. package/microservices/microservice-products/src/db/database.ts +0 -93
  196. package/microservices/microservice-products/src/db/migrations.ts +0 -58
  197. package/microservices/microservice-products/src/db/pricing-tiers.ts +0 -66
  198. package/microservices/microservice-products/src/db/products.ts +0 -452
  199. package/microservices/microservice-products/src/index.ts +0 -53
  200. package/microservices/microservice-products/src/mcp/index.ts +0 -453
  201. package/microservices/microservice-projects/package.json +0 -27
  202. package/microservices/microservice-projects/src/cli/index.ts +0 -480
  203. package/microservices/microservice-projects/src/db/database.ts +0 -93
  204. package/microservices/microservice-projects/src/db/migrations.ts +0 -65
  205. package/microservices/microservice-projects/src/db/projects.ts +0 -715
  206. package/microservices/microservice-projects/src/index.ts +0 -57
  207. package/microservices/microservice-projects/src/mcp/index.ts +0 -501
  208. package/microservices/microservice-proposals/package.json +0 -27
  209. package/microservices/microservice-proposals/src/cli/index.ts +0 -400
  210. package/microservices/microservice-proposals/src/db/database.ts +0 -93
  211. package/microservices/microservice-proposals/src/db/migrations.ts +0 -52
  212. package/microservices/microservice-proposals/src/db/proposals.ts +0 -532
  213. package/microservices/microservice-proposals/src/index.ts +0 -37
  214. package/microservices/microservice-proposals/src/mcp/index.ts +0 -375
  215. package/microservices/microservice-reading/package.json +0 -27
  216. package/microservices/microservice-reading/src/cli/index.ts +0 -464
  217. package/microservices/microservice-reading/src/db/database.ts +0 -93
  218. package/microservices/microservice-reading/src/db/migrations.ts +0 -59
  219. package/microservices/microservice-reading/src/db/reading.ts +0 -524
  220. package/microservices/microservice-reading/src/index.ts +0 -51
  221. package/microservices/microservice-reading/src/mcp/index.ts +0 -368
  222. package/microservices/microservice-shipping/package.json +0 -27
  223. package/microservices/microservice-shipping/src/cli/index.ts +0 -606
  224. package/microservices/microservice-shipping/src/db/database.ts +0 -93
  225. package/microservices/microservice-shipping/src/db/migrations.ts +0 -69
  226. package/microservices/microservice-shipping/src/db/shipping.ts +0 -1093
  227. package/microservices/microservice-shipping/src/index.ts +0 -53
  228. package/microservices/microservice-shipping/src/mcp/index.ts +0 -533
  229. package/microservices/microservice-social/package.json +0 -28
  230. package/microservices/microservice-social/src/cli/index.ts +0 -1583
  231. package/microservices/microservice-social/src/db/database.ts +0 -93
  232. package/microservices/microservice-social/src/db/migrations.ts +0 -160
  233. package/microservices/microservice-social/src/db/social.ts +0 -1076
  234. package/microservices/microservice-social/src/index.ts +0 -46
  235. package/microservices/microservice-social/src/lib/audience.ts +0 -353
  236. package/microservices/microservice-social/src/lib/content-ai.ts +0 -278
  237. package/microservices/microservice-social/src/lib/media.ts +0 -311
  238. package/microservices/microservice-social/src/lib/mentions.ts +0 -434
  239. package/microservices/microservice-social/src/lib/metrics-sync.ts +0 -264
  240. package/microservices/microservice-social/src/lib/publisher.ts +0 -377
  241. package/microservices/microservice-social/src/lib/scheduler.ts +0 -229
  242. package/microservices/microservice-social/src/lib/sentiment.ts +0 -256
  243. package/microservices/microservice-social/src/lib/threads.ts +0 -291
  244. package/microservices/microservice-social/src/mcp/index.ts +0 -1425
  245. package/microservices/microservice-social/src/server/index.ts +0 -441
  246. package/microservices/microservice-subscriptions/package.json +0 -27
  247. package/microservices/microservice-subscriptions/src/cli/index.ts +0 -715
  248. package/microservices/microservice-subscriptions/src/db/database.ts +0 -93
  249. package/microservices/microservice-subscriptions/src/db/migrations.ts +0 -125
  250. package/microservices/microservice-subscriptions/src/db/subscriptions.ts +0 -1256
  251. package/microservices/microservice-subscriptions/src/index.ts +0 -41
  252. package/microservices/microservice-subscriptions/src/mcp/index.ts +0 -631
  253. package/microservices/microservice-timesheets/package.json +0 -27
  254. package/microservices/microservice-timesheets/src/cli/index.ts +0 -373
  255. package/microservices/microservice-timesheets/src/db/database.ts +0 -82
  256. package/microservices/microservice-timesheets/src/db/locale.ts +0 -217
  257. package/microservices/microservice-timesheets/src/db/migrations.ts +0 -74
  258. package/microservices/microservice-timesheets/src/db/timesheets.ts +0 -447
  259. package/microservices/microservice-timesheets/src/index.ts +0 -44
  260. package/microservices/microservice-timesheets/src/mcp/index.ts +0 -269
  261. package/microservices/microservice-transcriber/package.json +0 -28
  262. package/microservices/microservice-transcriber/src/cli/index.ts +0 -1593
  263. package/microservices/microservice-transcriber/src/db/annotations.ts +0 -37
  264. package/microservices/microservice-transcriber/src/db/comments.ts +0 -166
  265. package/microservices/microservice-transcriber/src/db/database.ts +0 -82
  266. package/microservices/microservice-transcriber/src/db/migrations.ts +0 -118
  267. package/microservices/microservice-transcriber/src/db/proofread.ts +0 -119
  268. package/microservices/microservice-transcriber/src/db/transcripts.ts +0 -395
  269. package/microservices/microservice-transcriber/src/index.ts +0 -43
  270. package/microservices/microservice-transcriber/src/lib/config.ts +0 -77
  271. package/microservices/microservice-transcriber/src/lib/diff.ts +0 -91
  272. package/microservices/microservice-transcriber/src/lib/downloader.ts +0 -638
  273. package/microservices/microservice-transcriber/src/lib/feeds.ts +0 -62
  274. package/microservices/microservice-transcriber/src/lib/live.ts +0 -94
  275. package/microservices/microservice-transcriber/src/lib/notion.ts +0 -129
  276. package/microservices/microservice-transcriber/src/lib/proofread.ts +0 -296
  277. package/microservices/microservice-transcriber/src/lib/providers.ts +0 -713
  278. package/microservices/microservice-transcriber/src/lib/summarizer.ts +0 -147
  279. package/microservices/microservice-transcriber/src/lib/translator.ts +0 -75
  280. package/microservices/microservice-transcriber/src/lib/webhook.ts +0 -37
  281. package/microservices/microservice-transcriber/src/mcp/index.ts +0 -1330
  282. package/microservices/microservice-transcriber/src/server/index.ts +0 -199
  283. package/microservices/microservice-travel/package.json +0 -27
  284. package/microservices/microservice-travel/src/cli/index.ts +0 -505
  285. package/microservices/microservice-travel/src/db/database.ts +0 -93
  286. package/microservices/microservice-travel/src/db/migrations.ts +0 -77
  287. package/microservices/microservice-travel/src/db/travel.ts +0 -802
  288. package/microservices/microservice-travel/src/index.ts +0 -60
  289. package/microservices/microservice-travel/src/mcp/index.ts +0 -495
  290. package/microservices/microservice-wiki/package.json +0 -27
  291. package/microservices/microservice-wiki/src/cli/index.ts +0 -345
  292. package/microservices/microservice-wiki/src/db/database.ts +0 -93
  293. package/microservices/microservice-wiki/src/db/migrations.ts +0 -55
  294. package/microservices/microservice-wiki/src/db/wiki.ts +0 -395
  295. package/microservices/microservice-wiki/src/index.ts +0 -32
  296. package/microservices/microservice-wiki/src/mcp/index.ts +0 -344
@@ -1,1076 +0,0 @@
1
- /**
2
- * Social media CRUD operations and analytics
3
- */
4
-
5
- import { getDatabase } from "./database.js";
6
-
7
- // ---- Types ----
8
-
9
- export type Platform = "x" | "linkedin" | "instagram" | "threads" | "bluesky";
10
- export type PostStatus = "draft" | "scheduled" | "published" | "failed" | "pending_review";
11
-
12
- export type Recurrence = "daily" | "weekly" | "biweekly" | "monthly";
13
-
14
- /**
15
- * Platform character limits for post content validation
16
- */
17
- export const PLATFORM_LIMITS: Record<Platform, number> = {
18
- x: 280,
19
- linkedin: 3000,
20
- instagram: 2200,
21
- threads: 500,
22
- bluesky: 300,
23
- };
24
-
25
- export interface PlatformLimitWarning {
26
- platform: Platform;
27
- limit: number;
28
- content_length: number;
29
- over_by: number;
30
- }
31
-
32
- /**
33
- * Check if content exceeds platform character limit for a given account
34
- */
35
- export function checkPlatformLimit(content: string, accountId: string): PlatformLimitWarning | null {
36
- const account = getAccount(accountId);
37
- if (!account) return null;
38
-
39
- const limit = PLATFORM_LIMITS[account.platform];
40
- if (content.length > limit) {
41
- return {
42
- platform: account.platform,
43
- limit,
44
- content_length: content.length,
45
- over_by: content.length - limit,
46
- };
47
- }
48
- return null;
49
- }
50
-
51
- export interface Account {
52
- id: string;
53
- platform: Platform;
54
- handle: string;
55
- display_name: string | null;
56
- connected: boolean;
57
- access_token_env: string | null;
58
- metadata: Record<string, unknown>;
59
- created_at: string;
60
- }
61
-
62
- interface AccountRow {
63
- id: string;
64
- platform: string;
65
- handle: string;
66
- display_name: string | null;
67
- connected: number;
68
- access_token_env: string | null;
69
- metadata: string;
70
- created_at: string;
71
- }
72
-
73
- function rowToAccount(row: AccountRow): Account {
74
- return {
75
- ...row,
76
- platform: row.platform as Platform,
77
- connected: row.connected === 1,
78
- metadata: JSON.parse(row.metadata || "{}"),
79
- };
80
- }
81
-
82
- export interface Engagement {
83
- likes?: number;
84
- shares?: number;
85
- comments?: number;
86
- impressions?: number;
87
- clicks?: number;
88
- }
89
-
90
- export interface Post {
91
- id: string;
92
- account_id: string;
93
- content: string;
94
- media_urls: string[];
95
- status: PostStatus;
96
- scheduled_at: string | null;
97
- published_at: string | null;
98
- platform_post_id: string | null;
99
- engagement: Engagement;
100
- tags: string[];
101
- recurrence: Recurrence | null;
102
- thread_id: string | null;
103
- thread_position: number | null;
104
- created_at: string;
105
- updated_at: string;
106
- }
107
-
108
- interface PostRow {
109
- id: string;
110
- account_id: string;
111
- content: string;
112
- media_urls: string;
113
- status: string;
114
- scheduled_at: string | null;
115
- published_at: string | null;
116
- platform_post_id: string | null;
117
- engagement: string;
118
- tags: string;
119
- recurrence: string | null;
120
- thread_id: string | null;
121
- thread_position: number | null;
122
- created_at: string;
123
- updated_at: string;
124
- }
125
-
126
- function rowToPost(row: PostRow): Post {
127
- return {
128
- ...row,
129
- status: row.status as PostStatus,
130
- media_urls: JSON.parse(row.media_urls || "[]"),
131
- engagement: JSON.parse(row.engagement || "{}"),
132
- tags: JSON.parse(row.tags || "[]"),
133
- recurrence: (row.recurrence as Recurrence) || null,
134
- thread_id: row.thread_id || null,
135
- thread_position: row.thread_position ?? null,
136
- };
137
- }
138
-
139
- export interface Template {
140
- id: string;
141
- name: string;
142
- content: string;
143
- variables: string[];
144
- created_at: string;
145
- }
146
-
147
- interface TemplateRow {
148
- id: string;
149
- name: string;
150
- content: string;
151
- variables: string;
152
- created_at: string;
153
- }
154
-
155
- function rowToTemplate(row: TemplateRow): Template {
156
- return {
157
- ...row,
158
- variables: JSON.parse(row.variables || "[]"),
159
- };
160
- }
161
-
162
- // ---- Accounts ----
163
-
164
- export interface CreateAccountInput {
165
- platform: Platform;
166
- handle: string;
167
- display_name?: string;
168
- connected?: boolean;
169
- access_token_env?: string;
170
- metadata?: Record<string, unknown>;
171
- }
172
-
173
- export function createAccount(input: CreateAccountInput): Account {
174
- const db = getDatabase();
175
- const id = crypto.randomUUID();
176
- const metadata = JSON.stringify(input.metadata || {});
177
-
178
- db.prepare(
179
- `INSERT INTO accounts (id, platform, handle, display_name, connected, access_token_env, metadata)
180
- VALUES (?, ?, ?, ?, ?, ?, ?)`
181
- ).run(
182
- id,
183
- input.platform,
184
- input.handle,
185
- input.display_name || null,
186
- input.connected ? 1 : 0,
187
- input.access_token_env || null,
188
- metadata
189
- );
190
-
191
- return getAccount(id)!;
192
- }
193
-
194
- export function getAccount(id: string): Account | null {
195
- const db = getDatabase();
196
- const row = db.prepare("SELECT * FROM accounts WHERE id = ?").get(id) as AccountRow | null;
197
- return row ? rowToAccount(row) : null;
198
- }
199
-
200
- export interface ListAccountsOptions {
201
- platform?: Platform;
202
- connected?: boolean;
203
- limit?: number;
204
- }
205
-
206
- export function listAccounts(options: ListAccountsOptions = {}): Account[] {
207
- const db = getDatabase();
208
- const conditions: string[] = [];
209
- const params: unknown[] = [];
210
-
211
- if (options.platform) {
212
- conditions.push("platform = ?");
213
- params.push(options.platform);
214
- }
215
-
216
- if (options.connected !== undefined) {
217
- conditions.push("connected = ?");
218
- params.push(options.connected ? 1 : 0);
219
- }
220
-
221
- let sql = "SELECT * FROM accounts";
222
- if (conditions.length > 0) {
223
- sql += " WHERE " + conditions.join(" AND ");
224
- }
225
- sql += " ORDER BY created_at DESC";
226
-
227
- if (options.limit) {
228
- sql += " LIMIT ?";
229
- params.push(options.limit);
230
- }
231
-
232
- const rows = db.prepare(sql).all(...params) as AccountRow[];
233
- return rows.map(rowToAccount);
234
- }
235
-
236
- export interface UpdateAccountInput {
237
- platform?: Platform;
238
- handle?: string;
239
- display_name?: string;
240
- connected?: boolean;
241
- access_token_env?: string;
242
- metadata?: Record<string, unknown>;
243
- }
244
-
245
- export function updateAccount(id: string, input: UpdateAccountInput): Account | null {
246
- const db = getDatabase();
247
- const existing = getAccount(id);
248
- if (!existing) return null;
249
-
250
- const sets: string[] = [];
251
- const params: unknown[] = [];
252
-
253
- if (input.platform !== undefined) {
254
- sets.push("platform = ?");
255
- params.push(input.platform);
256
- }
257
- if (input.handle !== undefined) {
258
- sets.push("handle = ?");
259
- params.push(input.handle);
260
- }
261
- if (input.display_name !== undefined) {
262
- sets.push("display_name = ?");
263
- params.push(input.display_name);
264
- }
265
- if (input.connected !== undefined) {
266
- sets.push("connected = ?");
267
- params.push(input.connected ? 1 : 0);
268
- }
269
- if (input.access_token_env !== undefined) {
270
- sets.push("access_token_env = ?");
271
- params.push(input.access_token_env);
272
- }
273
- if (input.metadata !== undefined) {
274
- sets.push("metadata = ?");
275
- params.push(JSON.stringify(input.metadata));
276
- }
277
-
278
- if (sets.length === 0) return existing;
279
-
280
- params.push(id);
281
- db.prepare(`UPDATE accounts SET ${sets.join(", ")} WHERE id = ?`).run(...params);
282
-
283
- return getAccount(id);
284
- }
285
-
286
- export function deleteAccount(id: string): boolean {
287
- const db = getDatabase();
288
- const result = db.prepare("DELETE FROM accounts WHERE id = ?").run(id);
289
- return result.changes > 0;
290
- }
291
-
292
- export function countAccounts(): number {
293
- const db = getDatabase();
294
- const row = db.prepare("SELECT COUNT(*) as count FROM accounts").get() as { count: number };
295
- return row.count;
296
- }
297
-
298
- // ---- Posts ----
299
-
300
- export interface CreatePostInput {
301
- account_id: string;
302
- content: string;
303
- media_urls?: string[];
304
- status?: PostStatus;
305
- scheduled_at?: string;
306
- tags?: string[];
307
- recurrence?: Recurrence;
308
- thread_id?: string;
309
- thread_position?: number;
310
- }
311
-
312
- export function createPost(input: CreatePostInput): Post {
313
- const db = getDatabase();
314
- const id = crypto.randomUUID();
315
- const media_urls = JSON.stringify(input.media_urls || []);
316
- const tags = JSON.stringify(input.tags || []);
317
-
318
- db.prepare(
319
- `INSERT INTO posts (id, account_id, content, media_urls, status, scheduled_at, tags, recurrence, thread_id, thread_position)
320
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
321
- ).run(
322
- id,
323
- input.account_id,
324
- input.content,
325
- media_urls,
326
- input.status || "draft",
327
- input.scheduled_at || null,
328
- tags,
329
- input.recurrence || null,
330
- input.thread_id || null,
331
- input.thread_position ?? null
332
- );
333
-
334
- return getPost(id)!;
335
- }
336
-
337
- export function getPost(id: string): Post | null {
338
- const db = getDatabase();
339
- const row = db.prepare("SELECT * FROM posts WHERE id = ?").get(id) as PostRow | null;
340
- return row ? rowToPost(row) : null;
341
- }
342
-
343
- export interface ListPostsOptions {
344
- account_id?: string;
345
- status?: PostStatus;
346
- tag?: string;
347
- search?: string;
348
- limit?: number;
349
- offset?: number;
350
- }
351
-
352
- export function listPosts(options: ListPostsOptions = {}): Post[] {
353
- const db = getDatabase();
354
- const conditions: string[] = [];
355
- const params: unknown[] = [];
356
-
357
- if (options.account_id) {
358
- conditions.push("account_id = ?");
359
- params.push(options.account_id);
360
- }
361
-
362
- if (options.status) {
363
- conditions.push("status = ?");
364
- params.push(options.status);
365
- }
366
-
367
- if (options.tag) {
368
- conditions.push("tags LIKE ?");
369
- params.push(`%"${options.tag}"%`);
370
- }
371
-
372
- if (options.search) {
373
- conditions.push("content LIKE ?");
374
- params.push(`%${options.search}%`);
375
- }
376
-
377
- let sql = "SELECT * FROM posts";
378
- if (conditions.length > 0) {
379
- sql += " WHERE " + conditions.join(" AND ");
380
- }
381
- sql += " ORDER BY created_at DESC";
382
-
383
- if (options.limit) {
384
- sql += " LIMIT ?";
385
- params.push(options.limit);
386
- }
387
- if (options.offset) {
388
- sql += " OFFSET ?";
389
- params.push(options.offset);
390
- }
391
-
392
- const rows = db.prepare(sql).all(...params) as PostRow[];
393
- return rows.map(rowToPost);
394
- }
395
-
396
- export interface UpdatePostInput {
397
- content?: string;
398
- media_urls?: string[];
399
- status?: PostStatus;
400
- scheduled_at?: string | null;
401
- published_at?: string | null;
402
- platform_post_id?: string;
403
- engagement?: Engagement;
404
- tags?: string[];
405
- recurrence?: Recurrence | null;
406
- }
407
-
408
- export function updatePost(id: string, input: UpdatePostInput): Post | null {
409
- const db = getDatabase();
410
- const existing = getPost(id);
411
- if (!existing) return null;
412
-
413
- const sets: string[] = [];
414
- const params: unknown[] = [];
415
-
416
- if (input.content !== undefined) {
417
- sets.push("content = ?");
418
- params.push(input.content);
419
- }
420
- if (input.media_urls !== undefined) {
421
- sets.push("media_urls = ?");
422
- params.push(JSON.stringify(input.media_urls));
423
- }
424
- if (input.status !== undefined) {
425
- sets.push("status = ?");
426
- params.push(input.status);
427
- }
428
- if (input.scheduled_at !== undefined) {
429
- sets.push("scheduled_at = ?");
430
- params.push(input.scheduled_at);
431
- }
432
- if (input.published_at !== undefined) {
433
- sets.push("published_at = ?");
434
- params.push(input.published_at);
435
- }
436
- if (input.platform_post_id !== undefined) {
437
- sets.push("platform_post_id = ?");
438
- params.push(input.platform_post_id);
439
- }
440
- if (input.engagement !== undefined) {
441
- sets.push("engagement = ?");
442
- params.push(JSON.stringify(input.engagement));
443
- }
444
- if (input.tags !== undefined) {
445
- sets.push("tags = ?");
446
- params.push(JSON.stringify(input.tags));
447
- }
448
- if (input.recurrence !== undefined) {
449
- sets.push("recurrence = ?");
450
- params.push(input.recurrence);
451
- }
452
-
453
- if (sets.length === 0) return existing;
454
-
455
- sets.push("updated_at = datetime('now')");
456
- params.push(id);
457
-
458
- db.prepare(`UPDATE posts SET ${sets.join(", ")} WHERE id = ?`).run(...params);
459
-
460
- return getPost(id);
461
- }
462
-
463
- export function deletePost(id: string): boolean {
464
- const db = getDatabase();
465
- const result = db.prepare("DELETE FROM posts WHERE id = ?").run(id);
466
- return result.changes > 0;
467
- }
468
-
469
- export function countPosts(): number {
470
- const db = getDatabase();
471
- const row = db.prepare("SELECT COUNT(*) as count FROM posts").get() as { count: number };
472
- return row.count;
473
- }
474
-
475
- /**
476
- * Get all posts in a thread, ordered by thread_position
477
- */
478
- export function getThreadPosts(threadId: string): Post[] {
479
- const db = getDatabase();
480
- const rows = db.prepare(
481
- "SELECT * FROM posts WHERE thread_id = ? ORDER BY thread_position ASC"
482
- ).all(threadId) as PostRow[];
483
- return rows.map(rowToPost);
484
- }
485
-
486
- /**
487
- * Delete all posts in a thread
488
- */
489
- export function deleteThreadPosts(threadId: string): number {
490
- const db = getDatabase();
491
- const result = db.prepare("DELETE FROM posts WHERE thread_id = ?").run(threadId);
492
- return result.changes;
493
- }
494
-
495
- /**
496
- * Schedule a post — sets status to 'scheduled' and sets scheduled_at
497
- */
498
- export function schedulePost(id: string, scheduledAt: string): Post | null {
499
- return updatePost(id, { status: "scheduled", scheduled_at: scheduledAt });
500
- }
501
-
502
- /**
503
- * Mark a post as published
504
- */
505
- export function publishPost(id: string, platformPostId?: string): Post | null {
506
- return updatePost(id, {
507
- status: "published",
508
- published_at: new Date().toISOString().replace("T", " ").replace(/\.\d+Z$/, ""),
509
- platform_post_id: platformPostId,
510
- });
511
- }
512
-
513
- // ---- Templates ----
514
-
515
- export interface CreateTemplateInput {
516
- name: string;
517
- content: string;
518
- variables?: string[];
519
- }
520
-
521
- export function createTemplate(input: CreateTemplateInput): Template {
522
- const db = getDatabase();
523
- const id = crypto.randomUUID();
524
- const variables = JSON.stringify(input.variables || []);
525
-
526
- db.prepare(
527
- `INSERT INTO templates (id, name, content, variables)
528
- VALUES (?, ?, ?, ?)`
529
- ).run(id, input.name, input.content, variables);
530
-
531
- return getTemplate(id)!;
532
- }
533
-
534
- export function getTemplate(id: string): Template | null {
535
- const db = getDatabase();
536
- const row = db.prepare("SELECT * FROM templates WHERE id = ?").get(id) as TemplateRow | null;
537
- return row ? rowToTemplate(row) : null;
538
- }
539
-
540
- export function listTemplates(): Template[] {
541
- const db = getDatabase();
542
- const rows = db.prepare("SELECT * FROM templates ORDER BY name").all() as TemplateRow[];
543
- return rows.map(rowToTemplate);
544
- }
545
-
546
- export function deleteTemplate(id: string): boolean {
547
- const db = getDatabase();
548
- const result = db.prepare("DELETE FROM templates WHERE id = ?").run(id);
549
- return result.changes > 0;
550
- }
551
-
552
- /**
553
- * Use a template to create a post — replaces {{variable}} with values
554
- */
555
- export function useTemplate(
556
- templateId: string,
557
- accountId: string,
558
- values: Record<string, string>,
559
- tags?: string[]
560
- ): Post {
561
- const template = getTemplate(templateId);
562
- if (!template) throw new Error(`Template '${templateId}' not found`);
563
-
564
- let content = template.content;
565
- for (const [key, value] of Object.entries(values)) {
566
- content = content.replace(new RegExp(`\\{\\{${key}\\}\\}`, "g"), value);
567
- }
568
-
569
- return createPost({
570
- account_id: accountId,
571
- content,
572
- tags,
573
- });
574
- }
575
-
576
- // ---- Analytics ----
577
-
578
- export interface EngagementStats {
579
- total_posts: number;
580
- total_likes: number;
581
- total_shares: number;
582
- total_comments: number;
583
- total_impressions: number;
584
- total_clicks: number;
585
- avg_likes: number;
586
- avg_shares: number;
587
- avg_comments: number;
588
- avg_impressions: number;
589
- avg_clicks: number;
590
- }
591
-
592
- /**
593
- * Get engagement analytics for a specific account or across all accounts
594
- */
595
- export function getEngagementStats(accountId?: string): EngagementStats {
596
- const db = getDatabase();
597
- let sql = "SELECT engagement FROM posts WHERE status = 'published'";
598
- const params: unknown[] = [];
599
-
600
- if (accountId) {
601
- sql += " AND account_id = ?";
602
- params.push(accountId);
603
- }
604
-
605
- const rows = db.prepare(sql).all(...params) as { engagement: string }[];
606
- const engagements = rows.map((r) => JSON.parse(r.engagement || "{}") as Engagement);
607
-
608
- const total_posts = engagements.length;
609
- const total_likes = engagements.reduce((sum, e) => sum + (e.likes || 0), 0);
610
- const total_shares = engagements.reduce((sum, e) => sum + (e.shares || 0), 0);
611
- const total_comments = engagements.reduce((sum, e) => sum + (e.comments || 0), 0);
612
- const total_impressions = engagements.reduce((sum, e) => sum + (e.impressions || 0), 0);
613
- const total_clicks = engagements.reduce((sum, e) => sum + (e.clicks || 0), 0);
614
-
615
- return {
616
- total_posts,
617
- total_likes,
618
- total_shares,
619
- total_comments,
620
- total_impressions,
621
- total_clicks,
622
- avg_likes: total_posts > 0 ? Math.round(total_likes / total_posts) : 0,
623
- avg_shares: total_posts > 0 ? Math.round(total_shares / total_posts) : 0,
624
- avg_comments: total_posts > 0 ? Math.round(total_comments / total_posts) : 0,
625
- avg_impressions: total_posts > 0 ? Math.round(total_impressions / total_posts) : 0,
626
- avg_clicks: total_posts > 0 ? Math.round(total_clicks / total_posts) : 0,
627
- };
628
- }
629
-
630
- export interface PlatformStats {
631
- platform: Platform;
632
- account_count: number;
633
- post_count: number;
634
- engagement: EngagementStats;
635
- }
636
-
637
- /**
638
- * Get analytics grouped by platform
639
- */
640
- export function getStatsByPlatform(): PlatformStats[] {
641
- const db = getDatabase();
642
- const accounts = listAccounts();
643
- const platforms = [...new Set(accounts.map((a) => a.platform))];
644
-
645
- return platforms.map((platform) => {
646
- const platformAccounts = accounts.filter((a) => a.platform === platform);
647
- const accountIds = platformAccounts.map((a) => a.id);
648
-
649
- let post_count = 0;
650
- const allEngagements: Engagement[] = [];
651
-
652
- for (const accountId of accountIds) {
653
- const posts = listPosts({ account_id: accountId });
654
- post_count += posts.length;
655
- const published = posts.filter((p) => p.status === "published");
656
- allEngagements.push(...published.map((p) => p.engagement));
657
- }
658
-
659
- const total_posts = allEngagements.length;
660
- const total_likes = allEngagements.reduce((sum, e) => sum + (e.likes || 0), 0);
661
- const total_shares = allEngagements.reduce((sum, e) => sum + (e.shares || 0), 0);
662
- const total_comments = allEngagements.reduce((sum, e) => sum + (e.comments || 0), 0);
663
- const total_impressions = allEngagements.reduce((sum, e) => sum + (e.impressions || 0), 0);
664
- const total_clicks = allEngagements.reduce((sum, e) => sum + (e.clicks || 0), 0);
665
-
666
- return {
667
- platform,
668
- account_count: platformAccounts.length,
669
- post_count,
670
- engagement: {
671
- total_posts,
672
- total_likes,
673
- total_shares,
674
- total_comments,
675
- total_impressions,
676
- total_clicks,
677
- avg_likes: total_posts > 0 ? Math.round(total_likes / total_posts) : 0,
678
- avg_shares: total_posts > 0 ? Math.round(total_shares / total_posts) : 0,
679
- avg_comments: total_posts > 0 ? Math.round(total_comments / total_posts) : 0,
680
- avg_impressions: total_posts > 0 ? Math.round(total_impressions / total_posts) : 0,
681
- avg_clicks: total_posts > 0 ? Math.round(total_clicks / total_posts) : 0,
682
- },
683
- };
684
- });
685
- }
686
-
687
- /**
688
- * Get scheduled posts grouped by date (calendar view)
689
- */
690
- export function getCalendar(startDate?: string, endDate?: string): Record<string, Post[]> {
691
- const db = getDatabase();
692
- const conditions: string[] = ["status = 'scheduled'", "scheduled_at IS NOT NULL"];
693
- const params: unknown[] = [];
694
-
695
- if (startDate) {
696
- conditions.push("scheduled_at >= ?");
697
- params.push(startDate);
698
- }
699
- if (endDate) {
700
- conditions.push("scheduled_at <= ?");
701
- params.push(endDate);
702
- }
703
-
704
- const sql = `SELECT * FROM posts WHERE ${conditions.join(" AND ")} ORDER BY scheduled_at`;
705
- const rows = db.prepare(sql).all(...params) as PostRow[];
706
- const posts = rows.map(rowToPost);
707
-
708
- const calendar: Record<string, Post[]> = {};
709
- for (const post of posts) {
710
- const date = post.scheduled_at!.split(" ")[0].split("T")[0];
711
- if (!calendar[date]) calendar[date] = [];
712
- calendar[date].push(post);
713
- }
714
-
715
- return calendar;
716
- }
717
-
718
- /**
719
- * Get overall stats summary
720
- */
721
- export function getOverallStats(): {
722
- total_accounts: number;
723
- total_posts: number;
724
- posts_by_status: Record<string, number>;
725
- total_templates: number;
726
- engagement: EngagementStats;
727
- } {
728
- const db = getDatabase();
729
- const total_accounts = countAccounts();
730
- const total_posts = countPosts();
731
- const total_templates = (db.prepare("SELECT COUNT(*) as count FROM templates").get() as { count: number }).count;
732
-
733
- // Posts by status
734
- const statusRows = db
735
- .prepare("SELECT status, COUNT(*) as count FROM posts GROUP BY status")
736
- .all() as { status: string; count: number }[];
737
- const posts_by_status: Record<string, number> = {};
738
- for (const row of statusRows) {
739
- posts_by_status[row.status] = row.count;
740
- }
741
-
742
- const engagement = getEngagementStats();
743
-
744
- return {
745
- total_accounts,
746
- total_posts,
747
- posts_by_status,
748
- total_templates,
749
- engagement,
750
- };
751
- }
752
-
753
- // ---- Bulk Schedule ----
754
-
755
- export interface BatchScheduleInput {
756
- account_id: string;
757
- content: string;
758
- scheduled_at: string;
759
- media_urls?: string[];
760
- tags?: string[];
761
- recurrence?: Recurrence;
762
- }
763
-
764
- export interface BatchScheduleResult {
765
- scheduled: Post[];
766
- errors: { index: number; error: string }[];
767
- warnings: PlatformLimitWarning[];
768
- }
769
-
770
- /**
771
- * Schedule multiple posts at once from an array of post definitions
772
- */
773
- export function batchSchedule(posts: BatchScheduleInput[]): BatchScheduleResult {
774
- const scheduled: Post[] = [];
775
- const errors: { index: number; error: string }[] = [];
776
- const warnings: PlatformLimitWarning[] = [];
777
-
778
- for (let i = 0; i < posts.length; i++) {
779
- const input = posts[i];
780
- try {
781
- // Validate account exists
782
- const account = getAccount(input.account_id);
783
- if (!account) {
784
- errors.push({ index: i, error: `Account '${input.account_id}' not found` });
785
- continue;
786
- }
787
-
788
- // Check platform limit
789
- const warning = checkPlatformLimit(input.content, input.account_id);
790
- if (warning) {
791
- warnings.push(warning);
792
- }
793
-
794
- const post = createPost({
795
- account_id: input.account_id,
796
- content: input.content,
797
- media_urls: input.media_urls,
798
- status: "scheduled",
799
- scheduled_at: input.scheduled_at,
800
- tags: input.tags,
801
- recurrence: input.recurrence,
802
- });
803
-
804
- scheduled.push(post);
805
- } catch (err) {
806
- errors.push({ index: i, error: err instanceof Error ? err.message : String(err) });
807
- }
808
- }
809
-
810
- return { scheduled, errors, warnings };
811
- }
812
-
813
- // ---- Cross-Post ----
814
-
815
- export interface CrossPostResult {
816
- posts: Post[];
817
- warnings: PlatformLimitWarning[];
818
- }
819
-
820
- /**
821
- * Create identical post on multiple platform accounts
822
- */
823
- export function crossPost(
824
- content: string,
825
- platforms: Platform[],
826
- options?: { media_urls?: string[]; tags?: string[]; scheduled_at?: string }
827
- ): CrossPostResult {
828
- const posts: Post[] = [];
829
- const warnings: PlatformLimitWarning[] = [];
830
-
831
- for (const platform of platforms) {
832
- // Find an account for this platform
833
- const accounts = listAccounts({ platform });
834
- if (accounts.length === 0) {
835
- throw new Error(`No account found for platform '${platform}'`);
836
- }
837
-
838
- const account = accounts[0]; // Use first matching account
839
-
840
- // Check platform limit
841
- const limit = PLATFORM_LIMITS[platform];
842
- if (content.length > limit) {
843
- warnings.push({
844
- platform,
845
- limit,
846
- content_length: content.length,
847
- over_by: content.length - limit,
848
- });
849
- }
850
-
851
- const post = createPost({
852
- account_id: account.id,
853
- content,
854
- media_urls: options?.media_urls,
855
- status: options?.scheduled_at ? "scheduled" : "draft",
856
- scheduled_at: options?.scheduled_at,
857
- tags: options?.tags,
858
- });
859
-
860
- posts.push(post);
861
- }
862
-
863
- return { posts, warnings };
864
- }
865
-
866
- // ---- Best Time to Post ----
867
-
868
- export interface BestTimeSlot {
869
- day_of_week: number; // 0=Sunday, 6=Saturday
870
- day_name: string;
871
- hour: number;
872
- avg_engagement: number;
873
- post_count: number;
874
- }
875
-
876
- export interface BestTimeResult {
877
- best_hours: BestTimeSlot[];
878
- best_days: { day_of_week: number; day_name: string; avg_engagement: number; post_count: number }[];
879
- total_analyzed: number;
880
- }
881
-
882
- const DAY_NAMES = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
883
-
884
- /**
885
- * Analyze historical engagement data to find best time to post
886
- */
887
- export function getBestTimeToPost(accountId: string): BestTimeResult {
888
- const db = getDatabase();
889
- const rows = db.prepare(
890
- "SELECT published_at, engagement FROM posts WHERE account_id = ? AND status = 'published' AND published_at IS NOT NULL"
891
- ).all(accountId) as { published_at: string; engagement: string }[];
892
-
893
- if (rows.length === 0) {
894
- return { best_hours: [], best_days: [], total_analyzed: 0 };
895
- }
896
-
897
- // Group by day of week and hour
898
- const hourBuckets: Record<string, { total_engagement: number; count: number; day: number; hour: number }> = {};
899
- const dayBuckets: Record<number, { total_engagement: number; count: number }> = {};
900
-
901
- for (const row of rows) {
902
- const date = new Date(row.published_at.replace(" ", "T"));
903
- const dayOfWeek = date.getUTCDay();
904
- const hour = date.getUTCHours();
905
- const engagement = JSON.parse(row.engagement || "{}") as Engagement;
906
- const totalEng = (engagement.likes || 0) + (engagement.shares || 0) * 2 +
907
- (engagement.comments || 0) * 3 + (engagement.clicks || 0);
908
-
909
- const key = `${dayOfWeek}-${hour}`;
910
- if (!hourBuckets[key]) {
911
- hourBuckets[key] = { total_engagement: 0, count: 0, day: dayOfWeek, hour };
912
- }
913
- hourBuckets[key].total_engagement += totalEng;
914
- hourBuckets[key].count += 1;
915
-
916
- if (!dayBuckets[dayOfWeek]) {
917
- dayBuckets[dayOfWeek] = { total_engagement: 0, count: 0 };
918
- }
919
- dayBuckets[dayOfWeek].total_engagement += totalEng;
920
- dayBuckets[dayOfWeek].count += 1;
921
- }
922
-
923
- // Sort hours by avg engagement
924
- const best_hours: BestTimeSlot[] = Object.values(hourBuckets)
925
- .map((b) => ({
926
- day_of_week: b.day,
927
- day_name: DAY_NAMES[b.day],
928
- hour: b.hour,
929
- avg_engagement: b.count > 0 ? Math.round(b.total_engagement / b.count) : 0,
930
- post_count: b.count,
931
- }))
932
- .sort((a, b) => b.avg_engagement - a.avg_engagement)
933
- .slice(0, 10);
934
-
935
- // Sort days by avg engagement
936
- const best_days = Object.entries(dayBuckets)
937
- .map(([day, b]) => ({
938
- day_of_week: parseInt(day),
939
- day_name: DAY_NAMES[parseInt(day)],
940
- avg_engagement: b.count > 0 ? Math.round(b.total_engagement / b.count) : 0,
941
- post_count: b.count,
942
- }))
943
- .sort((a, b) => b.avg_engagement - a.avg_engagement);
944
-
945
- return { best_hours, best_days, total_analyzed: rows.length };
946
- }
947
-
948
- // ---- Reschedule ----
949
-
950
- /**
951
- * Update scheduled_at on a post without delete/recreate
952
- */
953
- export function reschedulePost(id: string, newDate: string): Post | null {
954
- const post = getPost(id);
955
- if (!post) return null;
956
-
957
- if (post.status !== "scheduled" && post.status !== "draft") {
958
- throw new Error(`Cannot reschedule post with status '${post.status}'. Must be 'draft' or 'scheduled'.`);
959
- }
960
-
961
- return updatePost(id, { scheduled_at: newDate, status: "scheduled" });
962
- }
963
-
964
- // ---- Approval Workflow ----
965
-
966
- /**
967
- * Submit a draft post for review — moves draft→pending_review
968
- */
969
- export function submitPostForReview(id: string): Post | null {
970
- const post = getPost(id);
971
- if (!post) return null;
972
-
973
- if (post.status !== "draft") {
974
- throw new Error(`Cannot submit post with status '${post.status}'. Must be 'draft'.`);
975
- }
976
-
977
- return updatePost(id, { status: "pending_review" });
978
- }
979
-
980
- /**
981
- * Approve a post — moves pending_review→scheduled (requires scheduled_at)
982
- */
983
- export function approvePost(id: string, scheduledAt?: string): Post | null {
984
- const post = getPost(id);
985
- if (!post) return null;
986
-
987
- if (post.status !== "pending_review") {
988
- throw new Error(`Cannot approve post with status '${post.status}'. Must be 'pending_review'.`);
989
- }
990
-
991
- const targetDate = scheduledAt || post.scheduled_at;
992
- if (!targetDate) {
993
- throw new Error("Cannot approve post without a scheduled date. Provide --at <datetime>.");
994
- }
995
-
996
- return updatePost(id, { status: "scheduled", scheduled_at: targetDate });
997
- }
998
-
999
- // ---- Recurring Posts ----
1000
-
1001
- /**
1002
- * Create a recurring post — sets recurrence and schedules the first instance
1003
- */
1004
- export function createRecurringPost(input: CreatePostInput & { recurrence: Recurrence }): Post {
1005
- if (!input.scheduled_at) {
1006
- throw new Error("Recurring posts must have a scheduled_at date for the first occurrence.");
1007
- }
1008
-
1009
- return createPost({
1010
- ...input,
1011
- status: "scheduled",
1012
- });
1013
- }
1014
-
1015
- // ---- Hashtag Analytics ----
1016
-
1017
- export interface HashtagStat {
1018
- hashtag: string;
1019
- post_count: number;
1020
- total_likes: number;
1021
- total_shares: number;
1022
- total_comments: number;
1023
- total_impressions: number;
1024
- avg_engagement: number;
1025
- }
1026
-
1027
- /**
1028
- * Extract hashtags from published posts and correlate with engagement
1029
- */
1030
- export function getHashtagStats(accountId: string): HashtagStat[] {
1031
- const db = getDatabase();
1032
- const rows = db.prepare(
1033
- "SELECT content, engagement FROM posts WHERE account_id = ? AND status = 'published'"
1034
- ).all(accountId) as { content: string; engagement: string }[];
1035
-
1036
- const hashtagMap: Record<string, {
1037
- count: number;
1038
- likes: number;
1039
- shares: number;
1040
- comments: number;
1041
- impressions: number;
1042
- }> = {};
1043
-
1044
- const hashtagRegex = /#(\w+)/g;
1045
-
1046
- for (const row of rows) {
1047
- const engagement = JSON.parse(row.engagement || "{}") as Engagement;
1048
- const matches = row.content.matchAll(hashtagRegex);
1049
-
1050
- for (const match of matches) {
1051
- const tag = match[1].toLowerCase();
1052
- if (!hashtagMap[tag]) {
1053
- hashtagMap[tag] = { count: 0, likes: 0, shares: 0, comments: 0, impressions: 0 };
1054
- }
1055
- hashtagMap[tag].count += 1;
1056
- hashtagMap[tag].likes += engagement.likes || 0;
1057
- hashtagMap[tag].shares += engagement.shares || 0;
1058
- hashtagMap[tag].comments += engagement.comments || 0;
1059
- hashtagMap[tag].impressions += engagement.impressions || 0;
1060
- }
1061
- }
1062
-
1063
- return Object.entries(hashtagMap)
1064
- .map(([hashtag, data]) => ({
1065
- hashtag,
1066
- post_count: data.count,
1067
- total_likes: data.likes,
1068
- total_shares: data.shares,
1069
- total_comments: data.comments,
1070
- total_impressions: data.impressions,
1071
- avg_engagement: data.count > 0
1072
- ? Math.round((data.likes + data.shares * 2 + data.comments * 3) / data.count)
1073
- : 0,
1074
- }))
1075
- .sort((a, b) => b.avg_engagement - a.avg_engagement);
1076
- }