| @@ -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']); |
| @@ -60,13 +68,20 @@ | ||
| 60 | 68 | |
| 61 | 69 | // Handler for submitting payment proof for manual gateways |
| 62 | 70 | add_action('wp_ajax_easy_invoice_submit_payment_proof', [$this, 'submitPaymentProof']); |
| 63 | 71 | add_action('wp_ajax_nopriv_easy_invoice_submit_payment_proof', [$this, 'submitPaymentProof']); |
| 72 | + | |
| 73 | + // Handler for manual payment submission | |
| 74 | + add_action('wp_ajax_easy_invoice_submit_manual_payment', [$this, 'submitManualPayment']); | |
| 75 | + add_action('wp_ajax_nopriv_easy_invoice_submit_manual_payment', [$this, 'submitManualPayment']); | |
| 64 | 76 | |
| 65 | 77 | // Handler for getting payment instructions for manual gateways |
| 66 | 78 | add_action('wp_ajax_easy_invoice_get_payment_instructions', [$this, 'getPaymentInstructions']); |
| 67 | 79 | add_action('wp_ajax_nopriv_easy_invoice_get_payment_instructions', [$this, 'getPaymentInstructions']); |
| 68 | 80 | |
| 81 | + // Enqueue frontend scripts | |
| 82 | + add_action('wp_enqueue_scripts', [$this, 'enqueueFrontendAssets']); | |
| 83 | + | |
| 69 | 84 | // Handler for admin to mark an invoice as paid |
| 70 | 85 | add_action('wp_ajax_easy_invoice_approve_payment', [$this, 'mark_invoice_paid_ajax']); |
| 71 | 86 | |
| 72 | 87 | // Stripe payment handlers moved to Pro plugin |
| @@ -72,15 +87,8 @@ | ||
| 72 | 87 | // Stripe payment handlers moved to Pro plugin |
| 73 | 88 | |
| 74 | 89 | add_action('wp_enqueue_scripts', [$this, 'enqueueScripts']); |
| 75 | 90 | |
| 76 | - // Add filter to show pending payments in admin | |
| 77 | - add_filter('easy_invoice_admin_payment_statuses', [$this, 'addPendingPaymentStatuses']); | |
| 78 | - | |
| 79 | - // Add custom columns to payments list | |
| 80 | - add_filter('manage_easy-payment_posts_columns', [$this, 'addPaymentMethodColumn']); | |
| 81 | - add_action('manage_easy-payment_posts_custom_column', [$this, 'renderPaymentMethodColumn'], 10, 2); | |
| 82 | - | |
| 83 | 91 | // Add reminder CRON job for pending payments |
| 84 | 92 | add_action('easy_invoice_payment_reminder', [$this, 'sendPaymentReminders']); |
| 85 | 93 | if (!wp_next_scheduled('easy_invoice_payment_reminder')) { |
| 86 | 94 | wp_schedule_event(time(), 'daily', 'easy_invoice_payment_reminder'); |
| @@ -93,16 +101,18 @@ | ||
| 93 | 101 | /** |
| 94 | 102 | * Get payment instructions for manual gateways |
| 95 | 103 | */ |
| 96 | 104 | public function getPaymentInstructions() { |
| 97 | - // Verify nonce | |
| 98 | - if (!wp_verify_nonce($_POST['nonce'], 'easy_invoice_payment')) { | |
| 105 | + // Verify nonce. $_POST['nonce'] was read unguarded, raising an | |
| 106 | + // undefined-index warning before the check could run. | |
| 107 | + $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : ''; | |
| 108 | + if (!wp_verify_nonce($nonce, 'easy_invoice_payment')) { | |
| 99 | 109 | wp_send_json_error(['message' => 'Security check failed']); |
| 100 | 110 | return; |
| 101 | 111 | } |
| 102 | 112 | |
| 103 | - $gateway = sanitize_text_field($_POST['gateway']); | |
| 104 | - $invoice_id = intval($_POST['invoice_id']); | |
| 113 | + $gateway = sanitize_text_field(($_POST['gateway'] ?? '')); | |
| 114 | + $invoice_id = intval(($_POST['invoice_id'] ?? '')); | |
| 105 | 115 | |
| 106 | 116 | if (!$gateway || !$invoice_id) { |
| 107 | 117 | wp_send_json_error(['message' => 'Missing required parameters']); |
| 108 | 118 | return; |
| @@ -116,8 +126,25 @@ | ||
| 116 | 126 | } |
| 117 | 127 | |
| 118 | 128 | $invoice = new \EasyInvoice\Models\Invoice($invoice_post); |
| 119 | 129 | |
| 130 | + // Authorisation. | |
| 131 | + // | |
| 132 | + // The previous guard here was `!easy_invoice_user_can('ei_view_invoices') && | |
| 133 | + // $invoice_post->post_status !== 'publish'`. That never fired: Models\Invoice | |
| 134 | + // writes every invoice with post_status 'publish' regardless of workflow | |
| 135 | + // status, so the second condition was always false. This endpoint is | |
| 136 | + // registered nopriv and the nonce it checks is a shared, page-wide one, so | |
| 137 | + // any caller could read the rendered payment instructions — which include | |
| 138 | + // invoice-specific detail — for an arbitrary invoice id. | |
| 139 | + // | |
| 140 | + // Same check as everywhere else: valid ?ik= / access_token, administrator, or | |
| 141 | + // the signed-in client the invoice belongs to. | |
| 142 | + if (!\EasyInvoice\Controllers\InvoiceController::canSubmitPaymentForInvoice($invoice_id, $invoice)) { | |
| 143 | + wp_send_json_error(['message' => __('Invoice not found', 'easy-invoice')]); | |
| 144 | + return; | |
| 145 | + } | |
| 146 | + | |
| 120 | 147 | // Get gateway instance |
| 121 | 148 | $gateway_instance = $this->gatewayManager->getGateway($gateway); |
| 122 | 149 | |
| 123 | 150 | if (!$gateway_instance) { |
| @@ -145,12 +172,57 @@ | ||
| 145 | 172 | if (!$screen || !property_exists($screen, 'id') || strpos($screen->id, 'easy-invoice') === false) { |
| 146 | 173 | return; |
| 147 | 174 | } |
| 148 | 175 | |
| 176 | + // Enqueue manual payment script | |
| 177 | + wp_enqueue_script( | |
| 178 | + 'easy-invoice-manual-payment', | |
| 179 | + EASY_INVOICE_PLUGIN_URL . 'assets/js/manual-payment.js', | |
| 180 | + ['jquery'], | |
| 181 | + '1.0.0', | |
| 182 | + true | |
| 183 | + ); | |
| 149 | 184 | |
| 185 | + // Localize script | |
| 186 | + wp_localize_script('easy-invoice-manual-payment', 'easy_invoice_ajax', [ | |
| 187 | + 'ajax_url' => admin_url('admin-ajax.php'), | |
| 188 | + 'nonce' => wp_create_nonce('easy_invoice_payment') | |
| 189 | + ]); | |
| 150 | 190 | } |
| 151 | 191 | |
| 152 | 192 | /** |
| 193 | + * Enqueue frontend assets | |
| 194 | + */ | |
| 195 | + public function enqueueFrontendAssets() { | |
| 196 | + // Only load on invoice pages | |
| 197 | + if (is_singular('easy_invoice')) { | |
| 198 | + wp_enqueue_script( | |
| 199 | + 'easy-invoice-manual-payment', | |
| 200 | + EASY_INVOICE_PLUGIN_URL . 'assets/js/manual-payment.js', | |
| 201 | + ['jquery'], | |
| 202 | + '1.0.0', | |
| 203 | + true | |
| 204 | + ); | |
| 205 | + | |
| 206 | + // Forward the per-invoice access token from the URL to the JS | |
| 207 | + // so the manual-payment AJAX request can present it back to | |
| 208 | + // canSubmitPaymentForInvoice. Without this the legitimate | |
| 209 | + // email-link recipient flow would break — they'd hit the gate. | |
| 210 | + $access_token = isset($_GET['ik']) | |
| 211 | + ? sanitize_text_field(wp_unslash($_GET['ik'])) | |
| 212 | + : ''; | |
| 213 | + /** This filter is documented in includes/Controllers/InvoiceController.php */ | |
| 214 | + $access_token = (string) apply_filters('easy_invoice_presented_access_token', $access_token, 'invoice'); | |
| 215 | + | |
| 216 | + wp_localize_script('easy-invoice-manual-payment', 'easy_invoice_ajax', [ | |
| 217 | + 'ajax_url' => admin_url('admin-ajax.php'), | |
| 218 | + 'nonce' => wp_create_nonce('easy_invoice_payment'), | |
| 219 | + 'access_token' => $access_token, | |
| 220 | + ]); | |
| 221 | + } | |
| 222 | + } | |
| 223 | + | |
| 224 | + /** | |
| 153 | 225 | * Display method implementation |
| 154 | 226 | * |
| 155 | 227 | * @param array $args Display arguments |
| 156 | 228 | */ |
| @@ -174,15 +246,15 @@ | ||
| 174 | 246 | try { |
| 175 | 247 | $payment = new Payment($payment_post); |
| 176 | 248 | $this->displayTemplate(EASY_INVOICE_PLUGIN_DIR . 'templates/payments/view.php', ['payment' => $payment]); |
| 177 | 249 | } catch (\Exception $e) { |
| 178 | - wp_die(__('Invalid payment ID', 'easy-invoice')); | |
| 250 | + wp_die(esc_html__('Invalid payment ID', 'easy-invoice')); | |
| 179 | 251 | } |
| 180 | 252 | } else { |
| 181 | - wp_die(__('Invalid payment ID', 'easy-invoice')); | |
| 253 | + wp_die(esc_html__('Invalid payment ID', 'easy-invoice')); | |
| 182 | 254 | } |
| 183 | 255 | } else { |
| 184 | - wp_die(__('Payment ID is required', 'easy-invoice')); | |
| 256 | + wp_die(esc_html__('Payment ID is required', 'easy-invoice')); | |
| 185 | 257 | } |
| 186 | 258 | break; |
| 187 | 259 | |
| 188 | 260 | case 'edit': |
| @@ -193,15 +265,15 @@ | ||
| 193 | 265 | try { |
| 194 | 266 | $payment = new Payment($payment_post); |
| 195 | 267 | $this->displayTemplate(EASY_INVOICE_PLUGIN_DIR . 'templates/payments/edit.php', ['payment' => $payment]); |
| 196 | 268 | } catch (\Exception $e) { |
| 197 | - wp_die(__('Invalid payment ID', 'easy-invoice')); | |
| 269 | + wp_die(esc_html__('Invalid payment ID', 'easy-invoice')); | |
| 198 | 270 | } |
| 199 | 271 | } else { |
| 200 | - wp_die(__('Invalid payment ID', 'easy-invoice')); | |
| 272 | + wp_die(esc_html__('Invalid payment ID', 'easy-invoice')); | |
| 201 | 273 | } |
| 202 | 274 | } else { |
| 203 | - wp_die(__('Payment ID is required', 'easy-invoice')); | |
| 275 | + wp_die(esc_html__('Payment ID is required', 'easy-invoice')); | |
| 204 | 276 | } |
| 205 | 277 | break; |
| 206 | 278 | |
| 207 | 279 | default: |
| @@ -278,64 +350,37 @@ | ||
| 278 | 350 | // Get pagination info from WordPress query |
| 279 | 351 | $total_payments = $wp_query->found_posts; |
| 280 | 352 | $total_pages = $wp_query->max_num_pages; |
| 281 | 353 | |
| 282 | - // Calculate statistics from ALL payments (not just current page) | |
| 283 | - $stats_args = array( | |
| 284 | - 'post_type' => 'easy_invoice_payment', | |
| 285 | - 'posts_per_page' => -1, // Get all payments | |
| 286 | - 'meta_query' => array( | |
| 287 | - array( | |
| 288 | - 'key' => '_status', | |
| 289 | - 'compare' => 'EXISTS', | |
| 290 | - ), | |
| 291 | - ), | |
| 292 | - ); | |
| 293 | - | |
| 294 | - // Set post status for stats based on current view | |
| 295 | - if ($current_view === 'trash') { | |
| 296 | - $stats_args['post_status'] = 'trash'; | |
| 297 | - } else { | |
| 298 | - $stats_args['post_status'] = 'publish'; | |
| 299 | - } | |
| 300 | - | |
| 301 | - $stats_query = new \WP_Query($stats_args); | |
| 302 | - | |
| 354 | + // Statistics over ALL payments (not just the current page), in one SQL | |
| 355 | + // pass. Loading every payment as a model to add them up did not scale. | |
| 356 | + global $wpdb; | |
| 357 | + $stats_status = 'trash' === $current_view ? 'trash' : 'publish'; | |
| 358 | + $stat_rows = $wpdb->get_results( $wpdb->prepare( | |
| 359 | + "SELECT st.meta_value AS status, COUNT(*) AS n, SUM(CAST(COALESCE(NULLIF(a.meta_value, ''), '0') AS DECIMAL(18,4))) AS amount | |
| 360 | + FROM {$wpdb->posts} p | |
| 361 | + INNER JOIN {$wpdb->postmeta} st ON st.post_id = p.ID AND st.meta_key = '_status' | |
| 362 | + LEFT JOIN {$wpdb->postmeta} a ON a.post_id = p.ID AND a.meta_key = '_amount' | |
| 363 | + WHERE p.post_type = 'easy_invoice_payment' AND p.post_status = %s | |
| 364 | + GROUP BY st.meta_value", | |
| 365 | + $stats_status | |
| 366 | + ), ARRAY_A ); | |
| 303 | 367 | $stats = [ |
| 304 | - 'total_payments' => $stats_query->found_posts, | |
| 305 | - 'total_amount' => 0, | |
| 368 | + 'total_payments' => 0, | |
| 369 | + 'total_amount' => 0, | |
| 306 | 370 | 'completed_payments' => 0, |
| 307 | - 'pending_payments' => 0, | |
| 308 | - 'failed_payments' => 0 | |
| 371 | + 'pending_payments' => 0, | |
| 372 | + 'failed_payments' => 0, | |
| 309 | 373 | ]; |
| 310 | - | |
| 311 | - // Calculate stats from the query results | |
| 312 | - if ($stats_query->have_posts()) { | |
| 313 | - while ($stats_query->have_posts()) { | |
| 314 | - $stats_query->the_post(); | |
| 315 | - $payment = new Payment(get_post()); | |
| 316 | - | |
| 317 | - $amount = floatval($payment->getAmount()); | |
| 318 | - $status = $payment->getStatus(); | |
| 319 | - | |
| 320 | - $stats['total_amount'] += $amount; | |
| 321 | - | |
| 322 | - switch ($status) { | |
| 323 | - case 'completed': | |
| 324 | - $stats['completed_payments']++; | |
| 325 | - break; | |
| 326 | - case 'pending': | |
| 327 | - $stats['pending_payments']++; | |
| 328 | - break; | |
| 329 | - case 'failed': | |
| 330 | - $stats['failed_payments']++; | |
| 331 | - break; | |
| 332 | - } | |
| 374 | + foreach ( (array) $stat_rows as $row ) { | |
| 375 | + $stats['total_payments'] += (int) $row['n']; | |
| 376 | + $stats['total_amount'] += (float) $row['amount']; | |
| 377 | + $key = $row['status'] . '_payments'; | |
| 378 | + if ( isset( $stats[ $key ] ) ) { | |
| 379 | + $stats[ $key ] += (int) $row['n']; | |
| 333 | 380 | } |
| 334 | 381 | } |
| 335 | - wp_reset_postdata(); | |
| 336 | 382 | |
| 337 | - // Ensure all required keys exist with default values | |
| 338 | 383 | $stats = array_merge([ |
| 339 | 384 | 'total_payments' => 0, |
| 340 | 385 | 'total_amount' => 0, |
| 341 | 386 | 'completed_payments' => 0, |
| @@ -343,15 +388,9 @@ | ||
| 343 | 388 | 'failed_payments' => 0 |
| 344 | 389 | ], $stats); |
| 345 | 390 | |
| 346 | 391 | // Get trash count for tab display |
| 347 | - $trash_args = array( | |
| 348 | - 'post_type' => 'easy_invoice_payment', | |
| 349 | - 'post_status' => 'trash', | |
| 350 | - 'posts_per_page' => -1 | |
| 351 | - ); | |
| 352 | - $trash_query = new \WP_Query($trash_args); | |
| 353 | - $trash_count = $trash_query->found_posts; | |
| 392 | + $trash_count = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_type = 'easy_invoice_payment' AND post_status = 'trash'" ); | |
| 354 | 393 | |
| 355 | 394 | // Define available status filters |
| 356 | 395 | $status_filters = array( |
| 357 | 396 | 'completed' => 'Completed', |
| @@ -394,11 +433,19 @@ | ||
| 394 | 433 | // Check if scripts are already enqueued |
| 395 | 434 | if (wp_script_is('easy-invoice-payment', 'enqueued')) { |
| 396 | 435 | return; |
| 397 | 436 | } |
| 398 | - if(!is_singular(PostTypes::EASY_INVOICE_POST_TYPE)){ | |
| 399 | - //return; | |
| 400 | - } | |
| 437 | + // The payment panel exists on the public invoice page only; every | |
| 438 | + // other front-end page of the site has no use for the script (or the | |
| 439 | + // jQuery it pulls in). | |
| 440 | + /** | |
| 441 | + * Filter whether the payment script loads on the current front-end request. | |
| 442 | + * | |
| 443 | + * @param bool $load Default: on a public invoice page. | |
| 444 | + */ | |
| 445 | + if (!apply_filters('easy_invoice_load_payment_assets', is_singular(PostTypes::EASY_INVOICE_POST_TYPE))) { | |
| 446 | + return; | |
| 447 | + } | |
| 401 | 448 | |
| 402 | 449 | // Enqueue our custom scripts |
| 403 | 450 | wp_enqueue_script( |
| 404 | 451 | 'easy-invoice-payment', |
| @@ -414,11 +461,22 @@ | ||
| 414 | 461 | $currency_code = $settings['easy_invoice_currency_code'] ?? 'USD'; |
| 415 | 462 | $currency_symbol = \EasyInvoice\Helpers\CurrencyHelper::getCurrencySymbol($currency_code); |
| 416 | 463 | |
| 417 | 464 | // Localize script variables for payment form |
| 465 | + // Forward the per-invoice access token (?ik=...) the same way the manual | |
| 466 | + // payment script already does. The payment endpoints authorise on it, and | |
| 467 | + // without this an anonymous client following an emailed link would have a | |
| 468 | + // token in their URL that never reached the AJAX request. | |
| 469 | + $ei_access_token = isset($_GET['ik']) | |
| 470 | + ? sanitize_text_field(wp_unslash($_GET['ik'])) | |
| 471 | + : ''; | |
| 472 | + /** This filter is documented in includes/Controllers/InvoiceController.php */ | |
| 473 | + $ei_access_token = (string) apply_filters('easy_invoice_presented_access_token', $ei_access_token, 'invoice'); | |
| 474 | + | |
| 418 | 475 | wp_localize_script('easy-invoice-payment', 'easy_invoice_vars', [ |
| 419 | 476 | 'ajax_url' => admin_url('admin-ajax.php'), |
| 420 | 477 | 'nonce' => wp_create_nonce('easy_invoice_payment'), |
| 478 | + 'access_token' => $ei_access_token, | |
| 421 | 479 | 'currency_symbol' => $currency_symbol, |
| 422 | 480 | 'currency_code' => $currency_code |
| 423 | 481 | ]); |
| 424 | 482 | } |
| @@ -433,8 +491,40 @@ | ||
| 433 | 491 | |
| 434 | 492 | $invoice_id = isset($_POST['invoice_id']) ? intval($_POST['invoice_id']) : 0; |
| 435 | 493 | $payment_method_slug = isset($_POST['payment_method']) ? sanitize_text_field($_POST['payment_method']) : ''; |
| 436 | 494 | |
| 495 | + $invoice_post = $invoice_id ? get_post($invoice_id) : null; | |
| 496 | + if (!$invoice_post || $invoice_post->post_type !== \EasyInvoice\Constants\PostTypes::EASY_INVOICE_POST_TYPE) { | |
| 497 | + wp_send_json_error(['message' => __('Invalid invoice.', 'easy-invoice')]); | |
| 498 | + return; | |
| 499 | + } | |
| 500 | + | |
| 501 | + $invoice = new \EasyInvoice\Models\Invoice($invoice_post); | |
| 502 | + | |
| 503 | + // Authorisation. This endpoint is nopriv and previously relied on a shared, | |
| 504 | + // page-wide nonce alone, so a caller holding one could start a payment | |
| 505 | + // against any invoice id and read back its amount and gateway details. | |
| 506 | + // Legitimate callers reach this from the invoice page, which forwards the | |
| 507 | + // per-invoice access token (see payment.js / payment-section.php). | |
| 508 | + // | |
| 509 | + // This MUST stay above the `easy_invoice_before_process_payment` filter | |
| 510 | + // below. That filter is not a notification — it is a dispatch point that | |
| 511 | + // short-circuits the whole request, and Easy Invoice Pro attaches four | |
| 512 | + // handlers to it (Stripe, Authorize.Net, Moneris and Partial Payments). | |
| 513 | + // While the check sat after the filter, those four gateways — every card | |
| 514 | + // gateway Pro ships — completed payments without the token ever being | |
| 515 | + // examined, so the gate only really covered the free plugin's own | |
| 516 | + // gateways. Authorising before dispatch is the whole point of the gate. | |
| 517 | + if (!\EasyInvoice\Controllers\InvoiceController::canSubmitPaymentForInvoice($invoice_id, $invoice)) { | |
| 518 | + // A Pro build older than this plugin cannot forward the token — see | |
| 519 | + // legacyProPaymentFallbackAllowed(). Refusing here would take the | |
| 520 | + // customer's money on Stripe without recording the payment. | |
| 521 | + if (!$this->legacyProPaymentFallbackAllowed($payment_method_slug)) { | |
| 522 | + wp_send_json_error(['message' => __('Invalid invoice.', 'easy-invoice')]); | |
| 523 | + return; | |
| 524 | + } | |
| 525 | + } | |
| 526 | + | |
| 437 | 527 | // Add filter for extensions to handle custom payment logic (e.g., partial payments) |
| 438 | 528 | $custom_result = apply_filters('easy_invoice_before_process_payment', null, $invoice_id, $_POST); |
| 439 | 529 | |
| 440 | 530 | if (is_array($custom_result) && isset($custom_result['handled']) && $custom_result['handled']) { |
| @@ -445,24 +535,39 @@ | ||
| 445 | 535 | } |
| 446 | 536 | return; |
| 447 | 537 | } |
| 448 | 538 | |
| 449 | - if (!$invoice_id || !$payment_method_slug) { | |
| 539 | + if (!$payment_method_slug) { | |
| 450 | 540 | wp_send_json_error(['message' => __('Missing required fields.', 'easy-invoice')]); |
| 451 | 541 | return; |
| 452 | 542 | } |
| 453 | 543 | |
| 454 | - $invoice_post = get_post($invoice_id); | |
| 455 | - if (!$invoice_post || $invoice_post->post_type !== \EasyInvoice\Constants\PostTypes::EASY_INVOICE_POST_TYPE) { | |
| 456 | - wp_send_json_error(['message' => __('Invalid invoice.', 'easy-invoice')]); | |
| 544 | + // Charge what is owed, not the face value: a part-paid or partly | |
| 545 | + // credited invoice must not be collected twice. | |
| 546 | + $due = \EasyInvoice\Services\InvoiceBalance::due($invoice); | |
| 547 | + $amount = $due; | |
| 548 | + if ($due <= 0) { | |
| 549 | + wp_send_json_error(['message' => __('Nothing is owed on this invoice.', 'easy-invoice')]); | |
| 457 | 550 | return; |
| 458 | 551 | } |
| 459 | 552 | |
| 460 | - $invoice = new \EasyInvoice\Models\Invoice($invoice_post); | |
| 461 | - $amount = $invoice->total ?? 0; | |
| 553 | + // A smaller amount is charged only when something (the Partial | |
| 554 | + // Payments addon) says this invoice may be paid in instalments. | |
| 555 | + $requested = isset($_POST['payment_amount']) ? round((float) str_replace(',', '', sanitize_text_field(wp_unslash($_POST['payment_amount']))), 2) : 0.0; | |
| 556 | + $is_partial = isset($_POST['is_partial_payment']) && '1' === (string) sanitize_text_field(wp_unslash($_POST['is_partial_payment'])); | |
| 557 | + if ($is_partial && $requested > 0 && $requested < $due) { | |
| 558 | + /** | |
| 559 | + * Filter whether the client may pay less than the amount due. | |
| 560 | + * | |
| 561 | + * @param bool $allow Default false. | |
| 562 | + * @param object $invoice Invoice model. | |
| 563 | + * @param float $requested Amount the client asked to pay. | |
| 564 | + */ | |
| 565 | + if (apply_filters('easy_invoice_allow_partial_payment_amount', false, $invoice, $requested)) { | |
| 566 | + $amount = $requested; | |
| 567 | + } | |
| 568 | + } | |
| 462 | 569 | |
| 463 | - // Log the payment processing details | |
| 464 | - | |
| 465 | 570 | $gateway_instance = $this->gatewayManager->getGateway($payment_method_slug); |
| 466 | 571 | |
| 467 | 572 | if (!$gateway_instance || !$gateway_instance->isEnabled() || !$gateway_instance->isAvailable()) { |
| 468 | 573 | wp_send_json_error(['message' => __('Selected payment gateway is not available or configured correctly.', 'easy-invoice')]); |
| @@ -473,8 +578,16 @@ | ||
| 473 | 578 | // Pass the entire $_POST array to the gateway |
| 474 | 579 | $result = $gateway_instance->processPayment($amount, $_POST); |
| 475 | 580 | |
| 476 | 581 | if (isset($result['success']) && $result['success']) { |
| 582 | + // An offline gateway with no follow-up step (cash, the free | |
| 583 | + // manual gateway) leaves the invoice pending here; bank | |
| 584 | + // transfer and cheque notify the admin themselves once the | |
| 585 | + // proof or cheque details arrive. | |
| 586 | + $offline_status = (string) ($result['payment_status'] ?? ($result['data']['status'] ?? '')); | |
| 587 | + if (in_array($payment_method_slug, ['manual', 'cash'], true) && 0 === strpos($offline_status, 'pending')) { | |
| 588 | + do_action('easy_invoice_manual_payment_submitted', $invoice_id, $payment_method_slug); | |
| 589 | + } | |
| 477 | 590 | wp_send_json_success($result); |
| 478 | 591 | } else { |
| 479 | 592 | wp_send_json_error(['message' => $result['message'] ?? __('Payment processing failed with the gateway.', 'easy-invoice')]); |
| 480 | 593 | } |
| @@ -485,8 +598,97 @@ | ||
| 485 | 598 | } |
| 486 | 599 | } |
| 487 | 600 | |
| 488 | 601 | /** |
| 602 | + * Whether to accept a payment that presented no per-invoice access token, | |
| 603 | + * because the Easy Invoice Pro build installed alongside cannot send one. | |
| 604 | + * | |
| 605 | + * Why this exists | |
| 606 | + * --------------- | |
| 607 | + * Pro's Stripe and Authorize.Net scripts post to `easy_invoice_process_payment`, | |
| 608 | + * which is a free-plugin endpoint, and from 2.4.0 that endpoint authorises on the | |
| 609 | + * per-invoice access token. Pro only began forwarding the token in 2.3.0. | |
| 610 | + * | |
| 611 | + * The two plugins update through different channels — free auto-updates from | |
| 612 | + * WordPress.org, Pro arrives from the licence server — so "free is newer than Pro" | |
| 613 | + * is not an edge case, it is the normal state for a while after release. Without | |
| 614 | + * this fallback, that pairing breaks client payments, and for Stripe it breaks them | |
| 615 | + * in the worst possible way: the script confirms the charge with Stripe FIRST and | |
| 616 | + * only then posts here to record it, so a refusal means the customer has paid and | |
| 617 | + * the invoice still says unpaid. | |
| 618 | + * | |
| 619 | + * What it does and does not allow | |
| 620 | + * ------------------------------- | |
| 621 | + * The relaxation is deliberately narrow, and is never wider than the behaviour | |
| 622 | + * that already shipped in 2.3.8: | |
| 623 | + * | |
| 624 | + * - Only when Pro is active AND older than 2.3.0. It disappears by itself the | |
| 625 | + * moment Pro is updated; there is nothing to remember to turn off. | |
| 626 | + * - Only when NO token was presented at all. A request carrying a wrong or | |
| 627 | + * expired token is a forgery attempt, not an old client script, and is refused. | |
| 628 | + * - Only for gateways provided by Pro. The free plugin's own scripts always | |
| 629 | + * forward the token, so a free gateway reaching here without one is not a | |
| 630 | + * version-skew case. | |
| 631 | + * - The shared `easy_invoice_payment` nonce has already been verified by the | |
| 632 | + * caller before this is consulted. | |
| 633 | + * - `getPaymentInstructions()` does NOT use this. That is the information | |
| 634 | + * disclosure path and stays fully gated regardless of Pro's version. | |
| 635 | + * | |
| 636 | + * Site owners who would rather fail the payment than accept the older | |
| 637 | + * authorisation can return false from | |
| 638 | + * `easy_invoice_allow_legacy_pro_payment_fallback`. | |
| 639 | + * | |
| 640 | + * @param string $payment_method_slug Gateway slug from the request. | |
| 641 | + * @return bool | |
| 642 | + */ | |
| 643 | + private function legacyProPaymentFallbackAllowed(string $payment_method_slug): bool { | |
| 644 | + if (!function_exists('easy_invoice_has_pro') || !easy_invoice_has_pro()) { | |
| 645 | + return false; | |
| 646 | + } | |
| 647 | + | |
| 648 | + // An older Pro that predates token forwarding. Treat a missing version | |
| 649 | + // constant as "older", since every build that defines it is >= 2.1. | |
| 650 | + $pro_version = defined('EASY_INVOICE_PRO_VERSION') ? (string) EASY_INVOICE_PRO_VERSION : '0'; | |
| 651 | + if (version_compare($pro_version, self::PRO_TOKEN_FORWARDING_VERSION, '>=')) { | |
| 652 | + return false; | |
| 653 | + } | |
| 654 | + | |
| 655 | + // A presented-but-invalid token is an attack, not version skew. | |
| 656 | + if (isset($_POST['access_token']) && $_POST['access_token'] !== '') { | |
| 657 | + return false; | |
| 658 | + } | |
| 659 | + if (isset($_GET['ik']) && $_GET['ik'] !== '') { | |
| 660 | + return false; | |
| 661 | + } | |
| 662 | + | |
| 663 | + // Restrict to gateways Pro actually provides. | |
| 664 | + $gateway_instance = $this->gatewayManager->getGateway($payment_method_slug); | |
| 665 | + if (!$gateway_instance || strpos(get_class($gateway_instance), 'EasyInvoicePro\\') !== 0) { | |
| 666 | + return false; | |
| 667 | + } | |
| 668 | + | |
| 669 | + /** | |
| 670 | + * Filter the legacy Pro payment fallback. | |
| 671 | + * | |
| 672 | + * @param bool $allowed Whether to accept the payment. | |
| 673 | + * @param string $pro_version Version of Easy Invoice Pro detected. | |
| 674 | + * @param string $payment_method_slug Gateway slug from the request. | |
| 675 | + */ | |
| 676 | + $allowed = (bool) apply_filters( | |
| 677 | + 'easy_invoice_allow_legacy_pro_payment_fallback', | |
| 678 | + true, | |
| 679 | + $pro_version, | |
| 680 | + $payment_method_slug | |
| 681 | + ); | |
| 682 | + | |
| 683 | + if ($allowed) { | |
| 684 | + update_option('easy_invoice_legacy_pro_payment_seen', $pro_version, false); | |
| 685 | + } | |
| 686 | + | |
| 687 | + return $allowed; | |
| 688 | + } | |
| 689 | + | |
| 690 | + /** | |
| 489 | 691 | * Handle payment callback/webhook |
| 490 | 692 | */ |
| 491 | 693 | public function handleCallback(): void { |
| 492 | 694 | check_ajax_referer('easy_invoice_payment', 'payment_nonce'); |
| @@ -497,8 +699,34 @@ | ||
| 497 | 699 | if (!$invoice_id || !$gateway) { |
| 498 | 700 | wp_send_json_error(['message' => __('Invalid request', 'easy-invoice')]); |
| 499 | 701 | } |
| 500 | 702 | |
| 703 | + // Authorisation. | |
| 704 | + // | |
| 705 | + // This endpoint is registered nopriv and the only thing standing in front of | |
| 706 | + // it was the shared, page-wide `easy_invoice_payment` nonce, which is rendered | |
| 707 | + // on every public invoice page — so anyone able to view a single invoice could | |
| 708 | + // lift one and then call this for any id they liked. The id was passed straight | |
| 709 | + // to the gateway without even confirming it was an invoice. | |
| 710 | + // | |
| 711 | + // That mattered because the cheque gateway's callback writes: it stores the | |
| 712 | + // cheque number, bank name, date and an uploaded image against whatever id it | |
| 713 | + // is handed. An unauthenticated caller could therefore attach forged cheque | |
| 714 | + // details, and a file, to any invoice on the site — or to any post at all. | |
| 715 | + // | |
| 716 | + // Same rule as everywhere else: valid per-invoice access key, administrator, or | |
| 717 | + // the signed-in client the invoice belongs to. | |
| 718 | + $invoice_post = get_post($invoice_id); | |
| 719 | + if (!$invoice_post || $invoice_post->post_type !== \EasyInvoice\Constants\PostTypes::EASY_INVOICE_POST_TYPE) { | |
| 720 | + wp_send_json_error(['message' => __('Invalid invoice.', 'easy-invoice')]); | |
| 721 | + } | |
| 722 | + | |
| 723 | + $invoice = new \EasyInvoice\Models\Invoice($invoice_post); | |
| 724 | + if (!\EasyInvoice\Controllers\InvoiceController::canSubmitPaymentForInvoice($invoice_id, $invoice) | |
| 725 | + && !$this->legacyProPaymentFallbackAllowed($gateway)) { | |
| 726 | + wp_send_json_error(['message' => __('Invalid invoice.', 'easy-invoice')]); | |
| 727 | + } | |
| 728 | + | |
| 501 | 729 | $gateway_instance = $this->gatewayManager->getGateway($gateway); |
| 502 | 730 | if (!$gateway_instance) { |
| 503 | 731 | wp_send_json_error(['message' => __('Invalid payment gateway', 'easy-invoice')]); |
| 504 | 732 | } |
| @@ -504,10 +732,14 @@ | ||
| 504 | 732 | } |
| 505 | 733 | |
| 506 | 734 | $result = $gateway_instance->handleCallback($_POST); |
| 507 | 735 | |
| 508 | - // Send admin notification for manual payments | |
| 509 | - if ($result['success'] && in_array($gateway, ['bank', 'cheque'])) { | |
| 736 | + // Tell the admin an offline payment is waiting for verification. Pro's | |
| 737 | + // bank-transfer and cheque gateways email the admin themselves from | |
| 738 | + // handleCallback(); the free manual gateway and Pro's cash gateway do | |
| 739 | + // not. (This used to test for 'bank' and 'cheque' — ids no gateway | |
| 740 | + // has — so it never fired.) | |
| 741 | + if ($result['success'] && in_array($gateway, ['manual', 'cash'], true)) { | |
| 510 | 742 | do_action('easy_invoice_manual_payment_submitted', $invoice_id, $gateway); |
| 511 | 743 | } |
| 512 | 744 | |
| 513 | 745 | if ($result['success']) { |
| @@ -531,9 +763,13 @@ | ||
| 531 | 763 | |
| 532 | 764 | $invoice = new \EasyInvoice\Models\Invoice($post); |
| 533 | 765 | $invoice_status = $invoice->getStatus(); |
| 534 | 766 | |
| 535 | - if (!in_array($invoice_status, [ 'unpaid', 'available'])) { | |
| 767 | + // Anything that still has a balance can be paid: an overdue invoice is the | |
| 768 | + // one a client most needs to settle, and a partially paid one still owes. | |
| 769 | + // Drafts, paid, cancelled and "awaiting verification" stay closed. | |
| 770 | + $payable_statuses = apply_filters('easy_invoice_payable_statuses', [ 'unpaid', 'available', 'overdue', 'partial', 'sent', 'pending' ]); | |
| 771 | + if (!in_array($invoice_status, $payable_statuses, true)) { | |
| 536 | 772 | return []; |
| 537 | 773 | } |
| 538 | 774 | |
| 539 | 775 | $enabled_gateways = $this->gatewayManager->getEnabledGateways(); |
| @@ -588,13 +824,27 @@ | ||
| 588 | 824 | */ |
| 589 | 825 | public function updatePayment() { |
| 590 | 826 | check_ajax_referer('easy_invoice_payment', 'payment_nonce'); |
| 591 | 827 | |
| 828 | + // Authorisation: this handler mutates payment-record fields | |
| 829 | + // (amount, method, status, notes) and on status=completed it | |
| 830 | + // can flip the linked invoice to paid via | |
| 831 | + // updateInvoiceStatusIfPaid(). The shared `easy_invoice_payment` | |
| 832 | + // nonce is rendered on every public invoice page so any | |
| 833 | + // authenticated visitor can obtain a valid one — the nonce is | |
| 834 | + // CSRF defense, NOT authorisation. Gate on the same payment- | |
| 835 | + // management capability as the sibling verifyManualPayment / | |
| 836 | + // rejectManualPayment / mark_invoice_paid_ajax handlers. | |
| 837 | + if (!easy_invoice_user_can('ei_record_payment')) { | |
| 838 | + wp_send_json_error(['message' => __('You do not have permission to update payments.', 'easy-invoice')]); | |
| 839 | + return; | |
| 840 | + } | |
| 841 | + | |
| 592 | 842 | $payment_id = isset($_POST['payment_id']) ? intval($_POST['payment_id']) : 0; |
| 593 | 843 | $invoice_id = isset($_POST['invoice_id']) ? intval($_POST['invoice_id']) : 0; |
| 594 | 844 | $amount = isset($_POST['amount']) ? floatval($_POST['amount']) : 0; |
| 595 | 845 | $payment_method = isset($_POST['payment_method']) ? sanitize_text_field($_POST['payment_method']) : ''; |
| 596 | - $payment_date = isset($_POST['payment_date']) ? sanitize_text_field($_POST['payment_date']) : date('Y-m-d'); | |
| 846 | + $payment_date = isset($_POST['payment_date']) ? sanitize_text_field($_POST['payment_date']) : current_time('Y-m-d'); | |
| 597 | 847 | $status = isset($_POST['status']) ? sanitize_text_field($_POST['status']) : 'pending'; |
| 598 | 848 | $notes = isset($_POST['notes']) ? sanitize_textarea_field($_POST['notes']) : ''; |
| 599 | 849 | |
| 600 | 850 | if (!$payment_id || !$invoice_id || !$amount || !$payment_method) { |
| @@ -650,13 +900,13 @@ | ||
| 650 | 900 | $total_payments = $this->calculateTotalPaymentsForInvoice($invoice_id); |
| 651 | 901 | $invoice_total = $invoice->getTotal(); |
| 652 | 902 | |
| 653 | 903 | if ($total_payments < $invoice_total) { |
| 654 | - // Not enough payments anymore, revert invoice to draft/pending | |
| 655 | - $invoice->setStatus('draft'); | |
| 904 | + // Not enough payments any more: part paid if anything | |
| 905 | + // remains, otherwise back to awaiting payment. An issued | |
| 906 | + // invoice never returns to draft. | |
| 907 | + $invoice->setStatus($total_payments > 0 ? 'partial' : 'available'); | |
| 656 | 908 | $invoice->save(); |
| 657 | - | |
| 658 | - error_log("Easy Invoice: Invoice #$invoice_id status reverted to 'draft' - payment marked as $status"); | |
| 659 | 909 | } else { |
| 660 | 910 | // Still enough payments from other completed payments |
| 661 | 911 | $this->updateInvoiceStatusIfPaid($invoice_id, $invoice, 'manual'); |
| 662 | 912 | } |
| @@ -677,9 +927,9 @@ | ||
| 677 | 927 | * Verify manual payment |
| 678 | 928 | */ |
| 679 | 929 | public function verifyManualPayment(): void { |
| 680 | 930 | // Check permissions |
| 681 | - if (!current_user_can('manage_options')) { | |
| 931 | + if (!easy_invoice_user_can('ei_record_payment')) { | |
| 682 | 932 | wp_send_json_error(['message' => __('You do not have permission to perform this action', 'easy-invoice')]); |
| 683 | 933 | return; |
| 684 | 934 | } |
| 685 | 935 | |
| @@ -760,10 +1010,11 @@ | ||
| 760 | 1010 | /** |
| 761 | 1011 | * Reject manual payment |
| 762 | 1012 | */ |
| 763 | 1013 | public function rejectManualPayment(): void { |
| 764 | - // Check permissions | |
| 765 | - if (!current_user_can('manage_options')) { | |
| 1014 | + // Check permissions — rejecting a manual payment is a record-payment | |
| 1015 | + // operation (it transitions state, doesn't refund money). | |
| 1016 | + if (!easy_invoice_user_can('ei_record_payment')) { | |
| 766 | 1017 | wp_send_json_error(['message' => __('You do not have permission to perform this action', 'easy-invoice')]); |
| 767 | 1018 | return; |
| 768 | 1019 | } |
| 769 | 1020 | |
| @@ -817,12 +1068,14 @@ | ||
| 817 | 1068 | if (!$invoice || !$invoice->getId()) { |
| 818 | 1069 | return; |
| 819 | 1070 | } |
| 820 | 1071 | |
| 821 | - // Use EmailManager to send payment confirmation | |
| 1072 | + // Use EmailManager to send payment confirmation using proper template system | |
| 1073 | + // This will check if payment email is enabled in settings | |
| 822 | 1074 | $email_manager = \EasyInvoice\Services\EmailManager::getInstance(); |
| 823 | - $email_manager->sendPaymentConfirmationEmail($invoice, [ | |
| 824 | - 'payment_id' => $payment_id | |
| 1075 | + $email_manager->sendInvoiceEmail($invoice, 'paid', [ | |
| 1076 | + 'payment_id' => $payment_id, | |
| 1077 | + 'skip_bcc' => true // Skip BCC to admin since this is a direct call | |
| 825 | 1078 | ]); |
| 826 | 1079 | } |
| 827 | 1080 | |
| 828 | 1081 | /** |
| @@ -842,58 +1095,12 @@ | ||
| 842 | 1095 | $email_manager = \EasyInvoice\Services\EmailManager::getInstance(); |
| 843 | 1096 | $email_manager->sendPaymentRejectionEmail($invoice, $reason); |
| 844 | 1097 | } |
| 845 | 1098 | |
| 846 | - /** | |
| 847 | - * Add pending payment statuses to admin filters | |
| 848 | - * | |
| 849 | - * @param array $statuses | |
| 850 | - * @return array | |
| 851 | - */ | |
| 852 | - public function addPendingPaymentStatuses($statuses): array { | |
| 853 | - $statuses['pending-bank'] = __('Pending Bank Transfer', 'easy-invoice'); | |
| 854 | - $statuses['pending-cheque'] = __('Pending Cheque', 'easy-invoice'); | |
| 855 | - return $statuses; | |
| 856 | - } | |
| 857 | 1099 | |
| 858 | - /** | |
| 859 | - * Add payment method column to payments list | |
| 860 | - * | |
| 861 | - * @param array $columns | |
| 862 | - * @return array | |
| 863 | - */ | |
| 864 | - public function addPaymentMethodColumn($columns): array { | |
| 865 | - $new_columns = []; | |
| 866 | 1100 | |
| 867 | - foreach ($columns as $key => $value) { | |
| 868 | - $new_columns[$key] = $value; | |
| 869 | 1101 | |
| 870 | - if ($key === 'title') { | |
| 871 | - $new_columns['payment_method'] = __('Payment Method', 'easy-invoice'); | |
| 872 | - } | |
| 873 | - } | |
| 874 | - | |
| 875 | - return $new_columns; | |
| 876 | - } | |
| 877 | - | |
| 878 | 1102 | /** |
| 879 | - * Render payment method column | |
| 880 | - * | |
| 881 | - * @param string $column | |
| 882 | - * @param int $post_id | |
| 883 | - */ | |
| 884 | - public function renderPaymentMethodColumn($column, $post_id): void { | |
| 885 | - if ($column === 'payment_method') { | |
| 886 | - $payment_method = get_post_meta($post_id, '_payment_method', true); | |
| 887 | - $payment_methods = [ | |
| 888 | - 'paypal' => __('PayPal', 'easy-invoice') | |
| 889 | - ]; | |
| 890 | - | |
| 891 | - echo isset($payment_methods[$payment_method]) ? esc_html($payment_methods[$payment_method]) : esc_html($payment_method); | |
| 892 | - } | |
| 893 | - } | |
| 894 | - | |
| 895 | - /** | |
| 896 | 1103 | * Send payment reminders for pending manual payments |
| 897 | 1104 | */ |
| 898 | 1105 | public function sendPaymentReminders(): void { |
| 899 | 1106 | // Get invoices with pending manual payments |
| @@ -944,8 +1151,184 @@ | ||
| 944 | 1151 | } |
| 945 | 1152 | } |
| 946 | 1153 | |
| 947 | 1154 | /** |
| 1155 | + * Submit manual payment | |
| 1156 | + */ | |
| 1157 | + public function submitManualPayment(): void { | |
| 1158 | + // CSRF defense — keep the existing nonce check. The nonce is | |
| 1159 | + // global (`easy_invoice_payment`) so any public invoice page leaks | |
| 1160 | + // a valid value; the REAL authorisation gate is the ownership | |
| 1161 | + // check below. | |
| 1162 | + if (!wp_verify_nonce($_POST['nonce'] ?? '', 'easy_invoice_payment')) { | |
| 1163 | + wp_send_json_error(['message' => __('Security check failed', 'easy-invoice')]); | |
| 1164 | + return; | |
| 1165 | + } | |
| 1166 | + | |
| 1167 | + $invoice_id = isset($_POST['invoice_id']) ? intval($_POST['invoice_id']) : 0; | |
| 1168 | + $payment_type = isset($_POST['payment_type']) ? sanitize_text_field($_POST['payment_type']) : ''; | |
| 1169 | + $payment_notes = isset($_POST['payment_notes']) ? sanitize_textarea_field($_POST['payment_notes']) : ''; | |
| 1170 | + | |
| 1171 | + if (!$invoice_id || !$payment_type) { | |
| 1172 | + wp_send_json_error(['message' => __('Missing required fields', 'easy-invoice')]); | |
| 1173 | + return; | |
| 1174 | + } | |
| 1175 | + | |
| 1176 | + // Get invoice | |
| 1177 | + $invoice_post = get_post($invoice_id); | |
| 1178 | + if (!$invoice_post || $invoice_post->post_type !== \EasyInvoice\Constants\PostTypes::EASY_INVOICE_POST_TYPE) { | |
| 1179 | + wp_send_json_error(['message' => __('Invalid invoice', 'easy-invoice')]); | |
| 1180 | + return; | |
| 1181 | + } | |
| 1182 | + | |
| 1183 | + $invoice = new \EasyInvoice\Models\Invoice($invoice_post); | |
| 1184 | + | |
| 1185 | + // Authorisation: reject unless the caller is the legitimate email | |
| 1186 | + // recipient (per-invoice access token), an admin, or the | |
| 1187 | + // logged-in client bound to this invoice. Without this gate the | |
| 1188 | + // public AJAX endpoint allowed any visitor with a harvested | |
| 1189 | + // global nonce to flood arbitrary invoices into | |
| 1190 | + // `pending_verification` and attach payment-proof uploads. | |
| 1191 | + if (!\EasyInvoice\Controllers\InvoiceController::canSubmitPaymentForInvoice($invoice_id, $invoice)) { | |
| 1192 | + wp_send_json_error([ | |
| 1193 | + 'message' => __('You do not have permission to submit a payment for this invoice.', 'easy-invoice'), | |
| 1194 | + ]); | |
| 1195 | + return; | |
| 1196 | + } | |
| 1197 | + $currency_code = $invoice->getCurrencyCode() ?: 'USD'; | |
| 1198 | + if ($currency_code === 'global') { | |
| 1199 | + $currency_code = get_option('easy_invoice_currency_code', 'USD'); | |
| 1200 | + } | |
| 1201 | + $currency_symbol = \EasyInvoice\Helpers\CurrencyHelper::getCurrencySymbol($currency_code); | |
| 1202 | + | |
| 1203 | + // Handle file upload (never trust client MIME or filename extension — use WordPress filetype APIs) | |
| 1204 | + $proof_url = ''; | |
| 1205 | + if (isset($_FILES['payment_proof']) && $_FILES['payment_proof']['error'] === UPLOAD_ERR_OK) { | |
| 1206 | + $file = $_FILES['payment_proof']; | |
| 1207 | + | |
| 1208 | + if (empty($file['tmp_name']) || !is_uploaded_file($file['tmp_name'])) { | |
| 1209 | + wp_send_json_error(['message' => __('Invalid upload.', 'easy-invoice')]); | |
| 1210 | + return; | |
| 1211 | + } | |
| 1212 | + | |
| 1213 | + $max_size = 5 * 1024 * 1024; // 5MB | |
| 1214 | + if ($file['size'] > $max_size) { | |
| 1215 | + wp_send_json_error(['message' => __('File size must be less than 5MB.', 'easy-invoice')]); | |
| 1216 | + return; | |
| 1217 | + } | |
| 1218 | + | |
| 1219 | + $allowed_mimes = [ | |
| 1220 | + 'jpg|jpeg|jpe' => 'image/jpeg', | |
| 1221 | + 'png' => 'image/png', | |
| 1222 | + 'gif' => 'image/gif', | |
| 1223 | + 'pdf' => 'application/pdf', | |
| 1224 | + ]; | |
| 1225 | + | |
| 1226 | + $checked = wp_check_filetype_and_ext($file['tmp_name'], $file['name'], $allowed_mimes); | |
| 1227 | + if (empty($checked['ext']) || empty($checked['type'])) { | |
| 1228 | + wp_send_json_error(['message' => __('Invalid file type. Only JPG, PNG, GIF, and PDF files are allowed.', 'easy-invoice')]); | |
| 1229 | + return; | |
| 1230 | + } | |
| 1231 | + | |
| 1232 | + $allowed_types = array_values($allowed_mimes); | |
| 1233 | + if (!in_array($checked['type'], $allowed_types, true)) { | |
| 1234 | + wp_send_json_error(['message' => __('Invalid file type. Only JPG, PNG, GIF, and PDF files are allowed.', 'easy-invoice')]); | |
| 1235 | + return; | |
| 1236 | + } | |
| 1237 | + | |
| 1238 | + $upload_dir = wp_upload_dir(); | |
| 1239 | + $proof_dir = $upload_dir['basedir'] . '/easy-invoice/payment-proofs/'; | |
| 1240 | + | |
| 1241 | + if (!wp_mkdir_p($proof_dir)) { | |
| 1242 | + wp_send_json_error(['message' => __('Could not create upload directory.', 'easy-invoice')]); | |
| 1243 | + return; | |
| 1244 | + } | |
| 1245 | + | |
| 1246 | + // Hand the move to WordPress rather than move_uploaded_file(): it | |
| 1247 | + // applies the site's filesystem method and permissions, and lets | |
| 1248 | + // the usual upload filters see the file. The directory is pointed | |
| 1249 | + // at our proofs folder for the duration of this one call. | |
| 1250 | + // Random, not time-based: a receipt carries bank details and the URL | |
| 1251 | + // is public, so the name must not be guessable. | |
| 1252 | + $filename = 'payment_proof_' . wp_generate_password(24, false, false) . '.' . $checked['ext']; | |
| 1253 | + $proof_url = $upload_dir['baseurl'] . '/easy-invoice/payment-proofs/'; | |
| 1254 | + $to_proofs = static function ($dirs) use ($proof_dir, $proof_url) { | |
| 1255 | + $dirs['path'] = untrailingslashit($proof_dir); | |
| 1256 | + $dirs['url'] = untrailingslashit($proof_url); | |
| 1257 | + $dirs['subdir'] = '/easy-invoice/payment-proofs'; | |
| 1258 | + return $dirs; | |
| 1259 | + }; | |
| 1260 | + if (!function_exists('wp_handle_upload')) { | |
| 1261 | + require_once ABSPATH . 'wp-admin/includes/file.php'; | |
| 1262 | + } | |
| 1263 | + add_filter('upload_dir', $to_proofs); | |
| 1264 | + \EasyInvoice\Helpers\UploadGuard::protectDirectory((wp_upload_dir())['basedir'] . '/easy-invoice/payment-proofs'); | |
| 1265 | + $moved = wp_handle_upload($file, [ | |
| 1266 | + 'test_form' => false, | |
| 1267 | + 'mimes' => $allowed_mimes, | |
| 1268 | + 'unique_filename_callback' => static function () use ($filename) { | |
| 1269 | + return $filename; | |
| 1270 | + }, | |
| 1271 | + ]); | |
| 1272 | + remove_filter('upload_dir', $to_proofs); | |
| 1273 | + | |
| 1274 | + if (!is_array($moved) || !empty($moved['error']) || empty($moved['url'])) { | |
| 1275 | + wp_send_json_error(['message' => __('Failed to save payment proof file.', 'easy-invoice')]); | |
| 1276 | + return; | |
| 1277 | + } | |
| 1278 | + $proof_url = $moved['url']; | |
| 1279 | + } | |
| 1280 | + | |
| 1281 | + // Create payment record | |
| 1282 | + $payment_data = [ | |
| 1283 | + 'post_title' => sprintf('Manual Payment (%s) for Invoice #%s', ucfirst($payment_type), $invoice->getNumber()), | |
| 1284 | + 'post_type' => 'easy_invoice_payment', | |
| 1285 | + 'post_status' => 'publish', | |
| 1286 | + 'post_author' => get_current_user_id(), | |
| 1287 | + ]; | |
| 1288 | + | |
| 1289 | + $payment_id = wp_insert_post($payment_data); | |
| 1290 | + | |
| 1291 | + if (is_wp_error($payment_id)) { | |
| 1292 | + wp_send_json_error(['message' => __('Failed to create payment record', 'easy-invoice')]); | |
| 1293 | + return; | |
| 1294 | + } | |
| 1295 | + | |
| 1296 | + // Save payment metadata | |
| 1297 | + update_post_meta($payment_id, '_invoice_id', $invoice_id); | |
| 1298 | + update_post_meta($payment_id, '_amount', $invoice->getTotal()); | |
| 1299 | + update_post_meta($payment_id, '_payment_method', 'manual'); | |
| 1300 | + update_post_meta($payment_id, '_payment_type', $payment_type); | |
| 1301 | + update_post_meta($payment_id, '_status', 'pending'); | |
| 1302 | + update_post_meta($payment_id, '_transaction_id', 'MANUAL-' . $invoice_id . '-' . time()); | |
| 1303 | + update_post_meta($payment_id, '_payment_date', current_time('mysql')); | |
| 1304 | + update_post_meta($payment_id, '_notes', $payment_notes); | |
| 1305 | + update_post_meta($payment_id, '_currency', $currency_code); | |
| 1306 | + update_post_meta($payment_id, '_currency_symbol', $currency_symbol); | |
| 1307 | + update_post_meta($payment_id, '_payment_proof', $proof_url); | |
| 1308 | + | |
| 1309 | + // Update invoice status to pending verification | |
| 1310 | + $invoice->setStatus('pending_verification'); | |
| 1311 | + $invoice->save(); | |
| 1312 | + | |
| 1313 | + // Store payment details on invoice | |
| 1314 | + $invoice->setMeta('_payment_method', 'manual'); | |
| 1315 | + $invoice->setMeta('_payment_type', $payment_type); | |
| 1316 | + $invoice->setMeta('_payment_status', 'pending'); | |
| 1317 | + $invoice->setMeta('_manual_payment_id', $payment_id); | |
| 1318 | + $invoice->setMeta('_manual_payment_proof', $proof_url); | |
| 1319 | + $invoice->setMeta('_manual_payment_notes', $payment_notes); | |
| 1320 | + | |
| 1321 | + // Send admin notification | |
| 1322 | + do_action('easy_invoice_manual_payment_submitted', $invoice_id, $payment_type); | |
| 1323 | + | |
| 1324 | + wp_send_json_success([ | |
| 1325 | + 'message' => __('Payment submitted successfully! Your payment will be verified by the administrator.', 'easy-invoice'), | |
| 1326 | + 'payment_id' => $payment_id | |
| 1327 | + ]); | |
| 1328 | + } | |
| 1329 | + | |
| 1330 | + /** | |
| 948 | 1331 | * Handle submission of payment proof for manual gateways (Bank Transfer, Cheque) |
| 949 | 1332 | */ |
| 950 | 1333 | public function submitPaymentProof(): void { |
| 951 | 1334 | $gateway_name = isset($_POST['gateway']) ? sanitize_text_field($_POST['gateway']) : ''; |
| @@ -1007,10 +1390,10 @@ | ||
| 1007 | 1390 | easy_invoice_toast_error(__('Invalid request or security check failed.', 'easy-invoice')); |
| 1008 | 1391 | return; |
| 1009 | 1392 | } |
| 1010 | 1393 | |
| 1011 | - // Use manage_options capability which administrators have | |
| 1012 | - if (!current_user_can('manage_options')) { | |
| 1394 | + // Mark-as-paid is a record-payment action — gated by the matching cap. | |
| 1395 | + if (!easy_invoice_user_can('ei_record_payment')) { | |
| 1013 | 1396 | easy_invoice_toast_error(__('You do not have permission to perform this action.', 'easy-invoice')); |
| 1014 | 1397 | return; |
| 1015 | 1398 | } |
| 1016 | 1399 | |
| @@ -1179,8 +1562,109 @@ | ||
| 1179 | 1562 | easy_invoice_toast_success(__('Invoice marked as paid successfully.', 'easy-invoice')); |
| 1180 | 1563 | } |
| 1181 | 1564 | |
| 1182 | 1565 | /** |
| 1566 | + * Record money received, from the admin "Add New Payment" form. | |
| 1567 | + * | |
| 1568 | + * The form used to post to the customer checkout endpoint, which runs a | |
| 1569 | + * gateway (bank-transfer instructions, a card form) — not what an admin | |
| 1570 | + * typing in a cheque they were handed wants. This books a completed | |
| 1571 | + * payment and settles the invoice: paid when the total is covered, | |
| 1572 | + * partial otherwise. | |
| 1573 | + */ | |
| 1574 | + public function recordPayment() { | |
| 1575 | + if (!isset($_POST['payment_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['payment_nonce'])), 'easy_invoice_payment')) { | |
| 1576 | + wp_send_json_error(['message' => __('Security check failed. Please reload the page and try again.', 'easy-invoice')]); | |
| 1577 | + } | |
| 1578 | + if (!easy_invoice_user_can('ei_record_payment')) { | |
| 1579 | + wp_send_json_error(['message' => __('You do not have permission to record payments.', 'easy-invoice')]); | |
| 1580 | + } | |
| 1581 | + $invoice_id = isset($_POST['invoice_id']) ? absint($_POST['invoice_id']) : 0; | |
| 1582 | + $amount = isset($_POST['amount']) ? (float) str_replace(',', '', sanitize_text_field(wp_unslash($_POST['amount']))) : 0.0; | |
| 1583 | + $method = isset($_POST['payment_method']) ? sanitize_key(wp_unslash($_POST['payment_method'])) : ''; | |
| 1584 | + $date = isset($_POST['payment_date']) ? sanitize_text_field(wp_unslash($_POST['payment_date'])) : ''; | |
| 1585 | + $notes = isset($_POST['notes']) ? sanitize_textarea_field(wp_unslash($_POST['notes'])) : ''; | |
| 1586 | + | |
| 1587 | + $invoice = $invoice_id > 0 ? \EasyInvoice\Providers\InvoiceServiceProvider::getInvoiceRepository()->find($invoice_id) : null; | |
| 1588 | + if (!$invoice) { | |
| 1589 | + wp_send_json_error(['message' => __('Choose the invoice the payment is for.', 'easy-invoice')]); | |
| 1590 | + } | |
| 1591 | + if ($amount <= 0) { | |
| 1592 | + wp_send_json_error(['message' => __('Enter an amount greater than zero.', 'easy-invoice')]); | |
| 1593 | + } | |
| 1594 | + if ('' === $method) { | |
| 1595 | + $method = 'manual'; | |
| 1596 | + } | |
| 1597 | + $when = $date && strtotime($date) ? gmdate('Y-m-d H:i:s', strtotime($date)) : current_time('mysql'); | |
| 1598 | + | |
| 1599 | + $currency_code = $invoice->getCurrencyCode() ?: get_option('easy_invoice_currency_code', 'USD'); | |
| 1600 | + $currency_symbol = \EasyInvoice\Helpers\CurrencyHelper::getCurrencySymbol($currency_code); | |
| 1601 | + $payment_id = wp_insert_post([ | |
| 1602 | + 'post_title' => sprintf('Payment for Invoice #%s', $invoice->getNumber()), | |
| 1603 | + 'post_type' => 'easy_invoice_payment', | |
| 1604 | + 'post_status' => 'publish', | |
| 1605 | + 'post_author' => get_current_user_id(), | |
| 1606 | + 'meta_input' => [ | |
| 1607 | + '_invoice_id' => $invoice_id, | |
| 1608 | + '_amount' => round($amount, 2), | |
| 1609 | + '_payment_method' => $method, | |
| 1610 | + '_status' => 'completed', | |
| 1611 | + '_transaction_id' => 'MANUAL-' . $invoice_id . '-' . time(), | |
| 1612 | + '_payment_date' => $when, | |
| 1613 | + '_notes' => $notes, | |
| 1614 | + '_payment_type' => 'manual', | |
| 1615 | + '_currency' => $currency_code, | |
| 1616 | + '_currency_symbol' => $currency_symbol, | |
| 1617 | + '_gateway_response' => wp_json_encode(['recorded_by' => get_current_user_id(), 'recorded_at' => current_time('mysql'), 'notes' => $notes]), | |
| 1618 | + ], | |
| 1619 | + ]); | |
| 1620 | + if (is_wp_error($payment_id) || !$payment_id) { | |
| 1621 | + wp_send_json_error(['message' => __('The payment could not be saved.', 'easy-invoice')]); | |
| 1622 | + } | |
| 1623 | + | |
| 1624 | + $new_status = \EasyInvoice\Services\InvoiceBalance::isSettled($invoice) ? 'paid' : 'partial'; | |
| 1625 | + update_post_meta($invoice_id, '_easy_invoice_payment_method', $method); | |
| 1626 | + $invoice->setStatus($new_status); | |
| 1627 | + $invoice->save(); | |
| 1628 | + $payment_event = [ | |
| 1629 | + 'payment_method' => $method, | |
| 1630 | + 'gateway_name' => 'manual', | |
| 1631 | + 'transaction_id' => get_post_meta($payment_id, '_transaction_id', true), | |
| 1632 | + 'amount' => $amount, | |
| 1633 | + 'date' => $date, | |
| 1634 | + ]; | |
| 1635 | + if ('paid' === $new_status) { | |
| 1636 | + do_action('easy_invoice_payment_completed', $invoice_id, $invoice, $payment_event); | |
| 1637 | + } else { | |
| 1638 | + /** | |
| 1639 | + * Fires when a payment is recorded that leaves a balance owing. | |
| 1640 | + * | |
| 1641 | + * @param int $invoice_id Invoice. | |
| 1642 | + * @param object $invoice Invoice model. | |
| 1643 | + * @param array $payment payment_method, gateway_name, transaction_id, amount, date. | |
| 1644 | + */ | |
| 1645 | + do_action('easy_invoice_payment_received', $invoice_id, $invoice, $payment_event); | |
| 1646 | + } | |
| 1647 | + /** | |
| 1648 | + * Fires after an administrator records a payment by hand. | |
| 1649 | + * | |
| 1650 | + * @param int $payment_id Payment record. | |
| 1651 | + * @param int $invoice_id Invoice. | |
| 1652 | + * @param float $amount Amount recorded. | |
| 1653 | + * @param string $new_status Invoice status afterwards. | |
| 1654 | + */ | |
| 1655 | + do_action('easy_invoice_payment_recorded', $payment_id, $invoice_id, $amount, $new_status); | |
| 1656 | + | |
| 1657 | + wp_send_json_success([ | |
| 1658 | + 'payment_id' => $payment_id, | |
| 1659 | + 'status' => $new_status, | |
| 1660 | + 'message' => 'paid' === $new_status | |
| 1661 | + ? __('Payment recorded — the invoice is paid.', 'easy-invoice') | |
| 1662 | + : sprintf(/* translators: %s: amount still owed. */ __('Payment recorded — %s still due.', 'easy-invoice'), $currency_symbol . number_format_i18n(\EasyInvoice\Services\InvoiceBalance::due($invoice), 2)), | |
| 1663 | + ]); | |
| 1664 | + } | |
| 1665 | + | |
| 1666 | + /** | |
| 1183 | 1667 | * Handle bulk actions for payments |
| 1184 | 1668 | */ |
| 1185 | 1669 | public function handleBulkActions() { |
| 1186 | 1670 | // Check if we're processing a bulk action |
| @@ -1188,19 +1672,21 @@ | ||
| 1188 | 1672 | return; |
| 1189 | 1673 | } |
| 1190 | 1674 | |
| 1191 | 1675 | // Check nonce and capability |
| 1192 | - if (!wp_verify_nonce($_POST['easy_invoice_payment_bulk_nonce'], 'easy_invoice_payment_bulk_action')) { | |
| 1193 | - wp_die(__('Security check failed.', 'easy-invoice')); | |
| 1676 | + if (!wp_verify_nonce(($_POST['easy_invoice_payment_bulk_nonce'] ?? ''), 'easy_invoice_payment_bulk_action')) { | |
| 1677 | + wp_die(esc_html__('Security check failed.', 'easy-invoice')); | |
| 1194 | 1678 | } |
| 1195 | 1679 | |
| 1196 | - if (!current_user_can('manage_options')) { | |
| 1197 | - wp_die(__('You do not have permission to perform this action.', 'easy-invoice')); | |
| 1680 | + // Bulk action on payments — record-payment cap is the right gate | |
| 1681 | + // (covers trash/restore/delete which all change payment state). | |
| 1682 | + if (!easy_invoice_user_can('ei_record_payment')) { | |
| 1683 | + wp_die(esc_html__('You do not have permission to perform this action.', 'easy-invoice')); | |
| 1198 | 1684 | } |
| 1199 | 1685 | |
| 1200 | 1686 | // Check if we have payment IDs |
| 1201 | 1687 | if (!isset($_POST['payment_ids']) || !is_array($_POST['payment_ids']) || empty($_POST['payment_ids'])) { |
| 1202 | - wp_redirect(admin_url('admin.php?page=easy-invoice-payments&bulk_error=no_selection')); | |
| 1688 | + wp_safe_redirect(admin_url('admin.php?page=easy-invoice-payments&bulk_error=no_selection')); | |
| 1203 | 1689 | exit; |
| 1204 | 1690 | } |
| 1205 | 1691 | |
| 1206 | 1692 | // Get bulk action and payment IDs |
| @@ -1237,13 +1723,13 @@ | ||
| 1237 | 1723 | } |
| 1238 | 1724 | } |
| 1239 | 1725 | |
| 1240 | 1726 | // Update invoice statuses for completed payments that were trashed |
| 1241 | - foreach ($invoice_updates as $invoice_id => $deleted_amount) { | |
| 1242 | - $this->updateInvoiceStatusAfterPaymentDeletion($invoice_id, $deleted_amount); | |
| 1727 | + foreach (array_keys($invoice_updates) as $invoice_id) { | |
| 1728 | + $this->syncInvoiceStatusWithPayments($invoice_id); | |
| 1243 | 1729 | } |
| 1244 | 1730 | |
| 1245 | - wp_redirect(admin_url('admin.php?page=easy-invoice-payments&bulk_trashed=' . $processed)); | |
| 1731 | + wp_safe_redirect(admin_url('admin.php?page=easy-invoice-payments&bulk_trashed=' . $processed)); | |
| 1246 | 1732 | break; |
| 1247 | 1733 | |
| 1248 | 1734 | case 'restore': |
| 1249 | 1735 | foreach ($payment_ids as $id) { |
| @@ -1275,13 +1761,13 @@ | ||
| 1275 | 1761 | } |
| 1276 | 1762 | } |
| 1277 | 1763 | |
| 1278 | 1764 | // Update invoice statuses for completed payments that were restored |
| 1279 | - foreach ($invoice_updates as $invoice_id => $restored_amount) { | |
| 1280 | - $this->updateInvoiceStatusAfterPaymentRestoration($invoice_id, $restored_amount); | |
| 1765 | + foreach (array_keys($invoice_updates) as $invoice_id) { | |
| 1766 | + $this->syncInvoiceStatusWithPayments($invoice_id); | |
| 1281 | 1767 | } |
| 1282 | 1768 | |
| 1283 | - wp_redirect(admin_url('admin.php?page=easy-invoice-payments&bulk_restored=' . $processed)); | |
| 1769 | + wp_safe_redirect(admin_url('admin.php?page=easy-invoice-payments&bulk_restored=' . $processed)); | |
| 1284 | 1770 | break; |
| 1285 | 1771 | |
| 1286 | 1772 | case 'delete': |
| 1287 | 1773 | foreach ($payment_ids as $id) { |
| @@ -1308,17 +1794,17 @@ | ||
| 1308 | 1794 | } |
| 1309 | 1795 | } |
| 1310 | 1796 | |
| 1311 | 1797 | // Update invoice statuses for completed payments that were deleted |
| 1312 | - foreach ($invoice_updates as $invoice_id => $deleted_amount) { | |
| 1313 | - $this->updateInvoiceStatusAfterPaymentDeletion($invoice_id, $deleted_amount); | |
| 1798 | + foreach (array_keys($invoice_updates) as $invoice_id) { | |
| 1799 | + $this->syncInvoiceStatusWithPayments($invoice_id); | |
| 1314 | 1800 | } |
| 1315 | 1801 | |
| 1316 | - wp_redirect(admin_url('admin.php?page=easy-invoice-payments&bulk_deleted=' . $processed)); | |
| 1802 | + wp_safe_redirect(admin_url('admin.php?page=easy-invoice-payments&bulk_deleted=' . $processed)); | |
| 1317 | 1803 | break; |
| 1318 | 1804 | |
| 1319 | 1805 | default: |
| 1320 | - wp_redirect(admin_url('admin.php?page=easy-invoice-payments&bulk_error=invalid_action')); | |
| 1806 | + wp_safe_redirect(admin_url('admin.php?page=easy-invoice-payments&bulk_error=invalid_action')); | |
| 1321 | 1807 | } |
| 1322 | 1808 | |
| 1323 | 1809 | exit; |
| 1324 | 1810 | } |
| @@ -1323,108 +1809,40 @@ | ||
| 1323 | 1809 | exit; |
| 1324 | 1810 | } |
| 1325 | 1811 | |
| 1326 | 1812 | /** |
| 1327 | - * Update invoice status after payment deletion | |
| 1813 | + * Put an invoice's status back in line with the completed payments and | |
| 1814 | + * credit notes it actually has — after a payment is trashed, restored or | |
| 1815 | + * deleted. Paid when nothing is owed, part-paid when something has been | |
| 1816 | + * received, otherwise awaiting payment; an issued invoice never returns | |
| 1817 | + * to draft. (This used to write the status to a meta key the invoice | |
| 1818 | + * does not use, so a trashed payment left the invoice "paid".) | |
| 1819 | + * | |
| 1820 | + * @param int $invoice_id Invoice. | |
| 1328 | 1821 | */ |
| 1329 | - private function updateInvoiceStatusAfterPaymentDeletion($invoice_id, $deleted_amount) { | |
| 1330 | - $invoice = new Invoice($invoice_id); | |
| 1331 | - | |
| 1332 | - if (!$invoice->getId()) { | |
| 1822 | + private function syncInvoiceStatusWithPayments($invoice_id) { | |
| 1823 | + $invoice = \EasyInvoice\Providers\InvoiceServiceProvider::getInvoiceRepository()->find((int) $invoice_id); | |
| 1824 | + if (!$invoice || !$invoice->getId()) { | |
| 1333 | 1825 | return; |
| 1334 | 1826 | } |
| 1335 | - | |
| 1336 | - // Get all remaining payments for this invoice | |
| 1337 | - $remaining_payments = get_posts(array( | |
| 1338 | - 'post_type' => 'easy_invoice_payment', | |
| 1339 | - 'post_status' => 'publish', | |
| 1340 | - 'meta_query' => array( | |
| 1341 | - array( | |
| 1342 | - 'key' => '_invoice_id', | |
| 1343 | - 'value' => $invoice_id, | |
| 1344 | - 'compare' => '=' | |
| 1345 | - ), | |
| 1346 | - array( | |
| 1347 | - 'key' => '_status', | |
| 1348 | - 'value' => 'completed', | |
| 1349 | - 'compare' => '=' | |
| 1350 | - ) | |
| 1351 | - ), | |
| 1352 | - 'posts_per_page' => -1 | |
| 1353 | - )); | |
| 1354 | - | |
| 1355 | - // Calculate total remaining payments | |
| 1356 | - $total_remaining = 0; | |
| 1357 | - foreach ($remaining_payments as $payment_post) { | |
| 1358 | - $payment = new Payment($payment_post); | |
| 1359 | - $total_remaining += floatval($payment->getAmount()); | |
| 1827 | + $current = (string) $invoice->getStatus(); | |
| 1828 | + if (in_array($current, ['draft', 'cancelled', 'canceled'], true)) { | |
| 1829 | + return; | |
| 1360 | 1830 | } |
| 1361 | - | |
| 1362 | - $invoice_total = floatval($invoice->getTotal()); | |
| 1363 | - | |
| 1364 | - // Update invoice status based on remaining payments | |
| 1365 | - if ($total_remaining >= $invoice_total) { | |
| 1366 | - // Still fully paid | |
| 1367 | - update_post_meta($invoice_id, '_status', 'paid'); | |
| 1368 | - } elseif ($total_remaining > 0) { | |
| 1369 | - // Partially paid | |
| 1370 | - update_post_meta($invoice_id, '_status', 'partial'); | |
| 1831 | + $paid = \EasyInvoice\Services\InvoiceBalance::paid((int) $invoice_id); | |
| 1832 | + if (\EasyInvoice\Services\InvoiceBalance::isSettled($invoice)) { | |
| 1833 | + $new = 'paid'; | |
| 1834 | + } elseif ($paid > 0) { | |
| 1835 | + $new = 'partial'; | |
| 1371 | 1836 | } else { |
| 1372 | - // No payments remaining | |
| 1373 | - update_post_meta($invoice_id, '_status', 'unpaid'); | |
| 1837 | + $new = in_array($current, ['unpaid', 'available'], true) ? $current : 'available'; | |
| 1374 | 1838 | } |
| 1839 | + if ($new !== $current) { | |
| 1840 | + $invoice->setStatus($new); | |
| 1841 | + $invoice->save(); | |
| 1842 | + } | |
| 1375 | 1843 | } |
| 1376 | 1844 | |
| 1377 | - /** | |
| 1378 | - * Update invoice status after payment restoration | |
| 1379 | - */ | |
| 1380 | - private function updateInvoiceStatusAfterPaymentRestoration($invoice_id, $restored_amount) { | |
| 1381 | - $invoice = new Invoice($invoice_id); | |
| 1382 | - | |
| 1383 | - if (!$invoice->getId()) { | |
| 1384 | - return; | |
| 1385 | - } | |
| 1386 | - | |
| 1387 | - // Get all payments for this invoice (including the restored one) | |
| 1388 | - $all_payments = get_posts(array( | |
| 1389 | - 'post_type' => 'easy_invoice_payment', | |
| 1390 | - 'post_status' => 'publish', | |
| 1391 | - 'meta_query' => array( | |
| 1392 | - array( | |
| 1393 | - 'key' => '_invoice_id', | |
| 1394 | - 'value' => $invoice_id, | |
| 1395 | - 'compare' => '=' | |
| 1396 | - ), | |
| 1397 | - array( | |
| 1398 | - 'key' => '_status', | |
| 1399 | - 'value' => 'completed', | |
| 1400 | - 'compare' => '=' | |
| 1401 | - ) | |
| 1402 | - ), | |
| 1403 | - 'posts_per_page' => -1 | |
| 1404 | - )); | |
| 1405 | - | |
| 1406 | - // Calculate total payments (including restored ones) | |
| 1407 | - $total_payments = 0; | |
| 1408 | - foreach ($all_payments as $payment_post) { | |
| 1409 | - $payment = new Payment($payment_post); | |
| 1410 | - $total_payments += floatval($payment->getAmount()); | |
| 1411 | - } | |
| 1412 | - | |
| 1413 | - $invoice_total = floatval($invoice->getTotal()); | |
| 1414 | - | |
| 1415 | - // Update invoice status based on total payments | |
| 1416 | - if ($total_payments >= $invoice_total) { | |
| 1417 | - // Fully paid | |
| 1418 | - update_post_meta($invoice_id, '_status', 'paid'); | |
| 1419 | - } elseif ($total_payments > 0) { | |
| 1420 | - // Partially paid | |
| 1421 | - update_post_meta($invoice_id, '_status', 'partial'); | |
| 1422 | - } else { | |
| 1423 | - // No payments | |
| 1424 | - update_post_meta($invoice_id, '_status', 'unpaid'); | |
| 1425 | - } | |
| 1426 | - } | |
| 1427 | 1845 | |
| 1428 | 1846 | // Stripe payment recording moved to Pro plugin |
| 1429 | 1847 | |
| 1430 | 1848 | |