optimal-cli 0.1.0 → 1.0.0

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 (107) hide show
  1. package/agents/.gitkeep +0 -0
  2. package/agents/content-ops.md +227 -0
  3. package/agents/financial-ops.md +184 -0
  4. package/agents/infra-ops.md +206 -0
  5. package/agents/profiles.json +5 -0
  6. package/bin/optimal.ts +1731 -0
  7. package/docs/CLI-REFERENCE.md +361 -0
  8. package/lib/assets/index.ts +225 -0
  9. package/lib/assets.ts +124 -0
  10. package/lib/auth/index.ts +189 -0
  11. package/lib/board/index.ts +309 -0
  12. package/lib/board/types.ts +124 -0
  13. package/lib/bot/claim.ts +43 -0
  14. package/lib/bot/coordinator.ts +254 -0
  15. package/lib/bot/heartbeat.ts +37 -0
  16. package/lib/bot/index.ts +9 -0
  17. package/lib/bot/protocol.ts +99 -0
  18. package/lib/bot/reporter.ts +42 -0
  19. package/lib/bot/skills.ts +81 -0
  20. package/lib/budget/projections.ts +561 -0
  21. package/lib/budget/scenarios.ts +312 -0
  22. package/lib/cms/publish-blog.ts +129 -0
  23. package/lib/cms/strapi-client.ts +302 -0
  24. package/lib/config/registry.ts +228 -0
  25. package/lib/config/schema.ts +58 -0
  26. package/lib/config.ts +247 -0
  27. package/lib/errors.ts +129 -0
  28. package/lib/format.ts +120 -0
  29. package/lib/infra/.gitkeep +0 -0
  30. package/lib/infra/deploy.ts +70 -0
  31. package/lib/infra/migrate.ts +141 -0
  32. package/lib/newsletter/.gitkeep +0 -0
  33. package/lib/newsletter/distribute.ts +256 -0
  34. package/{dist/lib/newsletter/generate-insurance.d.ts → lib/newsletter/generate-insurance.ts} +24 -7
  35. package/lib/newsletter/generate.ts +735 -0
  36. package/lib/returnpro/.gitkeep +0 -0
  37. package/lib/returnpro/anomalies.ts +258 -0
  38. package/lib/returnpro/audit.ts +194 -0
  39. package/lib/returnpro/diagnose.ts +400 -0
  40. package/lib/returnpro/kpis.ts +255 -0
  41. package/lib/returnpro/templates.ts +323 -0
  42. package/lib/returnpro/upload-income.ts +311 -0
  43. package/lib/returnpro/upload-netsuite.ts +696 -0
  44. package/lib/returnpro/upload-r1.ts +563 -0
  45. package/lib/returnpro/validate.ts +154 -0
  46. package/lib/social/meta.ts +228 -0
  47. package/lib/social/post-generator.ts +468 -0
  48. package/lib/social/publish.ts +301 -0
  49. package/lib/social/scraper.ts +503 -0
  50. package/lib/supabase.ts +25 -0
  51. package/lib/transactions/delete-batch.ts +258 -0
  52. package/lib/transactions/ingest.ts +659 -0
  53. package/lib/transactions/stamp.ts +654 -0
  54. package/package.json +15 -25
  55. package/dist/bin/optimal.d.ts +0 -2
  56. package/dist/bin/optimal.js +0 -995
  57. package/dist/lib/budget/projections.d.ts +0 -115
  58. package/dist/lib/budget/projections.js +0 -384
  59. package/dist/lib/budget/scenarios.d.ts +0 -93
  60. package/dist/lib/budget/scenarios.js +0 -214
  61. package/dist/lib/cms/publish-blog.d.ts +0 -62
  62. package/dist/lib/cms/publish-blog.js +0 -74
  63. package/dist/lib/cms/strapi-client.d.ts +0 -123
  64. package/dist/lib/cms/strapi-client.js +0 -213
  65. package/dist/lib/config.d.ts +0 -55
  66. package/dist/lib/config.js +0 -206
  67. package/dist/lib/infra/deploy.d.ts +0 -29
  68. package/dist/lib/infra/deploy.js +0 -58
  69. package/dist/lib/infra/migrate.d.ts +0 -34
  70. package/dist/lib/infra/migrate.js +0 -103
  71. package/dist/lib/kanban.d.ts +0 -46
  72. package/dist/lib/kanban.js +0 -118
  73. package/dist/lib/newsletter/distribute.d.ts +0 -52
  74. package/dist/lib/newsletter/distribute.js +0 -193
  75. package/dist/lib/newsletter/generate-insurance.js +0 -36
  76. package/dist/lib/newsletter/generate.d.ts +0 -104
  77. package/dist/lib/newsletter/generate.js +0 -571
  78. package/dist/lib/returnpro/anomalies.d.ts +0 -64
  79. package/dist/lib/returnpro/anomalies.js +0 -166
  80. package/dist/lib/returnpro/audit.d.ts +0 -32
  81. package/dist/lib/returnpro/audit.js +0 -147
  82. package/dist/lib/returnpro/diagnose.d.ts +0 -52
  83. package/dist/lib/returnpro/diagnose.js +0 -281
  84. package/dist/lib/returnpro/kpis.d.ts +0 -32
  85. package/dist/lib/returnpro/kpis.js +0 -192
  86. package/dist/lib/returnpro/templates.d.ts +0 -48
  87. package/dist/lib/returnpro/templates.js +0 -229
  88. package/dist/lib/returnpro/upload-income.d.ts +0 -25
  89. package/dist/lib/returnpro/upload-income.js +0 -235
  90. package/dist/lib/returnpro/upload-netsuite.d.ts +0 -37
  91. package/dist/lib/returnpro/upload-netsuite.js +0 -566
  92. package/dist/lib/returnpro/upload-r1.d.ts +0 -48
  93. package/dist/lib/returnpro/upload-r1.js +0 -398
  94. package/dist/lib/social/post-generator.d.ts +0 -83
  95. package/dist/lib/social/post-generator.js +0 -333
  96. package/dist/lib/social/publish.d.ts +0 -66
  97. package/dist/lib/social/publish.js +0 -226
  98. package/dist/lib/social/scraper.d.ts +0 -67
  99. package/dist/lib/social/scraper.js +0 -361
  100. package/dist/lib/supabase.d.ts +0 -4
  101. package/dist/lib/supabase.js +0 -20
  102. package/dist/lib/transactions/delete-batch.d.ts +0 -60
  103. package/dist/lib/transactions/delete-batch.js +0 -203
  104. package/dist/lib/transactions/ingest.d.ts +0 -43
  105. package/dist/lib/transactions/ingest.js +0 -555
  106. package/dist/lib/transactions/stamp.d.ts +0 -51
  107. package/dist/lib/transactions/stamp.js +0 -524
