• Skip to secondary menu
  • Skip to main content
  • Skip to primary sidebar
  • Home
  • Projects
  • Products
  • Themes
  • Tools
  • Request for Quote

Vengala Vinay

Having 12+ Years of Experience in Software Development

  • Home
  • WordPress
  • PHP
    • Codeigniter
  • Django
  • Magento
  • Selenium
  • Server
Home » Implementing automated compliance reporting for custom vendor commission records ledgers using TCPDF generator script

Implementing automated compliance reporting for custom vendor commission records ledgers using TCPDF generator script

Setting Up the Environment and Dependencies

To implement automated compliance reporting for custom vendor commission records ledgers, we’ll leverage PHP and the TCPDF library. This approach allows for dynamic PDF generation directly from your WordPress database, ensuring that your commission reports are always up-to-date and compliant with any internal or external auditing requirements. We’ll assume you have a WordPress installation with a custom database table or post type to store vendor commission data.

First, ensure you have Composer installed. If not, download and install it from getcomposer.org. Then, navigate to your WordPress theme’s directory (or a custom plugin directory if you prefer) in your terminal and run the following command to install TCPDF:

  • Navigate to your theme directory: cd wp-content/themes/your-theme-name
  • Run Composer to install TCPDF: composer require tecnickcom/tcpdf

This will create a vendor directory and download the TCPDF library. You’ll need to include the Composer autoloader in your PHP script to access the TCPDF classes.

Database Schema for Commission Records

For this example, let’s assume your commission data is stored in a custom table named wp_vendor_commissions with the following simplified structure:

  • id (INT, Primary Key, Auto Increment)
  • vendor_id (INT, Foreign Key to your vendors table)
  • invoice_id (INT, Foreign Key to your invoices table)
  • commission_amount (DECIMAL(10, 2))
  • commission_rate (DECIMAL(5, 2))
  • transaction_date (DATE)
  • payout_status (VARCHAR(50) – e.g., ‘Pending’, ‘Paid’, ‘Failed’)

If you’re using custom post types, you’ll need to adapt the data retrieval queries accordingly, using WP_Query and retrieving custom fields.

Core PHP Script for PDF Generation

Create a new PHP file, for instance, generate-commission-report.php, within your theme’s directory. This script will handle fetching data from the database and generating the PDF. We’ll include basic error handling and structure for a compliant report.

The script will need to include the Composer autoloader, instantiate TCPDF, set document properties, add a page, write content, and output the PDF. For a compliance report, it’s crucial to include details like report generation date, vendor information, transaction specifics, and calculated commission values.

generate-commission-report.php Script Breakdown

Here’s the core PHP script. Remember to replace placeholder database credentials and table names with your actual setup.

<?php
// Include Composer autoloader
require_once __DIR__ . '/vendor/autoload.php';

// --- Configuration ---
// Replace with your actual database connection details if not using WordPress global $wpdb
// For simplicity, we'll assume WordPress environment and use $wpdb
// If running this script outside of WordPress context, you'll need to establish a DB connection manually.

$report_title = "Vendor Commission Ledger Report";
$output_filename_prefix = "vendor_commission_report_";
$logo_path = __DIR__ . '/path/to/your/logo.png'; // Path to your company logo

// --- Helper Functions ---
function get_vendor_name($vendor_id) {
    // In a real WordPress setup, you'd query your vendors table or use WP functions
    // For this example, we'll use a placeholder.
    $vendors = [
        1 => 'Alpha Solutions',
        2 => 'Beta Services',
        3 => 'Gamma Enterprises',
    ];
    return isset($vendors[$vendor_id]) ? $vendors[$vendor_id] : 'Unknown Vendor';
}

// --- TCPDF Setup ---
class MYPDF extends TCPDF {
    // Page header
    public function Header() {
        // Logo
        if (file_exists($this->logo_path)) {
            $this->Image($this->logo_path, 10, 10, 30, '', '', '', 'T', false, 300, '', false, false, 0, false, false, false);
        }
        // Set font
        $this->SetFont('helvetica', 'B', 20);
        // Title
        $this->Cell(0, 15, $this->report_title, 0, false, 'C', 0, '', 0, false, 'M', 'M');
        // Line break
        $this->Ln(10);
    }

    // Page footer
    public function Footer() {
        // Position at 15 mm from bottom
        $this->SetY(-15);
        // Set font
        $this->SetFont('helvetica', 'I', 8);
        // Page number
        $this->Cell(0, 10, 'Page '.$this->getAliasNumPage().'/'.$this->getAliasNbPages(), 0, false, 'C', 0, '', 0, false, 'T', 'M');
        // Report generation timestamp
        $this->SetX(10); // Align to left margin
        $this->Cell(0, 10, 'Generated on: ' . date('Y-m-d H:i:s'), 0, false, 'L', 0, '', 0, false, 'T', 'M');
    }
}

