PluginProbe
Easy Invoice – Invoice Generator, PDF Quotes & Payments / 2.4.2
Easy Invoice – Invoice Generator, PDF Quotes & Payments v2.4.2
2.4.3 2.4.4 2.4.2 2.4.0 2.4.1 2.3.8 2.3.7 2.3.6 2.3.5 2.3.4 2.3.3 2.3.2 2.3.1 2.2.0 2.1.21 2.1.20 2.1.19 2.1.18 2.1.0 2.1.1 2.1.10 2.1.11 2.1.12 2.1.13 2.1.14 All 60 releases
← All changes | includes/Controllers/PaymentController.php +872 -468 2.1.19 → 2.4.2 View file →
@@ -29,8 +29,15 @@
29 29 use TemplateTrait;
30 30 use PaymentCalculationTrait;
31 31
32 32 /**
33 + * First Easy Invoice Pro release whose gateway scripts forward the per-invoice
34 + * access token to `easy_invoice_process_payment`. Older builds need the
35 + * compatibility path in legacyProPaymentFallbackAllowed().
36 + */
37 + const PRO_TOKEN_FORWARDING_VERSION = '2.3.0';
38 +
39 + /**
33 40 * Payment gateway manager instance
34 41 *
35 42 * @var PaymentGatewayManager
36 43 */
@@ -50,8 +57,9 @@
50 57 add_action('admin_enqueue_scripts', [$this, 'enqueueAssets']);
51 58 add_action('wp_ajax_easy_invoice_process_payment', [$this, 'processPayment']);
52 59 add_action('wp_ajax_nopriv_easy_invoice_process_payment', [$this, 'processPayment']);
53 60 add_action('wp_ajax_easy_invoice_update_payment', [$this, 'updatePayment']);
61 + add_action('wp_ajax_easy_invoice_record_payment', [$this, 'recordPayment']);
54 62 add_action('wp_ajax_easy_invoice_payment_callback', [$this, 'handleCallback']);
55 63 add_action('wp_ajax_nopriv_easy_invoice_payment_callback', [$this, 'handleCallback']);
56 64 add_action('wp_ajax_easy_invoice_verify_manual_payment', [$this, 'verifyManualPayment']);
57 65 add_action('wp_ajax_easy_invoice_reject_manual_payment', [$this, 'rejectManualPayment']);
@@ -74,20 +82,19 @@
74 82 add_action('wp_enqueue_scripts', [$this, 'enqueueFrontendAssets']);
75 83
76 84 // Handler for admin to mark an invoice as paid
77 85 add_action('wp_ajax_easy_invoice_approve_payment', [$this, 'mark_invoice_paid_ajax']);
86 + add_action('wp_ajax_easy_invoice_reject_payment', [$this, 'rejectPayment']);
87 + // Receipts clients attach to offline payments; staff-only, streamed by PHP.
88 + add_action('admin_post_' . \EasyInvoice\Services\OfflinePayments::PROOF_ACTION, ['\\EasyInvoice\\Services\\OfflinePayments', 'serveProof']);
89 + // Signed-out staff following the emailed link are sent to log in and back.
90 + add_action('before_delete_post', ['\\EasyInvoice\\Services\\OfflinePayments', 'deleteProofWithPayment'], 10, 2);
91 + add_action('admin_post_nopriv_' . \EasyInvoice\Services\OfflinePayments::PROOF_ACTION, ['\\EasyInvoice\\Services\\OfflinePayments', 'serveProof']);
78 92
79 93 // Stripe payment handlers moved to Pro plugin
80 94
81 95 add_action('wp_enqueue_scripts', [$this, 'enqueueScripts']);
82 96
83 - // Add filter to show pending payments in admin
84 - add_filter('easy_invoice_admin_payment_statuses', [$this, 'addPendingPaymentStatuses']);
85 -
86 - // Add custom columns to payments list
87 - add_filter('manage_easy-payment_posts_columns', [$this, 'addPaymentMethodColumn']);
88 - add_action('manage_easy-payment_posts_custom_column', [$this, 'renderPaymentMethodColumn'], 10, 2);
89 -
90 97 // Add reminder CRON job for pending payments
91 98 add_action('easy_invoice_payment_reminder', [$this, 'sendPaymentReminders']);
92 99 if (!wp_next_scheduled('easy_invoice_payment_reminder')) {
93 100 wp_schedule_event(time(), 'daily', 'easy_invoice_payment_reminder');
@@ -100,16 +107,18 @@
100 107 /**
101 108 * Get payment instructions for manual gateways
102 109 */
103 110 public function getPaymentInstructions() {
104 - // Verify nonce
105 - if (!wp_verify_nonce($_POST['nonce'], 'easy_invoice_payment')) {
111 + // Verify nonce. $_POST['nonce'] was read unguarded, raising an
112 + // undefined-index warning before the check could run.
113 + $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
114 + if (!wp_verify_nonce($nonce, 'easy_invoice_payment')) {
106 115 wp_send_json_error(['message' => 'Security check failed']);
107 116 return;
108 117 }
109 118
110 - $gateway = sanitize_text_field($_POST['gateway']);
111 - $invoice_id = intval($_POST['invoice_id']);
119 + $gateway = sanitize_text_field(($_POST['gateway'] ?? ''));
120 + $invoice_id = intval(($_POST['invoice_id'] ?? ''));
112 121
113 122 if (!$gateway || !$invoice_id) {
114 123 wp_send_json_error(['message' => 'Missing required parameters']);
115 124 return;
@@ -123,8 +132,25 @@
123 132 }
124 133
125 134 $invoice = new \EasyInvoice\Models\Invoice($invoice_post);
126 135
136 + // Authorisation.
137 + //
138 + // The previous guard here was `!easy_invoice_user_can('ei_view_invoices') &&
139 + // $invoice_post->post_status !== 'publish'`. That never fired: Models\Invoice
140 + // writes every invoice with post_status 'publish' regardless of workflow
141 + // status, so the second condition was always false. This endpoint is
142 + // registered nopriv and the nonce it checks is a shared, page-wide one, so
143 + // any caller could read the rendered payment instructions — which include
144 + // invoice-specific detail — for an arbitrary invoice id.
145 + //
146 + // Same check as everywhere else: valid ?ik= / access_token, administrator, or
147 + // the signed-in client the invoice belongs to.
148 + if (!\EasyInvoice\Controllers\InvoiceController::canSubmitPaymentForInvoice($invoice_id, $invoice)) {
149 + wp_send_json_error(['message' => __('Invoice not found', 'easy-invoice')]);
150 + return;
151 + }
152 +
127 153 // Get gateway instance
128 154 $gateway_instance = $this->gatewayManager->getGateway($gateway);
129 155
130 156 if (!$gateway_instance) {
@@ -182,12 +208,22 @@
182 208 '1.0.0',
183 209 true
184 210 );
185 211
186 - // Localize script
212 + // Forward the per-invoice access token from the URL to the JS
213 + // so the manual-payment AJAX request can present it back to
214 + // canSubmitPaymentForInvoice. Without this the legitimate
215 + // email-link recipient flow would break — they'd hit the gate.
216 + $access_token = isset($_GET['ik'])
217 + ? sanitize_text_field(wp_unslash($_GET['ik']))
218 + : '';
219 + /** This filter is documented in includes/Controllers/InvoiceController.php */
220 + $access_token = (string) apply_filters('easy_invoice_presented_access_token', $access_token, 'invoice');
221 +
187 222 wp_localize_script('easy-invoice-manual-payment', 'easy_invoice_ajax', [
188 - 'ajax_url' => admin_url('admin-ajax.php'),
189 - 'nonce' => wp_create_nonce('easy_invoice_payment')
223 + 'ajax_url' => admin_url('admin-ajax.php'),
224 + 'nonce' => wp_create_nonce('easy_invoice_payment'),
225 + 'access_token' => $access_token,
190 226 ]);
191 227 }
192 228 }
193 229
@@ -216,15 +252,15 @@
216 252 try {
217 253 $payment = new Payment($payment_post);
218 254 $this->displayTemplate(EASY_INVOICE_PLUGIN_DIR . 'templates/payments/view.php', ['payment' => $payment]);
219 255 } catch (\Exception $e) {
220 - wp_die(__('Invalid payment ID', 'easy-invoice'));
256 + wp_die(esc_html__('Invalid payment ID', 'easy-invoice'));
221 257 }
222 258 } else {
223 - wp_die(__('Invalid payment ID', 'easy-invoice'));
259 + wp_die(esc_html__('Invalid payment ID', 'easy-invoice'));
224 260 }
225 261 } else {
226 - wp_die(__('Payment ID is required', 'easy-invoice'));
262 + wp_die(esc_html__('Payment ID is required', 'easy-invoice'));
227 263 }
228 264 break;
229 265
230 266 case 'edit':
@@ -235,15 +271,15 @@
235 271 try {
236 272 $payment = new Payment($payment_post);
237 273 $this->displayTemplate(EASY_INVOICE_PLUGIN_DIR . 'templates/payments/edit.php', ['payment' => $payment]);
238 274 } catch (\Exception $e) {
239 - wp_die(__('Invalid payment ID', 'easy-invoice'));
275 + wp_die(esc_html__('Invalid payment ID', 'easy-invoice'));
240 276 }
241 277 } else {
242 - wp_die(__('Invalid payment ID', 'easy-invoice'));
278 + wp_die(esc_html__('Invalid payment ID', 'easy-invoice'));
243 279 }
244 280 } else {
245 - wp_die(__('Payment ID is required', 'easy-invoice'));
281 + wp_die(esc_html__('Payment ID is required', 'easy-invoice'));
246 282 }
247 283 break;
248 284
249 285 default:
@@ -284,12 +320,14 @@
284 320 }
285 321
286 322 // Add status filter if set
287 323 if (!empty($status_filter)) {
288 - $args['meta_query'] = array(
324 + // "pending" covers every awaiting-confirmation variant older versions wrote.
325 + $args['meta_query'] = array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
289 326 array(
290 - 'key' => '_status',
291 - 'value' => $status_filter,
327 + 'key' => '_status',
328 + 'value' => 'pending' === $status_filter ? \EasyInvoice\Services\OfflinePayments::pendingStatuses() : $status_filter,
329 + 'compare' => 'pending' === $status_filter ? 'IN' : '=',
292 330 ),
293 331 );
294 332 }
295 333
@@ -320,64 +358,45 @@
320 358 // Get pagination info from WordPress query
321 359 $total_payments = $wp_query->found_posts;
322 360 $total_pages = $wp_query->max_num_pages;
323 361
324 - // Calculate statistics from ALL payments (not just current page)
325 - $stats_args = array(
326 - 'post_type' => 'easy_invoice_payment',
327 - 'posts_per_page' => -1, // Get all payments
328 - 'meta_query' => array(
329 - array(
330 - 'key' => '_status',
331 - 'compare' => 'EXISTS',
332 - ),
333 - ),
334 - );
335 -
336 - // Set post status for stats based on current view
337 - if ($current_view === 'trash') {
338 - $stats_args['post_status'] = 'trash';
339 - } else {
340 - $stats_args['post_status'] = 'publish';
341 - }
342 -
343 - $stats_query = new \WP_Query($stats_args);
344 -
362 + // Statistics over ALL payments (not just the current page), in one SQL
363 + // pass. Loading every payment as a model to add them up did not scale.
364 + global $wpdb;
365 + $stats_status = 'trash' === $current_view ? 'trash' : 'publish';
366 + $stat_rows = $wpdb->get_results( $wpdb->prepare(
367 + "SELECT st.meta_value AS status, COUNT(*) AS n, SUM(CAST(COALESCE(NULLIF(a.meta_value, ''), '0') AS DECIMAL(18,4))) AS amount
368 + FROM {$wpdb->posts} p
369 + INNER JOIN {$wpdb->postmeta} st ON st.post_id = p.ID AND st.meta_key = '_status'
370 + LEFT JOIN {$wpdb->postmeta} a ON a.post_id = p.ID AND a.meta_key = '_amount'
371 + WHERE p.post_type = 'easy_invoice_payment' AND p.post_status = %s
372 + GROUP BY st.meta_value",
373 + $stats_status
374 + ), ARRAY_A );
345 375 $stats = [
346 - 'total_payments' => $stats_query->found_posts,
347 - 'total_amount' => 0,
376 + 'total_payments' => 0,
377 + 'total_amount' => 0,
348 378 'completed_payments' => 0,
349 - 'pending_payments' => 0,
350 - 'failed_payments' => 0
379 + 'pending_payments' => 0,
380 + 'failed_payments' => 0,
351 381 ];
352 -
353 - // Calculate stats from the query results
354 - if ($stats_query->have_posts()) {
355 - while ($stats_query->have_posts()) {
356 - $stats_query->the_post();
357 - $payment = new Payment(get_post());
358 -
359 - $amount = floatval($payment->getAmount());
360 - $status = $payment->getStatus();
361 -
362 - $stats['total_amount'] += $amount;
363 -
364 - switch ($status) {
365 - case 'completed':
366 - $stats['completed_payments']++;
367 - break;
368 - case 'pending':
369 - $stats['pending_payments']++;
370 - break;
371 - case 'failed':
372 - $stats['failed_payments']++;
373 - break;
374 - }
382 + foreach ( (array) $stat_rows as $row ) {
383 + $status = (string) $row['status'];
384 + $stats['total_payments'] += (int) $row['n'];
385 + // "Total amount" is money confirmed; submissions still waiting
386 + // for a decision, rejected and failed ones are not counted.
387 + if ( 'completed' === $status ) {
388 + $stats['total_amount'] += (float) $row['amount'];
375 389 }
390 + if ( in_array( $status, \EasyInvoice\Services\OfflinePayments::pendingStatuses(), true ) ) {
391 + $status = 'pending';
392 + }
393 + $key = $status . '_payments';
394 + if ( isset( $stats[ $key ] ) ) {
395 + $stats[ $key ] += (int) $row['n'];
396 + }
376 397 }
377 - wp_reset_postdata();
378 398
379 - // Ensure all required keys exist with default values
380 399 $stats = array_merge([
381 400 'total_payments' => 0,
382 401 'total_amount' => 0,
383 402 'completed_payments' => 0,
@@ -384,22 +403,48 @@
384 403 'pending_payments' => 0,
385 404 'failed_payments' => 0
386 405 ], $stats);
387 406
407 + // Money received, by currency, across every confirmed payment — the
408 + // header card used to add up only the rows on the page the admin
409 + // happened to be looking at.
410 + $currency_rows = $wpdb->get_results( $wpdb->prepare(
411 + "SELECT UPPER(COALESCE(NULLIF(c.meta_value, ''), %s)) AS currency,
412 + MAX(sym.meta_value) AS symbol,
413 + SUM(CAST(COALESCE(NULLIF(a.meta_value, ''), '0') AS DECIMAL(18,4))) AS amount
414 + FROM {$wpdb->posts} p
415 + INNER JOIN {$wpdb->postmeta} st ON st.post_id = p.ID AND st.meta_key = '_status' AND st.meta_value = 'completed'
416 + LEFT JOIN {$wpdb->postmeta} a ON a.post_id = p.ID AND a.meta_key = '_amount'
417 + LEFT JOIN {$wpdb->postmeta} c ON c.post_id = p.ID AND c.meta_key = '_currency'
418 + LEFT JOIN {$wpdb->postmeta} sym ON sym.post_id = p.ID AND sym.meta_key = '_currency_symbol'
419 + WHERE p.post_type = 'easy_invoice_payment' AND p.post_status = %s
420 + GROUP BY currency",
421 + get_option('easy_invoice_currency_code', 'USD'),
422 + $stats_status
423 + ), ARRAY_A );
424 + $amounts_by_currency = [];
425 + foreach ( (array) $currency_rows as $row ) {
426 + $code = 'GLOBAL' === $row['currency'] || '' === (string) $row['currency']
427 + ? strtoupper( (string) get_option('easy_invoice_currency_code', 'USD') )
428 + : (string) $row['currency'];
429 + if ( ! isset( $amounts_by_currency[ $code ] ) ) {
430 + $amounts_by_currency[ $code ] = [
431 + 'amount' => 0.0,
432 + 'symbol' => (string) ( $row['symbol'] ?: \EasyInvoice\Helpers\CurrencyHelper::getCurrencySymbol( $code ) ),
433 + ];
434 + }
435 + $amounts_by_currency[ $code ]['amount'] += (float) $row['amount'];
436 + }
437 +
388 438 // Get trash count for tab display
389 - $trash_args = array(
390 - 'post_type' => 'easy_invoice_payment',
391 - 'post_status' => 'trash',
392 - 'posts_per_page' => -1
393 - );
394 - $trash_query = new \WP_Query($trash_args);
395 - $trash_count = $trash_query->found_posts;
439 + $trash_count = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_type = 'easy_invoice_payment' AND post_status = 'trash'" );
396 440
397 441 // Define available status filters
398 442 $status_filters = array(
399 - 'completed' => 'Completed',
400 - 'pending' => 'Pending',
401 - 'failed' => 'Failed'
443 + 'completed' => __('Completed', 'easy-invoice'),
444 + 'pending' => __('Awaiting confirmation', 'easy-invoice'),
445 + 'rejected' => __('Rejected', 'easy-invoice'),
446 + 'failed' => __('Failed', 'easy-invoice'),
402 447 );
403 448
404 449 // Prepare template data
405 450 $template_data = [
@@ -408,8 +453,9 @@
408 453 'status_filter' => $status_filter,
409 454 'status_filters' => $status_filters,
410 455 'trash_count' => $trash_count,
411 456 'stats' => $stats,
457 + 'amounts_by_currency' => $amounts_by_currency,
412 458 'current_page' => $current_page,
413 459 'per_page' => $per_page,
414 460 'total_payments' => $total_payments,
415 461 'total_pages' => $total_pages,
@@ -436,11 +482,19 @@
436 482 // Check if scripts are already enqueued
437 483 if (wp_script_is('easy-invoice-payment', 'enqueued')) {
438 484 return;
439 485 }
440 - if(!is_singular(PostTypes::EASY_INVOICE_POST_TYPE)){
441 - //return;
442 - }
486 + // The payment panel exists on the public invoice page only; every
487 + // other front-end page of the site has no use for the script (or the
488 + // jQuery it pulls in).
489 + /**
490 + * Filter whether the payment script loads on the current front-end request.
491 + *
492 + * @param bool $load Default: on a public invoice page.
493 + */
494 + if (!apply_filters('easy_invoice_load_payment_assets', is_singular(PostTypes::EASY_INVOICE_POST_TYPE))) {
495 + return;
496 + }
443 497
444 498 // Enqueue our custom scripts
445 499 wp_enqueue_script(
446 500 'easy-invoice-payment',
@@ -456,11 +510,22 @@
456 510 $currency_code = $settings['easy_invoice_currency_code'] ?? 'USD';
457 511 $currency_symbol = \EasyInvoice\Helpers\CurrencyHelper::getCurrencySymbol($currency_code);
458 512
459 513 // Localize script variables for payment form
514 + // Forward the per-invoice access token (?ik=...) the same way the manual
515 + // payment script already does. The payment endpoints authorise on it, and
516 + // without this an anonymous client following an emailed link would have a
517 + // token in their URL that never reached the AJAX request.
518 + $ei_access_token = isset($_GET['ik'])
519 + ? sanitize_text_field(wp_unslash($_GET['ik']))
520 + : '';
521 + /** This filter is documented in includes/Controllers/InvoiceController.php */
522 + $ei_access_token = (string) apply_filters('easy_invoice_presented_access_token', $ei_access_token, 'invoice');
523 +
460 524 wp_localize_script('easy-invoice-payment', 'easy_invoice_vars', [
461 525 'ajax_url' => admin_url('admin-ajax.php'),
462 526 'nonce' => wp_create_nonce('easy_invoice_payment'),
527 + 'access_token' => $ei_access_token,
463 528 'currency_symbol' => $currency_symbol,
464 529 'currency_code' => $currency_code
465 530 ]);
466 531 }
@@ -475,8 +540,40 @@
475 540
476 541 $invoice_id = isset($_POST['invoice_id']) ? intval($_POST['invoice_id']) : 0;
477 542 $payment_method_slug = isset($_POST['payment_method']) ? sanitize_text_field($_POST['payment_method']) : '';
478 543
544 + $invoice_post = $invoice_id ? get_post($invoice_id) : null;
545 + if (!$invoice_post || $invoice_post->post_type !== \EasyInvoice\Constants\PostTypes::EASY_INVOICE_POST_TYPE) {
546 + wp_send_json_error(['message' => __('Invalid invoice.', 'easy-invoice')]);
547 + return;
548 + }
549 +
550 + $invoice = new \EasyInvoice\Models\Invoice($invoice_post);
551 +
552 + // Authorisation. This endpoint is nopriv and previously relied on a shared,
553 + // page-wide nonce alone, so a caller holding one could start a payment
554 + // against any invoice id and read back its amount and gateway details.
555 + // Legitimate callers reach this from the invoice page, which forwards the
556 + // per-invoice access token (see payment.js / payment-section.php).
557 + //
558 + // This MUST stay above the `easy_invoice_before_process_payment` filter
559 + // below. That filter is not a notification — it is a dispatch point that
560 + // short-circuits the whole request, and Easy Invoice Pro attaches four
561 + // handlers to it (Stripe, Authorize.Net, Moneris and Partial Payments).
562 + // While the check sat after the filter, those four gateways — every card
563 + // gateway Pro ships — completed payments without the token ever being
564 + // examined, so the gate only really covered the free plugin's own
565 + // gateways. Authorising before dispatch is the whole point of the gate.
566 + if (!\EasyInvoice\Controllers\InvoiceController::canSubmitPaymentForInvoice($invoice_id, $invoice)) {
567 + // A Pro build older than this plugin cannot forward the token — see
568 + // legacyProPaymentFallbackAllowed(). Refusing here would take the
569 + // customer's money on Stripe without recording the payment.
570 + if (!$this->legacyProPaymentFallbackAllowed($payment_method_slug)) {
571 + wp_send_json_error(['message' => __('Invalid invoice.', 'easy-invoice')]);
572 + return;
573 + }
574 + }
575 +
479 576 // Add filter for extensions to handle custom payment logic (e.g., partial payments)
480 577 $custom_result = apply_filters('easy_invoice_before_process_payment', null, $invoice_id, $_POST);
481 578
482 579 if (is_array($custom_result) && isset($custom_result['handled']) && $custom_result['handled']) {
@@ -487,24 +584,39 @@
487 584 }
488 585 return;
489 586 }
490 587
491 - if (!$invoice_id || !$payment_method_slug) {
588 + if (!$payment_method_slug) {
492 589 wp_send_json_error(['message' => __('Missing required fields.', 'easy-invoice')]);
493 590 return;
494 591 }
495 592
496 - $invoice_post = get_post($invoice_id);
497 - if (!$invoice_post || $invoice_post->post_type !== \EasyInvoice\Constants\PostTypes::EASY_INVOICE_POST_TYPE) {
498 - wp_send_json_error(['message' => __('Invalid invoice.', 'easy-invoice')]);
593 + // Charge what is owed, not the face value: a part-paid or partly
594 + // credited invoice must not be collected twice.
595 + $due = \EasyInvoice\Services\InvoiceBalance::due($invoice);
596 + $amount = $due;
597 + if ($due <= 0) {
598 + wp_send_json_error(['message' => __('Nothing is owed on this invoice.', 'easy-invoice')]);
499 599 return;
500 600 }
501 601
502 - $invoice = new \EasyInvoice\Models\Invoice($invoice_post);
503 - $amount = $invoice->total ?? 0;
602 + // A smaller amount is charged only when something (the Partial
603 + // Payments addon) says this invoice may be paid in instalments.
604 + $requested = isset($_POST['payment_amount']) ? round((float) str_replace(',', '', sanitize_text_field(wp_unslash($_POST['payment_amount']))), 2) : 0.0;
605 + $is_partial = isset($_POST['is_partial_payment']) && '1' === (string) sanitize_text_field(wp_unslash($_POST['is_partial_payment']));
606 + if ($is_partial && $requested > 0 && $requested < $due) {
607 + /**
608 + * Filter whether the client may pay less than the amount due.
609 + *
610 + * @param bool $allow Default false.
611 + * @param object $invoice Invoice model.
612 + * @param float $requested Amount the client asked to pay.
613 + */
614 + if (apply_filters('easy_invoice_allow_partial_payment_amount', false, $invoice, $requested)) {
615 + $amount = $requested;
616 + }
617 + }
504 618
505 - // Log the payment processing details
506 -
507 619 $gateway_instance = $this->gatewayManager->getGateway($payment_method_slug);
508 620
509 621 if (!$gateway_instance || !$gateway_instance->isEnabled() || !$gateway_instance->isAvailable()) {
510 622 wp_send_json_error(['message' => __('Selected payment gateway is not available or configured correctly.', 'easy-invoice')]);
@@ -515,8 +627,15 @@
515 627 // Pass the entire $_POST array to the gateway
516 628 $result = $gateway_instance->processPayment($amount, $_POST);
517 629
518 630 if (isset($result['success']) && $result['success']) {
631 + // An offline gateway with no follow-up step (cash, the free
632 + // manual gateway) leaves the invoice pending here; bank
633 + // transfer and cheque notify the admin themselves once the
634 + // proof or cheque details arrive.
635 + // Offline gateways (OfflineGateway) record their own pending
636 + // payment and fire easy_invoice_manual_payment_submitted with
637 + // the record's id; nothing to add here.
519 638 wp_send_json_success($result);
520 639 } else {
521 640 wp_send_json_error(['message' => $result['message'] ?? __('Payment processing failed with the gateway.', 'easy-invoice')]);
522 641 }
@@ -527,8 +646,97 @@
527 646 }
528 647 }
529 648
530 649 /**
650 + * Whether to accept a payment that presented no per-invoice access token,
651 + * because the Easy Invoice Pro build installed alongside cannot send one.
652 + *
653 + * Why this exists
654 + * ---------------
655 + * Pro's Stripe and Authorize.Net scripts post to `easy_invoice_process_payment`,
656 + * which is a free-plugin endpoint, and from 2.4.0 that endpoint authorises on the
657 + * per-invoice access token. Pro only began forwarding the token in 2.3.0.
658 + *
659 + * The two plugins update through different channels — free auto-updates from
660 + * WordPress.org, Pro arrives from the licence server — so "free is newer than Pro"
661 + * is not an edge case, it is the normal state for a while after release. Without
662 + * this fallback, that pairing breaks client payments, and for Stripe it breaks them
663 + * in the worst possible way: the script confirms the charge with Stripe FIRST and
664 + * only then posts here to record it, so a refusal means the customer has paid and
665 + * the invoice still says unpaid.
666 + *
667 + * What it does and does not allow
668 + * -------------------------------
669 + * The relaxation is deliberately narrow, and is never wider than the behaviour
670 + * that already shipped in 2.3.8:
671 + *
672 + * - Only when Pro is active AND older than 2.3.0. It disappears by itself the
673 + * moment Pro is updated; there is nothing to remember to turn off.
674 + * - Only when NO token was presented at all. A request carrying a wrong or
675 + * expired token is a forgery attempt, not an old client script, and is refused.
676 + * - Only for gateways provided by Pro. The free plugin's own scripts always
677 + * forward the token, so a free gateway reaching here without one is not a
678 + * version-skew case.
679 + * - The shared `easy_invoice_payment` nonce has already been verified by the
680 + * caller before this is consulted.
681 + * - `getPaymentInstructions()` does NOT use this. That is the information
682 + * disclosure path and stays fully gated regardless of Pro's version.
683 + *
684 + * Site owners who would rather fail the payment than accept the older
685 + * authorisation can return false from
686 + * `easy_invoice_allow_legacy_pro_payment_fallback`.
687 + *
688 + * @param string $payment_method_slug Gateway slug from the request.
689 + * @return bool
690 + */
691 + private function legacyProPaymentFallbackAllowed(string $payment_method_slug): bool {
692 + if (!function_exists('easy_invoice_has_pro') || !easy_invoice_has_pro()) {
693 + return false;
694 + }
695 +
696 + // An older Pro that predates token forwarding. Treat a missing version
697 + // constant as "older", since every build that defines it is >= 2.1.
698 + $pro_version = defined('EASY_INVOICE_PRO_VERSION') ? (string) EASY_INVOICE_PRO_VERSION : '0';
699 + if (version_compare($pro_version, self::PRO_TOKEN_FORWARDING_VERSION, '>=')) {
700 + return false;
701 + }
702 +
703 + // A presented-but-invalid token is an attack, not version skew.
704 + if (isset($_POST['access_token']) && $_POST['access_token'] !== '') {
705 + return false;
706 + }
707 + if (isset($_GET['ik']) && $_GET['ik'] !== '') {
708 + return false;
709 + }
710 +
711 + // Restrict to gateways Pro actually provides.
712 + $gateway_instance = $this->gatewayManager->getGateway($payment_method_slug);
713 + if (!$gateway_instance || strpos(get_class($gateway_instance), 'EasyInvoicePro\\') !== 0) {
714 + return false;
715 + }
716 +
717 + /**
718 + * Filter the legacy Pro payment fallback.
719 + *
720 + * @param bool $allowed Whether to accept the payment.
721 + * @param string $pro_version Version of Easy Invoice Pro detected.
722 + * @param string $payment_method_slug Gateway slug from the request.
723 + */
724 + $allowed = (bool) apply_filters(
725 + 'easy_invoice_allow_legacy_pro_payment_fallback',
726 + true,
727 + $pro_version,
728 + $payment_method_slug
729 + );
730 +
731 + if ($allowed) {
732 + update_option('easy_invoice_legacy_pro_payment_seen', $pro_version, false);
733 + }
734 +
735 + return $allowed;
736 + }
737 +
738 + /**
531 739 * Handle payment callback/webhook
532 740 */
533 741 public function handleCallback(): void {
534 742 check_ajax_referer('easy_invoice_payment', 'payment_nonce');
@@ -539,8 +747,34 @@
539 747 if (!$invoice_id || !$gateway) {
540 748 wp_send_json_error(['message' => __('Invalid request', 'easy-invoice')]);
541 749 }
542 750
751 + // Authorisation.
752 + //
753 + // This endpoint is registered nopriv and the only thing standing in front of
754 + // it was the shared, page-wide `easy_invoice_payment` nonce, which is rendered
755 + // on every public invoice page — so anyone able to view a single invoice could
756 + // lift one and then call this for any id they liked. The id was passed straight
757 + // to the gateway without even confirming it was an invoice.
758 + //
759 + // That mattered because the cheque gateway's callback writes: it stores the
760 + // cheque number, bank name, date and an uploaded image against whatever id it
761 + // is handed. An unauthenticated caller could therefore attach forged cheque
762 + // details, and a file, to any invoice on the site — or to any post at all.
763 + //
764 + // Same rule as everywhere else: valid per-invoice access key, administrator, or
765 + // the signed-in client the invoice belongs to.
766 + $invoice_post = get_post($invoice_id);
767 + if (!$invoice_post || $invoice_post->post_type !== \EasyInvoice\Constants\PostTypes::EASY_INVOICE_POST_TYPE) {
768 + wp_send_json_error(['message' => __('Invalid invoice.', 'easy-invoice')]);
769 + }
770 +
771 + $invoice = new \EasyInvoice\Models\Invoice($invoice_post);
772 + if (!\EasyInvoice\Controllers\InvoiceController::canSubmitPaymentForInvoice($invoice_id, $invoice)
773 + && !$this->legacyProPaymentFallbackAllowed($gateway)) {
774 + wp_send_json_error(['message' => __('Invalid invoice.', 'easy-invoice')]);
775 + }
776 +
543 777 $gateway_instance = $this->gatewayManager->getGateway($gateway);
544 778 if (!$gateway_instance) {
545 779 wp_send_json_error(['message' => __('Invalid payment gateway', 'easy-invoice')]);
546 780 }
@@ -546,10 +780,14 @@
546 780 }
547 781
548 782 $result = $gateway_instance->handleCallback($_POST);
549 783
550 - // Send admin notification for manual payments
551 - if ($result['success'] && in_array($gateway, ['bank', 'cheque'])) {
784 + // Tell the admin an offline payment is waiting for verification. Pro's
785 + // bank-transfer and cheque gateways email the admin themselves from
786 + // handleCallback(); the free manual gateway and Pro's cash gateway do
787 + // not. (This used to test for 'bank' and 'cheque' — ids no gateway
788 + // has — so it never fired.)
789 + if ($result['success'] && in_array($gateway, ['manual', 'cash'], true)) {
552 790 do_action('easy_invoice_manual_payment_submitted', $invoice_id, $gateway);
553 791 }
554 792
555 793 if ($result['success']) {
@@ -573,9 +811,13 @@
573 811
574 812 $invoice = new \EasyInvoice\Models\Invoice($post);
575 813 $invoice_status = $invoice->getStatus();
576 814
577 - if (!in_array($invoice_status, [ 'unpaid', 'available'])) {
815 + // Anything that still has a balance can be paid: an overdue invoice is the
816 + // one a client most needs to settle, and a partially paid one still owes.
817 + // Drafts, paid, cancelled and "awaiting verification" stay closed.
818 + $payable_statuses = apply_filters('easy_invoice_payable_statuses', [ 'unpaid', 'available', 'overdue', 'partial', 'sent', 'pending' ]);
819 + if (!in_array($invoice_status, $payable_statuses, true)) {
578 820 return [];
579 821 }
580 822
581 823 $enabled_gateways = $this->gatewayManager->getEnabledGateways();
@@ -601,8 +843,17 @@
601 843
602 844 $available_gateways = [];
603 845 $gateway_manager = \EasyInvoice\EasyInvoice::getInstance()->getGatewayManager();
604 846
847 + // An invoice saved before 2.4.2 could name the old "manual" gateway;
848 + // that meant the offline methods, which are gateways of their own now.
849 + if (!empty($selected_gateways) && in_array('manual', $selected_gateways, true)) {
850 + $selected_gateways = array_values(array_unique(array_merge(
851 + array_diff($selected_gateways, ['manual']),
852 + \EasyInvoice\Services\OfflinePayments::ids()
853 + )));
854 + }
855 +
605 856 // $enabled_gateways is an associative array with gateway_id as key and gateway object as value
606 857 foreach ($enabled_gateways as $gateway_id => $gateway) {
607 858 // If invoice has custom gateways selected, only show those
608 859 // If no custom gateways are selected (empty array), show all enabled gateways
@@ -630,13 +881,27 @@
630 881 */
631 882 public function updatePayment() {
632 883 check_ajax_referer('easy_invoice_payment', 'payment_nonce');
633 884
885 + // Authorisation: this handler mutates payment-record fields
886 + // (amount, method, status, notes) and on status=completed it
887 + // can flip the linked invoice to paid via
888 + // updateInvoiceStatusIfPaid(). The shared `easy_invoice_payment`
889 + // nonce is rendered on every public invoice page so any
890 + // authenticated visitor can obtain a valid one — the nonce is
891 + // CSRF defense, NOT authorisation. Gate on the same payment-
892 + // management capability as the sibling verifyManualPayment /
893 + // rejectManualPayment / mark_invoice_paid_ajax handlers.
894 + if (!easy_invoice_user_can('ei_record_payment')) {
895 + wp_send_json_error(['message' => __('You do not have permission to update payments.', 'easy-invoice')]);
896 + return;
897 + }
898 +
634 899 $payment_id = isset($_POST['payment_id']) ? intval($_POST['payment_id']) : 0;
635 900 $invoice_id = isset($_POST['invoice_id']) ? intval($_POST['invoice_id']) : 0;
636 901 $amount = isset($_POST['amount']) ? floatval($_POST['amount']) : 0;
637 902 $payment_method = isset($_POST['payment_method']) ? sanitize_text_field($_POST['payment_method']) : '';
638 - $payment_date = isset($_POST['payment_date']) ? sanitize_text_field($_POST['payment_date']) : date('Y-m-d');
903 + $payment_date = isset($_POST['payment_date']) ? sanitize_text_field($_POST['payment_date']) : current_time('Y-m-d');
639 904 $status = isset($_POST['status']) ? sanitize_text_field($_POST['status']) : 'pending';
640 905 $notes = isset($_POST['notes']) ? sanitize_textarea_field($_POST['notes']) : '';
641 906
642 907 if (!$payment_id || !$invoice_id || !$amount || !$payment_method) {
@@ -692,13 +957,13 @@
692 957 $total_payments = $this->calculateTotalPaymentsForInvoice($invoice_id);
693 958 $invoice_total = $invoice->getTotal();
694 959
695 960 if ($total_payments < $invoice_total) {
696 - // Not enough payments anymore, revert invoice to draft/pending
697 - $invoice->setStatus('draft');
961 + // Not enough payments any more: part paid if anything
962 + // remains, otherwise back to awaiting payment. An issued
963 + // invoice never returns to draft.
964 + $invoice->setStatus($total_payments > 0 ? 'partial' : 'available');
698 965 $invoice->save();
699 -
700 - error_log("Easy Invoice: Invoice #$invoice_id status reverted to 'draft' - payment marked as $status");
701 966 } else {
702 967 // Still enough payments from other completed payments
703 968 $this->updateInvoiceStatusIfPaid($invoice_id, $invoice, 'manual');
704 969 }
@@ -719,9 +984,9 @@
719 984 * Verify manual payment
720 985 */
721 986 public function verifyManualPayment(): void {
722 987 // Check permissions
723 - if (!current_user_can('manage_options')) {
988 + if (!easy_invoice_user_can('ei_record_payment')) {
724 989 wp_send_json_error(['message' => __('You do not have permission to perform this action', 'easy-invoice')]);
725 990 return;
726 991 }
727 992
@@ -802,10 +1067,11 @@
802 1067 /**
803 1068 * Reject manual payment
804 1069 */
805 1070 public function rejectManualPayment(): void {
806 - // Check permissions
807 - if (!current_user_can('manage_options')) {
1071 + // Check permissions — rejecting a manual payment is a record-payment
1072 + // operation (it transitions state, doesn't refund money).
1073 + if (!easy_invoice_user_can('ei_record_payment')) {
808 1074 wp_send_json_error(['message' => __('You do not have permission to perform this action', 'easy-invoice')]);
809 1075 return;
810 1076 }
811 1077
@@ -859,12 +1125,14 @@
859 1125 if (!$invoice || !$invoice->getId()) {
860 1126 return;
861 1127 }
862 1128
863 - // Use EmailManager to send payment confirmation
1129 + // Use EmailManager to send payment confirmation using proper template system
1130 + // This will check if payment email is enabled in settings
864 1131 $email_manager = \EasyInvoice\Services\EmailManager::getInstance();
865 - $email_manager->sendPaymentConfirmationEmail($invoice, [
866 - 'payment_id' => $payment_id
1132 + $email_manager->sendInvoiceEmail($invoice, 'paid', [
1133 + 'payment_id' => $payment_id,
1134 + 'skip_bcc' => true // Skip BCC to admin since this is a direct call
867 1135 ]);
868 1136 }
869 1137
870 1138 /**
@@ -884,106 +1152,103 @@
884 1152 $email_manager = \EasyInvoice\Services\EmailManager::getInstance();
885 1153 $email_manager->sendPaymentRejectionEmail($invoice, $reason);
886 1154 }
887 1155
888 - /**
889 - * Add pending payment statuses to admin filters
890 - *
891 - * @param array $statuses
892 - * @return array
893 - */
894 - public function addPendingPaymentStatuses($statuses): array {
895 - $statuses['pending-bank'] = __('Pending Bank Transfer', 'easy-invoice');
896 - $statuses['pending-cheque'] = __('Pending Cheque', 'easy-invoice');
897 - return $statuses;
898 - }
899 1156
900 - /**
901 - * Add payment method column to payments list
902 - *
903 - * @param array $columns
904 - * @return array
905 - */
906 - public function addPaymentMethodColumn($columns): array {
907 - $new_columns = [];
908 1157
909 - foreach ($columns as $key => $value) {
910 - $new_columns[$key] = $value;
911 1158
912 - if ($key === 'title') {
913 - $new_columns['payment_method'] = __('Payment Method', 'easy-invoice');
914 - }
915 - }
916 -
917 - return $new_columns;
918 - }
919 -
920 1159 /**
921 - * Render payment method column
1160 + * Daily payment reminder (free plugin).
922 1161 *
923 - * @param string $column
924 - * @param int $post_id
1162 + * Emails the "reminder" template once to every invoice still owed a
1163 + * set number of days after its due date (Settings → Advanced → Payment
1164 + * reminder). Invoices with a payment awaiting confirmation are left
1165 + * alone. When Easy Invoice Pro is active its own reminder (or the Smart
1166 + * Reminders addon) takes over and this does nothing.
925 1167 */
926 - public function renderPaymentMethodColumn($column, $post_id): void {
927 - if ($column === 'payment_method') {
928 - $payment_method = get_post_meta($post_id, '_payment_method', true);
929 - $payment_methods = [
930 - 'paypal' => __('PayPal', 'easy-invoice')
931 - ];
932 -
933 - echo isset($payment_methods[$payment_method]) ? esc_html($payment_methods[$payment_method]) : esc_html($payment_method);
1168 + public function sendPaymentReminders(): void {
1169 + if (function_exists('easy_invoice_has_pro') && easy_invoice_has_pro()) {
1170 + return;
934 1171 }
935 - }
1172 + $raw = get_option('easy_invoice_payment_reminder_days', 3);
1173 + if ('' === trim((string) $raw)) {
1174 + return; // Switched off in Settings.
1175 + }
1176 + /**
1177 + * Filter how many days after the due date the free reminder goes out
1178 + * (0 = on the due date); return a negative number to disable it.
1179 + *
1180 + * @param int $days Days.
1181 + */
1182 + $days = (int) apply_filters('easy_invoice_payment_reminder_days', (int) $raw);
1183 + if ($days < 0) {
1184 + return;
1185 + }
1186 + $cutoff = gmdate('Y-m-d', strtotime(current_time('Y-m-d') . ' -' . $days . ' days'));
936 1187
937 - /**
938 - * Send payment reminders for pending manual payments
939 - */
940 - public function sendPaymentReminders(): void {
941 - // Get invoices with pending manual payments
942 - $pending_invoices = get_posts([
943 - 'post_type' => \EasyInvoice\Constants\PostTypes::EASY_INVOICE_POST_TYPE,
944 - 'posts_per_page' => -1,
945 - 'meta_query' => [
1188 + $ids = get_posts([
1189 + 'post_type' => \EasyInvoice\Constants\PostTypes::EASY_INVOICE_POST_TYPE,
1190 + 'post_status' => 'publish',
1191 + 'posts_per_page' => 200,
1192 + 'fields' => 'ids',
1193 + 'orderby' => 'ID',
1194 + 'order' => 'ASC',
1195 + 'meta_query' => [ // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
946 1196 'relation' => 'AND',
947 1197 [
948 - 'key' => '_payment_status',
949 - 'value' => ['pending-bank', 'pending-cheque'],
950 - 'compare' => 'IN'
1198 + 'key' => \EasyInvoice\Constants\InvoiceFields::STATUS,
1199 + 'value' => ['available', 'unpaid', 'partial', 'overdue', 'sent'],
1200 + 'compare' => 'IN',
951 1201 ],
952 1202 [
953 - 'key' => '_payment_reminder_sent',
954 - 'compare' => 'NOT EXISTS'
955 - ]
956 - ]
1203 + 'key' => \EasyInvoice\Constants\InvoiceFields::DUE_DATE,
1204 + 'value' => $cutoff,
1205 + 'compare' => '<=',
1206 + 'type' => 'DATE',
1207 + ],
1208 + [
1209 + 'key' => '_payment_reminder_sent',
1210 + 'compare' => 'NOT EXISTS',
1211 + ],
1212 + ],
957 1213 ]);
1214 + if (!$ids) {
1215 + return;
1216 + }
958 1217
959 - if (!empty($pending_invoices)) {
960 - // Get currency settings
961 - $settings_controller = new \EasyInvoice\Controllers\SettingsController();
962 - $settings = $settings_controller->getSettings();
963 - $currency_code = $settings['easy_invoice_currency_code'] ?? 'USD';
964 - $currency_symbol = \EasyInvoice\Helpers\CurrencyHelper::getCurrencySymbol($currency_code);
965 -
966 - foreach ($pending_invoices as $post) {
967 - $invoice = new Invoice($post);
968 -
969 - if (!$invoice || !$invoice->getId()) {
970 - continue;
971 - }
972 -
973 - // Use EmailManager to send payment reminder
974 - $email_manager = \EasyInvoice\Services\EmailManager::getInstance();
975 - $result = $email_manager->sendInvoiceEmail($invoice, 'reminder', [
976 - 'payment_method' => get_post_meta($invoice->getId(), '_payment_method', true)
977 - ]);
978 -
979 - // Mark reminder as sent if email was sent successfully
980 - if ($result['success']) {
981 - update_post_meta($invoice->getId(), '_payment_reminder_sent', current_time('mysql'));
982 - }
1218 + $email_manager = \EasyInvoice\Services\EmailManager::getInstance();
1219 + foreach ($ids as $invoice_id) {
1220 + $invoice_id = (int) $invoice_id;
1221 + // A client who has told us they paid should not be chased.
1222 + if ('pending' === (string) get_post_meta($invoice_id, '_payment_status', true)) {
1223 + continue;
983 1224 }
984 -
985 - wp_reset_postdata();
1225 + $invoice = \EasyInvoice\Providers\InvoiceServiceProvider::getInvoiceRepository()->find($invoice_id);
1226 + if (!$invoice || \EasyInvoice\Services\InvoiceBalance::due($invoice) <= 0) {
1227 + continue;
1228 + }
1229 + /**
1230 + * Filter whether the free reminder is sent for this invoice.
1231 + *
1232 + * @param bool $send Default true.
1233 + * @param object $invoice Invoice model.
1234 + */
1235 + if (!apply_filters('easy_invoice_send_payment_reminder', true, $invoice)) {
1236 + continue;
1237 + }
1238 + $result = $email_manager->sendInvoiceEmail($invoice, 'reminder', [
1239 + 'payment_method' => (string) get_post_meta($invoice_id, '_easy_invoice_payment_method', true),
1240 + ]);
1241 + if (!empty($result['success'])) {
1242 + update_post_meta($invoice_id, '_payment_reminder_sent', current_time('mysql'));
1243 + /**
1244 + * Fires after the free reminder email for an invoice was sent.
1245 + *
1246 + * @param int $invoice_id Invoice.
1247 + * @param object $invoice Invoice model.
1248 + */
1249 + do_action('easy_invoice_payment_reminder_sent', $invoice_id, $invoice);
1250 + }
986 1251 }
987 1252 }
988 1253
989 1254 /**
@@ -989,10 +1254,13 @@
989 1254 /**
990 1255 * Submit manual payment
991 1256 */
992 1257 public function submitManualPayment(): void {
993 - // Verify nonce
994 - if (!wp_verify_nonce($_POST['nonce'], 'easy_invoice_payment')) {
1258 + // CSRF defense — keep the existing nonce check. The nonce is
1259 + // global (`easy_invoice_payment`) so any public invoice page leaks
1260 + // a valid value; the REAL authorisation gate is the ownership
1261 + // check below.
1262 + if (!wp_verify_nonce($_POST['nonce'] ?? '', 'easy_invoice_payment')) {
995 1263 wp_send_json_error(['message' => __('Security check failed', 'easy-invoice')]);
996 1264 return;
997 1265 }
998 1266
@@ -998,9 +1266,9 @@
998 1266
999 1267 $invoice_id = isset($_POST['invoice_id']) ? intval($_POST['invoice_id']) : 0;
1000 1268 $payment_type = isset($_POST['payment_type']) ? sanitize_text_field($_POST['payment_type']) : '';
1001 1269 $payment_notes = isset($_POST['payment_notes']) ? sanitize_textarea_field($_POST['payment_notes']) : '';
1002 -
1270 +
1003 1271 if (!$invoice_id || !$payment_type) {
1004 1272 wp_send_json_error(['message' => __('Missing required fields', 'easy-invoice')]);
1005 1273 return;
1006 1274 }
@@ -1012,8 +1280,21 @@
1012 1280 return;
1013 1281 }
1014 1282
1015 1283 $invoice = new \EasyInvoice\Models\Invoice($invoice_post);
1284 +
1285 + // Authorisation: reject unless the caller is the legitimate email
1286 + // recipient (per-invoice access token), an admin, or the
1287 + // logged-in client bound to this invoice. Without this gate the
1288 + // public AJAX endpoint allowed any visitor with a harvested
1289 + // global nonce to flood arbitrary invoices into
1290 + // `pending_verification` and attach payment-proof uploads.
1291 + if (!\EasyInvoice\Controllers\InvoiceController::canSubmitPaymentForInvoice($invoice_id, $invoice)) {
1292 + wp_send_json_error([
1293 + 'message' => __('You do not have permission to submit a payment for this invoice.', 'easy-invoice'),
1294 + ]);
1295 + return;
1296 + }
1016 1297 $currency_code = $invoice->getCurrencyCode() ?: 'USD';
1017 1298 if ($currency_code === 'global') {
1018 1299 $currency_code = get_option('easy_invoice_currency_code', 'USD');
1019 1300 }
@@ -1018,41 +1299,84 @@
1018 1299 $currency_code = get_option('easy_invoice_currency_code', 'USD');
1019 1300 }
1020 1301 $currency_symbol = \EasyInvoice\Helpers\CurrencyHelper::getCurrencySymbol($currency_code);
1021 1302
1022 - // Handle file upload
1303 + // Handle file upload (never trust client MIME or filename extension — use WordPress filetype APIs)
1023 1304 $proof_url = '';
1024 1305 if (isset($_FILES['payment_proof']) && $_FILES['payment_proof']['error'] === UPLOAD_ERR_OK) {
1025 1306 $file = $_FILES['payment_proof'];
1026 -
1027 - // Validate file
1028 - $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf'];
1307 +
1308 + if (empty($file['tmp_name']) || !is_uploaded_file($file['tmp_name'])) {
1309 + wp_send_json_error(['message' => __('Invalid upload.', 'easy-invoice')]);
1310 + return;
1311 + }
1312 +
1029 1313 $max_size = 5 * 1024 * 1024; // 5MB
1030 -
1031 - if (!in_array($file['type'], $allowed_types)) {
1314 + if ($file['size'] > $max_size) {
1315 + wp_send_json_error(['message' => __('File size must be less than 5MB.', 'easy-invoice')]);
1316 + return;
1317 + }
1318 +
1319 + $allowed_mimes = [
1320 + 'jpg|jpeg|jpe' => 'image/jpeg',
1321 + 'png' => 'image/png',
1322 + 'gif' => 'image/gif',
1323 + 'pdf' => 'application/pdf',
1324 + ];
1325 +
1326 + $checked = wp_check_filetype_and_ext($file['tmp_name'], $file['name'], $allowed_mimes);
1327 + if (empty($checked['ext']) || empty($checked['type'])) {
1032 1328 wp_send_json_error(['message' => __('Invalid file type. Only JPG, PNG, GIF, and PDF files are allowed.', 'easy-invoice')]);
1033 1329 return;
1034 1330 }
1035 -
1036 - if ($file['size'] > $max_size) {
1037 - wp_send_json_error(['message' => __('File size must be less than 5MB.', 'easy-invoice')]);
1331 +
1332 + $allowed_types = array_values($allowed_mimes);
1333 + if (!in_array($checked['type'], $allowed_types, true)) {
1334 + wp_send_json_error(['message' => __('Invalid file type. Only JPG, PNG, GIF, and PDF files are allowed.', 'easy-invoice')]);
1038 1335 return;
1039 1336 }
1040 -
1041 - // Upload file
1337 +
1042 1338 $upload_dir = wp_upload_dir();
1043 1339 $proof_dir = $upload_dir['basedir'] . '/easy-invoice/payment-proofs/';
1044 -
1045 - if (!file_exists($proof_dir)) {
1046 - wp_mkdir_p($proof_dir);
1340 +
1341 + if (!wp_mkdir_p($proof_dir)) {
1342 + wp_send_json_error(['message' => __('Could not create upload directory.', 'easy-invoice')]);
1343 + return;
1047 1344 }
1048 -
1049 - $filename = uniqid('payment_proof_') . '_' . sanitize_file_name($file['name']);
1050 - $filepath = $proof_dir . $filename;
1051 -
1052 - if (move_uploaded_file($file['tmp_name'], $filepath)) {
1053 - $proof_url = $upload_dir['baseurl'] . '/easy-invoice/payment-proofs/' . $filename;
1345 +
1346 + // Hand the move to WordPress rather than move_uploaded_file(): it
1347 + // applies the site's filesystem method and permissions, and lets
1348 + // the usual upload filters see the file. The directory is pointed
1349 + // at our proofs folder for the duration of this one call.
1350 + // Random, not time-based: a receipt carries bank details and the URL
1351 + // is public, so the name must not be guessable.
1352 + $filename = 'payment_proof_' . wp_generate_password(24, false, false) . '.' . $checked['ext'];
1353 + $proof_url = $upload_dir['baseurl'] . '/easy-invoice/payment-proofs/';
1354 + $to_proofs = static function ($dirs) use ($proof_dir, $proof_url) {
1355 + $dirs['path'] = untrailingslashit($proof_dir);
1356 + $dirs['url'] = untrailingslashit($proof_url);
1357 + $dirs['subdir'] = '/easy-invoice/payment-proofs';
1358 + return $dirs;
1359 + };
1360 + if (!function_exists('wp_handle_upload')) {
1361 + require_once ABSPATH . 'wp-admin/includes/file.php';
1054 1362 }
1363 + add_filter('upload_dir', $to_proofs);
1364 + \EasyInvoice\Helpers\UploadGuard::protectDirectory((wp_upload_dir())['basedir'] . '/easy-invoice/payment-proofs');
1365 + $moved = wp_handle_upload($file, [
1366 + 'test_form' => false,
1367 + 'mimes' => $allowed_mimes,
1368 + 'unique_filename_callback' => static function () use ($filename) {
1369 + return $filename;
1370 + },
1371 + ]);
1372 + remove_filter('upload_dir', $to_proofs);
1373 +
1374 + if (!is_array($moved) || !empty($moved['error']) || empty($moved['url'])) {
1375 + wp_send_json_error(['message' => __('Failed to save payment proof file.', 'easy-invoice')]);
1376 + return;
1377 + }
1378 + $proof_url = $moved['url'];
1055 1379 }
1056 1380
1057 1381 // Create payment record
1058 1382 $payment_data = [
@@ -1154,189 +1478,335 @@
1154 1478 }
1155 1479 }
1156 1480
1157 1481 /**
1158 - * AJAX handler for admin to mark an invoice as paid.
1482 + * Confirm an offline payment a client told us about (or mark an invoice
1483 + * paid by hand when nothing is pending).
1484 + *
1485 + * Expects `invoice_id`, the `easy_invoice_approve_payment` nonce, and
1486 + * ideally `payment_id` — the pending record the reviewer looked at.
1487 + * Only that record is completed; the invoice becomes Paid when the
1488 + * confirmed payments and credit notes cover it, Partially paid otherwise.
1159 1489 */
1160 1490 public function mark_invoice_paid_ajax(): void {
1161 - $invoice_id = isset($_POST['invoice_id']) ? intval($_POST['invoice_id']) : 0;
1162 - $nonce = isset($_POST['nonce']) ? sanitize_text_field($_POST['nonce']) : '';
1163 - $notes = isset($_POST['notes']) ? sanitize_textarea_field($_POST['notes']) : '';
1491 + $invoice_id = isset($_POST['invoice_id']) ? absint($_POST['invoice_id']) : 0;
1492 + $payment_id = isset($_POST['payment_id']) ? absint($_POST['payment_id']) : 0;
1493 + $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
1494 + $notes = isset($_POST['notes']) ? sanitize_textarea_field(wp_unslash($_POST['notes'])) : '';
1164 1495
1165 - if (empty($invoice_id) || !wp_verify_nonce($nonce, 'easy_invoice_approve_payment')) {
1496 + if (!wp_verify_nonce($nonce, 'easy_invoice_approve_payment')) {
1166 1497 easy_invoice_toast_error(__('Invalid request or security check failed.', 'easy-invoice'));
1167 1498 return;
1168 1499 }
1169 -
1170 - // Use manage_options capability which administrators have
1171 - if (!current_user_can('manage_options')) {
1500 + if (!easy_invoice_user_can('ei_record_payment')) {
1172 1501 easy_invoice_toast_error(__('You do not have permission to perform this action.', 'easy-invoice'));
1173 1502 return;
1174 1503 }
1175 1504
1176 - $invoice_post = get_post($invoice_id);
1505 + // A payment id alone is enough: the invoice is the one it belongs to.
1506 + if ($payment_id) {
1507 + $linked = (int) get_post_meta($payment_id, '_invoice_id', true);
1508 + if ($linked && !$invoice_id) {
1509 + $invoice_id = $linked;
1510 + }
1511 + if (!$linked || $linked !== $invoice_id || 'easy_invoice_payment' !== get_post_type($payment_id)) {
1512 + easy_invoice_toast_error(__('That payment does not belong to this invoice.', 'easy-invoice'));
1513 + return;
1514 + }
1515 + }
1516 +
1517 + $invoice_post = $invoice_id ? get_post($invoice_id) : null;
1177 1518 if (!$invoice_post || $invoice_post->post_type !== \EasyInvoice\Constants\PostTypes::EASY_INVOICE_POST_TYPE) {
1178 - wp_send_json_error(['message' => __('Invalid invoice.', 'easy-invoice')]);
1519 + easy_invoice_toast_error(__('Invalid invoice.', 'easy-invoice'));
1179 1520 return;
1180 1521 }
1522 + $invoice = new Invoice($invoice_post);
1523 + $pending = \EasyInvoice\Services\OfflinePayments::pendingStatuses();
1181 1524
1182 - $invoice = new Invoice($invoice_post);
1183 - // For manual approval, always use 'manual' as payment method
1184 - $payment_method = 'manual';
1525 + if (!$payment_id) {
1526 + // Older callers pass only the invoice: take its oldest pending submission.
1527 + $waiting = get_posts([
1528 + 'post_type' => 'easy_invoice_payment',
1529 + 'post_status' => 'any',
1530 + 'posts_per_page' => 1,
1531 + 'orderby' => 'date',
1532 + 'order' => 'ASC',
1533 + 'meta_query' => [ // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
1534 + ['key' => '_invoice_id', 'value' => $invoice_id],
1535 + ['key' => '_status', 'value' => $pending, 'compare' => 'IN'],
1536 + ],
1537 + ]);
1538 + $payment_id = $waiting ? (int) $waiting[0]->ID : 0;
1539 + }
1185 1540
1186 - // Update invoice post status to 'publish' (or your primary paid status)
1187 - wp_update_post(['ID' => $invoice_id, 'post_status' => 'publish']);
1188 - update_post_meta($invoice_id, '_payment_status', 'completed'); // General completed status for payments
1541 + $currency_code = $invoice->getCurrencyCode() ?: get_option('easy_invoice_currency_code', 'USD');
1542 + if ('global' === $currency_code) {
1543 + $currency_code = get_option('easy_invoice_currency_code', 'USD');
1544 + }
1545 + $currency_symbol = \EasyInvoice\Helpers\CurrencyHelper::getCurrencySymbol($currency_code);
1189 1546
1190 - // Allow plugins to control invoice status update
1191 - $should_update_invoice_status = apply_filters('easy_invoice_should_update_invoice_status', true, $invoice_id);
1192 - if ($should_update_invoice_status) {
1193 - update_post_meta($invoice_id, InvoiceFields::STATUS, 'paid'); // Specific invoice status field if used by model
1547 + if ($payment_id) {
1548 + $status = (string) get_post_meta($payment_id, '_status', true);
1549 + if (!in_array($status, $pending, true)) {
1550 + easy_invoice_toast_error(__('This payment has already been confirmed or rejected.', 'easy-invoice'));
1551 + return;
1552 + }
1553 + $amount = round((float) get_post_meta($payment_id, '_amount', true), 2);
1554 + $due = \EasyInvoice\Services\InvoiceBalance::due($invoice);
1555 + if ($amount <= 0 || $amount > $due + 0.005) {
1556 + // The client's figure was blank or more than is owed: confirm what is owed.
1557 + $amount = round(max(0.0, $due), 2);
1558 + update_post_meta($payment_id, '_amount', $amount);
1559 + }
1560 + if ($amount <= 0) {
1561 + easy_invoice_toast_error(__('Nothing is owed on this invoice; reject the submission instead.', 'easy-invoice'));
1562 + return;
1563 + }
1564 + update_post_meta($payment_id, '_status', 'completed');
1565 + update_post_meta($payment_id, '_verified_by', get_current_user_id());
1566 + update_post_meta($payment_id, '_verified_at', current_time('mysql'));
1567 + if ('' !== $notes) {
1568 + $existing = (string) get_post_meta($payment_id, '_notes', true);
1569 + update_post_meta($payment_id, '_notes', trim($existing . ('' !== $existing ? "\n" : '') . __('Confirmed:', 'easy-invoice') . ' ' . $notes));
1570 + }
1571 + $method = (string) get_post_meta($payment_id, '_payment_method', true) ?: 'manual';
1572 + } else {
1573 + // Nothing was submitted: staff are recording the balance as paid by hand.
1574 + $amount = round(\EasyInvoice\Services\InvoiceBalance::due($invoice), 2);
1575 + if ($amount <= 0) {
1576 + easy_invoice_toast_success(__('Nothing is owed on this invoice.', 'easy-invoice'));
1577 + return;
1578 + }
1579 + $method = 'manual';
1580 + $payment_id = wp_insert_post([
1581 + 'post_title' => sprintf('Manual Payment for Invoice #%s', $invoice->getNumber()),
1582 + 'post_type' => 'easy_invoice_payment',
1583 + 'post_status' => 'publish',
1584 + 'post_author' => get_current_user_id(),
1585 + 'meta_input' => [
1586 + '_invoice_id' => $invoice_id,
1587 + '_amount' => $amount,
1588 + '_payment_method' => $method,
1589 + '_status' => 'completed',
1590 + '_transaction_id' => 'MANUAL-' . $invoice_id . '-' . time(),
1591 + '_payment_date' => current_time('mysql'),
1592 + '_notes' => $notes,
1593 + '_payment_type' => 'manual',
1594 + '_currency' => $currency_code,
1595 + '_currency_symbol' => $currency_symbol,
1596 + '_verified_by' => get_current_user_id(),
1597 + '_verified_at' => current_time('mysql'),
1598 + '_gateway_response' => wp_json_encode(['admin_verified' => true, 'user' => get_current_user_id(), 'verification_date' => current_time('mysql'), 'notes' => $notes]),
1599 + ],
1600 + ], true);
1601 + if (is_wp_error($payment_id) || !$payment_id) {
1602 + easy_invoice_toast_error(__('The payment could not be saved.', 'easy-invoice'));
1603 + return;
1604 + }
1194 1605 }
1195 1606
1196 - // Use submitted notes or default note
1197 - $payment_notes = !empty($notes)
1198 - ? $notes
1199 - : __('Payment manually verified by admin.', 'easy-invoice');
1607 + \EasyInvoice\Services\InvoiceBalance::forget($invoice_id);
1608 + $new_status = \EasyInvoice\Services\InvoiceBalance::isSettled($invoice) ? 'paid' : 'partial';
1609 + $still_open = \EasyInvoice\Services\OfflinePayments::pendingForInvoice($invoice_id);
1610 + update_post_meta($invoice_id, '_payment_status', $still_open ? 'pending' : ('paid' === $new_status ? 'completed' : 'partial'));
1611 + update_post_meta($invoice_id, '_easy_invoice_payment_method', $method);
1200 1612
1201 - // Find existing pending payment records for this invoice
1202 - $existing_payment_args = [
1203 - 'post_type' => 'easy_invoice_payment',
1204 - 'posts_per_page' => 1,
1205 - 'meta_query' => [
1206 - 'relation' => 'AND',
1207 - [
1208 - 'key' => '_invoice_id',
1209 - 'value' => $invoice_id,
1210 - ],
1211 - [
1212 - 'key' => '_status',
1213 - 'value' => ['pending-bank', 'pending-cheque', 'pending'], // Check against pending statuses
1214 - 'compare' => 'IN'
1215 - ]
1216 - ]
1613 + /**
1614 + * Filter whether confirming a payment updates the invoice status.
1615 + *
1616 + * @param bool $update Default true.
1617 + * @param int $invoice_id Invoice.
1618 + */
1619 + if (apply_filters('easy_invoice_should_update_invoice_status', true, $invoice_id)) {
1620 + $invoice->setStatus($new_status);
1621 + $invoice->save();
1622 + }
1623 +
1624 + $payment_event = [
1625 + 'payment_method' => $method,
1626 + 'gateway_name' => $method,
1627 + 'transaction_id' => (string) get_post_meta($payment_id, '_transaction_id', true),
1628 + 'amount' => $amount,
1629 + 'date' => (string) get_post_meta($payment_id, '_payment_date', true),
1630 + 'payment_id' => (int) $payment_id,
1217 1631 ];
1218 - $existing_payments = get_posts($existing_payment_args);
1219 - $payment_id = null;
1220 -
1221 - if (!empty($existing_payments)) {
1222 - // Update existing pending payment instead of creating new one
1223 - $payment_id = $existing_payments[0]->ID;
1224 - update_post_meta($payment_id, '_status', 'completed'); // Update status to completed
1225 - update_post_meta($payment_id, '_payment_method', 'manual'); // Set payment method to manual
1226 - update_post_meta($payment_id, '_transaction_id', 'MANUAL-' . $invoice_id . '-' . time());
1227 - update_post_meta($payment_id, '_payment_date', current_time('mysql'));
1228 - update_post_meta($payment_id, '_notes', $payment_notes); // Update notes on existing payment
1632 + if ('paid' === $new_status) {
1633 + do_action('easy_invoice_payment_completed', $invoice_id, $invoice, $payment_event);
1229 1634 } else {
1230 - // Only create a new payment if no pending payments exist
1231 - // This prevents creating duplicate payment records
1232 - $existing_payments = get_posts([
1233 - 'post_type' => 'easy_invoice_payment',
1234 - 'posts_per_page' => -1,
1235 - 'meta_query' => [
1236 - [
1237 - 'key' => '_invoice_id',
1238 - 'value' => $invoice_id,
1239 - ]
1240 - ]
1241 - ]);
1635 + /** This action is documented in recordPayment(). */
1636 + do_action('easy_invoice_payment_received', $invoice_id, $invoice, $payment_event);
1637 + }
1638 + /**
1639 + * Fires when staff confirm an offline payment (or mark an invoice paid by hand).
1640 + *
1641 + * @param int $payment_id Payment record, now completed.
1642 + * @param int $invoice_id Invoice.
1643 + * @param float $amount Amount confirmed.
1644 + * @param string $new_status Invoice status afterwards: paid or partial.
1645 + */
1646 + do_action('easy_invoice_payment_approved', (int) $payment_id, $invoice_id, $amount, $new_status);
1242 1647
1243 - if (!empty($existing_payments)) {
1244 - // If payments exist but none are pending, don't create a new one
1245 - // Just update the invoice status
1246 - easy_invoice_toast_success(__('Invoice marked as paid successfully.', 'easy-invoice'));
1247 - return;
1248 - }
1648 + easy_invoice_toast_success(
1649 + 'paid' === $new_status
1650 + ? __('Payment confirmed — the invoice is paid.', 'easy-invoice')
1651 + : sprintf(/* translators: %s: amount still owed. */ __('Payment confirmed — %s still due.', 'easy-invoice'), $currency_symbol . number_format_i18n(\EasyInvoice\Services\InvoiceBalance::due($invoice), 2))
1652 + );
1653 + }
1249 1654
1250 - // Get currency from invoice
1251 - $currency_code = get_post_meta($invoice_id, '_easy_invoice_currency_code', true);
1252 - if (empty($currency_code) || $currency_code === 'global') {
1253 - $currency_code = get_option('easy_invoice_currency_code', 'USD');
1254 - }
1255 - $currency_symbol = \EasyInvoice\Helpers\CurrencyHelper::getCurrencySymbol($currency_code);
1655 + /**
1656 + * Turn down an offline payment a client told us about: the record stays
1657 + * (marked rejected, with the reason) so the trail is complete, nothing
1658 + * counts toward the balance, and the invoice keeps its status.
1659 + */
1660 + public function rejectPayment(): void {
1661 + $payment_id = isset($_POST['payment_id']) ? absint($_POST['payment_id']) : 0;
1662 + $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
1663 + $reason = isset($_POST['notes']) ? sanitize_textarea_field(wp_unslash($_POST['notes'])) : '';
1256 1664
1257 - $payment_data = [
1258 - 'invoice_id' => $invoice_id,
1259 - 'amount' => $invoice->getTotal(), // Or get amount from proof submission if it varies
1260 - 'payment_method' => $payment_method,
1261 - 'status' => 'completed',
1262 - 'transaction_id' => get_post_meta($invoice_id, '_' . $payment_method . '_transaction_id', true) ?: 'MANUAL-' . $invoice_id,
1263 - 'payment_date' => current_time('mysql'),
1264 - 'notes' => $payment_notes, // Use provided notes
1265 - 'payment_type' => 'manual',
1266 - 'currency' => $currency_code,
1267 - 'currency_symbol' => $currency_symbol,
1268 - 'gateway_response' => json_encode([
1269 - 'admin_verified' => true,
1270 - 'user' => get_current_user_id(),
1271 - 'verification_date' => current_time('mysql'),
1272 - 'notes' => $payment_notes // Store notes in response JSON as well
1273 - ])
1274 - ];
1275 - try {
1276 - // Create payment record using WordPress post creation
1277 - $payment_post_data = [
1278 - 'post_title' => sprintf('Manual Payment for Invoice #%s', $invoice->getNumber()),
1279 - 'post_type' => 'easy_invoice_payment',
1280 - 'post_status' => 'publish',
1281 - 'post_author' => get_current_user_id(),
1282 - 'meta_input' => [
1283 - '_invoice_id' => $invoice_id,
1284 - '_amount' => $invoice->getTotal(),
1285 - '_payment_method' => $payment_method,
1286 - '_status' => 'completed',
1287 - '_transaction_id' => get_post_meta($invoice_id, '_' . $payment_method . '_transaction_id', true) ?: 'MANUAL-' . $invoice_id,
1288 - '_payment_date' => current_time('mysql'),
1289 - '_notes' => $payment_notes,
1290 - '_payment_type' => 'manual',
1291 - '_currency' => $currency_code,
1292 - '_currency_symbol' => $currency_symbol,
1293 - '_gateway_response' => json_encode([
1294 - 'admin_verified' => true,
1295 - 'user' => get_current_user_id(),
1296 - 'verification_date' => current_time('mysql'),
1297 - 'notes' => $payment_notes
1298 - ])
1299 - ]
1300 - ];
1665 + if (!$payment_id || !wp_verify_nonce($nonce, 'easy_invoice_approve_payment')) {
1666 + easy_invoice_toast_error(__('Invalid request or security check failed.', 'easy-invoice'));
1667 + return;
1668 + }
1669 + if (!easy_invoice_user_can('ei_record_payment')) {
1670 + easy_invoice_toast_error(__('You do not have permission to perform this action.', 'easy-invoice'));
1671 + return;
1672 + }
1673 + if ('easy_invoice_payment' !== get_post_type($payment_id)) {
1674 + easy_invoice_toast_error(__('Payment not found.', 'easy-invoice'));
1675 + return;
1676 + }
1677 + $status = (string) get_post_meta($payment_id, '_status', true);
1678 + if (!in_array($status, \EasyInvoice\Services\OfflinePayments::pendingStatuses(), true)) {
1679 + easy_invoice_toast_error(__('Only a pending payment can be rejected.', 'easy-invoice'));
1680 + return;
1681 + }
1682 + $invoice_id = (int) get_post_meta($payment_id, '_invoice_id', true);
1301 1683
1302 - $payment_id = wp_insert_post($payment_post_data);
1303 - if (is_wp_error($payment_id)) {
1304 - easy_invoice_toast_error(__('Error creating payment record:', 'easy-invoice') . ' ' . $payment_id->get_error_message());
1305 - return;
1306 - }
1307 - } catch (\Exception $e) {
1308 - easy_invoice_toast_error(__('Error creating payment record:', 'easy-invoice') . ' ' . $e->getMessage());
1309 - return;
1684 + update_post_meta($payment_id, '_status', 'rejected');
1685 + update_post_meta($payment_id, '_rejected_by', get_current_user_id());
1686 + update_post_meta($payment_id, '_rejected_at', current_time('mysql'));
1687 + if ('' !== $reason) {
1688 + $existing = (string) get_post_meta($payment_id, '_notes', true);
1689 + update_post_meta($payment_id, '_notes', trim($existing . ('' !== $existing ? "\n" : '') . __('Rejected:', 'easy-invoice') . ' ' . $reason));
1690 + }
1691 + if ($invoice_id) {
1692 + if (\EasyInvoice\Services\OfflinePayments::pendingForInvoice($invoice_id)) {
1693 + update_post_meta($invoice_id, '_payment_status', 'pending');
1694 + } else {
1695 + delete_post_meta($invoice_id, '_payment_status');
1310 1696 }
1311 1697 }
1698 + /**
1699 + * Fires when staff reject an offline payment submission.
1700 + *
1701 + * @param int $payment_id Payment record, now rejected.
1702 + * @param int $invoice_id Invoice.
1703 + * @param string $reason Reason given, if any.
1704 + */
1705 + do_action('easy_invoice_payment_rejected', $payment_id, $invoice_id, $reason);
1312 1706
1313 - // Store payment details before updating status (for the hook)
1314 - $transaction_id = get_post_meta($invoice_id, '_' . $payment_method . '_transaction_id', true) ?: 'MANUAL-' . $invoice_id;
1315 - $invoice->setMeta('_payment_method', $payment_method);
1316 - $invoice->setMeta('_transaction_id', $transaction_id);
1707 + easy_invoice_toast_success(__('Payment rejected. The invoice still shows the amount as due.', 'easy-invoice'));
1708 + }
1317 1709
1318 - // Update invoice status to paid
1319 - // This will trigger 'easy_invoice_payment_completed' hook which sends admin notification
1320 - $invoice->setStatus('paid');
1321 - $invoice->save();
1710 + /**
1711 + * Record money received, from the admin "Add New Payment" form.
1712 + *
1713 + * The form used to post to the customer checkout endpoint, which runs a
1714 + * gateway (bank-transfer instructions, a card form) — not what an admin
1715 + * typing in a cheque they were handed wants. This books a completed
1716 + * payment and settles the invoice: paid when the total is covered,
1717 + * partial otherwise.
1718 + */
1719 + public function recordPayment() {
1720 + if (!isset($_POST['payment_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['payment_nonce'])), 'easy_invoice_payment')) {
1721 + wp_send_json_error(['message' => __('Security check failed. Please reload the page and try again.', 'easy-invoice')]);
1722 + }
1723 + if (!easy_invoice_user_can('ei_record_payment')) {
1724 + wp_send_json_error(['message' => __('You do not have permission to record payments.', 'easy-invoice')]);
1725 + }
1726 + $invoice_id = isset($_POST['invoice_id']) ? absint($_POST['invoice_id']) : 0;
1727 + $amount = isset($_POST['amount']) ? (float) str_replace(',', '', sanitize_text_field(wp_unslash($_POST['amount']))) : 0.0;
1728 + $method = isset($_POST['payment_method']) ? sanitize_key(wp_unslash($_POST['payment_method'])) : '';
1729 + $date = isset($_POST['payment_date']) ? sanitize_text_field(wp_unslash($_POST['payment_date'])) : '';
1730 + $notes = isset($_POST['notes']) ? sanitize_textarea_field(wp_unslash($_POST['notes'])) : '';
1322 1731
1323 - // Trigger the payment completed hook manually since we're updating status directly
1324 - do_action('easy_invoice_payment_completed', $invoice_id, $invoice, [
1325 - 'payment_method' => $payment_method,
1326 - 'gateway_name' => 'manual',
1327 - 'transaction_id' => $transaction_id,
1328 - 'amount' => $invoice->getTotal()
1732 + $invoice = $invoice_id > 0 ? \EasyInvoice\Providers\InvoiceServiceProvider::getInvoiceRepository()->find($invoice_id) : null;
1733 + if (!$invoice) {
1734 + wp_send_json_error(['message' => __('Choose the invoice the payment is for.', 'easy-invoice')]);
1735 + }
1736 + if ($amount <= 0) {
1737 + wp_send_json_error(['message' => __('Enter an amount greater than zero.', 'easy-invoice')]);
1738 + }
1739 + if ('' === $method) {
1740 + $method = 'manual';
1741 + }
1742 + $when = $date && strtotime($date) ? gmdate('Y-m-d H:i:s', strtotime($date)) : current_time('mysql');
1743 +
1744 + $currency_code = $invoice->getCurrencyCode() ?: get_option('easy_invoice_currency_code', 'USD');
1745 + $currency_symbol = \EasyInvoice\Helpers\CurrencyHelper::getCurrencySymbol($currency_code);
1746 + $payment_id = wp_insert_post([
1747 + 'post_title' => sprintf('Payment for Invoice #%s', $invoice->getNumber()),
1748 + 'post_type' => 'easy_invoice_payment',
1749 + 'post_status' => 'publish',
1750 + 'post_author' => get_current_user_id(),
1751 + 'meta_input' => [
1752 + '_invoice_id' => $invoice_id,
1753 + '_amount' => round($amount, 2),
1754 + '_payment_method' => $method,
1755 + '_status' => 'completed',
1756 + '_transaction_id' => 'MANUAL-' . $invoice_id . '-' . time(),
1757 + '_payment_date' => $when,
1758 + '_notes' => $notes,
1759 + '_payment_type' => 'manual',
1760 + '_currency' => $currency_code,
1761 + '_currency_symbol' => $currency_symbol,
1762 + '_gateway_response' => wp_json_encode(['recorded_by' => get_current_user_id(), 'recorded_at' => current_time('mysql'), 'notes' => $notes]),
1763 + ],
1329 1764 ]);
1765 + if (is_wp_error($payment_id) || !$payment_id) {
1766 + wp_send_json_error(['message' => __('The payment could not be saved.', 'easy-invoice')]);
1767 + }
1330 1768
1331 - // Trigger email confirmation and actions only if we have a payment_id
1332 - if ($payment_id) {
1333 - // Send confirmation email to customer
1334 - $this->sendPaymentConfirmationEmail($invoice_id, $payment_id);
1335 - do_action('easy_invoice_manual_payment_confirmed', $invoice_id, $payment_id, $payment_method);
1769 + $new_status = \EasyInvoice\Services\InvoiceBalance::isSettled($invoice) ? 'paid' : 'partial';
1770 + update_post_meta($invoice_id, '_easy_invoice_payment_method', $method);
1771 + $invoice->setStatus($new_status);
1772 + $invoice->save();
1773 + $payment_event = [
1774 + 'payment_method' => $method,
1775 + 'gateway_name' => 'manual',
1776 + 'transaction_id' => get_post_meta($payment_id, '_transaction_id', true),
1777 + 'amount' => $amount,
1778 + 'date' => $date,
1779 + ];
1780 + if ('paid' === $new_status) {
1781 + do_action('easy_invoice_payment_completed', $invoice_id, $invoice, $payment_event);
1782 + } else {
1783 + /**
1784 + * Fires when a payment is recorded that leaves a balance owing.
1785 + *
1786 + * @param int $invoice_id Invoice.
1787 + * @param object $invoice Invoice model.
1788 + * @param array $payment payment_method, gateway_name, transaction_id, amount, date.
1789 + */
1790 + do_action('easy_invoice_payment_received', $invoice_id, $invoice, $payment_event);
1336 1791 }
1792 + /**
1793 + * Fires after an administrator records a payment by hand.
1794 + *
1795 + * @param int $payment_id Payment record.
1796 + * @param int $invoice_id Invoice.
1797 + * @param float $amount Amount recorded.
1798 + * @param string $new_status Invoice status afterwards.
1799 + */
1800 + do_action('easy_invoice_payment_recorded', $payment_id, $invoice_id, $amount, $new_status);
1337 1801
1338 - easy_invoice_toast_success(__('Invoice marked as paid successfully.', 'easy-invoice'));
1802 + wp_send_json_success([
1803 + 'payment_id' => $payment_id,
1804 + 'status' => $new_status,
1805 + 'message' => 'paid' === $new_status
1806 + ? __('Payment recorded — the invoice is paid.', 'easy-invoice')
1807 + : sprintf(/* translators: %s: amount still owed. */ __('Payment recorded — %s still due.', 'easy-invoice'), $currency_symbol . number_format_i18n(\EasyInvoice\Services\InvoiceBalance::due($invoice), 2)),
1808 + ]);
1339 1809 }
1340 1810
1341 1811 /**
1342 1812 * Handle bulk actions for payments
@@ -1347,19 +1817,21 @@
1347 1817 return;
1348 1818 }
1349 1819
1350 1820 // Check nonce and capability
1351 - if (!wp_verify_nonce($_POST['easy_invoice_payment_bulk_nonce'], 'easy_invoice_payment_bulk_action')) {
1352 - wp_die(__('Security check failed.', 'easy-invoice'));
1821 + if (!wp_verify_nonce(($_POST['easy_invoice_payment_bulk_nonce'] ?? ''), 'easy_invoice_payment_bulk_action')) {
1822 + wp_die(esc_html__('Security check failed.', 'easy-invoice'));
1353 1823 }
1354 1824
1355 - if (!current_user_can('manage_options')) {
1356 - wp_die(__('You do not have permission to perform this action.', 'easy-invoice'));
1825 + // Bulk action on payments — record-payment cap is the right gate
1826 + // (covers trash/restore/delete which all change payment state).
1827 + if (!easy_invoice_user_can('ei_record_payment')) {
1828 + wp_die(esc_html__('You do not have permission to perform this action.', 'easy-invoice'));
1357 1829 }
1358 1830
1359 1831 // Check if we have payment IDs
1360 1832 if (!isset($_POST['payment_ids']) || !is_array($_POST['payment_ids']) || empty($_POST['payment_ids'])) {
1361 - wp_redirect(admin_url('admin.php?page=easy-invoice-payments&bulk_error=no_selection'));
1833 + wp_safe_redirect(admin_url('admin.php?page=easy-invoice-payments&bulk_error=no_selection'));
1362 1834 exit;
1363 1835 }
1364 1836
1365 1837 // Get bulk action and payment IDs
@@ -1396,13 +1868,13 @@
1396 1868 }
1397 1869 }
1398 1870
1399 1871 // Update invoice statuses for completed payments that were trashed
1400 - foreach ($invoice_updates as $invoice_id => $deleted_amount) {
1401 - $this->updateInvoiceStatusAfterPaymentDeletion($invoice_id, $deleted_amount);
1872 + foreach (array_keys($invoice_updates) as $invoice_id) {
1873 + $this->syncInvoiceStatusWithPayments($invoice_id);
1402 1874 }
1403 1875
1404 - wp_redirect(admin_url('admin.php?page=easy-invoice-payments&bulk_trashed=' . $processed));
1876 + wp_safe_redirect(admin_url('admin.php?page=easy-invoice-payments&bulk_trashed=' . $processed));
1405 1877 break;
1406 1878
1407 1879 case 'restore':
1408 1880 foreach ($payment_ids as $id) {
@@ -1434,13 +1906,13 @@
1434 1906 }
1435 1907 }
1436 1908
1437 1909 // Update invoice statuses for completed payments that were restored
1438 - foreach ($invoice_updates as $invoice_id => $restored_amount) {
1439 - $this->updateInvoiceStatusAfterPaymentRestoration($invoice_id, $restored_amount);
1910 + foreach (array_keys($invoice_updates) as $invoice_id) {
1911 + $this->syncInvoiceStatusWithPayments($invoice_id);
1440 1912 }
1441 1913
1442 - wp_redirect(admin_url('admin.php?page=easy-invoice-payments&bulk_restored=' . $processed));
1914 + wp_safe_redirect(admin_url('admin.php?page=easy-invoice-payments&bulk_restored=' . $processed));
1443 1915 break;
1444 1916
1445 1917 case 'delete':
1446 1918 foreach ($payment_ids as $id) {
@@ -1467,17 +1939,17 @@
1467 1939 }
1468 1940 }
1469 1941
1470 1942 // Update invoice statuses for completed payments that were deleted
1471 - foreach ($invoice_updates as $invoice_id => $deleted_amount) {
1472 - $this->updateInvoiceStatusAfterPaymentDeletion($invoice_id, $deleted_amount);
1943 + foreach (array_keys($invoice_updates) as $invoice_id) {
1944 + $this->syncInvoiceStatusWithPayments($invoice_id);
1473 1945 }
1474 1946
1475 - wp_redirect(admin_url('admin.php?page=easy-invoice-payments&bulk_deleted=' . $processed));
1947 + wp_safe_redirect(admin_url('admin.php?page=easy-invoice-payments&bulk_deleted=' . $processed));
1476 1948 break;
1477 1949
1478 1950 default:
1479 - wp_redirect(admin_url('admin.php?page=easy-invoice-payments&bulk_error=invalid_action'));
1951 + wp_safe_redirect(admin_url('admin.php?page=easy-invoice-payments&bulk_error=invalid_action'));
1480 1952 }
1481 1953
1482 1954 exit;
1483 1955 }
@@ -1482,108 +1954,40 @@
1482 1954 exit;
1483 1955 }
1484 1956
1485 1957 /**
1486 - * Update invoice status after payment deletion
1958 + * Put an invoice's status back in line with the completed payments and
1959 + * credit notes it actually has — after a payment is trashed, restored or
1960 + * deleted. Paid when nothing is owed, part-paid when something has been
1961 + * received, otherwise awaiting payment; an issued invoice never returns
1962 + * to draft. (This used to write the status to a meta key the invoice
1963 + * does not use, so a trashed payment left the invoice "paid".)
1964 + *
1965 + * @param int $invoice_id Invoice.
1487 1966 */
1488 - private function updateInvoiceStatusAfterPaymentDeletion($invoice_id, $deleted_amount) {
1489 - $invoice = new Invoice($invoice_id);
1490 -
1491 - if (!$invoice->getId()) {
1967 + private function syncInvoiceStatusWithPayments($invoice_id) {
1968 + $invoice = \EasyInvoice\Providers\InvoiceServiceProvider::getInvoiceRepository()->find((int) $invoice_id);
1969 + if (!$invoice || !$invoice->getId()) {
1492 1970 return;
1493 1971 }
1494 -
1495 - // Get all remaining payments for this invoice
1496 - $remaining_payments = get_posts(array(
1497 - 'post_type' => 'easy_invoice_payment',
1498 - 'post_status' => 'publish',
1499 - 'meta_query' => array(
1500 - array(
1501 - 'key' => '_invoice_id',
1502 - 'value' => $invoice_id,
1503 - 'compare' => '='
1504 - ),
1505 - array(
1506 - 'key' => '_status',
1507 - 'value' => 'completed',
1508 - 'compare' => '='
1509 - )
1510 - ),
1511 - 'posts_per_page' => -1
1512 - ));
1513 -
1514 - // Calculate total remaining payments
1515 - $total_remaining = 0;
1516 - foreach ($remaining_payments as $payment_post) {
1517 - $payment = new Payment($payment_post);
1518 - $total_remaining += floatval($payment->getAmount());
1972 + $current = (string) $invoice->getStatus();
1973 + if (in_array($current, ['draft', 'cancelled', 'canceled'], true)) {
1974 + return;
1519 1975 }
1520 -
1521 - $invoice_total = floatval($invoice->getTotal());
1522 -
1523 - // Update invoice status based on remaining payments
1524 - if ($total_remaining >= $invoice_total) {
1525 - // Still fully paid
1526 - update_post_meta($invoice_id, '_status', 'paid');
1527 - } elseif ($total_remaining > 0) {
1528 - // Partially paid
1529 - update_post_meta($invoice_id, '_status', 'partial');
1976 + $paid = \EasyInvoice\Services\InvoiceBalance::paid((int) $invoice_id);
1977 + if (\EasyInvoice\Services\InvoiceBalance::isSettled($invoice)) {
1978 + $new = 'paid';
1979 + } elseif ($paid > 0) {
1980 + $new = 'partial';
1530 1981 } else {
1531 - // No payments remaining
1532 - update_post_meta($invoice_id, '_status', 'unpaid');
1982 + $new = in_array($current, ['unpaid', 'available'], true) ? $current : 'available';
1533 1983 }
1984 + if ($new !== $current) {
1985 + $invoice->setStatus($new);
1986 + $invoice->save();
1987 + }
1534 1988 }
1535 1989
1536 - /**
1537 - * Update invoice status after payment restoration
1538 - */
1539 - private function updateInvoiceStatusAfterPaymentRestoration($invoice_id, $restored_amount) {
1540 - $invoice = new Invoice($invoice_id);
1541 -
1542 - if (!$invoice->getId()) {
1543 - return;
1544 - }
1545 -
1546 - // Get all payments for this invoice (including the restored one)
1547 - $all_payments = get_posts(array(
1548 - 'post_type' => 'easy_invoice_payment',
1549 - 'post_status' => 'publish',
1550 - 'meta_query' => array(
1551 - array(
1552 - 'key' => '_invoice_id',
1553 - 'value' => $invoice_id,
1554 - 'compare' => '='
1555 - ),
1556 - array(
1557 - 'key' => '_status',
1558 - 'value' => 'completed',
1559 - 'compare' => '='
1560 - )
1561 - ),
1562 - 'posts_per_page' => -1
1563 - ));
1564 -
1565 - // Calculate total payments (including restored ones)
1566 - $total_payments = 0;
1567 - foreach ($all_payments as $payment_post) {
1568 - $payment = new Payment($payment_post);
1569 - $total_payments += floatval($payment->getAmount());
1570 - }
1571 -
1572 - $invoice_total = floatval($invoice->getTotal());
1573 -
1574 - // Update invoice status based on total payments
1575 - if ($total_payments >= $invoice_total) {
1576 - // Fully paid
1577 - update_post_meta($invoice_id, '_status', 'paid');
1578 - } elseif ($total_payments > 0) {
1579 - // Partially paid
1580 - update_post_meta($invoice_id, '_status', 'partial');
1581 - } else {
1582 - // No payments
1583 - update_post_meta($invoice_id, '_status', 'unpaid');
1584 - }
1585 - }
1586 1990
1587 1991 // Stripe payment recording moved to Pro plugin
1588 1992
1589 1993