@hasna/microservices 0.0.3 → 0.0.5

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