Passed
Push — master ( 44d5e5...8a47d2 )
by Brian
04:22
created

WPInv_Ajax::recalculate_full_prices()   C

Complexity

Conditions 12
Paths 15

Size

Total Lines 66
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 12
eloc 36
c 1
b 0
f 0
nc 15
nop 0
dl 0
loc 66
rs 6.9666

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Contains the ajax handlers.
4
 *
5
 * @since 1.0.0
6
 * @package Invoicing
7
 */
8
 
9
defined( 'ABSPATH' ) || exit;
10
11
/**
12
 * WPInv_Ajax class.
13
 */
14
class WPInv_Ajax {
15
16
    /**
17
	 * Hook in ajax handlers.
18
	 */
19
	public static function init() {
20
		add_action( 'init', array( __CLASS__, 'define_ajax' ), 0 );
21
		add_action( 'template_redirect', array( __CLASS__, 'do_wpinv_ajax' ), 0 );
22
		self::add_ajax_events();
23
    }
24
25
    /**
26
	 * Set GetPaid AJAX constant and headers.
27
	 */
28
	public static function define_ajax() {
29
30
		if ( ! empty( $_GET['wpinv-ajax'] ) ) {
31
			getpaid_maybe_define_constant( 'DOING_AJAX', true );
32
			getpaid_maybe_define_constant( 'WPInv_DOING_AJAX', true );
33
			if ( ! WP_DEBUG || ( WP_DEBUG && ! WP_DEBUG_DISPLAY ) ) {
34
				/** @scrutinizer ignore-unhandled */ @ini_set( 'display_errors', 0 );
35
			}
36
			$GLOBALS['wpdb']->hide_errors();
37
		}
38
39
    }
40
    
41
    /**
42
	 * Send headers for GetPaid Ajax Requests.
43
	 *
44
	 * @since 1.0.18
45
	 */
46
	private static function wpinv_ajax_headers() {
47
		if ( ! headers_sent() ) {
48
			send_origin_headers();
49
			send_nosniff_header();
50
			nocache_headers();
51
			header( 'Content-Type: text/html; charset=' . get_option( 'blog_charset' ) );
52
			header( 'X-Robots-Tag: noindex' );
53
			status_header( 200 );
54
		}
55
    }
56
    
57
    /**
58
	 * Check for GetPaid Ajax request and fire action.
59
	 */
60
	public static function do_wpinv_ajax() {
61
		global $wp_query;
62
63
		if ( ! empty( $_GET['wpinv-ajax'] ) ) {
64
			$wp_query->set( 'wpinv-ajax', sanitize_text_field( wp_unslash( $_GET['wpinv-ajax'] ) ) );
0 ignored issues
show
Bug introduced by
It seems like wp_unslash($_GET['wpinv-ajax']) can also be of type array; however, parameter $str of sanitize_text_field() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

64
			$wp_query->set( 'wpinv-ajax', sanitize_text_field( /** @scrutinizer ignore-type */ wp_unslash( $_GET['wpinv-ajax'] ) ) );
Loading history...
65
		}
66
67
		$action = $wp_query->get( 'wpinv-ajax' );
68
69
		if ( $action ) {
70
			self::wpinv_ajax_headers();
71
			$action = sanitize_text_field( $action );
72
			do_action( 'wpinv_ajax_' . $action );
73
			wp_die();
74
		}
75
76
    }
77
78
    /**
79
	 * Hook in ajax methods.
80
	 */
81
    public static function add_ajax_events() {
82
83
        // array( 'event' => is_frontend )
84
        $ajax_events = array(
85
            'add_note'                    => false,
86
            'delete_note'                 => false,
87
            'get_states_field'            => true,
88
            'get_aui_states_field'        => true,
89
            'payment_form'                => true,
90
            'get_payment_form'            => true,
91
            'get_payment_form_states_field' => true,
92
            'get_invoicing_items'         => false,
93
            'get_customers'               => false,
94
            'get_invoice_items'           => false,
95
            'add_invoice_items'           => false,
96
            'admin_add_invoice_item'      => false,
97
            'recalculate_full_prices'     => false,
98
            'edit_invoice_item'           => false,
99
            'create_invoice_item'         => false,
100
            'remove_invoice_item'         => false,
101
            'get_billing_details'         => false,
102
            'recalculate_invoice_totals'  => false,
103
            'check_new_user_email'        => false,
104
            'run_tool'                    => false,
105
            'payment_form_refresh_prices' => true,
106
        );
107
108
        foreach ( $ajax_events as $ajax_event => $nopriv ) {
109
            add_action( 'wp_ajax_wpinv_' . $ajax_event, array( __CLASS__, $ajax_event ) );
110
            add_action( 'wp_ajax_getpaid_' . $ajax_event, array( __CLASS__, $ajax_event ) );
111
112
            if ( $nopriv ) {
113
                add_action( 'wp_ajax_nopriv_wpinv_' . $ajax_event, array( __CLASS__, $ajax_event ) );
114
                add_action( 'wp_ajax_nopriv_getpaid_' . $ajax_event, array( __CLASS__, $ajax_event ) );
115
                add_action( 'wpinv_ajax_' . $ajax_event, array( __CLASS__, $ajax_event ) );
116
            }
117
        }
118
    }
119
    
120
    public static function add_note() {
121
        check_ajax_referer( 'add-invoice-note', '_nonce' );
122
123
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
124
            die(-1);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
125
        }
126
127
        $post_id   = absint( $_POST['post_id'] );
128
        $note      = wp_kses_post( trim( stripslashes( $_POST['note'] ) ) );
129
        $note_type = sanitize_text_field( $_POST['note_type'] );
130
131
        $is_customer_note = $note_type == 'customer' ? 1 : 0;
132
133
        if ( $post_id > 0 ) {
134
            $note_id = wpinv_insert_payment_note( $post_id, $note, $is_customer_note );
0 ignored issues
show
Deprecated Code introduced by
The function wpinv_insert_payment_note() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

134
            $note_id = /** @scrutinizer ignore-deprecated */ wpinv_insert_payment_note( $post_id, $note, $is_customer_note );
Loading history...
135
136
            if ( $note_id > 0 && !is_wp_error( $note_id ) ) {
137
                wpinv_get_invoice_note_line_item( $note_id );
138
            }
139
        }
140
141
        die();
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
142
    }