// --- Data Retrieval ---
global $wpdb; // Access WordPress database object
$table_name = $wpdb->prefix . 'vendor_commissions';

// Example: Fetch all pending commissions for a specific vendor (or all)
// For compliance, you might want to filter by date range, payout status, etc.
$vendor_id_filter = isset($_GET['vendor_id']) ? intval($_GET['vendor_id']) : null;
$payout_status_filter = isset($_GET['payout_status']) ? sanitize_text_field($_GET['payout_status']) : 'Pending'; // Default to Pending

$sql = "SELECT * FROM {$table_name} WHERE payout_status = %s";
$params = [$payout_status_filter];

if ($vendor_id_filter) {
    $sql .= " AND vendor_id = %d";
    $params[] = $vendor_id_filter;
}

$sql .= " ORDER BY transaction_date ASC";

$commissions = $wpdb->get_results($wpdb->prepare($sql, $params));

if (!$commissions) {
    die("No commission records found matching the criteria.");
}

// --- PDF Generation ---

// Create new PDF document
$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// Set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Your Company Name');
$pdf->SetTitle($report_title);
$pdf->SetSubject('Vendor Commission Report');
$pdf->SetKeywords('commission, vendor, report, compliance');

// Set default header data (can be overridden in Header method)
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, $report_title, PDF_HEADER_STRING);

// Set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

// Set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

// Set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

// Set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

// Set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

// Add a page
$pdf->AddPage();

// Set font
$pdf->SetFont('helvetica', '', 10);

// Report Header
$pdf->Ln(5); // Add some space
$pdf->SetFont('helvetica', 'B', 14);
$pdf->Cell(0, 10, $report_title, 0, 1, 'C', 0, '', 0, false, 'T', 'M');
$pdf->SetFont('helvetica', '', 10);
$pdf->Cell(0, 5, 'Status: ' . ucfirst($payout_status_filter), 0, 1, 'C', 0, '', 0, false, 'T', 'M');
if ($vendor_id_filter) {
    $pdf->Cell(0, 5, 'Vendor: ' . get_vendor_name($vendor_id_filter), 0, 1, 'C', 0, '', 0, false, 'T', 'M');
}
$pdf->Ln(10);

// Table Header
$pdf->SetFont('helvetica', 'B', 10);
$pdf->SetFillColor(220, 220, 220); // Light grey background
$pdf->Cell(30, 7, 'Date', 1, 0, 'C', 1);
$pdf->Cell(40, 7, 'Vendor', 1, 0, 'C', 1);
$pdf->Cell(30, 7, 'Invoice ID', 1, 0, 'C', 1);
$pdf->Cell(30, 7, 'Commission Rate', 1, 0, 'C', 1);
$pdf->Cell(30, 7, 'Commission Amount', 1, 0, 'C', 1);
$pdf->Cell(30, 7, 'Status', 1, 1, 'C', 1);

// Table Rows
$pdf->SetFont('helvetica', '', 10);
$pdf->SetFillColor(255, 255, 255); // White background
$total_commission = 0;

foreach ($commissions as $commission) {
    $vendor_name = get_vendor_name($commission->vendor_id);
    $commission_amount = (float) $commission->commission_amount;
    $total_commission += $commission_amount;

    $pdf->Cell(30, 6, date('Y-m-d', strtotime($commission->transaction_date)), 1, 0, 'L', 0);
    $pdf->Cell(40, 6, $vendor_name, 1, 0, 'L', 0);
    $pdf->Cell(30, 6, $commission->invoice_id, 1, 0, 'C', 0);
    $pdf->Cell(30, 6, number_format($commission->commission_rate, 2) . '%', 1, 0, 'R', 0);
    $pdf->Cell(30, 6, '$' . number_format($commission_amount, 2), 1, 0, 'R', 0);
    $pdf->Cell(30, 6, $commission->payout_status, 1, 1, 'C', 0);
}

// Summary Row
$pdf->SetFont('helvetica', 'B', 10);
$pdf->SetFillColor(220, 220, 220);
$pdf->Cell(130, 7, 'Total Commission', 1, 0, 'R', 1); // Spans first 3 columns
$pdf->Cell(60, 7, '$' . number_format($total_commission, 2), 1, 1, 'R', 1);

// --- Output PDF ---
$current_date = date('Ymd');
$filename = $output_filename_prefix . $current_date . '.pdf';

// Output PDF to browser
$pdf->Output($filename, 'I'); // 'I' for inline display, 'D' for download

exit; // Ensure no other output is sent
?>

Integrating with WordPress

To make this script accessible and triggerable from your WordPress admin area, you can create a custom admin page or hook it into an existing one. A common approach is to create a new menu item in the WordPress dashboard.

