# SAWIS BI Tool - Developer Documentation

## Table of Contents
1. [Project Overview](#project-overview)
2. [Architecture](#architecture)
3. [Technology Stack](#technology-stack)
4. [Project Structure](#project-structure)
5. [State Management](#state-management)
6. [Component Architecture](#component-architecture)
7. [Routing & Navigation](#routing--navigation)
8. [API Integration](#api-integration)
9. [Testing Strategy](#testing-strategy)
10. [Development Setup](#development-setup)
11. [Deployment](#deployment)
12. [Contributing Guidelines](#contributing-guidelines)

## Project Overview

The SAWIS BI Tool is a comprehensive Business Intelligence application for the South African Wine Industry. It provides data visualization, reporting, and analytics capabilities for wine industry stakeholders including grape production data, vineyard status monitoring, and export reports.

### Key Features
- **Export Reports**: Comprehensive wine industry export reports and analytics
- **Grape Production**: Grape production data and statistics visualization
- **Vineyard Status**: Vineyard status monitoring and reporting
- **Interactive Dashboards**: Dynamic charts and pivot tables
- **Authentication**: Secure user authentication and authorization
- **Data Filtering**: Advanced filtering capabilities across multiple dimensions
- **Export Functionality**: Excel export for reports and data

## Architecture

### High-Level Architecture
```
┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│   Frontend      │    │   Backend API   │    │   Database      │
│   (React SPA)   │◄──►│   (ASP.NET)     │◄──►│   (SQL Server)  │
└─────────────────┘    └─────────────────┘    └─────────────────┘
```

### Frontend Architecture
- **Single Page Application (SPA)** built with React 18
- **Component-based architecture** with reusable UI components
- **State management** using Zustand for global state
- **Routing** handled by React Router v6
- **Styling** with Bootstrap 5 and custom CSS
- **Charts** powered by ECharts library
- **Testing** with Playwright for E2E testing

## Technology Stack

### Core Technologies
- **React 18.2.0** - Frontend framework
- **React Router DOM 6** - Client-side routing
- **Zustand 4.4.3** - State management
- **Bootstrap 5.2.3** - CSS framework
- **ECharts 5.4.3** - Data visualization

### Development Tools
- **Create React App** - Build tooling
- **ESLint** - Code linting
- **Playwright** - E2E testing
- **Tailwind CSS 3.3.3** - Utility-first CSS

### Additional Libraries
- **FontAwesome** - Icons
- **Axios** - HTTP client
- **js-cookie** - Cookie management
- **oidc-client** - OpenID Connect authentication
- **XLSX** - Excel file handling

## Project Structure

```
src/
├── components/           # Reusable UI components
│   ├── Charts/          # Chart components
│   ├── common/          # Common/shared components
│   ├── FormComponents/  # Form input components
│   ├── forms/           # Form components
│   ├── pivotTable/      # Pivot table components
│   ├── tabs/            # Tab components
│   ├── Layout.js        # Main layout component
│   ├── Navbar.js        # Navigation bar
│   ├── Sidebar.js       # Sidebar component
│   └── SidebarFilters.jsx # Filter sidebar
├── pages/               # Page components
│   ├── Home.js          # Homepage
│   ├── Reports.js       # Reports page
│   ├── GrapeProduction.js # Grape production page
│   └── VineyardStatus.js  # Vineyard status page
├── store/               # Zustand stores
│   ├── authStore.js     # Authentication state
│   ├── filterStore.js   # Filter state
│   ├── grapeProductionStore.js # Grape production state
│   ├── priceRangeStore.js # Price range state
│   └── vineyardStatusStore.js # Vineyard status state
├── lib/                 # Utility libraries
│   ├── constants.js     # Application constants
│   └── helpers.js       # Helper functions
├── assets/              # Static assets
│   └── images/          # Image files
├── App.js               # Main app component
├── AppRoutes.js         # Route definitions
└── index.js             # Application entry point
```

## State Management

The application uses Zustand for state management with separate stores for different domains:

### Authentication Store (`authStore.js`)
```javascript
// Manages user authentication state
{
  user: null,                    // Current user object
  login: async (credentials) => {}, // Login function
  logout: () => {},             // Logout function
  autoLogin: () => {}           // Auto-login from cookies
}
```

### Filter Store (`filterStore.js`)
```javascript
// Manages reporting filters and data
{
  filters: {},                  // Filter configurations
  data: [],                     // Chart data
  loadingChartData: false,      // Loading states
  updateFilters: (newState) => {}, // Update filter values
  getReportingData: async (user) => {} // Fetch reporting data
}
```

### Domain-Specific Stores
- **Grape Production Store**: Manages grape production filters and data
- **Vineyard Status Store**: Manages vineyard status filters and data
- **Price Range Store**: Manages price range data and filters

## Component Architecture

### Layout Components

#### Layout.js
Main application layout wrapper that includes:
- Navigation bar
- Footer with disclaimer and links
- Modal system for terms of use

#### Navbar.js
Top navigation component featuring:
- Responsive navigation menu
- Authentication state display
- Login/logout functionality
- Mobile menu toggle

#### Sidebar.js & SidebarFilters.jsx
Filter sidebar components providing:
- Collapsible sidebar interface
- Dynamic filter controls
- Filter state management
- Responsive design

### Page Components

#### Home.js
Landing page with:
- Navigation blocks to main sections
- About SAWIS information
- Company values and vision
- Responsive design

#### Reports.js
Main reports page featuring:
- Tabbed interface (Overview, Tables, Price Range, Reports)
- Dynamic sidebar based on active tab
- Integration with filter store
- Authentication-based feature visibility

#### GrapeProduction.js & VineyardStatus.js
Similar structure for domain-specific pages:
- Filter sidebar integration
- Pivot table rendering
- Data fetching and display
- Responsive layout

### Chart Components

#### Charts/ Directory
- **BIChart.jsx**: Main chart component
- **BIOverview.jsx**: Overview dashboard charts
- **PriceRange.jsx**: Price range visualization
- **PriceRangeTable.jsx**: Price range data table

### Pivot Table Components

#### pivotTable/ Directory
- **GenericPivotTable.jsx**: Reusable pivot table component
- **PivotTableRenderer.jsx**: Table rendering logic
- **ColumnSelector.jsx**: Column selection interface
- **TableCell.jsx**: Individual cell component

## Routing & Navigation

### Route Configuration (`AppRoutes.js`)
```javascript
const AppRoutes = [
  { index: true, element: <Home /> },
  { path: '/reports', element: <Reports /> },
  { path: '/grape-production', element: <GrapeProduction /> },
  { path: '/vineyard-status', element: <VineyardStatus /> }
];
```

### Navigation Structure
- **Home**: Landing page with navigation blocks
- **Reports**: Export reports and analytics
- **Grape Production**: Grape production data and statistics
- **Vineyard Status**: Vineyard monitoring and status

### Authentication-Based Routing
- Public routes accessible to all users
- Authenticated routes with additional features
- Automatic redirects based on authentication state

## API Integration

### Base Configuration
```javascript
// Environment-based API URL
process.env.REACT_APP_API_BASE_URL
```

### Authentication Endpoints
- `POST /loginAuth` - User authentication
- `GET /auth/getFilters` - Authenticated filter data
- `POST /auth/tables/*` - Authenticated table data

### Data Endpoints
- `GET /getFilters` - Filter configurations
- `POST /getChartData` - Chart data
- `POST /getYearOverYearComparison` - Year comparison data
- `POST /getTotale_Liters` - Volume data
- `POST /getExports` - Export data
- `POST /getCultivarChartData` - Cultivar data

### Error Handling
- Automatic session expiration detection
- User-friendly error messages
- Automatic logout on authentication failure

## Testing Strategy

### Playwright E2E Testing
Comprehensive end-to-end testing covering:

#### Test Files
- **homepage.spec.js**: Homepage functionality
- **navigation.spec.js**: Navigation between pages
- **authentication.spec.js**: Login/logout functionality
- **reports.spec.js**: Reports page functionality
- **grape-production.spec.js**: Grape production page
- **vineyard-status.spec.js**: Vineyard status page
- **accessibility.spec.js**: Accessibility compliance
- **performance.spec.js**: Performance benchmarks

#### Test Configuration
- **Base URL**: `http://localhost:44487`
- **Browsers**: Chromium, Firefox, WebKit, Mobile Chrome, Mobile Safari
- **Parallel execution**: Enabled
- **Screenshots**: On failure
- **Videos**: Retained on failure
- **Traces**: On first retry

#### Test Commands
```bash
npm run test:e2e          # Run all tests
npm run test:e2e:ui       # Interactive UI mode
npm run test:e2e:headed   # Headed mode
npm run test:e2e:debug    # Debug mode
npm run test:e2e:report   # Show test report
```

## Development Setup

### Prerequisites
- Node.js (v16 or higher)
- npm or yarn
- Git

### Installation
```bash
# Clone the repository
git clone <repository-url>
cd bitool_frontend

# Install dependencies
npm install

# Install Playwright browsers
npx playwright install
```

### Environment Configuration
Create environment variables:
```bash
REACT_APP_API_BASE_URL=http://localhost:5000/api
REACT_APP_USE_AUTH_HEADERS=true
```

### Development Server
```bash
# Start development server
npm start

# The application will be available at http://localhost:3000
```

### Available Scripts
```bash
npm start              # Start development server
npm run build          # Build for production
npm test               # Run unit tests
npm run lint           # Run ESLint
npm run test:e2e       # Run E2E tests
```

## Deployment

### Build Process
```bash
# Create production build
npm run build

# The build files will be in the 'build' directory
```

### Production Considerations
- Environment variables must be set for production
- API endpoints must be configured
- HTTPS should be used in production
- Service worker is disabled by default

### CI/CD Pipeline
The project includes:
- **Bitbucket Pipelines** configuration
- **SonarQube** integration for code quality
- **Automated testing** in CI environment

## Contributing Guidelines

### Code Style
- Use ESLint configuration provided
- Follow React best practices
- Use functional components with hooks
- Implement proper error handling

### Component Development
1. Create components in appropriate directories
2. Use TypeScript-style JSDoc comments
3. Implement proper prop validation
4. Add accessibility attributes
5. Write tests for new components

### State Management
1. Use Zustand stores for global state
2. Keep stores focused on specific domains
3. Implement proper loading states
4. Handle errors gracefully

### Testing
1. Write E2E tests for new features
2. Test both desktop and mobile views
3. Include accessibility tests
4. Test authentication flows

### Pull Request Process
1. Create feature branch from main
2. Implement changes with tests
3. Ensure all tests pass
4. Update documentation if needed
5. Submit pull request with description

## Additional Resources

### Documentation
- [React Documentation](https://reactjs.org/docs)
- [Zustand Documentation](https://github.com/pmndrs/zustand)
- [Playwright Documentation](https://playwright.dev)
- [Bootstrap Documentation](https://getbootstrap.com/docs)

### Development Tools
- [React Developer Tools](https://chrome.google.com/webstore/detail/react-developer-tools)
- [Redux DevTools](https://chrome.google.com/webstore/detail/redux-devtools) (for Zustand)
- [Playwright Inspector](https://playwright.dev/docs/debug)

### API Documentation
- Backend API documentation should be consulted for endpoint details
- Authentication flow documentation
- Data model specifications

---

*This documentation is maintained by the development team. Please keep it updated as the application evolves.*