143
144
    public static function delete_note() {
145
        check_ajax_referer( 'delete-invoice-note', '_nonce' );
146
147
        if ( !wpinv_current_user_can_manage_invoicing() ) {
148
            die(-1);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
149
        }
150
151
        $note_id = (int)$_POST['note_id'];
152
153
        if ( $note_id > 0 ) {
154
            wp_delete_comment( $note_id, true );
155
        }
156
157
        die();
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
158
    }
159
    
160
    public static function get_states_field() {
161
        echo wpinv_get_states_field();
162
        
163
        die();
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
164
    }
165
166
    /**
167
     * Retrieves a given user's billing address.
168
     */
169
    public static function get_billing_details() {
170
171
        // Verify nonce.
172
        check_ajax_referer( 'wpinv-nonce' );
173
174
        // Can the user manage the plugin?
175
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
176
            die(-1);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
177
        }
178
179
        // Do we have a user id?
180
        $user_id = $_GET['user_id'];
181
182
        if ( empty( $user_id ) || ! is_numeric( $user_id ) ) {
183
            die(-1);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
184
        }
185
186
        // Fetch the billing details.
187
        $billing_details    = wpinv_get_user_address( $user_id );
188
        $billing_details    = apply_filters( 'wpinv_ajax_billing_details', $billing_details, $user_id );
189
190
        // unset the user id and email.
191
        $to_ignore = array( 'user_id', 'email' );
192
193
        foreach ( $to_ignore as $key ) {
194
            if ( isset( $billing_details[ $key ] ) ) {
195
                unset( $billing_details[ $key ] );
196
            }
197
        }
198
199
        wp_send_json_success( $billing_details );
200
201
    }
202
203
    /**
204
     * Checks if a new users email is valid.
205
     */
206
    public static function check_new_user_email() {
207
208
        // Verify nonce.
209
        check_ajax_referer( 'wpinv-nonce' );
210
211
        // Can the user manage the plugin?
212
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
213
            die(-1);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
214
        }
215
216
        // We need an email address.
217
        if ( empty( $_GET['email'] ) ) {
218
            _e( "Provide the new user's email address", 'invoicing' );
219
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
220
        }
221
222
        // Ensure the email is valid.
223
        $email = sanitize_text_field( $_GET['email'] );
224
        if ( ! is_email( $email ) ) {
225
            _e( 'Invalid email address', 'invoicing' );
226
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
227
        }
228
229
        // And it does not exist.
230
        $id = email_exists( $email );
231
        if ( $id ) {
232
            wp_send_json_success( compact( 'id' ) );
233
        }
234
235
        wp_send_json_success( true );
236
    }
237
    
