Metadata-Version: 2.4
Name: confluence-manager
Version: 1.0.6
Summary: A comprehensive Python library for creating and managing Atlassian Confluence pages programmatically
Home-page: https://github.com/Pandiyarajk/confluence_manager
Author: Pandiyaraj Karuppasamy
Author-email: pandiyarajk@live.com
License: MIT
Project-URL: Bug Reports, https://github.com/Pandiyarajk/confluence_manager/issues
Project-URL: Source, https://github.com/Pandiyarajk/confluence_manager
Project-URL: Documentation, https://github.com/Pandiyarajk/confluence_manager#readme
Project-URL: PyPI, https://pypi.org/project/confluence-manager/
Keywords: confluence atlassian api documentation automation page-builder
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Documentation
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Operating System :: OS Independent
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: atlassian-python-api>=3.41.0
Requires-Dist: pandas>=2.0.0
Requires-Dist: openpyxl>=3.1.0
Requires-Dist: matplotlib>=3.7.0
Requires-Dist: Pillow>=10.0.0
Requires-Dist: requests>=2.31.0
Requires-Dist: python-dotenv>=1.0.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: black>=22.0.0; extra == "dev"
Requires-Dist: flake8>=5.0.0; extra == "dev"
Requires-Dist: mypy>=0.990; extra == "dev"
Requires-Dist: build>=0.10.0; extra == "dev"
Requires-Dist: twine>=4.0.0; extra == "dev"
Provides-Extra: advanced
Requires-Dist: plotly>=5.14.0; extra == "advanced"
Requires-Dist: seaborn>=0.12.0; extra == "advanced"
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: keywords
Dynamic: license
Dynamic: license-file
Dynamic: project-url
Dynamic: provides-extra
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# confluence-manager

A Python library for creating and managing Atlassian Confluence pages programmatically — text, tables, charts, images, and more.

```bash
pip install confluence-manager
```

## Features

- **Text Formatting** — bold, italic, colors, headings, panels, status badges, code blocks
- **Tables** — from JSON, Excel, pandas DataFrames, or plain Python lists with full styling
- **Charts** — bar, line, pie, scatter charts via matplotlib; upload directly to pages
- **Images** — upload and embed any image as a page attachment
- **Fluent Builder API** — chain calls to assemble pages in a readable style
- **Cloud & Server** — works with Confluence Cloud and Server/Data Center

## Configuration

Create a `.env` file in your project (or set environment variables):

```bash
CONFLUENCE_URL=https://your-domain.atlassian.net
CONFLUENCE_USERNAME=your-email@example.com
CONFLUENCE_API_TOKEN=your-api-token-here
CONFLUENCE_CLOUD=true
```

Get an API token at: https://id.atlassian.com/manage-profile/security/api-tokens

## Quick Start

```python
from confluence_manager import ConfluenceConfig, ConfluencePageUpdater, PageBuilder

config = ConfluenceConfig()  # reads from .env / environment variables
updater = ConfluencePageUpdater(config)

page = (PageBuilder(updater)
    .add_heading("My First Page", level=1)
    .add_paragraph("This page was created with Python!")
    .add_list(["Easy to use", "Powerful features", "Great documentation"])
    .publish(space="YOUR_SPACE_KEY", title="Welcome Page")
)

print(f"Page created: {page['_links']['webui']}")
```

## Usage

### Text Formatting

```python
from confluence_manager import TextFormatter

fmt = TextFormatter()

bold    = fmt.bold("Important!")
colored = fmt.color("Alert", "red")
panel   = fmt.panel("Deployment complete", title="Info", style="info")
status  = fmt.status_macro("In Progress", color="Yellow")
code    = fmt.code_block("print('hello')", "python")
```

### Tables

```python
from confluence_manager import TableHandler, TableBuilder

# From a JSON file
table = TableHandler.create_table_from_json("data.json")

# From an Excel file
table = TableHandler.create_table_from_excel("report.xlsx", sheet_name="Q4")

# Fluent builder with styling
table = (TableBuilder()
    .add_header(["Task", "Status", "Owner"])
    .add_row(["Deploy", "Done", "Alice"])
    .add_row(["Review", "Pending", "Bob"])
    .set_header_colors(["#4A90E2", "#4A90E2", "#4A90E2"])
    .set_row_colors(["#D4EDDA", "#FFF3CD"])
    .build()
)
```

### Charts

