business-as-code 2.0.2 → 2.1.1

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # business-as-code
2
2
 
3
+ ## 2.1.1
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [6beb531]
8
+ - ai-functions@2.1.1
9
+ - ai-database@2.1.1
10
+
11
+ ## 2.0.3
12
+
13
+ ### Patch Changes
14
+
15
+ - Updated dependencies
16
+ - rpc.do@0.2.0
17
+ - ai-database@2.0.3
18
+ - ai-functions@2.0.3
19
+
3
20
  ## 2.0.2
4
21
 
5
22
  ### Patch Changes
@@ -0,0 +1,282 @@
1
+ /**
2
+ * Basic usage example for business-as-code
3
+ *
4
+ * This example demonstrates how to define business entities, goals, products,
5
+ * KPIs, OKRs, and calculate financial metrics.
6
+ */
7
+ import { Business, Vision, Goals, Product, Service, Process, Workflow, kpis, okrs, financials, $, } from '../src/index.js';
8
+ // Define your business
9
+ const company = Business({
10
+ name: 'Acme Corp',
11
+ description: 'Building the future of widgets',
12
+ industry: 'Technology',
13
+ mission: 'To make widgets accessible to everyone',
14
+ values: ['Innovation', 'Customer Focus', 'Integrity'],
15
+ targetMarket: 'SMB and Enterprise',
16
+ foundedAt: new Date('2020-01-01'),
17
+ teamSize: 50,
18
+ structure: {
19
+ departments: [
20
+ {
21
+ name: 'Engineering',
22
+ head: 'Jane Smith',
23
+ members: ['Alice', 'Bob', 'Charlie'],
24
+ budget: 2000000,
25
+ },
26
+ {
27
+ name: 'Sales',
28
+ head: 'John Doe',
29
+ members: ['David', 'Eve'],
30
+ budget: 1000000,
31
+ },
32
+ ],
33
+ },
34
+ });
35
+ // Define vision
36
+ const vision = Vision({
37
+ statement: 'To become the world\'s most trusted widget platform',
38
+ timeframe: '5 years',
39
+ successIndicators: [
40
+ '10M+ active users',
41
+ 'Present in 50+ countries',
42
+ 'Industry-leading NPS score',
43
+ '$1B+ annual revenue',
44
+ ],
45
+ });
46
+ // Define goals
47
+ const goals = Goals([
48
+ {
49
+ name: 'Launch MVP',
50
+ description: 'Ship minimum viable product to early customers',
51
+ category: 'strategic',
52
+ targetDate: new Date('2024-06-30'),
53
+ owner: 'Product Team',
54
+ metrics: ['User signups', 'Feature completion rate'],
55
+ status: 'in-progress',
56
+ progress: 65,
57
+ },
58
+ {
59
+ name: 'Achieve Product-Market Fit',
60
+ description: 'Validate product value with target customers',
61
+ category: 'strategic',
62
+ targetDate: new Date('2024-12-31'),
63
+ owner: 'CEO',
64
+ metrics: ['NPS > 50', 'Churn < 5%', '100+ paying customers'],
65
+ status: 'in-progress',
66
+ progress: 30,
67
+ dependencies: ['Launch MVP'],
68
+ },
69
+ ]);
70
+ // Define products
71
+ const product = Product({
72
+ name: 'Widget Pro',
73
+ description: 'Enterprise-grade widget management platform',
74
+ category: 'SaaS',
75
+ targetSegment: 'Enterprise',
76
+ valueProposition: 'Reduce widget management costs by 50%',
77
+ pricingModel: 'subscription',
78
+ price: 99,
79
+ currency: 'USD',
80
+ cogs: 20,
81
+ features: [
82
+ 'Unlimited widgets',
83
+ 'Advanced analytics',
84
+ 'API access',
85
+ '24/7 support',
86
+ ],
87
+ roadmap: [
88
+ {
89
+ name: 'Mobile app',
90
+ description: 'Native iOS and Android apps',
91
+ targetDate: new Date('2024-09-01'),
92
+ priority: 'high',
93
+ status: 'in-progress',
94
+ },
95
+ ],
96
+ });
97
+ // Define services
98
+ const service = Service({
99
+ name: 'Widget Consulting',
100
+ description: 'Expert widget implementation and optimization',
101
+ category: 'Consulting',
102
+ targetSegment: 'Enterprise',
103
+ valueProposition: 'Get expert help implementing widgets in 2 weeks',
104
+ pricingModel: 'fixed',
105
+ price: 5000,
106
+ currency: 'USD',
107
+ deliveryTime: '2 weeks',
108
+ sla: {
109
+ uptime: 99.9,
110
+ responseTime: '< 24 hours',
111
+ supportHours: 'Business hours (9-5 EST)',
112
+ penalties: '10% refund per day of delay',
113
+ },
114
+ });
115
+ // Define a business process
116
+ const process = Process({
117
+ name: 'Customer Onboarding',
118
+ description: 'Process for onboarding new customers',
119
+ category: 'core',
120
+ owner: 'Customer Success Team',
121
+ steps: [
122
+ {
123
+ order: 1,
124
+ name: 'Welcome Email',
125
+ description: 'Send personalized welcome email',
126
+ responsible: 'CS Manager',
127
+ duration: '5 minutes',
128
+ automationLevel: 'automated',
129
+ },
130
+ {
131
+ order: 2,
132
+ name: 'Initial Setup Call',
133
+ description: 'Schedule and conduct setup call',
134
+ responsible: 'CS Rep',
135
+ duration: '30 minutes',
136
+ automationLevel: 'manual',
137
+ },
138
+ ],
139
+ inputs: ['Customer Information', 'Subscription Plan'],
140
+ outputs: ['Configured Account', 'Training Materials'],
141
+ });
142
+ // Define a workflow
143
+ const workflow = Workflow({
144
+ name: 'New Customer Welcome',
145
+ description: 'Automated welcome sequence for new customers',
146
+ trigger: {
147
+ type: 'event',
148
+ event: 'Customer.created',
149
+ },
150
+ actions: [
151
+ {
152
+ order: 1,
153
+ type: 'send',
154
+ description: 'Send welcome email',
155
+ params: {
156
+ template: 'welcome_email',
157
+ to: '{{customer.email}}',
158
+ },
159
+ },
160
+ {
161
+ order: 2,
162
+ type: 'create',
163
+ description: 'Create onboarding task',
164
+ params: {
165
+ type: 'Task',
166
+ title: 'Onboard {{customer.name}}',
167
+ assignee: 'customer_success_team',
168
+ },
169
+ },
170
+ ],
171
+ });
172
+ // Track KPIs
173
+ const kpiList = kpis([
174
+ {
175
+ name: 'Monthly Recurring Revenue',
176
+ description: 'Total predictable revenue per month',
177
+ category: 'financial',
178
+ unit: 'USD',
179
+ target: 100000,
180
+ current: 85000,
181
+ frequency: 'monthly',
182
+ dataSource: 'Billing System',
183
+ formula: 'SUM(active_subscriptions.price)',
184
+ },
185
+ {
186
+ name: 'Customer Churn Rate',
187
+ description: 'Percentage of customers lost per month',
188
+ category: 'customer',
189
+ unit: 'percent',
190
+ target: 5,
191
+ current: 3.2,
192
+ frequency: 'monthly',
193
+ dataSource: 'CRM',
194
+ formula: '(churned_customers / total_customers) * 100',
195
+ },
196
+ {
197
+ name: 'Net Promoter Score',
198
+ description: 'Customer satisfaction and loyalty metric',
199
+ category: 'customer',
200
+ unit: 'score',
201
+ target: 50,
202
+ current: 48,
203
+ frequency: 'quarterly',
204
+ dataSource: 'Survey Platform',
205
+ },
206
+ ]);
207
+ // Define OKRs
208
+ const okrList = okrs([
209
+ {
210
+ objective: 'Achieve Product-Market Fit',
211
+ description: 'Validate that our product solves a real problem for customers',
212
+ period: 'Q2 2024',
213
+ owner: 'CEO',
214
+ keyResults: [
215
+ {
216
+ description: 'Increase Net Promoter Score',
217
+ metric: 'NPS',
218
+ startValue: 40,
219
+ targetValue: 60,
220
+ currentValue: 52,
221
+ unit: 'score',
222
+ },
223
+ {
224
+ description: 'Reduce monthly churn rate',
225
+ metric: 'Churn Rate',
226
+ startValue: 8,
227
+ targetValue: 4,
228
+ currentValue: 5.5,
229
+ unit: 'percent',
230
+ },
231
+ {
232
+ description: 'Achieve customer retention',
233
+ metric: 'Customers with 3+ months',
234
+ startValue: 50,
235
+ targetValue: 200,
236
+ currentValue: 125,
237
+ unit: 'customers',
238
+ },
239
+ ],
240
+ status: 'on-track',
241
+ confidence: 75,
242
+ },
243
+ ]);
244
+ // Calculate financials
245
+ const metrics = financials({
246
+ revenue: 1000000,
247
+ cogs: 300000,
248
+ operatingExpenses: 500000,
249
+ currency: 'USD',
250
+ period: 'monthly',
251
+ });
252
+ // Use $ helper for calculations
253
+ console.log('\n=== Business Operations with $ ===');
254
+ console.log('Format currency:', $.format(1234.56));
255
+ console.log('Calculate percentage:', $.percent(25, 100));
256
+ console.log('Calculate growth:', $.growth(120, 100));
257
+ console.log('Calculate margin:', $.margin(100, 60));
258
+ console.log('Calculate ROI:', $.roi(150, 100));
259
+ console.log('Calculate LTV:', $.ltv(100, 12, 24));
260
+ console.log('Calculate CAC:', $.cac(10000, 100));
261
+ console.log('Calculate burn rate:', $.burnRate(100000, 70000, 3));
262
+ console.log('Calculate runway:', $.runway(100000, 10000));
263
+ // Display results
264
+ console.log('\n=== Business Summary ===');
265
+ console.log(`Company: ${company.name}`);
266
+ console.log(`Mission: ${company.mission}`);
267
+ console.log(`Team Size: ${company.teamSize}`);
268
+ console.log(`\nVision: ${vision.statement}`);
269
+ console.log(`Timeframe: ${vision.timeframe}`);
270
+ console.log(`\nGoals: ${goals.length}`);
271
+ console.log(`Products: ${product.name} - ${$.format(product.price)} ${product.pricingModel}`);
272
+ console.log(`Services: ${service.name} - ${$.format(service.price)} ${service.pricingModel}`);
273
+ console.log(`\nKPIs: ${kpiList.length}`);
274
+ console.log(`OKRs: ${okrList.length}`);
275
+ console.log(`\n=== Financial Metrics ===`);
276
+ console.log(`Revenue: ${$.format(metrics.revenue)}`);
277
+ console.log(`Gross Profit: ${$.format(metrics.grossProfit)}`);
278
+ console.log(`Gross Margin: ${metrics.grossMargin.toFixed(1)}%`);
279
+ console.log(`Operating Income: ${$.format(metrics.operatingIncome)}`);
280
+ console.log(`Operating Margin: ${metrics.operatingMargin.toFixed(1)}%`);
281
+ console.log(`Net Income: ${$.format(metrics.netIncome)}`);
282
+ console.log(`Net Margin: ${metrics.netMargin.toFixed(1)}%`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "business-as-code",
3
- "version": "2.0.2",
3
+ "version": "2.1.1",
4
4
  "description": "Primitives for expressing business logic and processes as code",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -20,9 +20,8 @@
20
20
  "clean": "rm -rf dist"
21
21
  },
