turash/docs/api/matching.md
Damir Mukimov 000eab4740
Major repository reorganization and missing backend endpoints implementation
Repository Structure:
- Move files from cluttered root directory into organized structure
- Create archive/ for archived data and scraper results
- Create bugulma/ for the complete application (frontend + backend)
- Create data/ for sample datasets and reference materials
- Create docs/ for comprehensive documentation structure
- Create scripts/ for utility scripts and API tools

Backend Implementation:
- Implement 3 missing backend endpoints identified in gap analysis:
  * GET /api/v1/organizations/{id}/matching/direct - Direct symbiosis matches
  * GET /api/v1/users/me/organizations - User organizations
  * POST /api/v1/proposals/{id}/status - Update proposal status
- Add complete proposal domain model, repository, and service layers
- Create database migration for proposals table
- Fix CLI server command registration issue

API Documentation:
- Add comprehensive proposals.md API documentation
- Update README.md with Users and Proposals API sections
- Document all request/response formats, error codes, and business rules

Code Quality:
- Follow existing Go backend architecture patterns
- Add proper error handling and validation
- Match frontend expected response schemas
- Maintain clean separation of concerns (handler -> service -> repository)
2025-11-25 06:01:16 +01:00

374 lines
8.2 KiB
Markdown

# Matching API
API endpoints for resource matching and optimization.
## Match Query Request
```json
{
"resource": {
"type": "waste_heat",
"direction": "supply",
"site_id": "uuid-optional",
"temperature_range": {
"min_celsius": 60.0,
"max_celsius": 120.0
},
"quantity_range": {
"min_amount": 100.0,
"max_amount": 1000.0,
"unit": "kW"
},
"quality_requirements": {
"min_purity_pct": 95.0,
"max_contamination_mg_kg": 100.0,
"required_certifications": ["ISO9001"],
"ph_range": {
"min": 6.5,
"max": 8.5
}
}
},
"constraints": {
"max_distance_km": 50.0,
"min_economic_value": 1000.0,
"precision_preference": ["exact", "measured", "estimated"],
"max_results": 20,
"organization_filters": {
"sector": "Manufacturing",
"min_trust_score": 0.7,
"preferred_partners": ["org-uuid-1", "org-uuid-2"]
},
"temporal_requirements": {
"availability_pattern": "continuous",
"min_overlap_hours_week": 40
}
},
"scoring_weights": {
"distance_weight": 0.3,
"economic_weight": 0.4,
"quality_weight": 0.2,
"trust_weight": 0.1
}
}
```
## Resource Types
- `waste_heat`: Thermal waste heat
- `excess_electricity`: Surplus electrical power
- `industrial_waste`: Manufacturing byproducts
- `water_waste`: Wastewater or process water
- `byproducts`: Production byproducts
- `cooling_water`: Excess cooling capacity
- `compressed_air`: Surplus compressed air
- `logistics`: Transportation capacity
- `materials`: Recyclable materials
- `service`: Service offerings
## Resource Directions
- `supply`: Resource available for provision
- `demand`: Resource needed for consumption
## Match Response
```json
{
"data": [
{
"id": "match-uuid",
"source_organization": {
"id": "org-uuid",
"name": "Supplier Company",
"sector": "Manufacturing"
},
"target_organization": {
"id": "org-uuid",
"name": "Consumer Company",
"sector": "Manufacturing"
},
"source_resource": {
"id": "resource-uuid",
"type": "waste_heat",
"direction": "supply",
"quantity": 500,
"unit": "kW",
"quality": {
"temperature_celsius": 80,
"purity_pct": 98
}
},
"target_resource": {
"id": "resource-uuid",
"type": "waste_heat",
"direction": "demand",
"quantity": 400,
"unit": "kW"
},
"compatibility_score": 0.92,
"temporal_overlap_score": 0.95,
"quality_score": 0.88,
"economic_value": 25000,
"distance_km": 15.5,
"transportation_estimate": {
"cost_per_year": 5000,
"method": "piping",
"feasibility_score": 0.95
},
"risk_assessment": {
"technical_risk": 0.1,
"regulatory_risk": 0.05,
"market_risk": 0.2,
"counterparty_risk": 0.15
},
"economic_impact": {
"annual_savings": 30000,
"npv": 150000,
"irr": 0.25,
"payback_years": 2.1,
"co2_avoided_tonnes": 150,
"capex_required": 25000,
"opex_per_year": 3000
},
"status": "suggested",
"priority": 8,
"suggested_actions": [
{
"type": "contact",
"description": "Initiate contact with supplier",
"priority": "high"
},
{
"type": "feasibility_study",
"description": "Conduct technical feasibility assessment",
"estimated_cost": 5000
}
],
"created_at": "2025-01-15T10:00:00Z",
"expires_at": "2025-02-15T10:00:00Z"
}
],
"metadata": {
"total_matches": 45,
"search_criteria": {},
"processing_time_ms": 250,
"algorithm_version": "2.1.0"
}
}
```
## Match Status Values
- `suggested`: Initial algorithmic match, not reviewed
- `negotiating`: Organizations in active discussion
- `reserved`: Match reserved for a period
- `contracted`: Formal agreement reached
- `live`: Active resource exchange
- `failed`: Match attempt unsuccessful
- `cancelled`: Match cancelled by participants
## API Endpoints
### Find Matches
```http
POST /api/v1/matching/find
```
**Request Body:** MatchQueryRequest (see schema above)
**Response:** MatchResponse with array of potential matches
### Get Top Matches
```http
GET /api/v1/matching/top
```
**Query Parameters:**
- `limit` (int, optional): Maximum results (default: 10)
- `resource_type` (string, optional): Filter by resource type
- `min_score` (float, optional): Minimum compatibility score (0.0-1.0)
**Response:** Array of highest-scoring matches
### Create Match from Query
```http
POST /api/v1/matching/create-from-query
```
**Request Body:**
```json
{
"query": MatchQueryRequest,
"match_override": {
"priority": 9,
"notes": "High-priority strategic match"
}
}
```
**Response:** Created match object
### Get Match Details
```http
GET /api/v1/matching/{matchId}
```
**Response:** Complete match object with negotiation history
### Update Match Status
```http
PUT /api/v1/matching/{matchId}/status
```
**Request Body:**
```json
{
"status": "negotiating",
"notes": "Initial contact established",
"participants": ["org-uuid-1", "org-uuid-2"]
}
```
**Response:** Updated match object
## Negotiation History
Each match maintains a complete negotiation history:
```json
{
"id": "negotiation-uuid",
"match_id": "match-uuid",
"timestamp": "2025-01-15T14:30:00Z",
"actor_id": "user-uuid",
"action": "proposed",
"notes": "Initial proposal submitted",
"old_value": null,
"new_value": {
"status": "negotiating",
"proposed_terms": {
"price_per_unit": 0.15,
"contract_duration_months": 24
}
},
"attachments": [
"https://api.turash.com/static/attachments/proposal_v1.pdf"
],
"metadata": {
"confidence_level": 0.85,
"automated_action": false
}
}
```
## Contract Details
When matches progress to formal agreements:
```json
{
"contract_id": "CTR-2025-001",
"signed_at": "2025-01-20T09:00:00Z",
"effective_from": "2025-02-01T00:00:00Z",
"termination_date": "2027-01-31T23:59:59Z",
"value_per_year": 25000,
"terms_url": "https://api.turash.com/contracts/CTR-2025-001.pdf",
"payment_terms": "Monthly in advance",
"termination_terms": "90 days notice",
"signatures": [
{
"organization_id": "org-uuid-1",
"signer_name": "John Doe",
"signer_title": "Operations Director",
"signed_at": "2025-01-20T09:00:00Z"
}
]
}
```
## Scoring Algorithm
Matches are scored using a multi-factor algorithm:
### Compatibility Score (0.0-1.0)
- **Distance Factor**: Inverse relationship with distance
- **Economic Value**: Direct relationship with potential savings
- **Quality Match**: Compatibility of resource specifications
- **Trust Score**: Organization reliability rating
- **Temporal Overlap**: Availability alignment
### Weights Configuration
```json
{
"distance_weight": 0.25,
"economic_weight": 0.35,
"quality_weight": 0.25,
"trust_weight": 0.15
}
```
## Transportation Estimation
Automatic calculation of transportation costs and feasibility:
### Methods
- `piping`: For fluids (water, steam, gases)
- `truck`: Road transportation
- `tanker`: Bulk liquid transport
- `conveyor`: Solid material transport
- `rail`: Rail transportation
### Feasibility Scoring
- **0.0-0.3**: Not feasible
- **0.3-0.7**: Requires engineering study
- **0.7-1.0**: Readily implementable
## Risk Assessment
Comprehensive risk evaluation:
- **Technical Risk**: Equipment compatibility, maintenance requirements
- **Regulatory Risk**: Permits, compliance, environmental regulations
- **Market Risk**: Price volatility, demand fluctuations
- **Counterparty Risk**: Partner reliability, contract compliance
## Error Handling
### Invalid Query
```json
{
"error": "Invalid match query",
"details": {
"resource.type": "Resource type is required",
"constraints.max_distance_km": "Maximum distance cannot exceed 500km"
}
}
```
### No Matches Found
```json
{
"error": "No matches found",
"details": {
"suggestions": [
"Try increasing maximum distance",
"Consider alternative resource types",
"Review quality requirements"
]
}
}
```
### Match Not Found
```json
{
"error": "Match not found"
}
```