当前位置: 首页 > Skill >

PL Report Generator

PL Report Generator

PL Report Generator

自动生成财务与业务报告,支持PDF输出、图表创建与分发。使用场景:(1) 生成周期性财务报告(损益表...

1.0.0 2026.11.07 205
获取Skill文件查看使用说明
作 者:叶安 许可证: 更新时间:2026.11.07
本文目录展开

Report Generator Skill

Automates the full report lifecycle: data extraction → formatting → chart generation → PDF rendering → distribution.

Core Capabilities

1. Financial Report Types

Report Frequency Primary Audience
Profit & Loss (Income Statement) Monthly / Quarterly CEO, Board
Balance Sheet Monthly / Quarterly CEO, Investors
Cash Flow Statement Weekly / Monthly CFO, Ops
AR/AP Aging Summary Weekly AR Team, Controller
Budget vs Actual Variance Monthly Department Heads
KPI Dashboard Weekly / Monthly All Executives
Client Profitability Report Monthly / Quarterly Partners
Payroll Summary Per-payroll-run HR, Finance

2. Business Reports

  • Operations Report — headcount, utilization, productivity metrics
  • Sales Pipeline Report — funnel stages, conversion rates, projected revenue
  • Expense Analysis — category breakdowns, trend lines, anomaly flagging
  • Vendor Spend Report — top vendors, spend trends, contract compliance
  • Project Profitability — budget vs actuals per engagement

Workflow

Step 1: Data Collection

Identify the source system and extract the raw data:

# QuickBooks export (CSV)
# Pull via QBO skill or manual export from client portal
# Source: reports/raw/2026-03-pl-raw.csv

# Google Sheets source
gog sheets read --id SHEET_ID --range "P&L!A1:Z100" > reports/raw/pl-data.json

# SQL/database source
# sqlite3 db.sqlite "SELECT * FROM transactions WHERE period='2026-02'" > raw.csv

Step 2: Data Processing

# scripts/process_pl.py
import csv, json
from collections import defaultdict

def process_pl(input_csv, period):
    """Process P&L raw data into structured format."""
    categories = defaultdict(float)
    
    with open(input_csv) as f:
        reader = csv.DictReader(f)
        for row in reader:
            categories[row['Category']] += float(row['Amount'] or 0)
    
    revenue = sum(v for k, v in categories.items() if 'Revenue' in k or 'Income' in k)
    cogs = sum(v for k, v in categories.items() if 'COGS' in k or 'Cost of' in k)
    gross_profit = revenue - cogs
    expenses = sum(v for k, v in categories.items() if k not in ['Revenue', 'COGS'])
    net_income = gross_profit - expenses
    
    return {
        'period': period,
        'revenue': revenue,
        'cogs': cogs,
        'gross_profit': gross_profit,
        'gross_margin': (gross_profit / revenue * 100) if revenue else 0,
        'expenses': expenses,
        'net_income': net_income,
        'net_margin': (net_income / revenue * 100) if revenue else 0,
        'categories': dict(categories)
    }

Step 3: Chart Generation

# scripts/generate_charts.py
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import numpy as np

def revenue_trend_chart(data_points, output_path):
    """Generate revenue trend line chart."""
    periods = [d['period'] for d in data_points]
    revenues = [d['revenue'] for d in data_points]
    
    fig, ax = plt.subplots(figsize=(10, 5))
    ax.plot(periods, revenues, 'b-o', linewidth=2, markersize=8)
    ax.fill_between(periods, revenues, alpha=0.1)
    ax.yaxis.set_major_formatter(mticker.FuncFormatter(lambda x, _: f'${x:,.0f}'))
    ax.set_title('Revenue Trend', fontsize=14, fontweight='bold')
    ax.set_xlabel('Period')
    ax.set_ylabel('Revenue')
    ax.grid(True, alpha=0.3)
    plt.tight_layout()
    plt.savefig(output_path, dpi=150, bbox_inches='tight')
    plt.close()
    return output_path

def expense_breakdown_chart(categories, output_path):
    """Generate expense category pie chart."""
    expense_cats = {k: v for k, v in categories.items() 
                    if v > 0 and 'Revenue' not in k and 'Income' not in k}
    
    labels = list(expense_cats.keys())
    values = list(expense_cats.values())
    
    fig, ax = plt.subplots(figsize=(8, 8))
    wedges, texts, autotexts = ax.pie(
        values, labels=labels, autopct='%1.1f%%',
        startangle=90, pctdistance=0.85
    )
    ax.set_title('Expense Breakdown', fontsize=14, fontweight='bold')
    plt.tight_layout()
    plt.savefig(output_path, dpi=150, bbox_inches='tight')
    plt.close()
    return output_path

def variance_bar_chart(budget_vs_actual, output_path):
    """Generate budget vs actual variance chart."""
    categories = list(budget_vs_actual.keys())
    budgets = [budget_vs_actual[c]['budget'] for c in categories]
    actuals = [budget_vs_actual[c]['actual'] for c in categories]
    
    x = np.arange(len(categories))
    width = 0.35
    
    fig, ax = plt.subplots(figsize=(12, 6))
    bars1 = ax.bar(x - width/2, budgets, width, label='Budget', color='steelblue')
    bars2 = ax.bar(x + width/2, actuals, width, label='Actual', color='coral')
    
    ax.set_title('Budget vs Actual', fontsize=14, fontweight='bold')
    ax.set_xticks(x)
    ax.set_xticklabels(categories, rotation=45, ha='right')
    ax.yaxis.set_major_formatter(mticker.FuncFormatter(lambda x, _: f'${x:,.0f}'))
    ax.legend()
    ax.grid(True, alpha=0.3, axis='y')
    plt.tight_layout()
    plt.savefig(output_path, dpi=150, bbox_inches='tight')
    plt.close()
    return output_path

Step 4: PDF Generation

# scripts/generate_pdf.py
# Requires: pip install reportlab pillow

from reportlab.lib import colors
from reportlab.lib.pagesizes import letter
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch
from reportlab.platypus import (
    SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, Image, PageBreak
)
from reportlab.lib.enums import TA_CENTER, TA_RIGHT
from datetime import datetime

def generate_pl_report(data, chart_paths, output_path, company_name="PrecisionLedger Client"):
    """Generate a complete P&L PDF report."""
    doc = SimpleDocTemplate(
        output_path,
        pagesize=letter,
        rightMargin=0.75*inch,
        leftMargin=0.75*inch,
        topMargin=0.75*inch,
        bottomMargin=0.75*inch
    )
    
    styles = getSampleStyleSheet()
    
    # Custom styles
    title_style = ParagraphStyle(
        'Title', parent=styles['Title'],
        fontSize=20, textColor=colors.HexColor('#1a1a2e'),
        spaceAfter=6
    )
    subtitle_style = ParagraphStyle(
        'Subtitle', parent=styles['Normal'],
        fontSize=11, textColor=colors.HexColor('#666666'),
        spaceAfter=20, alignment=TA_CENTER
    )
    section_style = ParagraphStyle(
        'Section', parent=styles['Heading2'],
        fontSize=13, textColor=colors.HexColor('#1a1a2e'),
        spaceBefore=16, spaceAfter=8,
        borderPad=4
    )
    
    story = []
    
    # Header
    story.append(Paragraph(company_name, title_style))
    story.append(Paragraph(
        f"Profit & Loss Statement — {data['period']}", subtitle_style
    ))
    story.append(Paragraph(
        f"Generated: {datetime.now().strftime('%B %d, %Y')}", 
        ParagraphStyle('gen_date', parent=styles['Normal'], 
                       fontSize=9, textColor=colors.grey, alignment=TA_CENTER)
    ))
    story.append(Spacer(1, 0.25*inch))
    
    # Key metrics summary table
    story.append(Paragraph("Executive Summary", section_style))
    
    summary_data = [
        ["Metric", "Amount", "Margin"],
        ["Total Revenue", f"${data['revenue']:,.2f}", "—"],
        ["Cost of Goods Sold", f"${data['cogs']:,.2f}", 
         f"{data['cogs']/data['revenue']*100:.1f}%" if data['revenue'] else "—"],
        ["Gross Profit", f"${data['gross_profit']:,.2f}", 
         f"{data['gross_margin']:.1f}%"],
        ["Total Expenses", f"${data['expenses']:,.2f}", 
         f"{data['expenses']/data['revenue']*100:.1f}%" if data['revenue'] else "—"],
        ["Net Income", f"${data['net_income']:,.2f}", 
         f"{data['net_margin']:.1f}%"],
    ]
    
    summary_table = Table(summary_data, colWidths=[3*inch, 2*inch, 1.5*inch])
    summary_table.setStyle(TableStyle([
        ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#1a1a2e')),
        ('TEXTCOLOR', (0, 0), (-1, 0), colors.white),
        ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
        ('FONTSIZE', (0, 0), (-1, 0), 11),
        ('ROWBACKGROUNDS', (0, 1), (-1, -1), [colors.white, colors.HexColor('#f8f9fa')]),
        ('FONTNAME', (0, -1), (-1, -1), 'Helvetica-Bold'),
        ('BACKGROUND', (0, -1), (-1, -1), colors.HexColor('#e8f4fd')),
        ('GRID', (0, 0), (-1, -1), 0.5, colors.HexColor('#dddddd')),
        ('ALIGN', (1, 0), (-1, -1), 'RIGHT'),
        ('TOPPADDING', (0, 0), (-1, -1), 8),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 8),
        ('LEFTPADDING', (0, 0), (0, -1), 12),
    ]))
    story.append(summary_table)
    story.append(Spacer(1, 0.25*inch))
    
    # Charts
    if 'revenue_trend' in chart_paths:
        story.append(Paragraph("Revenue Trend", section_style))
        story.append(Image(chart_paths['revenue_trend'], width=6.5*inch, height=3.25*inch))
        story.append(Spacer(1, 0.15*inch))
    
    if 'expense_breakdown' in chart_paths:
        story.append(Paragraph("Expense Breakdown", section_style))
        story.append(Image(chart_paths['expense_breakdown'], width=4*inch, height=4*inch))
    
    # Detailed category breakdown
    story.append(PageBreak())
    story.append(Paragraph("Detailed Breakdown", section_style))
    
    cat_data = [["Category", "Amount", "% of Revenue"]]
    for cat, amount in sorted(data['categories'].items(), key=lambda x: abs(x[1]), reverse=True):
        pct = f"{amount/data['revenue']*100:.1f}%" if data['revenue'] else "—"
        cat_data.append([cat, f"${amount:,.2f}", pct])
    
    cat_table = Table(cat_data, colWidths=[3.5*inch, 2*inch, 1.5*inch])
    cat_table.setStyle(TableStyle([
        ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#1a1a2e')),
        ('TEXTCOLOR', (0, 0), (-1, 0), colors.white),
        ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
        ('ROWBACKGROUNDS', (0, 1), (-1, -1), [colors.white, colors.HexColor('#f8f9fa')]),
        ('GRID', (0, 0), (-1, -1), 0.5, colors.HexColor('#dddddd')),
        ('ALIGN', (1, 0), (-1, -1), 'RIGHT'),
        ('TOPPADDING', (0, 0), (-1, -1), 6),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 6),
        ('LEFTPADDING', (0, 0), (0, -1), 12),
    ]))
    story.append(cat_table)
    
    doc.build(story)
    return output_path