238
    public static function run_tool() {
239
        check_ajax_referer( 'wpinv-nonce', '_nonce' );
240
        if ( !wpinv_current_user_can_manage_invoicing() ) {
241
            die(-1);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
242
        }
243
        
244
        $tool = sanitize_text_field( $_POST['tool'] );
245
        
246
        do_action( 'wpinv_run_tool' );
247
        
248
        if ( !empty( $tool ) ) {
249
            do_action( 'wpinv_tool_' . $tool );
250
        }
251
    }
252
253
    /**
254
     * Retrieves the markup for a payment form.
255
     */
256
    public static function get_payment_form() {
257
258
        // Check nonce.
259
        check_ajax_referer( 'getpaid_form_nonce' );
260
261
        // Is the request set up correctly?
262
		if ( empty( $_GET['form'] ) && empty( $_GET['item'] ) ) {
263
			echo aui()->alert(
264
				array(
265
					'type'    => 'warning',
266
					'content' => __( 'No payment form or item provided', 'invoicing' ),
267
				)
268
            );
269
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
270
        }
271
272
        // Payment form or button?
273
		if ( ! empty( $_GET['form'] ) ) {
274
            getpaid_display_payment_form( urldecode( $_GET['form'] ) );
275
		} else if( ! empty( $_GET['invoice'] ) ) {
276
		    getpaid_display_invoice_payment_form( urldecode( $_GET['invoice'] ) );
277
        } else {
278
			$items = getpaid_convert_items_to_array( urldecode( $_GET['item'] ) );
279
		    getpaid_display_item_payment_form( $items );
280
        }
281
282
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
283
284
    }
285
286
    /**
287
     * Payment forms.
288
     *
289
     * @since 1.0.18
290
     */
291
    public static function payment_form() {
292
293
        // Check nonce.
294
        check_ajax_referer( 'getpaid_form_nonce' );
295
296
        // ... form fields...
297
        if ( empty( $_POST['getpaid_payment_form_submission'] ) ) {
298
            _e( 'Error: Reload the page and try again.', 'invoicing' );
299
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
300
        }
301
302
        // Process the payment form.
303
        $checkout_class = apply_filters( 'getpaid_checkout_class', 'GetPaid_Checkout' );
304
        $checkout       = new $checkout_class( new GetPaid_Payment_Form_Submission() );
305
        $checkout->process_checkout();
306
307
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
308
    }
309
310
    /**
311
     * Payment forms.
312
     *
313
     * @since 1.0.18
314
     */
315
    public static function get_payment_form_states_field() {
316
317
        if ( empty( $_GET['country'] ) || empty( $_GET['form'] ) ) {
318
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
319
        }
320
321
        $elements = getpaid_get_payment_form_elements( $_GET['form'] );
322
323
        if ( empty( $elements ) ) {
324
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
325
        }
326
327
        $address_fields = array();
328
        foreach ( $elements as $element ) {
329
            if ( 'address' === $element['type'] ) {
330
                $address_fields = $element;
331
                break;
332
            }
333
        }
334
335
        if ( empty( $address_fields ) ) {
336
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
337
        }
338
339
        foreach ( $address_fields['fields'] as $address_field ) {
340
341
            if ( 'wpinv_state' == $address_field['name'] ) {
342
343
                $wrap_class  = getpaid_get_form_element_grid_class( $address_field );
344
                $wrap_class  = esc_attr( "$wrap_class getpaid-address-field-wrapper" );
345
                $placeholder = empty( $address_field['placeholder'] ) ? '' : esc_attr( $address_field['placeholder'] );
346
                $description = empty( $address_field['description'] ) ? '' : wp_kses_post( $address_field['description'] );
347
                $value       = is_user_logged_in() ? get_user_meta( get_current_user_id(), '_wpinv_state', true ) : '';
348
                $label       = empty( $address_field['label'] ) ? '' : wp_kses_post( $address_field['label'] );
349
350
                if ( ! empty( $address_field['required'] ) ) {
351
                    $label .= "<span class='text-danger'> *</span>";
352
                }
353
354
                $html = getpaid_get_states_select_markup (
355
                    sanitize_text_field( $_GET['country'] ),
356
                    $value,
357
                    $placeholder,
358
                    $label,
359
                    $description,
360
                    ! empty( $address_field['required'] ),
361
                    $wrap_class,
362
                    wpinv_clean( $_GET['name'] )
363
                );
364
365
                wp_send_json_success( $html );
366
                exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
367
368
            }
369
370
        }
371
    
372
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
373
    }
374
375
    /**
376
     * Recalculates invoice totals.
377
     */