File without changes
@@ -0,0 +1,256 @@
1
+ /**
2
+ * Newsletter Distribution Module
3
+ *
4
+ * Triggers newsletter distribution via the n8n webhook and updates
5
+ * Strapi delivery tracking fields accordingly.
6
+ *
7
+ * Functions:
8
+ * distributeNewsletter(documentId, opts?) — orchestrate distribution
9
+ * checkDistributionStatus(documentId) — read current delivery status
10
+ */
11
+
12
+ import 'dotenv/config'
13
+ import { strapiGet, strapiPut } from '../cms/strapi-client.js'
14
+
15
+ // ── Types ─────────────────────────────────────────────────────────────
16
+
17
+ export interface DistributionResult {
18
+ success: boolean
19
+ documentId: string
20
+ channel: string
21
+ webhookResponse?: unknown
22
+ error?: string
23
+ }
24
+
25
+ export interface DeliveryStatus {
26
+ documentId: string
27
+ delivery_status: string
28
+ delivered_at: string | null
29
+ recipients_count: number | null
30
+ ghl_campaign_id: string | null
31
+ delivery_errors: unknown[] | null
32
+ }
33
+
34
+ // Shape of the Strapi newsletter item's data fields we care about
35
+ interface NewsletterData {
36
+ documentId: string
37
+ publishedAt?: string | null
38
+ delivery_status?: string | null
39
+ delivered_at?: string | null
40
+ recipients_count?: number | null
41
+ ghl_campaign_id?: string | null
42
+ delivery_errors?: unknown[] | null
43
+ brand?: string
44
+ [key: string]: unknown
45
+ }
46
+
47
+ // ── Environment helpers ───────────────────────────────────────────────
48
+
49
+ function getWebhookUrl(): string {
50
+ const url = process.env.N8N_WEBHOOK_URL
51
+ if (!url) {
52
+ throw new Error(
53
+ 'Missing env var: N8N_WEBHOOK_URL\n' +
54
+ 'Set it to your n8n base URL, e.g. https://n8n.op-hub.com\n' +
55
+ 'The distribute module will POST to: $N8N_WEBHOOK_URL/webhook/newsletter-distribute',
56
+ )
57
+ }
58
+ return url.replace(/\/+$/, '')
59
+ }
60
+
61
+ // ── 1. Distribute Newsletter ──────────────────────────────────────────
62
+
63
+ /**
64
+ * Main orchestrator: fetch newsletter from Strapi, validate state,
65
+ * update delivery_status to 'sending', trigger the n8n webhook,
66
+ * and update tracking fields based on the result.
67
+ *
68
+ * @param documentId - Strapi documentId (UUID string) of the newsletter
69
+ * @param opts.channel - Distribution channel. Defaults to 'all'.
70
+ *
71
+ * @example
72
+ * const result = await distributeNewsletter('abc123-def456')
73
+ * const emailOnly = await distributeNewsletter('abc123-def456', { channel: 'email' })
74
+ */
75
+ export async function distributeNewsletter(
76
+ documentId: string,
77
+ opts: { channel?: 'email' | 'all' } = {},
78
+ ): Promise<DistributionResult> {
79
+ const channel = opts.channel ?? 'all'
80
+
81
+ // Step 1: Fetch the newsletter from Strapi
82
+ let newsletter: NewsletterData
83
+ try {
84
+ const response = await strapiGet<{ data: NewsletterData }>(
85
+ `/api/newsletters/${documentId}`,
86
+ )
87
+ newsletter = response.data
88
+ } catch (err) {
89
+ const msg = err instanceof Error ? err.message : String(err)
90
+ return {
91
+ success: false,
92
+ documentId,
93
+ channel,
94
+ error: `Failed to fetch newsletter from Strapi: ${msg}`,
95
+ }
96
+ }
97
+
98
+ // Step 2: Validate published state
99
+ if (!newsletter.publishedAt) {
100
+ return {
101
+ success: false,
102
+ documentId,
103
+ channel,
104
+ error:
105
+ 'Newsletter is not published. Publish it in Strapi before distributing.',
106
+ }
107
+ }
108
+
109
+ // Step 3: Validate delivery_status — only distribute if pending or unset
110
+ const currentStatus = newsletter.delivery_status ?? 'pending'
111
+ if (currentStatus !== 'pending' && currentStatus !== undefined) {
112
+ if (
113
+ currentStatus === 'sending' ||
114
+ currentStatus === 'delivered' ||
115
+ currentStatus === 'partial'
116
+ ) {
117
+ return {
118
+ success: false,
119
+ documentId,
120
+ channel,
121
+ error: `Newsletter already has delivery_status="${currentStatus}". Cannot re-distribute.`,
122
+ }
123
+ }
124
+ }
125
+
126
+ // Step 4: Mark as 'sending' in Strapi
127
+ try {
128
+ await strapiPut('/api/newsletters', documentId, {
129
+ delivery_status: 'sending',
130
+ })
131
+ } catch (err) {
132
+ const msg = err instanceof Error ? err.message : String(err)
133
+ return {
134
+ success: false,
135
+ documentId,
136
+ channel,
137
+ error: `Failed to update delivery_status to 'sending': ${msg}`,
138
+ }
139
+ }
140
+
141
+ // Step 5: Trigger n8n webhook
142
+ const webhookUrl = getWebhookUrl()
143
+ const webhookEndpoint = `${webhookUrl}/webhook/newsletter-distribute`
144
+ const brand = typeof newsletter.brand === 'string' ? newsletter.brand : ''
145
+
146
+ let webhookResponse: unknown
147
+ try {
148
+ const res = await fetch(webhookEndpoint, {
149
+ method: 'POST',
150
+ headers: { 'Content-Type': 'application/json' },
151
+ body: JSON.stringify({ documentId, brand, channel }),
152
+ })
153
+
154
+ if (!res.ok) {
155
+ let body: unknown
156
+ try {
157
+ body = await res.json()
158
+ } catch {
159
+ body = await res.text().catch(() => res.statusText)
160
+ }
161
+
162
+ // Webhook failed — update Strapi to 'failed' with error details
163
+ const errorDetails = [
164
+ { step: 'webhook', status: res.status, body },
165
+ ]
166
+ await strapiPut('/api/newsletters', documentId, {
167
+ delivery_status: 'failed',
168
+ delivery_errors: errorDetails,
169
+ }).catch(() => {
170
+ // Best-effort update — don't mask the original error
171
+ })
172
+
173
+ return {
174
+ success: false,
175
+ documentId,
176
+ channel,
177
+ error: `n8n webhook returned ${res.status}: ${JSON.stringify(body)}`,
178
+ }
179
+ }
180
+
181
+ try {
182
+ webhookResponse = await res.json()
183
+ } catch {
184
+ webhookResponse = { status: res.status }
185
+ }
186
+ } catch (err) {
187
+ // Network/connection error
188
+ const msg = err instanceof Error ? err.message : String(err)
189
+ const errorDetails = [{ step: 'webhook', error: msg }]
190
+
191
+ await strapiPut('/api/newsletters', documentId, {
192
+ delivery_status: 'failed',
193
+ delivery_errors: errorDetails,
194
+ }).catch(() => {
195
+ // Best-effort
196
+ })
197
+
198
+ return {
199
+ success: false,
200
+ documentId,
201
+ channel,
202
+ error: `n8n webhook request failed: ${msg}`,
203
+ }
204
+ }
205
+
206
+ // Step 6: Webhook succeeded — return success
207
+ // Note: n8n will update delivery_status to 'delivered' (or 'partial') via its
208
+ // own Strapi PUT once it finishes sending. We don't update it here.
209
+ return {
210
+ success: true,
211
+ documentId,
212
+ channel,
213
+ webhookResponse,
214
+ }
215
+ }
216
+
217
+ // ── 2. Check Distribution Status ─────────────────────────────────────
218
+
219
+ /**
220
+ * Fetch the current delivery tracking fields for a newsletter from Strapi.
221
+ *
222
+ * @param documentId - Strapi documentId (UUID string) of the newsletter
223
+ *
224
+ * @example
225
+ * const status = await checkDistributionStatus('abc123-def456')
226
+ * console.log(status.delivery_status) // 'delivered'
227
+ * console.log(status.recipients_count) // 847
228
+ */
229
+ export async function checkDistributionStatus(
230
+ documentId: string,
231
+ ): Promise<DeliveryStatus> {
232
+ const response = await strapiGet<{ data: NewsletterData }>(
233
+ `/api/newsletters/${documentId}`,
234
+ )
235
+
236
+ const data = response.data
237
+
238
+ return {
239
+ documentId,
240
+ delivery_status: typeof data.delivery_status === 'string'
241
+ ? data.delivery_status
242
+ : 'pending',
243
+ delivered_at: typeof data.delivered_at === 'string'
244
+ ? data.delivered_at
245
+ : null,
246
+ recipients_count: typeof data.recipients_count === 'number'
247
+ ? data.recipients_count
248
+ : null,
249
+ ghl_campaign_id: typeof data.ghl_campaign_id === 'string'
250
+ ? data.ghl_campaign_id
251
+ : null,
252
+ delivery_errors: Array.isArray(data.delivery_errors)
253
+ ? data.delivery_errors
254
+ : null,
255
+ }
256
+ }
@@ -9,21 +9,29 @@
9
9
  *