22
22
  "dependencies": {
23
- "ai-database": "2.0.2",
24
- "ai-functions": "2.0.2",
25
- "rpc.do": "^0.1.0"
23
+ "ai-database": "2.1.1",
24
+ "ai-functions": "2.1.1"
26
25
  },
27
26
  "keywords": [
28
27
  "business",
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Business entity definition
3
+ */
4
+ /**
5
+ * Define a business entity with organizational structure, mission, and values
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * const acme = Business({
10
+ * name: 'Acme Corp',
11
+ * description: 'Building the future of widgets',
12
+ * industry: 'Technology',
13
+ * mission: 'To make widgets accessible to everyone',
14
+ * values: ['Innovation', 'Customer Focus', 'Integrity'],
15
+ * targetMarket: 'SMB and Enterprise',
16
+ * foundedAt: new Date('2020-01-01'),
17
+ * teamSize: 50,
18
+ * structure: {
19
+ * departments: [
20
+ * {
21
+ * name: 'Engineering',
22
+ * head: 'Jane Smith',
23
+ * members: ['Alice', 'Bob', 'Charlie'],
24
+ * budget: 2000000,
25
+ * },
26
+ * {
27
+ * name: 'Sales',
28
+ * head: 'John Doe',
29
+ * members: ['David', 'Eve'],
30
+ * budget: 1000000,
31
+ * },
32
+ * ],
33
+ * },
34
+ * })
35
+ * ```
36
+ */
37
+ export function Business(definition) {
38
+ // Validate required fields
39
+ if (!definition.name) {
40
+ throw new Error('Business name is required');
41
+ }
42
+ // Return validated business definition
43
+ return {
44
+ ...definition,
45
+ foundedAt: definition.foundedAt || new Date(),
46
+ teamSize: definition.teamSize || 0,
47
+ values: definition.values || [],
48
+ metadata: definition.metadata || {},
49
+ };
50
+ }
51
+ /**
52
+ * Get total budget across all departments
53
+ */
54
+ export function getTotalBudget(business) {
55
+ if (!business.structure?.departments)
56
+ return 0;
57
+ return business.structure.departments.reduce((total, dept) => {
58
+ return total + (dept.budget || 0);
59
+ }, 0);
60
+ }
61
+ /**
62
+ * Get total team size across all departments
63
+ */
64
+ export function getTotalTeamSize(business) {
65
+ if (!business.structure?.departments)
66
+ return business.teamSize || 0;
67
+ return business.structure.departments.reduce((total, dept) => {
68
+ return total + (dept.members?.length || 0);
69
+ }, 0);
70
+ }
71
+ /**
72
+ * Get department by name
73
+ */
74
+ export function getDepartment(business, name) {
75
+ return business.structure?.departments?.find(d => d.name === name);
76
+ }
77
+ /**
78
+ * Get team by name
79
+ */
80
+ export function getTeam(business, name) {
81
+ return business.structure?.teams?.find(t => t.name === name);
82
+ }
83
+ /**
84
+ * Validate business definition
85
+ */
86
+ export function validateBusiness(business) {
87
+ const errors = [];
88
+ if (!business.name) {
89
+ errors.push('Business name is required');
90
+ }
91
+ if (business.teamSize && business.teamSize < 0) {
92
+ errors.push('Team size cannot be negative');
93
+ }
94
+ if (business.structure?.departments) {
95
+ for (const dept of business.structure.departments) {
96
+ if (!dept.name) {
97
+ errors.push('Department name is required');
98
+ }
99
+ if (dept.budget && dept.budget < 0) {
100
+ errors.push(`Department ${dept.name} budget cannot be negative`);
101
+ }
102
+ }
103
+ }
104
+ return {
105
+ valid: errors.length === 0,
106
+ errors,
107
+ };
108
+ }
package/src/dollar.js ADDED
@@ -0,0 +1,106 @@
1
+ /**
2
+ * $ - Business operations helper
3
+ *
4
+ * Provides convenient functions for common business calculations and formatting
5
+ */
6
+ import { formatCurrency, calculateGrowthRate, calculateGrossMargin, calculateROI, calculateCAC, calculateBurnRate, calculateRunway, } from './financials.js';
7
+ /**
8
+ * Create a business operations helper with context
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * import { $ } from 'business-as-code'
13
+ *
14
+ * // Format currency
15
+ * console.log($.format(1234.56)) // "$1,234.56"
16
+ * console.log($.format(1000, 'EUR')) // "€1,000"
17
+ *
18
+ * // Calculate percentage
19
+ * console.log($.percent(25, 100)) // 25
20
+ *
21
+ * // Calculate growth
22
+ * console.log($.growth(120, 100)) // 20
23
+ *
24
+ * // Calculate margin
25
+ * console.log($.margin(100, 60)) // 40
26
+ *
27
+ * // Calculate ROI
28
+ * console.log($.roi(150, 100)) // 50
29
+ *
30
+ * // Calculate LTV
31
+ * console.log($.ltv(100, 12, 24)) // 28800
32
+ *
33
+ * // Calculate CAC
34
+ * console.log($.cac(10000, 100)) // 100
35
+ *
36
+ * // Calculate burn rate
37
+ * console.log($.burnRate(100000, 70000, 3)) // 10000
38
+ *
39
+ * // Calculate runway
40
+ * console.log($.runway(100000, 10000)) // 10
41
+ * ```
42
+ */
43
+ export function createBusinessOperations(initialContext) {
44
+ const context = initialContext || {};
45
+ return {
46
+ format: (amount, currency) => {
47
+ return formatCurrency(amount, currency || context.business?.metadata?.currency || 'USD');
48
+ },
49
+ percent: (value, total) => {
50
+ if (total === 0)
51
+ return 0;
52
+ return (value / total) * 100;
53
+ },
54
+ growth: (current, previous) => {
55
+ return calculateGrowthRate(current, previous);
56
+ },
57
+ margin: (revenue, cost) => {
58
+ return calculateGrossMargin(revenue, cost);
59
+ },
60
+ roi: (gain, cost) => {
61
+ return calculateROI(gain, cost);
62
+ },
63
+ ltv: (averageValue, frequency, lifetime) => {
64
+ // frequency = purchases per year, lifetime = years
65
+ const annualValue = averageValue * frequency;
66
+ return annualValue * lifetime;
67
+ },
68
+ cac: (marketingSpend, newCustomers) => {
69
+ return calculateCAC(marketingSpend, newCustomers);
70
+ },
71
+ burnRate: (cashStart, cashEnd, months) => {
72
+ return calculateBurnRate(cashStart, cashEnd, months);
73
+ },
74
+ runway: (cash, burnRate) => {
75
+ return calculateRunway(cash, burnRate);
76
+ },
77
+ context,
78
+ log: (event, data) => {
79
+ console.log(`[Business Event] ${event}`, data || '');
80
+ },
81
+ };
82
+ }
83
+ /**
84
+ * Default business operations instance
85
+ */
86
+ export const $ = createBusinessOperations();
87
+ /**
88
+ * Update business context
89
+ */
90
+ export function updateContext(updates) {
91
+ Object.assign($.context, updates);
92
+ }
93
+ /**
94
+ * Get current business context
95
+ */
96
+ export function getContext() {
97
+ return $.context;
98
+ }
99
+ /**
100
+ * Reset business context
101
+ */
102
+ export function resetContext() {
103
+ Object.keys($.context).forEach(key => {
104
+ delete $.context[key];
105
+ });
106
+ }