mirror of
https://github.com/SamyRai/turash.git
synced 2025-12-26 23:01:33 +00:00
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)
304 lines
15 KiB
Go
304 lines
15 KiB
Go
package domain
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
|
|
"gorm.io/datatypes"
|
|
)
|
|
|
|
type ResourceDirection string
|
|
type ResourceType string
|
|
type PrecisionLevel string
|
|
type SourceType string
|
|
type PhysicalState string
|
|
type SupplyPattern string
|
|
type TemporalUnit string
|
|
|
|
const (
|
|
DirectionInput ResourceDirection = "input"
|
|
DirectionOutput ResourceDirection = "output"
|
|
|
|
TypeHeat ResourceType = "heat"
|
|
TypeWater ResourceType = "water"
|
|
TypeSteam ResourceType = "steam"
|
|
TypeCO2 ResourceType = "CO2"
|
|
TypeBiowaste ResourceType = "biowaste"
|
|
TypeCooling ResourceType = "cooling"
|
|
TypeLogistics ResourceType = "logistics"
|
|
TypeMaterials ResourceType = "materials"
|
|
TypeService ResourceType = "service"
|
|
|
|
PrecisionRough PrecisionLevel = "rough"
|
|
PrecisionEstimated PrecisionLevel = "estimated"
|
|
PrecisionMeasured PrecisionLevel = "measured"
|
|
|
|
SourceDeclared SourceType = "declared"
|
|
SourceDevice SourceType = "device"
|
|
SourceCalculated SourceType = "calculated"
|
|
|
|
StateSolid PhysicalState = "solid"
|
|
StateLiquid PhysicalState = "liquid"
|
|
StateGas PhysicalState = "gas"
|
|
|
|
PatternContinuous SupplyPattern = "continuous"
|
|
PatternBatch SupplyPattern = "batch"
|
|
PatternSeasonal SupplyPattern = "seasonal"
|
|
PatternOnDemand SupplyPattern = "on_demand"
|
|
PatternIrregular SupplyPattern = "irregular"
|
|
|
|
UnitPerSecond TemporalUnit = "per_second"
|
|
UnitPerMinute TemporalUnit = "per_minute"
|
|
UnitPerHour TemporalUnit = "per_hour"
|
|
UnitPerDay TemporalUnit = "per_day"
|
|
UnitPerWeek TemporalUnit = "per_week"
|
|
UnitPerMonth TemporalUnit = "per_month"
|
|
UnitPerYear TemporalUnit = "per_year"
|
|
UnitContinuous TemporalUnit = "continuous"
|
|
)
|
|
|
|
// VolumePricingTier represents pricing tiers based on volume
|
|
type VolumePricingTier struct {
|
|
MinVolume float64 `json:"min_volume"` // Minimum volume for this tier
|
|
MaxVolume *float64 `json:"max_volume,omitempty"` // Maximum volume for this tier (nil for unlimited)
|
|
PricePerUnit float64 `json:"price_per_unit"` // €/unit for this tier
|
|
DiscountPct float64 `json:"discount_pct"` // % discount from base price
|
|
}
|
|
|
|
// ReliabilityEntry represents historical reliability data
|
|
type ReliabilityEntry struct {
|
|
Date time.Time `json:"date"` // Date of the entry
|
|
UptimePct float64 `json:"uptime_pct"` // % uptime for that period
|
|
OutagesCount int `json:"outages_count"` // Number of outages
|
|
TotalDowntime float64 `json:"total_downtime"` // Hours of total downtime
|
|
}
|
|
|
|
// EnvironmentalImpact represents environmental impact parameters
|
|
type EnvironmentalImpact struct {
|
|
CarbonFootprintKgCo2Eq float64 `json:"carbon_footprint_kg_co2_eq,omitempty"` // kg CO2 equivalent per unit
|
|
WaterUsageLiters float64 `json:"water_usage_liters,omitempty"` // Liters per unit
|
|
EnergyConsumptionKwh float64 `json:"energy_consumption_kwh,omitempty"` // kWh per unit
|
|
WasteGenerationKg float64 `json:"waste_generation_kg,omitempty"` // kg waste per unit
|
|
EmissionsByType map[string]float64 `json:"emissions_by_type,omitempty"` // Emissions by pollutant type
|
|
RenewableEnergyPct *float64 `json:"renewable_energy_pct,omitempty"` // % from renewable sources
|
|
CircularityScore *float64 `json:"circularity_score,omitempty"` // 0-1 circularity rating
|
|
}
|
|
|
|
// PerformanceMetrics represents performance and reliability metrics
|
|
type PerformanceMetrics struct {
|
|
AverageEfficiencyPct *float64 `json:"average_efficiency_pct,omitempty"` // % efficiency rating
|
|
PeakPerformanceValue *float64 `json:"peak_performance_value,omitempty"` // Peak performance value
|
|
DegradationRatePctYear *float64 `json:"degradation_rate_pct_year,omitempty"` // % degradation per year
|
|
MaintenanceIntervalDays *int `json:"maintenance_interval_days,omitempty"` // Days between maintenance
|
|
ExpectedLifespanYears *float64 `json:"expected_lifespan_years,omitempty"` // Expected operational life
|
|
ReliabilityScore *float64 `json:"reliability_score,omitempty"` // 0-1 reliability rating
|
|
LastPerformanceTestAt *time.Time `json:"last_performance_test_at,omitempty"` // Last performance test
|
|
}
|
|
|
|
// Quality represents comprehensive quality parameters of a resource flow
|
|
type Quality struct {
|
|
// Basic quality parameters
|
|
TemperatureCelsius *float64 `json:"temperature_celsius,omitempty"`
|
|
PressureBar *float64 `json:"pressure_bar,omitempty"`
|
|
PurityPct *float64 `json:"purity_pct,omitempty"`
|
|
Grade string `json:"grade,omitempty"`
|
|
Hazardousness bool `json:"hazardousness"`
|
|
Composition string `json:"composition,omitempty"`
|
|
PhysicalState PhysicalState `json:"physical_state,omitempty"`
|
|
|
|
// Advanced quality parameters
|
|
ViscosityCp *float64 `json:"viscosity_cp,omitempty"` // cP for liquids
|
|
ConductivityMsCm *float64 `json:"conductivity_ms_cm,omitempty"` // mS/cm for liquids
|
|
PhLevel *float64 `json:"ph_level,omitempty"` // pH for liquids
|
|
DensityKgM3 *float64 `json:"density_kg_m3,omitempty"` // kg/m³
|
|
ParticleSizeMicron *float64 `json:"particle_size_micron,omitempty"` // microns
|
|
|
|
// Energy content parameters
|
|
BtuContentMjKg *float64 `json:"btu_content_mj_kg,omitempty"` // MJ/kg for biomass
|
|
MoisturePct *float64 `json:"moisture_pct,omitempty"` // % moisture content
|
|
AshContentPct *float64 `json:"ash_content_pct,omitempty"` // % ash content
|
|
|
|
// Gas quality parameters
|
|
OxygenPct *float64 `json:"oxygen_pct,omitempty"` // % O2 content
|
|
CarbonDioxidePct *float64 `json:"carbon_dioxide_pct,omitempty"` // % CO2 content
|
|
MethanePct *float64 `json:"methane_pct,omitempty"` // % CH4 content
|
|
|
|
// Certifications and standards
|
|
Certifications []string `json:"certifications,omitempty"` // ISO, HACCP, etc.
|
|
StandardsCompliance []string `json:"standards_compliance,omitempty"` // Food-grade, industrial, etc.
|
|
|
|
// Quality metrics
|
|
QualityScore *float64 `json:"quality_score,omitempty"` // 0-100 quality rating
|
|
LastTestedAt *time.Time `json:"last_tested_at,omitempty"` // Last quality test date
|
|
TestFrequencyDays *int `json:"test_frequency_days,omitempty"` // How often tested
|
|
}
|
|
|
|
// Quantity represents quantity parameters of a resource flow
|
|
type Quantity struct {
|
|
Amount float64 `json:"amount"`
|
|
Unit string `json:"unit"`
|
|
TemporalUnit TemporalUnit `json:"temporal_unit,omitempty"`
|
|
Variability float64 `json:"variability,omitempty"` // 0-1 coefficient of variation
|
|
}
|
|
|
|
// EconomicData represents comprehensive economic parameters
|
|
type EconomicData struct {
|
|
// Basic pricing
|
|
CostIn float64 `json:"cost_in,omitempty"` // €/unit for inputs
|
|
CostOut float64 `json:"cost_out,omitempty"` // €/unit for outputs
|
|
WasteDisposalCost float64 `json:"waste_disposal_cost,omitempty"` // €/unit
|
|
PrimaryInputCost float64 `json:"primary_input_cost,omitempty"` // €/unit
|
|
TransportationCost float64 `json:"transportation_cost,omitempty"` // €/km
|
|
CostSharingFraction float64 `json:"cost_sharing_fraction,omitempty"` // 0-1
|
|
|
|
// Advanced cost structure
|
|
AmortizationCost float64 `json:"amortization_cost,omitempty"` // €/unit/year
|
|
MaintenanceCost float64 `json:"maintenance_cost,omitempty"` // €/unit/year
|
|
InsuranceCost float64 `json:"insurance_cost,omitempty"` // €/unit/year
|
|
OpportunityCost float64 `json:"opportunity_cost,omitempty"` // €/unit (alternative use value)
|
|
|
|
// Volume-based pricing
|
|
MinimumOrderQuantity *float64 `json:"minimum_order_quantity,omitempty"` // Minimum order size
|
|
BulkDiscountPct *float64 `json:"bulk_discount_pct,omitempty"` // % discount for large orders
|
|
VolumePricingTiers []VolumePricingTier `json:"volume_pricing_tiers,omitempty"`
|
|
|
|
// Supply chain costs
|
|
LeadTimeDays *int `json:"lead_time_days,omitempty"` // Days to deliver
|
|
SupplierReliability *float64 `json:"supplier_reliability,omitempty"` // 0-1 reliability score
|
|
StorageCost float64 `json:"storage_cost,omitempty"` // €/unit/day storage cost
|
|
|
|
// Environmental costs/benefits
|
|
CarbonCreditValue float64 `json:"carbon_credit_value,omitempty"` // €/tonne CO2 equivalent
|
|
EnvironmentalTax float64 `json:"environmental_tax,omitempty"` // €/unit environmental tax
|
|
}
|
|
|
|
// Constraints represents comprehensive constraints and requirements
|
|
type Constraints struct {
|
|
// Geographic constraints
|
|
MaxDistanceKm float64 `json:"max_distance_km,omitempty"`
|
|
PreferredRegions []string `json:"preferred_regions,omitempty"` // Geographic preferences
|
|
|
|
// Regulatory constraints
|
|
RequiresPermit bool `json:"requires_permit"`
|
|
PermitType string `json:"permit_type,omitempty"` // Type of permit required
|
|
RegulatoryCompliance bool `json:"regulatory_compliance"`
|
|
ComplianceCertifications []string `json:"compliance_certifications,omitempty"` // Required certifications
|
|
|
|
// Quality constraints
|
|
MinQualityThreshold string `json:"min_quality_threshold,omitempty"`
|
|
MaxContaminantPct *float64 `json:"max_contaminant_pct,omitempty"` // Maximum allowed contaminants
|
|
RequiredCertifications []string `json:"required_certifications,omitempty"` // ISO, HACCP, etc.
|
|
|
|
// Operational constraints
|
|
MaxDowntimeHours *int `json:"max_downtime_hours,omitempty"` // Maximum allowed downtime
|
|
MaintenanceWindows []string `json:"maintenance_windows,omitempty"` // Preferred maintenance periods
|
|
ReliabilityRequirement *float64 `json:"reliability_requirement,omitempty"` // Required uptime %
|
|
|
|
// Environmental constraints
|
|
MaxEmissionLimits map[string]float64 `json:"max_emission_limits,omitempty"` // Emission limits by type
|
|
WaterUsageLimits *float64 `json:"water_usage_limits,omitempty"` // m³/unit max water usage
|
|
WasteLimits map[string]float64 `json:"waste_limits,omitempty"` // Waste limits by type
|
|
}
|
|
|
|
// TimeRange represents a time range in HH:MM format
|
|
type TimeRange struct {
|
|
Start string `json:"start"` // HH:MM format
|
|
End string `json:"end"` // HH:MM format
|
|
}
|
|
|
|
// TimeProfile represents comprehensive temporal characteristics
|
|
type TimeProfile struct {
|
|
// Basic availability
|
|
Availability map[string]TimeRange `json:"availability,omitempty"` // day of week -> time range
|
|
Seasonality []string `json:"seasonality,omitempty"` // months when available
|
|
SupplyPattern SupplyPattern `json:"supply_pattern,omitempty"` // continuous, batch, seasonal, on_demand, irregular
|
|
|
|
// Advanced temporal parameters
|
|
PredictabilityScore *float64 `json:"predictability_score,omitempty"` // 0-1 how predictable the supply is
|
|
PeakDemandMonths []string `json:"peak_demand_months,omitempty"` // Months with highest demand
|
|
LowDemandMonths []string `json:"low_demand_months,omitempty"` // Months with lowest demand
|
|
LeadTimeDays *int `json:"lead_time_days,omitempty"` // Days notice required
|
|
MinimumNoticeHours *int `json:"minimum_notice_hours,omitempty"` // Minimum notice for changes
|
|
|
|
// Supply reliability
|
|
UptimePct *float64 `json:"uptime_pct,omitempty"` // % uptime historically
|
|
ReliabilityHistory []ReliabilityEntry `json:"reliability_history,omitempty"` // Historical reliability data
|
|
LastOutageAt *time.Time `json:"last_outage_at,omitempty"` // Last outage timestamp
|
|
AverageOutageDuration *float64 `json:"average_outage_duration,omitempty"` // Hours average outage duration
|
|
}
|
|
|
|
// ServiceDetails represents additional details for service-type resource flows
|
|
type ServiceDetails struct {
|
|
Domain string `json:"domain,omitempty"` // maintenance, consulting, transport, inspection
|
|
Mobility string `json:"mobility,omitempty"` // on_site, remote
|
|
CapacityHrsMonth float64 `json:"capacity_h_per_month,omitempty"` // hours per month
|
|
ServiceAreaKm float64 `json:"service_area_km,omitempty"` // service radius
|
|
}
|
|
|
|
// ResourceFlow represents resource inputs, outputs, and services at specific sites
|
|
type ResourceFlow struct {
|
|
ID string `gorm:"primaryKey;type:text"`
|
|
OrganizationID string `gorm:"type:text;not null;index:idx_rf_organization_site"`
|
|
SiteID string `gorm:"type:text;not null;index:idx_rf_organization_site"`
|
|
Direction ResourceDirection `gorm:"type:varchar(10);not null;index:idx_rf_type_direction"`
|
|
Type ResourceType `gorm:"type:varchar(50);not null;index:idx_rf_type_direction"`
|
|
|
|
// Quality parameters (stored as JSONB)
|
|
Quality datatypes.JSON `gorm:"type:jsonb"` // Quality
|
|
|
|
// Quantity parameters (stored as JSONB)
|
|
Quantity datatypes.JSON `gorm:"type:jsonb;not null"` // Quantity
|
|
|
|
// Time profile (stored as JSONB)
|
|
TimeProfile datatypes.JSON `gorm:"type:jsonb"` // TimeProfile
|
|
|
|
// Economic data (stored as JSONB)
|
|
EconomicData datatypes.JSON `gorm:"type:jsonb"` // EconomicData
|
|
|
|
// Constraints (stored as JSONB)
|
|
Constraints datatypes.JSON `gorm:"type:jsonb"` // Constraints
|
|
|
|
// Service details (stored as JSONB, for service-type flows)
|
|
ServiceDetails datatypes.JSON `gorm:"type:jsonb"` // ServiceDetails
|
|
|
|
// Environmental impact (stored as JSONB)
|
|
EnvironmentalImpact datatypes.JSON `gorm:"type:jsonb"` // EnvironmentalImpact
|
|
|
|
// Performance metrics (stored as JSONB)
|
|
PerformanceMetrics datatypes.JSON `gorm:"type:jsonb"` // PerformanceMetrics
|
|
|
|
// Data quality and source
|
|
PrecisionLevel PrecisionLevel `gorm:"type:varchar(20);default:'estimated';index"`
|
|
SourceType SourceType `gorm:"type:varchar(50);default:'declared'"`
|
|
DeviceSignature string `gorm:"type:varchar(255)"` // Cryptographic signature for verified device data
|
|
|
|
// Metadata
|
|
DataCompletenessScore float64 `gorm:"type:decimal(3,2);default:0.5"` // 0-1 how complete the data is
|
|
LastValidatedAt *time.Time `gorm:"index"` // Last time data was validated
|
|
|
|
// Timestamps
|
|
CreatedAt time.Time `gorm:"autoCreateTime;index"`
|
|
UpdatedAt time.Time `gorm:"autoUpdateTime;index"`
|
|
|
|
// Associations
|
|
Organization *Organization `gorm:"foreignKey:OrganizationID"`
|
|
Site *Site `gorm:"foreignKey:SiteID"`
|
|
}
|
|
|
|
// TableName specifies the table name for GORM
|
|
func (ResourceFlow) TableName() string {
|
|
return "resource_flows"
|
|
}
|
|
|
|
type ResourceFlowRepository interface {
|
|
Create(ctx context.Context, rf *ResourceFlow) error
|
|
GetByID(ctx context.Context, id string) (*ResourceFlow, error)
|
|
GetBySiteID(ctx context.Context, siteID string) ([]*ResourceFlow, error)
|
|
GetByOrganizationID(ctx context.Context, organizationID string) ([]*ResourceFlow, error)
|
|
GetByTypeAndDirection(ctx context.Context, resType ResourceType, direction ResourceDirection) ([]*ResourceFlow, error)
|
|
GetOutputsInRadius(ctx context.Context, lat, lng, radiusKm float64, resType ResourceType) ([]*ResourceFlow, error)
|
|
GetInputsInRadius(ctx context.Context, lat, lng, radiusKm float64, resType ResourceType) ([]*ResourceFlow, error)
|
|
Update(ctx context.Context, rf *ResourceFlow) error
|
|
Delete(ctx context.Context, id string) error
|
|
}
|