10
10
  * Ported from: ~/projects/newsletter-automation/generate-newsletter-lifeinsur.py
11
11
  */
12
- import { type GenerateResult } from './generate.js';
12
+
13
+ import { generateNewsletter, type GenerateResult } from './generate.js'
14
+
15
+ // ── Types ─────────────────────────────────────────────────────────────
16
+
13
17
  /** Options accepted by generateInsuranceNewsletter() */
14
18
  export interface InsuranceNewsletterOptions {
15
- /** ISO date string (YYYY-MM-DD) for the edition date; defaults to today */
16
- date?: string;
17
- /** When true, skips the Strapi push and returns the generated payload only */
18
- dryRun?: boolean;
19
+ /** ISO date string (YYYY-MM-DD) for the edition date; defaults to today */
20
+ date?: string
21
+ /** When true, skips the Strapi push and returns the generated payload only */
22
+ dryRun?: boolean
19
23
  }
24
+
20
25
  /**
21
26
  * Result returned by generateInsuranceNewsletter().
22
27
  * Aliased from GenerateResult for a consistent public API surface;
23
28
  * all fields are identical — import GenerateResult from generate.ts if you
24
29
  * need the underlying type directly.
25
30
  */
26
- export type NewsletterResult = GenerateResult;
31
+ export type NewsletterResult = GenerateResult
32
+
33
+ // ── Orchestrator ──────────────────────────────────────────────────────
34
+
27
35
  /**
28
36
  * Generate a LIFEINSUR newsletter for Anchor Point Insurance Co.
29
37
  *
@@ -39,4 +47,13 @@ export type NewsletterResult = GenerateResult;
39
47
  * const result = await generateInsuranceNewsletter({ dryRun: false })
40
48
  * console.log(result.strapiDocumentId)
41
49
  */
42
- export declare function generateInsuranceNewsletter(options?: InsuranceNewsletterOptions): Promise<NewsletterResult>;
50
+ export async function generateInsuranceNewsletter(
51
+ options: InsuranceNewsletterOptions = {},
52
+ ): Promise<NewsletterResult> {
53
+ return generateNewsletter({
54
+ brand: 'LIFEINSUR',
55
+ date: options.date,
56
+ dryRun: options.dryRun,
57
+ // No excelPath — LIFEINSUR has no property listings
58
+ })
59
+ }