# easy-invoice/2.1.12/templates/invoices/builder.php

Easy Invoice – Invoice Generator, PDF Quotes &amp; Payments, version 2.1.12. 339 lines.

- Page: https://pluginprobe.com/plugins/easy-invoice/2.1.12/code/templates/invoices/builder.php
- Raw: https://pluginprobe.com/plugins/easy-invoice/2.1.12/raw/templates/invoices/builder.php
- Modified: 2025-08-16T13:51:26+00:00

Line numbers below start at 1. Link to a line or a range by appending a fragment to the
page URL, for example `https://pluginprobe.com/plugins/easy-invoice/2.1.12/code/templates/invoices/builder.php#L10-L20`.

```php
<?php
// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}

// Enqueue CSS and JS files for the builder page
wp_enqueue_style('easy-invoice-form', plugin_dir_url(__FILE__) . '../../assets/css/invoice-form.css', array(), '1.0.0');
wp_enqueue_script('easy-invoice-form', plugin_dir_url(__FILE__) . '../../assets/js/invoice-form.js', array('jquery'), '1.0.0', true);
wp_enqueue_script('easy-client-manager', plugin_dir_url(__FILE__) . '../../assets/js/client-manager.js', array('jquery'), '1.0.0', true);

use EasyInvoice\Providers\ClientServiceProvider;
use EasyInvoice\Providers\InvoiceServiceProvider;


// Get invoice ID if present in URL
$invoice_id = isset($_GET['invoice_id']) ? intval($_GET['invoice_id']) : 0;
$invoice = null;

// Check if this is a new invoice (no ID)
$is_new_invoice = ($invoice_id === 0);

// Default values for new invoice
$invoice_number_service = easy_invoice_get_invoice_number_service();
$invoice_data = array(
    'number' => $invoice_number_service->getNextNumber(),
    'date' => date('Y-m-d'),
    'due_date' => date('Y-m-d', strtotime('+30 days')),
    'client_id' => '',
    'client_name' => '',
    'client_email' => '',
    'client_phone' => '',
    'client_address' => '',
    'items' => array(),
    'notes' => '',
    'internal_notes' => '',
    'discount' => 0,
    'discount_type' => 'percentage',
    'calculation_method' => 'before_tax',
    'tax_rate' => 10,
    'prices_include_tax' => 'no',
    'payment_method' => 'bank_transfer',
    'payment_status' => 'unpaid',
    'currency' => 'USD',
    'currency_symbol' => '$',
    'title' => '',
    'description' => '',
    'terms' => '',
    'is_recurring' => 'no',
    'recurring_frequency' => '',
);

// Load clients for the dropdown
$client_repository = ClientServiceProvider::getClientRepository();
$clients = $client_repository->all();

// If editing an existing invoice, load its data
if ($invoice_id > 0) {
    // Get the invoice from repository
    $invoice_repository = InvoiceServiceProvider::getInvoiceRepository();
    $invoice = $invoice_repository->find($invoice_id);
} else {
    // Create a temporary WP_Post object for new invoice
    $empty_post = new WP_Post((object) array(
        'ID' => 0,
        'post_author' => get_current_user_id(),
        'post_date' => current_time('mysql'),
        'post_date_gmt' => current_time('mysql', 1),
        'post_title' => $invoice_data['number'],
        'post_status' => 'auto-draft',
        'comment_status' => 'closed',
        'ping_status' => 'closed',
        'post_name' => '',
        'post_modified' => current_time('mysql'),
        'post_modified_gmt' => current_time('mysql', 1),
        'post_parent' => 0,
        'guid' => '',
        'menu_order' => 0,
        'post_type' => \EasyInvoice\Constants\PostTypes::EASY_INVOICE_POST_TYPE,
        'post_mime_type' => '',
        'comment_count' => 0,
        'filter' => 'raw',
    ));
    
    $invoice = new \EasyInvoice\Models\Invoice($empty_post);
    
    // Set default values on the invoice object
    foreach ($invoice_data as $key => $value) {
        $setter = 'set' . easy_invoice_str_replace('_', '', ucwords($key, '_'));
        if (method_exists($invoice, $setter)) {
            // Handle client_id specially to avoid type errors
            if ($key === 'client_id' && empty($value)) {
                $invoice->setClientId(0);
            } else {
                $invoice->$setter($value);
            }
        }
    }
    
    // Initialize empty items array
    $invoice->setItems([]);
}

// Only load custom meta that's not handled by Invoice object
if ($invoice) {
    // These are still accessed from meta as they don't have model methods yet
    $invoice_data['terms'] = $invoice_id > 0 ? get_post_meta($invoice_id, '_easy_invoice_terms', true) : $invoice_data['terms'];
    $invoice_data['internal_notes'] = $invoice_id > 0 ? get_post_meta($invoice_id, '_easy_invoice_internal_notes', true) : $invoice_data['internal_notes'];
    $invoice_data['payment_method'] = $invoice_id > 0 ? get_post_meta($invoice_id, '_easy_invoice_payment_method', true) : $invoice_data['payment_method'];
    $invoice_data['payment_status'] = $invoice_id > 0 ? get_post_meta($invoice_id, '_easy_invoice_payment_status', true) : $invoice_data['payment_status'];
    $invoice_data['currency'] = $invoice_id > 0 ? get_post_meta($invoice_id, '_easy_invoice_currency_code', true) : $invoice_data['currency'];
    $invoice_data['currency_symbol'] = $invoice_id > 0 ? get_post_meta($invoice_id, '_easy_invoice_currency_position', true) : $invoice_data['currency_symbol'];
    $invoice_data['calculation_method'] = $invoice_id > 0 ? get_post_meta($invoice_id, '_easy_invoice_calculation_method', true) : $invoice_data['calculation_method'];
}

// Prepare invoice items JSON for JavaScript
$invoice_items_json = json_encode($invoice ? $invoice->getItems() : []);

// Create nonce for AJAX calls
$admin_nonce = wp_create_nonce('easy_invoice_admin_nonce');

// Prepare client data for JavaScript
$client_data_json = json_encode($client_data ?? null);

// Start output buffering to capture content
?>

<div id="easy-invoice-content" class="h-screen flex flex-col">
    <!-- Header -->
    <div class="bg-white shadow-sm w-full z-10">
        <div class="max-w-full mx-auto px-5">
            <div class="py-3 flex items-center justify-between">
                <div class="flex items-center">
                    <a href="<?php echo admin_url('admin.php?page=easy-invoice-all'); ?>" 
                       class="inline-flex items-center text-gray-600 hover:text-gray-900">
                        <i class="fas fa-arrow-left mr-2"></i>
                        <span>Back to Invoices</span>
                    </a>
                </div>
                <h1 class="text-lg font-semibold text-gray-800">
                    <?php 
                    if ($invoice_id && $invoice) {
                        $title = $invoice->title ?: $invoice->number ?: 'Untitled Invoice';
                        echo esc_html($title);
                    } else {
                        echo esc_html__('Create New Invoice', 'easy-invoice');
                    }
                    ?>
                </h1>
                <div class="flex items-center space-x-4">
                    <?php if ($invoice && $invoice_id > 0): ?>
                        <div class="flex items-center space-x-2">
                            <?php do_action('easy_invoice_builder_before_invoice_actions', $invoice); // Deposit info button appears here ?>
                        </div>
                    <?php endif; ?>
                    <button type="button" id="save-invoice-btn" class="inline-flex items-center px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                        <i class="fas fa-save mr-2"></i>
                        <span><?php echo (isset($_GET['invoice_id']) ? __('Update Invoice', 'easy-invoice') : __('Save Invoice', 'easy-invoice')); ?></span>
                    </button>
                    <button type="button" id="send-invoice-btn" class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                        <i class="fas fa-paper-plane mr-2"></i>
                        <span>Send Invoice</span>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Main Content -->
    <div class="flex-grow overflow-y-auto">
        <div class="max-w-full mx-auto px-5 py-5">
            <div id="ei-invoice-builder-grid" class="grid grid-cols-1 lg:grid-cols-2 gap-8">
                <!-- Left Panel - Editable Fields -->
                
                <?php  
                    include_once EASY_INVOICE_PLUGIN_DIR . 'templates/invoices/form.php';       

                    include_once EASY_INVOICE_PLUGIN_DIR . 'templates/invoices/live-preview.php';       
                ?>
            </div>

            <!-- Add Client Modal -->
            <div id="add_client_modal" class="hidden fixed inset-0 bg-gray-600 bg-opacity-75 overflow-y-auto h-full w-full z-50">
                <div class="relative top-20 mx-auto p-5 border w-11/12 md:w-2/3 lg:w-1/2 shadow-lg rounded-md bg-white">
                    <div class="flex justify-between items-center mb-4">
                        <h3 class="text-lg font-medium text-gray-900">Add New Client</h3>
                        <button type="button" class="close-modal text-gray-400 hover:text-gray-500">
                            <span class="sr-only">Close</span>
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                    
                    <?php 
                    // Unset the $client variable from the foreach loop to ensure clean add form
                    unset($client);
                    include_once EASY_INVOICE_PLUGIN_DIR . 'templates/client-form.php'; 
                    ?>
                </div>
            </div>

            <input type="hidden" name="invoice_template" id="invoice_template" value="<?php echo esc_attr($invoice ? $invoice->getTemplate() : 'standard'); ?>" />
        </div>
    </div>
</div>

<script type="text/javascript">
jQuery(document).ready(function($) {
    // Initialize easyInvoice object for client manager
    window.easyInvoice = {
        ajaxUrl: '<?php echo admin_url('admin-ajax.php'); ?>',
        nonce: '<?php echo wp_create_nonce('easy_invoice_nonce'); ?>',
        clientData: <?php echo $client_data_json; ?>,
        isPro: <?php echo easy_invoice_has_pro() ? 'true' : 'false'; ?>
    };
    
    // Handle Send Invoice button
    $('#send-invoice-btn').on('click', function(e) {
        e.preventDefault();
        
        // First save the invoice if it's not saved yet
        if ($('#invoice-id').val() == '0') {
            // Invoice not saved yet, save it first
            $('#save-invoice-btn').click();
            
            // Wait for save to complete, then send
            setTimeout(function() {
                if ($('#invoice-id').val() != '0') {
                    sendInvoiceEmail();
                } else {
                    if (typeof EasyInvoiceToast !== 'undefined') {
                        EasyInvoiceToast.warning('Please save the invoice first before sending.');
                    } else {
                        console.log('Please save the invoice first before sending.');
                    }
                }
            }, 2000);
        } else {
            // Invoice already saved, send directly
            sendInvoiceEmail();
        }
    });
    
    function sendInvoiceEmail() {
        const invoiceId = $('#invoice-id').val();
        
        if (invoiceId == '0') {
            if (typeof EasyInvoiceToast !== 'undefined') {
                EasyInvoiceToast.warning('Please save the invoice first before sending.');
            } else {
                console.log('Please save the invoice first before sending.');
            }
            return;
        }
        
        // Use the confirmation system instead of alert
        if (typeof EasyInvoiceConfirmation !== 'undefined') {
            EasyInvoiceConfirmation.confirmAction('send email', 'this invoice', function() {
                // Show loading state
                const $btn = $('#send-invoice-btn');
                const originalText = $btn.html();
                $btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-2"></i>Sending...');
                
                // Send AJAX request
                $.ajax({
                    url: window.easyInvoice.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'easy_invoice_send_invoice_email',
                        invoice_id: invoiceId,
                        nonce: '<?php echo wp_create_nonce('easy_invoice_send_invoice_email'); ?>'
                    },
                    success: function(response) {
                        if (response.success) {
                            if (typeof EasyInvoiceToast !== 'undefined') {
                                EasyInvoiceToast.success('Invoice email sent successfully!');
                            } else {
                                console.log('Invoice email sent successfully!');
                            }
                        } else {
                            if (typeof EasyInvoiceToast !== 'undefined') {
                                EasyInvoiceToast.error(response.data.message || 'Error sending email');
                            } else {
                                console.log('Error sending email: ' + (response.data.message || 'Unknown error'));
                            }
                        }
                    },
                    error: function() {
                        if (typeof EasyInvoiceToast !== 'undefined') {
                            EasyInvoiceToast.error('Error connecting to server');
                        } else {
                            console.log('Error connecting to server');
                        }
                    },
                    complete: function() {
                        // Reset button
                        $btn.prop('disabled', false).html(originalText);
                    }
                });
            });
        } else {
            // Fallback to browser confirm if confirmation system not available
            if (confirm('Send this invoice via email?')) {
                // Show loading state
                const $btn = $('#send-invoice-btn');
                const originalText = $btn.html();
                $btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-2"></i>Sending...');
                
                // Send AJAX request
                $.ajax({
                    url: window.easyInvoice.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'easy_invoice_send_invoice_email',
                        invoice_id: invoiceId,
                        nonce: '<?php echo wp_create_nonce('easy_invoice_send_invoice_email'); ?>'
                    },
                    success: function(response) {
                        if (response.success) {
                            alert('Invoice email sent successfully!');
                        } else {
                            alert(response.data.message || 'Error sending email');
                        }
                    },
                    error: function() {
                        alert('Error connecting to server');
                    },
                    complete: function() {
                        // Reset button
                        $btn.prop('disabled', false).html(originalText);
                    }
                });
            }
        }
    }
});
</script>



```
