feat: add functional requirements for profitability, Monte Carlo simulation, and Capex/Opex management; enhance user guide with planners

This commit is contained in:
2025-11-13 09:20:10 +01:00
parent d3597bc8c9
commit fb6be6d84f
11 changed files with 526 additions and 24 deletions

View File

@@ -48,10 +48,6 @@ CalMiner aims to provide a comprehensive platform for mining project scenario an
- [Data Synchronization](#data-synchronization) - [Data Synchronization](#data-synchronization)
- [Error Handling](#error-handling) - [Error Handling](#error-handling)
- [Reporting and Analytics](#reporting-and-analytics) - [Reporting and Analytics](#reporting-and-analytics)
- [Data Visualization](#data-visualization)
- [Custom Reports](#custom-reports)
- [Real-time Analytics](#real-time-analytics)
- [Historical Analysis](#historical-analysis)
## Multitenancy ## Multitenancy
@@ -245,20 +241,4 @@ Robust error handling mechanisms are implemented to manage integration failures
## Reporting and Analytics ## Reporting and Analytics
The Calminer system includes comprehensive reporting and analytics capabilities to support data-driven decision-making. The Calminer system includes comprehensive reporting and analytics capabilities to support data-driven decision-making. Detailed [Reporting and Analytics](08_concepts/11_reporting_analytics.md) documentation is available.
### Data Visualization
The system provides tools for visualizing data through charts, graphs, and dashboards, making it easier to identify trends and insights.
### Custom Reports
Users can create custom reports based on specific criteria, allowing for tailored analysis of project performance and resource utilization.
### Real-time Analytics
The system supports real-time data processing and analytics, enabling users to access up-to-date information and respond quickly to changing conditions.
### Historical Analysis
The system maintains a history of key metrics and events, allowing for retrospective analysis and identification of long-term trends.

View File

@@ -27,11 +27,10 @@ Represents authenticated platform users with optional elevated privileges.
**Relationships:** **Relationships:**
- `role_assignments`: Many-to-many with Role via UserRole - `role_assignments`: Many-to-many with Role via UserRole
- `roles`: Many-to-many with Role (viewonly)
#### Role #### Role
Role encapsulating a set of permissions. Defines user roles for role-based access control (RBAC).
**Table:** `roles` **Table:** `roles`
@@ -143,6 +142,124 @@ Line-item financial assumption attached to a scenario.
- `scenario`: Many-to-one with Scenario - `scenario`: Many-to-one with Scenario
### Project and Scenario Models
#### ProjectCapexSnapshot
Project-level snapshot capturing aggregated initial capital expenditure metrics.
**Table:** `project_capex_snapshots`
| Attribute | Type | Description |
| ---------------------- | --------------------------------- | ------------------------------------------------------- |
| id | Integer (PK) | Primary key |
| project_id | Integer (FK → projects.id) | Associated project |
| created_by_id | Integer (FK → users.id, nullable) | User that triggered persistence |
| calculation_source | String(64), nullable | Originating workflow identifier (UI, API, etc.) |
| calculated_at | DateTime | Timestamp the calculation completed |
| currency_code | String(3), nullable | Currency for totals |
| total_capex | Numeric(18,2), nullable | Aggregated capex before contingency |
| contingency_pct | Numeric(12,6), nullable | Applied contingency percentage |
| contingency_amount | Numeric(18,2), nullable | Monetary contingency amount |
| total_with_contingency | Numeric(18,2), nullable | Capex total after contingency |
| component_count | Integer, nullable | Number of normalized components captured |
| payload | JSON, nullable | Serialized component breakdown and calculation metadata |
| created_at | DateTime | Record creation timestamp |
| updated_at | DateTime | Last update timestamp |
**Relationships:**
- `project`: Many-to-one with Project
- `created_by`: Many-to-one with User (nullable)
#### ScenarioCapexSnapshot
Scenario-level snapshot storing detailed initial capex results.
**Table:** `scenario_capex_snapshots`
| Attribute | Type | Description |
| ---------------------- | --------------------------------- | ------------------------------------------------------- |
| id | Integer (PK) | Primary key |
| scenario_id | Integer (FK → scenarios.id) | Associated scenario |
| created_by_id | Integer (FK → users.id, nullable) | User that triggered persistence |
| calculation_source | String(64), nullable | Originating workflow identifier |
| calculated_at | DateTime | Timestamp the calculation completed |
| currency_code | String(3), nullable | Currency for totals |
| total_capex | Numeric(18,2), nullable | Aggregated capex before contingency |
| contingency_pct | Numeric(12,6), nullable | Applied contingency percentage |
| contingency_amount | Numeric(18,2), nullable | Monetary contingency amount |
| total_with_contingency | Numeric(18,2), nullable | Capex total after contingency |
| component_count | Integer, nullable | Number of normalized components captured |
| payload | JSON, nullable | Serialized component breakdown and calculation metadata |
| created_at | DateTime | Record creation timestamp |
| updated_at | DateTime | Last update timestamp |
**Relationships:**
- `scenario`: Many-to-one with Scenario
- `created_by`: Many-to-one with User (nullable)
#### ProjectProcessingOpexSnapshot
Project-level snapshot persisting recurring processing opex metrics.
**Table:** `project_processing_opex_snapshots`
| Attribute | Type | Description |
| ------------------------ | --------------------------------- | ------------------------------------------------------- |
| id | Integer (PK) | Primary key |
| project_id | Integer (FK → projects.id) | Associated project |
| created_by_id | Integer (FK → users.id, nullable) | User that triggered persistence |
| calculation_source | String(64), nullable | Originating workflow identifier |
| calculated_at | DateTime | Timestamp the calculation completed |
| currency_code | String(3), nullable | Currency for totals |
| overall_annual | Numeric(18,2), nullable | Total annual processing opex |
| escalated_total | Numeric(18,2), nullable | Escalated cost across the evaluation horizon |
| annual_average | Numeric(18,2), nullable | Average annual cost over the horizon |
| evaluation_horizon_years | Integer, nullable | Number of years included in the timeline |
| escalation_pct | Numeric(12,6), nullable | Escalation percentage applied |
| apply_escalation | Boolean | Flag indicating whether escalation was applied |
| component_count | Integer, nullable | Number of normalized components captured |
| payload | JSON, nullable | Serialized component breakdown and calculation metadata |
| created_at | DateTime | Record creation timestamp |
| updated_at | DateTime | Last update timestamp |
**Relationships:**
- `project`: Many-to-one with Project
- `created_by`: Many-to-one with User (nullable)
#### ScenarioProcessingOpexSnapshot
Scenario-level snapshot persisting recurring processing opex metrics.
**Table:** `scenario_processing_opex_snapshots`
| Attribute | Type | Description |
| ------------------------ | --------------------------------- | ------------------------------------------------------- |
| id | Integer (PK) | Primary key |
| scenario_id | Integer (FK → scenarios.id) | Associated scenario |
| created_by_id | Integer (FK → users.id, nullable) | User that triggered persistence |
| calculation_source | String(64), nullable | Originating workflow identifier |
| calculated_at | DateTime | Timestamp the calculation completed |
| currency_code | String(3), nullable | Currency for totals |
| overall_annual | Numeric(18,2), nullable | Total annual processing opex |
| escalated_total | Numeric(18,2), nullable | Escalated cost across the evaluation horizon |
| annual_average | Numeric(18,2), nullable | Average annual cost over the horizon |
| evaluation_horizon_years | Integer, nullable | Number of years included in the timeline |
| escalation_pct | Numeric(12,6), nullable | Escalation percentage applied |
| apply_escalation | Boolean | Flag indicating whether escalation was applied |
| component_count | Integer, nullable | Number of normalized components captured |
| payload | JSON, nullable | Serialized component breakdown and calculation metadata |
| created_at | DateTime | Record creation timestamp |
| updated_at | DateTime | Last update timestamp |
**Relationships:**
- `scenario`: Many-to-one with Scenario
- `created_by`: Many-to-one with User (nullable)
#### SimulationParameter #### SimulationParameter
Probability distribution settings for scenario simulations. Probability distribution settings for scenario simulations.

View File

@@ -0,0 +1,39 @@
# Reporting and Analytics
The Calminer application provides robust reporting and analytics features designed to help users visualize and interpret mining project data effectively.
## Dashboard Generation
Users can create and customize dashboards that display key metrics and performance indicators related to mining projects. Dashboards support various visualization types, including charts, graphs, and tables, and allow users to drill down into specific data points for deeper analysis.
## Report Creation
The system enables users to create detailed reports that summarize project scenarios, financial analyses, and simulation results. Reports can be exported in multiple formats, including PDF and Excel, for easy sharing and presentation.
## Data Visualization Tools
The system provides tools for visualizing data through charts, graphs, and dashboards, making it easier to identify trends and insights. Users can interact with visualizations to explore data in more detail.
## Analytics Engine
The backend analytics engine processes large datasets and performs complex calculations, including Monte Carlo simulations, to provide users with probabilistic assessments of project outcomes.
### Real-time Analytics
The system supports real-time data processing and analytics, enabling users to access up-to-date information and respond quickly to changing conditions.
### Historical Analysis
The system maintains a history of key metrics and events, allowing for retrospective analysis and identification of long-term trends.
## Custom Reports
Users can create custom reports based on specific criteria, allowing for tailored analysis of project performance and resource utilization.
## User-Friendly Interface
The reporting and analytics features are accessible through an intuitive web interface, allowing users to navigate reports and dashboards seamlessly.
## Integration with Scenario Management
Reporting tools are tightly integrated with the scenario management system, enabling users to generate reports directly from specific project scenarios and compare results across different configurations.

53
requirements/FR-011.md Normal file
View File

@@ -0,0 +1,53 @@
# Functional Requirement FR-011: Basic Profitability Calculation
## Description
The system shall provide functionality to perform basic profitability calculations for ore mining products based on user-defined input parameters.
A detailed specification is available in [specifications/price_calculation.md](specifications/price_calculation.md)
## Rationale
Profitability calculations are essential for mining companies to assess the financial viability of their operations. By enabling users to input key parameters and receive profitability metrics, the system will support informed decision-making and strategic planning.
## Acceptance Criteria
1. **Input Parameters**: The system shall accept the following input parameters:
- Metal type (e.g., copper, gold, lithium)
- Ore tonnage processed
- Head grade (%)
- Recovery rate (%)
- Treatment charge (currency/tonne)
- Smelting charge (currency/tonne)
- Moisture content (%)
- Impurity content (ppm for relevant impurities)
- Moisture penalty factor (currency/%)
- Impurity penalty factor (currency/ppm)
- Premiums/credits (currency)
- FX rate (currency conversion rate)
2. **Calculation Logic**: The system shall implement the profitability calculation logic as specified in the detailed specification document, including:
- Calculation of metal content based on ore tonnage, head grade, and recovery rate.
- Computation of gross revenue using metal content and reference prices.
- Deduction of treatment and smelting charges.
- Application of moisture and impurity penalties.
- Adjustment for premiums/credits.
- Conversion of final revenue to scenario currency using the FX rate.
3. **Output Metrics**: The system shall provide the following output metrics:
- Gross revenue (in scenario currency)
- Total charges (treatment and smelting)
- Total penalties (moisture and impurities)
- Net revenue before premiums
- Final adjusted revenue (after premiums/credits)
## Dependencies
- Accurate and up-to-date reference prices for supported metals.
- User interface components for inputting parameters and displaying results.
- Data validation mechanisms to ensure input parameters are within acceptable ranges.
- Integration with existing scenario management and reporting modules for seamless user experience.
## Notes
- The system should allow for easy updates to reference prices and other key parameters as market conditions change.
- User training and documentation will be essential to ensure effective use of the profitability calculation features.
- Future enhancements may include sensitivity analysis and scenario comparisons based on profitability metrics.

50
requirements/FR-012.md Normal file
View File

@@ -0,0 +1,50 @@
# Functional Requirement FR-012: Monte Carlo simulation engine
## Description
The system shall provide a Monte Carlo simulation engine to model uncertainties in mining project parameters. This engine will allow users to define probability distributions for key input variables and run simulations to assess the impact of these uncertainties on project outcomes.
A detailed specification is available in [specifications/monte_carlo_simulation.md](specifications/monte_carlo_simulation.md)
## Rationale
Monte Carlo simulations are a powerful tool for risk analysis and decision-making in mining projects. By modeling the variability of input parameters, users can better understand potential outcomes, identify risks, and make informed decisions based on probabilistic results.
## Acceptance Criteria
1. **Input Parameter Definitions**: The system shall allow users to define probability distributions for key input parameters, including but not limited to:
- Ore grade
- Recovery rate
- Operating costs
- Metal prices
2. **Simulation Configuration**: The system shall provide options for users to configure the simulation, including:
- Number of simulation iterations
- Random seed for reproducibility
- Output metrics to be recorded
3. **Result Analysis**: The system shall offer tools for analyzing simulation results, including:
- Summary statistics (mean, median, percentiles)
- Visualization of result distributions (histograms, box plots)
- Comparison of different scenarios or input configurations
4. **Integration with Existing Workflows**: The Monte Carlo simulation engine shall be integrated with existing scenario management and reporting tools within the system, allowing users to easily incorporate simulation results into their decision-making processes.
5. **Documentation**: The system shall include comprehensive documentation on how to use the Monte Carlo simulation engine, including examples and best practices.
## Dependencies
- Access to historical data for key input parameters to inform probability distribution definitions.
- Computational resources to support the execution of large-scale simulations.
- Integration with data management systems to facilitate the use of external data sources.
- User interface components for defining input parameters, configuring simulations, and visualizing results.
## Notes
- The Monte Carlo simulation engine should be designed for scalability to accommodate large datasets and complex models.
- Users should be able to easily update probability distributions and other simulation parameters as new information becomes available.
- Collaboration features may be beneficial to allow multiple users to work on simulation scenarios simultaneously.
- Future enhancements may include sensitivity analysis and scenario optimization based on simulation results.

40
requirements/FR-013.md Normal file
View File

@@ -0,0 +1,40 @@
# Functional Requirement FR-013: Capital Expenditure (Capex) management and calculation tools for mining projects
## Description
The system shall provide tools to calculate and manage Capital Expenditures (Capex) associated with mining projects. This includes the ability to input, store, and analyze various capital cost components such as equipment purchases, infrastructure development, land acquisition, and other one-time expenses.
## Rationale
Accurate Capex calculations are essential for budgeting, financial planning, and profitability analysis in mining projects. By providing robust tools to manage these costs, the system will enable users to make informed decisions regarding project feasibility and capital allocation.
## Acceptance Criteria
1. **Capex Component Definition**: The system shall allow users to define and categorize various Capex components, including but not limited to:
- Equipment purchases
- Infrastructure development
- Land acquisition
- Other one-time expenses
2. **Input and Storage**: The system shall provide interfaces for users to input Capex data and store it in a structured format for easy retrieval and analysis.
3. **Capex Calculation**: The system shall include tools to calculate total Capex based on the defined components and their respective values. This includes the ability to apply formulas and algorithms to derive insights from the data.
4. **Reporting and Visualization**: The system shall offer reporting and visualization features to help users understand Capex trends, identify cost drivers, and make data-driven decisions.
5. **Integration**: The system shall support integration with other financial and operational systems to ensure seamless data flow and consistency across platforms.
## Dependencies
- Integration with existing financial modules for comprehensive cost analysis.
- User interface components for inputting and managing Capex data.
- Data validation mechanisms to ensure accuracy and consistency of Capex inputs.
- Reporting and visualization libraries to support analysis and presentation of Capex data.
## Notes
- The Capex management tools should be designed for scalability to accommodate large datasets and complex cost structures.
- Users should be able to easily update Capex components and their values as project conditions change.
- Collaboration features may be beneficial to allow multiple users to work on Capex scenarios simultaneously.
- Future enhancements may include predictive analytics and machine learning capabilities to improve Capex forecasting and optimization.

41
requirements/FR-014.md Normal file
View File

@@ -0,0 +1,41 @@
# Functional Requirement FR-014: Operational Expenditure (Opex) management and calculation tools for mining projects
## Description
The system shall provide tools to calculate and manage Operational Expenditures (Opex) associated with mining projects. This includes the ability to input, store, and analyze various operational cost components such as labor, materials, energy consumption, maintenance, and other recurring expenses.
## Rationale
Accurate Opex calculations are essential for budgeting, financial planning, and profitability analysis in mining projects. By providing robust tools to manage these costs, the system will enable users to make informed decisions regarding project feasibility and operational efficiency.
## Acceptance Criteria
1. **Opex Component Definition**: The system shall allow users to define and categorize various Opex components, including but not limited to:
- Labor costs
- Material costs
- Energy costs
- Maintenance costs
- Other recurring expenses
2. **Input and Storage**: The system shall provide interfaces for users to input Opex data and store it in a structured format for easy retrieval and analysis.
3. **Opex Calculation**: The system shall include tools to calculate total Opex based on the defined components and their respective values. This includes the ability to apply formulas and algorithms to derive insights from the data.
4. **Reporting and Visualization**: The system shall offer reporting and visualization features to help users understand Opex trends, identify cost drivers, and make data-driven decisions.
5. **Integration**: The system shall support integration with other financial and operational systems to ensure seamless data flow and consistency across platforms.
## Dependencies
- Integration with existing financial modules for comprehensive cost analysis.
- User interface components for inputting and managing Opex data.
- Data validation mechanisms to ensure accuracy and consistency of Opex inputs.
- Reporting and visualization libraries to support analysis and presentation of Opex data.
## Notes
- The Opex management tools should be designed for scalability to accommodate large datasets and complex cost structures.
- Users should be able to easily update Opex components and their values as project conditions change.
- Collaboration features may be beneficial to allow multiple users to work on Opex scenarios simultaneously.
- Future enhancements may include predictive analytics and machine learning capabilities to improve Opex forecasting and optimization.

View File

@@ -22,5 +22,9 @@ This document outlines the key functional requirements for the CalMiner project.
| FR-008 | Facilitate export of analysis results in various formats (PDF, Excel, etc.). | Medium | [FR-008](../requirements/FR-008.md) | | FR-008 | Facilitate export of analysis results in various formats (PDF, Excel, etc.). | Medium | [FR-008](../requirements/FR-008.md) |
| FR-009 | Provide a user-friendly interface accessible via web browsers. | High | [FR-009](../requirements/FR-009.md) | | FR-009 | Provide a user-friendly interface accessible via web browsers. | High | [FR-009](../requirements/FR-009.md) |
| FR-010 | Enable collaboration features for multiple users to work on scenarios simultaneously. | Medium | [FR-010](../requirements/FR-010.md) | | FR-010 | Enable collaboration features for multiple users to work on scenarios simultaneously. | Medium | [FR-010](../requirements/FR-010.md) |
| FR-011 | Basic Profitability calculation for ore mining products based on input parameters. | High | [FR-011](../requirements/FR-011.md) |
| FR-012 | Monte Carlo simulation engine to model uncertainties in mining project parameters. | High | [FR-012](../requirements/FR-012.md) |
| FR-013 | Capital Expenditure (Capex) management and calculation tools for mining projects. | High | [FR-013](../requirements/FR-013.md) |
| FR-014 | Operational Expenditure (Opex) calculation tools for processing costs in mining. | High | [FR-014](../requirements/FR-014.md) |
Each functional requirement is detailed in its respective document, providing a comprehensive description, rationale, acceptance criteria, and dependencies. Please refer to the linked documents for more information on each requirement. Each functional requirement is detailed in its respective document, providing a comprehensive description, rationale, acceptance criteria, and dependencies. Please refer to the linked documents for more information on each requirement.

View File

@@ -1,3 +1,8 @@
# User Guide # User Guide
<!-- TODO: Create a user guide for Calminer. This should include instructions on how to use the various features of the application, along with screenshots and examples where applicable. --> CalMiner user-facing documentation is organized by feature area. Start with the guides below and expand the repository as new workflows ship.
## Available Guides
- [Initial Capex Planner](initial_capex_planner.md) — capture upfront capital components, run calculations, and persist snapshots for projects and scenarios.
- [Processing Opex Planner](processing_opex_planner.md) — manage recurring operational costs, apply escalation/discount assumptions, and store calculation snapshots.

View File

@@ -0,0 +1,59 @@
# Initial Capex Planner
The Initial Capex Planner helps project teams capture upfront capital requirements, categorize spend, and produce a shareable breakdown that feeds downstream profitability analysis. The feature implements the acceptance criteria described in [FR-013](../requirements/FR-013.md) and persists calculation snapshots for both projects and scenarios when context is provided.
## Access Paths
- **Workspace sidebar**: Navigate to _Workspace → Initial Capex Planner_.
- **Scenario detail page**: Use the _Initial Capex Planner_ button in the scenario header to open the planner pre-loaded with the selected project and scenario.
## Prerequisites
- Authenticated CalMiner account with at least _viewer_ permissions on the target project/scenario.
- Baseline pricing settings seeded through the database initializer (the GET route resolves pricing metadata for defaults).
## Planner Workflow
1. **Open the planner** via the sidebar or scenario action button. Query parameters (`project_id`, `scenario_id`) preload metadata for the selected context.
2. **Review defaults** in the form header: currency code, contingency, discount rate, and evaluation horizon pull from the scenario, project, or system defaults.
3. **Capture capex components** by adding rows to the components table. Each row records:
- Category (equipment, infrastructure, land, miscellaneous, etc.)
- Component name and optional internal identifier
- Amount and currency (defaults to scenario or project currency)
- Planned spend year and notes
4. **Adjust global parameters** in the sidebar panel for contingency percentage, discount rate, and evaluation horizon years.
5. **Run the calculation** with _Save & Calculate_. The POST request validates the payload, aggregates totals, applies contingency, and produces categorized and time-phased results.
6. **Review results** in the Capex Summary cards, category table, and timeline table. Optional chart containers are rendered for future visualization enhancements.
## Persistence Behaviour
- When a `project_id` or `scenario_id` is supplied, the POST handler stores a snapshot via `ProjectCapexSnapshot` and/or `ScenarioCapexSnapshot` before rendering results.
- Snapshots include aggregate totals, contingency metrics, component counts, and the normalized payload, enabling auditing and downstream financial modelling.
- JSON clients can set `options[persist]=0` to skip persistence in future iterations (HTML form defaults to persist enabled).
## API Reference
| Route | Method | Description |
| --------------------------------------------------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| `/calculations/capex` (`calculations.capex_form`) | GET | Renders the planner template with defaults for the provided project/scenario context. |
| `/calculations/capex` (`calculations.capex_submit`) | POST | Accepts form or JSON payload matching `CapexCalculationRequest`, returns HTML or JSON results, and persists snapshots when context is present. |
Key schemas and services:
- `schemas.calculations.CapexCalculationRequest`, `CapexComponentInput`, `CapexParameters`
- `services.calculations.calculate_initial_capex`
- `_persist_capex_snapshots` helper in `routes/calculations.py`
Refer to `tests/integration/test_capex_calculations.py` for example payloads and persistence assertions.
## Troubleshooting
- **Validation errors**: Field-level messages appear above the components table for row-specific issues and in the global error alert for general problems.
- **Currency mismatch**: The service enforces a single currency across all components; ensure component rows use the same ISO-4217 code or adjust the default currency.
- **Timeline gaps**: Rows without a `spend_year` are excluded from the timeline but still contribute to totals.
## Related Resources
- [Initial Capex Planner template](../../calminer/templates/scenarios/capex.html)
- [Capex snapshot models](../../calminer/models/capex_snapshot.py)
- [FR-013 Requirement](../requirements/FR-013.md)

View File

@@ -0,0 +1,114 @@
# Processing Opex Planner
The Processing Opex Planner captures recurring operational costs, applies escalation/discount assumptions, and persists calculation snapshots for projects and scenarios. It satisfies the Operational Expenditure tooling defined in [FR-014](../requirements/FR-014.md).
## Access Paths
- **Workspace sidebar**: Navigate to _Workspace → Processing Opex Planner_.
- **Scenario detail header**: Use the _Processing Opex Planner_ button to open the planner pre-loaded with the active project/scenario context.
## Prerequisites
- Authenticated CalMiner account with viewer or higher access to the target project or scenario.
- Baseline scenario/project metadata (currency, discount rate, primary resource) to seed form defaults when IDs are provided.
## Planner Workflow
1. **Open the planner** via the sidebar or scenario action. Query parameters (`project_id`, `scenario_id`) load project and scenario metadata plus the latest persisted snapshot, when available.
2. **Review defaults** in the global parameters panel. Currency, discount rate, evaluation horizon, and persist toggle derive from the scenario, project, or system defaults surfaced by `_prepare_opex_context` in `routes/calculations.py`.
3. **Capture opex components** in the components table. Each row records the details listed in the _Component Fields_ table below. Rows support dynamic add/remove interactions and inline validation messages for missing data.
4. **Adjust global parameters** such as escalation percentage, discount rate, evaluation horizon, and whether escalation applies to the timeline. Parameter defaults derive from the active scenario, project, or environment configuration.
5. **Add optional snapshot notes** that persist alongside stored results and appear in the snapshot history UI (planned) and API responses.
6. **Run the calculation** with _Save & Calculate_. The POST handler validates input via `ProcessingOpexCalculationRequest`, calls `services.calculations.calculate_processing_opex`, and repopulates the form with normalized data. When validation fails, the page returns a 422 status with component-level alerts.
7. **Review results** in the summary cards and detailed breakdowns: total annual opex, per-ton cost, category totals, escalated timeline table, and the normalized component listing. Alerts surface validation issues or component-level notices above the table.
### Component Fields
| Field | Description | Notes |
| -------------- | --------------------------------------------------------------------------- | ------------------------------------------------------ |
| `category` | Cost grouping (`labor`, `materials`, `energy`, `maintenance`, `other`). | Drives category totals and stacked charts. |
| `name` | Descriptive label for the component. | Displayed in breakdown tables and persisted snapshots. |
| `unit_cost` | Cost per unit in the selected currency. | Decimal, >= 0. |
| `quantity` | Units consumed per frequency period. | Decimal, >= 0. |
| `frequency` | Recurrence cadence (`daily`, `weekly`, `monthly`, `quarterly`, `annually`). | Controls timeline expansion scaling. |
| `currency` | ISO-4217 currency code. | Must match parameters currency when persisting. |
| `period_start` | First evaluation period (1-indexed) to include the component. | Optional; defaults to 1. |
| `period_end` | Final evaluation period to include the component. | Optional; defaults to evaluation horizon. |
| `notes` | Free-form text stored with the component. | Optional; hidden by default in HTML form. |
### Global Parameters
| Parameter | Purpose |
| -------------------------- | --------------------------------------------------------------------------------- |
| `currency_code` | Normalized currency for totals and timeline. |
| `escalation_pct` | Annual escalation applied to eligible components when `apply_escalation` is true. |
| `discount_rate_pct` | Discount rate surfaced for downstream profitability workflows. |
| `evaluation_horizon_years` | Number of years to expand the timeline. |
| `apply_escalation` | Boolean flag enabling escalation across the timeline. |
| `persist` (options) | Persists the calculation when project/scenario context is present. |
| `snapshot_notes` (options) | Optional metadata attached to stored snapshots. |
## Persistence Behaviour
- When `project_id` or `scenario_id` is supplied and `options[persist]` evaluates true (default for HTML form), snapshots are stored via `ProjectProcessingOpexSnapshot` and `ScenarioProcessingOpexSnapshot` repositories before rendering the response.
- Snapshot payloads capture normalized component entries, parameters, escalation settings, calculated totals, and optional notes, enabling historical comparison and downstream profitability inputs.
- JSON clients can disable persistence by sending `"options": {"persist": false}` or omit identifiers for ad hoc calculations.
## API Reference
| Route | Method | Description |
| ----------------------------------------------------------------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `/calculations/processing-opex` (`calculations.processing_opex_form`) | GET | Renders the planner template with defaults and any latest snapshot context for the supplied project/scenario IDs. |
| `/calculations/processing-opex` (`calculations.processing_opex_submit`) | POST | Accepts form or JSON payload matching `ProcessingOpexCalculationRequest`, returns HTML or JSON results, and persists snapshots when context is present. |
Key schemas and services:
- `schemas.calculations.ProcessingOpexComponentInput`, `ProcessingOpexParameters`, `ProcessingOpexCalculationRequest`, `ProcessingOpexCalculationResult`
- `services.calculations.calculate_processing_opex`
- `_prepare_opex_context`, `_persist_opex_snapshots`, and related helpers in `routes/calculations.py`
### Example JSON Request
```json
{
"components": [
{
"category": "energy",
"name": "Processing Plant Power",
"unit_cost": "480.00",
"quantity": "1.0",
"frequency": "monthly",
"currency": "USD",
"period_start": 1,
"period_end": 12
}
],
"parameters": {
"currency_code": "USD",
"escalation_pct": "3.0",
"discount_rate_pct": "8.0",
"evaluation_horizon_years": 10,
"apply_escalation": true
},
"options": {
"persist": true,
"snapshot_notes": "Baseline processing OPEX"
}
}
```
The response payload mirrors `ProcessingOpexCalculationResult`, returning normalized components, aggregated totals, timeline series, and snapshot metadata when persistence is enabled.
## Troubleshooting
- **Validation errors**: The planner surfaces field-level issues above the component table. JSON responses include `errors` and `message` keys mirroring Pydantic validation output.
- **Currency mismatch**: All component rows must share the same currency. Adjust row currencies or the default currency in the parameters panel to resolve mismatches enforced by the service layer.
- **Timeline coverage**: Ensure `period_start` and `period_end` fall within the evaluation horizon. Rows outside the horizon are ignored in the timeline though they still influence totals.
## Related Resources
- [Processing Opex planner template](../../calminer/templates/scenarios/opex.html)
- [Calculations route handlers](../../calminer/routes/calculations.py)
- [Opex schemas and results](../../calminer/schemas/calculations.py)
- [Service implementation and tests](../../calminer/services/calculations.py), [tests/services/test_calculations_processing_opex.py](../../calminer/tests/services/test_calculations_processing_opex.py)
- [Integration coverage](../../calminer/tests/integration/test_processing_opex_calculations.py)