Step 5: Distribution

# scripts/distribute_report.py

def distribute_via_email(report_path, recipients, subject, body):
    """Distribute report via email (use gog skill for Gmail)."""
    # Use: gog send --to recipient@email.com --subject "..." --attach report.pdf --body "..."
    # Or use himalaya skill for IMAP/SMTP
    # REQUIRES Irfan approval before sending to external clients
    pass

def distribute_via_telegram(report_path, chat_id):
    """Send report to Telegram channel."""
    # Use message tool: action=sendAttachment, target=chat_id, filePath=report_path
    pass

Quick-Start Templates

Monthly P&L Report (Full Pipeline)

# 1. Set up output dirs
mkdir -p reports/{raw,charts,output}

# 2. Extract data (QBO/Sheets/CSV)
# → reports/raw/2026-02-pl.csv

# 3. Process + generate
python scripts/process_pl.py reports/raw/2026-02-pl.csv "February 2026" > reports/raw/pl-data.json

# 4. Generate charts
python scripts/generate_charts.py reports/raw/pl-data.json reports/charts/

# 5. Generate PDF
python scripts/generate_pdf.py reports/raw/pl-data.json reports/charts/ reports/output/PL-Feb2026.pdf

# 6. Review (ALWAYS before distribution)
open reports/output/PL-Feb2026.pdf

