feat: 1st skill impl

This commit is contained in:
insleker 2026-01-16 16:58:31 +08:00
parent df2e5b531e
commit 69c955fd57
16 changed files with 2466 additions and 2 deletions

1
.gitignore vendored
View File

@ -160,3 +160,4 @@ cython_debug/
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
uv.lock

185
README.md
View File

@ -1,3 +1,184 @@
# report_skill_expm
# Report Generation Skills Experiment
adopt claude skill to generate report experiment
This repository contains AI skills for automated report generation. Currently includes a weekly project report generator that transforms time tracking data into formatted management reports.
## Available Skills
### 📊 Week Report Generator (`week_report_gen`)
Automatically generates weekly project reports (項目週報) from exported Excel time tracking data.
**Features:**
- Reads cost report Excel exports from project management systems
- Aggregates work hours by person and project
- Generates formatted weekly reports following company templates
- Auto-populates team members, work hours, and progress notes
- Creates professional Excel output with proper formatting
**Use Cases:**
- Weekly project status reporting
- Time tracking data transformation
- Team productivity summaries
- Management reporting automation
**Quick Start:**
```bash
cd skills/week_report_gen
python generate_report.py
```
**Documentation:**
- [SKILL.md](skills/week_report_gen/SKILL.md) - Comprehensive skill documentation
- [README.md](skills/week_report_gen/README.md) - Usage guide and examples
- [QUICK_REFERENCE.md](skills/week_report_gen/QUICK_REFERENCE.md) - AI assistant reference
## Getting Started
### Prerequisites
```bash
# Create virtual environment and install dependencies
uv sync
# Activate virtual environment (optional - uv run handles this)
.venv\Scripts\activate # Windows
source .venv/bin/activate # Linux/Mac
```
> **💡 Tip**: This project uses `pyproject.toml` for reliable dependency management with uv.
> See [UV_SETUP_GUIDE.md](UV_SETUP_GUIDE.md) for detailed setup instructions and best practices.
### Using with AI Assistants
Simply tell your AI assistant (GitHub Copilot, Claude, etc.):
> "Generate a weekly report from the cost report file"
The AI will automatically:
1. Read the skill documentation
2. Process the input data
3. Generate a formatted report
4. Show you a summary
### Manual Usage
```python
from skills.week_report_gen.generate_report import generate_weekly_report
# Generate report
output_file, summary = generate_weekly_report(
input_file='path/to/cost-report.xls',
output_file='path/to/weekly-report.xlsx'
)
print(f"Report saved: {output_file}")
```
## Repository Structure
```
report_skill_expm/
├── README.md # This file
├── skills/
│ └── week_report_gen/ # Weekly report generator skill
│ ├── SKILL.md # Skill documentation
│ ├── README.md # User guide
│ ├── QUICK_REFERENCE.md # AI assistant reference
│ ├── generate_report.py # Main script
│ └── references/ # Sample files and templates
│ ├── cost-report-*.xls # Example input
│ ├── 項目週報-模板.xlsx # Standard template
│ └── 項目週報-*.xlsx # Example outputs
└── .venv/ # Virtual environment (created)
```
## Input & Output Examples
### Input: Cost Report
```
日期 使用者 活動 專案 單位
2026-01-12 ben sung Development masterXXX 8
2026-01-12 Ryan Hsueh - AXEL PLC 8
2026-01-13 傑 羅 Development CNC Library 移植 4
```
### Output: Weekly Report
```
弘訊科技股份有限公司
2026年度週報(01月12日-01月16日
專案名稱 參與人員 工時 本周主要進展
──────────────────────────────────────────────────
AXEL PLC Ryan Hsueh 48.0 -
masterXXX ben sung 15.0 Development
migrate to entry based sdo queue
CNC Library移植 傑 羅 8.0 Development
程式碼整理及重構
```
## Development
### Adding New Skills
1. Create a new directory under `skills/`
2. Add a `SKILL.md` file with comprehensive documentation
3. Implement the skill functionality
4. Add examples and tests
5. Update this README
### Testing
```bash
# Test the weekly report generator
cd skills/week_report_gen
python generate_report.py
```
## Use Cases
### 1. Weekly Team Reports
Transform time tracking exports into management-ready weekly reports automatically.
### 2. Project Status Updates
Quickly see which projects are active, who's working on them, and how many hours were invested.
### 3. Resource Allocation Analysis
Understand how team members' time is distributed across projects.
### 4. Management Reporting
Generate standardized reports for management review with minimal manual effort.
## Roadmap
Future skills being considered:
- **Monthly Summary Generator**: Aggregate weekly reports into monthly summaries
- **Project Timeline Generator**: Visualize project progress over time
- **Resource Utilization Report**: Analyze team member utilization rates
- **Cost Analysis Report**: Transform time data into cost estimates
- **Multi-team Comparison**: Compare metrics across different teams
## Contributing
Contributions welcome! To add a new skill:
1. Follow the existing skill structure
2. Provide comprehensive documentation
3. Include example files
4. Test thoroughly
5. Submit a pull request
## License
MIT License - See individual skill files for specific licensing information.
## Support
For questions or issues:
1. Check the skill-specific documentation in `skills/[skill_name]/`
2. Review example files in `references/` directories
3. Open an issue for bugs or feature requests
## Acknowledgments
This project demonstrates how AI skills can automate routine reporting tasks, saving time and reducing errors in data transformation and report generation workflows.

292
UV_SETUP_GUIDE.md Normal file
View File

