forked from Zhubei_iXD/report_skill_expm
314 lines
10 KiB
Python
314 lines
10 KiB
Python
"""
|
|
Example: Various Report Generation Methods
|
|
|
|
This script demonstrates how to use different skills:
|
|
1. week_report_gen: Generate from Excel cost report
|
|
2. week_work_package_log: Analyze work package time entries with completion tracking
|
|
3. week_report_gen_from_json: Generate report directly from API data
|
|
"""
|
|
|
|
import os
|
|
import sys
|
|
|
|
|
|
def main():
|
|
"""
|
|
Main function demonstrating various report generation methods.
|
|
"""
|
|
print("Report Generation Skills - Examples")
|
|
print("====================================")
|
|
print()
|
|
print("Choose an example to run:")
|
|
print("1. Work Package Analysis (with completion tracking)")
|
|
print("2. Weekly Report Generation (from Excel)")
|
|
print("3. Weekly Report Generation (from JSON/API)")
|
|
print()
|
|
|
|
try:
|
|
choice = input("Enter your choice (1-3): ").strip()
|
|
|
|
if choice == "1":
|
|
example_work_package_analysis()
|
|
elif choice == "2":
|
|
example_weekly_report_excel()
|
|
elif choice == "3":
|
|
example_weekly_report_json()
|
|
else:
|
|
print("Invalid choice. Please run the script again.")
|
|
|
|
except KeyboardInterrupt:
|
|
print("\n\nExample interrupted by user.")
|
|
except Exception as e:
|
|
print(f"\nUnexpected error: {e}")
|
|
|
|
|
|
def example_work_package_analysis():
|
|
"""
|
|
Example: Analyze work package time entries with completion tracking
|
|
"""
|
|
print("=" * 70)
|
|
print("Work Package Analysis - Example")
|
|
print("=" * 70)
|
|
print()
|
|
|
|
# Add the skill directory to the path
|
|
base_dir = os.path.dirname(os.path.abspath(__file__))
|
|
skill_path = os.path.join(base_dir, '.claude', 'skills', 'week_work_package_log')
|
|
sys.path.insert(0, skill_path)
|
|
|
|
try:
|
|
from work_package_logger import WeekWorkPackageLogger
|
|
|
|
# Initialize logger
|
|
logger = WeekWorkPackageLogger()
|
|
|
|
# Test connection first
|
|
print("Testing OpenProject API connection...")
|
|
if not logger.test_connection():
|
|
print("Failed to connect to OpenProject API. Check your credentials.")
|
|
return
|
|
|
|
# Example date range (replace with actual dates)
|
|
start_date = "2026-01-22"
|
|
end_date = "2026-01-22"
|
|
|
|
print(f"\nFetching work package data for {start_date} to {end_date}...")
|
|
print()
|
|
|
|
# Display tree format with completion percentages
|
|
logger.fetch_and_display_time_entries(start_date, end_date, 'tree')
|
|
|
|
print("\n" + "=" * 70)
|
|
print("JSON Output for Integration:")
|
|
print("=" * 70)
|
|
|
|
# Get JSON format for data integration
|
|
json_data = logger.fetch_and_display_time_entries(start_date, end_date, 'json')
|
|
|
|
if json_data:
|
|
print(f"\nTotal projects analyzed: {json_data['summary']['total_projects']}")
|
|
print(f"Total hours logged: {json_data['summary']['total_hours']}h")
|
|
|
|
# Show completion summary for work packages
|
|
print("\nWork Package Completion Summary:")
|
|
for project in json_data['projects']:
|
|
_print_wp_completion_summary(project, 0)
|
|
|
|
print("\n✓ Work package analysis completed successfully!")
|
|
|
|
except ImportError as e:
|
|
print(f"Error importing work_package_logger: {e}")
|
|
print("Make sure the week_work_package_log skill is properly installed.")
|
|
except Exception as e:
|
|
print(f"Error during work package analysis: {e}")
|
|
|
|
|
|
def _print_wp_completion_summary(node, depth=0):
|
|
"""Helper function to print work package completion summary"""
|
|
indent = " " * depth
|
|
|
|
if node['type'] == 'work_package' and 'completion' in node:
|
|
print(f"{indent}- {node['name']}: {node['completion']} ({node['total_hours']:.1f}h)")
|
|
elif node['type'] == 'project':
|
|
print(f"{indent}📁 {node['name']} ({node['total_hours']:.1f}h)")
|
|
|
|
for child in node.get('children', []):
|
|
_print_wp_completion_summary(child, depth + 1)
|
|
|
|
"""
|
|
Main function demonstrating various report generation methods.
|
|
"""
|
|
print("Report Generation Skills - Examples")
|
|
print("====================================")
|
|
print()
|
|
print("Choose an example to run:")
|
|
print("1. Work Package Analysis (with completion tracking)")
|
|
print("2. Weekly Report Generation (from Excel)")
|
|
print("3. Weekly Report Generation (from JSON/API)")
|
|
print()
|
|
|
|
try:
|
|
choice = input("Enter your choice (1-3): ").strip()
|
|
|
|
if choice == "1":
|
|
example_work_package_analysis()
|
|
elif choice == "2":
|
|
example_weekly_report_excel()
|
|
elif choice == "3":
|
|
example_weekly_report_json()
|
|
else:
|
|
print("Invalid choice. Please run the script again.")
|
|
|
|
except KeyboardInterrupt:
|
|
print("\n\nExample interrupted by user.")
|
|
except Exception as e:
|
|
print(f"\nUnexpected error: {e}")
|
|
|
|
|
|
def example_weekly_report_excel():
|
|
"""
|
|
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
|
|
|
|
|
|
def example_weekly_report_json():
|
|
"""
|
|
Example: Generate weekly report directly from OpenProject API (JSON-based)
|
|
"""
|
|
print("=" * 70)
|
|
print("Weekly Report from JSON - Example")
|
|
print("=" * 70)
|
|
print()
|
|
|
|
# Add the skill directory to the path
|
|
base_dir = os.path.dirname(os.path.abspath(__file__))
|
|
skill_path = os.path.join(base_dir, '.claude', 'skills', 'week_report_gen_from_json')
|
|
sys.path.insert(0, skill_path)
|
|
|
|
try:
|
|
from generate_report import main as generate_json_report
|
|
|
|
# Example parameters
|
|
start_date = "2026-01-20"
|
|
end_date = "2026-01-22"
|
|
output_file = os.path.join(base_dir, "temp", "週報-示例-JSON版本.xlsx")
|
|
|
|
print(f"Generating report for {start_date} to {end_date}...")
|
|
print(f"Output file: {output_file}")
|
|
print()
|
|
|
|
# Note: This would typically be called with command line arguments
|
|
# For demonstration, we're calling it directly
|
|
print("Note: This example shows the concept. In practice, use:")
|
|
print(f"uv run --env-file .env python .claude\\skills\\week_report_gen_from_json\\generate_report.py \"{start_date}\" \"{end_date}\" \"{output_file}\"")
|
|
print()
|
|
print("Features:")
|
|
print("- Direct API integration (no manual Excel export)")
|
|
print("- Intelligent cell merging and formatting")
|
|
print("- Hierarchical project structure recognition")
|
|
print("- Work package completion tracking")
|
|
|
|
except ImportError as e:
|
|
print(f"Error importing week_report_gen_from_json: {e}")
|
|
print("Make sure the week_report_gen_from_json skill is properly installed.")
|
|
except Exception as e:
|
|
print(f"Error during JSON report generation: {e}")
|
|
|
|
if __name__ == "__main__":
|
|
main()
|
|
sys.exit(main())
|