KPI Dashboard (Quick Summary)

# scripts/kpi_dashboard.py
# Generates a one-page KPI card PDF

KPI_DEFINITIONS = {
    'Gross Margin': {'target': 0.65, 'format': 'percent'},
    'Net Margin': {'target': 0.20, 'format': 'percent'},
    'Revenue Growth MoM': {'target': 0.05, 'format': 'percent'},
    'AR Days Outstanding': {'target': 30, 'format': 'days', 'lower_is_better': True},
    'Cash Runway': {'target': 6, 'format': 'months'},
    'Billable Utilization': {'target': 0.80, 'format': 'percent'},
}

Variance Report (Budget vs Actual)

# Compare budget to actuals and flag variances > threshold
VARIANCE_THRESHOLD = 0.10  # 10% triggers flag

def flag_variances(budget_vs_actual, threshold=VARIANCE_THRESHOLD):
    flags = []
    for category, values in budget_vs_actual.items():
        if values['budget'] > 0:
            variance_pct = (values['actual'] - values['budget']) / values['budget']
            if abs(variance_pct) > threshold:
                direction = 'over' if variance_pct > 0 else 'under'
                flags.append({
                    'category': category,
                    'budget': values['budget'],
                    'actual': values['actual'],
                    'variance_pct': variance_pct,
                    'direction': direction,
                    'severity': 'HIGH' if abs(variance_pct) > 0.25 else 'MEDIUM'
                })
    return sorted(flags, key=lambda x: abs(x['variance_pct']), reverse=True)