Add the following code to your theme’s functions.php file or a custom plugin:

add_action('admin_menu', 'add_commission_report_menu');

function add_commission_report_menu() {
    add_menu_page(
        'Commission Reports',           // Page title
        'Commission Reports',           // Menu title
        'manage_options',               // Capability required
        'commission-reports',           // Menu slug
        'render_commission_report_page', // Callback function to display the page content
        'dashicons-chart-bar',          // Icon URL or Dashicon class
        80                              // Position in menu
    );
}

function render_commission_report_page() {
    ?>
    <div class="wrap">
        <h1>Generate Vendor Commission Report</h1>
        <form method="get" action="">
            <input type="hidden" name="page" value="commission-reports" />

            <label for="vendor_id">Filter by Vendor:</label>
            <select name="vendor_id" id="vendor_id">
                <option value="">All Vendors</option>
                 'Alpha Solutions',
                    2 => 'Beta Services',
                    3 => 'Gamma Enterprises',
                ];
                foreach ($vendors as $id => $name) {
                    $selected = (isset($_GET['vendor_id']) && $_GET['vendor_id'] == $id) ? 'selected' : '';
                    echo "<option value='{$id}' {$selected}>{$name}</option>";
                }
                ?>
            </select>
            <br /><br />

            <label for="payout_status">Filter by Payout Status:</label>
            <select name="payout_status" id="payout_status">
                <option value="Pending" Pending</option>
                <option value="Paid" Paid</option>
                <option value="Failed" Failed</option>
                <option value="" All Statuses</option>
            </select>
            <br /><br />

            <input type="submit" name="generate_report" class="button button-primary" value="Generate PDF Report" />
        </form>

        <?php
        // Logic to trigger the PDF generation script when the form is submitted
        if (isset($_GET['generate_report']) && $_GET['generate_report'] == 'Generate PDF Report') {
            // Construct the URL to the PDF generation script, passing GET parameters
            $pdf_script_url = admin_url('admin-ajax.php'); // Using AJAX handler is more robust
            // For direct execution, you might need to include the script directly or use a rewrite rule.
            // A simpler, though less clean, approach for demonstration:
            // Redirect to the PDF script with parameters.
            // This will navigate the user away from the admin page.

            $query_params = [];
            if (isset($_GET['vendor_id']) && !empty($_GET['vendor_id'])) {
                $query_params['vendor_id'] = intval($_GET['vendor_id']);
            }
            if (isset($_GET['payout_status']) && !empty($_GET['payout_status'])) {
                $query_params['payout_status'] = sanitize_text_field($_GET['payout_status']);
            }

            // Construct the full URL to your PDF script.
            // IMPORTANT: Ensure this script is accessible and correctly placed.
            // For example, if it's in your theme directory:
            $pdf_script_path = get_template_directory_uri() . '/generate-commission-report.php';
            $full_pdf_url = $pdf_script_path . '?' . http_build_query($query_params);

            // Redirect to the PDF generation script
            echo '<script>window.location.href="' . esc_url($full_pdf_url) . '";</script>';
            exit; // Stop further execution on this page
        }
        ?>
    </div>
    <?php
}

// Helper function for selected attribute in select options
function selected( $value, $current = false, $echo = true ) {
    $selected = '';
    if ( $value === $current ) {
        $selected = ' selected="selected"';
        if ( $echo ) {
            echo $selected;
        }
    }
    return $selected;
}
?>

In this integration:

  • add_action('admin_menu', 'add_commission_report_menu'); hooks a function to add a new page to the WordPress admin menu.
  • add_menu_page() creates the menu item.
  • render_commission_report_page() is the callback function that displays the HTML form for filtering and generating the report.
  • The form uses GET parameters to pass filter criteria (vendor_id, payout_status).
  • When the “Generate PDF Report” button is clicked, the form submits, and the PHP code within render_commission_report_page checks for the submission.
  • It then constructs the URL to your generate-commission-report.php script, appending the filter parameters, and redirects the user to that URL.
  • The generate-commission-report.php script (which must be placed in your theme’s root directory or a known path) will then execute, fetch data, and output the PDF.
  • The selected() helper function is a common WordPress utility to set the selected attribute for <option> tags.

Security and Compliance Considerations