@ -0,0 +1,292 @@
# Quick Start Guide for UV-based Setup
## Why UV + pyproject.toml?
**Reliable**: All dependencies locked to specific versions
**Fast**: UV is significantly faster than pip
**Reproducible**: Same environment across all machines
**Simple**: One command to set up everything
**Modern**: Using Python packaging best practices
## Installation
### First Time Setup
```bash
# Install uv (if not already installed)
# Windows (PowerShell)
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
# Linux/macOS
curl -LsSf https://astral.sh/uv/install.sh | sh
# Or with pip
pip install uv
```
### Project Setup
```bash
# Clone or navigate to the repository
cd report_skill_expm
# Create virtual environment and install all dependencies
uv sync
# That's it! All dependencies are now installed and locked
```
## Usage
### Option 1: Using `uv run` (Recommended)
No need to activate the virtual environment - uv handles it automatically:
```bash
# Run the example
uv run python example.py
# Run the report generator directly
uv run python skills/week_report_gen/generate_report.py
# Import and use in Python
uv run python -c "from skills.week_report_gen.generate_report import generate_weekly_report; print('Ready!')"
```
### Option 2: Traditional Virtual Environment
```bash
# Activate the virtual environment
.venv\Scripts\activate # Windows
source .venv/bin/activate # Linux/Mac
# Now you can run Python normally
python example.py
python skills/week_report_gen/generate_report.py
```
## What's in pyproject.toml?
```toml
[project]
name = "report-skill-expm"
version = "1.0.0"
requires-python = ">=3.9"
dependencies = [
"openpyxl>=3.1.0", # Excel file handling
"pandas>=2.0.0", # Data processing
"xlrd>=2.0.0", # Reading .xls files
]
[project.optional-dependencies]
dev = [
"pytest>=7.0.0", # Testing framework
"black>=23.0.0", # Code formatter
"flake8>=6.0.0", # Linter
]
```
## Common Commands
```bash
# Install/update dependencies
uv sync
# Install with dev dependencies
uv sync --extra dev
# Add a new dependency
uv add package-name
# Remove a dependency
uv remove package-name
# Update all dependencies
uv sync --upgrade
# Show installed packages
uv pip list
# Run any Python script
uv run python your_script.py
# Run a specific module
uv run python -m skills.week_report_gen.generate_report
# Start Python REPL with dependencies available
uv run python
```
## Benefits Over Manual pip Installation
### Before (Manual)
```bash
python -m venv .venv
.venv\Scripts\activate
pip install openpyxl pandas xlrd
# Need to remember all packages and versions
# No lock file - different versions on different machines
```
### After (UV + pyproject.toml)
```bash
uv sync
# Done! Everything locked and reproducible
```
## Dependency Management
### Adding Dependencies
```bash
# Add a runtime dependency
uv add requests
# Add a development dependency
uv add --dev pytest-cov
# Add with version constraint
uv add "pandas>=2.0,<3.0"
```
### Updating Dependencies
```bash
# Update all dependencies
uv sync --upgrade
# Update specific package
uv add --upgrade pandas
```
### Lock File
The `uv.lock` file (auto-generated) ensures:
- ✅ Exact versions are used across all environments
- ✅ Transitive dependencies are locked
- ✅ No "works on my machine" issues
- ✅ Fast, deterministic installs
**Commit `uv.lock` to version control!**
## Troubleshooting
### "uv: command not found"
Install uv first:
```bash
pip install uv
# or
curl -LsSf https://astral.sh/uv/install.sh | sh
```
### "No module named 'xxx'"
Make sure you've run `uv sync`:
```bash
uv sync
```
### Virtual Environment Not Found
Recreate it:
```bash
rm -rf .venv # or rmdir /s .venv on Windows
uv sync
```
### Import Errors
Use `uv run` to automatically activate the environment:
```bash
uv run python your_script.py
```
## CI/CD Integration
### GitHub Actions
```yaml
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.11'
- name: Install uv
run: pip install uv
- name: Install dependencies
run: uv sync
- name: Run tests
run: uv run pytest
```
### GitLab CI
```yaml
test:
script:
- pip install uv
- uv sync
- uv run pytest
```
## Migration from requirements.txt
If you have an old `requirements.txt`:
```bash
# Import from requirements.txt
uv add $(cat requirements.txt)
# Or manually add each package
uv add openpyxl pandas xlrd
```
## Best Practices
1. **Always commit `uv.lock`** - Ensures reproducible builds
2. **Use `uv run`** - Simplifies workflow, no activation needed
3. **Keep pyproject.toml clean** - Only list direct dependencies
4. **Use version constraints** - `>=3.1.0` not `==3.1.0`
5. **Separate dev dependencies** - Use `[project.optional-dependencies]`
## Comparison: pip vs uv
| Feature | pip | uv |
|---------|-----|-----|
| Speed | 🐌 Slow | 🚀 Fast (10-100x) |
| Lock file | requirements.txt (manual) | uv.lock (automatic) |
| Resolver | Sometimes inconsistent | Always consistent |
| Parallel installs | No | Yes |
| Built-in venv | Need separate commands | Integrated |
## Resources
- [UV Documentation](https://github.com/astral-sh/uv)
- [Python Packaging Guide](https://packaging.python.org/)
- [pyproject.toml Specification](https://peps.python.org/pep-0621/)
---
**Quick Reference Card**
```bash
# Setup
uv sync # Install everything
# Run
uv run python app.py # Execute with dependencies
# Manage
uv add pkg # Add dependency
uv remove pkg # Remove dependency
uv sync --upgrade # Update all
# Dev
uv sync --extra dev # Install dev dependencies
uv run pytest # Run tests
uv run black . # Format code
```

139
example.py Normal file
View File

@ -0,0 +1,139 @@
"""
Example: Generate Weekly Report
This script demonstrates how to use the week_report_gen skill
to generate a weekly report from a cost report Excel file.
"""
import os
import sys
# Add the skill directory to the path
skill_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'skills', 'week_report_gen')
sys.path.insert(0, skill_path)
from generate_report import generate_weekly_report
def main():
"""
Example: Generate a weekly report from the sample cost report.
"""
print("=" * 70)
print("Weekly Report Generator - Example")
print("=" * 70)
print()
# Define paths
base_dir = os.path.dirname(os.path.abspath(__file__))
skill_dir = os.path.join(base_dir, 'skills', 'week_report_gen')
input_file = os.path.join(
skill_dir,
'references',
'cost-report-2026-01-16-T-16-22-3620260116-7-1r1n4h.xls'
)
output_file = os.path.join(
skill_dir,
'references',
'項目週報-示例輸出-20260116.xlsx'
)
template_file = os.path.join(
skill_dir,
'references',
'項目週報-模板.xlsx'
)
# Verify input file exists
if not os.path.exists(input_file):
print(f"❌ Error: Input file not found: {input_file}")
return 1
print(f"📁 Input: {os.path.basename(input_file)}")
print(f"📁 Output: {os.path.basename(output_file)}")
print(f"📋 Template: {os.path.basename(template_file)}")
print()
print("-" * 70)
print()
try:
# Generate the report
output_path, summary_data = generate_weekly_report(
input_file=input_file,
output_file=output_file,
template_file=template_file if os.path.exists(template_file) else None,
team_name="智能控制組"
)
# Display results
print()
print("=" * 70)
print("📊 REPORT SUMMARY")
print("=" * 70)
print()
total_hours = summary_data['工時'].sum()
total_projects = len(summary_data)
print(f"Total Projects: {total_projects}")
print(f"Total Work Hours: {total_hours}")
print()
print("-" * 70)
print()
# Display each project
for idx, row in summary_data.iterrows():
print(f"🔹 {row['專案名稱']}")
print(f" Team: {row['參與人員']}")
print(f" Hours: {row['工時']}")
if row['本周主要進展'] and str(row['本周主要進展']) != 'nan':
progress_lines = str(row['本周主要進展']).split('\n')
print(f" Progress:")
for line in progress_lines:
if line.strip():
print(f"{line.strip()}")
print()
print("=" * 70)
print("✅ SUCCESS!")
print("=" * 70)
print()
print(f"Report saved to:")
print(f" {output_path}")
print()
print("📝 Next steps:")
print(" 1. Open the generated Excel file")
print(" 2. Review and edit the '本周主要進展' (progress) entries")
print(" 3. Fill in the '進度' (progress percentage) for each project")
print(" 4. Add '交付物' (deliverables) if any")
print(" 5. Indicate '代碼上傳' (code upload) status (Y/N)")
print(" 6. Fill in '下周計畫' (next week's plan)")
print()
return 0
except Exception as e:
print()
print("=" * 70)
print("❌ ERROR")
print("=" * 70)
print()
print(f"An error occurred while generating the report:")
print(f" {str(e)}")
print()
import traceback
print("Detailed error information:")
print("-" * 70)
traceback.print_exc()
print("-" * 70)
print()
return 1
if __name__ == "__main__":
sys.exit(main())

31
pyproject.toml Normal file
View File

@ -0,0 +1,31 @@
[project]
authors = [{ name = "insleker", email = "existedinnettw@gmail.com" }]
description = "AI skills for automated report generation from time tracking data"
license = { text = "MIT" }
name = "report-skill-expm"
readme = "README.md"
requires-python = ">=3.9"
version = "1.0.0"
dependencies = ["openpyxl>=3.1.0", "pandas>=2.0.0", "xlrd>=2.0.0"]
[project.optional-dependencies]
dev = ["pytest>=7.0.0", "black>=23.0.0", "flake8>=6.0.0"]
[project.scripts]
generate-weekly-report = "skills.week_report_gen.generate_report:main"
[build-system]
build-backend = "hatchling.build"
requires = ["hatchling"]
[tool.hatch.build.targets.wheel]
packages = ["skills"]
[tool.black]
line-length = 100
# target-version = ['py38', 'py39', 'py310', 'py311', 'py312']
[tool.pytest.ini_options]
python_files = ["test_*.py"]
testpaths = ["tests"]

View File

@ -0,0 +1,405 @@
# Weekly Report Generator Skill - Complete Guide
## 🎯 What This Skill Does
The **Weekly Report Generator** (`week_report_gen`) is an AI skill that automatically transforms time tracking data from project management systems into professional weekly project reports (項目週報).
### Key Benefits
**Saves Time**: Automates report generation from raw time tracking data
**Reduces Errors**: Eliminates manual data entry and calculation mistakes
**Consistent Format**: Uses company standard templates every time
**Smart Aggregation**: Automatically groups work by project and team member
**AI-Powered**: Works seamlessly with GitHub Copilot, Claude, and other AI assistants
---
## 📦 What's Included
```
skills/week_report_gen/
├── SKILL.md # Comprehensive technical documentation
├── README.md # User guide with examples
├── QUICK_REFERENCE.md # AI assistant reference guide
├── generate_report.py # Main Python script
└── references/
├── cost-report-*.xls # Example input file
├── 項目週報-模板.xlsx # Standard template
└── 項目週報-*.xlsx # Example outputs
```
---
## 🚀 Quick Start
### 1. Setup (One Time)
```bash
# From repository root: create venv and install all dependencies
uv sync
# Activate it (optional - uv run handles this automatically)
.venv\Scripts\activate # Windows
source .venv/bin/activate # Mac/Linux
```
### 2. Generate Your First Report
**Option A: Using AI Assistant** (Easiest)
Just say:
> "Generate a weekly report from my cost report file"
**Option B: Command Line**
```bash
# From repository root
uv run python skills/week_report_gen/generate_report.py
# Or navigate first
cd skills/week_report_gen
uv run python generate_report.py
```
**Option C: Python Script**
```python
from skills.week_report_gen.generate_report import generate_weekly_report
output_file, summary = generate_weekly_report(
input_file='cost-report.xls',
output_file='weekly-report.xlsx'
)
```
---
## 📊 Input → Output
### Input: Cost Report Excel
Raw time tracking data exported from your project management system.
| 日期 | 使用者 | 活動 | 專案 | 單位 |
|------|--------|------|------|------|
| 2026-01-12 | ben sung | Development | masterXXX | 8 |
| 2026-01-12 | Ryan Hsueh | - | AXEL PLC | 8 |
### Output: Weekly Report Excel
Formatted, professional report ready for management review.
| 專案名稱 | 參與人員 | 工時 | 本周主要進展 | 下周計畫 |
|----------|----------|------|--------------|----------|
| masterXXX | ben sung | 15.0 | Development<br>migrate to entry based sdo queue | _(fill in)_ |
| AXEL PLC | Ryan Hsueh | 48.0 | - | _(fill in)_ |
---
## 🎨 Key Features
### 1. Smart Data Aggregation
- Automatically sums hours by project and person
- Groups multiple entries from the same project
- Combines team members who worked on the same project
### 2. Auto-Population
**Automatically filled:**
- ✅ 專案名稱 (Project name)
- ✅ 參與人員 (Team members)
- ✅ 工時 (Total hours)
- ✅ 本周主要進展 (Progress notes from comments)
**Leave blank for manual input:**
- ⬜ 進度 (Progress percentage)
- ⬜ 交付物 (Deliverables)
- ⬜ 代碼上傳 (Code upload status)
- ⬜ 下周計畫 (Next week's plan)
### 3. Professional Formatting
- Company header and branding
- Proper column widths
- Header formatting with gray background
- Separator rows between projects
- Text wrapping for long entries
- Merged cells for titles
### 4. Date Range Detection
Automatically extracts the reporting period from the data:
```
2026年度週報(01月12日-01月16日
```
---
## 💡 Usage Examples
### Example 1: Basic Generation
```bash
# Navigate to skill directory
cd skills/week_report_gen
# Run with default settings (uses sample file)
python generate_report.py
# Output: 項目週報-智能控制組-20260116.xlsx
```
### Example 2: Custom Files
```bash
# Specify input and output files
python generate_report.py \
"path/to/your-cost-report.xls" \
"path/to/output-weekly-report.xlsx"
```
### Example 3: Python Integration
```python
from generate_report import generate_weekly_report
# Generate report for specific team
output, summary = generate_weekly_report(
input_file='data/cost-report.xls',
output_file='reports/weekly-20260116.xlsx',
template_file='templates/standard.xlsx',
team_name='研發部-AI組'
)
# View summary
print(f"Generated report with {len(summary)} projects")
print(f"Total hours: {summary['工時'].sum()}")
```
### Example 4: AI Assistant
```
You: "Generate a weekly report from cost-report-2026-01-16.xls for the AI team"
AI: "I'll generate the weekly report for the AI team.
[Processing...]
✓ Report generated successfully!
Summary of 5 projects:
- Project A (Team Member 1, Team Member 2, 32 hours)
- Project B (Team Member 3, 16 hours)
...
Report saved to: 項目週報-AI組-20260116.xlsx
Please review and fill in:
- Progress percentages
- Deliverables
- Next week's plan"
```
---
## 📋 After Report Generation
### Manual Steps Required
1. **Open the Excel file** in your spreadsheet application
2. **Review "本周主要進展" (Progress)**
- Check auto-generated progress notes
- Edit for clarity and completeness
- Add any missing accomplishments
3. **Fill in "進度" (Progress %)**
- Enter progress as decimal (0.5 = 50%)
- Example: 0.75 for 75% complete
4. **Add "交付物" (Deliverables)**
- List specific deliverables if any
- Include document names, versions, etc.
5. **Mark "代碼上傳" (Code Upload)**
- Enter "Y" if code was uploaded
- Enter "N" if not applicable
6. **Plan "下周計畫" (Next Week)**
- Outline next week's goals
- Be specific and actionable
7. **Add Visual Materials** (Optional)
- Insert diagrams, screenshots, etc.
- Reference in the header suggestion
---
## 🔧 Customization
### Change Team Name
```python
generate_weekly_report(
input_file='cost.xls',
output_file='report.xlsx',
team_name='您的團隊名稱' # Your team name
)
```
### Adjust Column Widths
Edit `generate_report.py`:
```python
column_widths = {
'B': 25, # Wider project name column
'E': 40, # Wider progress column
# Adjust as needed
}
```
### Modify Grouping Logic
Edit the `format_for_weekly_report()` function to change:
- How projects are grouped
- What information is included in progress
- How team members are listed
---
## 🐛 Troubleshooting
### Error: "Module not found"
**Solution:**
```bash
# Make sure you're in the virtual environment
.venv\Scripts\activate
# Install dependencies
uv pip install openpyxl pandas xlrd
```
### Error: "Column not found"
**Cause:** Input file has different column names
**Solution:**
1. Open the input Excel file
2. Check column names match: 日期, 使用者, 專案, 單位
3. If different, the script will try alternative headers
4. Contact support if issues persist
### Empty or No Output
**Check:**
1. Input file has data (not just headers)
2. Data starts at expected row (usually row 2)
3. File isn't corrupted or password-protected
4. Required columns have values (not all empty)
### Report Looks Wrong
**Verify:**
1. Template file exists and is valid
2. Using correct template for your organization
3. Excel/LibreOffice can open the file
4. File isn't read-only
---
## 📚 Additional Resources
### Documentation Files
- **[SKILL.md](SKILL.md)** - Complete technical documentation
- Detailed API reference
- Function descriptions
- Code examples
- Error handling guide
- **[README.md](README.md)** - Comprehensive user guide
- Feature overview
- Installation instructions
- Usage examples
- Customization options
- **[QUICK_REFERENCE.md](QUICK_REFERENCE.md)** - AI assistant guide
- How to use with AI assistants
- Common patterns
- Troubleshooting for AI
- Best practices
### Example Files
Located in `references/` directory:
- Input example: `cost-report-*.xls`
- Template: `項目週報-模板.xlsx`
- Output example: `項目週報-台灣-軟體部-智能控制組 (20260115).xlsx`
---
## 🎓 Tips & Best Practices
### For Users
1. **Run Weekly**: Generate reports at week-end for best workflow
2. **Review Before Sharing**: Always check auto-generated content
3. **Keep Template Updated**: Update template when format changes
4. **Backup Originals**: Keep raw cost reports for audit trail
5. **Consistent Naming**: Use consistent project names in time tracking
### For Developers
1. **Test with Real Data**: Use actual cost reports for testing
2. **Handle Edge Cases**: Test with empty data, special characters, etc.
3. **Preserve Formulas**: If using formulas, don't hardcode values
4. **Document Changes**: Update SKILL.md when modifying code
5. **Version Control**: Track changes to template and script
### For AI Assistants
1. **Validate First**: Check input file exists before processing
2. **Show Progress**: Display what's being done at each step
3. **Summarize Results**: Show key metrics after generation
4. **Remind Manual Steps**: List fields that need manual input
5. **Handle Errors Gracefully**: Provide helpful error messages
---
## 📞 Support & Contact
### Getting Help
1. **Check Documentation**: Review SKILL.md and README.md
2. **Review Examples**: Look at reference files in `references/`
3. **Test Script**: Run the example script: `python example.py`
4. **Open Issue**: Report bugs or request features
### Reporting Issues
When reporting issues, include:
- Error message (full stack trace)
- Input file format (column names, sample data)
- Expected vs actual output
- Version of Python and libraries
- Operating system
---
## 📝 License
MIT License - See individual skill files for complete terms.
---
## 🙏 Acknowledgments
This skill demonstrates how AI can automate routine reporting tasks, saving valuable time and reducing errors in data transformation workflows.
**Built with:**
- Python 3.x
- openpyxl (Excel file handling)
- pandas (Data processing)
- Love and attention to detail ❤️
---
**Version:** 1.0.0
**Last Updated:** January 16, 2026
**Status:** Production Ready ✅

View File

@ -0,0 +1,250 @@
# Weekly Report Generator - Quick Reference
## For AI Assistants (GitHub Copilot/Claude)
When a user asks to generate a weekly report, follow these steps:
### 1. Identify the Request
User might say:
- "Generate a weekly report"
- "Create 項目週報 from cost report"
- "Transform time tracking data into weekly report"
- "Make a weekly project report from the Excel export"
### 2. Read the Skill Documentation
```python
# Read the full skill instructions
read_file('skills/week_report_gen/SKILL.md')
```
### 3. Use the Generate Report Script
```python
# Import and run the generator
from skills.week_report_gen.generate_report import generate_weekly_report
# Generate report with provided file paths
output_file, summary_df = generate_weekly_report(
input_file='path/to/cost-report.xls',
output_file='path/to/output-report.xlsx',
template_file='skills/week_report_gen/references/項目週報-模板.xlsx',
team_name='智能控制組' # Or user-specified team name
)
print(f"✓ Report generated: {output_file}")
print("\nProject Summary:")
for idx, row in summary_df.iterrows():
print(f"\n{row['專案名稱']}")
print(f" Team: {row['參與人員']}")
print(f" Hours: {row['工時']}")
```
### 4. Alternative: Run via Terminal
```bash
cd skills/week_report_gen
python generate_report.py "path/to/cost-report.xls" "path/to/output.xlsx"
```
## Common Usage Patterns
### Pattern 1: User Provides Input File
```
User: "Generate weekly report from cost-report-2026-01-16.xls"
Assistant Actions:
1. Locate the input file
2. Determine output filename (based on date and team)
3. Run generate_weekly_report()
4. Show summary of projects and hours
5. Confirm file saved location
```
### Pattern 2: User Wants to Customize Output
```
User: "Create weekly report for 研發部 team"
Assistant Actions:
1. Ask for input file if not specified
2. Use team_name parameter: team_name='研發部'
3. Generate report
4. Confirm customization applied
```
### Pattern 3: User Has Multiple Cost Reports
```
User: "Generate reports for all cost reports in the folder"
Assistant Actions:
1. List all .xls/.xlsx files in references folder
2. Filter for cost report files
3. Generate report for each
4. Provide summary of all generated reports
```
## Key Functions
### read_cost_report(file_path)
Reads and parses the cost report Excel file.
**Returns**: DataFrame with columns [日期, 使用者, 活動, 專案, 單位, etc.]
### aggregate_work_hours(df)
Groups work hours by user and project.
**Returns**:
- `summary_df`: Aggregated data
- `start_date`: Report start date
- `end_date`: Report end date
### format_for_weekly_report(summary_df)
Transforms aggregated data into weekly report format.
**Returns**: DataFrame ready for Excel output
### generate_weekly_report(input_file, output_file, template_file, team_name)
Main function that orchestrates the entire process.
**Returns**:
- `output_file`: Path to generated report
- `report_df`: Summary DataFrame
## Example AI Responses
### Example 1: Basic Generation
```
User: "Generate a weekly report from the cost report file"
AI Assistant:
"I'll generate the weekly report from your cost report.
[Runs generate_report.py]
✓ Weekly report generated successfully!
Summary of 8 projects:
- AXEL PLC (Ryan Hsueh, 48 hours)
- CNC Library 移植 (傑 羅, 8 hours)
- masterXXX (ben sung, 15 hours)
...
Report saved to: 項目週報-智能控制組-20260116.xlsx
Please review and fill in the following fields:
- 進度 (Progress percentages)
- 交付物 (Deliverables)
- 代碼上傳 (Code upload status)
- 下周計畫 (Next week's plan)"
```
### Example 2: Custom Team Name
```
User: "Create a weekly report for the 研發部-AI組 team"
AI Assistant:
"I'll create a weekly report for the 研發部-AI組 team.
[Runs with team_name='研發部-AI組']
✓ Report generated with custom team name!
File: 項目週報-研發部-AI組-20260116.xlsx"
```
### Example 3: Batch Processing
```
User: "Generate weekly reports for all cost report files"
AI Assistant:
"I found 3 cost report files. Generating reports...
1. cost-report-2026-01-16.xls → 項目週報-20260116.xlsx ✓
2. cost-report-2026-01-09.xls → 項目週報-20260109.xlsx ✓
3. cost-report-2025-12-30.xls → 項目週報-20251230.xlsx ✓
All reports generated successfully!"
```
## Troubleshooting Guide for AI
### Issue: File Not Found
```python
# Check if file exists
import os
if not os.path.exists(input_file):
# List available files
files = os.listdir('skills/week_report_gen/references')
print(f"Available files: {files}")
# Ask user for correct filename
```
### Issue: Missing Columns
```python
# Check what columns are present
import pandas as pd
df = pd.read_excel(input_file, header=1)
print(f"Available columns: {list(df.columns)}")
# Suggest using different header row or file format
```
### Issue: Empty Output
```python
# Check data was loaded
if len(df) == 0:
print("No data found in file. Check:")
print("1. Correct sheet is being read")
print("2. Data starts at expected row")
print("3. File isn't corrupted")
```
## Best Practices for AI Assistants
1. **Always validate input file exists** before processing
2. **Show summary of data** after reading (number of entries, date range, projects)
3. **Display key metrics** in the output (total hours, number of projects, team members)
4. **Remind user of manual fields** that need to be filled in
5. **Provide file location** of generated report clearly
6. **Handle errors gracefully** with helpful error messages
7. **Suggest next steps** after generation (review, fill in fields, etc.)
## Quick Code Snippets
### Check Available Cost Reports
```python
import os
files = [f for f in os.listdir('skills/week_report_gen/references')
if f.startswith('cost-report') and f.endswith(('.xls', '.xlsx'))]
print(f"Found {len(files)} cost report(s): {files}")
```
### Validate Input File Structure
```python
import pandas as pd
df = pd.read_excel(file_path, header=1)
required = ['日期', '使用者', '專案', '單位']
missing = [col for col in required if col not in df.columns]
if missing:
print(f"⚠ Missing columns: {missing}")
else:
print("✓ File structure is valid")
```
### Preview Data Before Processing
```python
df = pd.read_excel(file_path, header=1)
print(f"Date range: {df['日期'].min()} to {df['日期'].max()}")
print(f"Total entries: {len(df)}")
print(f"Projects: {', '.join(df['專案'].unique()[:5])}")
print(f"Team members: {', '.join(df['使用者'].unique()[:5])}")
```

View File

@ -0,0 +1,250 @@
# Weekly Report Generator Skill
This skill automatically generates weekly project reports (項目週報) from time tracking data exported from project management systems.
## Overview
The Weekly Report Generator transforms cost report Excel exports into formatted weekly reports following the company's standard template. It aggregates work hours by person and project, and creates a structured report ready for management review.
## Features
- **Automated Data Processing**: Reads and parses Excel cost reports automatically
- **Smart Aggregation**: Groups work hours by user and project
- **Template-Based**: Uses company standard template for consistent formatting
- **Date Range Detection**: Automatically extracts reporting period from data
- **Multi-Team Support**: Handles multiple team members per project
- **Formatted Output**: Generates professionally formatted Excel reports
## Files
- `SKILL.md` - Detailed skill documentation and API reference
- `generate_report.py` - Python script for report generation
- `references/` - Sample files and templates
- `cost-report-*.xls` - Example input cost report
- `項目週報-模板.xlsx` - Standard template
- `項目週報-*.xlsx` - Example outputs
## Quick Start
### Prerequisites
```bash
# From the repository root, create venv and install dependencies
uv sync
# Activate virtual environment (optional - uv run handles this)
.venv\Scripts\activate # Windows
source .venv/bin/activate # Linux/Mac
```
### Usage
#### Command Line
```bash
# Generate report with default paths (from repo root)
uv run python skills/week_report_gen/generate_report.py
# Or navigate to skill directory first
cd skills/week_report_gen
uv run python generate_report.py
# Generate report with custom input
uv run python generate_report.py path/to/cost-report.xls
# Generate report with custom input and output
uv run python generate_report.py path/to/cost-report.xls path/to/output-report.xlsx
```
#### Python Script
```python
from generate_report import generate_weekly_report
# Generate report
output_file, summary_df = generate_weekly_report(
input_file='references/cost-report-2026-01-16-T-16-22-3620260116-7-1r1n4h.xls',
output_file='output/weekly-report.xlsx',
template_file='references/項目週報-模板.xlsx',
team_name='智能控制組'
)
print(f"Report saved to: {output_file}")
print("\nProject Summary:")
print(summary_df)
```
#### AI Assistant (GitHub Copilot/Claude)
Simply tell your AI assistant:
> "Generate a weekly report from the cost report file"
Or more specifically:
> "Use the week_report_gen skill to create a weekly report from `cost-report-2026-01-16-T-16-22-3620260116-7-1r1n4h.xls`"
The AI assistant will automatically:
1. Read the cost report
2. Aggregate work hours by project and person
3. Generate a formatted weekly report
4. Save it with the appropriate filename
## Input Format
The input Excel file should contain time tracking data with these columns:
| Column | Description | Required |
|--------|-------------|----------|
| 日期 | Date of work entry | ✓ |
| 使用者 | User/person name | ✓ |
| 專案 | Project name | ✓ |
| 單位 | Work hours | ✓ |
| 活動 | Activity type (Development, Testing, etc.) | |
| 留言 | Comments/notes | |
| 費用類別 | Cost category | |
| 費用 | Cost amount | |
**Example Input:**
```
日期 使用者 活動 專案 單位
2026-01-12 ben sung Development masterXXX 8
2026-01-12 Ryan Hsueh - AXEL PLC 8
2026-01-13 傑 羅 Development CNC Library 移植 4
```
## Output Format
The output Excel file follows the standard 項目週報 template:
| Column | Description | Auto-filled |
|--------|-------------|-------------|
| 專案名稱 | Project name | ✓ |
| 子項目名稱 | Sub-project name | |
| 進度 | Progress (0-1) | |
| 本周主要進展 | This week's progress | ✓ (from activities/comments) |
| 參與人員 | Team members | ✓ |
| 工時 | Total work hours | ✓ |
| 交付物 | Deliverables | |
| 代碼上傳 | Code uploaded (Y/N) | |
| 下周計畫 | Next week's plan | |
**Fields marked with ✓ are automatically filled by the script.**
## Output Example
```
弘訊科技股份有限公司
2026年度週報(01月12日-01月16日
專案名稱 參與人員 工時 本周主要進展
─────────────────────────────────────────────────────────
AXEL PLC Ryan Hsueh 48.0 -
CNC Library 移植 傑 羅 8.0 Development
程式碼整理及重構
TX7PLC-DSLIB 測試
masterXXX ben sung 15.0 Development
migrate to entry based sdo queue
verify master402 migrate to new API
```
## Manual Steps After Generation
After the report is generated, you should:
1. **Review Progress Notes** - Edit the "本周主要進展" entries for clarity
2. **Add Progress Percentages** - Fill in "進度" for each project (0.0 to 1.0)
3. **Document Deliverables** - Add specific deliverables in "交付物"
4. **Mark Code Status** - Indicate if code was uploaded (Y/N) in "代碼上傳"
5. **Plan Next Week** - Fill in "下周計畫" for each project
6. **Add Sub-projects** - If needed, split projects into sub-items
7. **Attach Materials** - Add design diagrams, screenshots, etc. as mentioned in header
## File Naming Convention
Output files follow this pattern:
```
項目週報-[部門名稱]-[組別] ([YYYYMMDD]).xlsx
```
Examples:
- `項目週報-台灣-軟體部-智能控制組 (20260115).xlsx`
- `項目週報-智能控制組-20260116.xlsx`
## Troubleshooting
### Error: "Module not found"
```bash
# Install missing dependencies
uv pip install openpyxl pandas xlrd
```
### Error: "Column not found"
The input file format may differ. Check that it has the required columns:
- 日期 (Date)
- 使用者 (User)
- 專案 (Project)
- 單位 (Hours)
### Empty or Missing Data
Ensure the input Excel file:
- Has data in the correct sheet (usually first sheet)
- Has a header row with column names
- Contains actual work hour entries
### Template Not Found
If the template file is missing, the script will create a basic report. For best results, provide the template file:
```python
generate_weekly_report(
input_file='input.xls',
output_file='output.xlsx',
template_file='references/項目週報-模板.xlsx' # Specify template
)
```
## Customization
### Change Team Name
```python
generate_weekly_report(
input_file='input.xls',
output_file='output.xlsx',
team_name='您的團隊名稱' # Custom team name
)
```
### Modify Column Widths
Edit `generate_report.py`:
```python
column_widths = {
'B': 25, # Wider project name column
'E': 40, # Wider progress column
# ... etc
}
```
### Custom Aggregation Logic
Modify the `format_for_weekly_report()` function to change how data is grouped or displayed.
## Tips
1. **Run Weekly**: Generate reports at the end of each week for best workflow
2. **Review Before Sending**: Always review auto-generated content for accuracy
3. **Keep Template Updated**: If company template changes, update the template file
4. **Backup Original**: Keep original cost reports for reference
5. **Use Consistent Names**: Ensure project names are consistent across time tracking
## Support
For issues or questions:
1. Check the `SKILL.md` file for detailed documentation
2. Review example files in the `references/` directory
3. Examine the generated report structure for customization ideas
## License
MIT License - See skill documentation for details.

View File

@ -0,0 +1,334 @@
---
name: week_report_gen
description: "Automated weekly report generation from exported Excel time tracking data. Transforms cost report exports into formatted weekly project reports following company templates. Use when generating 項目週報 (project weekly reports) from time tracking data exported from project management systems."
license: MIT
---
# Weekly Report Generator Skill
## Overview
This skill automates the creation of weekly project reports (項目週報) from time tracking data exported from project management systems. It reads Excel cost reports, aggregates work hours by person and project, and generates formatted weekly reports following the company's standard template.
## When to Use This Skill
Use this skill when:
- User wants to generate a weekly report (週報) from time tracking data
- User has an exported cost report Excel file (.xls or .xlsx)
- User needs to create 項目週報 in the standard company format
- User mentions transforming time tracking data into weekly reports
## Input Format
**Input File**: Cost Report Excel file (e.g., `cost-report-2026-01-16-T-16-22-3620260116-7-1r1n4h.xls`)
Expected columns in the input file:
- `日期` - Date of the work entry
- `使用者` - User/person name
- `活動` - Activity type (Development, Testing, Specification, Support, etc.)
- `專案` - Project name
- `留言` - Comments/notes (optional)
- `單位` - Work hours/units
- `費用類別` - Cost category
- `費用` - Cost amount
## Output Format
**Output File**: Weekly Report Excel file (e.g., `項目週報-台灣-軟體部-智能控制組 (20260115).xlsx`)
The output follows the company's standard 項目週報 template with these columns:
- `專案名稱` - Project name
- `子項目名稱` - Sub-project name
- `進度` - Progress (percentage 0-1)
- `本周主要進展 (請條列說明)` - This week's main progress (bullet points)
- `參與人員` - Participants
- `工时(个人投入研发工时` - Work hours invested
- `交付物` - Deliverables
- `代碼(如有)是否上傳` - Code uploaded (Y/N)
- `下周計畫` - Next week's plan
## Processing Workflow
### Step 1: Read and Parse Input Data
```python
import pandas as pd
import openpyxl
from datetime import datetime
# Read the cost report Excel file
def read_cost_report(file_path):
"""
Read cost report and parse the data.
Skip header row if present.
"""
# Try reading with header=1 (skip first row if it's a title)
df = pd.read_excel(file_path, header=1)
# Verify expected columns exist
required_cols = ['日期', '使用者', '活動', '專案', '單位']
if not all(col in df.columns for col in required_cols):
# Try header=0 if header=1 doesn't work
df = pd.read_excel(file_path, header=0)
# Clean data: remove rows with missing critical values
df = df.dropna(subset=['使用者', '專案', '單位'])
return df
```
### Step 2: Aggregate Data by Person and Project
```python
def aggregate_work_hours(df):
"""
Group work hours by user and project.
Returns a summary DataFrame.
"""
# Extract date range for report period
df['日期'] = pd.to_datetime(df['日期'])
start_date = df['日期'].min()
end_date = df['日期'].max()
# Group by user and project
summary = df.groupby(['使用者', '專案', '活動']).agg({
'單位': 'sum',
'留言': lambda x: '\n'.join(x.dropna().unique()) if '留言' in df.columns else ''
}).reset_index()
summary.columns = ['使用者', '專案', '活動', '工時', '備註']
# Sort by user and hours (descending)
summary = summary.sort_values(['使用者', '工時'], ascending=[True, False])
return summary, start_date, end_date
```
### Step 3: Format Data for Weekly Report
```python
def format_for_weekly_report(summary_df):
"""
Transform aggregated data into weekly report format.
Group entries by project and list participants.
"""
# Group by project
report_data = []
for project in summary_df['專案'].unique():
project_data = summary_df[summary_df['專案'] == project]
# Get all participants and their hours
participants = []
total_hours = 0
activities = []
notes = []
for _, row in project_data.iterrows():
participants.append(f"{row['使用者']}")
total_hours += row['工時']
if row['活動'] and row['活動'] != '-':
activities.append(row['活動'])
if row['備註']:
notes.append(row['備註'])
# Format main progress
progress_text = '\n'.join(set(notes)) if notes else ''
if activities:
activity_text = '\n'.join(set(activities))
progress_text = f"{activity_text}\n{progress_text}" if progress_text else activity_text
report_data.append({
'專案名稱': project,
'子項目名稱': None,
'進度': None, # User should fill this in
'本周主要進展': progress_text,
'參與人員': ', '.join(set(participants)),
'工時': total_hours,
'交付物': None,
'代碼上傳': None,
'下周計畫': None
})
return pd.DataFrame(report_data)
```
### Step 4: Generate Excel Output with Template
```python
def generate_weekly_report(input_file, output_file, template_file=None):
"""
Main function to generate weekly report from cost report.
Args:
input_file: Path to input cost report Excel file
output_file: Path to output weekly report Excel file
template_file: Optional path to template file (if not using default)
"""
# Read and process input
df = read_cost_report(input_file)
summary, start_date, end_date = aggregate_work_hours(df)
report_df = format_for_weekly_report(summary)
# Load template or create new workbook
if template_file and os.path.exists(template_file):
wb = openpyxl.load_workbook(template_file)
# Create new sheet for this week
sheet_name = f"{end_date.strftime('%Y%m%d')}-智能控制組"
ws = wb.create_sheet(sheet_name)
else:
wb = openpyxl.Workbook()
ws = wb.active
sheet_name = f"{end_date.strftime('%Y%m%d')}-週報"
ws.title = sheet_name
# Write header
ws['B1'] = '弘訊科技股份有限公司'
ws['B2'] = f"2026年度週報({start_date.strftime('%m月%d日')}-{end_date.strftime('%m月%d日')}"
ws['B3'] = '建議用可視化素材(如有)輔助報告:設計圖、產品架構圖、產品實物照片等等相關材料'
# Write column headers (row 4)
headers = ['專案名稱', '子項目名稱', '進度', '本周主要進展 (請條列說明)',
'參與人員', '工时(个人投入研发工时', '交付物', '代碼(如有)是否上傳', '下周計畫']
for col_idx, header in enumerate(headers, start=2): # Start from column B
ws.cell(row=4, column=col_idx, value=header)
# Write data starting from row 5
current_row = 5
for _, row_data in report_df.iterrows():
ws.cell(row=current_row, column=2, value=row_data['專案名稱'])
ws.cell(row=current_row, column=3, value=row_data['子項目名稱'])
ws.cell(row=current_row, column=4, value=row_data['進度'])
ws.cell(row=current_row, column=5, value=row_data['本周主要進展'])
ws.cell(row=current_row, column=6, value=row_data['參與人員'])
ws.cell(row=current_row, column=7, value=row_data['工時'])
ws.cell(row=current_row, column=8, value=row_data['交付物'])
ws.cell(row=current_row, column=9, value=row_data['代碼上傳'])
ws.cell(row=current_row, column=10, value=row_data['下周計畫'])
current_row += 1
# Add separator row
current_row += 1
ws.cell(row=current_row, column=2, value='專案名稱')
for col_idx, header in enumerate(headers[1:], start=3):
ws.cell(row=current_row, column=col_idx, value=header)
current_row += 1
# Apply formatting
from openpyxl.styles import Font, Alignment, PatternFill, Border, Side
# Header formatting
header_fill = PatternFill(start_color='D3D3D3', end_color='D3D3D3', fill_type='solid')
bold_font = Font(bold=True)
center_align = Alignment(horizontal='center', vertical='center', wrap_text=True)
# Format title rows
ws['B1'].font = Font(bold=True, size=14)
ws['B1'].alignment = center_align
ws['B2'].font = Font(bold=True, size=12)
ws['B3'].font = Font(size=10, italic=True)
# Format column headers
for col_idx in range(2, 11):
cell = ws.cell(row=4, column=col_idx)
cell.fill = header_fill
cell.font = bold_font
cell.alignment = center_align
# Set column widths
column_widths = {
'B': 20, # 專案名稱
'C': 20, # 子項目名稱
'D': 8, # 進度
'E': 35, # 本周主要進展
'F': 15, # 參與人員
'G': 12, # 工時
'H': 15, # 交付物
'I': 10, # 代碼上傳
'J': 20 # 下周計畫
}
for col, width in column_widths.items():
ws.column_dimensions[col].width = width
# Save workbook
wb.save(output_file)
return output_file, report_df
```
## Usage Example
When the user provides a cost report file and wants to generate a weekly report:
```python
# Example usage
input_file = 'skills/week_report_gen/references/cost-report-2026-01-16-T-16-22-3620260116-7-1r1n4h.xls'
output_file = 'skills/week_report_gen/references/項目週報-智能控制組-20260116.xlsx'
template_file = 'skills/week_report_gen/references/項目週報-模板.xlsx'
# Generate the report
output_path, summary_data = generate_weekly_report(
input_file=input_file,
output_file=output_file,
template_file=template_file
)
print(f"Weekly report generated: {output_path}")
print("\nSummary:")
print(summary_data)
```
## Important Notes
1. **Data Validation**: The script validates that required columns exist in the input file. If column names don't match, it will attempt different header configurations.
2. **Date Range**: The report automatically extracts the date range from the input data to generate the report period header.
3. **Work Hours Aggregation**: Hours are summed by person and project to provide accurate totals for the weekly report.
4. **Manual Fields**: Some fields like "進度" (Progress), "交付物" (Deliverables), and "下周計畫" (Next Week's Plan) are left blank for manual input, as they require subjective assessment.
5. **Formatting**: The output maintains the company's standard formatting including:
- Company header
- Date range
- Column structure
- Separator rows between projects
- Appropriate column widths
6. **Multiple Team Members**: When multiple people work on the same project, their names are combined in the "參與人員" column and hours are summed.
## Error Handling
The script includes error handling for common issues:
- Missing or incorrect column names
- Empty or invalid data
- Missing template file (will create basic template)
- Date parsing errors
## Customization
You can customize the output by:
- Modifying column widths in the `column_widths` dictionary
- Adjusting header formatting styles
- Changing the grouping logic (e.g., by activity type)
- Adding additional calculated fields
## Next Steps After Generation
After generating the weekly report:
1. Review the "本周主要進展" (Main Progress) entries - these are auto-populated from notes but may need editing
2. Fill in the "進度" (Progress) percentages for each project
3. Add specific "交付物" (Deliverables) if any
4. Indicate "代碼上傳" (Code Uploaded) status as Y/N
5. Plan and fill in "下周計畫" (Next Week's Plan) for each project
6. Add any visual materials mentioned in row 3 header
## File Naming Convention
Output files should follow this pattern:
```
項目週報-[部門名稱]-[組別] ([YYYYMMDD]).xlsx
```
Example: `項目週報-台灣-軟體部-智能控制組 (20260115).xlsx`

View File

@ -0,0 +1,282 @@
# Weekly Report Generator - Visual Workflow
```
┌─────────────────────────────────────────────────────────────────────────┐
│ WEEKLY REPORT GENERATOR WORKFLOW │
└─────────────────────────────────────────────────────────────────────────┘
┌──────────────────┐
│ INPUT FILE │
│ (Cost Report) │
│ .xls/.xlsx │
└────────┬─────────┘
│ 日期 使用者 活動 專案 單位
│ 01-12 ben sung Dev masterXXX 8
│ 01-12 Ryan - AXEL PLC 8
│ 01-13 傑 羅 Dev CNC Lib 4
┌─────────────────────────────────┐
│ STEP 1: READ & PARSE │
│ • Load Excel file │
│ • Identify columns │
│ • Clean missing data │
│ • Extract date range │
└────────┬────────────────────────┘
│ DataFrame with validated data
│ Date range: 2026-01-12 to 2026-01-16
┌─────────────────────────────────┐
│ STEP 2: AGGREGATE │
│ • Group by user & project │
│ • Sum work hours │
│ • Combine activities │
│ • Collect comments │
└────────┬────────────────────────┘
│ Project: masterXXX
│ • ben sung: 15 hours
│ • Activities: Development, Specification
│ • Notes: migrate to entry based sdo queue...
┌─────────────────────────────────┐
│ STEP 3: FORMAT │
│ • Group by project │
│ • List team members │
│ • Format progress notes │
│ • Calculate totals │
└────────┬────────────────────────┘
│ Formatted report data ready for Excel
┌─────────────────────────────────┐
│ STEP 4: GENERATE EXCEL │
│ • Load template (if exists) │
│ • Create new sheet │
│ • Write headers │
│ • Write project data │
│ • Apply formatting │
│ • Save file │
└────────┬────────────────────────┘
┌──────────────────────────────────────────────┐
│ OUTPUT FILE (Weekly Report) │
│ 項目週報-智能控制組 │
│ │
│ 弘訊科技股份有限公司 │
│ 2026年度週報(01月12日-01月16日
│ │
│ 專案 參與人員 工時 本周進展 │
│ ──────────────────────────────────────── │
│ AXEL Ryan Hsueh 48.0 - │
│ master ben sung 15.0 Development │
│ XXX migrate to.. │
│ │
└──────────────────────────────────────────────┘
DATA FLOW DIAGRAM
═════════════════
Raw Time Data ──────┐
Export from PM ├─────────► Read Excel ────► Parse Columns
System │ │
│ │
Cost Report File ───┘ ▼
Validate & Clean
Extract Date Range
Group by Project ────┐
│ │
│ │
Sum Hours ◄──────────┤
│ │
│ │
Combine Teams ◄──────┘
Format Progress
Load Template
Write to Excel
Apply Styling
Save Output File
Weekly Report ✓
COMPONENT ARCHITECTURE
══════════════════════
┌─────────────────────────────────────────────────────────────┐
│ SKILL ARCHITECTURE │
├─────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ User Interface Layer │ │
│ ├─────────────────────────────────────────────────────┤ │
│ │ • Command Line Interface │ │
│ │ • AI Assistant Integration │ │
│ │ • Python API │ │
│ └────────────────┬────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Core Processing Layer │ │
│ ├─────────────────────────────────────────────────────┤ │
│ │ • read_cost_report() │ │
│ │ └─► Load Excel, validate columns │ │
│ │ │ │
│ │ • aggregate_work_hours() │ │
│ │ └─► Group data, sum hours, extract dates │ │
│ │ │ │
│ │ • format_for_weekly_report() │ │
│ │ └─► Transform to report format │ │
│ │ │ │
│ │ • generate_weekly_report() │ │
│ │ └─► Main orchestration function │ │
│ └────────────────┬────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Output Generation Layer │ │
│ ├─────────────────────────────────────────────────────┤ │
│ │ • Excel Writer (openpyxl) │ │
│ │ • Template Handler │ │
│ │ • Style & Format Applier │ │
│ │ • File Saver │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘
▲ ▲
│ │
┌────┴─────┐ ┌──────┴──────┐
│ pandas │ │ openpyxl │
│ (Data │ │ (Excel │
│ Process) │ │ Files) │
└──────────┘ └─────────────┘
FILE ORGANIZATION
═════════════════
skills/week_report_gen/
├── 📄 SKILL.md ─────────────────► Technical documentation
│ • API reference
│ • Function details
│ • Code examples
├── 📄 README.md ────────────────► User guide
│ • Installation
│ • Quick start
│ • Examples
├── 📄 QUICK_REFERENCE.md ───────► AI assistant guide
│ • Usage patterns
│ • Best practices
├── 📄 COMPLETE_GUIDE.md ────────► Comprehensive guide
│ • Everything combined
│ • Tips & tricks
├── 🐍 generate_report.py ───────► Main script
│ • Core functions
│ • Entry point
└── 📁 references/
├── 📊 cost-report-*.xls ────► Example input
├── 📋 項目週報-模板.xlsx ───► Template
└── 📊 項目週報-*.xlsx ──────► Example output
USAGE PATTERNS
══════════════
Pattern 1: AI Assistant
────────────────────────
User: "Generate weekly report"
AI reads SKILL.md
AI runs generate_report.py
AI shows summary
Report saved ✓
Pattern 2: Command Line
───────────────────────
$ python generate_report.py input.xls output.xlsx
Script processes data
Console shows progress
Report saved ✓
Pattern 3: Python Integration
──────────────────────────────
from generate_report import generate_weekly_report
output, summary = generate_weekly_report(...)
Use summary data in your code
Process complete ✓
KEY SUCCESS FACTORS
═══════════════════
✓ Input Validation
└─► Verify file exists, columns present, data valid
✓ Smart Aggregation
└─► Group logically, sum accurately, preserve info
✓ Template Support
└─► Use existing templates, maintain consistency
✓ Error Handling
└─► Clear messages, graceful failures, helpful hints
✓ Formatting
└─► Professional appearance, proper widths, colors
✓ Documentation
└─► Clear examples, complete reference, AI-friendly
```

View File

@ -0,0 +1,299 @@
"""
Weekly Report Generator
This script generates weekly project reports from cost report Excel exports.
"""
import pandas as pd
import openpyxl
from datetime import datetime
from openpyxl.styles import Font, Alignment, PatternFill, Border, Side
import os
def read_cost_report(file_path):
"""
Read cost report and parse the data.
Skip header row if present.
"""
try:
# Try reading with header=1 (skip first row if it's a title)
df = pd.read_excel(file_path, header=1)
# Verify expected columns exist
required_cols = ['日期', '使用者', '專案', '單位']
if not all(col in df.columns for col in required_cols):
# Try header=0 if header=1 doesn't work
df = pd.read_excel(file_path, header=0)
except Exception as e:
print(f"Error reading file: {e}")
raise
# Clean data: remove rows with missing critical values
df = df.dropna(subset=['使用者', '專案', '單位'])
return df
def aggregate_work_hours(df):
"""
Group work hours by user and project.
Returns a summary DataFrame and date range.
"""
# Extract date range for report period
df['日期'] = pd.to_datetime(df['日期'])
start_date = df['日期'].min()
end_date = df['日期'].max()
# Group by user and project
agg_dict = {'單位': 'sum'}
# Add 留言 (comments) if column exists
if '留言' in df.columns:
agg_dict['留言'] = lambda x: '\n'.join([str(i) for i in x.dropna().unique() if str(i) != 'nan'])
# Add 活動 (activity) if column exists
if '活動' in df.columns:
summary = df.groupby(['使用者', '專案', '活動']).agg(agg_dict).reset_index()
summary.columns = ['使用者', '專案', '活動', '工時'] + (['備註'] if '留言' in df.columns else [])
else:
summary = df.groupby(['使用者', '專案']).agg(agg_dict).reset_index()
summary.columns = ['使用者', '專案', '工時'] + (['備註'] if '留言' in df.columns else [])
summary['活動'] = ''
# Sort by user and hours (descending)
summary = summary.sort_values(['專案', '工時'], ascending=[True, False])
return summary, start_date, end_date
def format_for_weekly_report(summary_df):
"""
Transform aggregated data into weekly report format.
Group entries by project and list participants.
"""
report_data = []
for project in summary_df['專案'].unique():
project_data = summary_df[summary_df['專案'] == project]
# Get all participants and their hours
participants = []
total_hours = 0
activities = []
notes = []
for _, row in project_data.iterrows():
user_name = row['使用者']
user_hours = row['工時']
participants.append(f"{user_name}")
total_hours += user_hours
if '活動' in row and row['活動'] and row['活動'] != '-' and pd.notna(row['活動']):
activities.append(row['活動'])
if '備註' in row and row['備註'] and pd.notna(row['備註']):
notes.append(row['備註'])
# Format main progress
progress_text = ''
if activities:
activity_text = '\n'.join([f"{act}" for act in set(activities)])
progress_text = activity_text
if notes:
note_text = '\n'.join(set(notes))
progress_text = f"{progress_text}\n{note_text}" if progress_text else note_text
report_data.append({
'專案名稱': project,
'子項目名稱': None,
'進度': None, # User should fill this in
'本周主要進展': progress_text if progress_text else None,
'參與人員': ', '.join(set(participants)),
'工時': total_hours,
'交付物': None,
'代碼上傳': None,
'下周計畫': None
})
return pd.DataFrame(report_data)
def generate_weekly_report(input_file, output_file, template_file=None, team_name="智能控制組"):
"""
Main function to generate weekly report from cost report.
Args:
input_file: Path to input cost report Excel file
output_file: Path to output weekly report Excel file
template_file: Optional path to template file (if not using default)
team_name: Team name for sheet title (default: "智能控制組")
Returns:
Tuple of (output_file_path, report_dataframe)
"""
print(f"Reading cost report from: {input_file}")
# Read and process input
df = read_cost_report(input_file)
print(f"Loaded {len(df)} entries from cost report")
summary, start_date, end_date = aggregate_work_hours(df)
print(f"Date range: {start_date.strftime('%Y-%m-%d')} to {end_date.strftime('%Y-%m-%d')}")
print(f"Found {len(summary)} work entries across {summary['專案'].nunique()} projects")
report_df = format_for_weekly_report(summary)
print(f"Formatted {len(report_df)} project entries for report")
# Load template or create new workbook
if template_file and os.path.exists(template_file):
print(f"Loading template from: {template_file}")
wb = openpyxl.load_workbook(template_file)
# Create new sheet for this week
sheet_name = f"{end_date.strftime('%Y%m%d')}-{team_name}"
ws = wb.create_sheet(sheet_name, 0) # Insert at beginning
else:
print("Creating new workbook (no template provided)")
wb = openpyxl.Workbook()
ws = wb.active
sheet_name = f"{end_date.strftime('%Y%m%d')}-{team_name}"
ws.title = sheet_name
# Write header
ws['B1'] = '弘訊科技股份有限公司'
ws['B2'] = f"2026年度週報({start_date.strftime('%m月%d')}-{end_date.strftime('%m月%d')}"
ws['B3'] = '建議用可視化素材(如有)輔助報告:設計圖、產品架構圖、產品實物照片等等相關材料'
# Write column headers (row 4)
headers = ['專案名稱', '子項目名稱', '進度', '本周主要進展 (請條列說明)',
'參與人員', '工时(个人投入研发工时', '交付物', '代碼(如有)是否上傳', '下周計畫']
for col_idx, header in enumerate(headers, start=2): # Start from column B
ws.cell(row=4, column=col_idx, value=header)
# Write data starting from row 5
current_row = 5
for idx, row_data in report_df.iterrows():
ws.cell(row=current_row, column=2, value=row_data['專案名稱'])
ws.cell(row=current_row, column=3, value=row_data['子項目名稱'])
ws.cell(row=current_row, column=4, value=row_data['進度'])
ws.cell(row=current_row, column=5, value=row_data['本周主要進展'])
ws.cell(row=current_row, column=6, value=row_data['參與人員'])
ws.cell(row=current_row, column=7, value=row_data['工時'])
ws.cell(row=current_row, column=8, value=row_data['交付物'])
ws.cell(row=current_row, column=9, value=row_data['代碼上傳'])
ws.cell(row=current_row, column=10, value=row_data['下周計畫'])
current_row += 1
# Add separator row (except after last entry)
if idx < len(report_df) - 1:
current_row += 1
ws.cell(row=current_row, column=2, value='專案名稱')
for col_idx, header in enumerate(headers[1:], start=3):
ws.cell(row=current_row, column=col_idx, value=header)
current_row += 1
# Apply formatting
header_fill = PatternFill(start_color='D3D3D3', end_color='D3D3D3', fill_type='solid')
bold_font = Font(bold=True)
center_align = Alignment(horizontal='center', vertical='center', wrap_text=True)
wrap_align = Alignment(vertical='top', wrap_text=True)
# Format title rows
ws['B1'].font = Font(bold=True, size=14)
ws['B1'].alignment = center_align
ws['B2'].font = Font(bold=True, size=12)
ws['B2'].alignment = center_align
ws['B3'].font = Font(size=10, italic=True)
ws['B3'].alignment = wrap_align
# Merge cells for headers
ws.merge_cells('B1:J1')
ws.merge_cells('B2:J2')
ws.merge_cells('B3:J3')
# Format column headers and separator rows
for row in range(1, current_row + 1):
cell_b = ws.cell(row=row, column=2)
if cell_b.value == '專案名稱' or row == 4:
for col_idx in range(2, 11):
cell = ws.cell(row=row, column=col_idx)
cell.fill = header_fill
cell.font = bold_font
cell.alignment = center_align
# Set column widths
column_widths = {
'B': 20, # 專案名稱
'C': 20, # 子項目名稱
'D': 8, # 進度
'E': 35, # 本周主要進展
'F': 15, # 參與人員
'G': 12, # 工時
'H': 15, # 交付物
'I': 10, # 代碼上傳
'J': 20 # 下周計畫
}
for col, width in column_widths.items():
ws.column_dimensions[col].width = width
# Apply wrap text to all data cells
for row in range(5, current_row):
for col in range(2, 11):
ws.cell(row=row, column=col).alignment = wrap_align
# Save workbook
wb.save(output_file)
print(f"\n✓ Weekly report saved to: {output_file}")
return output_file, report_df
if __name__ == "__main__":
# Example usage
import sys
# Default paths
script_dir = os.path.dirname(os.path.abspath(__file__))
if len(sys.argv) > 1:
input_file = sys.argv[1]
else:
input_file = os.path.join(script_dir, 'references', 'cost-report-2026-01-16-T-16-22-3620260116-7-1r1n4h.xls')
if len(sys.argv) > 2:
output_file = sys.argv[2]
else:
timestamp = datetime.now().strftime('%Y%m%d')
output_file = os.path.join(script_dir, 'references', f'項目週報-智能控制組-{timestamp}.xlsx')
template_file = os.path.join(script_dir, 'references', '項目週報-模板.xlsx')
# Generate the report
try:
output_path, summary_data = generate_weekly_report(
input_file=input_file,
output_file=output_file,
template_file=template_file if os.path.exists(template_file) else None
)
print("\n" + "="*60)
print("SUMMARY OF PROJECTS:")
print("="*60)
for idx, row in summary_data.iterrows():
print(f"\nProject: {row['專案名稱']}")
print(f" Team: {row['參與人員']}")
print(f" Hours: {row['工時']}")
if row['本周主要進展']:
print(f" Progress:\n {row['本周主要進展'].replace(chr(10), chr(10) + ' ')}")
print("\n" + "="*60)
print("✓ Report generation completed successfully!")
print("="*60)
except Exception as e:
print(f"\n✗ Error generating report: {e}")
import traceback
traceback.print_exc()
sys.exit(1)