Report Naming Conventions

reports/
├── raw/           ← source data (CSV, JSON exports)
├── charts/        ← generated chart images (PNG)
├── output/        ← final PDFs
│   ├── PL-YYYY-MM-{ClientCode}.pdf
│   ├── BS-YYYY-MM-{ClientCode}.pdf
│   ├── CF-YYYY-MM-{ClientCode}.pdf
│   ├── KPI-YYYY-MM-{ClientCode}.pdf
│   └── BVA-YYYY-MM-{ClientCode}.pdf  ← Budget vs Actual
└── templates/     ← reusable layout templates

Dependencies

# Python packages
pip install reportlab matplotlib pillow pandas numpy

# Verify
python -c "import reportlab, matplotlib, pandas; print('OK')"

Safety & Compliance Rules

  1. Never distribute to external parties without Irfan's explicit approval
  2. Always review PDF before sending — no automated external distribution
  3. Client data stays in reports/raw/ only — never commit to git
  4. Watermark drafts — add "DRAFT" overlay until final review
  5. Audit trail — log every distribution: reports/distribution-log.json
  6. PII handling — redact employee SSNs, salaries from any shared reports

Integration Points

System How to Connect Direction
QuickBooks Online QBO skill / CSV export Read only
Google Sheets gog sheets skill Read / Write summary
Email (Gmail) gog mail / himalaya skill Send (with approval)
Telegram message tool Send PDF
File System Direct path Read/Write reports/

When NOT to Use This Skill

  • Real-time BI dashboards — Use Looker, Power BI, or Tableau instead
  • Regulatory/tax filings — These require human sign-off and certified software
  • Live transaction streams — This skill works on batch/period-end data
  • Ad hoc data questions — Just run a direct financial analysis, don't generate a full report
  • Data entry or corrections — This is output-only; never write back to source systems

推荐文章

更多
PHP时间戳与日期字符串相互转换方法详解

本文介绍PHP中时间数值(Unix时间戳)与日期字符串之间的相互转换方法。通过strtotime和date函数,实现将当前时间、指定日期转换为时间戳,以及将时间戳格式化为可读的日期时间字符串,并提供相关在线计算工具推荐。

2025.11.30 1,034
PHP日期转时间戳时区偏差怎么解决

在 PHP 中将日期字符串转换为时间戳时,若未显式指定时区,默认使用脚本配置的 date.timezone 或系统时区。当服务器时区与业务逻辑预期(如 UTC )不一致时,会产生偏差。解决核心是确保输入字符串携带明确时区信息,或在转换前统一设置时区上下文。