For robust compliance, consider these points:

  • Access Control: The manage_options capability in add_menu_page restricts access to administrators. Adjust this based on your user roles and permissions.
  • Data Validation: Always sanitize and validate all input, especially data coming from GET/POST requests (e.g., intval() for IDs, sanitize_text_field() for strings). The script already includes basic sanitization.
  • Audit Trails: Log report generation events (who generated what report, when, and with which parameters) in a separate audit log table. This is crucial for compliance.
  • Data Integrity: Ensure the commission data itself is accurate and has been validated before being stored. The report is only as good as the data it represents.
  • Secure Storage: If sensitive data is included, ensure your WordPress installation and database are secured against unauthorized access.
  • Report Content: The report should clearly state the period covered, the vendor, the specific transactions, commission calculations, and any relevant terms or disclaimers.
  • Error Handling: Implement comprehensive error logging for both the database queries and the PDF generation process. Use error_log() or a dedicated logging plugin.
  • Dependencies: Keep your TCPDF library and WordPress core updated to patch security vulnerabilities.

Advanced Enhancements

To further enhance this solution:

  • AJAX Integration: Instead of a direct redirect, use AJAX to call the PDF generation script. This keeps the user on the admin page and provides a better user experience, allowing for loading indicators. You would hook into admin_ajax_nopriv_generate_commission_report and admin_ajax_generate_commission_report.
  • Date Range Filters: Add start and end date input fields to the form for more flexible reporting periods.
  • Batch Generation: Implement functionality to generate reports for multiple vendors or for a specific date range in one go.
  • Scheduled Reports: Use WP-Cron to schedule regular report generation (e.g., weekly or monthly) and email them to stakeholders.
  • Customizable Templates: Allow users to select different report templates or customize the layout and fields included in the PDF.
  • Digital Signatures: For enhanced compliance, explore libraries that support adding digital signatures to PDFs.
  • Internationalization: Ensure your script handles different date formats, currencies, and languages if your application serves a global audience.

By following these steps, you can build a robust and automated system for generating compliant vendor commission reports directly within your WordPress environment.

Primary Sidebar

A little about the Author

Having 12+ Years of Experience in Software Development, Vinay is a principal software architect, senior systems engineer, and elite technical consultant. He specializes in bespoke PHP/WordPress development, high-performance Magento 2 & Shopify architectures, custom plugin/theme development from scratch, and legacy code modernization (including VB6, VB.NET, PyQt, and Crystal Reports). Known for solving complex database bottlenecks, speed optimization (Core Web Vitals), and advanced security code auditing, Vinay engineers production-ready systems designed to scale under heavy concurrent load conditions.



Chat on WhatsApp

Recent Posts

  • Debugging Guide: Diagnosing PHP-FPM child process pool exhaustion in multi-site network environments with modern tools
  • Debugging and Resolving complex namespace class loading collisions issues during heavy concurrent database traffic
  • Step-by-Step Guide: Offloading high-frequency customer support tickets metadata writes to a Redis KV store
  • How to refactor legacy event ticket registers queries using modern WP_Query and custom Transient caching
  • Step-by-Step Guide: Offloading high-frequency member profile directories metadata writes to a Redis KV store

Categories

  • apache (1)
  • Business & Monetization (390)
  • Centos (4)
  • Comparisons & Decision Making (55)
  • Debian (2)
  • Debugging & Troubleshooting (662)
  • Desktop Applications (14)
  • DevOps (7)
  • DevOps & Cloud Scaling (962)
  • Django (1)
  • Laravel (4)
  • Migration & Architecture (192)
  • Mobile Applications (24)
  • MySQL (1)
  • Performance & Optimization (873)
  • PHP (5)
  • PHP Development (49)
  • Plugins & Themes (244)
  • Programming Languages (9)
  • Python (20)
  • Ruby on Rails (1)
  • Security & Compliance (647)
  • SEO & Growth (492)
  • Server (118)
  • Ubuntu (9)
  • VB6 & VB.NET (8)
  • Web Applications & Frontend (19)
  • Web Assembly (Wasm) (2)
  • WordPress (22)
  • WordPress Plugin Development (726)
  • WordPress Theme Development (357)

Recent Posts

  • Debugging Guide: Diagnosing PHP-FPM child process pool exhaustion in multi-site network environments with modern tools
  • Debugging and Resolving complex namespace class loading collisions issues during heavy concurrent database traffic
  • Step-by-Step Guide: Offloading high-frequency customer support tickets metadata writes to a Redis KV store

Top Categories

  • DevOps & Cloud Scaling (962)
  • Performance & Optimization (873)
  • WordPress Plugin Development (726)
  • Debugging & Troubleshooting (662)
  • Security & Compliance (647)
  • SEO & Growth (492)

Our Products

  • ERP & LMS Systems (4)
  • Directories & Marketplaces (4)
  • Healthcare Portals (3)
  • Point of Sale (POS) (2)
  • E-Commerce Engines (2)

Our Services

  • E-Commerce Development (10)
  • WordPress Development (8)
  • Python & Desktop GUI (7)
  • General Consulting (7)
  • Legacy Modernization (5)
  • Mobile App Development (4)

Copyright © 2026 · Vinay Vengala