blax
Version:
Blax - HMS-Powered Multi-Agent Platform with Government Agency Analysis, Deep Research, and Enterprise-Ready Deployment. No local LLM keys required.
362 lines • 12.6 kB
JavaScript
import { EventEmitter } from 'events';
export var DealStatus;
(function (DealStatus) {
DealStatus["CREATED"] = "created";
DealStatus["PLANNING"] = "planning";
DealStatus["IN_PROGRESS"] = "in_progress";
DealStatus["REVIEW"] = "review";
DealStatus["COMPLETED"] = "completed";
DealStatus["CANCELLED"] = "cancelled";
DealStatus["FAILED"] = "failed";
})(DealStatus || (DealStatus = {}));
/**
* Deal Registry for managing collaborative deals
* Provides CRUD operations and business logic for deal lifecycle
*/
export class DealRegistry extends EventEmitter {
deals = new Map();
dealMetrics = new Map();
initialized = false;
constructor() {
super();
}
async initialize() {
if (this.initialized)
return;
// In a full implementation, this would load deals from persistent storage
this.initialized = true;
this.emit('initialized');
}
/**
* Create a new deal
*/
async createDeal(request) {
const dealId = this.generateDealId();
const now = new Date();
// Generate stakeholder IDs
const stakeholders = request.stakeholders.map((s, index) => ({
...s,
id: `${dealId}_stakeholder_${index + 1}`
}));
const deal = {
dealId,
name: request.name,
problem: request.problem,
description: request.description || '',
proposedSolutions: [],
stakeholders,
financing: request.financing,
metrics: [],
status: DealStatus.CREATED,
priority: request.priority || 'medium',
tags: request.tags || [],
createdAt: now,
updatedAt: now,
deadline: request.deadline,
assignedAgents: [],
progress: 0,
currentPhase: 'initialization',
expectedValue: request.financing.totalBudget,
requiredStandards: request.requiredStandards || [],
complianceStatus: {},
auditLog: [{
timestamp: now,
actor: 'system',
action: 'deal_created',
details: { source: 'api' }
}],
metadata: request.metadata || {}
};
// Initialize compliance status
for (const standard of deal.requiredStandards) {
deal.complianceStatus[standard] = 'pending';
}
this.deals.set(dealId, deal);
this.initializeDealMetrics(deal);
this.emit('dealCreated', deal);
return deal;
}
/**
* Get a deal by ID
*/
async getDeal(dealId) {
return this.deals.get(dealId) || null;
}
/**
* Update a deal
*/
async updateDeal(dealId, updates, actor = 'system') {
const deal = this.deals.get(dealId);
if (!deal)
return null;
const oldStatus = deal.status;
const updatedDeal = {
...deal,
...updates,
updatedAt: new Date()
};
// Add audit log entry
updatedDeal.auditLog.push({
timestamp: new Date(),
actor,
action: 'deal_updated',
details: {
changes: updates,
previousStatus: oldStatus
}
});
this.deals.set(dealId, updatedDeal);
this.updateDealMetrics(updatedDeal);
this.emit('dealUpdated', { deal: updatedDeal, changes: updates, actor });
// Emit status change event if status changed
if (updates.status && updates.status !== oldStatus) {
this.emit('dealStatusChanged', {
deal: updatedDeal,
oldStatus,
newStatus: updates.status
});
}
return updatedDeal;
}
/**
* Delete a deal
*/
async deleteDeal(dealId, actor = 'system') {
const deal = this.deals.get(dealId);
if (!deal)
return false;
// Add final audit log
deal.auditLog.push({
timestamp: new Date(),
actor,
action: 'deal_deleted',
details: { finalStatus: deal.status }
});
this.deals.delete(dealId);
this.dealMetrics.delete(dealId);
this.emit('dealDeleted', { deal, actor });
return true;
}
/**
* Search deals
*/
async searchDeals(query) {
let filteredDeals = Array.from(this.deals.values());
// Apply filters
if (query.status?.length) {
filteredDeals = filteredDeals.filter(deal => query.status.includes(deal.status));
}
if (query.priority?.length) {
filteredDeals = filteredDeals.filter(deal => query.priority.includes(deal.priority));
}
if (query.tags?.length) {
filteredDeals = filteredDeals.filter(deal => query.tags.some(tag => deal.tags.includes(tag)));
}
if (query.stakeholders?.length) {
filteredDeals = filteredDeals.filter(deal => deal.stakeholders.some(s => query.stakeholders.includes(s.name)));
}
if (query.assignedAgents?.length) {
filteredDeals = filteredDeals.filter(deal => deal.assignedAgents.some(agent => query.assignedAgents.includes(agent)));
}
if (query.createdAfter) {
filteredDeals = filteredDeals.filter(deal => deal.createdAt >= query.createdAfter);
}
if (query.createdBefore) {
filteredDeals = filteredDeals.filter(deal => deal.createdAt <= query.createdBefore);
}
if (query.minValue !== undefined) {
filteredDeals = filteredDeals.filter(deal => deal.expectedValue >= query.minValue);
}
if (query.maxValue !== undefined) {
filteredDeals = filteredDeals.filter(deal => deal.expectedValue <= query.maxValue);
}
if (query.standards?.length) {
filteredDeals = filteredDeals.filter(deal => query.standards.some(standard => deal.requiredStandards.includes(standard)));
}
if (query.textSearch) {
const searchTerm = query.textSearch.toLowerCase();
filteredDeals = filteredDeals.filter(deal => deal.name.toLowerCase().includes(searchTerm) ||
deal.problem.toLowerCase().includes(searchTerm) ||
deal.description.toLowerCase().includes(searchTerm));
}
const total = filteredDeals.length;
// Apply pagination
const offset = query.offset || 0;
const limit = query.limit || 50;
const paginatedDeals = filteredDeals.slice(offset, offset + limit);
return { deals: paginatedDeals, total };
}
/**
* Add a solution to a deal
*/
async addSolution(dealId, solution, actor = 'system') {
const deal = this.deals.get(dealId);
if (!deal)
return null;
const fullSolution = {
...solution,
solutionId: `${dealId}_solution_${deal.proposedSolutions.length + 1}`
};
deal.proposedSolutions.push(fullSolution);
deal.updatedAt = new Date();
// Add audit log
deal.auditLog.push({
timestamp: new Date(),
actor,
action: 'solution_added',
details: { solutionId: fullSolution.solutionId, name: fullSolution.name }
});
this.updateDealMetrics(deal);
this.emit('solutionAdded', { deal, solution: fullSolution, actor });
return fullSolution;
}
/**
* Add a metric to a deal
*/
async addMetric(dealId, metric, actor = 'system') {
const deal = this.deals.get(dealId);
if (!deal)
return null;
const fullMetric = {
...metric,
metricId: `${dealId}_metric_${deal.metrics.length + 1}`,
lastUpdated: new Date()
};
deal.metrics.push(fullMetric);
deal.updatedAt = new Date();
// Add audit log
deal.auditLog.push({
timestamp: new Date(),
actor,
action: 'metric_added',
details: { metricId: fullMetric.metricId, name: fullMetric.name }
});
this.updateDealMetrics(deal);
this.emit('metricAdded', { deal, metric: fullMetric, actor });
return fullMetric;
}
/**
* Assign agents to a deal
*/
async assignAgents(dealId, agentIds, actor = 'system') {
const deal = this.deals.get(dealId);
if (!deal)
return false;
const newAgents = agentIds.filter(id => !deal.assignedAgents.includes(id));
deal.assignedAgents.push(...newAgents);
deal.updatedAt = new Date();
// Add audit log
deal.auditLog.push({
timestamp: new Date(),
actor,
action: 'agents_assigned',
details: { assignedAgents: newAgents }
});
this.emit('agentsAssigned', { deal, assignedAgents: newAgents, actor });
return true;
}
/**
* Get deal metrics
*/
async getDealMetrics(dealId) {
return this.dealMetrics.get(dealId) || null;
}
/**
* Get all deals
*/
getAllDeals() {
return Array.from(this.deals.values());
}
/**
* Get deal count by status
*/
getDealCountByStatus() {
const counts = Object.values(DealStatus).reduce((acc, status) => {
acc[status] = 0;
return acc;
}, {});
for (const deal of this.deals.values()) {
counts[deal.status]++;
}
return counts;
}
initializeDealMetrics(deal) {
const metrics = {
dealId: deal.dealId,
totalValue: deal.expectedValue,
valueDelta: 0,
completionPercentage: deal.progress,
metricsAttainability: this.calculateMetricsAttainability(deal),
riskScore: this.calculateRiskScore(deal),
complianceScore: this.calculateComplianceScore(deal),
stakeholderSatisfaction: 0.5, // Default neutral
agentEfficiency: 0.5, // Default neutral
lastUpdated: new Date()
};
this.dealMetrics.set(deal.dealId, metrics);
}
updateDealMetrics(deal) {
const existing = this.dealMetrics.get(deal.dealId);
if (!existing) {
this.initializeDealMetrics(deal);
return;
}
const updated = {
...existing,
totalValue: deal.expectedValue,
valueDelta: (deal.actualValue || 0) - deal.expectedValue,
completionPercentage: deal.progress,
metricsAttainability: this.calculateMetricsAttainability(deal),
riskScore: this.calculateRiskScore(deal),
complianceScore: this.calculateComplianceScore(deal),
lastUpdated: new Date()
};
this.dealMetrics.set(deal.dealId, updated);
}
calculateMetricsAttainability(deal) {
if (deal.metrics.length === 0)
return 1.0;
const attainableCount = deal.metrics.filter(m => m.attainable && m.measurable).length;
return attainableCount / deal.metrics.length;
}
calculateRiskScore(deal) {
if (deal.proposedSolutions.length === 0)
return 0.5;
let totalRisk = 0;
let riskCount = 0;
for (const solution of deal.proposedSolutions) {
for (const risk of solution.risks) {
totalRisk += risk.probability * risk.impact;
riskCount++;
}
}
return riskCount > 0 ? totalRisk / riskCount : 0.2;
}
calculateComplianceScore(deal) {
if (deal.requiredStandards.length === 0)
return 1.0;
const compliantCount = Object.values(deal.complianceStatus)
.filter(status => status === 'compliant').length;
return compliantCount / deal.requiredStandards.length;
}
generateDealId() {
const timestamp = Date.now().toString(36);
const random = Math.random().toString(36).substring(2, 8);
return `deal_${timestamp}_${random}`;
}
/**
* Health check
*/
async healthCheck() {
return {
status: 'healthy',
details: {
initialized: this.initialized,
dealCount: this.deals.size,
dealsByStatus: this.getDealCountByStatus(),
metricsCount: this.dealMetrics.size
}
};
}
}
//# sourceMappingURL=dealModel.js.map