2026.10.24 1,031
PHP跨域配置:怎么安全地允许指定域名而非使用通配符

在 PHP 中安全地允许指定域名跨域,核心是解析请求头中的 Origin ,验证其是否在白名单内,然后动态设置 Access-Control-Allow-Origin 响应头。不要使用通配符 * ,也不要硬编码单一域名。

2025.03.29 1,018
JavaScript中利用replace结合正则实现replaceAll效果

JavaScript原生仅支持replace()进行单次或全局替换,缺乏类似Java的replaceAll()便捷方法。本文总结四种在JS中实现全量替换的方案:使用带g标志的正则、带gm标志的正则、扩展String原型以及split后join。通过对比代码示例,展示各方法的实现细节与适用场景,帮助开发者根据需求选择最优解。

2025.04.29 1,017
OpenAI的Jalapeno芯片未落地,教你分辨300兆瓦算力消息

OpenAI计划在SB Energy租赁的数据中心部署约300兆瓦自研Jalapeno推理芯片,但目前双方仍处于洽谈阶段,交易细节与上线时间表均未公布。本文带你按报道原文核实项目所处阶段,厘清芯片发布、电力功率与实际推理算力的边界,并将融资意向与签约、开工、投运节点分开追踪,避免误将规划容量计入现有算力。

2026.12.02 1,013
PHP实现基础文件上传:HTML表单与$_FILES处理流程

在 HTML 表单中设置 enctype="multipart/form-data" ,并在 PHP 后端通过 $_FILES 数组接收文件,调用 move_uploaded_file() 将临时文件移动到目标目录即可完成上传。

2026.09.07 1,013
Skill 文件
  • SKILL.md
    • Report Generator Skill
    • Core Capabilities
      • 1. Financial Report Types
      • 2. Business Reports
    • Workflow
      • Step 1: Data Collection
      • Step 2: Data Processing
      • Step 3: Chart Generation
      • Step 4: PDF Generation
      • Step 5: Distribution
    • Quick-Start Templates
      • Monthly P&L Report (Full Pipeline)
      • KPI Dashboard (Quick Summary)
      • Variance Report (Budget vs Actual)
    • Report Naming Conventions
    • Dependencies
    • Safety & Compliance Rules
    • Integration Points
    • When NOT to Use This Skill
  • 项目或源文件

相关 Skill

更多
service-qa-coach service-qa-coach Review support quality for chat, email, phone, social DM, or marketplace service teams. Use when a team needs a QA scorecard, failure-mode analysis, coaching plan, calibration checklist, or service-improvement brief without live ticketing, CRM, or contact-center system access.
高中数学作业批改助手 高中数学作业批改助手 >图片识别 直接读取学生手写作答照片,识别公式、符号、步骤 🧮 自动推导 根据题目自动生成参考答案和评分细则,无需教师预设 📊 逐步给分 每个关键步骤独立评分,体现过程分 📝 结构化报告 输出含识别内容、参考答案、逐步评分、改进建议的完整报告 🗂 批量批改 支持一次性批改多道题,最终汇总得分表
Vibration Analysis Vibration Analysis 分析来自CMS趋势、RMS/峰值、频谱及SCADA报警的风机传动链(主轴、齿轮箱、发电机)振动数据。
Traditional Bone Tool Making Basics Traditional Bone Tool Making Basics Use when you need custom, durable, repairable tools like awls, needles, scrapers, harpoons, or fishing hooks made from local animal bones or antlers and comm...
音频混音工具 音频混音工具 名称:Sound Mixing Tool(标识 sound-mixing-tool) 短简介(≤60字):音乐/音效响度精确对齐 + 融合混音工作流:用 ffmpeg 两段式 loudnorm 把多组素材 LUFS 偏差压到 <0.10,再最小干预融合、导出可进引擎的独立分轨。 标签/关键词:音频混音 响度匹配 LUFS ffmpeg 游戏音频 音效设计 Wwise FMOD 分轨导出 后期处理 触发词:混音 · 响度匹配 · LUFS 对齐 · MIX 版本 · 音乐音效分轨 · 融合 · 不打架 · 不能盖住 适用场景 :游戏音频集成、影视短视频配乐、播客后期