378
    public static function recalculate_invoice_totals() {
379
380
        // Verify nonce.
381
        check_ajax_referer( 'wpinv-nonce' );
382
383
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
384
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
385
        }
386
387
        // We need an invoice.
388
        if ( empty( $_POST['post_id'] ) ) {
389
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
390
        }
391
392
        // Fetch the invoice.
393
        $invoice = new WPInv_Invoice( trim( $_POST['post_id'] ) );
394
395
        // Ensure it exists.
396
        if ( ! $invoice->get_id() ) {
397
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
398
        }
399
400
        // Maybe set the country, state, currency.
401
        foreach ( array( 'country', 'state', 'currency', 'vat_number', 'discount_code' ) as $key ) {
402
            if ( isset( $_POST[ $key ] ) ) {
403
                $method = "set_$key";
404
                $invoice->$method( sanitize_text_field( $_POST[ $key ] ) );
405
            }
406
        }
407
408
        // Maybe disable taxes.
409
        $invoice->set_disable_taxes( ! empty( $_POST['taxes'] ) );
410
411
        // Discount code.
412
        if ( ! $invoice->is_paid() && ! $invoice->is_refunded() ) {
413
            $discount = new WPInv_Discount( $invoice->get_discount_code() );
414
            if ( $discount->exists() ) {
415
                $invoice->add_discount( getpaid_calculate_invoice_discount( $invoice, $discount ) );
416
            } else {
417
                $invoice->remove_discount( 'discount_code' );
418
            }
419
        }
420
421
        // Recalculate totals.
422
        $invoice->recalculate_total();
423
424
        $total        = wpinv_price( $invoice->get_total(), $invoice->get_currency() );
425
        $suscriptions = getpaid_get_invoice_subscriptions( $invoice );
426
        if ( is_a( $suscriptions, 'WPInv_Subscription' ) && $invoice->is_recurring() && $invoice->is_parent() && $invoice->get_total() != $invoice->get_recurring_total() ) {
427
            $recurring_total = wpinv_price( $invoice->get_recurring_total(), $invoice->get_currency() );
428
            $total          .= '<small class="form-text text-muted">' . sprintf( __( 'Recurring Price: %s', 'invoicing' ), $recurring_total ) . '</small>';
429
        }
430
431
        $totals = array(
432
            'subtotal' => wpinv_price( $invoice->get_subtotal(), $invoice->get_currency() ),
433
            'discount' => wpinv_price( $invoice->get_total_discount(), $invoice->get_currency() ),
434
            'tax'      => wpinv_price( $invoice->get_total_tax(), $invoice->get_currency() ),
435
            'total'    => $total,
436
        );
437
438
        $totals = apply_filters( 'getpaid_invoice_totals', $totals, $invoice );
439
440
        wp_send_json_success( compact( 'totals' ) );
441
    }
442
443
    /**
444
     * Get items belonging to a given invoice.
445
     */
446
    public static function get_invoice_items() {
447
448
        // Verify nonce.
449
        check_ajax_referer( 'wpinv-nonce' );
450
451
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
452
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
453
        }
454
455
        // We need an invoice and items.
456
        if ( empty( $_POST['post_id'] ) ) {
457
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
458
        }
459
460
        // Fetch the invoice.
461
        $invoice = new WPInv_Invoice( trim( $_POST['post_id'] ) );
462
463
        // Ensure it exists.
464
        if ( ! $invoice->get_id() ) {
465
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
466
        }
467
468
        // Return an array of invoice items.
469
        $items = array();
470
471
        foreach ( $invoice->get_items() as $item ) {
472
            $items[] = $item->prepare_data_for_invoice_edit_ajax(  $invoice->get_currency(), $invoice->is_renewal()  );
473
        }
474
475
        wp_send_json_success( compact( 'items' ) );
476
    }
477
478
    /**
479
     * Edits an invoice item.
480
     */
481
    public static function edit_invoice_item() {
482
483
        // Verify nonce.
484
        check_ajax_referer( 'wpinv-nonce' );
485
486
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
487
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
488
        }
489
490
        // We need an invoice and item details.
491
        if ( empty( $_POST['post_id'] ) || empty( $_POST['data'] ) ) {
492
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
493
        }
494
495
        // Fetch the invoice.
496
        $invoice = new WPInv_Invoice( trim( $_POST['post_id'] ) );
497
498
        // Ensure it exists and its not been paid for.
499
        if ( ! $invoice->get_id() || $invoice->is_paid() || $invoice->is_refunded() ) {
500
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
501
        }
502
503
        // Format the data.
