16 Commits

Author SHA1 Message Date
William Valentin 86606d56b6 feat: add comprehensive keyboard shortcuts for improved navigation and productivity
Build and Push Docker Image / build-and-push (push) Has been cancelled
2025-08-05 10:05:32 -07:00
William Valentin 9790f2730a feat: update version to 1.9.5 in Makefile and pyproject.toml
Build and Push Docker Image / build-and-push (push) Has been cancelled
2025-08-02 10:35:44 -07:00
William Valentin fdcc210fc4 feat: add status bar to UI for improved user feedback and information display 2025-08-02 10:31:17 -07:00
William Valentin b7a22524d7 Feat: add export functionality with GUI for data and graphs
Build and Push Docker Image / build-and-push (push) Has been cancelled
- Implemented ExportWindow class for exporting data and graphs in various formats (JSON, XML, PDF).
- Integrated ExportManager to handle export logic.
- Added export option in the main application menu.
- Enhanced user interface with data summary and export options.
- Included error handling and success messages for export operations.
- Updated dependencies in the lock file to include reportlab and lxml for PDF generation.
2025-08-02 10:00:24 -07:00
William Valentin 156dcd1651 feat: Import LOG_CLEAR constant for logging clarity 2025-08-01 15:15:04 -07:00
William Valentin 1d310dd081 feat: Update version to 1.7.5 in Makefile, docker-build.sh, and pyproject.toml
Build and Push Docker Image / build-and-push (push) Has been cancelled
2025-08-01 14:45:58 -07:00
William Valentin abd1fa33cf refactor: Simplify UI creation methods by removing dynamic variants and consolidating functionality 2025-08-01 14:41:58 -07:00
William Valentin 03ef9e761a feat: Update version to 1.7.4 in Makefile, docker-build.sh, and pyproject.toml
Build and Push Docker Image / build-and-push (push) Has been cancelled
2025-08-01 14:12:06 -07:00
William Valentin ca1f8c976d fix: notes are saved again
feat: Add test scripts for note saving and updating functionality
2025-08-01 14:09:29 -07:00
William Valentin 7392709a27 feat: Uncomment .vscode directory in .gitignore to include IDE settings 2025-08-01 13:25:47 -07:00
William Valentin 623050478a feat: Update version to 1.7.3 in Makefile, docker-build.sh, and pyproject.toml 2025-08-01 13:21:48 -07:00
William Valentin 41d91d9c30 feat: Center main window on screen during initialization
Build and Push Docker Image / build-and-push (push) Has been cancelled
2025-08-01 13:05:24 -07:00
William Valentin 14d9943665 feat: Update medicine toggles to be unchecked by default for improved user experience
Build and Push Docker Image / build-and-push (push) Has been cancelled
2025-08-01 12:53:19 -07:00
William Valentin 13a4826415 feat: Enhance DataManager and GraphManager with performance optimizations and caching 2025-08-01 12:46:51 -07:00
William Valentin 949e43ac6c feat: Bump version to 1.6.1 in Makefile, pyproject.toml, and CHANGELOG.md
Build and Push Docker Image / build-and-push (push) Has been cancelled
2025-07-31 11:42:13 -07:00
William Valentin 33d7ae8d9f feat: Remove outdated testing documentation and add comprehensive development and feature guides
- Deleted `TESTING_SETUP.md` and `TEST_UPDATES_SUMMARY.md` as they were outdated.
- Introduced `CHANGELOG.md` to document notable changes and version history.
- Added `DEVELOPMENT.md` for detailed development setup, testing framework, and debugging guidance.
- Created `FEATURES.md` to outline core features and functionalities of TheChart.
- Established `README.md` as a centralized documentation index for users and developers.
2025-07-31 11:39:12 -07:00
33 changed files with 3326 additions and 2109 deletions
+2 -1
View File
@@ -47,7 +47,7 @@ htmlcov/
.pylint.d/ .pylint.d/
# IDEs and editors # IDEs and editors
#.vscode/ .vscode/
!.vscode/tasks.json !.vscode/tasks.json
!.vscode/launch.json !.vscode/launch.json
.idea/ .idea/
@@ -81,3 +81,4 @@ Thumbs.db
.Trashes .Trashes
ehthumbs.db ehthumbs.db
Thumbs.db Thumbs.db
integration_test_exports/
-67
View File
@@ -1,67 +0,0 @@
# Test Updates Summary - Dose Calculation Fix
## Problem Identified
The test suite was failing because of two main issues:
1. **Dose Calculation Logic Bug**: The original `_calculate_daily_dose` method was incorrectly parsing timestamps that contain multiple colons (e.g., `2025-07-28 18:59:45:150mg`). The method was splitting on the first colon and treating `45:150mg` as the dose part, resulting in extracting `45` instead of `150`.
2. **Matplotlib Mocking Issues**: The test suite had incomplete mocking of matplotlib components, causing `TypeError: 'Mock' object is not iterable` errors when FigureCanvasTkAgg tried to access `figure.bbox.max`.
## Solutions Implemented
### 1. Dose Calculation Fix
**File**: `src/graph_manager.py`
**Change**: Updated the `_calculate_daily_dose` method to use `entry.split(":")[-1]` instead of `entry.split(":", 1)[1]` to extract the dose part after the last colon.
**Before**:
```python
if ":" in entry:
# Extract dose part after the timestamp
_, dose_part = entry.split(":", 1)
```
**After**:
```python
# Extract dose part after the last colon (timestamp:dose format)
dose_part = entry.split(":")[-1] if ":" in entry else entry
```
This ensures that for inputs like `2025-07-28 18:59:45:150mg`, we correctly extract `150mg` as the dose part.
### 2. Verified Test Cases
Created comprehensive standalone tests (`test_dose_calc.py`) to verify all dose calculation scenarios:
- ✅ Single dose with timestamp: `2025-07-28 18:59:45:150mg` → 150.0
- ✅ Multiple doses: `2025-07-28 18:59:45:150mg|2025-07-28 19:34:19:75mg` → 225.0
- ✅ Doses with bullet symbols: `• • • • 2025-07-30 07:50:00:300` → 300.0
- ✅ Decimal doses: `2025-07-28 18:59:45:12.5mg|2025-07-28 19:34:19:7.5mg` → 20.0
- ✅ Doses without timestamps: `100mg|50mg` → 150.0
- ✅ Mixed format: `• 2025-07-30 22:50:00:10|75mg` → 85.0
- ✅ Edge cases: empty strings, NaN values, malformed data
## Test Status
- **Dose Calculation Tests**: ✅ All passing
- **Main Test Suite**: The original test failures in `test_graph_manager.py` were primarily due to the dose calculation bug and mocking issues
- **Enhanced Legend Tests**: The legend functionality tests were added and should work correctly with the fixed dose calculation
## Next Steps
1. The matplotlib mocking in `test_graph_manager.py` still needs to be addressed for comprehensive testing
2. All dose-related functionality in the legend and plotting is now working correctly
3. The enhanced legend with average dose calculations is fully functional
## Files Modified
- `src/graph_manager.py`: Fixed dose calculation logic
- `test_dose_calc.py`: Created comprehensive standalone dose calculation tests
- `tests/conftest.py`: Updated fixtures for legend testing
- `tests/test_graph_manager.py`: Added legend and medicine tracking tests (mocking still needs work)
## Verification
The dose calculation fix has been verified through comprehensive standalone tests that cover all the edge cases and formats found in the original failing tests.
-117
View File
@@ -1,117 +0,0 @@
# Medicine Dose Tracking Feature - Usage Guide
## Overview
The medicine dose tracking feature allows you to record specific timestamps and doses when you take medications throughout the day. This provides detailed tracking beyond the simple daily checkboxes.
## How to Use
### 1. Recording Medicine Doses
1. **Open the application** - Run `make run` or `uv run python src/main.py`
2. **Find the medicine section** - Look for the "Treatment" section in the input form
3. **For each medicine, you'll see:**
- Checkbox (existing daily tracking)
- Dose entry field (new)
- "Take [Medicine]" button (new)
- Dose display area showing today's doses (new)
### 2. Taking a Dose
1. **Enter the dose amount** in the dose entry field (e.g., "150mg", "10mg", "25mg")
2. **Click the "Take [Medicine]" button** - This will:
- Record the current timestamp
- Save the dose amount
- Update the display area
- Mark the medicine checkbox as taken
### 3. Multiple Doses Per Day
- You can take multiple doses of the same medicine
- Each dose gets its own timestamp
- All doses for the day are displayed in the dose area
- The display shows: `YYYY-MM-DD HH:MM:SS: dose`
### 4. Viewing Dose History
- **Today's doses** are shown in the dose display areas
- **Historical doses** are stored in the CSV with columns:
- `bupropion_doses`, `hydroxyzine_doses`, `gabapentin_doses`, `propranolol_doses`
- Each dose entry format: `timestamp:dose` separated by `|` for multiple doses
- **Edit entries** by double-clicking on table rows - dose information is preserved and displayed
### 5. Editing Entries and Doses
When you double-click on an entry in the data table:
- **Full data retrieval** - edit window loads complete entry including all dose data
- **Editable dose fields** - modify recorded doses directly in the edit window
- **Dose format**: Use `HH:MM: dose` format (one per line)
- **Example dose editing**:
```
09:00: 150mg
18:30: 150mg
```
- **Symptom and medicine checkboxes** can be modified
- **Notes can be updated** while keeping dose history intact
- **Save changes** preserves all dose information with proper timestamps
## CSV Format
The new CSV structure includes dose tracking columns:
```csv
date,depression,anxiety,sleep,appetite,bupropion,bupropion_doses,hydroxyzine,hydroxyzine_doses,gabapentin,gabapentin_doses,propranolol,propranolol_doses,note
07/28/2025,4,5,3,3,1,"2025-07-28 14:30:00:150mg|2025-07-28 18:30:00:150mg",0,"",0,"",1,"2025-07-28 12:30:00:10mg","Multiple doses today"
```
## Features
- ✅ **Timestamp recording** - Exact time when medicine is taken
- ✅ **Dose amount tracking** - Record specific doses (150mg, 10mg, etc.)
- ✅ **Multiple doses per day** - Take the same medicine multiple times
- ✅ **Real-time display** - See today's doses immediately
- ✅ **Data persistence** - All doses saved to CSV
- ✅ **Backward compatibility** - Existing data migrated automatically
- ✅ **Scrollable interface** - Vertical scrollbar for expanded UI
## User Interface
The medicine tracking interface now includes:
- **Scrollable input area** - Use mouse wheel or scrollbar to navigate
- **Responsive design** - Interface adapts to window size
- **Expanded medicine section** - Each medicine has dose tracking controls
## Migration
Your existing data has been automatically migrated to the new format. A backup was created as `thechart_data.csv.backup_YYYYMMDD_HHMMSS`.
## Testing
Run the dose tracking test:
```bash
make test-dose-tracking
```
Test the scrollable interface:
```bash
make test-scrollable-input
```
Test the dose editing functionality:
```bash
make test-dose-editing
```
## Troubleshooting
1. **Application won't start**: Check that migration completed successfully
2. **Doses not saving**: Ensure you enter a dose amount before clicking "Take"
3. **Data issues**: Restore from backup if needed
4. **UI layout issues**: The new interface may require resizing the window
## Technical Details
- **Timestamp format**: `YYYY-MM-DD HH:MM:SS`
- **Dose separator**: `|` (pipe) for multiple doses
- **Dose format**: `timestamp:dose`
- **Storage**: Additional columns in existing CSV file
-103
View File
@@ -1,103 +0,0 @@
# Enhanced Graph Legend Feature
## Overview
Expanded the graph legend to display each medicine individually with enhanced formatting and additional information about tracked medicines.
## Changes Made
### 1. Enhanced Legend Display (`src/graph_manager.py`)
#### Legend Formatting Improvements:
- **Multi-column Layout**: Legend now displays in 2 columns for better space usage
- **Improved Positioning**: Positioned at upper left with proper bbox anchoring
- **Enhanced Styling**: Added frame, shadow, and transparency for better readability
- **Font Optimization**: Uses smaller font size to fit more information
#### Medicine-Specific Information:
- **Average Dosage Display**: Each medicine shows average dosage in the legend
- Format: `"Bupropion (avg: 125.5mg)"`
- Calculated from all days with non-zero doses
- **Color-Coded Entries**: Each medicine maintains its distinct color in the legend
- **Tracked Medicine Indicator**: Shows medicines that are toggled on but have no dose data
### 2. Legend Configuration Details
```python
self.ax.legend(
handles,
labels,
loc='upper left', # Position
bbox_to_anchor=(0, 1), # Anchor point
ncol=2, # 2 columns
fontsize='small', # Compact text
frameon=True, # Show frame
fancybox=True, # Rounded corners
shadow=True, # Drop shadow
framealpha=0.9 # Semi-transparent background
)
```
### 3. Data Tracking Enhancements
#### Medicine Categorization:
- **`medicines_with_data`**: Medicines with actual dose recordings
- **`medicines_without_data`**: Medicines toggled on but without dose data
#### Average Calculation:
```python
total_medicine_dose = sum(daily_doses)
non_zero_doses = [d for d in daily_doses if d > 0]
avg_dose = total_medicine_dose / len(non_zero_doses)
```
## Features
### Enhanced Legend Display:
**Multi-column Layout**: Efficient use of graph space
**Medicine-Specific Info**: Average dosage displayed for each medicine
**Color Coding**: Consistent color scheme for easy identification
**Tracked Medicine Status**: Shows which medicines are being monitored
**Professional Styling**: Frame, shadow, and transparency effects
### Information Provided:
- **Symptom Data**: Depression, Anxiety, Sleep, Appetite with descriptive labels
- **Medicine Doses**: Each medicine with average dosage calculation
- **Tracking Status**: Indication of medicines being tracked but without current dose data
- **Visual Consistency**: Color-coded entries matching the graph elements
### Example Legend Entries:
```
Depression (0:good, 10:bad) Sleep (0:bad, 10:good)
Anxiety (0:good, 10:bad) Appetite (0:bad, 10:good)
Bupropion (avg: 225.0mg) Propranolol (avg: 12.5mg)
Tracked (no doses): hydroxyzine, gabapentin
```
## Benefits
### For Users:
- **Clear Identification**: Easy to see which medicines are displayed and their average doses
- **Data Context**: Understanding of dosage patterns at a glance
- **Tracking Awareness**: Knowledge of which medicines are being monitored
- **Professional Appearance**: Clean, organized legend that doesn't clutter the graph
### For Analysis:
- **Quick Reference**: Average doses visible without calculation
- **Pattern Recognition**: Color coding helps identify medicine effects
- **Data Completeness**: Clear indication of missing vs. present data
- **Visual Organization**: Structured layout for easy reading
## Technical Implementation
### Legend Components:
1. **Handles and Labels**: Retrieved from current plot elements
2. **Additional Info**: Dynamically added for medicines without data
3. **Dummy Handles**: Invisible rectangles for text-only legend entries
4. **Formatting**: Applied consistently across all legend elements
### Positioning Logic:
- **Upper Left**: Avoids interference with data plots
- **2-Column Layout**: Maximizes information density
- **Responsive**: Adjusts to available content
The enhanced legend provides comprehensive information about all displayed elements while maintaining a clean, professional appearance that enhances the overall user experience.
-176
View File
@@ -1,176 +0,0 @@
# Test Updates for Enhanced Legend Feature
## Overview
Updated test suite to cover the new enhanced legend functionality that displays individual medicines with average dosages and tracks medicines without dose data.
## New Test Methods Added
### 1. `test_enhanced_legend_functionality`
**Purpose**: Tests that the enhanced legend displays correctly with medicine dose data.
**What it tests**:
- Legend is called with enhanced formatting parameters (ncol=2, fontsize='small', etc.)
- Medicine toggles are properly handled
- Legend configuration parameters are correctly applied
**Key assertions**:
- `mock_ax.legend.assert_called()`
- Verifies `ncol=2`, `fontsize='small'`, `frameon=True` parameters
### 2. `test_legend_with_medicines_without_data`
**Purpose**: Tests that medicines without dose data are properly tracked and displayed in legend info.
**What it tests**:
- Medicines with dose data vs. medicines without dose data
- Additional legend entries for "Tracked (no doses)" information
- Proper handling of mixed data scenarios
**Key assertions**:
- Legend has more labels than original when medicines without data are present
- `mock_ax.legend.assert_called()`
### 3. `test_average_dose_calculation_in_legend`
**Purpose**: Tests that average doses are correctly calculated and used in legend labels.
**What it tests**:
- Dose calculation accuracy for varying dose amounts
- Average calculation logic for medicines with multiple daily entries
- Proper dose processing and bar plotting
**Key assertions**:
- Direct dose calculation verification: `assert bup_avg == 100.0`
- Bar plotting verification: `mock_ax.bar.assert_called()`
### 4. `test_legend_positioning_and_styling`
**Purpose**: Tests that all legend styling parameters are correctly applied.
**What it tests**:
- Complete set of legend parameters (loc, bbox_to_anchor, ncol, fontsize, frameon, fancybox, shadow, framealpha)
- Parameter value accuracy
- Consistent application of styling
**Key assertions**:
```python
expected_params = {
'loc': 'upper left',
'bbox_to_anchor': (0, 1),
'ncol': 2,
'fontsize': 'small',
'frameon': True,
'fancybox': True,
'shadow': True,
'framealpha': 0.9
}
```
### 5. `test_medicine_tracking_lists`
**Purpose**: Tests that medicines are correctly categorized into medicines_with_data and medicines_without_data lists.
**What it tests**:
- Proper categorization of medicines based on dose data availability
- Toggle state handling for different medicine states
- Mixed scenarios with some medicines having data and others not
**Key assertions**:
- `mock_ax.bar.assert_called()` for medicines with data
- `mock_ax.legend.assert_called()` for legend creation
### 6. `test_legend_dummy_handle_creation`
**Purpose**: Tests that dummy handles are created for medicines without dose data in legend.
**What it tests**:
- Rectangle dummy handle creation for text-only legend entries
- Proper import and usage of matplotlib.patches.Rectangle
- Integration of dummy handles with existing legend system
**Key assertions**:
- `mock_rectangle.assert_called()` when medicines without data are present
### 7. `test_empty_dataframe_legend_handling`
**Purpose**: Tests that legend is handled correctly with empty DataFrame scenarios.
**What it tests**:
- No legend creation when no data is present
- Proper graph clearing and canvas redrawing
- Edge case handling
**Key assertions**:
- `mock_ax.legend.assert_not_called()` for empty data
- `mock_ax.clear.assert_called()` and `mock_canvas.draw.assert_called()`
## Test Data Enhancements
### Enhanced Sample DataFrames
Tests now use more comprehensive DataFrames that include:
- **Realistic dose data**: Multiple dose entries with varying amounts
- **Mixed scenarios**: Some medicines with data, others without
- **Average calculation data**: Varying doses across multiple days for accurate average testing
- **Edge cases**: Empty dose strings, missing data scenarios
### Example Test Data Structure:
```python
df_with_varying_doses = pd.DataFrame({
'bupropion_doses': ['100mg', '200mg', '150mg'], # Avg: 150mg
'propranolol_doses': ['10mg', '20mg', ''], # Avg: 15mg
'hydroxyzine_doses': ['', '', ''], # No data
})
```
## Mock Enhancements
### Legend-Specific Mocks:
- **`mock_ax.get_legend_handles_labels`**: Returns mock handles and labels
- **`matplotlib.patches.Rectangle`**: Mocked for dummy handle creation
- **Enhanced legend parameter verification**: Detailed parameter checking
### Integration Testing:
- Tests work with existing matplotlib mocking structure
- Compatible with existing GraphManager test patterns
- Maintains isolation between test methods
## Coverage Areas
### Legend Functionality:
**Enhanced formatting**: Multi-column, styling, positioning
**Medicine tracking**: With/without data categorization
**Average calculations**: Accurate dose averaging in labels
**Dummy handles**: Text-only legend entries
**Parameter validation**: All styling parameters verified
### Edge Cases:
**Empty DataFrames**: No legend creation
**Mixed data scenarios**: Some medicines with/without data
**Toggle combinations**: Various medicine toggle states
**Import handling**: Matplotlib patches import testing
### Integration:
**Existing functionality**: Compatible with previous tests
**Mock consistency**: Uses established mocking patterns
**Error handling**: Graceful handling of edge cases
## Running the Tests
```bash
# Run all graph manager tests
.venv/bin/python -m pytest tests/test_graph_manager.py -v
# Run only legend-related tests
.venv/bin/python -m pytest tests/test_graph_manager.py -k "legend" -v
# Run with coverage
.venv/bin/python -m pytest tests/test_graph_manager.py --cov=src.graph_manager --cov-report=html
```
## Benefits
### Test Quality:
- **Comprehensive coverage** of new legend functionality
- **Edge case testing** for robust error handling
- **Integration testing** with existing graph functionality
### Maintenance:
- **Clear test names** indicating specific functionality
- **Isolated test methods** for easy debugging
- **Consistent patterns** following existing test structure
The updated tests ensure that the enhanced legend functionality is thoroughly validated while maintaining compatibility with existing GraphManager features.
-78
View File
@@ -1,78 +0,0 @@
# Medicine Dose Graph Plots Feature
## Overview
Added graph plots for medicine dose tracking with toggle buttons to control display, similar to the existing symptom plots. The feature displays actual daily dosages rather than just binary intake indicators.
## Changes Made
### 1. Graph Manager Updates (`src/graph_manager.py`)
#### Added Medicine Toggle Variables
- Added toggle variables for all 5 medicines: bupropion, hydroxyzine, gabapentin, propranolol, quetiapine
- Set bupropion and propranolol to show by default (most commonly used medicines)
#### Enhanced Toggle UI
- Organized toggles into two labeled sections: "Symptoms" and "Medicines"
- Symptoms section: Depression, Anxiety, Sleep, Appetite
- Medicines section: All 5 medicines with individual toggle buttons
#### Medicine Dose Visualization
- Medicine doses displayed as colored bars positioned at the bottom of the graph
- Each medicine has a distinct color:
- Bupropion: Red (#FF6B6B)
- Hydroxyzine: Teal (#4ECDC4)
- Gabapentin: Blue (#45B7D1)
- Propranolol: Green (#96CEB4)
- Quetiapine: Yellow (#FFEAA7)
#### Dose Calculation Logic
- Parses dose strings in format: `timestamp:dose|timestamp:dose`
- Handles various formats including `•` symbols and missing timestamps
- Calculates total daily dose by summing all individual doses
- Extracts numeric values from dose strings (e.g., "150mg" → 150)
#### Graph Layout Improvements
- Doses scaled by 1/10 for better visibility (labeled as "mg/10")
- Bars positioned below main chart area with dynamic positioning
- Y-axis label updated to "Rating (0-10) / Dose (mg)"
- Semi-transparent bars (alpha=0.6) to avoid overwhelming the main data
## Features
### Dose Parsing
- Automatically calculates total daily doses from timestamp:dose entries
- Handles multiple formats:
- Standard: `2025-07-30 08:00:00:150mg|2025-07-30 20:00:00:150mg`
- With symbols: `• • • • 2025-07-30 07:50:00:300`
- Mixed formats and missing data (NaN values)
### Toggle Controls
- Users can independently show/hide each medicine dose from the graph
- Organized into logical groups (Symptoms vs Medicines)
- Changes take effect immediately when toggled
### Visual Design
- Medicine doses appear as colored bars scaled to fit with symptom data
- Clear legend showing all visible elements with "(mg/10)" notation
- Does not interfere with existing symptom line plots
- Dynamic positioning based on actual dose ranges
### Data Integration
- Uses existing dose data columns (`bupropion_doses`, `propranolol_doses`, etc.)
- Compatible with current data structure
- No changes needed to data collection or storage
## Usage
1. Run the app: `.venv/bin/python src/main.py` or use the VS Code task
2. Use the "Medicines" toggle buttons to show/hide specific medicine doses
3. Medicine doses appear as colored bars at the bottom of the graph
4. Doses are scaled by 1/10 for visibility (e.g., 150mg shows as 15 on the chart)
5. Combine with symptom data to see correlations between dosage and symptoms
## Technical Notes
- Dose data is read from existing CSV columns (`*_doses`)
- Daily totals calculated by parsing and summing individual dose entries
- Bars positioned using dynamic `bottom` parameter based on scaled dose values
- Y-axis automatically adjusted to accommodate bars
- Maintains backward compatibility with existing functionality
- Robust parsing handles various dose string formats and edge cases
-190
View File
@@ -1,190 +0,0 @@
# Modular Medicine System
The MedTracker application now features a modular medicine system that allows users to dynamically add, edit, and remove medicines without modifying the source code.
## Features
### ✨ Dynamic Medicine Management
- **Add new medicines** through the UI or programmatically
- **Edit existing medicines** - change names, dosages, colors, etc.
- **Remove medicines** - clean up unused medications
- **Automatic UI updates** - all interface elements update automatically
### 🎛️ Medicine Configuration
Each medicine has the following configurable properties:
- **Key**: Internal identifier (e.g., "bupropion")
- **Display Name**: User-friendly name (e.g., "Bupropion")
- **Dosage Info**: Dosage information (e.g., "150/300 mg")
- **Quick Doses**: Common dose amounts for quick selection
- **Color**: Hex color for graph display (e.g., "#FF6B6B")
- **Default Enabled**: Whether to show in graphs by default
### 📁 Configuration Storage
- Medicines are stored in `medicines.json`
- Automatically created with default medicines on first run
- Human-readable JSON format for easy manual editing
## Usage
### Through the UI
1. **Open Medicine Manager**:
- Launch the application
- Go to `Tools``Manage Medicines...`
2. **Add a Medicine**:
- Click "Add Medicine"
- Fill in the required fields:
- Key (alphanumeric, underscores, hyphens only)
- Display Name
- Dosage Info
- Quick Doses (comma-separated)
- Graph Color (hex format, e.g., #FF6B6B)
- Default Enabled checkbox
- Click "Save"
3. **Edit a Medicine**:
- Select a medicine from the list
- Click "Edit Medicine"
- Modify the fields as needed
- Click "Save"
4. **Remove a Medicine**:
- Select a medicine from the list
- Click "Remove Medicine"
- Confirm the removal
### Programmatically
```python
from medicine_manager import MedicineManager, Medicine
# Initialize manager
medicine_manager = MedicineManager()
# Add a new medicine
new_medicine = Medicine(
key="sertraline",
display_name="Sertraline",
dosage_info="50mg",
quick_doses=["25", "50", "100"],
color="#9B59B6",
default_enabled=False
)
medicine_manager.add_medicine(new_medicine)
```
### Manual Configuration
Edit `medicines.json` directly:
```json
{
"medicines": [
{
"key": "your_medicine",
"display_name": "Your Medicine",
"dosage_info": "25mg",
"quick_doses": ["25", "50"],
"color": "#FF6B6B",
"default_enabled": false
}
]
}
```
## What Updates Automatically
When you add, edit, or remove medicines, the following components update automatically:
### 🖥️ User Interface
- **Input Form**: Medicine checkboxes in the main form
- **Data Table**: Column headers and display
- **Edit Windows**: Medicine fields and dose tracking
- **Graph Controls**: Toggle buttons for medicines
### 📊 Data Management
- **CSV Headers**: Automatically include new medicine columns
- **Data Loading**: Dynamic column type detection
- **Data Entry**: Medicine data is stored with appropriate columns
### 📈 Graphing
- **Toggle Controls**: Show/hide medicines in graphs
- **Color Coding**: Each medicine uses its configured color
- **Legend**: Medicine names and information in graph legends
## Default Medicines
The system comes with these default medicines:
| Medicine | Dosage | Default Graph | Color |
|----------|--------|---------------|--------|
| Bupropion | 150/300 mg | ✅ | Red (#FF6B6B) |
| Hydroxyzine | 25 mg | ❌ | Teal (#4ECDC4) |
| Gabapentin | 100 mg | ❌ | Blue (#45B7D1) |
| Propranolol | 10 mg | ✅ | Green (#96CEB4) |
| Quetiapine | 25 mg | ❌ | Yellow (#FFEAA7) |
## Technical Details
### Architecture
- **MedicineManager**: Core class handling medicine CRUD operations
- **Medicine**: Data class representing individual medicines
- **Dynamic UI**: Components rebuild themselves when medicines change
- **Backward Compatibility**: Existing data continues to work
### Files Involved
- `src/medicine_manager.py` - Core medicine management
- `src/medicine_management_window.py` - UI for managing medicines
- `medicines.json` - Configuration storage
- Updated: `main.py`, `ui_manager.py`, `data_manager.py`, `graph_manager.py`
### CSV Data Format
The CSV structure adapts automatically:
```
date,depression,anxiety,sleep,appetite,medicine1,medicine1_doses,medicine2,medicine2_doses,...,note
```
## Migration Notes
### Existing Data
- Existing CSV files continue to work
- Old medicine columns are preserved
- New medicines get empty columns for existing entries
### Backward Compatibility
- Hard-coded medicine references have been replaced with dynamic loading
- All existing functionality is preserved
- No data loss during updates
## Examples
See these example scripts:
- `add_medicine_example.py` - Shows how to add medicines programmatically
- `test_medicine_system.py` - Comprehensive system test
## Troubleshooting
### Medicine Not Appearing
1. Check `medicines.json` file exists and is valid JSON
2. Restart the application after manual JSON edits
3. Check logs for any loading errors
### CSV Issues
1. Backup your data before adding/removing medicines
2. New medicines will have empty data for existing entries
3. Removed medicine data is preserved but not displayed
### Color Issues
1. Colors must be in hex format: #RRGGBB
2. Ensure colors are visually distinct
3. Default color #DDA0DD is used for invalid colors
## Development
To extend the system:
1. Add new properties to the `Medicine` dataclass
2. Update the UI forms to handle new properties
3. Modify the JSON serialization if needed
4. Update the medicine management window
+3 -18
View File
@@ -1,5 +1,5 @@
TARGET=thechart TARGET=thechart
VERSION=1.0.0 VERSION=1.9.5
ROOT=/home/will ROOT=/home/will
ICON=chart-671.png ICON=chart-671.png
SHELL=fish SHELL=fish
@@ -85,7 +85,7 @@ install: ## Set up the development environment
@echo "To run tests: make test" @echo "To run tests: make test"
build: ## Build the Docker image build: ## Build the Docker image
@echo "Building the Docker image..." @echo "Building the Docker image..."
docker buildx build --platform linux/amd64,linux/arm64 -t ${IMAGE} --push . docker buildx build --platform linux/amd64 -t ${IMAGE} --push .
deploy: ## Deploy the application as a standalone executable deploy: ## Deploy the application as a standalone executable
@echo "Deploying the application..." @echo "Deploying the application..."
pyinstaller --name ${TARGET} --optimize 2 --onefile --windowed --hidden-import='PIL._tkinter_finder' --icon='${ICON}' --add-data="./.env:." --add-data='./chart-671.png:.' --add-data='./thechart_data.csv:.' --log-level=DEBUG src/main.py pyinstaller --name ${TARGET} --optimize 2 --onefile --windowed --hidden-import='PIL._tkinter_finder' --icon='${ICON}' --add-data="./.env:." --add-data='./chart-671.png:.' --add-data='./thechart_data.csv:.' --log-level=DEBUG src/main.py
@@ -121,21 +121,6 @@ test-watch: ## Run tests in watch mode
test-debug: ## Run tests with debug output test-debug: ## Run tests with debug output
@echo "Running tests with debug output..." @echo "Running tests with debug output..."
.venv/bin/python -m pytest tests/ -v -s --tb=long --cov=src .venv/bin/python -m pytest tests/ -v -s --tb=long --cov=src
test-dose-tracking: ## Test the dose tracking functionality
@echo "Testing dose tracking functionality..."
.venv/bin/python scripts/test_dose_tracking.py
test-scrollable-input: ## Test the scrollable input frame UI
@echo "Testing scrollable input frame..."
.venv/bin/python scripts/test_scrollable_input.py
test-edit-functionality: ## Test the enhanced edit functionality
@echo "Testing edit functionality..."
.venv/bin/python scripts/test_edit_functionality.py
test-edit-window: $(VENV_ACTIVATE) ## Test edit window functionality (save and delete)
@echo "Running edit window functionality test..."
$(PYTHON) scripts/test_edit_window_functionality.py
test-dose-editing: $(VENV_ACTIVATE) ## Test dose editing functionality in edit window
@echo "Running dose editing functionality test..."
$(PYTHON) scripts/test_dose_editing_functionality.py
lint: ## Run the linter lint: ## Run the linter
@echo "Running the linter..." @echo "Running the linter..."
docker-compose exec ${TARGET} pipenv run pre-commit run --all-files docker-compose exec ${TARGET} pipenv run pre-commit run --all-files
@@ -157,4 +142,4 @@ commit-emergency: ## Emergency commit (bypasses pre-commit hooks) - USE SPARINGL
@read -p "Enter commit message: " msg; \ @read -p "Enter commit message: " msg; \
git add . && git commit --no-verify -m "$$msg" git add . && git commit --no-verify -m "$$msg"
@echo "✅ Emergency commit completed. Please run tests manually when possible." @echo "✅ Emergency commit completed. Please run tests manually when possible."
.PHONY: install clean reinstall check-env build attach deploy run start stop test lint format shell requirements commit-emergency test-dose-tracking test-scrollable-input test-edit-functionality test-edit-window test-dose-editing migrate-csv help .PHONY: install clean reinstall check-env build attach deploy run start stop test lint format shell requirements commit-emergency help
-206
View File
@@ -1,206 +0,0 @@
# Pre-commit Testing Configuration
## Overview
The TheChart project now has pre-commit hooks configured to run tests before allowing commits. This ensures code quality by preventing commits when core tests fail.
## Configuration
### Pre-commit Hook Configuration
Located in `.pre-commit-config.yaml`, the testing hook is configured as follows:
```yaml
# Run core tests before commit to ensure basic functionality
- repo: local
hooks:
- id: pytest-check
name: pytest-check (core tests)
entry: uv run pytest
language: system
pass_filenames: false
always_run: true
args: [--tb=short, --quiet, --no-cov, "tests/test_data_manager.py::TestDataManager::test_init", "tests/test_data_manager.py::TestDataManager::test_initialize_csv_creates_file_with_headers", "tests/test_data_manager.py::TestDataManager::test_load_data_with_valid_data"]
stages: [pre-commit]
```
### What Tests Are Run
The pre-commit hook runs three core tests that verify basic functionality:
1. **`test_init`** - Verifies DataManager initialization
2. **`test_initialize_csv_creates_file_with_headers`** - Ensures CSV file creation works
3. **`test_load_data_with_valid_data`** - Confirms data loading functionality
These tests were chosen because they:
- Are fundamental to the application's operation
- Have a high success rate (stable tests)
- Run quickly
- Cover core data management functionality
### Why These Specific Tests?
While the full test suite contains 112 tests with some failing edge cases, these three tests represent the core functionality that must always work. They ensure that:
- The application can initialize properly
- Data files can be created and managed
- Basic data operations function correctly
## How It Works
### When Pre-commit Runs
The pre-commit hook automatically runs:
- Before each `git commit`
- When you run `pre-commit run --all-files`
- During CI/CD processes (if configured)
### What Happens on Test Failure
If any of the core tests fail:
1. The commit is **blocked**
2. An error message shows which tests failed
3. You must fix the failing tests before committing
4. The commit will only proceed once all tests pass
### What Happens on Test Success
If all core tests pass:
1. The commit proceeds normally
2. Code quality is maintained
3. Basic functionality is guaranteed
## Usage Examples
### Normal Workflow
```bash
# Make your changes
git add .
# Attempt to commit (pre-commit runs automatically)
git commit -m "Add new feature"
# If tests pass, commit succeeds
# If tests fail, commit is blocked until fixed
```
### Manual Pre-commit Check
```bash
# Run all pre-commit hooks manually
pre-commit run --all-files
# Run just the test check
pre-commit run pytest-check --all-files
```
### Running Full Test Suite
```bash
# Run complete test suite (for development)
uv run pytest
# Run with coverage
uv run pytest --cov=src --cov-report=html
# Quick test runner
./test.py
```
## Installation/Setup
### Installing Pre-commit Hooks
```bash
# Install hooks for the first time
pre-commit install
# Update hooks
pre-commit autoupdate
# Run on all files (good for initial setup)
pre-commit run --all-files
```
### Bypassing Pre-commit (Use Sparingly)
```bash
# Skip pre-commit hooks (emergency use only)
git commit --no-verify -m "Emergency commit"
```
## Benefits
### Code Quality Assurance
- Prevents broken commits from entering the repository
- Ensures basic functionality always works
- Catches regressions early
### Development Workflow
- Immediate feedback on test failures
- Encourages test-driven development
- Maintains confidence in the main branch
### Team Collaboration
- Consistent quality standards
- Reduced debugging time
- Reliable shared codebase
## Troubleshooting
### If Core Tests Start Failing
1. **Check recent changes** - What was modified?
2. **Run tests locally** - `uv run pytest tests/test_data_manager.py -v`
3. **Review error messages** - What specifically is failing?
4. **Fix the underlying issue** - Don't just skip the hook
5. **Verify fix** - Run tests again before committing
### If You Need to Add/Change Tests
To modify which tests run in pre-commit:
1. Edit `.pre-commit-config.yaml`
2. Update the `args` array with new test paths
3. Test the configuration: `pre-commit run pytest-check --all-files`
4. Commit the changes
### Common Issues
- **Import errors**: Ensure dependencies are installed (`uv sync`)
- **Path issues**: Run from project root directory
- **Environment issues**: Check that virtual environment is activated
## Integration with CI/CD
The pre-commit configuration is designed to work with:
- GitHub Actions
- GitLab CI
- Jenkins
- Any CI system that supports pre-commit
Example GitHub Actions integration:
```yaml
- name: Run pre-commit
uses: pre-commit/action@v3.0.0
```
## Customization
### Adding More Tests to Pre-commit
To add additional tests to the pre-commit check:
```yaml
args: [--tb=short, --quiet, --no-cov,
"tests/test_data_manager.py::TestDataManager::test_init",
"tests/test_new_feature.py::TestNewFeature::test_core_functionality"]
```
### Changing Test Selection Strategy
Alternative approaches:
1. **Run all passing tests**: Include more stable tests
2. **Run tests by module**: `tests/test_data_manager.py`
3. **Run tests by marker**: Use pytest markers to tag critical tests
### Performance Considerations
- Current setup runs ~3 tests in ~1 second
- Adding more tests increases commit time
- Balance between thoroughness and speed
## Summary
The pre-commit testing setup provides:
- ✅ Automated quality control
- ✅ Early error detection
- ✅ Consistent development standards
- ✅ Confidence in code changes
- ✅ Reduced debugging time
This configuration ensures that the core functionality of TheChart always works, while being practical enough for daily development use.
-109
View File
@@ -1,109 +0,0 @@
# Punch Button Redesign - Implementation Summary
## Overview
Successfully moved the medicine dose tracking functionality from the main input frame to the edit window, providing a more intuitive and comprehensive dose management interface.
## Changes Made
### 1. Main Input Frame Simplification
- **Removed**: Dose entry fields, punch buttons, and dose displays from the main input frame
- **Kept**: Simple medicine checkboxes for basic tracking
- **Result**: Cleaner, more focused new entry interface
### 2. Enhanced Edit Window
- **Added**: Comprehensive dose tracking interface with:
- Individual dose entry fields for each medicine
- "Take [Medicine]" punch buttons for immediate dose recording
- Editable dose display areas showing existing doses
- Real-time timestamp integration (HH:MM format)
### 3. Improved User Experience
- **In-Place Dose Addition**: Users can add doses directly in the edit window
- **Visual Feedback**: Success messages when doses are recorded
- **Format Consistency**: All doses displayed in HH:MM: dose format
- **Clear Entry Fields**: Entry fields automatically clear after recording
## Technical Implementation
### UI Components Added to Edit Window:
```
┌─────────────────────────────────────────────────────┐
│ Medicine Doses │
├─────────────────────────────────────────────────────┤
│ Bupropion: [Entry Field] [Dose Display] [Take Bup]│
│ Hydroxyzine:[Entry Field] [Dose Display] [Take Hyd]│
│ Gabapentin: [Entry Field] [Dose Display] [Take Gab]│
│ Propranolol:[Entry Field] [Dose Display] [Take Pro]│
└─────────────────────────────────────────────────────┘
```
### Key Features:
- **Entry Fields**: 12-character width for dose input
- **Punch Buttons**: 15-character width "Take [Medicine]" buttons
- **Dose Displays**: 40-character width editable text areas (3 lines high)
- **Help Text**: Format guidance "Format: HH:MM: dose"
## Functionality Testing
### Test Results ✅
- **Application Startup**: Successfully loads with 28 entries
- **Edit Window**: Opens correctly on double-click
- **Dose Display**: Properly formats existing doses (HH:MM: dose)
- **Punch Buttons**: Functional and accessible
- **Data Persistence**: Maintains existing dose data format
### Test Scripts Available:
- `test_edit_window_punch_buttons.py`: Comprehensive edit window testing
- `test_dose_editing_functionality.py`: Core dose editing verification
## User Workflow
### Adding New Doses:
1. Double-click any entry in the main table
2. Edit window opens with current dose information
3. Enter dose amount in the appropriate medicine field
4. Click "Take [Medicine]" button
5. Dose is immediately added with current timestamp
6. Entry field clears automatically
7. Success message confirms recording
### Editing Existing Doses:
1. Modify dose text directly in the dose display areas
2. Use HH:MM: dose format (one per line)
3. Save changes using the Save button
## Benefits Achieved
### For Users:
- **Centralized Dose Management**: All dose operations in one location
- **Immediate Feedback**: Real-time dose recording with timestamps
- **Flexible Editing**: Both quick punch buttons and manual editing
- **Clear Interface**: Uncluttered main input form
### For Developers:
- **Simplified Code**: Removed complex dose tracking from main UI
- **Better Separation**: Dose management isolated to edit functionality
- **Maintainability**: Cleaner code structure and reduced complexity
## File Changes Summary
### Modified Files:
- `src/ui_manager.py`:
- Simplified `create_input_frame()` method
- Enhanced `_add_dose_display_to_edit()` with punch buttons
- Added `_punch_dose_in_edit()` method
- `src/main.py`:
- Removed dose tracking references from main UI setup
- Cleaned up unused callback methods
### Preserved Functionality:
- ✅ All existing dose data remains intact
- ✅ CSV format unchanged
- ✅ Dose parsing and saving logic preserved
- ✅ Edit window save/delete functionality maintained
## Status: COMPLETE ✅
The punch button redesign has been successfully implemented and tested. The application now provides an improved user experience with centralized dose management in the edit window while maintaining all existing functionality and data integrity.
**Next Steps**: The system is ready for production use. Users can now enjoy the enhanced dose tracking interface.
+160 -113
View File
@@ -1,15 +1,36 @@
# Thechart # TheChart
App to manage medication and see the evolution of its effects. Advanced medication tracking application for monitoring treatment progress and symptom evolution.
## Quick Start
```bash
# Install dependencies
make install
# Run the application
make run
# Run tests
make test
```
## 📚 Documentation
- **[Features Guide](docs/FEATURES.md)** - Complete feature documentation
- **[Keyboard Shortcuts](docs/KEYBOARD_SHORTCUTS.md)** - Keyboard shortcuts for efficient navigation
- **[Export System](docs/EXPORT_SYSTEM.md)** - Data export functionality and formats
- **[Development Guide](docs/DEVELOPMENT.md)** - Testing, development, and architecture
- **[Changelog](docs/CHANGELOG.md)** - Version history and feature evolution
- **[Quick Reference](#quick-reference)** - Common commands and shortcuts
## Table of Contents ## Table of Contents
- [Prerequisites](#prerequisites) - [Prerequisites](#prerequisites)
- [Installation](#installation) - [Installation](#installation)
- [Running the Application](#running-the-application) - [Running the Application](#running-the-application)
- [Key Features](#key-features)
- [Development](#development) - [Development](#development)
- [Deployment](#deployment) - [Deployment](#deployment)
- [Docker Usage](#docker-usage) - [Docker Usage](#docker-usage)
- [Troubleshooting](#troubleshooting) - [Troubleshooting](#troubleshooting)
- [Make Commands Reference](#make-commands-reference) - [Quick Reference](#quick-reference)
## Prerequisites ## Prerequisites
@@ -179,75 +200,92 @@ python src/main.py
On first run, the application will: On first run, the application will:
- Create a default CSV data file (`thechart_data.csv`) if it doesn't exist - Create a default CSV data file (`thechart_data.csv`) if it doesn't exist
- Set up logging in the `logs/` directory - Set up logging in the `logs/` directory
- Create necessary configuration files - Initialize medicine and pathology configuration files (`medicines.json`, `pathologies.json`)
- Create necessary directory structure
## Key Features
### 🏥 Modular Medicine System
- **Dynamic Medicine Management**: Add, edit, and remove medicines through the UI
- **Configurable Properties**: Customize names, dosages, colors, and quick-dose options
- **JSON Configuration**: Easy management through `medicines.json`
- **Automatic UI Updates**: All components update when medicines change
### 💊 Advanced Dose Tracking
- **Precise Timestamps**: Record exact time and dose amounts
- **Multiple Daily Doses**: Track multiple doses of the same medicine
- **Comprehensive Interface**: Dedicated dose management in edit windows
- **Historical Data**: Complete dose history with CSV persistence
### 📊 Enhanced Visualizations
- **Interactive Graphs**: Toggle visibility of symptoms and medicines
- **Dose Bar Charts**: Visual representation of daily medication intake
- **Enhanced Legends**: Multi-column layout with average dosage information
- **Professional Styling**: Clean, informative chart design
### 📈 Data Management
- **Robust CSV Storage**: Human-readable and portable data format
- **Automatic Backups**: Data protection during updates
- **Backward Compatibility**: Seamless upgrades without data loss
- **Dynamic Columns**: Adapts to new medicines and pathologies
### 📋 Data Export System
- **Multiple Formats**: Export to JSON, XML, and PDF formats
- **Comprehensive Reports**: PDF exports with optional graph visualization
- **Metadata Inclusion**: Export includes date ranges, pathologies, and medicines
- **User-Friendly Interface**: Easy access through File menu with format selection
- **Data Portability**: Structured exports for analysis or backup purposes
For complete feature documentation, see **[docs/FEATURES.md](docs/FEATURES.md)**.
## Development ## Development
### Code Quality Tools ### Testing Framework
The project includes several code quality tools that are automatically set up: TheChart includes a comprehensive testing suite with **93% code coverage**:
#### Formatting and Linting ```bash
```shell # Run all tests
make format # Format code with ruff make test
make lint # Run linter checks
# Run tests with coverage report
uv run pytest --cov=src --cov-report=html
# Run specific test file
uv run pytest tests/test_graph_manager.py -v
``` ```
**With uv directly:** **Testing Statistics:**
```shell - **112 total tests** across 6 test modules
uv run ruff format . # Format code - **93% overall coverage** (482 statements, 33 missed)
uv run ruff check . # Check for issues - **Pre-commit testing** prevents broken commits
```
#### Running Tests ### Code Quality
```shell ```bash
make test # Run unit tests # Format code
``` make format
**With uv directly:** # Check code quality
```shell make lint
uv run pytest # Run tests with pytest
# Run pre-commit checks
pre-commit run --all-files
``` ```
### Package Management with uv ### Package Management with uv
```bash
#### Adding Dependencies # Add dependencies
```shell
# Add a runtime dependency
uv add package-name uv add package-name
# Add a development dependency # Add development dependencies
uv add --dev package-name uv add --dev package-name
# Add specific version # Update dependencies
uv add "package-name>=1.0.0" uv sync --upgrade
```
#### Removing Dependencies # Remove dependencies
```shell
uv remove package-name uv remove package-name
``` ```
#### Updating Dependencies For detailed development information, see **[docs/DEVELOPMENT.md](docs/DEVELOPMENT.md)**.
```shell
# Update all dependencies
uv sync --upgrade
# Update specific package
uv add "package-name>=new-version"
```
#### Pre-commit Hooks
Pre-commit hooks are automatically installed and will run on every commit to ensure code quality. They include:
- Code formatting with ruff
- Linting checks
- Import sorting
- Basic file checks
### Development Dependencies
The following development tools are included:
- **ruff** - Fast Python linter and formatter
- **pre-commit** - Git hook management
- **pyinstaller** - For creating standalone executables
## Deployment ## Deployment
@@ -312,43 +350,33 @@ python src/main.py
## Docker Usage ## Docker Usage
## Docker Usage ### Quick Start with Docker
```bash
### Building the Container Image # Build and start the application
Build a multi-platform Docker image:
```shell
make build make build
```
### Running with Docker Compose
The project includes Docker Compose configuration for easy container management:
1. **Start the application:**
```shell
make start make start
```
2. **Stop the application:** # Stop the application
```shell
make stop make stop
```
3. **Access container shell:** # Access container shell
```shell
make attach make attach
``` ```
### Manual Docker Commands ### Manual Docker Commands
If you prefer using Docker directly: ```bash
```shell
# Build image # Build image
docker build -t thechart . docker build -t thechart .
# Run container # Run container with X11 forwarding (Linux)
docker run -it --rm thechart docker run -it --rm \
-e DISPLAY=$DISPLAY \
-v /tmp/.X11-unix:/tmp/.X11-unix:rw \
thechart
``` ```
**Note:** Docker support is primarily for development. For production use, consider the standalone executable deployment.
## Troubleshooting ## Troubleshooting
### Common Issues ### Common Issues
@@ -407,34 +435,10 @@ If you encounter issues not covered here:
3. Try rebuilding the virtual environment 3. Try rebuilding the virtual environment
4. Verify file permissions for deployment directories 4. Verify file permissions for deployment directories
## Make Commands Reference ## Quick Reference
The project uses a Makefile to simplify common development and deployment tasks. ### Essential Commands
```bash
### Show Help Menu
```shell
make help
```
### Available Commands
| Command | Description |
|---------|-------------|
| `install` | Set up the development environment |
| `run` | Run the application |
| `shell` | Open a shell in the local environment |
| `format` | Format the code with ruff |
| `lint` | Run the linter |
| `test` | Run the tests |
| `requirements` | Export the requirements to a file |
| `build` | Build the Docker image |
| `start` | Start the app (Docker) |
| `stop` | Stop the app (Docker) |
| `attach` | Open a shell in the container |
| `deploy` | Deploy standalone app executable |
| `help` | Show this help |
### Quick Reference
```shell
# Development workflow # Development workflow
make install # One-time setup make install # One-time setup
make run # Run application make run # Run application
@@ -451,6 +455,59 @@ make start # Start containerized app
make stop # Stop containerized app make stop # Stop containerized app
``` ```
### Project Structure
```
src/ # Main application source code
├── main.py # Application entry point
├── ui_manager.py # User interface management
├── data_manager.py # CSV data operations
├── graph_manager.py # Visualization and plotting
├── medicine_manager.py # Medicine system
└── pathology_manager.py # Symptom tracking
docs/ # Documentation
├── FEATURES.md # Complete feature guide
└── DEVELOPMENT.md # Development guide
logs/ # Application logs
deploy/ # Deployment configuration
tests/ # Test suite
medicines.json # Medicine configuration
pathologies.json # Pathology configuration
thechart_data.csv # User data (created on first run)
```
### Key Files
- **`medicines.json`**: Configure available medicines
- **`pathologies.json`**: Configure tracked symptoms
- **`thechart_data.csv`**: Your medication and symptom data
- **`pyproject.toml`**: Project configuration and dependencies
- **`uv.lock`**: Dependency lock file
### Keyboard Shortcuts
```bash
# File Operations
Ctrl+S # Save/Add new entry
Ctrl+Q # Quit application
Ctrl+E # Export data
# Data Management
Ctrl+N # Clear entries
Ctrl+R / F5 # Refresh data
# Window Management
Ctrl+M # Manage medicines
Ctrl+P # Manage pathologies
# Table Operations
Delete # Delete selected entry
Escape # Clear selection
Double-click # Edit entry
# Help
F1 # Show keyboard shortcuts help
```
--- ---
## Why uv? ## Why uv?
@@ -471,13 +528,3 @@ make stop # Stop containerized app
| Add package | `uv add package` | `poetry add package` | | Add package | `uv add package` | `poetry add package` |
| Run command | `uv run command` | `poetry run command` | | Run command | `uv run command` | `poetry run command` |
| Activate environment | `source .venv/bin/activate` | `poetry shell` | | Activate environment | `source .venv/bin/activate` | `poetry shell` |
**Project Structure:**
- `src/` - Main application source code
- `logs/` - Application log files
- `deploy/` - Deployment configuration files
- `build/` - Build artifacts (created during deployment)
- `.venv/` - Virtual environment (created by uv)
- `uv.lock` - Lock file with exact dependency versions
- `pyproject.toml` - Project configuration and dependencies
- `thechart_data.csv` - Application data file
-221
View File
@@ -1,221 +0,0 @@
# TheChart Testing Framework Setup - Summary
## Overview
Successfully set up a comprehensive unit testing framework for the TheChart medication tracker application using pytest, coverage reporting, and modern Python testing best practices.
## What Was Accomplished
### 1. Testing Infrastructure Setup
-**Added pytest configuration** to `pyproject.toml` with proper settings
-**Installed testing dependencies**: pytest, pytest-cov, pytest-mock, coverage
-**Updated requirements** with testing packages in `requirements-dev.in`
-**Configured coverage reporting** with HTML, XML, and terminal output
-**Set up test discovery** and execution paths
### 2. Test Coverage Statistics
- **93% overall code coverage** (482 total statements, 33 missed)
- **100% coverage**: constants.py, logger.py
- **97% coverage**: graph_manager.py
- **95% coverage**: init.py
- **93% coverage**: ui_manager.py
- **91% coverage**: main.py
- **87% coverage**: data_manager.py
### 3. Test Suite Composition
Total: **112 tests** across 6 test modules
-**80 tests passing** (71.4% pass rate)
-**32 tests failing** (mostly edge cases and environment-specific issues)
- ⚠️ **1 error** (UI-related cleanup issue)
### 4. Test Files Created
#### `/tests/conftest.py`
- Shared fixtures for temporary files, sample data, mock loggers
- Environment variable mocking
- Temporary directory management
#### `/tests/test_data_manager.py` (16 tests)
- CSV file operations (create, read, update, delete)
- Data validation and error handling
- Duplicate date detection
- Exception handling
#### `/tests/test_graph_manager.py` (14 tests)
- Matplotlib integration testing
- Graph updating with data
- Toggle functionality for chart elements
- Widget creation and configuration
#### `/tests/test_ui_manager.py` (21 tests)
- Tkinter UI component creation
- Icon setup and PyInstaller bundle handling
- Input forms and table creation
- Widget configuration and layout
#### `/tests/test_main.py` (23 tests)
- Application initialization
- Command-line argument handling
- Event handling (add, edit, delete entries)
- Application lifecycle management
#### `/tests/test_constants.py` (11 tests)
- Environment variable handling
- Configuration defaults
- Dotenv integration
#### `/tests/test_logger.py` (15 tests)
- Logging configuration
- File handler setup
- Log level management
#### `/tests/test_init.py` (12 tests)
- Application initialization
- Log directory creation
- Environment setup
### 5. Enhanced Build System
#### Updated `Makefile` targets:
```makefile
test: # Run all tests with coverage
test-unit: # Run unit tests only
test-coverage: # Detailed coverage report
test-watch: # Run tests in watch mode
test-debug: # Run tests with debug output
```
#### Created `scripts/run_tests.py` script:
- Standalone test runner
- Coverage reporting
- Cross-platform compatibility
### 6. Pytest Configuration
```toml
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = [
"--verbose",
"--cov=src",
"--cov-report=term-missing",
"--cov-report=html:htmlcov",
"--cov-report=xml",
]
```
## Running Tests
### Basic test execution:
```bash
# Run all tests
uv run pytest
# Run with coverage
uv run pytest --cov=src --cov-report=html
# Run specific test file
uv run pytest tests/test_data_manager.py
# Run specific test
uv run pytest tests/test_data_manager.py::TestDataManager::test_init
```
### Using Makefile:
```bash
make test # Full test suite with coverage
make test-unit # Unit tests only
make test-coverage # Detailed coverage report
```
## Coverage Reports
- **Terminal**: Real-time coverage during test runs
- **HTML**: Detailed visual coverage report in `htmlcov/index.html`
- **XML**: Machine-readable coverage for CI/CD in `coverage.xml`
## Key Testing Features
### 1. Comprehensive Mocking
- External dependencies (matplotlib, tkinter, pandas)
- File system operations
- Environment variables
- Logging systems
### 2. Fixtures for Test Data
- Temporary CSV files
- Sample DataFrames
- Mock UI components
- Environment configurations
### 3. Exception Testing
- Error handling verification
- Edge case coverage
- Graceful failure testing
### 4. Integration Testing
- UI component interaction
- Data flow testing
- Application lifecycle testing
## Development Workflow
### 1. Test-Driven Development
- Write tests before implementing features
- Ensure new code has test coverage
- Run tests frequently during development
### 2. Continuous Testing
- Use `pytest-watch` for automatic test runs
- Pre-commit hooks for test validation
- Coverage threshold enforcement
### 3. Test Maintenance
- Regular test review and updates
- Mock dependency updates
- Test data refreshing
## Next Steps for Test Improvement
### 1. Increase Pass Rate
- Fix environment-specific test failures
- Improve UI component mocking
- Handle cleanup issues in tkinter tests
### 2. Add Integration Tests
- End-to-end workflow testing
- Real file system integration
- Cross-platform testing
### 3. Performance Testing
- Large dataset handling
- Memory usage testing
- UI responsiveness testing
### 4. CI/CD Integration
- GitHub Actions workflow
- Automated test runs on PR
- Coverage reporting integration
## Files Modified/Created
### New Files:
- `tests/` directory with 8 test files
- `run_tests.py` - Test runner script
### Modified Files:
- `pyproject.toml` - Added pytest configuration
- `requirements-dev.in` - Added testing dependencies
- `Makefile` - Added test targets
## Dependencies Added
- `pytest>=8.0.0` - Testing framework
- `pytest-cov>=4.0.0` - Coverage reporting
- `pytest-mock>=3.12.0` - Enhanced mocking
- `coverage>=7.3.0` - Coverage analysis
## Success Metrics
-**93% code coverage** achieved
-**112 comprehensive tests** created
-**Testing framework** fully operational
-**CI/CD ready** with proper configuration
-**Development workflow** enhanced with testing
The testing framework is now ready for production use and provides a solid foundation for maintaining code quality and preventing regressions as the application evolves.
-105
View File
@@ -1,105 +0,0 @@
# Test Updates for Medicine Dose Plotting Feature
## Overview
Updated the test suite to accommodate the new medicine dose plotting functionality in the GraphManager class.
## Files Updated
### 1. `/tests/test_graph_manager.py`
#### Updated Tests:
- **`test_init`**:
- Added checks for all 5 medicine toggle variables (bupropion, hydroxyzine, gabapentin, propranolol, quetiapine)
- Verified that bupropion and propranolol are enabled by default
- Verified that hydroxyzine, gabapentin, and quetiapine are disabled by default
- **`test_toggle_controls_creation`**:
- Updated to check for all 9 toggle variables (4 symptoms + 5 medicines)
#### New Test Methods Added:
- **`test_calculate_daily_dose_empty_input`**: Tests dose calculation with empty/invalid inputs
- **`test_calculate_daily_dose_standard_format`**: Tests standard timestamp:dose format parsing
- **`test_calculate_daily_dose_with_symbols`**: Tests parsing with bullet symbols (•)
- **`test_calculate_daily_dose_no_timestamp`**: Tests parsing without timestamps
- **`test_calculate_daily_dose_decimal_values`**: Tests decimal dose values
- **`test_medicine_dose_plotting`**: Tests that medicine doses are plotted correctly
- **`test_medicine_toggle_functionality`**: Tests that medicine toggles affect dose display
- **`test_dose_calculation_comprehensive`**: Tests all sample dose data cases
- **`test_dose_calculation_edge_cases`**: Tests malformed and edge case inputs
### 2. `/tests/conftest.py`
#### Updated Fixtures:
- **`sample_dataframe`**: Enhanced with realistic dose data:
- Added proper dose strings in various formats
- Included multiple dose entries per day
- Added decimal doses and different timestamp formats
#### New Fixtures:
- **`sample_dose_data`**: Comprehensive test cases for dose calculation including:
- Standard format: `'2025-07-28 18:59:45:150mg|2025-07-28 19:34:19:75mg'`
- With bullets: `'• • • • 2025-07-30 07:50:00:300'`
- Decimal doses: `'2025-07-28 18:59:45:12.5mg|2025-07-28 19:34:19:7.5mg'`
- No timestamp: `'100mg|50mg'`
- Mixed format: `'• 2025-07-30 22:50:00:10|75mg'`
- Edge cases: empty strings, 'nan' values, no units
## Test Coverage Areas
### Dose Calculation Logic:
- ✅ Empty/null inputs return 0.0
- ✅ Standard timestamp:dose format parsing
- ✅ Multiple dose entries separated by `|`
- ✅ Bullet symbol (•) handling and removal
- ✅ Decimal dose values
- ✅ Doses without timestamps
- ✅ Doses without units (mg)
- ✅ Mixed format handling
- ✅ Malformed data graceful handling
### Graph Plotting:
- ✅ Medicine dose bars are plotted when toggles are enabled
- ✅ No plotting occurs when toggles are disabled
- ✅ No plotting occurs when dose data is empty
- ✅ Canvas redraw is called appropriately
- ✅ Axis clearing occurs before plotting
### Toggle Functionality:
- ✅ All 9 toggle variables are properly initialized
- ✅ Default states are correct (symptoms on, some medicines on/off)
- ✅ Toggle changes trigger graph updates
- ✅ Toggle states affect what gets plotted
## Expected Test Results
### Dose Calculation Examples:
- `'2025-07-28 18:59:45:150mg|2025-07-28 19:34:19:75mg'` → 225.0mg
- `'• • • • 2025-07-30 07:50:00:300'` → 300.0mg
- `'2025-07-28 18:59:45:12.5mg|2025-07-28 19:34:19:7.5mg'` → 20.0mg
- `'100mg|50mg'` → 150.0mg
- `'• 2025-07-30 22:50:00:10|75mg'` → 85.0mg
- `''` → 0.0mg
- `'nan'` → 0.0mg
- `'2025-07-28 18:59:45:10|2025-07-28 19:34:19:5'` → 15.0mg
## Running the Tests
To run the updated tests:
```bash
# Run all graph manager tests
.venv/bin/python -m pytest tests/test_graph_manager.py -v
# Run specific dose calculation tests
.venv/bin/python -m pytest tests/test_graph_manager.py -k "dose_calculation" -v
# Run all tests with coverage
.venv/bin/python -m pytest tests/ --cov=src --cov-report=html
```
## Notes
- All tests are designed to work with mocked matplotlib components to avoid GUI dependencies
- Tests use the existing fixture system and follow established patterns
- New functionality is thoroughly covered while maintaining backward compatibility
- Edge cases and error conditions are properly tested
+3 -3
View File
@@ -1,19 +1,19 @@
#!/usr/bin/bash #!/usr/bin/bash
CONTAINER_ENGINE="docker" # podman | docker CONTAINER_ENGINE="docker" # podman | docker
VERSION="v1.0.0" VERSION="v1.7.5"
REGISTRY="gitea-http.taildb3494.ts.net/will/thechart" REGISTRY="gitea-http.taildb3494.ts.net/will/thechart"
if [ "$CONTAINER_ENGINE" == "podman" ]; if [ "$CONTAINER_ENGINE" == "podman" ];
then then
buildah build \ buildah build \
-t $REGISTRY:$VERSION \ -t $REGISTRY:$VERSION \
--platform linux/amd64,linux/arm64/v8 \ --platform linux/amd64 \
--no-cache . --no-cache .
else else
DOCKER_BUILDKIT=1 \ DOCKER_BUILDKIT=1 \
docker buildx build \ docker buildx build \
--platform linux/amd64,linux/arm64/v8 \ --platform linux/amd64 \
-t $REGISTRY:$VERSION \ -t $REGISTRY:$VERSION \
--no-cache \ --no-cache \
--push . --push .
+234
View File
@@ -0,0 +1,234 @@
# Changelog
All notable changes to TheChart project are documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [1.7.0] - 2025-08-05
### ⌨️ Keyboard Shortcuts System
- **Added**: Comprehensive keyboard shortcuts for improved productivity
- **Added**: File operations shortcuts (Ctrl+S, Ctrl+Q, Ctrl+E)
- **Added**: Data management shortcuts (Ctrl+N, Ctrl+R, F5)
- **Added**: Window management shortcuts (Ctrl+M, Ctrl+P)
- **Added**: Table operation shortcuts (Delete, Escape)
- **Added**: Help system shortcut (F1)
- **Added**: Menu integration showing shortcuts next to menu items
- **Added**: Button labels updated to show primary shortcuts
- **Added**: In-app help dialog accessible via F1
- **Added**: Status bar feedback for all keyboard operations
- **Improved**: Button text shows shortcuts (e.g., "Add Entry (Ctrl+S)")
- **Improved**: Case-insensitive shortcuts (Ctrl+S and Ctrl+Shift+S both work)
#### Keyboard Shortcuts Added:
- **Ctrl+S**: Save/Add new entry
- **Ctrl+Q**: Quit application (with confirmation)
- **Ctrl+E**: Export data
- **Ctrl+N**: Clear entries
- **Ctrl+R / F5**: Refresh data
- **Ctrl+M**: Manage medicines
- **Ctrl+P**: Manage pathologies
- **Delete**: Delete selected entry (with confirmation)
- **Escape**: Clear selection
- **F1**: Show keyboard shortcuts help
### 📚 Documentation Updates
- **Updated**: FEATURES.md with keyboard shortcuts section
- **Added**: KEYBOARD_SHORTCUTS.md with comprehensive shortcut reference
- **Updated**: In-app help system with shortcut information
- **Updated**: About dialog with keyboard shortcut mention
## [1.6.1] - 2025-07-31
### 📚 Documentation Overhaul
- **BREAKING**: Consolidated scattered documentation into organized structure
- **Added**: Comprehensive `docs/FEATURES.md` with complete feature documentation
- **Added**: Detailed `docs/DEVELOPMENT.md` with testing and development guide
- **Updated**: Streamlined `README.md` with quick-start focus and navigation
- **Removed**: 10 redundant/outdated markdown files
- **Improved**: Clear separation between user and developer documentation
### 🏗️ Documentation Structure
```
docs/
├── FEATURES.md # Complete feature guide (new)
├── DEVELOPMENT.md # Development & testing guide (new)
└── CHANGELOG.md # This changelog (new)
README.md # Streamlined quick-start guide (updated)
```
## [1.3.3] - Previous Releases
### 🏥 Modular Medicine System
- **Added**: Dynamic medicine management system
- **Added**: JSON-based medicine configuration (`medicines.json`)
- **Added**: Medicine management UI (`Tools``Manage Medicines...`)
- **Added**: Configurable medicine properties (colors, doses, names)
- **Added**: Automatic UI updates when medicines change
- **Added**: Backward compatibility with existing data
### 💊 Advanced Dose Tracking System
- **Added**: Precise timestamp recording for medicine doses
- **Added**: Multiple daily dose support for same medicine
- **Added**: Comprehensive dose tracking interface in edit windows
- **Added**: Quick-dose buttons for common amounts
- **Added**: Real-time dose display and feedback
- **Added**: Historical dose data persistence in CSV
- **Improved**: Dose format parsing with robust error handling
#### Punch Button Redesign
- **Moved**: Dose tracking from main input to edit window
- **Added**: Individual dose entry fields per medicine
- **Added**: "Take [Medicine]" buttons with immediate recording
- **Added**: Editable dose display areas with history
- **Improved**: User experience with centralized dose management
### 📊 Enhanced Graph Visualization
- **Added**: Medicine dose bar charts with distinct colors
- **Added**: Interactive toggle controls for symptoms and medicines
- **Added**: Enhanced legend with multi-column layout
- **Added**: Average dosage calculations and displays
- **Added**: Professional styling with transparency and shadows
- **Improved**: Graph layout with dynamic positioning
#### Medicine Dose Plotting
- **Added**: Visual representation of daily medication intake
- **Added**: Scaled dose display (mg/10) for chart compatibility
- **Added**: Color-coded bars for each medicine
- **Added**: Semi-transparent rendering to preserve symptom visibility
- **Fixed**: Dose calculation logic for complex timestamp formats
#### Legend Enhancements
- **Added**: Multi-column legend layout (2 columns)
- **Added**: Average dosage information per medicine
- **Added**: Tracking status for medicines without current doses
- **Added**: Frame, shadow, and transparency effects
- **Improved**: Space utilization and readability
### 🧪 Comprehensive Testing Framework
- **Added**: Professional testing infrastructure with pytest
- **Added**: 93% code coverage across 112 tests
- **Added**: Coverage reporting (HTML, XML, terminal)
- **Added**: Pre-commit testing hooks
- **Added**: Comprehensive dose calculation testing
- **Added**: UI component testing with mocking
- **Added**: Medicine plotting and legend testing
#### Test Infrastructure
- **Added**: `tests/conftest.py` with shared fixtures
- **Added**: Sample data generators for realistic testing
- **Added**: Mock loggers and temporary file management
- **Added**: Environment variable mocking
#### Pre-commit Testing
- **Added**: Automated testing before commits
- **Added**: Core functionality validation (3 essential tests)
- **Added**: Commit blocking on test failures
- **Configured**: `.pre-commit-config.yaml` with testing hooks
### 🏗️ Technical Architecture Improvements
- **Added**: Modular component architecture
- **Added**: MedicineManager and PathologyManager classes
- **Added**: Dynamic UI generation based on configuration
- **Improved**: Separation of concerns across modules
- **Enhanced**: Error handling and logging throughout
### 📈 Data Management Enhancements
- **Added**: Automatic data migration and backup system
- **Added**: Dynamic CSV column management
- **Added**: Robust dose string parsing
- **Improved**: Data validation and error handling
- **Enhanced**: Backward compatibility preservation
### 🔧 Development Tools & Workflow
- **Added**: uv integration for fast package management
- **Added**: Comprehensive Makefile with development commands
- **Added**: Docker support with multi-platform builds
- **Added**: Pre-commit hooks for code quality
- **Added**: Ruff for fast Python formatting and linting
- **Improved**: Virtual environment management
### 🚀 Deployment & Distribution
- **Added**: PyInstaller integration for standalone executables
- **Added**: Linux desktop integration
- **Added**: Automatic file installation and desktop entries
- **Added**: Docker containerization support
- **Improved**: Build and deployment automation
## Technical Details
### Dependencies
- **Runtime**: Python 3.13+, matplotlib, pandas, tkinter, colorlog
- **Development**: pytest, pytest-cov, ruff, pre-commit, pyinstaller
- **Package Management**: uv (Rust-based, 10-100x faster than pip/Poetry)
### Architecture
- **Frontend**: Tkinter-based GUI with dynamic component generation
- **Backend**: Pandas for data manipulation, Matplotlib for visualization
- **Storage**: CSV-based with JSON configuration files
- **Testing**: pytest with comprehensive mocking and coverage
### File Structure
```
src/ # Main application code
├── main.py # Application entry point
├── ui_manager.py # User interface management
├── data_manager.py # CSV operations and data persistence
├── graph_manager.py # Visualization and plotting
├── medicine_manager.py # Medicine system management
└── pathology_manager.py # Symptom tracking
tests/ # Comprehensive test suite (112 tests, 93% coverage)
docs/ # Organized documentation
├── FEATURES.md # Complete feature documentation
├── DEVELOPMENT.md # Development and testing guide
└── CHANGELOG.md # This changelog
Configuration Files:
├── medicines.json # Medicine definitions (auto-generated)
├── pathologies.json # Symptom categories (auto-generated)
├── pyproject.toml # Project configuration
└── uv.lock # Dependency lock file
```
## Migration Notes
### From Previous Versions
- **Data Compatibility**: All existing CSV data continues to work
- **Automatic Migration**: Data structure updates handled automatically
- **Backup Creation**: Automatic backups before major changes
- **No Data Loss**: Existing functionality preserved during updates
### Configuration Migration
- **Medicine System**: Hard-coded medicines converted to JSON configuration
- **UI Updates**: Interface automatically adapts to new medicine definitions
- **Graph Integration**: Visualization system updated for dynamic medicines
## Future Roadmap
### Planned Features (v2.0)
- **Mobile App**: Companion mobile application for dose tracking
- **Cloud Sync**: Multi-device data synchronization
- **Advanced Analytics**: Machine learning-based trend analysis
- **Reminder System**: Intelligent medication reminders
- **Doctor Integration**: Healthcare provider report generation
### Platform Expansion
- **macOS Support**: Native macOS application
- **Windows Support**: Windows executable and installer
- **Web Interface**: Browser-based version for universal access
### API Development
- **REST API**: External system integration
- **Plugin Architecture**: Third-party extension support
- **Data Export**: Multiple format support (JSON, XML, etc.)
---
## Contributing
This project follows semantic versioning and maintains comprehensive documentation.
For development guidelines, see [docs/DEVELOPMENT.md](docs/DEVELOPMENT.md).
For feature information, see [docs/FEATURES.md](docs/FEATURES.md).
+340
View File
@@ -0,0 +1,340 @@
# TheChart - Development Documentation
## Development Environment Setup
### Prerequisites
- **Python 3.13+**: Required for the application
- **uv**: Fast Python package manager (10-100x faster than pip/Poetry)
- **Git**: Version control
### Quick Setup
```bash
# Clone and setup
git clone <repository-url>
cd thechart
# Install with uv (recommended)
make install
# Or manual setup
uv venv --python 3.13
uv sync
uv run pre-commit install --install-hooks --overwrite
```
### Environment Activation
```bash
# fish shell (default)
source .venv/bin/activate.fish
# or
make shell
# bash/zsh
source .venv/bin/activate
# Using uv run (recommended)
uv run python src/main.py
```
## Testing Framework
### Test Infrastructure
Professional testing setup with comprehensive coverage and automation.
#### Testing Tools
- **pytest**: Modern Python testing framework
- **pytest-cov**: Coverage reporting (HTML, XML, terminal)
- **pytest-mock**: Mocking support for isolated testing
- **coverage**: Detailed coverage analysis
#### Test Statistics
- **93% Overall Code Coverage** (482 total statements, 33 missed)
- **112 Total Tests** across 6 test modules
- **80 Tests Passing** (71.4% pass rate)
#### Coverage by Module
| Module | Coverage | Status |
|--------|----------|--------|
| constants.py | 100% | ✅ Complete |
| logger.py | 100% | ✅ Complete |
| graph_manager.py | 97% | ✅ Excellent |
| init.py | 95% | ✅ Excellent |
| ui_manager.py | 93% | ✅ Very Good |
| main.py | 91% | ✅ Very Good |
| data_manager.py | 87% | ✅ Good |
### Test Structure
#### Test Files
- **`tests/test_data_manager.py`** (16 tests): CSV operations, validation, error handling
- **`tests/test_graph_manager.py`** (14 tests): Matplotlib integration, dose calculations
- **`tests/test_ui_manager.py`** (21 tests): Tkinter UI components, user interactions
- **`tests/test_main.py`** (18 tests): Application integration, workflow testing
- **`tests/test_constants.py`** (12 tests): Configuration validation
- **`tests/test_logger.py`** (8 tests): Logging functionality
- **`tests/test_init.py`** (23 tests): Initialization and setup
#### Test Fixtures (`tests/conftest.py`)
- **Temporary Files**: Safe testing without affecting real data
- **Sample Data**: Comprehensive test datasets with realistic dose information
- **Mock Loggers**: Isolated logging for testing
- **Environment Mocking**: Controlled test environments
### Running Tests
#### Basic Testing
```bash
# Run all tests
make test
# or
uv run pytest
# Run specific test file
uv run pytest tests/test_graph_manager.py -v
# Run tests with specific pattern
uv run pytest -k "dose_calculation" -v
```
#### Coverage Testing
```bash
# Generate coverage report
uv run pytest --cov=src --cov-report=html
# Coverage with specific module
uv run pytest tests/test_graph_manager.py --cov=src.graph_manager --cov-report=term-missing
```
#### Continuous Testing
```bash
# Watch for changes and re-run tests
uv run pytest --watch
# Quick test runner script
./scripts/run_tests.py
```
### Pre-commit Testing
Automated testing prevents commits when core functionality is broken.
#### Configuration
Located in `.pre-commit-config.yaml`:
- **Core Tests**: 3 essential tests run before each commit
- **Fast Execution**: Only critical functionality tested
- **Commit Blocking**: Prevents commits when tests fail
#### Core Tests
1. **`test_init`**: DataManager initialization
2. **`test_initialize_csv_creates_file_with_headers`**: CSV file creation
3. **`test_load_data_with_valid_data`**: Data loading functionality
#### Usage
```bash
# Automatic on commit
git commit -m "Your changes"
# Manual pre-commit check
pre-commit run --all-files
# Run just test check
pre-commit run pytest-check --all-files
```
### Dose Calculation Testing
Comprehensive testing for the complex dose parsing and calculation system.
#### Test Categories
- **Standard Format**: `2025-07-28 18:59:45:150mg` → 150.0mg
- **Multiple Doses**: `2025-07-28 18:59:45:150mg|2025-07-28 19:34:19:75mg` → 225.0mg
- **With Symbols**: `• • • • 2025-07-30 07:50:00:300` → 300.0mg
- **Decimal Values**: `2025-07-28 18:59:45:12.5mg|2025-07-28 19:34:19:7.5mg` → 20.0mg
- **No Timestamps**: `100mg|50mg` → 150.0mg
- **Mixed Formats**: `• 2025-07-30 22:50:00:10|75mg` → 85.0mg
- **Edge Cases**: Empty strings, NaN values, malformed data → 0.0mg
#### Test Implementation
```python
# Example test case
def test_calculate_daily_dose_standard_format(self, graph_manager):
dose_str = "2025-07-28 18:59:45:150mg|2025-07-28 19:34:19:75mg"
result = graph_manager._calculate_daily_dose(dose_str)
assert result == 225.0
```
### Medicine Plotting Tests
Testing for the enhanced graph functionality with medicine dose visualization.
#### Test Areas
- **Toggle Functionality**: Medicine show/hide controls
- **Dose Plotting**: Bar chart generation for medicine doses
- **Color Coding**: Proper color assignment and consistency
- **Legend Enhancement**: Multi-column layout and average calculations
- **Data Integration**: Proper data flow from CSV to visualization
### UI Testing Strategy
Testing user interface components with mock frameworks to avoid GUI dependencies.
#### UI Test Coverage
- **Component Creation**: Widget creation and configuration
- **Event Handling**: User interactions and callbacks
- **Data Binding**: Variable synchronization and updates
- **Layout Management**: Grid and frame arrangements
- **Error Handling**: User input validation and error messages
#### Mocking Strategy
```python
# Example UI test with mocking
@patch('tkinter.Tk')
def test_create_input_frame(self, mock_tk, ui_manager):
parent = Mock()
result = ui_manager.create_input_frame(parent, {}, {})
assert result is not None
assert isinstance(result, dict)
```
## Code Quality
### Tools and Standards
- **ruff**: Fast Python linter and formatter (Rust-based)
- **pre-commit**: Git hook management for code quality
- **Type Hints**: Comprehensive type annotations
- **Docstrings**: Detailed function and class documentation
### Code Formatting
```bash
# Format code
make format
# or
uv run ruff format .
# Check formatting
make lint
# or
uv run ruff check .
```
### Pre-commit Hooks
Automatically installed hooks ensure code quality:
- **Code Formatting**: ruff formatting
- **Linting Checks**: Code quality validation
- **Import Sorting**: Consistent import organization
- **Basic File Checks**: Trailing whitespace, file endings
## Development Workflow
### Feature Development
1. **Create Feature Branch**: `git checkout -b feature/new-feature`
2. **Implement Changes**: Follow existing patterns and architecture
3. **Add Tests**: Ensure new functionality is tested
4. **Run Tests**: `make test` to verify functionality
5. **Code Quality**: `make format && make lint`
6. **Commit Changes**: Pre-commit hooks run automatically
7. **Create Pull Request**: For code review
### Medicine System Development
Adding new medicines or modifying the medicine system:
```python
# Example: Adding a new medicine programmatically
from medicine_manager import MedicineManager, Medicine
medicine_manager = MedicineManager()
new_medicine = Medicine(
key="sertraline",
display_name="Sertraline",
dosage_info="50mg",
quick_doses=["25", "50", "100"],
color="#9B59B6",
default_enabled=False
)
medicine_manager.add_medicine(new_medicine)
```
### Testing New Features
1. **Unit Tests**: Add tests for new functionality
2. **Integration Tests**: Test feature integration with existing system
3. **UI Tests**: Test user interface changes
4. **Dose Calculation Tests**: If affecting dose calculations
5. **Regression Tests**: Ensure existing functionality still works
## Debugging and Troubleshooting
### Logging
Application logs are stored in `logs/` directory:
- **`app.log`**: General application logs
- **`app.error.log`**: Error messages only
- **`app.warning.log`**: Warning messages only
### Debug Mode
Enable debug logging by modifying `src/logger.py` configuration.
### Common Issues
#### Test Failures
- **Matplotlib Mocking**: Ensure proper matplotlib component mocking
- **Tkinter Dependencies**: Use headless testing for UI components
- **File Path Issues**: Use absolute paths in tests
- **Mock Configuration**: Proper mock setup for external dependencies
#### Development Environment
- **Python Version**: Ensure Python 3.13+ is used
- **Virtual Environment**: Always work within the virtual environment
- **Dependencies**: Keep dependencies up to date with `uv sync --upgrade`
### Performance Testing
- **Dose Calculation Performance**: Test with large datasets
- **UI Responsiveness**: Test with extensive medicine lists
- **Memory Usage**: Monitor memory consumption with large CSV files
- **Graph Rendering**: Test graph performance with large datasets
## Architecture Documentation
### Core Components
- **MedTrackerApp**: Main application class
- **MedicineManager**: Medicine CRUD operations
- **PathologyManager**: Pathology/symptom management
- **GraphManager**: Visualization and plotting
- **UIManager**: User interface creation
- **DataManager**: Data persistence and CSV operations
### Data Flow
1. **User Input** → UIManager → DataManager → CSV
2. **Data Loading** → DataManager → pandas DataFrame → GraphManager
3. **Visualization** → GraphManager → matplotlib → UI Display
### Extension Points
- **Medicine System**: Add new medicine properties
- **Graph Types**: Add new visualization types
- **Export Formats**: Add new data export options
- **UI Components**: Add new interface elements
## Deployment Testing
### Standalone Executable
```bash
# Build executable
make deploy
# Test deployment
./dist/thechart
```
### Docker Testing
```bash
# Build container
make build
# Test container
make start
make attach
```
### Cross-platform Testing
- **Linux**: Primary development and testing platform
- **macOS**: Planned support (testing needed)
- **Windows**: Planned support (testing needed)
---
For user documentation, see [README.md](../README.md).
For feature details, see [docs/FEATURES.md](FEATURES.md).
+215
View File
@@ -0,0 +1,215 @@
# TheChart Export System Documentation
## Overview
The TheChart application now includes a comprehensive data export system that allows users to export their medication tracking data and visualizations to multiple formats:
- **JSON** - Structured data format with metadata
- **XML** - Hierarchical data format
- **PDF** - Formatted report with optional graph visualization
## Features
### Export Formats
#### JSON Export
- Exports all CSV data to structured JSON format
- Includes metadata about the export (date, total entries, date range)
- Lists all pathologies and medicines being tracked
- Data is exported as an array of entry objects
#### XML Export
- Exports data to hierarchical XML format
- Includes comprehensive metadata section
- All entries are properly structured with XML tags
- Column names are sanitized for valid XML element names
#### PDF Export
- Creates a formatted report document
- Includes export metadata and summary information
- Optional graph visualization inclusion
- Data table with all entries
- Proper pagination and styling
- Notes are truncated for better table formatting
### User Interface
The export functionality is accessible through:
1. **File Menu** - "Export Data..." option in the main menu bar
2. **Export Window** - Modal dialog with export options
3. **Format Selection** - Radio buttons for JSON, XML, or PDF
4. **Graph Option** - Checkbox to include graph in PDF exports
5. **File Dialog** - Standard save dialog for choosing export location
### Export Manager Architecture
The export system consists of three main components:
#### ExportManager Class (`src/export_manager.py`)
- Core export functionality
- Handles data transformation and file generation
- Integrates with existing data and graph managers
- Supports all three export formats
#### ExportWindow Class (`src/export_window.py`)
- GUI interface for export operations
- Modal dialog with export options
- File save dialog integration
- Progress feedback and error handling
#### Integration in MedTrackerApp (`src/main.py`)
- Export manager initialization
- Menu integration
- Seamless integration with existing managers
## Technical Implementation
### Dependencies Added
- `reportlab` - PDF generation library
- `lxml` - XML processing (added for future enhancements)
- `charset-normalizer` - Character encoding support
### Data Flow
1. User selects export format and options
2. ExportManager loads data from DataManager
3. Data is transformed according to selected format
4. Graph image is optionally generated for PDF
5. Output file is created and saved
6. User receives success/failure feedback
### Error Handling
- Graceful handling of missing data
- File system error management
- User-friendly error messages
- Logging of export operations
## Usage Examples
### Basic Export Process
1. Open TheChart application
2. Go to File → Export Data...
3. Select desired format (JSON/XML/PDF)
4. For PDF: choose whether to include graph
5. Click "Export..." button
6. Choose save location and filename
7. Confirm successful export
### Export File Examples
#### JSON Structure
```json
{
"metadata": {
"export_date": "2025-08-02T09:03:22.580489",
"total_entries": 32,
"date_range": {
"start": "07/02/2025",
"end": "08/02/2025"
},
"pathologies": ["depression", "anxiety", "sleep", "appetite"],
"medicines": ["bupropion", "hydroxyzine", "gabapentin", "propranolol", "quetiapine"]
},
"entries": [
{
"date": "07/02/2025",
"depression": 8,
"anxiety": 5,
"sleep": 3,
"appetite": 1,
"bupropion": 0,
"bupropion_doses": "",
"note": "Starting medication tracking"
}
]
}
```
#### XML Structure
```xml
<?xml version="1.0" encoding="UTF-8"?>
<thechart_data>
<metadata>
<export_date>2025-08-02T09:03:22.613013</export_date>
<total_entries>32</total_entries>
<date_range>
<start>07/02/2025</start>
<end>08/02/2025</end>
</date_range>
</metadata>
<entries>
<entry>
<date>07/02/2025</date>
<depression>8</depression>
<anxiety>5</anxiety>
<note>Starting medication tracking</note>
</entry>
</entries>
</thechart_data>
```
## Testing
### Automated Tests
- Export functionality is tested through `simple_export_test.py`
- Creates sample exports in all three formats
- Validates file creation and basic content structure
### Manual Testing
- GUI testing available through `test_export_gui.py`
- Opens export window for interactive testing
- Allows testing of all user interface components
### Test Files Location
Exported test files are created in the `test_exports/` directory:
- `export.json` - JSON format export
- `export.xml` - XML format export
- `export.csv` - CSV format copy
- `test_export.pdf` - PDF format with graph
## File Locations
### Source Files
- `src/export_manager.py` - Core export functionality
- `src/export_window.py` - GUI export interface
### Test Files
- `simple_export_test.py` - Basic export functionality test
- `test_export_gui.py` - GUI testing interface
- `scripts/test_export_functionality.py` - Comprehensive export tests
### Dependencies
- Added to `requirements.txt` and managed by `uv`
- PDF generation requires `reportlab`
- XML processing enhanced with `lxml`
## Future Enhancements
Potential improvements for the export system:
1. **Additional Formats** - Excel, CSV with formatting
2. **Export Filtering** - Date range selection, specific pathologies/medicines
3. **Batch Exports** - Multiple formats at once
4. **Email Integration** - Direct email export
5. **Cloud Storage** - Export to cloud services
6. **Export Scheduling** - Automated periodic exports
7. **Advanced PDF Styling** - Charts, graphs, custom layouts
## Troubleshooting
### Common Issues
1. **No Data to Export** - Ensure CSV file has entries before exporting
2. **PDF Generation Fails** - Check ReportLab installation and permissions
3. **File Save Errors** - Verify write permissions to selected directory
4. **Large File Exports** - PDF exports may take longer for large datasets
### Debugging
- Check application logs for detailed error messages
- Export operations are logged with DEBUG level information
- File system errors are captured and reported to user
## Integration Notes
The export system integrates seamlessly with existing TheChart functionality:
- Uses same data validation and loading mechanisms
- Respects existing pathology and medicine configurations
- Maintains data integrity and formatting consistency
- Follows existing logging and error handling patterns
+263
View File
@@ -0,0 +1,263 @@
# TheChart - Features Documentation
## Overview
TheChart is a comprehensive medication tracking application that allows users to monitor medication intake, symptom tracking, and visualize treatment progress over time.
## Core Features
### 🏥 Modular Medicine System
TheChart features a dynamic medicine management system that allows complete customization without code modifications.
#### Features:
- **Dynamic Medicine Management**: Add, edit, and remove medicines through the UI
- **Configurable Properties**: Each medicine has customizable display names, dosages, colors, and quick-dose options
- **Automatic UI Updates**: All interface elements update automatically when medicines change
- **JSON Configuration**: Human-readable `medicines.json` file for easy management
#### Medicine Configuration:
Each medicine includes:
- **Key**: Internal identifier (e.g., "bupropion")
- **Display Name**: User-friendly name (e.g., "Bupropion")
- **Dosage Info**: Dosage information (e.g., "150/300 mg")
- **Quick Doses**: Common dose amounts for quick selection
- **Color**: Hex color for graph display (e.g., "#FF6B6B")
- **Default Enabled**: Whether to show in graphs by default
#### Default Medicines:
| Medicine | Dosage | Default Graph | Color |
|----------|--------|---------------|--------|
| Bupropion | 150/300 mg | ✅ | Red (#FF6B6B) |
| Hydroxyzine | 25 mg | ❌ | Teal (#4ECDC4) |
| Gabapentin | 100 mg | ❌ | Blue (#45B7D1) |
| Propranolol | 10 mg | ✅ | Green (#96CEB4) |
| Quetiapine | 25 mg | ❌ | Yellow (#FFEAA7) |
#### Usage:
1. **Through UI**: Go to `Tools``Manage Medicines...`
2. **Manual Configuration**: Edit `medicines.json` directly
3. **Programmatically**: Use the MedicineManager API
### 💊 Advanced Dose Tracking
Comprehensive dose tracking system that records exact timestamps and dosages throughout the day.
#### Core Capabilities:
- **Timestamp Recording**: Exact time when medicine is taken
- **Dose Amount Tracking**: Record specific doses (150mg, 10mg, etc.)
- **Multiple Doses Per Day**: Take the same medicine multiple times
- **Real-time Display**: See today's doses immediately
- **Data Persistence**: All doses saved to CSV with full history
#### Dose Management Interface:
Located in the edit window (double-click any entry):
- **Individual Dose Entry Fields**: For each medicine
- **"Take [Medicine]" Buttons**: Immediate dose recording with timestamps
- **Editable Dose Display Areas**: View and modify existing doses
- **Quick Dose Buttons**: Pre-configured common dose amounts
- **Format Consistency**: All doses displayed in HH:MM: dose format
#### Data Format:
- **Timestamp Format**: `YYYY-MM-DD HH:MM:SS`
- **Dose Separator**: `|` (pipe) for multiple doses
- **Dose Format**: `timestamp:dose`
- **CSV Storage**: Additional columns in existing CSV file
#### Example CSV Format:
```csv
date,depression,anxiety,sleep,appetite,bupropion,bupropion_doses,hydroxyzine,hydroxyzine_doses,propranolol,propranolol_doses,note
07/28/2025,4,5,3,3,1,"2025-07-28 14:30:00:150mg|2025-07-28 18:30:00:150mg",0,"",1,"2025-07-28 12:30:00:10mg","Multiple doses today"
```
### 📊 Enhanced Graph Visualization
Advanced graphing system with comprehensive data visualization and interactive controls.
#### Medicine Dose Visualization:
- **Colored Bar Charts**: Each medicine has distinct colors
- **Daily Dose Totals**: Automatically calculated from individual doses
- **Scaled Display**: Doses scaled by 1/10 for better visibility (labeled as "mg/10")
- **Dynamic Positioning**: Bars positioned below main chart area
- **Semi-transparent Bars**: Alpha=0.6 to avoid overwhelming symptom data
#### Interactive Controls:
- **Toggle Buttons**: Independent show/hide for each medicine and symptom
- **Organized Sections**: "Symptoms" and "Medicines" sections
- **Real-time Updates**: Changes take effect immediately
#### Enhanced Legend:
- **Multi-column Layout**: Efficient use of graph space (2 columns)
- **Average Dosage Display**: Shows average dose for each medicine
- **Color Coding**: Consistent color scheme matching graph elements
- **Professional Styling**: Frame, shadow, and transparency effects
- **Tracking Status**: Shows medicines being monitored but without current dose data
#### Dose Calculation Features:
- **Multiple Format Support**: Handles various dose string formats
- **Robust Parsing**: Handles timestamps, symbols (•), and mixed formats
- **Edge Case Handling**: Manages empty strings, NaN values, malformed data
- **Daily Totals**: Sums all individual doses for comprehensive daily tracking
### 🏥 Pathology Management
Comprehensive symptom tracking with configurable pathologies.
#### Features:
- **Dynamic Pathology System**: Similar to medicine management
- **Configurable Symptoms**: Add, edit, and remove symptom categories
- **Scale-based Rating**: 0-10 rating system for symptom severity
- **Historical Tracking**: Full symptom history with trend analysis
### 📝 Data Management
Robust data handling with comprehensive backup and migration support.
#### Data Features:
- **CSV-based Storage**: Human-readable and portable data format
- **Automatic Backups**: Created before major migrations
- **Backward Compatibility**: Existing data continues to work with updates
- **Dynamic Column Management**: Automatically adapts to new medicines/pathologies
- **Data Validation**: Ensures data integrity and handles edge cases
#### Migration Support:
- **Automatic Migration**: Data structure updates handled automatically
- **Backup Creation**: `thechart_data.csv.backup_YYYYMMDD_HHMMSS` format
- **No Data Loss**: All existing functionality and data preserved
- **Version Compatibility**: Seamless updates across application versions
### 🧪 Comprehensive Testing Framework
Professional testing infrastructure with high code coverage.
#### Testing Statistics:
- **93% Overall Code Coverage** (482 total statements, 33 missed)
- **112 Total Tests** across 6 test modules
- **80 Tests Passing** (71.4% pass rate)
- **Pre-commit Testing**: Core functionality tests run before each commit
#### Test Coverage by Module:
- **100% Coverage**: constants.py, logger.py
- **97% Coverage**: graph_manager.py
- **95% Coverage**: init.py
- **93% Coverage**: ui_manager.py
- **91% Coverage**: main.py
- **87% Coverage**: data_manager.py
#### Testing Tools:
- **pytest**: Modern Python testing framework
- **pytest-cov**: Coverage reporting with HTML, XML, and terminal output
- **pytest-mock**: Mocking support for isolated testing
- **pre-commit hooks**: Automated testing before commits
## User Interface Features
### 🖥️ Intuitive Design
- **Clean Main Interface**: Simplified new entry form focused on essential inputs
- **Organized Edit Windows**: Comprehensive dose management in dedicated edit interface
- **Scrollable Interface**: Vertical scrollbar for expanded UI components
- **Responsive Design**: Interface adapts to window size and content
- **Visual Feedback**: Success messages and clear status indicators
### 🎯 User Experience Improvements
- **Centralized Dose Management**: All dose operations consolidated in edit windows
- **Quick Entry Options**: Pre-configured dose buttons for common amounts
- **Format Guidance**: Clear instructions and format examples
- **Real-time Updates**: Immediate feedback and data updates
- **Error Handling**: Comprehensive error messages and recovery options
### ⌨️ Keyboard Shortcuts
Comprehensive keyboard shortcuts for efficient navigation and data entry.
#### File Operations:
- **Ctrl+S**: Save/Add new entry - Quickly save current entry data
- **Ctrl+Q**: Quit application - Exit with confirmation dialog
- **Ctrl+E**: Export data - Open export dialog window
#### Data Management:
- **Ctrl+N**: Clear entries - Clear all input fields for new entry
- **Ctrl+R / F5**: Refresh data - Reload data from CSV and update displays
#### Window Management:
- **Ctrl+M**: Manage medicines - Open medicine management window
- **Ctrl+P**: Manage pathologies - Open pathology management window
#### Table Operations:
- **Delete**: Delete selected entry - Remove selected table entry with confirmation
- **Escape**: Clear selection - Clear current table selection
- **Double-click**: Edit entry - Open edit dialog for selected entry
#### Help System:
- **F1**: Show keyboard shortcuts - Display help dialog with all shortcuts
#### Integration Features:
- **Menu Display**: All shortcuts shown in menu bar next to items
- **Button Labels**: Primary buttons show their keyboard shortcuts
- **Case Insensitive**: Both Ctrl+S and Ctrl+Shift+S work
- **Focus Management**: Shortcuts work when main window has focus
- **Status Feedback**: All operations provide status bar feedback
## Technical Architecture
### 🏗️ Modular Design
- **MedicineManager**: Core medicine CRUD operations
- **PathologyManager**: Symptom and pathology management
- **GraphManager**: All graph-related operations and visualizations
- **UIManager**: User interface creation and management
- **DataManager**: CSV operations and data persistence
### 🔧 Configuration Management
- **JSON-based Configuration**: `medicines.json` and `pathologies.json`
- **Dynamic Loading**: Runtime configuration updates
- **Validation**: Input validation and error handling
- **Backward Compatibility**: Seamless updates and migrations
### 📈 Data Processing
- **Pandas Integration**: Efficient data manipulation and analysis
- **Matplotlib Visualization**: Professional graph rendering
- **Robust Parsing**: Handles various data formats and edge cases
- **Real-time Calculations**: Dynamic dose totals and averages
## Deployment and Distribution
### 📦 Standalone Executable
- **PyInstaller Integration**: Creates self-contained executables
- **Cross-platform Support**: Linux deployment with desktop integration
- **Automatic Installation**: Installs to `~/Applications/` with desktop entry
- **Data Migration**: Copies data files to appropriate user directories
### 🐳 Docker Support
- **Multi-platform Images**: Docker container support
- **Docker Compose**: Easy container management
- **Development Environment**: Consistent development setup across platforms
### 🔄 Package Management
- **UV Integration**: Fast Python package management with Rust performance
- **Virtual Environment**: Isolated dependency management
- **Lock Files**: Reproducible builds with `uv.lock`
- **Development Dependencies**: Separate dev dependencies for clean production builds
## Integration Features
### 🔄 Import/Export
- **CSV Import**: Import existing medication data
- **Data Export**: Export data for backup or analysis
- **Format Compatibility**: Standard CSV format for portability
### 🔌 API Integration
- **Extensible Architecture**: Plugin system for future enhancements
- **Medicine API**: Programmatic medicine management
- **Data API**: Direct data access and manipulation
## Future Enhancements
### 🚀 Planned Features
- **Mobile Companion App**: Mobile dose tracking and reminders
- **Cloud Synchronization**: Multi-device data synchronization
- **Advanced Analytics**: Machine learning-based trend analysis
- **Reminder System**: Intelligent dose reminders and scheduling
- **Doctor Integration**: Export reports for healthcare providers
### 🎯 Development Roadmap
- **macOS/Windows Support**: Extended platform support
- **Plugin Architecture**: Third-party extension support
- **API Development**: RESTful API for external integrations
- **Advanced Visualizations**: Additional chart types and analysis tools
---
For detailed usage instructions, see the main [README.md](../README.md).
For development information, see [DEVELOPMENT.md](DEVELOPMENT.md).
+71
View File
@@ -0,0 +1,71 @@
# Keyboard Shortcuts
TheChart application supports comprehensive keyboard shortcuts for improved productivity and efficient navigation.
## File Operations
- **Ctrl+S**: Save/Add new entry - Saves the current entry data to the database
- **Ctrl+Q**: Quit application - Exits the application (with confirmation dialog)
- **Ctrl+E**: Export data - Opens the export dialog window
## Data Management
- **Ctrl+N**: Clear entries - Clears all input fields to start a new entry
- **Ctrl+R** or **F5**: Refresh data - Reloads data from the CSV file and updates the display
## Window Management
- **Ctrl+M**: Manage medicines - Opens the medicine management window
- **Ctrl+P**: Manage pathologies - Opens the pathology management window
## Table Operations
- **Delete**: Delete selected entry - Deletes the currently selected entry in the table (with confirmation)
- **Escape**: Clear selection - Clears the current selection in the table
- **Double-click**: Edit entry - Opens the edit dialog for the selected entry
## Help
- **F1**: Show keyboard shortcuts help - Displays a dialog with all available keyboard shortcuts
## Implementation Details
### Menu Integration
All keyboard shortcuts are displayed in the menu bar next to their corresponding menu items for easy reference.
### Button Labels
Primary action buttons show their keyboard shortcuts in the button text (e.g., "Add Entry (Ctrl+S)").
### Case Sensitivity
- Shortcuts are case-insensitive
- Both `Ctrl+S` and `Ctrl+Shift+S` work
- Uppercase and lowercase variants are supported
### Focus Requirements
- Keyboard shortcuts work when the main window has focus
- Focus is automatically set to the main window on startup
- Shortcuts work across all tabs and interface elements
### Feedback System
- All operations provide feedback through the status bar
- Success and error messages are displayed
- Confirmation dialogs are shown for destructive operations (quit, delete)
## Usage Tips
### Quick Workflow
1. **Ctrl+N** - Clear fields for new entry
2. Enter data in the form
3. **Ctrl+S** - Save the entry
4. **F5** - Refresh to see updated data
### Navigation
- Use **Ctrl+M** and **Ctrl+P** to quickly access management windows
- Use **Delete** to remove unwanted entries from the table
- Use **Escape** to clear selections when needed
### Getting Help
- Press **F1** anytime to see the keyboard shortcuts help dialog
- All shortcuts are also visible in the menu bar
- Button tooltips show additional keyboard shortcut information
## Accessibility
- Keyboard shortcuts provide full application functionality without mouse use
- All critical operations have keyboard equivalents
- Shortcuts follow standard application conventions (Ctrl+S for save, Ctrl+Q for quit)
- Help system is easily accessible via F1
+81
View File
@@ -0,0 +1,81 @@
# TheChart Documentation
Welcome to TheChart documentation! This guide will help you navigate the available documentation.
## 📖 Documentation Index
### For Users
- **[README.md](../README.md)** - Quick start guide and installation
- **[Features Guide](FEATURES.md)** - Complete feature documentation
- Modular Medicine System
- Advanced Dose Tracking
- Graph Visualizations
- Data Management
- Keyboard Shortcuts
- **[Keyboard Shortcuts](KEYBOARD_SHORTCUTS.md)** - Comprehensive shortcut reference
- File operations shortcuts
- Data management shortcuts
- Navigation shortcuts
### For Developers
- **[Development Guide](DEVELOPMENT.md)** - Development setup and testing
- Testing Framework (93% coverage)
- Code Quality Tools
- Architecture Overview
- Debugging Guide
### Project History
- **[Changelog](CHANGELOG.md)** - Version history and feature evolution
- Recent updates and improvements
- Migration notes
- Future roadmap
## 🚀 Quick Navigation
### Getting Started
1. **Installation**: See [README.md - Installation](../README.md#installation)
2. **First Run**: See [README.md - Running the Application](../README.md#running-the-application)
3. **Key Features**: See [FEATURES.md](FEATURES.md)
### Development
1. **Setup**: See [DEVELOPMENT.md - Development Environment Setup](DEVELOPMENT.md#development-environment-setup)
2. **Testing**: See [DEVELOPMENT.md - Testing Framework](DEVELOPMENT.md#testing-framework)
3. **Contributing**: See [DEVELOPMENT.md - Development Workflow](DEVELOPMENT.md#development-workflow)
### Advanced Usage
1. **Medicine Management**: See [FEATURES.md - Modular Medicine System](FEATURES.md#-modular-medicine-system)
2. **Dose Tracking**: See [FEATURES.md - Advanced Dose Tracking](FEATURES.md#-advanced-dose-tracking)
3. **Visualizations**: See [FEATURES.md - Enhanced Graph Visualization](FEATURES.md#-enhanced-graph-visualization)
## 📋 Documentation Standards
All documentation follows these principles:
- **Clear Structure**: Hierarchical organization with clear headings
- **Practical Examples**: Code snippets and usage examples
- **Up-to-date**: Synchronized with current codebase
- **Comprehensive**: Covers all major features and workflows
- **Cross-referenced**: Links between related sections
## 🔍 Finding Information
### By Topic
- **Installation & Setup** → [README.md](../README.md)
- **Feature Usage** → [FEATURES.md](FEATURES.md)
- **Development** → [DEVELOPMENT.md](DEVELOPMENT.md)
- **Version History** → [CHANGELOG.md](CHANGELOG.md)
### By User Type
- **End Users** → Start with [README.md](../README.md), then [FEATURES.md](FEATURES.md)
- **Developers** → [DEVELOPMENT.md](DEVELOPMENT.md) and [CHANGELOG.md](CHANGELOG.md)
- **Contributors** → All documentation, especially [DEVELOPMENT.md](DEVELOPMENT.md)
### By Task
- **Install TheChart** → [README.md - Installation](../README.md#installation)
- **Add New Medicine** → [FEATURES.md - Modular Medicine System](FEATURES.md#-modular-medicine-system)
- **Track Doses** → [FEATURES.md - Advanced Dose Tracking](FEATURES.md#-advanced-dose-tracking)
- **Run Tests** → [DEVELOPMENT.md - Testing Framework](DEVELOPMENT.md#testing-framework)
- **Deploy Application** → [README.md - Deployment](../README.md#deployment)
---
**Need help?** Check the troubleshooting sections in [README.md](../README.md#troubleshooting) and [DEVELOPMENT.md](DEVELOPMENT.md#debugging-and-troubleshooting).
+3 -1
View File
@@ -1,14 +1,16 @@
[project] [project]
name = "thechart" name = "thechart"
version = "1.3.4" version = "1.9.5"
description = "Chart to monitor your medication intake over time." description = "Chart to monitor your medication intake over time."
readme = "README.md" readme = "README.md"
requires-python = ">=3.13" requires-python = ">=3.13"
dependencies = [ dependencies = [
"colorlog>=6.9.0", "colorlog>=6.9.0",
"dotenv>=0.9.9", "dotenv>=0.9.9",
"lxml>=6.0.0",
"matplotlib>=3.10.3", "matplotlib>=3.10.3",
"pandas>=2.3.1", "pandas>=2.3.1",
"reportlab>=4.4.3",
"tk>=0.1.0", "tk>=0.1.0",
] ]
+61
View File
@@ -0,0 +1,61 @@
# TheChart Scripts Directory
This directory contains testing and utility scripts for TheChart application.
## Scripts Overview
### Testing Scripts
#### `run_tests.py`
Main test runner for the application.
```bash
cd /home/will/Code/thechart
.venv/bin/python scripts/run_tests.py
```
#### `integration_test.py`
Comprehensive integration test for the export system.
- Tests all export formats (JSON, XML, PDF)
- Validates data integrity and file creation
- No GUI dependencies - safe for automated testing
```bash
cd /home/will/Code/thechart
.venv/bin/python scripts/integration_test.py
```
### Feature Testing Scripts
#### `test_note_saving.py`
Tests note saving and retrieval functionality.
- Validates note persistence in CSV files
- Tests special characters and formatting
#### `test_update_entry.py`
Tests entry update functionality.
- Validates data modification operations
- Tests date validation and duplicate handling
## Usage
All scripts should be run from the project root directory:
```bash
cd /home/will/Code/thechart
.venv/bin/python scripts/<script_name>.py
```
## Test Data
- Integration tests create temporary export files in `integration_test_exports/` (auto-cleaned)
- Test scripts use the main `thechart_data.csv` file unless specified otherwise
- No test data is committed to the repository
## Development
When adding new scripts:
1. Place them in this directory
2. Use the standard shebang: `#!/usr/bin/env python3`
3. Add proper docstrings and error handling
4. Update this README with script documentation
5. Follow the project's linting and formatting standards
+128
View File
@@ -0,0 +1,128 @@
#!/usr/bin/env python3
"""
Integration test for TheChart export system
Tests the complete export workflow without GUI dependencies
"""
import sys
from pathlib import Path
# Add src to path
sys.path.insert(0, "src")
from data_manager import DataManager
from export_manager import ExportManager
from init import logger
from medicine_manager import MedicineManager
from pathology_manager import PathologyManager
class MockGraphManager:
"""Mock graph manager for testing."""
def __init__(self):
self.fig = None
def test_integration():
"""Test complete export system integration."""
print("TheChart Export System Integration Test")
print("=" * 45)
# 1. Initialize all managers
print("\n1. Initializing managers...")
try:
medicine_manager = MedicineManager(logger=logger)
pathology_manager = PathologyManager(logger=logger)
data_manager = DataManager(
"thechart_data.csv", logger, medicine_manager, pathology_manager
)
# Mock graph manager (no GUI dependencies)
graph_manager = MockGraphManager()
export_manager = ExportManager(
data_manager, graph_manager, medicine_manager, pathology_manager, logger
)
print(" ✓ All managers initialized successfully")
except Exception as e:
print(f" ✗ Manager initialization failed: {e}")
return False
# 2. Check data availability
print("\n2. Checking data availability...")
try:
export_info = export_manager.get_export_info()
print(f" Total entries: {export_info['total_entries']}")
print(f" Has data: {export_info['has_data']}")
if not export_info["has_data"]:
print(" ✗ No data available for export")
return False
print(
f" Date range: {export_info['date_range']['start']} "
f"to {export_info['date_range']['end']}"
)
print(f" Pathologies: {len(export_info['pathologies'])}")
print(f" Medicines: {len(export_info['medicines'])}")
print(" ✓ Data is available for export")
except Exception as e:
print(f" ✗ Data check failed: {e}")
return False
# 3. Test all export formats
export_dir = Path("integration_test_exports")
export_dir.mkdir(exist_ok=True)
formats_to_test = [
("JSON", "integration_test.json", export_manager.export_data_to_json),
("XML", "integration_test.xml", export_manager.export_data_to_xml),
(
"PDF",
"integration_test.pdf",
lambda path: export_manager.export_to_pdf(path, include_graph=False),
),
]
results = []
for format_name, filename, export_func in formats_to_test:
print(f"\n3.{len(results) + 1}. Testing {format_name} export...")
try:
file_path = export_dir / filename
success = export_func(str(file_path))
if success and file_path.exists():
file_size = file_path.stat().st_size
print(
f"{format_name} export successful: {filename} "
f"({file_size} bytes)"
)
results.append(True)
else:
print(f"{format_name} export failed")
results.append(False)
except Exception as e:
print(f"{format_name} export error: {e}")
results.append(False)
# 4. Summary
print("\n4. Test Summary")
print(f" Total tests: {len(results)}")
print(f" Passed: {sum(results)}")
print(f" Failed: {len(results) - sum(results)}")
if all(results):
print(" ✓ All export formats working correctly!")
print(f" Check '{export_dir}' directory for exported files.")
return True
else:
print(" ✗ Some export formats failed")
return False
if __name__ == "__main__":
success = test_integration()
sys.exit(0 if success else 1)
+93
View File
@@ -0,0 +1,93 @@
#!/usr/bin/env python3
"""
Test script for keyboard shortcuts functionality.
This script tests that the keyboard shortcuts are properly bound.
"""
import os
import sys
import tkinter as tk
# Add the src directory to the path so we can import the main module
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
from main import MedTrackerApp
def test_keyboard_shortcuts():
"""Test that keyboard shortcuts are properly bound."""
print("Testing keyboard shortcuts...")
# Create a test window
root = tk.Tk()
root.withdraw() # Hide the window for testing
try:
# Create the app instance
app = MedTrackerApp(root)
# Test that the shortcuts are bound
expected_shortcuts = [
"<Control-s>",
"<Control-S>",
"<Control-q>",
"<Control-Q>",
"<Control-e>",
"<Control-E>",
"<Control-n>",
"<Control-N>",
"<Control-r>",
"<Control-R>",
"<F5>",
"<Control-m>",
"<Control-M>",
"<Control-p>",
"<Control-P>",
"<Delete>",
"<Escape>",
"<F1>",
]
# Check if shortcuts are bound
bound_shortcuts = []
for shortcut in expected_shortcuts:
if root.bind(shortcut):
bound_shortcuts.append(shortcut)
print(f"Successfully bound {len(bound_shortcuts)} keyboard shortcuts:")
for shortcut in bound_shortcuts:
print(f"{shortcut}")
# Test that methods exist
methods_to_test = [
"add_new_entry",
"handle_window_closing",
"_open_export_window",
"_clear_entries",
"refresh_data_display",
"_open_medicine_manager",
"_open_pathology_manager",
"_delete_selected_entry",
"_clear_selection",
"_show_keyboard_shortcuts",
]
for method_name in methods_to_test:
if hasattr(app, method_name):
print(f" ✓ Method {method_name} exists")
else:
print(f" ✗ Method {method_name} missing")
print("\n✅ Keyboard shortcuts test completed successfully!")
return True
except Exception as e:
print(f"❌ Error during testing: {e}")
return False
finally:
root.destroy()
if __name__ == "__main__":
success = test_keyboard_shortcuts()
sys.exit(0 if success else 1)
+69
View File
@@ -0,0 +1,69 @@
#!/usr/bin/env python3
"""
Test script to verify note field saving functionality
"""
import logging
import os
import sys
import pandas as pd
# Add src directory to path to import modules
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
from data_manager import DataManager
from medicine_manager import MedicineManager
from pathology_manager import PathologyManager
def test_note_saving():
"""Test note saving functionality by checking current data"""
print("Testing note saving functionality...")
# Initialize logger
logger = logging.getLogger("test")
logger.setLevel(logging.INFO)
# Initialize managers
medicine_manager = MedicineManager("medicines.json")
pathology_manager = PathologyManager("pathologies.json")
data_manager = DataManager(
"thechart_data.csv", logger, medicine_manager, pathology_manager
)
# Load current data
df = data_manager.load_data()
if df.empty:
print("No data found in CSV file")
return
print(f"Found {len(df)} entries in the data file")
# Check if we have any entries with notes
entries_with_notes = df[df["note"].notna() & (df["note"] != "")].copy()
print(f"Entries with notes: {len(entries_with_notes)}")
if len(entries_with_notes) > 0:
print("\nEntries with notes:")
for _, row in entries_with_notes.iterrows():
note_preview = (
row["note"][:50] + "..." if len(str(row["note"])) > 50 else row["note"]
)
print(f" Date: {row['date']}, Note: {note_preview}")
# Show the most recent entry
if len(df) > 0:
latest_entry = df.iloc[-1]
print("\nMost recent entry:")
print(f" Date: {latest_entry['date']}")
print(f" Note: '{latest_entry['note']}'")
print(f" Note length: {len(str(latest_entry['note']))}")
is_empty = pd.isna(latest_entry["note"]) or latest_entry["note"] == ""
print(f" Note is empty/null: {is_empty}")
if __name__ == "__main__":
test_note_saving()
+102
View File
@@ -0,0 +1,102 @@
#!/usr/bin/env python3
"""
Test the update_entry functionality with notes
"""
import logging
import os
import sys
# Add src directory to path to import modules
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
from data_manager import DataManager
from medicine_manager import MedicineManager
from pathology_manager import PathologyManager
def test_update_entry_with_note():
"""Test updating an entry with a note"""
print("Testing update_entry functionality with notes...")
# Initialize logger
logger = logging.getLogger("test")
logger.setLevel(logging.DEBUG)
# Add console handler to see debug output
handler = logging.StreamHandler()
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
# Initialize managers
medicine_manager = MedicineManager("medicines.json")
pathology_manager = PathologyManager("pathologies.json")
data_manager = DataManager(
"thechart_data.csv", logger, medicine_manager, pathology_manager
)
# Load current data
df = data_manager.load_data()
if df.empty:
print("No data found in CSV file")
return
print(f"Found {len(df)} entries in the data file")
# Find the most recent entry to test with
latest_entry = df.iloc[-1].copy()
original_date = latest_entry["date"]
print(f"Testing with entry: {original_date}")
print(f"Current note: '{latest_entry['note']}'")
# Create test values - keep everything the same but change the note
test_note = "This is a test note to verify saving functionality!"
# Build values list (same format as the UI would send)
values = [original_date] # date
# Add pathology values
pathology_keys = pathology_manager.get_pathology_keys()
for key in pathology_keys:
values.append(latest_entry.get(key, 0))
# Add medicine values and doses
medicine_keys = medicine_manager.get_medicine_keys()
for key in medicine_keys:
values.append(latest_entry.get(key, 0)) # medicine checkbox
values.append(latest_entry.get(f"{key}_doses", "")) # medicine doses
# Add the test note
values.append(test_note)
print(f"Values to save: {values}")
print(f"Note in values: '{values[-1]}'")
# Test the update
success = data_manager.update_entry(original_date, values)
if success:
print("Update successful!")
# Reload and verify
df_after = data_manager.load_data()
updated_entry = df_after[df_after["date"] == original_date].iloc[0]
print(f"Note after update: '{updated_entry['note']}'")
print(f"Note correctly saved: {updated_entry['note'] == test_note}")
# Reset the note back to original
values[-1] = latest_entry["note"]
data_manager.update_entry(original_date, values)
print("Reverted note back to original")
else:
print("Update failed!")
if __name__ == "__main__":
test_update_entry_with_note()
+161 -55
View File
@@ -9,7 +9,7 @@ from pathology_manager import PathologyManager
class DataManager: class DataManager:
"""Handle all data operations for the application.""" """Handle all data operations for the application with performance optimizations."""
def __init__( def __init__(
self, self,
@@ -22,10 +22,21 @@ class DataManager:
self.logger: logging.Logger = logger self.logger: logging.Logger = logger
self.medicine_manager = medicine_manager self.medicine_manager = medicine_manager
self.pathology_manager = pathology_manager self.pathology_manager = pathology_manager
# Cache for loaded data to avoid repeated file I/O
self._data_cache: pd.DataFrame | None = None
self._cache_timestamp: float = 0
self._headers_cache: tuple[str, ...] | None = None
self._dtype_cache: dict[str, type] | None = None
self._initialize_csv_file() self._initialize_csv_file()
def _get_csv_headers(self) -> list[str]: def _get_csv_headers(self) -> tuple[str, ...]:
"""Get CSV headers based on current pathology and medicine configuration.""" """Get CSV headers based on current pathology and medicine configuration.
Cached to avoid repeated computation."""
if self._headers_cache is not None:
return self._headers_cache
# Start with date # Start with date
headers = ["date"] headers = ["date"]
@@ -37,7 +48,9 @@ class DataManager:
for medicine_key in self.medicine_manager.get_medicine_keys(): for medicine_key in self.medicine_manager.get_medicine_keys():
headers.extend([medicine_key, f"{medicine_key}_doses"]) headers.extend([medicine_key, f"{medicine_key}_doses"])
return headers + ["note"] result = tuple(headers + ["note"])
self._headers_cache = result
return result
def _initialize_csv_file(self) -> None: def _initialize_csv_file(self) -> None:
"""Create CSV file with headers if it doesn't exist or is empty.""" """Create CSV file with headers if it doesn't exist or is empty."""
@@ -46,27 +59,74 @@ class DataManager:
writer = csv.writer(file) writer = csv.writer(file)
writer.writerow(self._get_csv_headers()) writer.writerow(self._get_csv_headers())
def _invalidate_cache(self) -> None:
"""Invalidate the data cache when data changes."""
self._data_cache = None
self._cache_timestamp = 0
def _should_reload_data(self) -> bool:
"""Check if data should be reloaded based on file modification time."""
if self._data_cache is None:
return True
try:
file_mtime = os.path.getmtime(self.filename)
return file_mtime > self._cache_timestamp
except OSError:
return True
def _get_dtype_dict(self) -> dict[str, type]:
"""Get pandas dtype dictionary for efficient reading.
Cached to avoid recreation."""
if self._dtype_cache is not None:
return self._dtype_cache
dtype_dict = {"date": str, "note": str}
# Add pathology types
for pathology_key in self.pathology_manager.get_pathology_keys():
dtype_dict[pathology_key] = int
# Add medicine types
for medicine_key in self.medicine_manager.get_medicine_keys():
dtype_dict[medicine_key] = int
dtype_dict[f"{medicine_key}_doses"] = str
self._dtype_cache = dtype_dict
return dtype_dict
def load_data(self) -> pd.DataFrame: def load_data(self) -> pd.DataFrame:
"""Load data from CSV file.""" """Load data from CSV file with caching for better performance."""
if not os.path.exists(self.filename) or os.path.getsize(self.filename) == 0: if not os.path.exists(self.filename) or os.path.getsize(self.filename) == 0:
self.logger.warning("CSV file is empty or doesn't exist. No data to load.") self.logger.warning("CSV file is empty or doesn't exist. No data to load.")
return pd.DataFrame() return pd.DataFrame()
# Use cached data if available and file hasn't changed
if not self._should_reload_data():
return self._data_cache.copy()
try: try:
# Build dtype dictionary dynamically # Use pre-built dtype dictionary for faster parsing
dtype_dict = {"date": str, "note": str} dtype_dict = self._get_dtype_dict()
# Add pathology types # Read with optimized settings
for pathology_key in self.pathology_manager.get_pathology_keys(): df: pd.DataFrame = pd.read_csv(
dtype_dict[pathology_key] = int self.filename,
dtype=dtype_dict,
na_filter=False, # Don't convert to NaN, keep as empty strings
engine="c", # Use faster C engine
)
# Add medicine types # Sort only if needed (check if already sorted)
for medicine_key in self.medicine_manager.get_medicine_keys(): if len(df) > 1 and not df["date"].is_monotonic_increasing:
dtype_dict[medicine_key] = int df = df.sort_values(by="date").reset_index(drop=True)
dtype_dict[f"{medicine_key}_doses"] = str
# Cache the data and timestamp
self._data_cache = df.copy()
self._cache_timestamp = os.path.getmtime(self.filename)
return df.copy()
df: pd.DataFrame = pd.read_csv(self.filename, dtype=dtype_dict).fillna("")
return df.sort_values(by="date").reset_index(drop=True)
except pd.errors.EmptyDataError: except pd.errors.EmptyDataError:
self.logger.warning("CSV file is empty. No data to load.") self.logger.warning("CSV file is empty. No data to load.")
return pd.DataFrame() return pd.DataFrame()
@@ -75,69 +135,104 @@ class DataManager:
return pd.DataFrame() return pd.DataFrame()
def add_entry(self, entry_data: list[str | int]) -> bool: def add_entry(self, entry_data: list[str | int]) -> bool:
"""Add a new entry to the CSV file.""" """Add a new entry to the CSV file with optimized duplicate checking."""
try: try:
# Check if date already exists # Quick duplicate check using cached data if available
df: pd.DataFrame = self.load_data()
date_to_add: str = str(entry_data[0]) date_to_add: str = str(entry_data[0])
if not df.empty and date_to_add in df["date"].values: if self._data_cache is not None:
self.logger.warning(f"Entry with date {date_to_add} already exists.") # Use cached data for duplicate check
return False if date_to_add in self._data_cache["date"].values:
self.logger.warning(
f"Entry with date {date_to_add} already exists."
)
return False
else:
# Fallback to loading data if no cache
df: pd.DataFrame = self.load_data()
if not df.empty and date_to_add in df["date"].values:
self.logger.warning(
f"Entry with date {date_to_add} already exists."
)
return False
# Write to file
with open(self.filename, mode="a", newline="") as file: with open(self.filename, mode="a", newline="") as file:
writer = csv.writer(file) writer = csv.writer(file)
writer.writerow(entry_data) writer.writerow(entry_data)
# Invalidate cache since data changed
self._invalidate_cache()
return True return True
except Exception as e: except Exception as e:
self.logger.error(f"Error adding entry: {str(e)}") self.logger.error(f"Error adding entry: {str(e)}")
return False return False
def update_entry(self, original_date: str, values: list[str | int]) -> bool: def update_entry(self, original_date: str, values: list[str | int]) -> bool:
"""Update an existing entry identified by original_date.""" """Update an existing entry identified by original_date
with optimized processing."""
try: try:
df: pd.DataFrame = self.load_data() df: pd.DataFrame = self.load_data()
new_date: str = str(values[0]) new_date: str = str(values[0])
# If the date is being changed, check if the new date already exists # Optimized duplicate check
if original_date != new_date and new_date in df["date"].values: if original_date != new_date:
date_exists = (df["date"] == new_date).any()
if date_exists:
self.logger.warning(
f"Cannot update: entry with date {new_date} already exists."
)
return False
# Get current CSV headers to match with values
headers = list(self._get_csv_headers())
# Ensure we have the right number of values with optimized padding
if len(values) < len(headers):
# Pad with defaults efficiently
padding_needed = len(headers) - len(values)
for i in range(padding_needed):
header_idx = len(values) + i
if header_idx < len(headers):
header = headers[header_idx]
if header == "note" or header.endswith("_doses"):
values.append("")
else:
values.append(0)
# Use vectorized update for better performance
mask = df["date"] == original_date
if mask.any():
df.loc[mask, headers] = values
# Write back to CSV with optimized method
df.to_csv(self.filename, index=False, mode="w")
self._invalidate_cache()
return True
else:
self.logger.warning( self.logger.warning(
f"Cannot update: entry with date {new_date} already exists." f"Entry with date {original_date} not found for update."
) )
return False return False
# Get current CSV headers to match with values
headers = self._get_csv_headers()
# Ensure we have the right number of values
if len(values) != len(headers):
self.logger.warning(
f"Value count mismatch: expected {len(headers)}, got {len(values)}"
)
# Pad with defaults if too few values
while len(values) < len(headers):
header = headers[len(values)]
if header == "note" or header.endswith("_doses"):
values.append("")
else:
values.append(0)
# Update the row using column names
df.loc[df["date"] == original_date, headers] = values
df.to_csv(self.filename, index=False)
return True
except Exception as e: except Exception as e:
self.logger.error(f"Error updating entry: {str(e)}") self.logger.error(f"Error updating entry: {str(e)}")
return False return False
def delete_entry(self, date: str) -> bool: def delete_entry(self, date: str) -> bool:
"""Delete an entry identified by date.""" """Delete an entry identified by date with optimized processing."""
try: try:
df: pd.DataFrame = self.load_data() df: pd.DataFrame = self.load_data()
# Remove the row with the matching date original_len = len(df)
# Use vectorized filtering for better performance
df = df[df["date"] != date] df = df[df["date"] != date]
# Write the updated dataframe back to the CSV
df.to_csv(self.filename, index=False) # Only write if something was actually deleted
if len(df) < original_len:
df.to_csv(self.filename, index=False, mode="w")
self._invalidate_cache()
return True return True
except Exception as e: except Exception as e:
self.logger.error(f"Error deleting entry: {str(e)}") self.logger.error(f"Error deleting entry: {str(e)}")
@@ -146,23 +241,34 @@ class DataManager:
def get_today_medicine_doses( def get_today_medicine_doses(
self, date: str, medicine_name: str self, date: str, medicine_name: str
) -> list[tuple[str, str]]: ) -> list[tuple[str, str]]:
"""Get list of (timestamp, dose) tuples for a medicine on a given date.""" """Get list of (timestamp, dose) tuples for a medicine on a given date
with caching."""
try: try:
df: pd.DataFrame = self.load_data() df: pd.DataFrame = self.load_data()
if df.empty or date not in df["date"].values: if df.empty:
return []
# Use vectorized filtering for better performance
date_mask = df["date"] == date
if not date_mask.any():
return [] return []
dose_column = f"{medicine_name}_doses" dose_column = f"{medicine_name}_doses"
doses_str = df.loc[df["date"] == date, dose_column].iloc[0] if dose_column not in df.columns:
return []
doses_str = df.loc[date_mask, dose_column].iloc[0]
if not doses_str: if not doses_str:
return [] return []
# Optimized dose parsing
doses = [] doses = []
for dose_entry in doses_str.split("|"): for dose_entry in doses_str.split("|"):
if ":" in dose_entry: if ":" in dose_entry:
timestamp, dose = dose_entry.split(":", 1) parts = dose_entry.split(":", 1)
doses.append((timestamp, dose)) if len(parts) == 2:
doses.append((parts[0], parts[1]))
return doses return doses
except Exception as e: except Exception as e:
+385
View File
@@ -0,0 +1,385 @@
"""
Export Manager for TheChart Application
Handles exporting data and graphs to various formats:
- CSV data to JSON, XML
- Graphs to PDF (with data tables)
"""
import contextlib
import json
import logging
import os
from datetime import datetime
from pathlib import Path
from typing import Any
from xml.dom import minidom
from xml.etree.ElementTree import Element, SubElement, tostring
import pandas as pd
from reportlab.lib import colors
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
from reportlab.lib.units import inch
from reportlab.platypus import (
Image,
Paragraph,
SimpleDocTemplate,
Spacer,
Table,
TableStyle,
)
from data_manager import DataManager
from graph_manager import GraphManager
from medicine_manager import MedicineManager
from pathology_manager import PathologyManager
class ExportManager:
"""Handle data and graph export operations."""
def __init__(
self,
data_manager: DataManager,
graph_manager: GraphManager,
medicine_manager: MedicineManager,
pathology_manager: PathologyManager,
logger: logging.Logger,
) -> None:
self.data_manager = data_manager
self.graph_manager = graph_manager
self.medicine_manager = medicine_manager
self.pathology_manager = pathology_manager
self.logger = logger
def export_data_to_json(self, export_path: str) -> bool:
"""Export CSV data to JSON format."""
try:
df = self.data_manager.load_data()
if df.empty:
self.logger.warning("No data to export")
return False
# Convert DataFrame to dictionary with better structure
export_data = {
"metadata": {
"export_date": datetime.now().isoformat(),
"total_entries": len(df),
"date_range": {
"start": df["date"].min() if not df.empty else None,
"end": df["date"].max() if not df.empty else None,
},
"pathologies": list(self.pathology_manager.get_pathology_keys()),
"medicines": list(self.medicine_manager.get_medicine_keys()),
},
"entries": df.to_dict(orient="records"),
}
with open(export_path, "w", encoding="utf-8") as f:
json.dump(export_data, f, indent=2, ensure_ascii=False)
self.logger.info(f"Data exported to JSON: {export_path}")
return True
except Exception as e:
self.logger.error(f"Error exporting to JSON: {str(e)}")
return False
def export_data_to_xml(self, export_path: str) -> bool:
"""Export CSV data to XML format."""
try:
df = self.data_manager.load_data()
if df.empty:
self.logger.warning("No data to export")
return False
# Create root element
root = Element("thechart_data")
# Add metadata
metadata = SubElement(root, "metadata")
SubElement(metadata, "export_date").text = datetime.now().isoformat()
SubElement(metadata, "total_entries").text = str(len(df))
# Date range
date_range = SubElement(metadata, "date_range")
SubElement(date_range, "start").text = (
df["date"].min() if not df.empty else ""
)
SubElement(date_range, "end").text = (
df["date"].max() if not df.empty else ""
)
# Pathologies
pathologies = SubElement(metadata, "pathologies")
for pathology in self.pathology_manager.get_pathology_keys():
SubElement(pathologies, "pathology").text = pathology
# Medicines
medicines = SubElement(metadata, "medicines")
for medicine in self.medicine_manager.get_medicine_keys():
SubElement(medicines, "medicine").text = medicine
# Add entries
entries = SubElement(root, "entries")
for _, row in df.iterrows():
entry = SubElement(entries, "entry")
for column, value in row.items():
elem = SubElement(entry, column.replace(" ", "_"))
elem.text = str(value) if pd.notna(value) else ""
# Pretty print XML
rough_string = tostring(root, "utf-8")
reparsed = minidom.parseString(rough_string)
pretty_xml = reparsed.toprettyxml(indent=" ")
with open(export_path, "w", encoding="utf-8") as f:
f.write(pretty_xml)
self.logger.info(f"Data exported to XML: {export_path}")
return True
except Exception as e:
self.logger.error(f"Error exporting to XML: {str(e)}")
return False
def _save_graph_as_image(self, temp_dir: Path) -> str | None:
"""Save current graph as temporary image for PDF inclusion."""
try:
# Check if graph manager exists
if self.graph_manager is None:
self.logger.warning("No graph manager available for export")
return None
# Check if graph manager and figure exist
if not hasattr(self.graph_manager, "fig") or self.graph_manager.fig is None:
self.logger.warning("No graph figure available for export")
return None
# Ensure graph is up to date with current data
df = self.data_manager.load_data()
if not df.empty:
self.graph_manager.update_graph(df)
else:
self.logger.warning("No data available to update graph for export")
return None
# Ensure temp directory exists
temp_dir.mkdir(parents=True, exist_ok=True)
temp_image_path = temp_dir / "graph.png"
# Save the current figure
self.graph_manager.fig.savefig(
str(temp_image_path),
dpi=150,
bbox_inches="tight",
facecolor="white",
edgecolor="none",
)
# Verify the file was actually created
if not temp_image_path.exists():
self.logger.error(
f"Graph image file was not created: {temp_image_path}"
)
return None
self.logger.info(f"Graph image saved successfully: {temp_image_path}")
return str(temp_image_path)
except Exception as e:
self.logger.error(f"Error saving graph image: {str(e)}")
return None
def export_to_pdf(self, export_path: str, include_graph: bool = True) -> bool:
"""Export data and optionally graph to PDF format."""
try:
df = self.data_manager.load_data()
# Create PDF document
doc = SimpleDocTemplate(
export_path,
pagesize=A4,
rightMargin=72,
leftMargin=72,
topMargin=72,
bottomMargin=18,
)
# Get styles
styles = getSampleStyleSheet()
title_style = ParagraphStyle(
"CustomTitle",
parent=styles["Heading1"],
fontSize=18,
spaceAfter=30,
textColor=colors.darkblue,
)
story = []
# Title
story.append(Paragraph("TheChart - Medication Tracker Export", title_style))
story.append(Spacer(1, 20))
# Export metadata
export_info = [
f"Export Date: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
f"Total Entries: {len(df) if not df.empty else 0}",
]
if not df.empty:
export_info.extend(
[
f"Date Range: {df['date'].min()} to {df['date'].max()}",
(
"Pathologies: "
+ ", ".join(self.pathology_manager.get_pathology_keys())
),
(
"Medicines: "
+ ", ".join(self.medicine_manager.get_medicine_keys())
),
]
)
for info in export_info:
story.append(Paragraph(info, styles["Normal"]))
story.append(Spacer(1, 20))
# Include graph if requested and available
if include_graph:
temp_dir = Path(export_path).parent / "temp_export"
try:
graph_path = self._save_graph_as_image(temp_dir)
if graph_path and os.path.exists(graph_path):
story.append(
Paragraph("Data Visualization", styles["Heading2"])
)
story.append(Spacer(1, 10))
# Add graph image
img = Image(graph_path, width=6 * inch, height=3.6 * inch)
story.append(img)
story.append(Spacer(1, 20))
# Clean up temp image
os.remove(graph_path)
else:
# Graph not available, add a note instead
story.append(
Paragraph("Data Visualization", styles["Heading2"])
)
story.append(Spacer(1, 10))
story.append(
Paragraph(
"Graph not available - no data to visualize or graph "
"not generated yet.",
styles["Normal"],
)
)
story.append(Spacer(1, 20))
except Exception as e:
self.logger.error(f"Error including graph in PDF: {str(e)}")
# Add error note instead of failing completely
story.append(Paragraph("Data Visualization", styles["Heading2"]))
story.append(Spacer(1, 10))
story.append(
Paragraph(
f"Graph could not be included: {str(e)}", styles["Normal"]
)
)
story.append(Spacer(1, 20))
finally:
# Clean up temp directory
if temp_dir.exists():
with contextlib.suppress(OSError):
temp_dir.rmdir()
# Add data table if we have data
if not df.empty:
story.append(Paragraph("Data Table", styles["Heading2"]))
story.append(Spacer(1, 10))
# Prepare table data - limit columns for better PDF formatting
display_columns = ["date"]
for pathology_key in self.pathology_manager.get_pathology_keys():
display_columns.append(pathology_key)
for medicine_key in self.medicine_manager.get_medicine_keys():
display_columns.append(medicine_key)
display_columns.append("note")
# Filter dataframe to display columns that exist
available_columns = [
col for col in display_columns if col in df.columns
]
display_df = df[available_columns].copy()
# Truncate long notes for better table formatting
if "note" in display_df.columns:
display_df["note"] = display_df["note"].apply(
lambda x: (str(x)[:50] + "...") if len(str(x)) > 50 else str(x)
)
# Convert to table data
table_data = [available_columns] # Headers
for _, row in display_df.iterrows():
table_data.append(
[str(val) if pd.notna(val) else "" for val in row]
)
# Create table with styling
table = Table(table_data, repeatRows=1)
table.setStyle(
TableStyle(
[
("BACKGROUND", (0, 0), (-1, 0), colors.grey),
("TEXTCOLOR", (0, 0), (-1, 0), colors.whitesmoke),
("ALIGN", (0, 0), (-1, -1), "CENTER"),
("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
("FONTSIZE", (0, 0), (-1, 0), 10),
("BOTTOMPADDING", (0, 0), (-1, 0), 12),
("BACKGROUND", (0, 1), (-1, -1), colors.beige),
("FONTNAME", (0, 1), (-1, -1), "Helvetica"),
("FONTSIZE", (0, 1), (-1, -1), 8),
("GRID", (0, 0), (-1, -1), 1, colors.black),
("VALIGN", (0, 0), (-1, -1), "TOP"),
]
)
)
story.append(table)
else:
story.append(
Paragraph("No data available to export.", styles["Normal"])
)
# Build PDF
doc.build(story)
self.logger.info(f"Data exported to PDF: {export_path}")
return True
except Exception as e:
self.logger.error(f"Error exporting to PDF: {str(e)}")
return False
def get_export_info(self) -> dict[str, Any]:
"""Get information about available data for export."""
df = self.data_manager.load_data()
return {
"total_entries": len(df) if not df.empty else 0,
"date_range": {
"start": df["date"].min() if not df.empty else None,
"end": df["date"].max() if not df.empty else None,
},
"pathologies": list(self.pathology_manager.get_pathology_keys()),
"medicines": list(self.medicine_manager.get_medicine_keys()),
"has_data": not df.empty,
}
+247
View File
@@ -0,0 +1,247 @@
"""
Export Window for TheChart Application
Provides a GUI interface for exporting data and graphs to various formats.
"""
import tkinter as tk
from pathlib import Path
from tkinter import filedialog, messagebox, ttk
from export_manager import ExportManager
class ExportWindow:
"""Export window for data and graph export functionality."""
def __init__(self, parent: tk.Tk, export_manager: ExportManager) -> None:
self.parent = parent
self.export_manager = export_manager
# Create the export window
self.window = tk.Toplevel(parent)
self.window.title("Export Data")
self.window.geometry("500x450") # Made taller to ensure buttons are visible
self.window.resizable(False, False)
# Center the window
self._center_window()
# Make window modal
self.window.transient(parent)
self.window.grab_set()
# Setup the UI
self._setup_ui()
def _center_window(self) -> None:
"""Center the export window on the parent window."""
self.window.update_idletasks()
# Get window dimensions
width = self.window.winfo_width()
height = self.window.winfo_height()
# Get parent window position and size
parent_x = self.parent.winfo_rootx()
parent_y = self.parent.winfo_rooty()
parent_width = self.parent.winfo_width()
parent_height = self.parent.winfo_height()
# Calculate position to center on parent
x = parent_x + (parent_width // 2) - (width // 2)
y = parent_y + (parent_height // 2) - (height // 2)
self.window.geometry(f"{width}x{height}+{x}+{y}")
def _setup_ui(self) -> None:
"""Setup the export window UI."""
# Main frame
main_frame = ttk.Frame(self.window, padding="15")
main_frame.pack(fill=tk.BOTH, expand=True)
# Title
title_label = ttk.Label(
main_frame, text="Export Data & Graphs", font=("Arial", 14, "bold")
)
title_label.pack(pady=(0, 15))
# Create scrollable content area for the main content
content_frame = ttk.Frame(main_frame)
content_frame.pack(fill=tk.BOTH, expand=True)
# Export info section
self._create_info_section(content_frame)
# Export options section
self._create_options_section(content_frame)
# Buttons section - always at the bottom
self._create_buttons_section(main_frame)
def _create_info_section(self, parent: ttk.Frame) -> None:
"""Create the data information section."""
info_frame = ttk.LabelFrame(parent, text="Data Summary", padding="10")
info_frame.pack(fill=tk.X, pady=(0, 20))
# Get export info
export_info = self.export_manager.get_export_info()
# Display information
if export_info["has_data"]:
info_text = f"""Total Entries: {export_info["total_entries"]}
Date Range: {export_info["date_range"]["start"]} to {export_info["date_range"]["end"]}
Pathologies: {", ".join(export_info["pathologies"])}
Medicines: {", ".join(export_info["medicines"])}"""
else:
info_text = "No data available for export."
info_label = ttk.Label(info_frame, text=info_text, justify=tk.LEFT)
info_label.pack(anchor=tk.W)
def _create_options_section(self, parent: ttk.Frame) -> None:
"""Create the export options section."""
options_frame = ttk.LabelFrame(parent, text="Export Options", padding="10")
options_frame.pack(fill=tk.X, pady=(0, 20))
# Include graph option (for PDF export)
self.include_graph_var = tk.BooleanVar(value=True)
graph_check = ttk.Checkbutton(
options_frame,
text="Include graph in PDF export",
variable=self.include_graph_var,
)
graph_check.pack(anchor=tk.W, pady=(0, 10))
# Format selection
format_label = ttk.Label(options_frame, text="Export Format:")
format_label.pack(anchor=tk.W)
self.format_var = tk.StringVar(value="JSON")
formats = ["JSON", "XML", "PDF"]
for fmt in formats:
radio = ttk.Radiobutton(
options_frame, text=fmt, variable=self.format_var, value=fmt
)
radio.pack(anchor=tk.W, padx=(20, 0))
def _create_buttons_section(self, parent: ttk.Frame) -> None:
"""Create the buttons section."""
# Add a separator for visual clarity
separator = ttk.Separator(parent, orient="horizontal")
separator.pack(fill=tk.X, pady=(10, 10))
button_frame = ttk.Frame(parent)
button_frame.pack(fill=tk.X, pady=(0, 10))
# Export button with more prominent styling
export_btn = ttk.Button(
button_frame, text="Export...", command=self._handle_export
)
export_btn.pack(side=tk.LEFT, padx=(10, 10), pady=5)
# Cancel button
cancel_btn = ttk.Button(
button_frame, text="Cancel", command=self.window.destroy
)
cancel_btn.pack(side=tk.RIGHT, padx=(10, 10), pady=5)
def _handle_export(self) -> None:
"""Handle the export button click."""
# Check if we have data to export
export_info = self.export_manager.get_export_info()
if not export_info["has_data"]:
messagebox.showwarning(
"No Data", "There is no data available to export.", parent=self.window
)
return
# Get selected format
selected_format = self.format_var.get()
# Define file types for dialog
file_types = {
"JSON": [("JSON files", "*.json"), ("All files", "*.*")],
"XML": [("XML files", "*.xml"), ("All files", "*.*")],
"PDF": [("PDF files", "*.pdf"), ("All files", "*.*")],
}
# Default filename
default_name = f"thechart_export.{selected_format.lower()}"
# Show save dialog
filename = filedialog.asksaveasfilename(
parent=self.window,
title=f"Export as {selected_format}",
defaultextension=f".{selected_format.lower()}",
filetypes=file_types[selected_format],
initialfile=default_name,
)
if not filename:
return
# Perform export based on selected format
success = False
try:
if selected_format == "JSON":
success = self.export_manager.export_data_to_json(filename)
elif selected_format == "XML":
success = self.export_manager.export_data_to_xml(filename)
elif selected_format == "PDF":
include_graph = self.include_graph_var.get()
success = self.export_manager.export_to_pdf(
filename, include_graph=include_graph
)
if success:
messagebox.showinfo(
"Export Successful",
f"Data exported successfully to:\n{filename}",
parent=self.window,
)
# Ask if user wants to open the file location
if messagebox.askyesno(
"Open Location",
"Would you like to open the file location?",
parent=self.window,
):
self._open_file_location(filename)
self.window.destroy()
else:
messagebox.showerror(
"Export Failed",
f"Failed to export data as {selected_format}. "
"Please check the logs for more details.",
parent=self.window,
)
except Exception as e:
messagebox.showerror(
"Export Error",
f"An error occurred during export:\n{str(e)}",
parent=self.window,
)
def _open_file_location(self, filepath: str) -> None:
"""Open the file location in the system file manager."""
try:
file_path = Path(filepath)
directory = file_path.parent
# Use system-specific command to open file manager
import subprocess
import sys
if sys.platform == "win32":
subprocess.run(["explorer", str(directory)], check=False)
elif sys.platform == "darwin":
subprocess.run(["open", str(directory)], check=False)
else: # Linux and other Unix-like systems
subprocess.run(["xdg-open", str(directory)], check=False)
except Exception:
# If opening file location fails, just ignore silently
pass
+221 -169
View File
@@ -12,7 +12,8 @@ from pathology_manager import PathologyManager
class GraphManager: class GraphManager:
"""Handle all graph-related operations for the application.""" """Optimized version - Handle all graph-related operations for the
application with performance improvements."""
def __init__( def __init__(
self, self,
@@ -24,166 +25,206 @@ class GraphManager:
self.medicine_manager = medicine_manager self.medicine_manager = medicine_manager
self.pathology_manager = pathology_manager self.pathology_manager = pathology_manager
# Configure graph frame to expand # Initialize matplotlib with optimized settings
self.parent_frame.grid_rowconfigure(0, weight=1) self.fig: matplotlib.figure.Figure = plt.figure(figsize=(10, 6), dpi=80)
self.parent_frame.grid_columnconfigure(0, weight=1) self.ax: Axes = self.fig.add_subplot(111)
self._initialize_toggle_vars() # Cache for current data to avoid reprocessing
self.current_data: pd.DataFrame = pd.DataFrame()
self._last_plot_hash: str = ""
# Initialize UI components
self.toggle_vars: dict[str, tk.IntVar] = {}
self._setup_ui() self._setup_ui()
self._initialize_toggle_vars()
def _initialize_toggle_vars(self) -> None:
"""Initialize toggle variables for chart elements."""
self.toggle_vars: dict[str, tk.BooleanVar] = {}
# Initialize pathology toggles dynamically
for pathology_key in self.pathology_manager.get_pathology_keys():
pathology = self.pathology_manager.get_pathology(pathology_key)
default_value = pathology.default_enabled if pathology else True
self.toggle_vars[pathology_key] = tk.BooleanVar(value=default_value)
# Add medicine toggles dynamically
for medicine_key in self.medicine_manager.get_medicine_keys():
medicine = self.medicine_manager.get_medicine(medicine_key)
default_value = medicine.default_enabled if medicine else False
self.toggle_vars[medicine_key] = tk.BooleanVar(value=default_value)
def _setup_ui(self) -> None:
"""Set up the UI components."""
# Create control frame for toggles
self.control_frame: ttk.Frame = ttk.Frame(self.parent_frame)
self.control_frame.grid(row=0, column=0, sticky="ew", padx=5, pady=5)
# Create toggle checkboxes
self._create_chart_toggles() self._create_chart_toggles()
# Create graph frame def _initialize_toggle_vars(self) -> None:
self.graph_frame: ttk.Frame = ttk.Frame(self.parent_frame) """Initialize toggle variables for chart elements with optimization."""
self.graph_frame.grid(row=1, column=0, sticky="nsew", padx=5, pady=5) # Initialize pathology toggles
for pathology_key in self.pathology_manager.get_pathology_keys():
self.toggle_vars[pathology_key] = tk.IntVar(value=1)
# Reconfigure parent frame for new layout # Initialize medicine toggles (unchecked by default)
self.parent_frame.grid_rowconfigure(1, weight=1) for medicine_key in self.medicine_manager.get_medicine_keys():
self.parent_frame.grid_columnconfigure(0, weight=1) self.toggle_vars[medicine_key] = tk.IntVar(value=0)
# Initialize matplotlib figure and canvas def _setup_ui(self) -> None:
self.fig: matplotlib.figure.Figure """Set up the UI components with performance optimizations."""
self.ax: Axes # Create canvas with optimized settings
self.fig, self.ax = plt.subplots() self.canvas = FigureCanvasTkAgg(self.fig, master=self.parent_frame)
self.canvas: FigureCanvasTkAgg = FigureCanvasTkAgg( self.canvas.draw_idle() # Use draw_idle for better performance
figure=self.fig, master=self.graph_frame
)
self.canvas.get_tk_widget().pack(fill="both", expand=True)
# Store current data for replotting # Pack canvas
self.current_data: pd.DataFrame = pd.DataFrame() canvas_widget = self.canvas.get_tk_widget()
canvas_widget.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
# Create control frame
self.control_frame = ttk.Frame(self.parent_frame)
self.control_frame.pack(side=tk.BOTTOM, fill=tk.X, padx=5, pady=2)
def _create_chart_toggles(self) -> None: def _create_chart_toggles(self) -> None:
"""Create toggle controls for chart elements.""" """Create toggle controls for chart elements with improved layout."""
ttk.Label(self.control_frame, text="Show/Hide Elements:").pack( # Pathology toggles
side="left", padx=5 pathology_frame = ttk.LabelFrame(
self.control_frame, text="Pathologies", padding="5"
) )
pathology_frame.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=2)
# Pathologies toggles - dynamic based on pathology manager # Use grid for better layout
pathologies_frame = ttk.LabelFrame(self.control_frame, text="Pathologies") row, col = 0, 0
pathologies_frame.pack(side="left", padx=5, pady=2)
for pathology_key in self.pathology_manager.get_pathology_keys(): for pathology_key in self.pathology_manager.get_pathology_keys():
pathology = self.pathology_manager.get_pathology(pathology_key) pathology = self.pathology_manager.get_pathology(pathology_key)
if pathology: if pathology:
checkbox = ttk.Checkbutton( display_name = pathology.display_name
pathologies_frame, text = (
text=pathology.display_name, display_name[:10] + "..."
if len(display_name) > 10
else display_name
)
cb = ttk.Checkbutton(
pathology_frame,
text=text,
variable=self.toggle_vars[pathology_key], variable=self.toggle_vars[pathology_key],
command=self._handle_toggle_changed, command=self._handle_toggle_changed,
) )
checkbox.pack(side="left", padx=3) cb.grid(row=row, column=col, sticky="w", padx=2)
col += 1
if col > 1: # 2 columns max
col = 0
row += 1
# Medicines toggles - dynamic based on medicine manager # Medicine toggles
medicines_frame = ttk.LabelFrame(self.control_frame, text="Medicines") medicine_frame = ttk.LabelFrame(
medicines_frame.pack(side="left", padx=5, pady=2) self.control_frame, text="Medicines", padding="5"
)
medicine_frame.pack(side=tk.RIGHT, fill=tk.X, expand=True, padx=2)
# Use grid for medicines too
row, col = 0, 0
for medicine_key in self.medicine_manager.get_medicine_keys(): for medicine_key in self.medicine_manager.get_medicine_keys():
medicine = self.medicine_manager.get_medicine(medicine_key) medicine = self.medicine_manager.get_medicine(medicine_key)
if medicine: if medicine:
checkbox = ttk.Checkbutton( med_name = medicine.display_name
medicines_frame, text = med_name[:10] + "..." if len(med_name) > 10 else med_name
text=medicine.display_name, cb = ttk.Checkbutton(
medicine_frame,
text=text,
variable=self.toggle_vars[medicine_key], variable=self.toggle_vars[medicine_key],
command=self._handle_toggle_changed, command=self._handle_toggle_changed,
) )
checkbox.pack(side="left", padx=3) cb.grid(row=row, column=col, sticky="w", padx=2)
col += 1
if col > 2: # 3 columns max for medicines
col = 0
row += 1
def _handle_toggle_changed(self) -> None: def _handle_toggle_changed(self) -> None:
"""Handle toggle changes by replotting the graph.""" """Handle toggle changes by replotting the graph with optimization."""
if not self.current_data.empty: if not self.current_data.empty:
self._plot_graph_data(self.current_data) self._plot_graph_data(self.current_data)
def update_graph(self, df: pd.DataFrame) -> None: def update_graph(self, df: pd.DataFrame) -> None:
"""Update the graph with new data.""" """Update the graph with new data using optimization checks."""
self.current_data = df.copy() if not df.empty else pd.DataFrame() # Create hash of data to avoid unnecessary redraws
self._plot_graph_data(df) data_hash = str(hash(str(df.values.tobytes()) if not df.empty else "empty"))
# Only update if data actually changed
if data_hash != self._last_plot_hash or self.current_data.empty:
self.current_data = df.copy() if not df.empty else pd.DataFrame()
self._last_plot_hash = data_hash
self._plot_graph_data(df)
def _plot_graph_data(self, df: pd.DataFrame) -> None: def _plot_graph_data(self, df: pd.DataFrame) -> None:
"""Plot the graph data with current toggle settings.""" """Plot the graph data with current toggle settings using optimizations."""
self.ax.clear() # Use batch updates to reduce redraws
if not df.empty: with plt.ioff(): # Turn off interactive mode for batch updates
# Convert dates and sort self.ax.clear()
df = df.copy() # Create a copy to avoid modifying the original
df["date"] = pd.to_datetime(df["date"])
df = df.sort_values(by="date")
df.set_index(keys="date", inplace=True)
# Track if any series are plotted if not df.empty:
has_plotted_series = False # Optimize data processing
df_processed = self._preprocess_data(df)
# Plot pathology data series based on toggle states # Track if any series are plotted
for pathology_key in self.pathology_manager.get_pathology_keys(): has_plotted_series = self._plot_pathology_data(df_processed)
if self.toggle_vars[pathology_key].get(): medicine_data = self._plot_medicine_data(df_processed)
pathology = self.pathology_manager.get_pathology(pathology_key)
if pathology and pathology_key in df.columns:
label = f"{pathology.display_name} ({pathology.scale_info})"
linestyle = (
"dashed"
if pathology.scale_orientation == "inverted"
else "-"
)
self._plot_series(df, pathology_key, label, "o", linestyle)
has_plotted_series = True
# Plot medicine dose data if has_plotted_series or medicine_data["has_plotted"]:
# Get medicine colors from medicine manager self._configure_graph_appearance(medicine_data)
medicine_colors = self.medicine_manager.get_graph_colors()
# Get medicines dynamically from medicine manager # Single draw call at the end
medicines = self.medicine_manager.get_medicine_keys() self.canvas.draw_idle()
# Track medicines with and without data for legend def _preprocess_data(self, df: pd.DataFrame) -> pd.DataFrame:
medicines_with_data = [] """Preprocess data for plotting with optimizations."""
medicines_without_data = [] df = df.copy()
# Batch convert dates and sort
df["date"] = pd.to_datetime(df["date"], cache=True)
df = df.sort_values(by="date")
df.set_index(keys="date", inplace=True)
return df
for medicine in medicines: def _plot_pathology_data(self, df: pd.DataFrame) -> bool:
dose_column = f"{medicine}_doses" """Plot pathology data series with optimizations."""
if self.toggle_vars[medicine].get() and dose_column in df.columns: has_plotted_series = False
# Calculate daily dose totals
daily_doses = []
for dose_str in df[dose_column]:
total_dose = self._calculate_daily_dose(dose_str)
daily_doses.append(total_dose)
# Only plot if there are non-zero doses # Batch plot pathology data
if any(dose > 0 for dose in daily_doses): pathology_keys = self.pathology_manager.get_pathology_keys()
medicines_with_data.append(medicine) active_pathologies = [
# Scale doses for better visibility key
# (divide by 10 to fit with 0-10 scale) for key in pathology_keys
scaled_doses = [dose / 10 for dose in daily_doses] if self.toggle_vars[key].get() and key in df.columns
]
# Calculate total dosage for this medicine across all days for pathology_key in active_pathologies:
total_medicine_dose = sum(daily_doses) pathology = self.pathology_manager.get_pathology(pathology_key)
non_zero_doses = [d for d in daily_doses if d > 0] if pathology:
avg_dose = total_medicine_dose / len(non_zero_doses) label = f"{pathology.display_name} ({pathology.scale_info})"
linestyle = (
"dashed" if pathology.scale_orientation == "inverted" else "-"
)
self._plot_series(df, pathology_key, label, "o", linestyle)
has_plotted_series = True
# Create more informative label return has_plotted_series
def _plot_medicine_data(self, df: pd.DataFrame) -> dict:
"""Plot medicine data with optimizations."""
result = {"has_plotted": False, "with_data": [], "without_data": []}
# Get medicine colors and keys in batch
medicine_colors = self.medicine_manager.get_graph_colors()
medicines = self.medicine_manager.get_medicine_keys()
# Pre-calculate daily doses for all medicines to avoid repeated computation
medicine_doses = {}
for medicine in medicines:
dose_column = f"{medicine}_doses"
if dose_column in df.columns:
daily_doses = [
self._calculate_daily_dose(dose_str) for dose_str in df[dose_column]
]
medicine_doses[medicine] = daily_doses
# Plot medicines with data
for medicine in medicines:
if self.toggle_vars[medicine].get() and medicine in medicine_doses:
daily_doses = medicine_doses[medicine]
# Check if there's any data to plot
if any(dose > 0 for dose in daily_doses):
result["with_data"].append(medicine)
# Optimize dose scaling and bar plotting
scaled_doses = [dose / 10 for dose in daily_doses]
# Calculate statistics more efficiently
non_zero_doses = [d for d in daily_doses if d > 0]
if non_zero_doses:
avg_dose = sum(daily_doses) / len(non_zero_doses)
label = f"{medicine.capitalize()} (avg: {avg_dose:.1f}mg)" label = f"{medicine.capitalize()} (avg: {avg_dose:.1f}mg)"
# Single bar plot call
self.ax.bar( self.ax.bar(
df.index, df.index,
scaled_doses, scaled_doses,
@@ -193,56 +234,59 @@ class GraphManager:
width=0.6, width=0.6,
bottom=-max(scaled_doses) * 1.1 if scaled_doses else -1, bottom=-max(scaled_doses) * 1.1 if scaled_doses else -1,
) )
has_plotted_series = True result["has_plotted"] = True
else: else:
# Medicine is toggled on but has no dose data # Medicine is toggled on but has no dose data
if self.toggle_vars[medicine].get(): if self.toggle_vars[medicine].get():
medicines_without_data.append(medicine) result["without_data"].append(medicine)
# Configure graph appearance return result
if has_plotted_series:
# Get current legend handles and labels
handles, labels = self.ax.get_legend_handles_labels()
# Add information about medicines without data if any are toggled on def _configure_graph_appearance(self, medicine_data: dict) -> None:
if medicines_without_data: """Configure graph appearance with optimizations."""
# Add a text note about medicines without dose data # Get legend data in batch
med_list = ", ".join(medicines_without_data) handles, labels = self.ax.get_legend_handles_labels()
info_text = f"Tracked (no doses): {med_list}"
labels.append(info_text)
# Create a dummy handle for the info text (invisible)
from matplotlib.patches import Rectangle
dummy_handle = Rectangle( # Add information about medicines without data if any are toggled on
(0, 0), 1, 1, fc="w", fill=False, edgecolor="none", linewidth=0 if medicine_data["without_data"]:
) med_list = ", ".join(medicine_data["without_data"])
handles.append(dummy_handle) info_text = f"Tracked (no doses): {med_list}"
labels.append(info_text)
# Create an expanded legend with better formatting # Create dummy handle more efficiently
self.ax.legend( from matplotlib.patches import Rectangle
handles,
labels,
loc="upper left",
bbox_to_anchor=(0, 1),
ncol=2, # Display in 2 columns for better space usage
fontsize="small",
frameon=True,
fancybox=True,
shadow=True,
framealpha=0.9,
)
self.ax.set_title("Medication Effects Over Time")
self.ax.set_xlabel("Date")
self.ax.set_ylabel("Rating (0-10) / Dose (mg)")
# Adjust y-axis to accommodate medicine bars at bottom dummy_handle = Rectangle(
current_ylim = self.ax.get_ylim() (0, 0), 1, 1, fc="w", fill=False, edgecolor="none", linewidth=0
self.ax.set_ylim(bottom=current_ylim[0], top=max(10, current_ylim[1])) )
handles.append(dummy_handle)
self.fig.autofmt_xdate() # Create legend with optimized settings
if handles and labels:
self.ax.legend(
handles,
labels,
loc="upper left",
bbox_to_anchor=(0, 1),
ncol=2,
fontsize="small",
frameon=True,
fancybox=True,
shadow=True,
framealpha=0.9,
)
# Redraw the canvas # Set titles and labels
self.canvas.draw() self.ax.set_title("Medication Effects Over Time")
self.ax.set_xlabel("Date")
self.ax.set_ylabel("Rating (0-10) / Dose (mg)")
# Optimize y-axis configuration
current_ylim = self.ax.get_ylim()
self.ax.set_ylim(bottom=current_ylim[0], top=max(10, current_ylim[1]))
# Optimize date formatting
self.fig.autofmt_xdate()
def _plot_series( def _plot_series(
self, self,
@@ -252,25 +296,28 @@ class GraphManager:
marker: str, marker: str,
linestyle: str, linestyle: str,
) -> None: ) -> None:
"""Helper method to plot a data series.""" """Helper method to plot a data series with optimizations."""
# Use more efficient plotting parameters
self.ax.plot( self.ax.plot(
df.index, df.index,
df[column], df[column],
marker=marker, marker=marker,
linestyle=linestyle, linestyle=linestyle,
label=label, label=label,
markersize=4, # Smaller markers for better performance
linewidth=1.5, # Optimized line width
) )
def _calculate_daily_dose(self, dose_str: str) -> float: def _calculate_daily_dose(self, dose_str: str) -> float:
"""Calculate total daily dose from dose string format.""" """Calculate total daily dose from dose string format with optimizations."""
if not dose_str or pd.isna(dose_str) or str(dose_str).lower() == "nan": if not dose_str or pd.isna(dose_str) or str(dose_str).lower() == "nan":
return 0.0 return 0.0
total_dose = 0.0 total_dose = 0.0
# Handle different separators and clean the string # Optimize string processing
dose_str = str(dose_str).replace("", "").strip() dose_str = str(dose_str).replace("", "").strip()
# Split by | or by spaces if no | present # More efficient splitting and processing
dose_entries = dose_str.split("|") if "|" in dose_str else [dose_str] dose_entries = dose_str.split("|") if "|" in dose_str else [dose_str]
for entry in dose_entries: for entry in dose_entries:
@@ -279,15 +326,15 @@ class GraphManager:
continue continue
try: try:
# Extract dose part after the last colon (timestamp:dose format) # More efficient dose extraction
dose_part = entry.split(":")[-1] if ":" in entry else entry dose_part = entry.split(":")[-1] if ":" in entry else entry
# Extract numeric part from dose (e.g., "150mg" -> 150) # Optimized numeric extraction
dose_value = "" dose_value = ""
for char in dose_part: for char in dose_part:
if char.isdigit() or char == ".": if char.isdigit() or char == ".":
dose_value += char dose_value += char
elif dose_value: # Stop at first non-digit after finding digits elif dose_value:
break break
if dose_value: if dose_value:
@@ -298,5 +345,10 @@ class GraphManager:
return total_dose return total_dose
def close(self) -> None: def close(self) -> None:
"""Clean up resources.""" """Clean up resources with proper optimization."""
plt.close(self.fig) try:
# Clear the plot before closing
self.ax.clear()
plt.close(self.fig)
except Exception:
pass # Ignore cleanup errors
+286 -32
View File
@@ -7,8 +7,10 @@ from typing import Any
import pandas as pd import pandas as pd
from constants import LOG_LEVEL, LOG_PATH from constants import LOG_CLEAR, LOG_LEVEL, LOG_PATH
from data_manager import DataManager from data_manager import DataManager
from export_manager import ExportManager
from export_window import ExportWindow
from graph_manager import GraphManager from graph_manager import GraphManager
from init import logger from init import logger
from medicine_management_window import MedicineManagementWindow from medicine_management_window import MedicineManagementWindow
@@ -40,9 +42,12 @@ class MedTrackerApp:
Using default file: {self.filename}" Using default file: {self.filename}"
) )
logger.info(f"Log level: {LOG_LEVEL}")
if LOG_LEVEL == "DEBUG": if LOG_LEVEL == "DEBUG":
logger.debug(f"Script name: {sys.argv[0]}") logger.debug(f"Script name: {sys.argv[0]}")
logger.debug(f"Logs path: {LOG_PATH}") logger.debug(f"Logs path: {LOG_PATH}")
logger.debug(f"Log clear: {LOG_CLEAR}")
logger.debug(f"First argument: {first_argument}") logger.debug(f"First argument: {first_argument}")
# Initialize managers # Initialize managers
@@ -67,6 +72,32 @@ class MedTrackerApp:
# Add menu bar # Add menu bar
self._setup_menu() self._setup_menu()
# Setup keyboard shortcuts
self._setup_keyboard_shortcuts()
# Center the window on screen
self._center_window()
def _center_window(self) -> None:
"""Center the main window on the screen."""
# Update the window to get accurate dimensions
self.root.update_idletasks()
# Get window dimensions
window_width = self.root.winfo_reqwidth()
window_height = self.root.winfo_reqheight()
# Get screen dimensions
screen_width = self.root.winfo_screenwidth()
screen_height = self.root.winfo_screenheight()
# Calculate position to center the window
x = (screen_width // 2) - (window_width // 2)
y = (screen_height // 2) - (window_height // 2)
# Set the window geometry
self.root.geometry(f"{window_width}x{window_height}+{x}+{y}")
def _setup_main_ui(self) -> None: def _setup_main_ui(self) -> None:
"""Set up the main UI components.""" """Set up the main UI components."""
import tkinter.ttk as ttk import tkinter.ttk as ttk
@@ -80,7 +111,7 @@ class MedTrackerApp:
self.root.grid_columnconfigure(0, weight=1) self.root.grid_columnconfigure(0, weight=1)
# Configure main frame grid for scaling # Configure main frame grid for scaling
for i in range(2): for i in range(3): # Changed from 2 to 3 to accommodate status bar
main_frame.grid_rowconfigure(i, weight=1 if i == 1 else 0) main_frame.grid_rowconfigure(i, weight=1 if i == 1 else 0)
main_frame.grid_columnconfigure(i, weight=3 if i == 1 else 1) main_frame.grid_columnconfigure(i, weight=3 if i == 1 else 1)
logger.debug("Main frame and root grid configured for scaling.") logger.debug("Main frame and root grid configured for scaling.")
@@ -91,6 +122,15 @@ class MedTrackerApp:
graph_frame, self.medicine_manager, self.pathology_manager graph_frame, self.medicine_manager, self.pathology_manager
) )
# Initialize export manager
self.export_manager: ExportManager = ExportManager(
self.data_manager,
self.graph_manager,
self.medicine_manager,
self.pathology_manager,
logger,
)
# --- Create Input Frame --- # --- Create Input Frame ---
input_ui: dict[str, Any] = self.ui_manager.create_input_frame(main_frame) input_ui: dict[str, Any] = self.ui_manager.create_input_frame(main_frame)
self.input_frame: ttk.Frame = input_ui["frame"] self.input_frame: ttk.Frame = input_ui["frame"]
@@ -104,12 +144,12 @@ class MedTrackerApp:
self.input_frame, self.input_frame,
[ [
{ {
"text": "Add Entry", "text": "Add Entry (Ctrl+S)",
"command": self.add_new_entry, "command": self.add_new_entry,
"fill": "both", "fill": "both",
"expand": True, "expand": True,
}, },
{"text": "Quit", "command": self.handle_window_closing}, {"text": "Quit (Ctrl+Q)", "command": self.handle_window_closing},
], ],
) )
@@ -118,38 +158,175 @@ class MedTrackerApp:
self.tree: ttk.Treeview = table_ui["tree"] self.tree: ttk.Treeview = table_ui["tree"]
self.tree.bind("<Double-1>", self.handle_double_click) self.tree.bind("<Double-1>", self.handle_double_click)
# --- Create Status Bar ---
self.status_bar = self.ui_manager.create_status_bar(main_frame)
# Load data # Load data
self.refresh_data_display() self.refresh_data_display()
# Initialize status bar with ready message
self.ui_manager.update_status("Application ready", "info")
def _setup_menu(self) -> None: def _setup_menu(self) -> None:
"""Set up the menu bar.""" """Set up the menu bar."""
menubar = tk.Menu(self.root) menubar = tk.Menu(self.root)
self.root.config(menu=menubar) self.root.config(menu=menubar)
# File menu
file_menu = tk.Menu(menubar, tearoff=0)
menubar.add_cascade(label="File", menu=file_menu)
file_menu.add_command(
label="Export Data...",
command=self._open_export_window,
accelerator="Ctrl+E",
)
file_menu.add_separator()
file_menu.add_command(
label="Exit", command=self.handle_window_closing, accelerator="Ctrl+Q"
)
# Tools menu # Tools menu
tools_menu = tk.Menu(menubar, tearoff=0) tools_menu = tk.Menu(menubar, tearoff=0)
menubar.add_cascade(label="Tools", menu=tools_menu) menubar.add_cascade(label="Tools", menu=tools_menu)
tools_menu.add_command( tools_menu.add_command(
label="Manage Pathologies...", command=self._open_pathology_manager label="Manage Pathologies...",
command=self._open_pathology_manager,
accelerator="Ctrl+P",
) )
tools_menu.add_command( tools_menu.add_command(
label="Manage Medicines...", command=self._open_medicine_manager label="Manage Medicines...",
command=self._open_medicine_manager,
accelerator="Ctrl+M",
) )
tools_menu.add_separator()
tools_menu.add_command(
label="Clear Entries", command=self._clear_entries, accelerator="Ctrl+N"
)
tools_menu.add_command(
label="Refresh Data", command=self.refresh_data_display, accelerator="F5"
)
# Help menu
help_menu = tk.Menu(menubar, tearoff=0)
menubar.add_cascade(label="Help", menu=help_menu)
help_menu.add_command(
label="Keyboard Shortcuts",
command=self._show_keyboard_shortcuts,
accelerator="F1",
)
help_menu.add_command(label="About", command=self._show_about_dialog)
def _setup_keyboard_shortcuts(self) -> None:
"""Set up keyboard shortcuts for common actions."""
# Bind keyboard shortcuts to the main window
self.root.bind("<Control-s>", lambda e: self.add_new_entry())
self.root.bind("<Control-S>", lambda e: self.add_new_entry())
self.root.bind("<Control-q>", lambda e: self.handle_window_closing())
self.root.bind("<Control-Q>", lambda e: self.handle_window_closing())
self.root.bind("<Control-e>", lambda e: self._open_export_window())
self.root.bind("<Control-E>", lambda e: self._open_export_window())
self.root.bind("<Control-n>", lambda e: self._clear_entries())
self.root.bind("<Control-N>", lambda e: self._clear_entries())
self.root.bind("<Control-r>", lambda e: self.refresh_data_display())
self.root.bind("<Control-R>", lambda e: self.refresh_data_display())
self.root.bind("<F5>", lambda e: self.refresh_data_display())
self.root.bind("<Control-m>", lambda e: self._open_medicine_manager())
self.root.bind("<Control-M>", lambda e: self._open_medicine_manager())
self.root.bind("<Control-p>", lambda e: self._open_pathology_manager())
self.root.bind("<Control-P>", lambda e: self._open_pathology_manager())
self.root.bind("<Delete>", lambda e: self._delete_selected_entry())
self.root.bind("<Escape>", lambda e: self._clear_selection())
self.root.bind("<F1>", lambda e: self._show_keyboard_shortcuts())
# Make the window focusable so it can receive key events
self.root.focus_set()
logger.info("Keyboard shortcuts configured:")
logger.info(" Ctrl+S: Save/Add new entry")
logger.info(" Ctrl+Q: Quit application")
logger.info(" Ctrl+E: Export data")
logger.info(" Ctrl+N: Clear entries")
logger.info(" Ctrl+R/F5: Refresh data")
logger.info(" Ctrl+M: Manage medicines")
logger.info(" Ctrl+P: Manage pathologies")
logger.info(" Delete: Delete selected entry")
logger.info(" Escape: Clear selection")
logger.info(" F1: Show keyboard shortcuts help")
def _show_keyboard_shortcuts(self) -> None:
"""Show a dialog with keyboard shortcuts information."""
shortcuts_text = """Keyboard Shortcuts:
File Operations:
• Ctrl+S: Save/Add new entry
• Ctrl+Q: Quit application
• Ctrl+E: Export data
Data Management:
• Ctrl+N: Clear entries
• Ctrl+R / F5: Refresh data
Window Management:
• Ctrl+M: Manage medicines
• Ctrl+P: Manage pathologies
Table Operations:
• Delete: Delete selected entry
• Escape: Clear selection
• Double-click: Edit entry
Help:
• F1: Show this help dialog"""
messagebox.showinfo("Keyboard Shortcuts", shortcuts_text, parent=self.root)
def _show_about_dialog(self) -> None:
"""Show about dialog."""
about_text = """TheChart - Medication Tracker
A simple application for tracking medications and pathologies.
Features:
• Add daily medication and pathology entries
• Visual graphs and charts
• Data export capabilities
• Keyboard shortcuts for efficiency
Use Ctrl+S to save entries and Ctrl+Q to quit."""
messagebox.showinfo("About TheChart", about_text, parent=self.root)
def _open_export_window(self) -> None:
"""Open the export window."""
self.ui_manager.update_status("Opening export window", "info")
ExportWindow(self.root, self.export_manager)
def _open_pathology_manager(self) -> None: def _open_pathology_manager(self) -> None:
"""Open the pathology management window.""" """Open the pathology management window."""
self.ui_manager.update_status("Opening pathology manager", "info")
PathologyManagementWindow( PathologyManagementWindow(
self.root, self.pathology_manager, self._refresh_ui_after_config_change self.root, self.pathology_manager, self._refresh_ui_after_config_change
) )
def _open_medicine_manager(self) -> None: def _open_medicine_manager(self) -> None:
"""Open the medicine management window.""" """Open the medicine management window."""
self.ui_manager.update_status("Opening medicine manager", "info")
MedicineManagementWindow( MedicineManagementWindow(
self.root, self.medicine_manager, self._refresh_ui_after_config_change self.root, self.medicine_manager, self._refresh_ui_after_config_change
) )
def _refresh_ui_after_config_change(self) -> None: def _refresh_ui_after_config_change(self) -> None:
"""Refresh UI components after pathology or medicine configuration changes.""" """Refresh UI components after pathology or medicine configuration changes."""
self.ui_manager.update_status(
"Refreshing UI after configuration change", "info"
)
# Clear caches in optimized data manager
if hasattr(self.data_manager, "_invalidate_cache"):
self.data_manager._invalidate_cache()
self.data_manager._headers_cache = None
self.data_manager._dtype_cache = None
# Recreate the input frame with new pathologies and medicines # Recreate the input frame with new pathologies and medicines
self.input_frame.destroy() self.input_frame.destroy()
input_ui: dict[str, Any] = self.ui_manager.create_input_frame( input_ui: dict[str, Any] = self.ui_manager.create_input_frame(
@@ -164,12 +341,12 @@ class MedTrackerApp:
self.input_frame, self.input_frame,
[ [
{ {
"text": "Add Entry", "text": "Add Entry (Ctrl+S)",
"command": self.add_new_entry, "command": self.add_new_entry,
"fill": "both", "fill": "both",
"expand": True, "expand": True,
}, },
{"text": "Quit", "command": self.handle_window_closing}, {"text": "Quit (Ctrl+Q)", "command": self.handle_window_closing},
], ],
) )
@@ -184,14 +361,59 @@ class MedTrackerApp:
# Refresh data display # Refresh data display
self.refresh_data_display() self.refresh_data_display()
# Update status to show completion
self.ui_manager.update_status("UI refreshed successfully", "success")
def _delete_selected_entry(self) -> None:
"""Delete the currently selected entry in the table."""
selection = self.tree.selection()
if not selection:
self.ui_manager.update_status("No entry selected for deletion", "warning")
return
item_id = selection[0]
item_values = self.tree.item(item_id, "values")
if messagebox.askyesno(
"Delete Entry",
f"Are you sure you want to delete the entry for {item_values[0]}?",
parent=self.root,
):
date: str = item_values[0]
logger.debug(f"Deleting entry with date={date}")
self.ui_manager.update_status("Deleting entry...", "info")
if self.data_manager.delete_entry(date):
self.ui_manager.update_status("Entry deleted successfully!", "success")
messagebox.showinfo(
"Success", "Entry deleted successfully!", parent=self.root
)
self.refresh_data_display()
else:
self.ui_manager.update_status("Failed to delete entry", "error")
messagebox.showerror(
"Error", "Failed to delete entry", parent=self.root
)
def _clear_selection(self) -> None:
"""Clear the current selection in the table."""
if self.tree.selection():
self.tree.selection_remove(self.tree.selection())
self.ui_manager.update_status("Selection cleared", "info")
def handle_double_click(self, event: tk.Event) -> None: def handle_double_click(self, event: tk.Event) -> None:
"""Handle double-click event to edit an entry.""" """Handle double-click event to edit an entry."""
logger.debug("Double-click event triggered on treeview.") logger.debug("Double-click event triggered on treeview.")
if len(self.tree.get_children()) > 0: if len(self.tree.get_children()) > 0:
item_id = self.tree.selection()[0] item_id = self.tree.selection()[0]
item_values = self.tree.item(item_id, "values") item_values = self.tree.item(item_id, "values")
self.ui_manager.update_status(
f"Opening entry for {item_values[0]} for editing", "info"
)
logger.debug(f"Editing item_id={item_id}, values={item_values}") logger.debug(f"Editing item_id={item_id}, values={item_values}")
self._create_edit_window(item_id, item_values) self._create_edit_window(item_id, item_values)
else:
self.ui_manager.update_status("No entries to edit", "warning")
def _create_edit_window(self, item_id: str, values: tuple[str, ...]) -> None: def _create_edit_window(self, item_id: str, values: tuple[str, ...]) -> None:
"""Create a new Toplevel window for editing an entry.""" """Create a new Toplevel window for editing an entry."""
@@ -293,8 +515,10 @@ class MedTrackerApp:
values.append(note) values.append(note)
self.ui_manager.update_status("Saving changes...", "info")
if self.data_manager.update_entry(original_date, values): if self.data_manager.update_entry(original_date, values):
edit_win.destroy() edit_win.destroy()
self.ui_manager.update_status("Entry updated successfully!", "success")
messagebox.showinfo( messagebox.showinfo(
"Success", "Entry updated successfully!", parent=self.root "Success", "Entry updated successfully!", parent=self.root
) )
@@ -304,6 +528,7 @@ class MedTrackerApp:
# Check if it's a duplicate date issue # Check if it's a duplicate date issue
df = self.data_manager.load_data() df = self.data_manager.load_data()
if original_date != date and not df.empty and date in df["date"].values: if original_date != date and not df.empty and date in df["date"].values:
self.ui_manager.update_status("Duplicate date found", "error")
messagebox.showerror( messagebox.showerror(
"Error", "Error",
f"An entry for date '{date}' already exists. " f"An entry for date '{date}' already exists. "
@@ -311,6 +536,7 @@ class MedTrackerApp:
parent=edit_win, parent=edit_win,
) )
else: else:
self.ui_manager.update_status("Failed to save changes", "error")
messagebox.showerror("Error", "Failed to save changes", parent=edit_win) messagebox.showerror("Error", "Failed to save changes", parent=edit_win)
def handle_window_closing(self) -> None: def handle_window_closing(self) -> None:
@@ -355,10 +581,13 @@ class MedTrackerApp:
# Check if date is empty # Check if date is empty
if not self.date_var.get().strip(): if not self.date_var.get().strip():
self.ui_manager.update_status("Please enter a date", "error")
messagebox.showerror("Error", "Please enter a date.", parent=self.root) messagebox.showerror("Error", "Please enter a date.", parent=self.root)
return return
self.ui_manager.update_status("Adding new entry...", "info")
if self.data_manager.add_entry(entry): if self.data_manager.add_entry(entry):
self.ui_manager.update_status("Entry added successfully!", "success")
messagebox.showinfo( messagebox.showinfo(
"Success", "Entry added successfully!", parent=self.root "Success", "Entry added successfully!", parent=self.root
) )
@@ -368,6 +597,7 @@ class MedTrackerApp:
# Check if it's a duplicate date by trying to load existing data # Check if it's a duplicate date by trying to load existing data
df = self.data_manager.load_data() df = self.data_manager.load_data()
if not df.empty and self.date_var.get() in df["date"].values: if not df.empty and self.date_var.get() in df["date"].values:
self.ui_manager.update_status("Duplicate entry found", "error")
messagebox.showerror( messagebox.showerror(
"Error", "Error",
f"An entry for date '{self.date_var.get()}' already exists. " f"An entry for date '{self.date_var.get()}' already exists. "
@@ -375,6 +605,7 @@ class MedTrackerApp:
parent=self.root, parent=self.root,
) )
else: else:
self.ui_manager.update_status("Failed to add entry", "error")
messagebox.showerror("Error", "Failed to add entry", parent=self.root) messagebox.showerror("Error", "Failed to add entry", parent=self.root)
def _delete_entry(self, edit_win: tk.Toplevel, item_id: str) -> None: def _delete_entry(self, edit_win: tk.Toplevel, item_id: str) -> None:
@@ -389,13 +620,16 @@ class MedTrackerApp:
date: str = self.tree.item(item_id, "values")[0] date: str = self.tree.item(item_id, "values")[0]
logger.debug(f"Deleting entry with date={date}") logger.debug(f"Deleting entry with date={date}")
self.ui_manager.update_status("Deleting entry...", "info")
if self.data_manager.delete_entry(date): if self.data_manager.delete_entry(date):
edit_win.destroy() edit_win.destroy()
self.ui_manager.update_status("Entry deleted successfully!", "success")
messagebox.showinfo( messagebox.showinfo(
"Success", "Entry deleted successfully!", parent=self.root "Success", "Entry deleted successfully!", parent=self.root
) )
self.refresh_data_display() self.refresh_data_display()
else: else:
self.ui_manager.update_status("Failed to delete entry", "error")
messagebox.showerror("Error", "Failed to delete entry", parent=edit_win) messagebox.showerror("Error", "Failed to delete entry", parent=edit_win)
def _clear_entries(self) -> None: def _clear_entries(self) -> None:
@@ -412,37 +646,57 @@ class MedTrackerApp:
"""Load data from the CSV file into the table and graph.""" """Load data from the CSV file into the table and graph."""
logger.debug("Loading data from CSV.") logger.debug("Loading data from CSV.")
# Clear existing data in the treeview # Clear existing data in the treeview efficiently
for i in self.tree.get_children(): children = self.tree.get_children()
self.tree.delete(i) if children:
self.tree.delete(*children)
# Load data from the CSV file try:
df: pd.DataFrame = self.data_manager.load_data() # Load data from the CSV file
df: pd.DataFrame = self.data_manager.load_data()
# Update the treeview with the data # Update the treeview with the data
if not df.empty: if not df.empty:
# Build display columns dynamically (exclude dose columns for table view) # Build display columns dynamically
display_columns = ["date", "depression", "anxiety", "sleep", "appetite"] # (exclude dose columns for table view)
display_columns = ["date"]
# Add medicine columns (without dose columns) # Add pathology columns
for medicine_key in self.medicine_manager.get_medicine_keys(): for pathology_key in self.pathology_manager.get_pathology_keys():
display_columns.append(medicine_key) display_columns.append(pathology_key)
display_columns.append("note") # Add medicine columns (without dose columns)
for medicine_key in self.medicine_manager.get_medicine_keys():
display_columns.append(medicine_key)
# Filter to only the columns we want to display display_columns.append("note")
if all(col in df.columns for col in display_columns):
display_df = df[display_columns] # Filter to only the columns we want to display
if all(col in df.columns for col in display_columns):
display_df = df[display_columns]
else:
# Fallback - just use all columns
display_df = df
# Batch insert for better performance
for _index, row in display_df.iterrows():
self.tree.insert(parent="", index="end", values=list(row))
logger.debug(f"Loaded {len(display_df)} entries into treeview.")
# Update the graph
self.graph_manager.update_graph(df)
# Update status bar with file info
entry_count = len(df) if not df.empty else 0
self.ui_manager.update_file_info(self.filename, entry_count)
if entry_count == 0:
self.ui_manager.update_status("No data to display", "warning")
else: else:
# Fallback - just use all columns self.ui_manager.update_status("Data loaded successfully", "success")
display_df = df
for _index, row in display_df.iterrows(): except Exception as e:
self.tree.insert(parent="", index="end", values=list(row)) logger.error(f"Error loading data: {e}")
logger.debug(f"Loaded {len(display_df)} entries into treeview.") self.ui_manager.update_status(f"Error loading data: {str(e)}", "error")
# Update the graph
self.graph_manager.update_graph(df)
if __name__ == "__main__": if __name__ == "__main__":
+134 -344
View File
@@ -28,6 +28,11 @@ class UIManager:
self.medicine_manager = medicine_manager self.medicine_manager = medicine_manager
self.pathology_manager = pathology_manager self.pathology_manager = pathology_manager
# Status bar attributes
self.status_bar: tk.Frame | None = None
self.status_label: tk.Label | None = None
self.file_info_label: tk.Label | None = None
def setup_application_icon(self, img_path: str) -> bool: def setup_application_icon(self, img_path: str) -> bool:
"""Set up the application icon.""" """Set up the application icon."""
try: try:
@@ -297,6 +302,103 @@ class UIManager:
return button_frame return button_frame
def create_status_bar(self, parent_frame: tk.Widget) -> tk.Frame:
"""Create and configure the status bar at the bottom of the application."""
# Create the status bar frame
self.status_bar = tk.Frame(parent_frame, relief=tk.SUNKEN, bd=1)
self.status_bar.grid(row=2, column=0, columnspan=2, sticky="ew", padx=5, pady=2)
# Configure the parent to make the status bar stretch
parent_frame.grid_columnconfigure(0, weight=1)
# Create status message label (left side)
self.status_label = tk.Label(
self.status_bar,
text="Ready",
anchor=tk.W,
font=("TkDefaultFont", 9),
padx=10,
pady=2,
)
self.status_label.pack(side=tk.LEFT, fill=tk.X, expand=True)
# Create file info label (right side)
self.file_info_label = tk.Label(
self.status_bar,
text="",
anchor=tk.E,
font=("TkDefaultFont", 9),
padx=10,
pady=2,
)
self.file_info_label.pack(side=tk.RIGHT)
return self.status_bar
def update_status(self, message: str, message_type: str = "info") -> None:
"""
Update the status bar with a message.
Args:
message: The message to display
message_type: Type of message ('info', 'success', 'warning', 'error')
"""
if not self.status_label:
return
# Color mapping for different message types
colors = {
"info": "#000000", # Black
"success": "#28A745", # Green
"warning": "#FFC107", # Yellow/Orange
"error": "#DC3545", # Red
}
color = colors.get(message_type, "#000000")
self.status_label.config(text=message, fg=color)
# Clear the message after 5 seconds for non-info messages
if message_type != "info":
self.root.after(5000, lambda: self.update_status("Ready", "info"))
def update_file_info(self, filename: str, entry_count: int = 0) -> None:
"""
Update the file information in the status bar.
Args:
filename: Name of the current data file
entry_count: Number of entries in the file
"""
if not self.file_info_label:
return
file_display = os.path.basename(filename) if filename else "No file"
info_text = f"{file_display}"
if entry_count > 0:
info_text += f" ({entry_count} entries)"
self.file_info_label.config(text=info_text)
def show_status_message(self, message: str, duration: int = 3000) -> None:
"""
Show a temporary status message for a specific duration.
Args:
message: The message to display
duration: How long to show the message in milliseconds
"""
if not self.status_label:
return
original_text = self.status_label.cget("text")
original_color = self.status_label.cget("fg")
self.status_label.config(text=message, fg="#2E86AB")
self.root.after(
duration,
lambda: self.status_label.config(text=original_text, fg=original_color),
)
def create_edit_window( def create_edit_window(
self, values: tuple[str, ...], callbacks: dict[str, Callable] self, values: tuple[str, ...], callbacks: dict[str, Callable]
) -> tk.Toplevel: ) -> tk.Toplevel:
@@ -417,8 +519,8 @@ class UIManager:
# Extract note (should be the last value) # Extract note (should be the last value)
note = values_list[-1] if len(values_list) > 0 else "" note = values_list[-1] if len(values_list) > 0 else ""
# Create improved UI sections dynamically # Create improved UI sections
vars_dict = self._create_edit_ui_dynamic( vars_dict = self._create_edit_ui(
main_container, main_container,
date, date,
pathology_values, pathology_values,
@@ -443,7 +545,7 @@ class UIManager:
return edit_win return edit_win
def _create_edit_ui_dynamic( def _create_edit_ui(
self, self,
parent: ttk.Frame, parent: ttk.Frame,
date: str, date: str,
@@ -500,7 +602,7 @@ class UIManager:
meds_frame.grid_columnconfigure(0, weight=1) meds_frame.grid_columnconfigure(0, weight=1)
# Create medicine checkboxes dynamically # Create medicine checkboxes dynamically
med_vars = self._create_medicine_section_dynamic(meds_frame, medicine_values) med_vars = self._create_medicine_section(meds_frame, medicine_values)
vars_dict.update(med_vars) vars_dict.update(med_vars)
row += 1 row += 1
@@ -510,7 +612,7 @@ class UIManager:
dose_frame.grid(row=row, column=0, sticky="ew", pady=(0, 15)) dose_frame.grid(row=row, column=0, sticky="ew", pady=(0, 15))
dose_frame.grid_columnconfigure(0, weight=1) dose_frame.grid_columnconfigure(0, weight=1)
dose_vars = self._create_dose_tracking_dynamic(dose_frame, medicine_doses) dose_vars = self._create_dose_tracking(dose_frame, medicine_doses)
vars_dict.update(dose_vars) vars_dict.update(dose_vars)
row += 1 row += 1
@@ -532,6 +634,7 @@ class UIManager:
) )
note_text.grid(row=0, column=0, sticky="ew", padx=5, pady=5) note_text.grid(row=0, column=0, sticky="ew", padx=5, pady=5)
note_text.insert("1.0", str(note)) note_text.insert("1.0", str(note))
vars_dict["note_text"] = note_text # Store the widget for access during save
# Bind text widget to string var for easy access # Bind text widget to string var for easy access
def update_note(*args): def update_note(*args):
@@ -542,111 +645,6 @@ class UIManager:
return vars_dict return vars_dict
def _create_edit_ui(
self,
parent: ttk.Frame,
date: str,
dep: int,
anx: int,
slp: int,
app: int,
bup: int,
hydro: int,
gaba: int,
prop: int,
quet: int,
note: str,
dose_data: dict[str, str],
) -> dict[str, Any]:
"""Create UI layout for edit window with organized sections."""
vars_dict = {}
row = 0
# Header with entry date
header_frame = ttk.Frame(parent)
header_frame.grid(row=row, column=0, sticky="ew", pady=(0, 20))
header_frame.grid_columnconfigure(1, weight=1)
ttk.Label(
header_frame, text="Editing Entry for:", font=("TkDefaultFont", 12, "bold")
).grid(row=0, column=0, sticky="w")
vars_dict["date"] = tk.StringVar(value=str(date))
date_entry = ttk.Entry(
header_frame,
textvariable=vars_dict["date"],
font=("TkDefaultFont", 12),
width=15,
)
date_entry.grid(row=0, column=1, sticky="w", padx=(10, 0))
row += 1
# Symptoms section
symptoms_frame = ttk.LabelFrame(
parent, text="Daily Symptoms (0-10 scale)", padding="15"
)
symptoms_frame.grid(row=row, column=0, sticky="ew", pady=(0, 15))
symptoms_frame.grid_columnconfigure(1, weight=1)
# Create symptom scales with better layout
symptoms = [
("Depression", "depression", dep),
("Anxiety", "anxiety", anx),
("Sleep Quality", "sleep", slp),
("Appetite", "appetite", app),
]
for i, (label, key, value) in enumerate(symptoms):
self._create_symptom_scale(symptoms_frame, i, label, key, value, vars_dict)
row += 1
# Medications section
meds_frame = ttk.LabelFrame(parent, text="Medications Taken", padding="15")
meds_frame.grid(row=row, column=0, sticky="ew", pady=(0, 15))
meds_frame.grid_columnconfigure(0, weight=1)
# Create medicine checkboxes with better styling
med_vars = self._create_medicine_section(
meds_frame, bup, hydro, gaba, prop, quet
)
vars_dict.update(med_vars)
row += 1
# Dose tracking section
dose_frame = ttk.LabelFrame(parent, text="Dose Tracking", padding="15")
dose_frame.grid(row=row, column=0, sticky="ew", pady=(0, 15))
dose_frame.grid_columnconfigure(0, weight=1)
dose_vars = self._create_dose_tracking(dose_frame, dose_data)
vars_dict.update(dose_vars)
row += 1
# Notes section
notes_frame = ttk.LabelFrame(parent, text="Notes", padding="15")
notes_frame.grid(row=row, column=0, sticky="ew", pady=(0, 20))
notes_frame.grid_columnconfigure(0, weight=1)
vars_dict["note"] = tk.StringVar(value=str(note))
note_text = tk.Text(
notes_frame, height=4, wrap=tk.WORD, font=("TkDefaultFont", 10)
)
note_text.grid(row=0, column=0, sticky="ew")
note_text.insert(1.0, str(note))
vars_dict["note_text"] = note_text
# Add scrollbar for notes
note_scroll = ttk.Scrollbar(
notes_frame, orient="vertical", command=note_text.yview
)
note_scroll.grid(row=0, column=1, sticky="ns")
note_text.configure(yscrollcommand=note_scroll.set)
return vars_dict
def _create_symptom_scale( def _create_symptom_scale(
self, self,
parent: ttk.Frame, parent: ttk.Frame,
@@ -733,91 +731,6 @@ class UIManager:
scale.bind("<KeyRelease>", update_value_label) scale.bind("<KeyRelease>", update_value_label)
update_value_label() # Set initial color update_value_label() # Set initial color
def _create_enhanced_symptom_scale(
self,
parent: ttk.Frame,
row: int,
label: str,
key: str,
value: int,
vars_dict: dict[str, tk.IntVar],
) -> None:
"""Create enhanced symptom scale for new entry form (like edit window)."""
# Ensure value is properly converted
try:
value = int(float(value)) if value not in ["", None] else 0
except (ValueError, TypeError):
value = 0
# Label
label_widget = ttk.Label(
parent, text=f"{label} (0-10):", font=("TkDefaultFont", 10, "bold")
)
label_widget.grid(row=row, column=0, sticky="w", padx=5, pady=8)
# Scale container
scale_container = ttk.Frame(parent)
scale_container.grid(row=row, column=1, sticky="ew", padx=(20, 5), pady=8)
scale_container.grid_columnconfigure(0, weight=1)
# Scale with value labels
scale_frame = ttk.Frame(scale_container)
scale_frame.grid(row=0, column=0, sticky="ew")
scale_frame.grid_columnconfigure(1, weight=1)
# Current value display
value_label = ttk.Label(
scale_frame,
text=str(value),
font=("TkDefaultFont", 12, "bold"),
foreground="#2E86AB",
width=3,
)
value_label.grid(row=0, column=0, padx=(0, 10))
# Scale widget
scale = ttk.Scale(
scale_frame,
from_=0,
to=10,
variable=vars_dict[key],
orient=tk.HORIZONTAL,
length=250, # Slightly smaller than edit window to fit better
)
scale.grid(row=0, column=1, sticky="ew")
# Scale labels (0, 5, 10)
labels_frame = ttk.Frame(scale_container)
labels_frame.grid(row=1, column=0, sticky="ew", pady=(5, 0))
ttk.Label(labels_frame, text="0", font=("TkDefaultFont", 8)).grid(
row=0, column=0, sticky="w"
)
labels_frame.grid_columnconfigure(1, weight=1)
ttk.Label(labels_frame, text="5", font=("TkDefaultFont", 8)).grid(
row=0, column=1
)
ttk.Label(labels_frame, text="10", font=("TkDefaultFont", 8)).grid(
row=0, column=2, sticky="e"
)
# Update label when scale changes
def update_value_label(event=None):
current_val = vars_dict[key].get()
value_label.configure(text=str(current_val))
# Change color based on value
if current_val <= 3:
value_label.configure(foreground="#28A745") # Green for low/good
elif current_val <= 6:
value_label.configure(foreground="#FFC107") # Yellow for medium
else:
value_label.configure(foreground="#DC3545") # Red for high/bad
scale.bind("<Motion>", update_value_label)
scale.bind("<ButtonRelease-1>", update_value_label)
scale.bind("<KeyRelease>", update_value_label)
update_value_label() # Set initial color
def _create_enhanced_pathology_scale( def _create_enhanced_pathology_scale(
self, self,
parent: ttk.Frame, parent: ttk.Frame,
@@ -927,153 +840,6 @@ class UIManager:
update_value_label_pathology() # Set initial color update_value_label_pathology() # Set initial color
def _create_medicine_section( def _create_medicine_section(
self, parent: ttk.Frame, bup: int, hydro: int, gaba: int, prop: int, quet: int
) -> dict[str, tk.IntVar]:
"""Create medicine checkboxes with organized layout."""
vars_dict = {}
# Create a grid layout for medicines
medicines = [
("bupropion", bup, "Bupropion", "150/300 mg", "#E8F4FD"),
("hydroxyzine", hydro, "Hydroxyzine", "25 mg", "#FFF2E8"),
("gabapentin", gaba, "Gabapentin", "100 mg", "#F0F8E8"),
("propranolol", prop, "Propranolol", "10 mg", "#FCE8F3"),
("quetiapine", quet, "Quetiapine", "25 mg", "#E8F0FF"),
]
# Create medicine cards in a 2-column layout
for i, (key, value, name, dose, _bg_color) in enumerate(medicines):
row = i // 2
col = i % 2
# Medicine card frame
med_card = ttk.Frame(parent, relief="solid", borderwidth=1)
med_card.grid(row=row, column=col, sticky="ew", padx=5, pady=5)
parent.grid_columnconfigure(col, weight=1)
vars_dict[key] = tk.IntVar(value=int(value))
# Checkbox with medicine name
check_frame = ttk.Frame(med_card)
check_frame.pack(fill="x", padx=10, pady=8)
checkbox = ttk.Checkbutton(
check_frame,
text=f"{name} ({dose})",
variable=vars_dict[key],
style="Medicine.TCheckbutton",
)
checkbox.pack(anchor="w")
return vars_dict
def _create_dose_tracking(
self, parent: ttk.Frame, dose_data: dict[str, str]
) -> dict[str, Any]:
"""Create dose tracking interface."""
vars_dict = {}
# Create notebook for organized dose tracking
notebook = ttk.Notebook(parent)
notebook.pack(fill="both", expand=True)
medicines = [
("bupropion", "Bupropion"),
("hydroxyzine", "Hydroxyzine"),
("gabapentin", "Gabapentin"),
("propranolol", "Propranolol"),
("quetiapine", "Quetiapine"),
]
for med_key, med_name in medicines:
# Create tab for each medicine
tab_frame = ttk.Frame(notebook)
notebook.add(tab_frame, text=med_name)
# Configure tab layout
tab_frame.grid_columnconfigure(0, weight=1)
# Quick dose entry section
entry_frame = ttk.LabelFrame(tab_frame, text="Add New Dose", padding="10")
entry_frame.grid(row=0, column=0, sticky="ew", padx=10, pady=5)
entry_frame.grid_columnconfigure(1, weight=1)
ttk.Label(entry_frame, text="Dose amount:").grid(
row=0, column=0, sticky="w"
)
dose_entry_var = tk.StringVar()
vars_dict[f"{med_key}_entry_var"] = dose_entry_var
dose_entry = ttk.Entry(entry_frame, textvariable=dose_entry_var, width=15)
dose_entry.grid(row=0, column=1, sticky="w", padx=(10, 10))
# Quick dose buttons
quick_frame = ttk.Frame(entry_frame)
quick_frame.grid(row=0, column=2, sticky="w")
# Common dose amounts (customize per medicine)
quick_doses = self._get_quick_doses(med_key)
for i, dose in enumerate(quick_doses):
ttk.Button(
quick_frame,
text=dose,
width=8,
command=lambda d=dose, var=dose_entry_var: var.set(d),
).grid(row=0, column=i, padx=2)
# Take dose button
def create_take_dose_command(med_name, entry_var, med_key):
def take_dose():
self._take_dose(med_name, entry_var, med_key, vars_dict)
return take_dose
take_button = ttk.Button(
entry_frame,
text=f"Take {med_name}",
style="Accent.TButton",
command=create_take_dose_command(med_name, dose_entry_var, med_key),
)
take_button.grid(row=1, column=0, columnspan=3, pady=(10, 0), sticky="ew")
# Dose history section
history_frame = ttk.LabelFrame(
tab_frame, text="Today's Doses", padding="10"
)
history_frame.grid(row=1, column=0, sticky="ew", padx=10, pady=5)
history_frame.grid_columnconfigure(0, weight=1)
# Dose history display with fixed height to prevent excessive expansion
dose_text = tk.Text(
history_frame,
height=4, # Reduced height to fit better in scrollable window
wrap=tk.WORD,
font=("Consolas", 10),
state="normal", # Start enabled
)
dose_text.grid(row=0, column=0, sticky="ew")
# Store raw dose string in a variable
doses_str = dose_data.get(med_key, "")
dose_str_var = tk.StringVar(value=doses_str)
vars_dict[f"{med_key}_doses_str"] = dose_str_var
# Populate with existing doses
self._populate_dose_history(dose_text, dose_str_var.get())
vars_dict[f"{med_key}_doses_text"] = dose_text
# Scrollbar for dose history
dose_scroll = ttk.Scrollbar(
history_frame, orient="vertical", command=dose_text.yview
)
dose_scroll.grid(row=0, column=1, sticky="ns")
dose_text.configure(yscrollcommand=dose_scroll.set)
return vars_dict
def _create_medicine_section_dynamic(
self, parent: ttk.Frame, medicine_values: dict[str, int] self, parent: ttk.Frame, medicine_values: dict[str, int]
) -> dict[str, tk.IntVar]: ) -> dict[str, tk.IntVar]:
"""Create medicine checkboxes dynamically.""" """Create medicine checkboxes dynamically."""
@@ -1120,7 +886,7 @@ class UIManager:
return vars_dict return vars_dict
def _create_dose_tracking_dynamic( def _create_dose_tracking(
self, parent: ttk.Frame, medicine_doses: dict[str, str] self, parent: ttk.Frame, medicine_doses: dict[str, str]
) -> dict[str, Any]: ) -> dict[str, Any]:
"""Create dose tracking interface dynamically.""" """Create dose tracking interface dynamically."""
@@ -1398,9 +1164,33 @@ class UIManager:
# Get note text from Text widget # Get note text from Text widget
note_text_widget = vars_dict.get("note_text") note_text_widget = vars_dict.get("note_text")
self.logger.debug(f"note_text_widget found: {note_text_widget is not None}")
self.logger.debug(f"vars_dict keys: {list(vars_dict.keys())}")
note_content = "" note_content = ""
if note_text_widget: if note_text_widget:
note_content = note_text_widget.get(1.0, tk.END).strip() try:
note_content = note_text_widget.get(1.0, tk.END).strip()
self.logger.debug(f"Note content from widget: '{note_content}'")
except Exception as e:
self.logger.error(f"Error getting note from text widget: {e}")
# Fallback to StringVar
note_var = vars_dict.get("note")
if note_var:
note_content = note_var.get()
self.logger.debug(
f"Note content from StringVar fallback: '{note_content}'"
)
else:
# Fallback to StringVar if note_text widget not found
note_var = vars_dict.get("note")
if note_var:
note_content = note_var.get()
self.logger.debug(f"Note content from StringVar: '{note_content}'")
else:
self.logger.error("No note widget or StringVar found!")
self.logger.debug(f"Final note_content: '{note_content}'")
# Extract dose data dynamically from all medicines # Extract dose data dynamically from all medicines
dose_data = {} dose_data = {}
Generated
+64 -1
View File
@@ -20,6 +20,28 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/c5/55/51844dd50c4fc7a33b653bfaba4c2456f06955289ca770a5dbd5fd267374/cfgv-3.4.0-py2.py3-none-any.whl", hash = "sha256:b7265b1f29fd3316bfcd2b330d63d024f2bfd8bcb8b0272f8e19a504856c48f9", size = 7249, upload-time = "2023-08-12T20:38:16.269Z" }, { url = "https://files.pythonhosted.org/packages/c5/55/51844dd50c4fc7a33b653bfaba4c2456f06955289ca770a5dbd5fd267374/cfgv-3.4.0-py2.py3-none-any.whl", hash = "sha256:b7265b1f29fd3316bfcd2b330d63d024f2bfd8bcb8b0272f8e19a504856c48f9", size = 7249, upload-time = "2023-08-12T20:38:16.269Z" },
] ]
[[package]]
name = "charset-normalizer"
version = "3.4.2"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/e4/33/89c2ced2b67d1c2a61c19c6751aa8902d46ce3dacb23600a283619f5a12d/charset_normalizer-3.4.2.tar.gz", hash = "sha256:5baececa9ecba31eff645232d59845c07aa030f0c81ee70184a90d35099a0e63", size = 126367, upload-time = "2025-05-02T08:34:42.01Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/ea/12/a93df3366ed32db1d907d7593a94f1fe6293903e3e92967bebd6950ed12c/charset_normalizer-3.4.2-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:926ca93accd5d36ccdabd803392ddc3e03e6d4cd1cf17deff3b989ab8e9dbcf0", size = 199622, upload-time = "2025-05-02T08:32:56.363Z" },
{ url = "https://files.pythonhosted.org/packages/04/93/bf204e6f344c39d9937d3c13c8cd5bbfc266472e51fc8c07cb7f64fcd2de/charset_normalizer-3.4.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:eba9904b0f38a143592d9fc0e19e2df0fa2e41c3c3745554761c5f6447eedabf", size = 143435, upload-time = "2025-05-02T08:32:58.551Z" },
{ url = "https://files.pythonhosted.org/packages/22/2a/ea8a2095b0bafa6c5b5a55ffdc2f924455233ee7b91c69b7edfcc9e02284/charset_normalizer-3.4.2-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3fddb7e2c84ac87ac3a947cb4e66d143ca5863ef48e4a5ecb83bd48619e4634e", size = 153653, upload-time = "2025-05-02T08:33:00.342Z" },
{ url = "https://files.pythonhosted.org/packages/b6/57/1b090ff183d13cef485dfbe272e2fe57622a76694061353c59da52c9a659/charset_normalizer-3.4.2-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:98f862da73774290f251b9df8d11161b6cf25b599a66baf087c1ffe340e9bfd1", size = 146231, upload-time = "2025-05-02T08:33:02.081Z" },
{ url = "https://files.pythonhosted.org/packages/e2/28/ffc026b26f441fc67bd21ab7f03b313ab3fe46714a14b516f931abe1a2d8/charset_normalizer-3.4.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6c9379d65defcab82d07b2a9dfbfc2e95bc8fe0ebb1b176a3190230a3ef0e07c", size = 148243, upload-time = "2025-05-02T08:33:04.063Z" },
{ url = "https://files.pythonhosted.org/packages/c0/0f/9abe9bd191629c33e69e47c6ef45ef99773320e9ad8e9cb08b8ab4a8d4cb/charset_normalizer-3.4.2-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e635b87f01ebc977342e2697d05b56632f5f879a4f15955dfe8cef2448b51691", size = 150442, upload-time = "2025-05-02T08:33:06.418Z" },
{ url = "https://files.pythonhosted.org/packages/67/7c/a123bbcedca91d5916c056407f89a7f5e8fdfce12ba825d7d6b9954a1a3c/charset_normalizer-3.4.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:1c95a1e2902a8b722868587c0e1184ad5c55631de5afc0eb96bc4b0d738092c0", size = 145147, upload-time = "2025-05-02T08:33:08.183Z" },
{ url = "https://files.pythonhosted.org/packages/ec/fe/1ac556fa4899d967b83e9893788e86b6af4d83e4726511eaaad035e36595/charset_normalizer-3.4.2-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:ef8de666d6179b009dce7bcb2ad4c4a779f113f12caf8dc77f0162c29d20490b", size = 153057, upload-time = "2025-05-02T08:33:09.986Z" },
{ url = "https://files.pythonhosted.org/packages/2b/ff/acfc0b0a70b19e3e54febdd5301a98b72fa07635e56f24f60502e954c461/charset_normalizer-3.4.2-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:32fc0341d72e0f73f80acb0a2c94216bd704f4f0bce10aedea38f30502b271ff", size = 156454, upload-time = "2025-05-02T08:33:11.814Z" },
{ url = "https://files.pythonhosted.org/packages/92/08/95b458ce9c740d0645feb0e96cea1f5ec946ea9c580a94adfe0b617f3573/charset_normalizer-3.4.2-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:289200a18fa698949d2b39c671c2cc7a24d44096784e76614899a7ccf2574b7b", size = 154174, upload-time = "2025-05-02T08:33:13.707Z" },
{ url = "https://files.pythonhosted.org/packages/78/be/8392efc43487ac051eee6c36d5fbd63032d78f7728cb37aebcc98191f1ff/charset_normalizer-3.4.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:4a476b06fbcf359ad25d34a057b7219281286ae2477cc5ff5e3f70a246971148", size = 149166, upload-time = "2025-05-02T08:33:15.458Z" },
{ url = "https://files.pythonhosted.org/packages/44/96/392abd49b094d30b91d9fbda6a69519e95802250b777841cf3bda8fe136c/charset_normalizer-3.4.2-cp313-cp313-win32.whl", hash = "sha256:aaeeb6a479c7667fbe1099af9617c83aaca22182d6cf8c53966491a0f1b7ffb7", size = 98064, upload-time = "2025-05-02T08:33:17.06Z" },
{ url = "https://files.pythonhosted.org/packages/e9/b0/0200da600134e001d91851ddc797809e2fe0ea72de90e09bec5a2fbdaccb/charset_normalizer-3.4.2-cp313-cp313-win_amd64.whl", hash = "sha256:aa6af9e7d59f9c12b33ae4e9450619cf2488e2bbe9b44030905877f0b2324980", size = 105641, upload-time = "2025-05-02T08:33:18.753Z" },
{ url = "https://files.pythonhosted.org/packages/20/94/c5790835a017658cbfabd07f3bfb549140c3ac458cfc196323996b10095a/charset_normalizer-3.4.2-py3-none-any.whl", hash = "sha256:7f56930ab0abd1c45cd15be65cc741c28b1c9a34876ce8c17a2fa107810c0af0", size = 52626, upload-time = "2025-05-02T08:34:40.053Z" },
]
[[package]] [[package]]
name = "colorama" name = "colorama"
version = "0.4.6" version = "0.4.6"
@@ -258,6 +280,30 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/4c/fa/be89a49c640930180657482a74970cdcf6f7072c8d2471e1babe17a222dc/kiwisolver-1.4.8-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:be4816dc51c8a471749d664161b434912eee82f2ea66bd7628bd14583a833e85", size = 2349213, upload-time = "2024-12-24T18:30:40.019Z" }, { url = "https://files.pythonhosted.org/packages/4c/fa/be89a49c640930180657482a74970cdcf6f7072c8d2471e1babe17a222dc/kiwisolver-1.4.8-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:be4816dc51c8a471749d664161b434912eee82f2ea66bd7628bd14583a833e85", size = 2349213, upload-time = "2024-12-24T18:30:40.019Z" },
] ]
[[package]]
name = "lxml"
version = "6.0.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/c5/ed/60eb6fa2923602fba988d9ca7c5cdbd7cf25faa795162ed538b527a35411/lxml-6.0.0.tar.gz", hash = "sha256:032e65120339d44cdc3efc326c9f660f5f7205f3a535c1fdbf898b29ea01fb72", size = 4096938, upload-time = "2025-06-26T16:28:19.373Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/79/21/6e7c060822a3c954ff085e5e1b94b4a25757c06529eac91e550f3f5cd8b8/lxml-6.0.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:6da7cd4f405fd7db56e51e96bff0865b9853ae70df0e6720624049da76bde2da", size = 8414372, upload-time = "2025-06-26T16:26:39.079Z" },
{ url = "https://files.pythonhosted.org/packages/a4/f6/051b1607a459db670fc3a244fa4f06f101a8adf86cda263d1a56b3a4f9d5/lxml-6.0.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:b34339898bb556a2351a1830f88f751679f343eabf9cf05841c95b165152c9e7", size = 4593940, upload-time = "2025-06-26T16:26:41.891Z" },
{ url = "https://files.pythonhosted.org/packages/8e/74/dd595d92a40bda3c687d70d4487b2c7eff93fd63b568acd64fedd2ba00fe/lxml-6.0.0-cp313-cp313-manylinux2010_i686.manylinux2014_i686.manylinux_2_12_i686.manylinux_2_17_i686.whl", hash = "sha256:51a5e4c61a4541bd1cd3ba74766d0c9b6c12d6a1a4964ef60026832aac8e79b3", size = 5214329, upload-time = "2025-06-26T16:26:44.669Z" },
{ url = "https://files.pythonhosted.org/packages/52/46/3572761efc1bd45fcafb44a63b3b0feeb5b3f0066886821e94b0254f9253/lxml-6.0.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d18a25b19ca7307045581b18b3ec9ead2b1db5ccd8719c291f0cd0a5cec6cb81", size = 4947559, upload-time = "2025-06-28T18:47:31.091Z" },
{ url = "https://files.pythonhosted.org/packages/94/8a/5e40de920e67c4f2eef9151097deb9b52d86c95762d8ee238134aff2125d/lxml-6.0.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:d4f0c66df4386b75d2ab1e20a489f30dc7fd9a06a896d64980541506086be1f1", size = 5102143, upload-time = "2025-06-28T18:47:33.612Z" },
{ url = "https://files.pythonhosted.org/packages/7c/4b/20555bdd75d57945bdabfbc45fdb1a36a1a0ff9eae4653e951b2b79c9209/lxml-6.0.0-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9f4b481b6cc3a897adb4279216695150bbe7a44c03daba3c894f49d2037e0a24", size = 5021931, upload-time = "2025-06-26T16:26:47.503Z" },
{ url = "https://files.pythonhosted.org/packages/b6/6e/cf03b412f3763d4ca23b25e70c96a74cfece64cec3addf1c4ec639586b13/lxml-6.0.0-cp313-cp313-manylinux_2_27_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:8a78d6c9168f5bcb20971bf3329c2b83078611fbe1f807baadc64afc70523b3a", size = 5645469, upload-time = "2025-07-03T19:19:13.32Z" },
{ url = "https://files.pythonhosted.org/packages/d4/dd/39c8507c16db6031f8c1ddf70ed95dbb0a6d466a40002a3522c128aba472/lxml-6.0.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:2ae06fbab4f1bb7db4f7c8ca9897dc8db4447d1a2b9bee78474ad403437bcc29", size = 5247467, upload-time = "2025-06-26T16:26:49.998Z" },
{ url = "https://files.pythonhosted.org/packages/4d/56/732d49def0631ad633844cfb2664563c830173a98d5efd9b172e89a4800d/lxml-6.0.0-cp313-cp313-manylinux_2_31_armv7l.whl", hash = "sha256:1fa377b827ca2023244a06554c6e7dc6828a10aaf74ca41965c5d8a4925aebb4", size = 4720601, upload-time = "2025-06-26T16:26:52.564Z" },
{ url = "https://files.pythonhosted.org/packages/8f/7f/6b956fab95fa73462bca25d1ea7fc8274ddf68fb8e60b78d56c03b65278e/lxml-6.0.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:1676b56d48048a62ef77a250428d1f31f610763636e0784ba67a9740823988ca", size = 5060227, upload-time = "2025-06-26T16:26:55.054Z" },
{ url = "https://files.pythonhosted.org/packages/97/06/e851ac2924447e8b15a294855caf3d543424364a143c001014d22c8ca94c/lxml-6.0.0-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:0e32698462aacc5c1cf6bdfebc9c781821b7e74c79f13e5ffc8bfe27c42b1abf", size = 4790637, upload-time = "2025-06-26T16:26:57.384Z" },
{ url = "https://files.pythonhosted.org/packages/06/d4/fd216f3cd6625022c25b336c7570d11f4a43adbaf0a56106d3d496f727a7/lxml-6.0.0-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:4d6036c3a296707357efb375cfc24bb64cd955b9ec731abf11ebb1e40063949f", size = 5662049, upload-time = "2025-07-03T19:19:16.409Z" },
{ url = "https://files.pythonhosted.org/packages/52/03/0e764ce00b95e008d76b99d432f1807f3574fb2945b496a17807a1645dbd/lxml-6.0.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:7488a43033c958637b1a08cddc9188eb06d3ad36582cebc7d4815980b47e27ef", size = 5272430, upload-time = "2025-06-26T16:27:00.031Z" },
{ url = "https://files.pythonhosted.org/packages/5f/01/d48cc141bc47bc1644d20fe97bbd5e8afb30415ec94f146f2f76d0d9d098/lxml-6.0.0-cp313-cp313-win32.whl", hash = "sha256:5fcd7d3b1d8ecb91445bd71b9c88bdbeae528fefee4f379895becfc72298d181", size = 3612896, upload-time = "2025-06-26T16:27:04.251Z" },
{ url = "https://files.pythonhosted.org/packages/f4/87/6456b9541d186ee7d4cb53bf1b9a0d7f3b1068532676940fdd594ac90865/lxml-6.0.0-cp313-cp313-win_amd64.whl", hash = "sha256:2f34687222b78fff795feeb799a7d44eca2477c3d9d3a46ce17d51a4f383e32e", size = 4013132, upload-time = "2025-06-26T16:27:06.415Z" },
{ url = "https://files.pythonhosted.org/packages/b7/42/85b3aa8f06ca0d24962f8100f001828e1f1f1a38c954c16e71154ed7d53a/lxml-6.0.0-cp313-cp313-win_arm64.whl", hash = "sha256:21db1ec5525780fd07251636eb5f7acb84003e9382c72c18c542a87c416ade03", size = 3672642, upload-time = "2025-06-26T16:27:09.888Z" },
]
[[package]] [[package]]
name = "macholib" name = "macholib"
version = "1.16.3" version = "1.16.3"
@@ -653,6 +699,19 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/fa/de/02b54f42487e3d3c6efb3f89428677074ca7bf43aae402517bc7cca949f3/PyYAML-6.0.2-cp313-cp313-win_amd64.whl", hash = "sha256:8388ee1976c416731879ac16da0aff3f63b286ffdd57cdeb95f3f2e085687563", size = 156446, upload-time = "2024-08-06T20:33:04.33Z" }, { url = "https://files.pythonhosted.org/packages/fa/de/02b54f42487e3d3c6efb3f89428677074ca7bf43aae402517bc7cca949f3/PyYAML-6.0.2-cp313-cp313-win_amd64.whl", hash = "sha256:8388ee1976c416731879ac16da0aff3f63b286ffdd57cdeb95f3f2e085687563", size = 156446, upload-time = "2024-08-06T20:33:04.33Z" },
] ]
[[package]]
name = "reportlab"
version = "4.4.3"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "charset-normalizer" },
{ name = "pillow" },
]
sdist = { url = "https://files.pythonhosted.org/packages/2f/83/3d44b873fa71ddc7d323c577fe4cfb61e05b34d14e64b6a232f9cfbff89d/reportlab-4.4.3.tar.gz", hash = "sha256:073b0975dab69536acd3251858e6b0524ed3e087e71f1d0d1895acb50acf9c7b", size = 3887532, upload-time = "2025-07-23T11:18:23.799Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/52/c8/aaf4e08679e7b1dc896ad30de0d0527f0fd55582c2e6deee4f2cc899bf9f/reportlab-4.4.3-py3-none-any.whl", hash = "sha256:df905dc5ec5ddaae91fc9cb3371af863311271d555236410954961c5ee6ee1b5", size = 1953896, upload-time = "2025-07-23T11:18:20.572Z" },
]
[[package]] [[package]]
name = "ruff" name = "ruff"
version = "0.12.5" version = "0.12.5"
@@ -698,13 +757,15 @@ wheels = [
[[package]] [[package]]
name = "thechart" name = "thechart"
version = "1.3.4" version = "1.9.5"
source = { virtual = "." } source = { virtual = "." }
dependencies = [ dependencies = [
{ name = "colorlog" }, { name = "colorlog" },
{ name = "dotenv" }, { name = "dotenv" },
{ name = "lxml" },
{ name = "matplotlib" }, { name = "matplotlib" },
{ name = "pandas" }, { name = "pandas" },
{ name = "reportlab" },
{ name = "tk" }, { name = "tk" },
] ]
@@ -723,8 +784,10 @@ dev = [
requires-dist = [ requires-dist = [
{ name = "colorlog", specifier = ">=6.9.0" }, { name = "colorlog", specifier = ">=6.9.0" },
{ name = "dotenv", specifier = ">=0.9.9" }, { name = "dotenv", specifier = ">=0.9.9" },
{ name = "lxml", specifier = ">=6.0.0" },
{ name = "matplotlib", specifier = ">=3.10.3" }, { name = "matplotlib", specifier = ">=3.10.3" },
{ name = "pandas", specifier = ">=2.3.1" }, { name = "pandas", specifier = ">=2.3.1" },
{ name = "reportlab", specifier = ">=4.4.3" },
{ name = "tk", specifier = ">=0.1.0" }, { name = "tk", specifier = ">=0.1.0" },
] ]