```python
from confluence_manager import ChartGenerator

chart = ChartGenerator()

bar_path = chart.create_bar_chart(
    data={"Q1": 100000, "Q2": 125000, "Q3": 150000, "Q4": 175000},
    title="Quarterly Revenue",
    xlabel="Quarter",
    ylabel="Revenue ($)"
)

line_path = chart.create_line_chart(
    data={"Product A": [10, 15, 20, 25], "Product B": [15, 18, 22, 28]},
    title="Product Trends"
)

pie_path = chart.create_pie_chart(
    data={"North": 30, "South": 25, "East": 25, "West": 20},
    title="Regional Distribution"
)
```

### Full Page Builder

```python
from confluence_manager import ConfluenceConfig, ConfluencePageUpdater, PageBuilder

config  = ConfluenceConfig()
updater = ConfluencePageUpdater(config)

page = (PageBuilder(updater)
    .add_heading("Weekly Report", level=1)
    .add_panel("All targets met this week!", title="Summary", style="info")
    .add_heading("Metrics", level=2)
    .add_table_from_json("metrics.json")
    .add_heading("Action Items", level=2)
    .add_list(["Review Q4 budget", "Schedule team meeting"], ordered=True)
    .add_heading("Recent Changes", level=2)
    .add_code_block("git commit -m 'Fixed critical bug'", "bash")
    .publish(space="TEAM", title="Weekly Report")
)
```

### Update an Existing Page

```python
# publish() automatically updates if a page with the same title already exists
page = (PageBuilder(updater)
    .add_heading("Updated Report")
    .add_table_from_json("new_data.json")
    .publish(space="TEAM", title="Weekly Report")
)

# Or update explicitly by page ID (found in the page URL)
page = (PageBuilder(updater)
    .add_heading("Updated Report")
    .update(page_id="1234567890", title="Weekly Report")
)
```

## Reusable Table Functions

Four ready-to-use functions handle the full pipeline — load data, apply theme, create or update the page — with a single call.

| Function | Input | Use case |
|----------|-------|----------|
| `build_table(data, ...)` | list of dicts | Returns table HTML (no Confluence needed) |
| `build_table_from_json(path, ...)` | JSON file path | Returns table HTML |
| `publish_table(space, title, data, ...)` | list of dicts | Publishes directly to Confluence |
| `publish_table_from_json(space, title, path, ...)` | JSON file path | Publishes directly to Confluence |

### Color Themes

Available themes: **blue** (default) · **green** · **red** · **amber** · **purple** · **grey** · **teal**

Header background, header text, and alternating row colors are all set by the theme.

```python
from confluence_manager import THEMES, THEME_NAMES

print(THEME_NAMES)
# ['blue', 'green', 'red', 'amber', 'purple', 'grey', 'teal']

print(THEMES["blue"])
# {'header_bg': '#1565C0', 'header_text': '#FFFFFF', 'row_even': '#E3F2FD', 'row_odd': '#FFFFFF'}
```

### Status-Based Row Coloring

Pass `status_column` to automatically color rows based on cell values:

| Value (case-insensitive) | Row color |
|--------------------------|-----------|
| Done, Completed, Pass, Success | Green `#D4EDDA` |
| In Progress, Pending, Review, WIP | Yellow `#FFF3CD` |
| Failed, Error, Blocked, Cancelled | Red `#F8D7DA` |
| Todo, Not Started, Skipped, N/A | Grey `#E2E3E5` |

Unrecognised values fall back to the theme's alternating row colors.

### As a Python Package

```python
from confluence_manager import publish_table, publish_table_from_json

# From a list of dicts
publish_table(
    space="TEAM",
    title="Sprint Status",
    data=[
        {"Task": "Deploy API",  "Owner": "Alice", "Status": "Done"},
        {"Task": "Write tests", "Owner": "Bob",   "Status": "In Progress"},
        {"Task": "Code review", "Owner": "Carol", "Status": "Pending"},
    ],
    theme="blue",
    status_column="Status",
    description="Updated automatically every sprint.",
)

# From a JSON file — specific columns, green theme
page = publish_table_from_json(
    space="TEAM",
    title="Weekly Metrics",
    json_path="reports/weekly.json",
    columns=["Date", "Metric", "Value", "Status"],
    theme="green",
    status_column="Status",
)
print(page["_links"]["webui"])
```

**JSON file formats supported:**

```json
// List of objects (most common)
[{"Task": "Deploy", "Status": "Done"}, ...]

// Wrapped in a data key
{"data": [{"Task": "Deploy", "Status": "Done"}, ...]}

// Headers + rows arrays
{"headers": ["Task", "Status"], "rows": [["Deploy", "Done"], ...]}
```

### Build Table HTML Only (no Confluence connection)

```python
from confluence_manager import build_table, build_table_from_json

# Build HTML from data — useful for embedding in a larger PageBuilder chain
table_html = build_table(
    data=rows,
    theme="amber",
    status_column="Status",
)

table_html = build_table_from_json("data.json", theme="purple")
```