504
        $data = wp_unslash( wp_list_pluck( $_POST['data'], 'value', 'field' ) );
505
506
        // Ensure that we have an item id.
507
        if ( empty( $data['id'] ) ) {
508
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
509
        }
510
511
        // Abort if the invoice does not have the specified item.
512
        $item = $invoice->get_item( (int) $data['id'] );
513
514
        if ( empty( $item ) ) {
515
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
516
        }
517
518
        // Update the item.
519
        $item->set_price( floatval( $data['price'] ) );
520
        $item->set_name( sanitize_text_field( $data['name'] ) );
521
        $item->set_description( wp_kses_post( $data['description'] ) );
522
        $item->set_quantity( floatval( $data['quantity'] ) );
523
524
        // Add it to the invoice.
525
        $error = $invoice->add_item( $item );
526
        $alert = false;
527
        if ( is_wp_error( $error ) ) {
528
            $alert = $error->get_error_message();
529
        }
530
531
        // Update totals.
532
        $invoice->recalculate_total();
533
534
        // Save the invoice.
535
        $invoice->save();
536
537
        // Return an array of invoice items.
538
        $items = array();
539
540
        foreach ( $invoice->get_items() as $item ) {
541
            $items[] = $item->prepare_data_for_invoice_edit_ajax(  $invoice->get_currency()  );
542
        }
543
544
        wp_send_json_success( compact( 'items', 'alert' ) );
545
    }
546
547
    /**
548
     * Creates an invoice item.
549
     */
550
    public static function create_invoice_item() {
551
552
        // Verify nonce.
553
        check_ajax_referer( 'wpinv-nonce' );
554
555
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
556
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
557
        }
558
559
        // We need an invoice and item details.
560
        if ( empty( $_POST['invoice_id'] ) || empty( $_POST['_wpinv_quick'] ) ) {
561
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
562
        }
563
564
        // Fetch the invoice.
565
        $invoice = new WPInv_Invoice( trim( $_POST['invoice_id'] ) );
566
567
        // Ensure it exists and its not been paid for.
568
        if ( ! $invoice->get_id() || $invoice->is_paid() || $invoice->is_refunded() ) {
569
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
570
        }
571
572
        // Format the data.
573
        $data = wp_unslash( $_POST['_wpinv_quick'] );
574
575
        $item = new WPInv_Item();
576
        $item->set_price( floatval( $data['price'] ) );
577
        $item->set_name( sanitize_text_field( $data['name'] ) );
578
        $item->set_description( wp_kses_post( $data['description'] ) );
579
        $item->set_type( sanitize_text_field( $data['type'] ) );
580
        $item->set_vat_rule( sanitize_text_field( $data['vat_rule'] ) );
581
        $item->set_vat_class( sanitize_text_field( $data['vat_class'] ) );
582
        $item->set_status( 'publish' );
583
        $item->save();
584
585
        if ( ! $item->exists() ) {
586
            $alert = __( 'Could not create invoice item. Please try again.', 'invoicing' );
587
            wp_send_json_success( compact( 'alert' ) );
588
        }
589
590
        $item = new GetPaid_Form_Item( $item->get_id() );
591
        $item->set_quantity( floatval( $data['qty'] ) );
592
593
        // Add it to the invoice.
594
        $error = $invoice->add_item( $item );
595
        $alert = false;
0 ignored issues
show
Unused Code introduced by
The assignment to $alert is dead and can be removed.
Loading history...
596
597
        if ( is_wp_error( $error ) ) {
598
            $alert = $error->get_error_message();
599
            wp_send_json_success( compact( 'alert' ) );
600
         }
601
602
        // Update totals.
603
        $invoice->recalculate_total();
604
605
        // Save the invoice.
606
        $invoice->save();
607
608
        // Save the invoice.
609
        $invoice->recalculate_total();
610
        $invoice->save();
611
        ob_start();
612
        GetPaid_Meta_Box_Invoice_Items::output_row( GetPaid_Meta_Box_Invoice_Items::get_columns( $invoice ), $item, $invoice );
613
        $row = ob_get_clean();
614
        wp_send_json_success( compact( 'row' ) );
615
    }
616
617
    /**
618
     * Deletes an invoice item.
619
     */
620
    public static function remove_invoice_item() {
621
622
        // Verify nonce.
623
        check_ajax_referer( 'wpinv-nonce' );
624
625
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
626
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
627
        }
628
629
        // We need an invoice and an item.
630
        if ( empty( $_POST['post_id'] ) || empty( $_POST['item_id'] ) ) {
631
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
632
        }
