turash/bugulma/ORGANIZATION_VS_BUSINESS_ANALYSIS.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

257 lines
9.0 KiB
Markdown

# Organization vs Business - Architectural Analysis
## Summary
**Correct Architecture:** Organization is the main entity that can represent various types (governmental, business, NGO, etc.). Business is a **subtype/specialization** of Organization for commercial entities.
**Current Issue:** The codebase has both concepts defined but they're used inconsistently. Sites reference "Business" when they should reference "Organization" (the parent entity).
## Correct Architecture
### Hierarchical Relationship
```
Organization (Base Entity)
├── Business (Commercial Organization)
│ ├── Legal form, certifications, NACE codes
│ ├── Strategic vision, readiness maturity
│ └── Trust scores, business focus
├── Governmental Organization
├── NGO / Non-Profit
└── Other Organization Types
```
**Key Principles:**
- **Organization** = Main entity (can be any type: business, government, NGO, etc.)
- **Business** = Subtype of Organization (commercial entities only)
- **Site** = Owned/operated by Organizations (not just Businesses)
- **ResourceFlow** = Attached to Sites, owned by Organizations
**Correct Relationship**: Organization → Sites → ResourceFlows
### 2. Backend Implementation (Actual State)
#### Two Separate Domain Models Exist:
**`domain/organization.go`** (Currently Used):
```go
type Organization struct {
ID string
Name string
Sector string // Simple string, not NACE code
Description string
LogoURL string
Website string
Address string
Verified bool
CreatedAt time.Time
UpdatedAt time.Time
}
```
**`domain/business.go`** (Defined but Not Fully Integrated):
```go
type Business struct {
ID string
Name string
LegalForm string
PrimaryContactEmail string
PrimaryContactPhone string
IndustrialSector string // NACE code
CompanySize int
YearsOperation int
SupplyChainRole string
Certifications []string
BusinessFocus []string
StrategicVision string
DriversBarriers string
ReadinessMaturity int
TrustScore float64
CreatedAt time.Time
UpdatedAt time.Time
}
```
#### API Endpoints Use "Organization":
- `/api/organizations` - Uses OrganizationHandler
- `/api/organizations/:id` - Returns Organization entities
- OrganizationService and OrganizationRepository are actively used
#### But Sites Incorrectly Reference "Business":
- `BackendSite.OwnerBusinessID` - **WRONG**: Should be `OwnerOrganizationID`
- `/api/sites/business/:businessId` - **WRONG**: Should be `/api/sites/organization/:organizationId`
- Site schema has `owner_business_id` field - **WRONG**: Should be `owner_organization_id`
**Issue**: Sites should reference Organizations (the parent entity), not just Businesses.
### 3. Frontend Implementation
**Uses "Organization" terminology:**
- `Organization` type throughout
- `OrganizationPage`, `OrganizationContent`, etc.
- Routes: `/organization/:id`
- Context: `OrganizationContext`
**But calls "Business" APIs:**
- `getSitesByBusiness(businessId)` - Function name uses "business"
- `site.OwnerBusinessID` - Field name uses "Business"
- `businessId={organization.ID}` - Treats Organization ID as Business ID
## The Problem
### Current Issues:
1. **Incorrect Field Names:**
- Sites use `OwnerBusinessID` but should use `OwnerOrganizationID`
- Not all Organizations are Businesses (could be government, NGO, etc.)
- Field name implies only Businesses can own sites
2. **API Endpoint Mismatch:**
- `/api/sites/business/:businessId` should be `/api/sites/organization/:organizationId`
- Endpoint name suggests only Businesses can have sites
3. **Missing Business Subtype:**
- Business domain model exists but isn't integrated as Organization subtype
- No way to distinguish Business organizations from other types
- Rich Business metadata (certifications, NACE codes) not accessible
4. **Data Model Confusion:**
- Sites reference "Business" but accept Organization IDs
- No validation that Organization is actually a Business (when needed)
- Potential for data integrity issues
## Current Assumption (Implicit)
The codebase currently assumes:
```
Organization.ID can be used as Business.ID (treating all Organizations as Businesses)
```
But this is:
- ❌ Not all Organizations are Businesses
- ❌ Field names suggest Business-only ownership
- ❌ No way to distinguish Business organizations from others
- ❌ Creates confusion about entity relationships
## Recommended Solution
### Implement Organization as Base Entity with Business Subtype
**Architecture:**
```
Organization (Base)
- ID, Name, Sector, Description, LogoURL, Website, Address, Verified
- Type: "business" | "governmental" | "ngo" | "other"
Business (Subtype/Extension)
- OrganizationID (references Organization)
- LegalForm, Certifications, NACE codes
- StrategicVision, ReadinessMaturity, TrustScore
- BusinessFocus, DriversBarriers
```
**Action Plan:**
1. **Fix Site References (Priority 1):**
- Rename `OwnerBusinessID``OwnerOrganizationID` in Site schema
- Update API: `/api/sites/business/:id``/api/sites/organization/:id`
- Update frontend: `getSitesByBusiness``getSitesByOrganization`
- Sites belong to Organizations (any type)
2. **Add Organization Type Field:**
- Add `Type` or `OrganizationType` field to Organization
- Values: "business", "governmental", "ngo", "other"
- Allows filtering and type-specific features
3. **Implement Business as Extension:**
- Business table/entity references Organization.ID
- One-to-one relationship: Organization → Business (optional)
- Only Business-type organizations have Business records
- Business-specific features only available for Business organizations
4. **Update APIs:**
- Keep `/api/organizations` for all organization types
- Add `/api/organizations/:id/business` for Business-specific data
- Or: `/api/businesses/:organizationId` for Business extension
5. **Frontend Updates:**
- Use Organization everywhere (correct)
- Access Business data when `organization.type === "business"`
- Update components to handle different organization types
**Pros:**
- ✅ Correctly models Organization as parent entity
- ✅ Supports multiple organization types (business, government, NGO)
- ✅ Business metadata available when needed
- ✅ Clear, extensible architecture
- ✅ Minimal breaking changes (mostly field renames)
**Cons:**
- Requires database migration for Site field rename
- Need to handle Business extension relationship
- Some API endpoint changes
## Immediate Fixes Needed
### Phase 1: Fix Site References (Critical)
1. **Backend:**
- Rename `OwnerBusinessID``OwnerOrganizationID` in Site domain model
- Update Site repository and handlers
- Update API endpoint: `/api/sites/business/:id``/api/sites/organization/:id`
- Add database migration
2. **Frontend:**
- Update `BackendSite` schema: `OwnerBusinessID``OwnerOrganizationID`
- Rename `getSitesByBusiness``getSitesByOrganization`
- Update all references in hooks and components
### Phase 2: Add Organization Type (Important)
1. **Backend:**
- Add `Type` field to Organization domain model
- Add migration to set default type for existing records
- Update Organization service and handlers
2. **Frontend:**
- Add `Type` field to Organization schema
- Update UI to display organization type
- Filter/group by type if needed
### Phase 3: Implement Business Extension (Future)
1. **Backend:**
- Create Business extension table/entity
- Add foreign key: `Business.OrganizationID → Organization.ID`
- Create Business service for Business-specific operations
- Add API endpoints for Business data
2. **Frontend:**
- Add Business type/interface
- Fetch Business data when `organization.type === "business"`
- Display Business-specific fields (certifications, etc.)
## Files Affected
- `bugulma/backend/internal/domain/organization.go`
- `bugulma/backend/internal/domain/business.go`
- `bugulma/backend/internal/handler/site_handler.go`
- `bugulma/frontend/schemas/backend/site.ts`
- `bugulma/frontend/services/sites-api.ts`
- `bugulma/frontend/hooks/map/useOrganizationSites.ts`
- All frontend components using "Organization"
## Conclusion
**Correct Architecture:** Organization is the main entity. Business is a subtype for commercial organizations. Other types (governmental, NGO) are also Organizations.
**Current State:** Sites incorrectly reference "Business" when they should reference "Organization". Business extension exists but isn't integrated.
**Recommended Action:**
1. **Phase 1 (Critical)**: Fix Site references to use Organization
2. **Phase 2 (Important)**: Add Organization Type field
3. **Phase 3 (Future)**: Implement Business as optional extension
**Priority:** High - Field names are misleading and don't support the correct architecture where Organizations can be non-business entities.