### As a CLI Tool

After `pip install confluence-manager`, a `confluence-manager` command is available:

```bash
# Minimal — blue theme, all columns
confluence-manager publish-table \
  --space TEAM \
  --title "Sprint Status" \
  --json sprint.json

# Full options
confluence-manager publish-table \
  --space TEAM \
  --title "Sprint Status" \
  --json sprint.json \
  --theme green \
  --status-column Status \
  --columns Task Owner Status DueDate \
  --heading "Sprint 42 — Status Board" \
  --description "Auto-published on every push to main."
```

Or call the module directly without installing:

```bash
python -m confluence_manager publish-table --space TEAM --title "Report" --json data.json
```

---

## GitHub Actions Workflow

Use `confluence-manager` in a workflow to publish pages automatically on push, schedule, or any event.

```yaml
# .github/workflows/publish-confluence.yml
name: Publish to Confluence

on:
  push:
    branches: [main]
  schedule:
    - cron: "0 8 * * 1"   # every Monday at 08:00 UTC

jobs:
  publish:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v6

      - uses: actions/setup-python@v6
        with:
          python-version: "3.13"

      - name: Install confluence-manager
        run: pip install confluence-manager

      - name: Publish table (CLI)
        env:
          CONFLUENCE_URL:       ${{ secrets.CONFLUENCE_URL }}
          CONFLUENCE_USERNAME:  ${{ secrets.CONFLUENCE_USERNAME }}
          CONFLUENCE_API_TOKEN: ${{ secrets.CONFLUENCE_API_TOKEN }}
          CONFLUENCE_CLOUD:     "true"
        run: |
          confluence-manager publish-table \
            --space TEAM \
            --title  "Weekly Status" \
            --json   reports/status.json \
            --theme  green \
            --status-column Status
```

**Or use a Python script** when you need a richer page (charts, multiple sections, etc.):

```yaml
      - name: Publish report (script)
        env:
          CONFLUENCE_URL:       ${{ secrets.CONFLUENCE_URL }}
          CONFLUENCE_USERNAME:  ${{ secrets.CONFLUENCE_USERNAME }}
          CONFLUENCE_API_TOKEN: ${{ secrets.CONFLUENCE_API_TOKEN }}
          CONFLUENCE_CLOUD:     "true"
        run: python publish.py
```

```python
# publish.py  — committed to your repo
from datetime import date
from confluence_manager import (
    ConfluenceConfig, ConfluencePageUpdater, PageBuilder,
    build_table_from_json,
)

config  = ConfluenceConfig()
updater = ConfluencePageUpdater(config)

page = (PageBuilder(updater)
    .add_heading(f"Weekly Report — {date.today()}", level=1)
    .add_paragraph("Automatically generated every Monday.")
    .add_heading("Metrics", level=2)
    .add_raw_html(build_table_from_json(
        "reports/metrics.json", theme="blue", status_column="Status"
    ))
    .add_heading("Action Items", level=2)
    .add_table_from_json("reports/actions.json")
    .publish(space="TEAM", title="Weekly Report")
)
print(f"Published: {page['_links']['webui']}")
```

Add your Confluence credentials as repository secrets under **Settings → Secrets and variables → Actions**.

## Security

- Never commit `.env` or credentials — add `.env` to `.gitignore`
- Use API tokens, not passwords, for Confluence Cloud
- Store secrets in your CI/CD secret store (GitHub Actions, GitLab CI, etc.)

## Troubleshooting

| Error | Cause | Fix |
|-------|-------|-----|
| `401 Unauthorized` | Wrong credentials | Check `CONFLUENCE_USERNAME` (use email for Cloud) and `CONFLUENCE_API_TOKEN` |
| `ValueError: ... is required` | Missing env vars | Ensure `.env` exists or environment variables are set |
| `403 Forbidden` | No write access | Grant your account write permission to the space |
| `ModuleNotFoundError: atlassian` | Package missing | `pip install confluence-manager` |

## API Reference

| Class | Purpose |
|-------|---------|
| `ConfluenceConfig` | Load credentials from env / `.env` |
| `ConfluenceClient` | Low-level page CRUD and file attachments |
| `TextFormatter` | Generate Confluence storage-format HTML |
| `TableHandler` | Build tables from JSON, Excel, DataFrames |
| `TableBuilder` | Fluent table construction with styling |
| `ChartGenerator` | Create and embed charts as images |
| `ConfluencePageUpdater` | Mid-level API combining all utilities |
| `PageBuilder` | Fluent page builder — chain and publish |

## License

MIT — see [LICENSE](LICENSE) for details.