633
634
        // Fetch the invoice.
635
        $invoice = new WPInv_Invoice( trim( $_POST['post_id'] ) );
636
637
        // Ensure it exists and its not been paid for.
638
        if ( ! $invoice->get_id() || $invoice->is_paid() || $invoice->is_refunded() ) {
639
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
640
        }
641
642
        // Abort if the invoice does not have the specified item.
643
        $item = $invoice->get_item( (int) $_POST['item_id'] );
644
645
        if ( empty( $item ) ) {
646
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
647
        }
648
649
        $invoice->remove_item( (int) $_POST['item_id'] );
650
651
        // Update totals.
652
        $invoice->recalculate_total();
653
654
        // Save the invoice.
655
        $invoice->save();
656
657
        // Return an array of invoice items.
658
        $items = array();
659
660
        foreach ( $invoice->get_items() as $item ) {
661
            $items[] = $item->prepare_data_for_invoice_edit_ajax(  $invoice->get_currency()  );
662
        }
663
664
        wp_send_json_success( compact( 'items' ) );
665
    }
666
667
    /**
668
     * Adds an item to an invoice.
669
     */
670
    public static function recalculate_full_prices() {
671
672
        // Verify nonce.
673
        check_ajax_referer( 'wpinv-nonce' );
674
675
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
676
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
677
        }
678
679
        // We need an invoice and item.
680
        if ( empty( $_POST['post_id'] ) ) {
681
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
682
        }
683
684
        // Fetch the invoice.
685
        $invoice = new WPInv_Invoice( trim( $_POST['post_id'] ) );
686
        $alert   = false;
0 ignored issues
show
Unused Code introduced by
The assignment to $alert is dead and can be removed.
Loading history...
687
688
        // Ensure it exists and its not been paid for.
689
        if ( ! $invoice->get_id() || $invoice->is_paid() || $invoice->is_refunded() ) {
690
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
691
        }
692
693
        $invoice->set_items( array() );
694
695
        if ( ! empty( $_POST['getpaid_items'] ) ) {
696
697
            foreach ( $_POST['getpaid_items'] as $item_id => $args ) {
698
                $item = new GetPaid_Form_Item( $item_id );
699
700
                if ( $item->exists() ) {
701
                    $item->set_price( floatval( $args['price'] ) );
702
                    $item->set_quantity( floatval( $args['quantity'] ) );
703
                    $item->set_name( sanitize_text_field( $args['name'] ) );
704
                    $item->set_description( wp_kses_post( $args['description'] ) );
705
                    $invoice->add_item( $item );
706
                }
707
            }
708
709
        }
710
711
        $invoice->set_disable_taxes( ! empty( $_POST['disable_taxes'] ) );
712
713
        // Maybe set the country, state, currency.
714
        foreach ( array( 'country', 'state', 'currency', 'vat_number', 'wpinv_discount_code' ) as $key ) {
715
            if ( isset( $_POST[ $key ] ) ) {
716
                $_key   = str_replace( 'wpinv_', '', $key );
717
                $method = "set_$_key";
718
                $invoice->$method( sanitize_text_field( $_POST[ $key ] ) );
719
            }
720
        }
721
722
        $discount = new WPInv_Discount( $invoice->get_discount_code() );
723
        if ( $discount->exists() ) {
724
            $invoice->add_discount( getpaid_calculate_invoice_discount( $invoice, $discount ) );
725
        } else {
726
            $invoice->remove_discount( 'discount_code' );
727
        }
728
729
        // Save the invoice.
730
        $invoice->recalculate_total();
731
        $invoice->save();
732
        ob_start();
733
        GetPaid_Meta_Box_Invoice_Items::output( get_post( $invoice->get_id() ), $invoice );
734
        $table = ob_get_clean();
735
        wp_send_json_success( compact( 'table' ) );
736
    }
737
738
    /**
739
     * Adds an item to an invoice.
740
     */
741
    public static function admin_add_invoice_item() {
742
743
        // Verify nonce.
744
        check_ajax_referer( 'wpinv-nonce' );
745
746
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
747
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
748
        }
749
750
        // We need an invoice and item.
751
        if ( empty( $_POST['post_id'] ) || empty( $_POST['item_id'] ) ) {
752
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
753
        }
754
755
        // Fetch the invoice.
756
        $invoice = new WPInv_Invoice( trim( $_POST['post_id'] ) );
757
        $alert   = false;
0 ignored issues
show
Unused Code introduced by
The assignment to $alert is dead and can be removed.
Loading history...
758
759
        // Ensure it exists and its not been paid for.
760
        if ( ! $invoice->get_id() || $invoice->is_paid() || $invoice->is_refunded() ) {
761
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
762
        }
763
764
        // Add the item.
765
        $item  = new GetPaid_Form_Item( (int) $_POST['item_id'] );
766
        $error = $invoice->add_item( $item );
767
768
        if ( is_wp_error( $error ) ) {
769
            $alert = $error->get_error_message();
770
            wp_send_json_success( compact( 'alert' ) );
771
        }
772
773
        // Save the invoice.
774
        $invoice->recalculate_total();
775
        $invoice->save();
776
        ob_start();
777
        GetPaid_Meta_Box_Invoice_Items::output_row( GetPaid_Meta_Box_Invoice_Items::get_columns( $invoice ), $item, $invoice );
778
        $row = ob_get_clean();
779
        wp_send_json_success( compact( 'row' ) );
780
    }
781
782
    /**
783
     * Adds a items to an invoice.
784
     */
785
    public static function add_invoice_items() {
786
787
        // Verify nonce.
788
        check_ajax_referer( 'wpinv-nonce' );
789
790
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
791
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
792
        }
793
794
        // We need an invoice and items.
795
        if ( empty( $_POST['post_id'] ) || empty( $_POST['items'] ) ) {
796
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
797
        }
798
799
        // Fetch the invoice.
800
        $invoice = new WPInv_Invoice( trim( $_POST['post_id'] ) );
801
        $alert   = false;
802
803
        // Ensure it exists and its not been paid for.
804
        if ( ! $invoice->get_id() || $invoice->is_paid() || $invoice->is_refunded() ) {
805
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
806
        }
807
808
        // Add the items.
809
        foreach ( $_POST['items'] as $data ) {
810
811
            $item = new GetPaid_Form_Item( $data[ 'id' ] );
812
813
            if ( is_numeric( $data[ 'qty' ] ) && (float) $data[ 'qty' ] > 0 ) {
814
                $item->set_quantity( $data[ 'qty' ] );
815
            }
816
817
            if ( $item->get_id() > 0 ) {
818
                $error = $invoice->add_item( $item );
819
820
                if ( is_wp_error( $error ) ) {
821
                    $alert = $error->get_error_message();
822
                }
823
824
            }
825
826
        }
827
828
        // Save the invoice.
829
        $invoice->recalculate_total();
830
        $invoice->save();
831
832
        // Return an array of invoice items.
833
        $items = array();
834
835
        foreach ( $invoice->get_items() as $item ) {
836
            $items[] = $item->prepare_data_for_invoice_edit_ajax( $invoice->get_currency() );
837
        }
838
839
        wp_send_json_success( compact( 'items', 'alert' ) );
840
    }
841
842
    /**
843
     * Retrieves items that should be added to an invoice.
844
     */
845
    public static function get_invoicing_items() {
846
847
        // Verify nonce.
848
        check_ajax_referer( 'wpinv-nonce' );
849
850
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
851
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
852
        }
853
854
        // We need a search term.
855
        if ( empty( $_GET['search'] ) ) {
856
            wp_send_json_success( array() );
857
        }
858
859
        // Retrieve items.
860
        $item_args = array(
861
            'post_type'      => 'wpi_item',
862
            'orderby'        => 'title',
863
            'order'          => 'ASC',
864
            'posts_per_page' => -1,
865
            'post_status'    => array( 'publish' ),
866
            's'              => trim( $_GET['search'] ),
867
            'meta_query'     => array(
868
                array(
869
                    'key'       => '_wpinv_type',
870
                    'compare'   => '!=',
871
                    'value'     => 'package'
872
                )
873
            )
874
        );
875
876
        $items = get_posts( apply_filters( 'getpaid_ajax_invoice_items_query_args', $item_args ) );
877
        $data  = array();
878
879
        $is_payment_form = ( ! empty( $_GET['post_id'] ) && 'wpi_payment_form' == get_post_type( $_GET['post_id'] ) );
880
881
        foreach ( $items as $item ) {
882
            $item      = new GetPaid_Form_Item( $item );
883
            $data[] = array(
884
                'id'        => (int) $item->get_id(),
885
                'text'      => strip_tags( $item->get_name() ),
886
                'form_data' => $is_payment_form ? $item->prepare_data_for_use( false ) : '',
887
            );
888
        }
889
890
        wp_send_json_success( $data );
891
892
    }
893
894
    /**
895
     * Retrieves items that should be added to an invoice.
896
     */
897
    public static function get_customers() {
898
899
        // Verify nonce.
900
        check_ajax_referer( 'wpinv-nonce' );
901
902
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
903
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
904
        }
905
906
        // We need a search term.
907
        if ( empty( $_GET['search'] ) ) {
908
            wp_send_json_success( array() );
909
        }
910
911
        // Retrieve customers.
912
    
913
        $customer_args = array(
914
            'fields'         => array( 'ID', 'user_email', 'display_name' ),
915
            'orderby'        => 'display_name',
916
            'search'         => '*' . sanitize_text_field( $_GET['search'] ) . '*',
917
            'search_columns' => array( 'user_login', 'user_email', 'display_name' ),
918
        );
919
920
        $customers = get_users( apply_filters( 'getpaid_ajax_invoice_customers_query_args', $customer_args ) );
921
        $data      = array();
922
923
        foreach ( $customers as $customer ) {
924
            $data[] = array(
925
                'id'        => (int) $customer->ID,
926
                'text'      => strip_tags( sprintf( _x( '%1$s (%2$s)', 'user dropdown', 'invoicing' ), $customer->display_name, $customer->user_email ) ),
927
            );
928
        }
929
930
        wp_send_json_success( $data );
931
932
    }
933
934
    /**
935
     * Retrieves the states field for AUI forms.
936
     */
937
    public static function get_aui_states_field() {
938
939
        // Verify nonce.
940
        check_ajax_referer( 'wpinv-nonce' );
941
942
        // We need a country.
943
        if ( empty( $_GET['country'] ) ) {
944
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
945
        }
946
947
        $states = wpinv_get_country_states( sanitize_text_field( $_GET['country'] ) );
948
        $state  = isset( $_GET['state'] ) ? sanitize_text_field( $_GET['state'] ) : wpinv_get_default_state();
949
        $name   = isset( $_GET['name'] ) ? sanitize_text_field( $_GET['name'] ) : 'wpinv_state';
950
        $class  = isset( $_GET['class'] ) ? sanitize_text_field( $_GET['class'] ) : 'form-control-sm';
951
952
        if ( empty( $states ) ) {
953
954
            $html = aui()->input(
955
                array(
956
                    'type'        => 'text',
957
                    'id'          => 'wpinv_state',
958
                    'name'        => $name,
959
                    'label'       => __( 'State', 'invoicing' ),
960
                    'label_type'  => 'vertical',
961
                    'placeholder' => __( 'State', 'invoicing' ),
962
                    'class'       => $class,
963
                    'value'       => $state,
964
                )
965
            );
966
967
        } else {
968
969
            $html = aui()->select(
970
                array(
971
                    'id'          => 'wpinv_state',
972
                    'name'        => $name,
973
                    'label'       => __( 'State', 'invoicing' ),
974
                    'label_type'  => 'vertical',
975
                    'placeholder' => __( 'Select a state', 'invoicing' ),
976
                    'class'       => $class,
977
                    'value'       => $state,
978
                    'options'     => $states,
979
                    'data-allow-clear' => 'false',
980
                    'select2'          => true,
981
                )
982
            );
983
984
        }
985
986
        wp_send_json_success(
987
            array(
988
                'html'   => $html,
989
                'select' => ! empty ( $states )
990
            )
991
        );
992
993
    }
994
995
    /**
996
     * Refresh prices.
997
     *
998
     * @since 1.0.19
999
     */
1000
    public static function payment_form_refresh_prices() {
1001
1002
        // Check nonce.
1003
        check_ajax_referer( 'getpaid_form_nonce' );
1004
1005
        // ... form fields...
1006
        if ( empty( $_POST['getpaid_payment_form_submission'] ) ) {
1007
            _e( 'Error: Reload the page and try again.', 'invoicing' );
1008
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
1009
        }
1010
1011
        // Load the submission.
1012
        $submission = new GetPaid_Payment_Form_Submission();
1013
1014
        // Do we have an error?
1015
        if ( ! empty( $submission->last_error ) ) {
1016
            wp_send_json_error(
1017
                array(
1018
                    'code'  => $submission->last_error_code,
1019
                    'error' => $submission->last_error
1020
                )
1021
            );
1022
        }
1023
1024
        // Prepare the response.
1025
        $response = new GetPaid_Payment_Form_Submission_Refresh_Prices( $submission );
1026
1027
        // Filter the response.
1028
        $response = apply_filters( 'getpaid_payment_form_ajax_refresh_prices', $response->response, $submission );
1029
1030
        wp_send_json_success( $response );
1031
    }
1032
1033
}
1034
1035
WPInv_Ajax::init();