Completed
Branch FET/10339/exit-modal-for-ee-de... (81712e)
by
unknown
29:29 queued 13:19
created

Transactions_Admin_Page::getActionButtons()   C

Complexity

Conditions 13
Paths 113

Size

Total Lines 70
Code Lines 49

Duplication

Lines 20
Ratio 28.57 %

Importance

Changes 0
Metric Value
cc 13
eloc 49
nc 113
nop 1
dl 20
loc 70
rs 5.3272
c 0
b 0
f 0

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
use EventEspresso\core\exceptions\InvalidDataTypeException;
4
use EventEspresso\core\exceptions\InvalidInterfaceException;
5
6
defined('EVENT_ESPRESSO_VERSION') || exit;
7
8
/**
9
 * EE_Admin_Transactions class
10
 *
11
 * @package               Event Espresso
12
 * @subpackage            includes/core/admin/transactions/Transactions_Admin_Page.core.php
13
 * @author                Brent Christensen
14
 * ------------------------------------------------------------------------
15
 */
16
class Transactions_Admin_Page extends EE_Admin_Page
17
{
18
19
    /**
20
     * @var EE_Transaction
21
     */
22
    private $_transaction;
23
24
    /**
25
     * @var EE_Session
26
     */
27
    private $_session;
28
29
    /**
30
     * @var array $_txn_status
31
     */
32
    private static $_txn_status;
33
34
    /**
35
     * @var array $_pay_status
36
     */
37
    private static $_pay_status;
38
39
    /**
40
     * @var array $_existing_reg_payment_REG_IDs
41
     */
42
    protected $_existing_reg_payment_REG_IDs = null;
43
44
45
    /**
46
     * @Constructor
47
     * @access public
48
     * @param bool $routing
49
     * @throws EE_Error
50
     * @throws InvalidArgumentException
51
     * @throws ReflectionException
52
     * @throws InvalidDataTypeException
53
     * @throws InvalidInterfaceException
54
     */
55
    public function __construct($routing = true)
56
    {
57
        parent::__construct($routing);
58
    }
59
60
61
    /**
62
     *    _init_page_props
63
     *
64
     * @return void
65
     */
66 View Code Duplication
    protected function _init_page_props()
67
    {
68
        $this->page_slug        = TXN_PG_SLUG;
69
        $this->page_label       = esc_html__('Transactions', 'event_espresso');
70
        $this->_admin_base_url  = TXN_ADMIN_URL;
71
        $this->_admin_base_path = TXN_ADMIN;
72
    }
73
74
75
    /**
76
     *    _ajax_hooks
77
     *
78
     * @return void
79
     */
80
    protected function _ajax_hooks()
81
    {
82
        add_action('wp_ajax_espresso_apply_payment', array($this, 'apply_payments_or_refunds'));
83
        add_action('wp_ajax_espresso_apply_refund', array($this, 'apply_payments_or_refunds'));
84
        add_action('wp_ajax_espresso_delete_payment', array($this, 'delete_payment'));
85
    }
86
87
88
    /**
89
     *    _define_page_props
90
     *
91
     * @return void
92
     */
93 View Code Duplication
    protected function _define_page_props()
94
    {
95
        $this->_admin_page_title = $this->page_label;
96
        $this->_labels           = array(
97
            'buttons' => array(
98
                'add'    => esc_html__('Add New Transaction', 'event_espresso'),
99
                'edit'   => esc_html__('Edit Transaction', 'event_espresso'),
100
                'delete' => esc_html__('Delete Transaction', 'event_espresso'),
101
            ),
102
        );
103
    }
104
105
106
    /**
107
     *        grab url requests and route them
108
     *
109
     * @access private
110
     * @return void
111
     * @throws EE_Error
112
     * @throws InvalidArgumentException
113
     * @throws InvalidDataTypeException
114
     * @throws InvalidInterfaceException
115
     */
116
    public function _set_page_routes()
117
    {
118
119
        $this->_set_transaction_status_array();
120
121
        $txn_id = ! empty($this->_req_data['TXN_ID'])
122
                  && ! is_array($this->_req_data['TXN_ID'])
123
            ? $this->_req_data['TXN_ID']
124
            : 0;
125
126
        $this->_page_routes = array(
127
128
            'default' => array(
129
                'func'       => '_transactions_overview_list_table',
130
                'capability' => 'ee_read_transactions',
131
            ),
132
133
            'view_transaction' => array(
134
                'func'       => '_transaction_details',
135
                'capability' => 'ee_read_transaction',
136
                'obj_id'     => $txn_id,
137
            ),
138
139
            'send_payment_reminder' => array(
140
                'func'       => '_send_payment_reminder',
141
                'noheader'   => true,
142
                'capability' => 'ee_send_message',
143
            ),
144
145
            'espresso_apply_payment' => array(
146
                'func'       => 'apply_payments_or_refunds',
147
                'noheader'   => true,
148
                'capability' => 'ee_edit_payments',
149
            ),
150
151
            'espresso_apply_refund' => array(
152
                'func'       => 'apply_payments_or_refunds',
153
                'noheader'   => true,
154
                'capability' => 'ee_edit_payments',
155
            ),
156
157
            'espresso_delete_payment' => array(
158
                'func'       => 'delete_payment',
159
                'noheader'   => true,
160
                'capability' => 'ee_delete_payments',
161
            ),
162
163
        );
164
    }
165
166
167
    protected function _set_page_config()
168
    {
169
        $this->_page_config = array(
170
            'default'          => array(
171
                'nav'           => array(
172
                    'label' => esc_html__('Overview', 'event_espresso'),
173
                    'order' => 10,
174
                ),
175
                'list_table'    => 'EE_Admin_Transactions_List_Table',
176
                'help_tabs'     => array(
177
                    'transactions_overview_help_tab'                       => array(
178
                        'title'    => esc_html__('Transactions Overview', 'event_espresso'),
179
                        'filename' => 'transactions_overview',
180
                    ),
181
                    'transactions_overview_table_column_headings_help_tab' => array(
182
                        'title'    => esc_html__('Transactions Table Column Headings', 'event_espresso'),
183
                        'filename' => 'transactions_overview_table_column_headings',
184
                    ),
185
                    'transactions_overview_views_filters_help_tab'         => array(
186
                        'title'    => esc_html__('Transaction Views & Filters & Search', 'event_espresso'),
187
                        'filename' => 'transactions_overview_views_filters_search',
188
                    ),
189
                ),
190
                'help_tour'     => array('Transactions_Overview_Help_Tour'),
191
                /**
192
                 * commented out because currently we are not displaying tips for transaction list table status but this
193
                 * may change in a later iteration so want to keep the code for then.
194
                 */
195
                //'qtips' => array( 'Transactions_List_Table_Tips' ),
196
                'require_nonce' => false,
197
            ),
198
            'view_transaction' => array(
199
                'nav'       => array(
200
                    'label'      => esc_html__('View Transaction', 'event_espresso'),
201
                    'order'      => 5,
202
                    'url'        => isset($this->_req_data['TXN_ID'])
203
                        ? add_query_arg(array('TXN_ID' => $this->_req_data['TXN_ID']), $this->_current_page_view_url)
204
                        : $this->_admin_base_url,
205
                    'persistent' => false,
206
                ),
207
                'help_tabs' => array(
208
                    'transactions_view_transaction_help_tab'                                              => array(
209
                        'title'    => esc_html__('View Transaction', 'event_espresso'),
210
                        'filename' => 'transactions_view_transaction',
211
                    ),
212
                    'transactions_view_transaction_transaction_details_table_help_tab'                    => array(
213
                        'title'    => esc_html__('Transaction Details Table', 'event_espresso'),
214
                        'filename' => 'transactions_view_transaction_transaction_details_table',
215
                    ),
216
                    'transactions_view_transaction_attendees_registered_help_tab'                         => array(
217
                        'title'    => esc_html__('Attendees Registered', 'event_espresso'),
218
                        'filename' => 'transactions_view_transaction_attendees_registered',
219
                    ),
220
                    'transactions_view_transaction_views_primary_registrant_billing_information_help_tab' => array(
221
                        'title'    => esc_html__('Primary Registrant & Billing Information', 'event_espresso'),
222
                        'filename' => 'transactions_view_transaction_primary_registrant_billing_information',
223
                    ),
224
                ),
225
                'qtips'     => array('Transaction_Details_Tips'),
226
                'help_tour' => array('Transaction_Details_Help_Tour'),
227
                'metaboxes' => array('_transaction_details_metaboxes'),
228
229
                'require_nonce' => false,
230
            ),
231
        );
232
    }
233
234
235
    /**
236
     * The below methods aren't used by this class currently
237
     */
238
    protected function _add_screen_options()
239
    {
240
        //noop
241
    }
242
243
    protected function _add_feature_pointers()
244
    {
245
        //noop
246
    }
247
248
    public function admin_init()
249
    {
250
        // IF a registration was JUST added via the admin...
251
        if (isset(
252
            $this->_req_data['redirect_from'],
253
            $this->_req_data['EVT_ID'],
254
            $this->_req_data['event_name']
255
        )) {
256
            // then set a cookie so that we can block any attempts to use
257
            // the back button as a way to enter another registration.
258
            setcookie(
259
                'ee_registration_added',
260
                $this->_req_data['EVT_ID'], time() + WEEK_IN_SECONDS, '/'
261
            );
262
            // and update the global
263
            $_COOKIE['ee_registration_added'] = $this->_req_data['EVT_ID'];
264
        }
265
        EE_Registry::$i18n_js_strings['invalid_server_response'] = esc_html__(
266
            'An error occurred! Your request may have been processed, but a valid response from the server was not received. Please refresh the page and try again.',
267
            'event_espresso'
268
        );
269
        EE_Registry::$i18n_js_strings['error_occurred']          = esc_html__(
270
            'An error occurred! Please refresh the page and try again.',
271
            'event_espresso'
272
        );
273
        EE_Registry::$i18n_js_strings['txn_status_array']        = self::$_txn_status;
274
        EE_Registry::$i18n_js_strings['pay_status_array']        = self::$_pay_status;
275
        EE_Registry::$i18n_js_strings['payments_total']          = esc_html__('Payments Total', 'event_espresso');
276
        EE_Registry::$i18n_js_strings['transaction_overpaid']    = esc_html__(
277
            'This transaction has been overpaid ! Payments Total',
278
            'event_espresso'
279
        );
280
    }
281
282
    public function admin_notices()
283
    {
284
        //noop
285
    }
286
287
    public function admin_footer_scripts()
288
    {
289
        //noop
290
    }
291
292
293
    /**
294
     * _set_transaction_status_array
295
     * sets list of transaction statuses
296
     *
297
     * @access private
298
     * @return void
299
     * @throws EE_Error
300
     * @throws InvalidArgumentException
301
     * @throws InvalidDataTypeException
302
     * @throws InvalidInterfaceException
303
     */
304
    private function _set_transaction_status_array()
305
    {
306
        self::$_txn_status = EEM_Transaction::instance()->status_array(true);
307
    }
308
309
310
    /**
311
     * get_transaction_status_array
312
     * return the transaction status array for wp_list_table
313
     *
314
     * @access public
315
     * @return array
316
     */
317
    public function get_transaction_status_array()
318
    {
319
        return self::$_txn_status;
320
    }
321
322
323
    /**
324
     *    get list of payment statuses
325
     *
326
     * @access private
327
     * @return void
328
     * @throws EE_Error
329
     * @throws InvalidArgumentException
330
     * @throws InvalidDataTypeException
331
     * @throws InvalidInterfaceException
332
     */
333
    private function _get_payment_status_array()
334
    {
335
        self::$_pay_status                      = EEM_Payment::instance()->status_array(true);
336
        $this->_template_args['payment_status'] = self::$_pay_status;
337
338
    }
339
340
341
    /**
342
     *    _add_screen_options_default
343
     *
344
     * @access protected
345
     * @return void
346
     * @throws InvalidArgumentException
347
     * @throws InvalidDataTypeException
348
     * @throws InvalidInterfaceException
349
     */
350
    protected function _add_screen_options_default()
351
    {
352
        $this->_per_page_screen_option();
353
    }
354
355
356
    /**
357
     * load_scripts_styles
358
     *
359
     * @access public
360
     * @return void
361
     */
362
    public function load_scripts_styles()
363
    {
364
        //enqueue style
365
        wp_register_style(
366
            'espresso_txn',
367
            TXN_ASSETS_URL . 'espresso_transactions_admin.css',
368
            array(),
369
            EVENT_ESPRESSO_VERSION
370
        );
371
        wp_enqueue_style('espresso_txn');
372
        //scripts
373
        wp_register_script('espresso_txn', TXN_ASSETS_URL . 'espresso_transactions_admin.js', array(
374
            'ee_admin_js',
375
            'ee-datepicker',
376
            'jquery-ui-datepicker',
377
            'jquery-ui-draggable',
378
            'ee-dialog',
379
            'ee-accounting',
380
            'ee-serialize-full-array',
381
        ), EVENT_ESPRESSO_VERSION, true);
382
        wp_enqueue_script('espresso_txn');
383
    }
384
385
386
    /**
387
     *    load_scripts_styles_view_transaction
388
     *
389
     * @access public
390
     * @return void
391
     */
392
    public function load_scripts_styles_view_transaction()
393
    {
394
        //styles
395
        wp_enqueue_style('espresso-ui-theme');
396
    }
397
398
399
    /**
400
     *    load_scripts_styles_default
401
     *
402
     * @access public
403
     * @return void
404
     */
405
    public function load_scripts_styles_default()
406
    {
407
        //styles
408
        wp_enqueue_style('espresso-ui-theme');
409
    }
410
411
412
    /**
413
     *    _set_list_table_views_default
414
     *
415
     * @access protected
416
     * @return void
417
     */
418
    protected function _set_list_table_views_default()
419
    {
420
        $this->_views = array(
421
            'all'       => array(
422
                'slug'  => 'all',
423
                'label' => esc_html__('View All Transactions', 'event_espresso'),
424
                'count' => 0,
425
            ),
426
            'abandoned' => array(
427
                'slug'  => 'abandoned',
428
                'label' => esc_html__('Abandoned Transactions', 'event_espresso'),
429
                'count' => 0,
430
            ),
431
            'failed'    => array(
432
                'slug'  => 'failed',
433
                'label' => esc_html__('Failed Transactions', 'event_espresso'),
434
                'count' => 0,
435
            ),
436
        );
437
    }
438
439
440
    /**
441
     * _set_transaction_object
442
     * This sets the _transaction property for the transaction details screen
443
     *
444
     * @access private
445
     * @return void
446
     * @throws EE_Error
447
     * @throws InvalidArgumentException
448
     * @throws RuntimeException
449
     * @throws InvalidDataTypeException
450
     * @throws InvalidInterfaceException
451
     * @throws ReflectionException
452
     */
453
    private function _set_transaction_object()
454
    {
455
        if ($this->_transaction instanceof EE_Transaction) {
456
            return;
457
        } //get out we've already set the object
458
459
        $TXN_ID = ! empty($this->_req_data['TXN_ID'])
460
            ? absint($this->_req_data['TXN_ID'])
461
            : false;
462
463
        //get transaction object
464
        $this->_transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
465
        $this->_session     = $this->_transaction instanceof EE_Transaction
466
            ? $this->_transaction->get('TXN_session_data')
467
            : null;
468
        $this->_transaction->verify_abandoned_transaction_status();
469
470 View Code Duplication
        if (! $this->_transaction instanceof EE_Transaction) {
471
            $error_msg = sprintf(
472
                esc_html__(
473
                    'An error occurred and the details for the transaction with the ID # %d could not be retrieved.',
474
                    'event_espresso'
475
                ),
476
                $TXN_ID
477
            );
478
            EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
479
        }
480
    }
481
482
483
    /**
484
     *    _transaction_legend_items
485
     *
486
     * @access protected
487
     * @return array
488
     * @throws EE_Error
489
     * @throws InvalidArgumentException
490
     * @throws ReflectionException
491
     * @throws InvalidDataTypeException
492
     * @throws InvalidInterfaceException
493
     */
494
    protected function _transaction_legend_items()
495
    {
496
        EE_Registry::instance()->load_helper('MSG_Template');
497
        $items = array();
498
499 View Code Duplication
        if (EE_Registry::instance()->CAP->current_user_can(
500
            'ee_read_global_messages',
501
            'view_filtered_messages'
502
        )) {
503
            $related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
504
            if (is_array($related_for_icon)
505
                && isset($related_for_icon['css_class'], $related_for_icon['label'])
506
            ) {
507
                $items['view_related_messages'] = array(
508
                    'class' => $related_for_icon['css_class'],
509
                    'desc'  => $related_for_icon['label'],
510
                );
511
            }
512
        }
513
514
        $items = apply_filters(
515
            'FHEE__Transactions_Admin_Page___transaction_legend_items__items',
516
            array_merge(
517
                $items,
518
                array(
519
                    'view_details'          => array(
520
                        'class' => 'dashicons dashicons-cart',
521
                        'desc'  => esc_html__('View Transaction Details', 'event_espresso'),
522
                    ),
523
                    'view_invoice'          => array(
524
                        'class' => 'dashicons dashicons-media-spreadsheet',
525
                        'desc'  => esc_html__('View Transaction Invoice', 'event_espresso'),
526
                    ),
527
                    'view_receipt'          => array(
528
                        'class' => 'dashicons dashicons-media-default',
529
                        'desc'  => esc_html__('View Transaction Receipt', 'event_espresso'),
530
                    ),
531
                    'view_registration'     => array(
532
                        'class' => 'dashicons dashicons-clipboard',
533
                        'desc'  => esc_html__('View Registration Details', 'event_espresso'),
534
                    ),
535
                    'payment_overview_link' => array(
536
                        'class' => 'dashicons dashicons-money',
537
                        'desc'  => esc_html__('Make Payment on Frontend', 'event_espresso'),
538
                    ),
539
                )
540
            )
541
        );
542
543
        if (EE_Registry::instance()->CAP->current_user_can(
544
            'ee_send_message',
545
            'espresso_transactions_send_payment_reminder'
546
        )) {
547
            if (EEH_MSG_Template::is_mt_active('payment_reminder')) {
548
                $items['send_payment_reminder'] = array(
549
                    'class' => 'dashicons dashicons-email-alt',
550
                    'desc'  => esc_html__('Send Payment Reminder', 'event_espresso'),
551
                );
552
            } else {
553
                $items['blank*'] = array(
554
                    'class' => '',
555
                    'desc'  => '',
556
                );
557
            }
558
        } else {
559
            $items['blank*'] = array(
560
                'class' => '',
561
                'desc'  => '',
562
            );
563
        }
564
        $more_items = apply_filters(
565
            'FHEE__Transactions_Admin_Page___transaction_legend_items__more_items',
566
            array(
567
                'overpaid'   => array(
568
                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::overpaid_status_code,
569
                    'desc'  => EEH_Template::pretty_status(
570
                        EEM_Transaction::overpaid_status_code,
571
                        false,
572
                        'sentence'
573
                    ),
574
                ),
575
                'complete'   => array(
576
                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::complete_status_code,
577
                    'desc'  => EEH_Template::pretty_status(
578
                        EEM_Transaction::complete_status_code,
579
                        false,
580
                        'sentence'
581
                    ),
582
                ),
583
                'incomplete' => array(
584
                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::incomplete_status_code,
585
                    'desc'  => EEH_Template::pretty_status(
586
                        EEM_Transaction::incomplete_status_code,
587
                        false,
588
                        'sentence'
589
                    ),
590
                ),
591
                'abandoned'  => array(
592
                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::abandoned_status_code,
593
                    'desc'  => EEH_Template::pretty_status(
594
                        EEM_Transaction::abandoned_status_code,
595
                        false,
596
                        'sentence'
597
                    ),
598
                ),
599
                'failed'     => array(
600
                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::failed_status_code,
601
                    'desc'  => EEH_Template::pretty_status(
602
                        EEM_Transaction::failed_status_code,
603
                        false,
604
                        'sentence'
605
                    ),
606
                ),
607
            )
608
        );
609
610
        return array_merge($items, $more_items);
611
    }
612
613
614
    /**
615
     *    _transactions_overview_list_table
616
     *
617
     * @access protected
618
     * @return void
619
     * @throws DomainException
620
     * @throws EE_Error
621
     * @throws InvalidArgumentException
622
     * @throws InvalidDataTypeException
623
     * @throws InvalidInterfaceException
624
     * @throws ReflectionException
625
     */
626
    protected function _transactions_overview_list_table()
627
    {
628
        $this->_admin_page_title = esc_html__('Transactions', 'event_espresso');
629
        $event = isset($this->_req_data['EVT_ID'])
630
            ? EEM_Event::instance()->get_one_by_ID($this->_req_data['EVT_ID'])
631
            : null;
632
        $this->_template_args['admin_page_header'] = $event instanceof EE_Event
633
            ? sprintf(
634
                esc_html__(
635
                    '%sViewing Transactions for the Event: %s%s',
636
                    'event_espresso'
637
                ),
638
                '<h3>',
639
                '<a href="'
640
                . EE_Admin_Page::add_query_args_and_nonce(
641
                    array('action' => 'edit', 'post' => $event->ID()),
642
                    EVENTS_ADMIN_URL
643
                )
644
                . '" title="'
645
                . esc_attr__(
646
                    'Click to Edit event',
647
                    'event_espresso'
648
                )
649
                . '">' . $event->get('EVT_name') . '</a>',
650
                '</h3>'
651
            )
652
            : '';
653
        $this->_template_args['after_list_table']  = $this->_display_legend($this->_transaction_legend_items());
654
        $this->display_admin_list_table_page_with_no_sidebar();
655
    }
656
657
658
    /**
659
     *    _transaction_details
660
     * generates HTML for the View Transaction Details Admin page
661
     *
662
     * @access protected
663
     * @return void
664
     * @throws DomainException
665
     * @throws EE_Error
666
     * @throws InvalidArgumentException
667
     * @throws InvalidDataTypeException
668
     * @throws InvalidInterfaceException
669
     * @throws RuntimeException
670
     * @throws ReflectionException
671
     */
672
    protected function _transaction_details()
673
    {
674
        do_action('AHEE__Transactions_Admin_Page__transaction_details__start', $this->_transaction);
675
676
        $this->_set_transaction_status_array();
677
678
        $this->_template_args                      = array();
679
        $this->_template_args['transactions_page'] = $this->_wp_page_slug;
680
681
        $this->_set_transaction_object();
682
683
        $primary_registration = $this->_transaction->primary_registration();
684
        $attendee = $primary_registration instanceof EE_Registration
0 ignored issues
show
Unused Code introduced by
$attendee is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
685
            ? $primary_registration->attendee()
686
            : null;
687
688
        $this->_template_args['txn_nmbr']['value'] = $this->_transaction->ID();
689
        $this->_template_args['txn_nmbr']['label'] = esc_html__('Transaction Number', 'event_espresso');
690
691
        $this->_template_args['txn_datetime']['value'] = $this->_transaction->get_i18n_datetime('TXN_timestamp');
692
        $this->_template_args['txn_datetime']['label'] = esc_html__('Date', 'event_espresso');
693
694
        $this->_template_args['txn_status']['value'] = self::$_txn_status[$this->_transaction->get('STS_ID')];
695
        $this->_template_args['txn_status']['label'] = esc_html__('Transaction Status', 'event_espresso');
696
        $this->_template_args['txn_status']['class'] = 'status-' . $this->_transaction->get('STS_ID');
697
698
        $this->_template_args['grand_total'] = $this->_transaction->get('TXN_total');
699
        $this->_template_args['total_paid']  = $this->_transaction->get('TXN_paid');
700
701
        $amount_due = $this->_transaction->get('TXN_total') - $this->_transaction->get('TXN_paid');
702
        $this->_template_args['amount_due'] = EEH_Template::format_currency(
703
            $amount_due,
704
            true
705
        );
706
        if (EE_Registry::instance()->CFG->currency->sign_b4) {
707
            $this->_template_args['amount_due'] = EE_Registry::instance()->CFG->currency->sign
708
                                                  . $this->_template_args['amount_due'];
709
        } else {
710
            $this->_template_args['amount_due'] .= EE_Registry::instance()->CFG->currency->sign;
711
        }
712
        $this->_template_args['amount_due_class'] = '';
713
714
        if ($this->_transaction->get('TXN_paid') == $this->_transaction->get('TXN_total')) {
715
            // paid in full
716
            $this->_template_args['amount_due'] = false;
717 View Code Duplication
        } elseif ($this->_transaction->get('TXN_paid') > $this->_transaction->get('TXN_total')) {
718
            // overpaid
719
            $this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn';
720
        } elseif ($this->_transaction->get('TXN_total') > 0
721
                  && $this->_transaction->get('TXN_paid') > 0
722
        ) {
723
            // monies owing
724
            $this->_template_args['amount_due_class'] = 'txn-overview-part-payment-spn';
725 View Code Duplication
        } elseif ($this->_transaction->get('TXN_total') > 0
726
                  && $this->_transaction->get('TXN_paid') == 0
727
        ) {
728
            // no payments made yet
729
            $this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn';
730
        } elseif ($this->_transaction->get('TXN_total') == 0) {
731
            // free event
732
            $this->_template_args['amount_due'] = false;
733
        }
734
735
        $payment_method = $this->_transaction->payment_method();
736
737
        $this->_template_args['method_of_payment_name'] = $payment_method instanceof EE_Payment_Method
738
            ? $payment_method->admin_name()
739
            : esc_html__('Unknown', 'event_espresso');
740
741
        $this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
742
        // link back to overview
743
        $this->_template_args['txn_overview_url'] = ! empty($_SERVER['HTTP_REFERER'])
744
            ? $_SERVER['HTTP_REFERER']
745
            : TXN_ADMIN_URL;
746
747
748
        // next link
749
        $next_txn                                 = $this->_transaction->next(
750
            null,
751
            array(array('STS_ID' => array('!=', EEM_Transaction::failed_status_code))),
752
            'TXN_ID'
753
        );
754
        $this->_template_args['next_transaction'] = $next_txn
755
            ? $this->_next_link(
756
                EE_Admin_Page::add_query_args_and_nonce(
757
                    array('action' => 'view_transaction', 'TXN_ID' => $next_txn['TXN_ID']),
758
                    TXN_ADMIN_URL
759
                ),
760
                'dashicons dashicons-arrow-right ee-icon-size-22'
761
            )
762
            : '';
763
        // previous link
764
        $previous_txn                                 = $this->_transaction->previous(
765
            null,
766
            array(array('STS_ID' => array('!=', EEM_Transaction::failed_status_code))),
767
            'TXN_ID'
768
        );
769
        $this->_template_args['previous_transaction'] = $previous_txn
770
            ? $this->_previous_link(
771
                EE_Admin_Page::add_query_args_and_nonce(
772
                    array('action' => 'view_transaction', 'TXN_ID' => $previous_txn['TXN_ID']),
773
                    TXN_ADMIN_URL
774
                ),
775
                'dashicons dashicons-arrow-left ee-icon-size-22'
776
            )
777
            : '';
778
779
        // were we just redirected here after adding a new registration ???
780
        if (isset(
781
            $this->_req_data['redirect_from'],
782
            $this->_req_data['EVT_ID'],
783
            $this->_req_data['event_name']
784
        )) {
785
            if (EE_Registry::instance()->CAP->current_user_can(
786
                'ee_edit_registrations',
787
                'espresso_registrations_new_registration',
788
                $this->_req_data['EVT_ID']
789
            )) {
790
                $this->_admin_page_title .= '<a id="add-new-registration" class="add-new-h2 button-primary" href="';
791
                $this->_admin_page_title .= EE_Admin_Page::add_query_args_and_nonce(
792
                    array(
793
                        'page'     => 'espresso_registrations',
794
                        'action'   => 'new_registration',
795
                        'return'   => 'default',
796
                        'TXN_ID'   => $this->_transaction->ID(),
797
                        'event_id' => $this->_req_data['EVT_ID'],
798
                    ),
799
                    REG_ADMIN_URL
800
                );
801
                $this->_admin_page_title .= '">';
802
803
                $this->_admin_page_title .= sprintf(
804
                    esc_html__('Add Another New Registration to Event: "%1$s" ?', 'event_espresso'),
805
                    htmlentities(urldecode($this->_req_data['event_name']), ENT_QUOTES, 'UTF-8')
806
                );
807
                $this->_admin_page_title .= '</a>';
808
            }
809
            EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
810
        }
811
        // grab messages at the last second
812
        $this->_template_args['notices'] = EE_Error::get_notices();
813
        // path to template
814
        $template_path                             = TXN_TEMPLATE_PATH . 'txn_admin_details_header.template.php';
815
        $this->_template_args['admin_page_header'] = EEH_Template::display_template(
816
            $template_path,
817
            $this->_template_args,
818
            true
819
        );
820
821
        // the details template wrapper
822
        $this->display_admin_page_with_sidebar();
823
824
    }
825
826
827
    /**
828
     *        _transaction_details_metaboxes
829
     *
830
     * @access protected
831
     * @return void
832
     * @throws EE_Error
833
     * @throws InvalidArgumentException
834
     * @throws InvalidDataTypeException
835
     * @throws InvalidInterfaceException
836
     * @throws RuntimeException
837
     * @throws ReflectionException
838
     */
839
    protected function _transaction_details_metaboxes()
840
    {
841
842
        $this->_set_transaction_object();
843
844
        add_meta_box(
845
            'edit-txn-details-mbox',
846
            esc_html__('Transaction Details', 'event_espresso'),
847
            array($this, 'txn_details_meta_box'),
848
            $this->_wp_page_slug,
849
            'normal',
850
            'high'
851
        );
852
        add_meta_box(
853
            'edit-txn-attendees-mbox',
854
            esc_html__('Attendees Registered in this Transaction', 'event_espresso'),
855
            array($this, 'txn_attendees_meta_box'),
856
            $this->_wp_page_slug,
857
            'normal',
858
            'high',
859
            array('TXN_ID' => $this->_transaction->ID())
860
        );
861
        add_meta_box(
862
            'edit-txn-registrant-mbox',
863
            esc_html__('Primary Contact', 'event_espresso'),
864
            array($this, 'txn_registrant_side_meta_box'),
865
            $this->_wp_page_slug,
866
            'side',
867
            'high'
868
        );
869
        add_meta_box(
870
            'edit-txn-billing-info-mbox',
871
            esc_html__('Billing Information', 'event_espresso'),
872
            array($this, 'txn_billing_info_side_meta_box'),
873
            $this->_wp_page_slug,
874
            'side',
875
            'high'
876
        );
877
    }
878
879
880
    /**
881
     * Callback for transaction actions metabox.
882
     *
883
     * @param EE_Transaction|null $transaction
884
     * @throws DomainException
885
     * @throws EE_Error
886
     * @throws InvalidArgumentException
887
     * @throws InvalidDataTypeException
888
     * @throws InvalidInterfaceException
889
     * @throws ReflectionException
890
     * @throws RuntimeException
891
     */
892
    public function getActionButtons(EE_Transaction $transaction = null)
893
    {
894
        $content = '';
895
        $actions = array();
896
        if (! $transaction instanceof EE_Transaction) {
897
            return $content;
898
        }
899
        /** @var EE_Registration $primary_registration */
900
        $primary_registration = $transaction->primary_registration();
901
        $attendee = $primary_registration instanceof EE_Registration
902
            ? $primary_registration->attendee()
903
            : null;
904
905
        if ($attendee instanceof EE_Attendee
906
            && EE_Registry::instance()->CAP->current_user_can(
907
                'ee_send_message',
908
                'espresso_transactions_send_payment_reminder'
909
            )
910
        ) {
911
            $actions['payment_reminder'] =
912
                EEH_MSG_Template::is_mt_active('payment_reminder')
913
                && $this->_transaction->get('STS_ID') !== EEM_Transaction::complete_status_code
914
                && $this->_transaction->get('STS_ID') !== EEM_Transaction::overpaid_status_code
915
                    ? EEH_Template::get_button_or_link(
916
                        EE_Admin_Page::add_query_args_and_nonce(
917
                            array(
918
                                'action'      => 'send_payment_reminder',
919
                                'TXN_ID'      => $this->_transaction->ID(),
920
                                'redirect_to' => 'view_transaction',
921
                            ),
922
                            TXN_ADMIN_URL
923
                        ),
924
                        esc_html__(' Send Payment Reminder', 'event_espresso'),
925
                        'button secondary-button',
926
                        'dashicons dashicons-email-alt'
927
                    )
928
                    : '';
929
        }
930
931 View Code Duplication
        if ($primary_registration instanceof EE_Registration
932
            && EEH_MSG_Template::is_mt_active('receipt')
933
        ) {
934
            $actions['receipt'] = EEH_Template::get_button_or_link(
935
                $primary_registration->receipt_url(),
936
                esc_html__('View Receipt', 'event_espresso'),
937
                'button secondary-button',
938
                'dashicons dashicons-media-default'
939
            );
940
        }
941
942 View Code Duplication
        if ($primary_registration instanceof EE_Registration
943
            && EEH_MSG_Template::is_mt_active('invoice')
944
        ) {
945
            $actions['invoice'] = EEH_Template::get_button_or_link(
946
                $primary_registration->invoice_url(),
947
                esc_html__('View Invoice', 'event_espresso'),
948
                'button secondary-button',
949
                'dashicons dashicons-media-spreadsheet'
950
            );
951
        }
952
        $actions = array_filter(
953
            apply_filters('FHEE__Transactions_Admin_Page__getActionButtons__actions', $actions, $transaction)
954
        );
955
        if ($actions) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $actions of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
956
            $content = '<ul>';
957
            $content .= '<li>' . implode('</li><li>', $actions) . '</li>';
958
            $content .= '</uL>';
959
        }
960
        return $content;
961
    }
962
963
964
    /**
965
     * txn_details_meta_box
966
     * generates HTML for the Transaction main meta box
967
     *
968
     * @return void
969
     * @throws DomainException
970
     * @throws EE_Error
971
     * @throws InvalidArgumentException
972
     * @throws InvalidDataTypeException
973
     * @throws InvalidInterfaceException
974
     * @throws RuntimeException
975
     * @throws ReflectionException
976
     */
977
    public function txn_details_meta_box()
978
    {
979
        $this->_set_transaction_object();
980
        $this->_template_args['TXN_ID']   = $this->_transaction->ID();
981
        $this->_template_args['attendee'] = $this->_transaction->primary_registration() instanceof EE_Registration
982
            ? $this->_transaction->primary_registration()->attendee()
983
            : null;
984
        $this->_template_args['can_edit_payments'] = EE_Registry::instance()->CAP->current_user_can(
985
            'ee_edit_payments',
986
            'apply_payment_or_refund_from_registration_details'
987
        );
988
        $this->_template_args['can_delete_payments'] = EE_Registry::instance()->CAP->current_user_can(
989
            'ee_delete_payments',
990
            'delete_payment_from_registration_details'
991
        );
992
993
        //get line table
994
        EEH_Autoloader::register_line_item_display_autoloaders();
995
        $Line_Item_Display                       = new EE_Line_Item_Display(
996
            'admin_table',
997
            'EE_Admin_Table_Line_Item_Display_Strategy'
998
        );
999
        $this->_template_args['line_item_table'] = $Line_Item_Display->display_line_item(
1000
            $this->_transaction->total_line_item()
1001
        );
1002
        $this->_template_args['REG_code']        = $this->_transaction->get_first_related('Registration')
1003
                                                                      ->get('REG_code');
1004
1005
        // process taxes
1006
        $taxes                         = $this->_transaction->get_many_related(
1007
            'Line_Item',
1008
            array(array('LIN_type' => EEM_Line_Item::type_tax))
1009
        );
1010
        $this->_template_args['taxes'] = ! empty($taxes) ? $taxes : false;
1011
1012
        $this->_template_args['grand_total']     = EEH_Template::format_currency(
1013
            $this->_transaction->get('TXN_total'),
1014
            false,
1015
            false
1016
        );
1017
        $this->_template_args['grand_raw_total'] = $this->_transaction->get('TXN_total');
1018
        $this->_template_args['TXN_status']      = $this->_transaction->get('STS_ID');
1019
1020
        // process payment details
1021
        $payments = $this->_transaction->get_many_related('Payment');
1022
        if (! empty($payments)) {
1023
            $this->_template_args['payments']              = $payments;
1024
            $this->_template_args['existing_reg_payments'] = $this->_get_registration_payment_IDs($payments);
1025
        } else {
1026
            $this->_template_args['payments']              = false;
1027
            $this->_template_args['existing_reg_payments'] = array();
1028
        }
1029
1030
        $this->_template_args['edit_payment_url']   = add_query_arg(array('action' => 'edit_payment'), TXN_ADMIN_URL);
1031
        $this->_template_args['delete_payment_url'] = add_query_arg(
1032
            array('action' => 'espresso_delete_payment'),
1033
            TXN_ADMIN_URL
1034
        );
1035
1036
        if (isset($txn_details['invoice_number'])) {
0 ignored issues
show
Bug introduced by
The variable $txn_details seems to never exist, and therefore isset should always return false. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
1037
            $this->_template_args['txn_details']['invoice_number']['value'] = $this->_template_args['REG_code'];
1038
            $this->_template_args['txn_details']['invoice_number']['label'] = esc_html__(
1039
                'Invoice Number',
1040
                'event_espresso'
1041
            );
1042
        }
1043
1044
        $this->_template_args['txn_details']['registration_session']['value'] = $this->_transaction
1045
            ->get_first_related('Registration')
1046
            ->get('REG_session');
1047
        $this->_template_args['txn_details']['registration_session']['label'] = esc_html__(
1048
            'Registration Session',
1049
            'event_espresso'
1050
        );
1051
1052
        $this->_template_args['txn_details']['ip_address']['value'] = isset($this->_session['ip_address'])
1053
            ? $this->_session['ip_address']
1054
            : '';
1055
        $this->_template_args['txn_details']['ip_address']['label'] = esc_html__(
1056
            'Transaction placed from IP',
1057
            'event_espresso'
1058
        );
1059
1060
        $this->_template_args['txn_details']['user_agent']['value'] = isset($this->_session['user_agent'])
1061
            ? $this->_session['user_agent']
1062
            : '';
1063
        $this->_template_args['txn_details']['user_agent']['label'] = esc_html__(
1064
            'Registrant User Agent',
1065
            'event_espresso'
1066
        );
1067
1068
        $reg_steps = '<ul>';
1069
        foreach ($this->_transaction->reg_steps() as $reg_step => $reg_step_status) {
1070
            if ($reg_step_status === true) {
1071
                $reg_steps .= '<li style="color:#70cc50">'
1072
                              . sprintf(
1073
                                  esc_html__('%1$s : Completed', 'event_espresso'),
1074
                                  ucwords(str_replace('_', ' ', $reg_step))
1075
                              )
1076
                              . '</li>';
1077
            } elseif (is_numeric($reg_step_status) && $reg_step_status !== false) {
1078
                $reg_steps .= '<li style="color:#2EA2CC">'
1079
                              . sprintf(
1080
                                  esc_html__('%1$s : Initiated %2$s', 'event_espresso'),
1081
                                  ucwords(str_replace('_', ' ', $reg_step)),
1082
                                  date(
1083
                                      get_option('date_format') . ' ' . get_option('time_format'),
1084
                                      ($reg_step_status + (get_option('gmt_offset') * HOUR_IN_SECONDS))
1085
                                  )
1086
                              )
1087
                              . '</li>';
1088
            } else {
1089
                $reg_steps .= '<li style="color:#E76700">'
1090
                              . sprintf(
1091
                                  esc_html__('%1$s : Never Initiated', 'event_espresso'),
1092
                                  ucwords(str_replace('_', ' ', $reg_step))
1093
                              )
1094
                              . '</li>';
1095
            }
1096
        }
1097
        $reg_steps                                                 .= '</ul>';
1098
        $this->_template_args['txn_details']['reg_steps']['value'] = $reg_steps;
1099
        $this->_template_args['txn_details']['reg_steps']['label'] = esc_html__(
1100
            'Registration Step Progress',
1101
            'event_espresso'
1102
        );
1103
1104
1105
        $this->_get_registrations_to_apply_payment_to();
1106
        $this->_get_payment_methods($payments);
1107
        $this->_get_payment_status_array();
1108
        $this->_get_reg_status_selection(); //sets up the template args for the reg status array for the transaction.
1109
1110
        $this->_template_args['transaction_form_url']    = add_query_arg(array(
1111
            'action'  => 'edit_transaction',
1112
            'process' => 'transaction',
1113
        ), TXN_ADMIN_URL);
1114
        $this->_template_args['apply_payment_form_url']  = add_query_arg(array(
1115
            'page'   => 'espresso_transactions',
1116
            'action' => 'espresso_apply_payment',
1117
        ), WP_AJAX_URL);
1118
        $this->_template_args['delete_payment_form_url'] = add_query_arg(array(
1119
            'page'   => 'espresso_transactions',
1120
            'action' => 'espresso_delete_payment',
1121
        ), WP_AJAX_URL);
1122
1123
        $this->_template_args['action_buttons'] = $this->getActionButtons($this->_transaction);
1124
1125
        // 'espresso_delete_payment_nonce'
1126
1127
        $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_txn_details.template.php';
1128
        echo EEH_Template::display_template($template_path, $this->_template_args, true);
1129
    }
1130
1131
1132
    /**
1133
     * _get_registration_payment_IDs
1134
     *    generates an array of Payment IDs and their corresponding Registration IDs
1135
     *
1136
     * @access protected
1137
     * @param EE_Payment[] $payments
1138
     * @return array
1139
     * @throws EE_Error
1140
     * @throws InvalidArgumentException
1141
     * @throws InvalidDataTypeException
1142
     * @throws InvalidInterfaceException
1143
     * @throws ReflectionException
1144
     */
1145
    protected function _get_registration_payment_IDs($payments = array())
1146
    {
1147
        $existing_reg_payments = array();
1148
        // get all reg payments for these payments
1149
        $reg_payments = EEM_Registration_Payment::instance()->get_all(array(
1150
            array(
1151
                'PAY_ID' => array(
1152
                    'IN',
1153
                    array_keys($payments),
1154
                ),
1155
            ),
1156
        ));
1157
        if (! empty($reg_payments)) {
1158
            foreach ($payments as $payment) {
1159
                if (! $payment instanceof EE_Payment) {
1160
                    continue;
1161
                } elseif (! isset($existing_reg_payments[$payment->ID()])) {
1162
                    $existing_reg_payments[$payment->ID()] = array();
1163
                }
1164
                foreach ($reg_payments as $reg_payment) {
1165
                    if ($reg_payment instanceof EE_Registration_Payment
1166
                        && $reg_payment->payment_ID() === $payment->ID()
1167
                    ) {
1168
                        $existing_reg_payments[$payment->ID()][] = $reg_payment->registration_ID();
1169
                    }
1170
                }
1171
            }
1172
        }
1173
1174
        return $existing_reg_payments;
1175
    }
1176
1177
1178
    /**
1179
     * _get_registrations_to_apply_payment_to
1180
     *    generates HTML for displaying a series of checkboxes in the admin payment modal window
1181
     * which allows the admin to only apply the payment to the specific registrations
1182
     *
1183
     * @access protected
1184
     * @return void
1185
     * @throws \EE_Error
1186
     */
1187
    protected function _get_registrations_to_apply_payment_to()
1188
    {
1189
        // we want any registration with an active status (ie: not deleted or cancelled)
1190
        $query_params                      = array(
1191
            array(
1192
                'STS_ID' => array(
1193
                    'IN',
1194
                    array(
1195
                        EEM_Registration::status_id_approved,
1196
                        EEM_Registration::status_id_pending_payment,
1197
                        EEM_Registration::status_id_not_approved,
1198
                    ),
1199
                ),
1200
            ),
1201
        );
1202
        $registrations_to_apply_payment_to = EEH_HTML::br()
1203
                                             . EEH_HTML::div(
1204
                                                 '',
1205
                                                 'txn-admin-apply-payment-to-registrations-dv',
1206
                                                 '',
1207
                                                 'clear: both; margin: 1.5em 0 0; display: none;'
1208
                                             );
1209
        $registrations_to_apply_payment_to .= EEH_HTML::br() . EEH_HTML::div('', '', 'admin-primary-mbox-tbl-wrap');
1210
        $registrations_to_apply_payment_to .= EEH_HTML::table('', '', 'admin-primary-mbox-tbl');
1211
        $registrations_to_apply_payment_to .= EEH_HTML::thead(
1212
            EEH_HTML::tr(
1213
                EEH_HTML::th(esc_html__('ID', 'event_espresso')) .
1214
                EEH_HTML::th(esc_html__('Registrant', 'event_espresso')) .
1215
                EEH_HTML::th(esc_html__('Ticket', 'event_espresso')) .
1216
                EEH_HTML::th(esc_html__('Event', 'event_espresso')) .
1217
                EEH_HTML::th(esc_html__('Paid', 'event_espresso'), '', 'txn-admin-payment-paid-td jst-cntr') .
1218
                EEH_HTML::th(esc_html__('Owing', 'event_espresso'), '', 'txn-admin-payment-owing-td jst-cntr') .
1219
                EEH_HTML::th(esc_html__('Apply', 'event_espresso'), '', 'jst-cntr')
1220
            )
1221
        );
1222
        $registrations_to_apply_payment_to .= EEH_HTML::tbody();
1223
        // get registrations for TXN
1224
        $registrations = $this->_transaction->registrations($query_params);
1225
        $existing_reg_payments = $this->_template_args['existing_reg_payments'];
1226
        foreach ($registrations as $registration) {
1227
            if ($registration instanceof EE_Registration) {
1228
                $attendee_name                     = $registration->attendee() instanceof EE_Attendee
1229
                    ? $registration->attendee()->full_name()
1230
                    : esc_html__('Unknown Attendee', 'event_espresso');
1231
                $owing                             = $registration->final_price() - $registration->paid();
1232
                $taxable                           = $registration->ticket()->taxable()
1233
                    ? ' <span class="smaller-text lt-grey-text"> ' . esc_html__('+ tax', 'event_espresso') . '</span>'
1234
                    : '';
1235
                $checked = empty($existing_reg_payments) || in_array($registration->ID(), $existing_reg_payments)
1236
                    ? ' checked="checked"'
1237
                    : '';
1238
                $disabled                          = $registration->final_price() > 0 ? '' : ' disabled';
1239
                $registrations_to_apply_payment_to .= EEH_HTML::tr(
1240
                    EEH_HTML::td($registration->ID()) .
1241
                    EEH_HTML::td($attendee_name) .
1242
                    EEH_HTML::td(
1243
                        $registration->ticket()->name() . ' : ' . $registration->ticket()->pretty_price() . $taxable
1244
                    ) .
1245
                    EEH_HTML::td($registration->event_name()) .
1246
                    EEH_HTML::td($registration->pretty_paid(), '', 'txn-admin-payment-paid-td jst-cntr') .
1247
                    EEH_HTML::td(EEH_Template::format_currency($owing), '', 'txn-admin-payment-owing-td jst-cntr') .
1248
                    EEH_HTML::td(
1249
                        '<input type="checkbox" value="' . $registration->ID()
1250
                        . '" name="txn_admin_payment[registrations]"'
1251
                        . $checked . $disabled . '>',
1252
                        '',
1253
                        'jst-cntr'
1254
                    ),
1255
                    'apply-payment-registration-row-' . $registration->ID()
1256
                );
1257
            }
1258
        }
1259
        $registrations_to_apply_payment_to                         .= EEH_HTML::tbodyx();
1260
        $registrations_to_apply_payment_to                         .= EEH_HTML::tablex();
1261
        $registrations_to_apply_payment_to                         .= EEH_HTML::divx();
1262
        $registrations_to_apply_payment_to                         .= EEH_HTML::p(
1263
            esc_html__(
1264
                'The payment will only be applied to the registrations that have a check mark in their corresponding check box. Checkboxes for free registrations have been disabled.',
1265
                'event_espresso'
1266
            ),
1267
            '',
1268
            'clear description'
1269
        );
1270
        $registrations_to_apply_payment_to                         .= EEH_HTML::divx();
1271
        $this->_template_args['registrations_to_apply_payment_to'] = $registrations_to_apply_payment_to;
1272
    }
1273
1274
1275
    /**
1276
     * _get_reg_status_selection
1277
     *
1278
     * @todo   this will need to be adjusted either once MER comes along OR we move default reg status to tickets
1279
     *         instead of events.
1280
     * @access protected
1281
     * @return void
1282
     * @throws EE_Error
1283
     */
1284
    protected function _get_reg_status_selection()
1285
    {
1286
        //first get all possible statuses
1287
        $statuses = EEM_Registration::reg_status_array(array(), true);
1288
        //let's add a "don't change" option.
1289
        $status_array['NAN']                                 = esc_html__('Leave the Same', 'event_espresso');
0 ignored issues
show
Coding Style Comprehensibility introduced by
$status_array was never initialized. Although not strictly required by PHP, it is generally a good practice to add $status_array = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
1290
        $status_array                                        = array_merge($status_array, $statuses);
1291
        $this->_template_args['status_change_select']        = EEH_Form_Fields::select_input(
1292
            'txn_reg_status_change[reg_status]',
1293
            $status_array,
1294
            'NAN',
1295
            'id="txn-admin-payment-reg-status-inp"',
1296
            'txn-reg-status-change-reg-status'
1297
        );
1298
        $this->_template_args['delete_status_change_select'] = EEH_Form_Fields::select_input(
1299
            'delete_txn_reg_status_change[reg_status]',
1300
            $status_array,
1301
            'NAN',
1302
            'delete-txn-admin-payment-reg-status-inp',
1303
            'delete-txn-reg-status-change-reg-status'
1304
        );
1305
    }
1306
1307
1308
    /**
1309
     *    _get_payment_methods
1310
     * Gets all the payment methods available generally, or the ones that are already
1311
     * selected on these payments (in case their payment methods are no longer active).
1312
     * Has the side-effect of updating the template args' payment_methods item
1313
     *
1314
     * @access private
1315
     * @param EE_Payment[] to show on this page
1316
     * @return void
1317
     * @throws EE_Error
1318
     * @throws InvalidArgumentException
1319
     * @throws InvalidDataTypeException
1320
     * @throws InvalidInterfaceException
1321
     * @throws ReflectionException
1322
     */
1323
    private function _get_payment_methods($payments = array())
1324
    {
1325
        $payment_methods_of_payments = array();
1326
        foreach ($payments as $payment) {
1327
            if ($payment instanceof EE_Payment) {
1328
                $payment_methods_of_payments[] = $payment->get('PMD_ID');
1329
            }
1330
        }
1331
        if ($payment_methods_of_payments) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $payment_methods_of_payments of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1332
            $query_args = array(
1333
                array(
1334
                    'OR*payment_method_for_payment' => array(
1335
                        'PMD_ID'    => array('IN', $payment_methods_of_payments),
1336
                        'PMD_scope' => array('LIKE', '%' . EEM_Payment_Method::scope_admin . '%'),
1337
                    ),
1338
                ),
1339
            );
1340
        } else {
1341
            $query_args = array(array('PMD_scope' => array('LIKE', '%' . EEM_Payment_Method::scope_admin . '%')));
1342
        }
1343
        $this->_template_args['payment_methods'] = EEM_Payment_Method::instance()->get_all($query_args);
1344
    }
1345
1346
1347
    /**
1348
     * txn_attendees_meta_box
1349
     *    generates HTML for the Attendees Transaction main meta box
1350
     *
1351
     * @access public
1352
     * @param WP_Post $post
1353
     * @param array   $metabox
1354
     * @return void
1355
     * @throws DomainException
1356
     * @throws EE_Error
1357
     */
1358
    public function txn_attendees_meta_box($post, $metabox = array('args' => array()))
1359
    {
1360
1361
        /** @noinspection NonSecureExtractUsageInspection */
1362
        extract($metabox['args']);
1363
        $this->_template_args['post']            = $post;
1364
        $this->_template_args['event_attendees'] = array();
1365
        // process items in cart
1366
        $line_items = $this->_transaction->get_many_related(
1367
            'Line_Item',
1368
            array(array('LIN_type' => 'line-item'))
1369
        );
1370
        if (! empty($line_items)) {
1371
            foreach ($line_items as $item) {
1372
                if ($item instanceof EE_Line_Item) {
1373
                    switch ($item->OBJ_type()) {
1374
                        case 'Event':
1375
                            break;
1376
                        case 'Ticket':
1377
                            $ticket = $item->ticket();
1378
                            //right now we're only handling tickets here.
1379
                            //Cause its expected that only tickets will have attendees right?
1380
                            if (! $ticket instanceof EE_Ticket) {
1381
                                continue;
1382
                            }
1383
                            try {
1384
                                $event_name = $ticket->get_event_name();
1385
                            } catch (Exception $e) {
1386
                                EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1387
                                $event_name = esc_html__('Unknown Event', 'event_espresso');
1388
                            }
1389
                            $event_name   .= ' - ' . $item->get('LIN_name');
1390
                            $ticket_price = EEH_Template::format_currency($item->get('LIN_unit_price'));
1391
                            // now get all of the registrations for this transaction that use this ticket
1392
                            $registrations = $ticket->get_many_related(
1393
                                'Registration',
1394
                                array(array('TXN_ID' => $this->_transaction->ID()))
1395
                            );
1396
                            foreach ($registrations as $registration) {
1397
                                if (! $registration instanceof EE_Registration) {
1398
                                    continue;
1399
                                }
1400
                                $this->_template_args['event_attendees'][$registration->ID()]['STS_ID']
1401
                                    = $registration->status_ID();
1402
                                $this->_template_args['event_attendees'][$registration->ID()]['att_num']
1403
                                    = $registration->count();
1404
                                $this->_template_args['event_attendees'][$registration->ID()]['event_ticket_name']
1405
                                    = $event_name;
1406
                                $this->_template_args['event_attendees'][$registration->ID()]['ticket_price']
1407
                                    = $ticket_price;
1408
                                // attendee info
1409
                                $attendee = $registration->get_first_related('Attendee');
1410
                                if ($attendee instanceof EE_Attendee) {
1411
                                    $this->_template_args['event_attendees'][$registration->ID()]['att_id']
1412
                                        = $attendee->ID();
1413
                                    $this->_template_args['event_attendees'][$registration->ID()]['attendee']
1414
                                        = $attendee->full_name();
1415
                                    $this->_template_args['event_attendees'][$registration->ID()]['email']
1416
                                        = '<a href="mailto:' . $attendee->email() . '?subject=' . $event_name
1417
                                          . esc_html__(
1418
                                              ' Event',
1419
                                              'event_espresso'
1420
                                          )
1421
                                          . '">' . $attendee->email() . '</a>';
1422
                                    $this->_template_args['event_attendees'][$registration->ID()]['address']
1423
                                        = EEH_Address::format($attendee, 'inline', false, false);
1424
                                } else {
1425
                                    $this->_template_args['event_attendees'][$registration->ID()]['att_id']   = '';
1426
                                    $this->_template_args['event_attendees'][$registration->ID()]['attendee'] = '';
1427
                                    $this->_template_args['event_attendees'][$registration->ID()]['email']    = '';
1428
                                    $this->_template_args['event_attendees'][$registration->ID()]['address']  = '';
1429
                                }
1430
                            }
1431
                            break;
1432
1433
                    }
1434
                }
1435
            }
1436
1437
            $this->_template_args['transaction_form_url'] = add_query_arg(
1438
                array(
1439
                    'action'  => 'edit_transaction',
1440
                    'process' => 'attendees',
1441
                ),
1442
                TXN_ADMIN_URL
1443
            );
1444
            echo EEH_Template::display_template(
1445
                TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_attendees.template.php',
1446
                $this->_template_args,
1447
                true
1448
            );
1449
1450
        } else {
1451
            echo sprintf(
1452
                esc_html__(
1453
                    '%1$sFor some reason, there are no attendees registered for this transaction. Likely the registration was abandoned in process.%2$s',
1454
                    'event_espresso'
1455
                ),
1456
                '<p class="important-notice">',
1457
                '</p>'
1458
            );
1459
        }
1460
    }
1461
1462
1463
    /**
1464
     * txn_registrant_side_meta_box
1465
     * generates HTML for the Edit Transaction side meta box
1466
     *
1467
     * @access public
1468
     * @return void
1469
     * @throws DomainException
1470
     * @throws EE_Error
1471
     * @throws InvalidArgumentException
1472
     * @throws InvalidDataTypeException
1473
     * @throws InvalidInterfaceException
1474
     * @throws ReflectionException
1475
     */
1476
    public function txn_registrant_side_meta_box()
1477
    {
1478
        $primary_att = $this->_transaction->primary_registration() instanceof EE_Registration
1479
            ? $this->_transaction->primary_registration()->get_first_related('Attendee')
1480
            : null;
1481
        if (! $primary_att instanceof EE_Attendee) {
1482
            $this->_template_args['no_attendee_message'] = esc_html__(
1483
                'There is no attached contact for this transaction.  The transaction either failed due to an error or was abandoned.',
1484
                'event_espresso'
1485
            );
1486
            $primary_att                                 = EEM_Attendee::instance()->create_default_object();
1487
        }
1488
        $this->_template_args['ATT_ID']            = $primary_att->ID();
1489
        $this->_template_args['prime_reg_fname']   = $primary_att->fname();
1490
        $this->_template_args['prime_reg_lname']   = $primary_att->lname();
1491
        $this->_template_args['prime_reg_email']   = $primary_att->email();
1492
        $this->_template_args['prime_reg_phone']   = $primary_att->phone();
1493
        $this->_template_args['edit_attendee_url'] = EE_Admin_Page::add_query_args_and_nonce(array(
1494
            'action' => 'edit_attendee',
1495
            'post'   => $primary_att->ID(),
1496
        ), REG_ADMIN_URL);
1497
        // get formatted address for registrant
1498
        $this->_template_args['formatted_address'] = EEH_Address::format($primary_att);
1499
        echo EEH_Template::display_template(
1500
            TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_registrant.template.php',
1501
            $this->_template_args,
1502
            true
1503
        );
1504
    }
1505
1506
1507
    /**
1508
     * txn_billing_info_side_meta_box
1509
     *    generates HTML for the Edit Transaction side meta box
1510
     *
1511
     * @access public
1512
     * @return void
1513
     * @throws DomainException
1514
     * @throws EE_Error
1515
     */
1516
    public function txn_billing_info_side_meta_box()
1517
    {
1518
1519
        $this->_template_args['billing_form']     = $this->_transaction->billing_info();
1520
        $this->_template_args['billing_form_url'] = add_query_arg(
1521
            array('action' => 'edit_transaction', 'process' => 'billing'),
1522
            TXN_ADMIN_URL
1523
        );
1524
1525
        $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_billing_info.template.php';
1526
        echo EEH_Template::display_template($template_path, $this->_template_args, true);/**/
1527
    }
1528
1529
1530
    /**
1531
     * apply_payments_or_refunds
1532
     *    registers a payment or refund made towards a transaction
1533
     *
1534
     * @access public
1535
     * @return void
1536
     * @throws EE_Error
1537
     * @throws InvalidArgumentException
1538
     * @throws ReflectionException
1539
     * @throws RuntimeException
1540
     * @throws InvalidDataTypeException
1541
     * @throws InvalidInterfaceException
1542
     */
1543
    public function apply_payments_or_refunds()
1544
    {
1545
        $json_response_data = array('return_data' => false);
1546
        $valid_data         = $this->_validate_payment_request_data();
1547
        $has_access = EE_Registry::instance()->CAP->current_user_can(
1548
            'ee_edit_payments',
1549
            'apply_payment_or_refund_from_registration_details'
1550
        );
1551
        if (! empty($valid_data) && $has_access) {
1552
            $PAY_ID = $valid_data['PAY_ID'];
1553
            //save  the new payment
1554
            $payment = $this->_create_payment_from_request_data($valid_data);
1555
            // get the TXN for this payment
1556
            $transaction = $payment->transaction();
1557
            // verify transaction
1558
            if ($transaction instanceof EE_Transaction) {
1559
                // calculate_total_payments_and_update_status
1560
                $this->_process_transaction_payments($transaction);
1561
                $REG_IDs = $this->_get_REG_IDs_to_apply_payment_to($payment);
1562
                $this->_remove_existing_registration_payments($payment, $PAY_ID);
1563
                // apply payment to registrations (if applicable)
1564
                if (! empty($REG_IDs)) {
1565
                    $this->_update_registration_payments($transaction, $payment, $REG_IDs);
1566
                    $this->_maybe_send_notifications();
1567
                    // now process status changes for the same registrations
1568
                    $this->_process_registration_status_change($transaction, $REG_IDs);
1569
                }
1570
                $this->_maybe_send_notifications($payment);
1571
                //prepare to render page
1572
                $json_response_data['return_data'] = $this->_build_payment_json_response($payment, $REG_IDs);
1573
                do_action(
1574
                    'AHEE__Transactions_Admin_Page__apply_payments_or_refund__after_recording',
1575
                    $transaction,
1576
                    $payment
1577
                );
1578
            } else {
1579
                EE_Error::add_error(
1580
                    esc_html__(
1581
                        'A valid Transaction for this payment could not be retrieved.',
1582
                        'event_espresso'
1583
                    ),
1584
                    __FILE__,
1585
                    __FUNCTION__,
1586
                    __LINE__
1587
                );
1588
            }
1589 View Code Duplication
        } else {
1590
            if ($has_access) {
1591
                EE_Error::add_error(
1592
                    esc_html__(
1593
                        'The payment form data could not be processed. Please try again.',
1594
                        'event_espresso'
1595
                    ),
1596
                    __FILE__,
1597
                    __FUNCTION__,
1598
                    __LINE__
1599
                );
1600
            } else {
1601
                EE_Error::add_error(
1602
                    esc_html__(
1603
                        'You do not have access to apply payments or refunds to a registration.',
1604
                        'event_espresso'
1605
                    ),
1606
                    __FILE__,
1607
                    __FUNCTION__,
1608
                    __LINE__
1609
                );
1610
            }
1611
        }
1612
        $notices              = EE_Error::get_notices(
1613
            false,
1614
            false,
1615
            false
1616
        );
1617
        $this->_template_args = array(
1618
            'data'    => $json_response_data,
1619
            'error'   => $notices['errors'],
1620
            'success' => $notices['success'],
1621
        );
1622
        $this->_return_json();
1623
    }
1624
1625
1626
    /**
1627
     * _validate_payment_request_data
1628
     *
1629
     * @return array
1630
     * @throws EE_Error
1631
     */
1632
    protected function _validate_payment_request_data()
1633
    {
1634
        if (! isset($this->_req_data['txn_admin_payment'])) {
1635
            return false;
1636
        }
1637
        $payment_form = $this->_generate_payment_form_section();
1638
        try {
1639
            if ($payment_form->was_submitted()) {
1640
                $payment_form->receive_form_submission();
1641
                if (! $payment_form->is_valid()) {
1642
                    $submission_error_messages = array();
1643
                    foreach ($payment_form->get_validation_errors_accumulated() as $validation_error) {
1644
                        if ($validation_error instanceof EE_Validation_Error) {
1645
                            $submission_error_messages[] = sprintf(
1646
                                _x('%s : %s', 'Form Section Name : Form Validation Error', 'event_espresso'),
1647
                                $validation_error->get_form_section()->html_label_text(),
1648
                                $validation_error->getMessage()
1649
                            );
1650
                        }
1651
                    }
1652
                    EE_Error::add_error(
1653
                        implode('<br />', $submission_error_messages),
1654
                        __FILE__,
1655
                        __FUNCTION__,
1656
                        __LINE__
1657
                    );
1658
1659
                    return array();
1660
                }
1661
            }
1662
        } catch (EE_Error $e) {
1663
            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1664
1665
            return array();
1666
        }
1667
1668
        return $payment_form->valid_data();
1669
    }
1670
1671
1672
    /**
1673
     * _generate_payment_form_section
1674
     *
1675
     * @return EE_Form_Section_Proper
1676
     * @throws EE_Error
1677
     */
1678
    protected function _generate_payment_form_section()
1679
    {
1680
        return new EE_Form_Section_Proper(
1681
            array(
1682
                'name'        => 'txn_admin_payment',
1683
                'subsections' => array(
1684
                    'PAY_ID'          => new EE_Text_Input(
1685
                        array(
1686
                            'default'               => 0,
1687
                            'required'              => false,
1688
                            'html_label_text'       => esc_html__('Payment ID', 'event_espresso'),
1689
                            'validation_strategies' => array(new EE_Int_Normalization()),
1690
                        )
1691
                    ),
1692
                    'TXN_ID'          => new EE_Text_Input(
1693
                        array(
1694
                            'default'               => 0,
1695
                            'required'              => true,
1696
                            'html_label_text'       => esc_html__('Transaction ID', 'event_espresso'),
1697
                            'validation_strategies' => array(new EE_Int_Normalization()),
1698
                        )
1699
                    ),
1700
                    'type'            => new EE_Text_Input(
1701
                        array(
1702
                            'default'               => 1,
1703
                            'required'              => true,
1704
                            'html_label_text'       => esc_html__('Payment or Refund', 'event_espresso'),
1705
                            'validation_strategies' => array(new EE_Int_Normalization()),
1706
                        )
1707
                    ),
1708
                    'amount'          => new EE_Text_Input(
1709
                        array(
1710
                            'default'               => 0,
1711
                            'required'              => true,
1712
                            'html_label_text'       => esc_html__('Payment amount', 'event_espresso'),
1713
                            'validation_strategies' => array(new EE_Float_Normalization()),
1714
                        )
1715
                    ),
1716
                    'status'          => new EE_Text_Input(
1717
                        array(
1718
                            'default'         => EEM_Payment::status_id_approved,
1719
                            'required'        => true,
1720
                            'html_label_text' => esc_html__('Payment status', 'event_espresso'),
1721
                        )
1722
                    ),
1723
                    'PMD_ID'          => new EE_Text_Input(
1724
                        array(
1725
                            'default'               => 2,
1726
                            'required'              => true,
1727
                            'html_label_text'       => esc_html__('Payment Method', 'event_espresso'),
1728
                            'validation_strategies' => array(new EE_Int_Normalization()),
1729
                        )
1730
                    ),
1731
                    'date'            => new EE_Text_Input(
1732
                        array(
1733
                            'default'         => time(),
1734
                            'required'        => true,
1735
                            'html_label_text' => esc_html__('Payment date', 'event_espresso'),
1736
                        )
1737
                    ),
1738
                    'txn_id_chq_nmbr' => new EE_Text_Input(
1739
                        array(
1740
                            'default'               => '',
1741
                            'required'              => false,
1742
                            'html_label_text'       => esc_html__('Transaction or Cheque Number', 'event_espresso'),
1743
                            'validation_strategies' => array(
1744
                                new EE_Max_Length_Validation_Strategy(
1745
                                    esc_html__('Input too long', 'event_espresso'),
1746
                                    100
1747
                                ),
1748
                            ),
1749
                        )
1750
                    ),
1751
                    'po_number'       => new EE_Text_Input(
1752
                        array(
1753
                            'default'               => '',
1754
                            'required'              => false,
1755
                            'html_label_text'       => esc_html__('Purchase Order Number', 'event_espresso'),
1756
                            'validation_strategies' => array(
1757
                                new EE_Max_Length_Validation_Strategy(
1758
                                    esc_html__('Input too long', 'event_espresso'),
1759
                                    100
1760
                                ),
1761
                            ),
1762
                        )
1763
                    ),
1764
                    'accounting'      => new EE_Text_Input(
1765
                        array(
1766
                            'default'               => '',
1767
                            'required'              => false,
1768
                            'html_label_text'       => esc_html__('Extra Field for Accounting', 'event_espresso'),
1769
                            'validation_strategies' => array(
1770
                                new EE_Max_Length_Validation_Strategy(
1771
                                    esc_html__('Input too long', 'event_espresso'),
1772
                                    100
1773
                                ),
1774
                            ),
1775
                        )
1776
                    ),
1777
                ),
1778
            )
1779
        );
1780
    }
1781
1782
1783
    /**
1784
     * _create_payment_from_request_data
1785
     *
1786
     * @param array $valid_data
1787
     * @return EE_Payment
1788
     * @throws EE_Error
1789
     */
1790
    protected function _create_payment_from_request_data($valid_data)
1791
    {
1792
        $PAY_ID = $valid_data['PAY_ID'];
1793
        // get payment amount
1794
        $amount = $valid_data['amount'] ? abs($valid_data['amount']) : 0;
1795
        // payments have a type value of 1 and refunds have a type value of -1
1796
        // so multiplying amount by type will give a positive value for payments, and negative values for refunds
1797
        $amount = $valid_data['type'] < 0 ? $amount * -1 : $amount;
1798
        // for some reason the date string coming in has extra spaces between the date and time.  This fixes that.
1799
        $date    = $valid_data['date']
1800
            ? preg_replace('/\s+/', ' ', $valid_data['date'])
1801
            : date('Y-m-d g:i a', current_time('timestamp'));
1802
        $payment = EE_Payment::new_instance(
1803
            array(
1804
                'TXN_ID'              => $valid_data['TXN_ID'],
1805
                'STS_ID'              => $valid_data['status'],
1806
                'PAY_timestamp'       => $date,
1807
                'PAY_source'          => EEM_Payment_Method::scope_admin,
1808
                'PMD_ID'              => $valid_data['PMD_ID'],
1809
                'PAY_amount'          => $amount,
1810
                'PAY_txn_id_chq_nmbr' => $valid_data['txn_id_chq_nmbr'],
1811
                'PAY_po_number'       => $valid_data['po_number'],
1812
                'PAY_extra_accntng'   => $valid_data['accounting'],
1813
                'PAY_details'         => $valid_data,
1814
                'PAY_ID'              => $PAY_ID,
1815
            ),
1816
            '',
1817
            array('Y-m-d', 'g:i a')
1818
        );
1819
1820
        if (! $payment->save()) {
1821
            EE_Error::add_error(
1822
                sprintf(
1823
                    esc_html__('Payment %1$d has not been successfully saved to the database.', 'event_espresso'),
1824
                    $payment->ID()
1825
                ),
1826
                __FILE__, __FUNCTION__, __LINE__
1827
            );
1828
        }
1829
1830
        return $payment;
1831
    }
1832
1833
1834
    /**
1835
     * _process_transaction_payments
1836
     *
1837
     * @param \EE_Transaction $transaction
1838
     * @return void
1839
     * @throws EE_Error
1840
     * @throws InvalidArgumentException
1841
     * @throws ReflectionException
1842
     * @throws InvalidDataTypeException
1843
     * @throws InvalidInterfaceException
1844
     */
1845
    protected function _process_transaction_payments(EE_Transaction $transaction)
1846
    {
1847
        /** @type EE_Transaction_Payments $transaction_payments */
1848
        $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
1849
        //update the transaction with this payment
1850 View Code Duplication
        if ($transaction_payments->calculate_total_payments_and_update_status($transaction)) {
1851
            EE_Error::add_success(esc_html__(
1852
                'The payment has been processed successfully.', 'event_espresso'),
1853
                __FILE__,
1854
                __FUNCTION__,
1855
                __LINE__
1856
            );
1857
        } else {
1858
            EE_Error::add_error(
1859
                esc_html__(
1860
                    'The payment was processed successfully but the amount paid for the transaction was not updated.',
1861
                    'event_espresso'
1862
                )
1863
                ,
1864
                __FILE__,
1865
                __FUNCTION__,
1866
                __LINE__
1867
            );
1868
        }
1869
    }
1870
1871
1872
    /**
1873
     * _get_REG_IDs_to_apply_payment_to
1874
     * returns a list of registration IDs that the payment will apply to
1875
     *
1876
     * @param \EE_Payment $payment
1877
     * @return array
1878
     * @throws EE_Error
1879
     */
1880
    protected function _get_REG_IDs_to_apply_payment_to(EE_Payment $payment)
1881
    {
1882
        $REG_IDs = array();
1883
        // grab array of IDs for specific registrations to apply changes to
1884
        if (isset($this->_req_data['txn_admin_payment']['registrations'])) {
1885
            $REG_IDs = (array)$this->_req_data['txn_admin_payment']['registrations'];
1886
        }
1887
        //nothing specified ? then get all reg IDs
1888
        if (empty($REG_IDs)) {
1889
            $registrations = $payment->transaction()->registrations();
1890
            $REG_IDs       = ! empty($registrations)
1891
                ? array_keys($registrations)
1892
                : $this->_get_existing_reg_payment_REG_IDs($payment);
1893
        }
1894
1895
        // ensure that REG_IDs are integers and NOT strings
1896
        return array_map('intval', $REG_IDs);
1897
    }
1898
1899
1900
    /**
1901
     * @return array
1902
     */
1903
    public function existing_reg_payment_REG_IDs()
1904
    {
1905
        return $this->_existing_reg_payment_REG_IDs;
1906
    }
1907
1908
1909
    /**
1910
     * @param array $existing_reg_payment_REG_IDs
1911
     */
1912
    public function set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs = null)
1913
    {
1914
        $this->_existing_reg_payment_REG_IDs = $existing_reg_payment_REG_IDs;
0 ignored issues
show
Documentation Bug introduced by
It seems like $existing_reg_payment_REG_IDs can be null. However, the property $_existing_reg_payment_REG_IDs is declared as array. Maybe change the type of the property to array|null or add a type check?

Our type inference engine has found an assignment of a scalar value (like a string, an integer or null) to a property which is an array.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property.

To type hint that a parameter can be either an array or null, you can set a type hint of array and a default value of null. The PHP interpreter will then accept both an array or null for that parameter.

function aContainsB(array $needle = null, array  $haystack) {
    if (!$needle) {
        return false;
    }

    return array_intersect($haystack, $needle) == $haystack;
}

The function can be called with either null or an array for the parameter $needle but will only accept an array as $haystack.

Loading history...
1915
    }
1916
1917
1918
    /**
1919
     * _get_existing_reg_payment_REG_IDs
1920
     * returns a list of registration IDs that the payment is currently related to
1921
     * as recorded in the database
1922
     *
1923
     * @param \EE_Payment $payment
1924
     * @return array
1925
     * @throws EE_Error
1926
     */
1927
    protected function _get_existing_reg_payment_REG_IDs(EE_Payment $payment)
1928
    {
1929
        if ($this->existing_reg_payment_REG_IDs() === null) {
1930
            // let's get any existing reg payment records for this payment
1931
            $existing_reg_payment_REG_IDs = $payment->get_many_related('Registration');
1932
            // but we only want the REG IDs, so grab the array keys
1933
            $existing_reg_payment_REG_IDs = ! empty($existing_reg_payment_REG_IDs)
1934
                ? array_keys($existing_reg_payment_REG_IDs)
1935
                : array();
1936
            $this->set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs);
1937
        }
1938
1939
        return $this->existing_reg_payment_REG_IDs();
1940
    }
1941
1942
1943
    /**
1944
     * _remove_existing_registration_payments
1945
     * this calculates the difference between existing relations
1946
     * to the supplied payment and the new list registration IDs,
1947
     * removes any related registrations that no longer apply,
1948
     * and then updates the registration paid fields
1949
     *
1950
     * @param \EE_Payment $payment
1951
     * @param int         $PAY_ID
1952
     * @return bool;
1953
     * @throws EE_Error
1954
     * @throws InvalidArgumentException
1955
     * @throws ReflectionException
1956
     * @throws InvalidDataTypeException
1957
     * @throws InvalidInterfaceException
1958
     */
1959
    protected function _remove_existing_registration_payments(EE_Payment $payment, $PAY_ID = 0)
1960
    {
1961
        // newly created payments will have nothing recorded for $PAY_ID
1962
        if ($PAY_ID == 0) {
1963
            return false;
1964
        }
1965
        $existing_reg_payment_REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment);
1966
        if (empty($existing_reg_payment_REG_IDs)) {
1967
            return false;
1968
        }
1969
        /** @type EE_Transaction_Payments $transaction_payments */
1970
        $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
1971
1972
        return $transaction_payments->delete_registration_payments_and_update_registrations(
1973
            $payment,
1974
            array(
1975
                array(
1976
                    'PAY_ID' => $payment->ID(),
1977
                    'REG_ID' => array('IN', $existing_reg_payment_REG_IDs),
1978
                ),
1979
            )
1980
        );
1981
    }
1982
1983
1984
    /**
1985
     * _update_registration_payments
1986
     * this applies the payments to the selected registrations
1987
     * but only if they have not already been paid for
1988
     *
1989
     * @param  EE_Transaction $transaction
1990
     * @param \EE_Payment     $payment
1991
     * @param array           $REG_IDs
1992
     * @return void
1993
     * @throws EE_Error
1994
     * @throws InvalidArgumentException
1995
     * @throws ReflectionException
1996
     * @throws RuntimeException
1997
     * @throws InvalidDataTypeException
1998
     * @throws InvalidInterfaceException
1999
     */
2000
    protected function _update_registration_payments(
2001
        EE_Transaction $transaction,
2002
        EE_Payment $payment,
2003
        $REG_IDs = array()
2004
    ) {
2005
        // we can pass our own custom set of registrations to EE_Payment_Processor::process_registration_payments()
2006
        // so let's do that using our set of REG_IDs from the form
2007
        $registration_query_where_params = array(
2008
            'REG_ID' => array('IN', $REG_IDs),
2009
        );
2010
        // but add in some conditions regarding payment,
2011
        // so that we don't apply payments to registrations that are free or have already been paid for
2012
        // but ONLY if the payment is NOT a refund ( ie: the payment amount is not negative )
2013
        if (! $payment->is_a_refund()) {
2014
            $registration_query_where_params['REG_final_price']  = array('!=', 0);
2015
            $registration_query_where_params['REG_final_price*'] = array('!=', 'REG_paid', true);
2016
        }
2017
        $registrations = $transaction->registrations(array($registration_query_where_params));
2018
        if (! empty($registrations)) {
2019
            /** @type EE_Payment_Processor $payment_processor */
2020
            $payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2021
            $payment_processor->process_registration_payments($transaction, $payment, $registrations);
2022
        }
2023
    }
2024
2025
2026
    /**
2027
     * _process_registration_status_change
2028
     * This processes requested registration status changes for all the registrations
2029
     * on a given transaction and (optionally) sends out notifications for the changes.
2030
     *
2031
     * @param  EE_Transaction $transaction
2032
     * @param array           $REG_IDs
2033
     * @return bool
2034
     * @throws EE_Error
2035
     * @throws InvalidArgumentException
2036
     * @throws ReflectionException
2037
     * @throws InvalidDataTypeException
2038
     * @throws InvalidInterfaceException
2039
     */
2040
    protected function _process_registration_status_change(EE_Transaction $transaction, $REG_IDs = array())
2041
    {
2042
        // first if there is no change in status then we get out.
2043
        if (
2044
            ! isset($this->_req_data['txn_reg_status_change']['reg_status'])
2045
            || $this->_req_data['txn_reg_status_change']['reg_status'] === 'NAN'
2046
        ) {
2047
            //no error message, no change requested, just nothing to do man.
2048
            return false;
2049
        }
2050
        /** @type EE_Transaction_Processor $transaction_processor */
2051
        $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
2052
2053
        // made it here dude?  Oh WOW.  K, let's take care of changing the statuses
2054
        return $transaction_processor->manually_update_registration_statuses(
2055
            $transaction,
2056
            sanitize_text_field($this->_req_data['txn_reg_status_change']['reg_status']),
2057
            array(array('REG_ID' => array('IN', $REG_IDs)))
2058
        );
2059
    }
2060
2061
2062
    /**
2063
     * _build_payment_json_response
2064
     *
2065
     * @access public
2066
     * @param \EE_Payment $payment
2067
     * @param array       $REG_IDs
2068
     * @param bool | null $delete_txn_reg_status_change
2069
     * @return array
2070
     * @throws EE_Error
2071
     * @throws InvalidArgumentException
2072
     * @throws InvalidDataTypeException
2073
     * @throws InvalidInterfaceException
2074
     * @throws ReflectionException
2075
     */
2076
    protected function _build_payment_json_response(
2077
        EE_Payment $payment,
2078
        $REG_IDs = array(),
2079
        $delete_txn_reg_status_change = null
2080
    ) {
2081
        // was the payment deleted ?
2082
        if (is_bool($delete_txn_reg_status_change)) {
2083
            return array(
2084
                'PAY_ID'                       => $payment->ID(),
2085
                'amount'                       => $payment->amount(),
2086
                'total_paid'                   => $payment->transaction()->paid(),
2087
                'txn_status'                   => $payment->transaction()->status_ID(),
2088
                'pay_status'                   => $payment->STS_ID(),
2089
                'registrations'                => $this->_registration_payment_data_array($REG_IDs),
2090
                'delete_txn_reg_status_change' => $delete_txn_reg_status_change,
2091
            );
2092
        } else {
2093
            $this->_get_payment_status_array();
2094
2095
            return array(
2096
                'amount'           => $payment->amount(),
2097
                'total_paid'       => $payment->transaction()->paid(),
2098
                'txn_status'       => $payment->transaction()->status_ID(),
2099
                'pay_status'       => $payment->STS_ID(),
2100
                'PAY_ID'           => $payment->ID(),
2101
                'STS_ID'           => $payment->STS_ID(),
2102
                'status'           => self::$_pay_status[$payment->STS_ID()],
2103
                'date'             => $payment->timestamp('Y-m-d', 'h:i a'),
2104
                'method'           => strtoupper($payment->source()),
2105
                'PM_ID'            => $payment->payment_method() ? $payment->payment_method()->ID() : 1,
2106
                'gateway'          => $payment->payment_method()
2107
                    ? $payment->payment_method()->admin_name()
2108
                    : esc_html__("Unknown", 'event_espresso'),
2109
                'gateway_response' => $payment->gateway_response(),
2110
                'txn_id_chq_nmbr'  => $payment->txn_id_chq_nmbr(),
2111
                'po_number'        => $payment->po_number(),
2112
                'extra_accntng'    => $payment->extra_accntng(),
2113
                'registrations'    => $this->_registration_payment_data_array($REG_IDs),
2114
            );
2115
        }
2116
    }
2117
2118
2119
    /**
2120
     * delete_payment
2121
     *    delete a payment or refund made towards a transaction
2122
     *
2123
     * @access public
2124
     * @return void
2125
     * @throws EE_Error
2126
     * @throws InvalidArgumentException
2127
     * @throws ReflectionException
2128
     * @throws InvalidDataTypeException
2129
     * @throws InvalidInterfaceException
2130
     */
2131
    public function delete_payment()
2132
    {
2133
        $json_response_data = array('return_data' => false);
2134
        $PAY_ID             = isset($this->_req_data['delete_txn_admin_payment']['PAY_ID'])
2135
            ? absint($this->_req_data['delete_txn_admin_payment']['PAY_ID'])
2136
            : 0;
2137
        $can_delete = EE_Registry::instance()->CAP->current_user_can(
2138
            'ee_delete_payments',
2139
            'delete_payment_from_registration_details'
2140
        );
2141
        if ($PAY_ID && $can_delete) {
2142
            $delete_txn_reg_status_change = isset($this->_req_data['delete_txn_reg_status_change'])
2143
                ? $this->_req_data['delete_txn_reg_status_change']
2144
                : false;
2145
            $payment                      = EEM_Payment::instance()->get_one_by_ID($PAY_ID);
2146
            if ($payment instanceof EE_Payment) {
2147
                $REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment);
2148
                /** @type EE_Transaction_Payments $transaction_payments */
2149
                $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
2150
                if ($transaction_payments->delete_payment_and_update_transaction($payment)) {
2151
                    $json_response_data['return_data'] = $this->_build_payment_json_response(
2152
                        $payment,
2153
                        $REG_IDs,
2154
                        $delete_txn_reg_status_change
2155
                    );
2156
                    if ($delete_txn_reg_status_change) {
2157
                        $this->_req_data['txn_reg_status_change'] = $delete_txn_reg_status_change;
2158
                        //MAKE sure we also add the delete_txn_req_status_change to the
2159
                        //$_REQUEST global because that's how messages will be looking for it.
2160
                        $_REQUEST['txn_reg_status_change'] = $delete_txn_reg_status_change;
2161
                        $this->_maybe_send_notifications();
2162
                        $this->_process_registration_status_change($payment->transaction(), $REG_IDs);
0 ignored issues
show
Bug introduced by
It seems like $payment->transaction() can be null; however, _process_registration_status_change() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
2163
                    }
2164
                }
2165
            } else {
2166
                EE_Error::add_error(
2167
                    esc_html__('Valid Payment data could not be retrieved from the database.', 'event_espresso'),
2168
                    __FILE__, __FUNCTION__, __LINE__
2169
                );
2170
            }
2171 View Code Duplication
        } else {
2172
            if ($can_delete) {
2173
                EE_Error::add_error(
2174
                    esc_html__(
2175
                        'A valid Payment ID was not received, therefore payment form data could not be loaded.',
2176
                        'event_espresso'
2177
                    ),
2178
                    __FILE__, __FUNCTION__, __LINE__
2179
                );
2180
            } else {
2181
                EE_Error::add_error(
2182
                    esc_html__(
2183
                        'You do not have access to delete a payment.',
2184
                        'event_espresso'
2185
                    ),
2186
                    __FILE__,
2187
                    __FUNCTION__,
2188
                    __LINE__
2189
                );
2190
            }
2191
        }
2192
        $notices              = EE_Error::get_notices(false, false, false);
2193
        $this->_template_args = array(
2194
            'data'      => $json_response_data,
2195
            'success'   => $notices['success'],
2196
            'error'     => $notices['errors'],
2197
            'attention' => $notices['attention'],
2198
        );
2199
        $this->_return_json();
2200
    }
2201
2202
2203
    /**
2204
     * _registration_payment_data_array
2205
     * adds info for 'owing' and 'paid' for each registration to the json response
2206
     *
2207
     * @access protected
2208
     * @param array $REG_IDs
2209
     * @return array
2210
     * @throws EE_Error
2211
     * @throws InvalidArgumentException
2212
     * @throws InvalidDataTypeException
2213
     * @throws InvalidInterfaceException
2214
     * @throws ReflectionException
2215
     */
2216
    protected function _registration_payment_data_array($REG_IDs)
2217
    {
2218
        $registration_payment_data = array();
2219
        //if non empty reg_ids lets get an array of registrations and update the values for the apply_payment/refund rows.
2220
        if (! empty($REG_IDs)) {
2221
            $registrations = EEM_Registration::instance()->get_all(array(array('REG_ID' => array('IN', $REG_IDs))));
2222
            foreach ($registrations as $registration) {
2223
                if ($registration instanceof EE_Registration) {
2224
                    $registration_payment_data[$registration->ID()] = array(
2225
                        'paid'  => $registration->pretty_paid(),
2226
                        'owing' => EEH_Template::format_currency($registration->final_price() - $registration->paid()),
2227
                    );
2228
                }
2229
            }
2230
        }
2231
2232
        return $registration_payment_data;
2233
    }
2234
2235
2236
    /**
2237
     * _maybe_send_notifications
2238
     * determines whether or not the admin has indicated that notifications should be sent.
2239
     * If so, will toggle a filter switch for delivering registration notices.
2240
     * If passed an EE_Payment object, then it will trigger payment notifications instead.
2241
     *
2242
     * @access protected
2243
     * @param \EE_Payment | null $payment
2244
     */
2245
    protected function _maybe_send_notifications($payment = null)
2246
    {
2247
        switch ($payment instanceof EE_Payment) {
2248
            // payment notifications
2249 View Code Duplication
            case true :
2250
                if (
2251
                    isset(
2252
                        $this->_req_data['txn_payments'],
2253
                        $this->_req_data['txn_payments']['send_notifications']
2254
                    ) &&
2255
                    filter_var($this->_req_data['txn_payments']['send_notifications'], FILTER_VALIDATE_BOOLEAN)
2256
                ) {
2257
                    $this->_process_payment_notification($payment);
2258
                }
2259
                break;
2260
            // registration notifications
2261 View Code Duplication
            case false :
2262
                if (
2263
                    isset(
2264
                        $this->_req_data['txn_reg_status_change'],
2265
                        $this->_req_data['txn_reg_status_change']['send_notifications']
2266
                    ) &&
2267
                    filter_var($this->_req_data['txn_reg_status_change']['send_notifications'], FILTER_VALIDATE_BOOLEAN)
2268
                ) {
2269
                    add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
2270
                }
2271
                break;
2272
        }
2273
    }
2274
2275
2276
    /**
2277
     * _send_payment_reminder
2278
     *    generates HTML for the View Transaction Details Admin page
2279
     *
2280
     * @access protected
2281
     * @return void
2282
     * @throws EE_Error
2283
     * @throws InvalidArgumentException
2284
     * @throws InvalidDataTypeException
2285
     * @throws InvalidInterfaceException
2286
     */
2287
    protected function _send_payment_reminder()
2288
    {
2289
        $TXN_ID      = ! empty($this->_req_data['TXN_ID']) ? absint($this->_req_data['TXN_ID']) : false;
2290
        $transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
2291
        $query_args  = isset($this->_req_data['redirect_to']) ? array(
2292
            'action' => $this->_req_data['redirect_to'],
2293
            'TXN_ID' => $this->_req_data['TXN_ID'],
2294
        ) : array();
2295
        do_action(
2296
            'AHEE__Transactions_Admin_Page___send_payment_reminder__process_admin_payment_reminder',
2297
            $transaction
2298
        );
2299
        $this->_redirect_after_action(
2300
            false,
2301
            esc_html__('payment reminder', 'event_espresso'),
2302
            esc_html__('sent', 'event_espresso'),
2303
            $query_args,
2304
            true
2305
        );
2306
    }
2307
2308
2309
    /**
2310
     *  get_transactions
2311
     *    get transactions for given parameters (used by list table)
2312
     *
2313
     * @param  int     $perpage how many transactions displayed per page
2314
     * @param  boolean $count   return the count or objects
2315
     * @param string   $view
2316
     * @return mixed int = count || array of transaction objects
2317
     * @throws EE_Error
2318
     * @throws InvalidArgumentException
2319
     * @throws InvalidDataTypeException
2320
     * @throws InvalidInterfaceException
2321
     */
2322
    public function get_transactions($perpage, $count = false, $view = '')
2323
    {
2324
2325
        $TXN = EEM_Transaction::instance();
2326
2327
        $start_date = isset($this->_req_data['txn-filter-start-date'])
2328
            ? wp_strip_all_tags($this->_req_data['txn-filter-start-date'])
2329
            : date(
2330
                'm/d/Y',
2331
                strtotime('-10 year')
2332
            );
2333
        $end_date   = isset($this->_req_data['txn-filter-end-date'])
2334
            ? wp_strip_all_tags($this->_req_data['txn-filter-end-date'])
2335
            : date('m/d/Y');
2336
2337
        //make sure our timestamps start and end right at the boundaries for each day
2338
        $start_date = date('Y-m-d', strtotime($start_date)) . ' 00:00:00';
2339
        $end_date   = date('Y-m-d', strtotime($end_date)) . ' 23:59:59';
2340
2341
2342
        //convert to timestamps
2343
        $start_date = strtotime($start_date);
2344
        $end_date   = strtotime($end_date);
2345
2346
        //makes sure start date is the lowest value and vice versa
2347
        $start_date = min($start_date, $end_date);
2348
        $end_date   = max($start_date, $end_date);
2349
2350
        //convert to correct format for query
2351
        $start_date = EEM_Transaction::instance()->convert_datetime_for_query(
2352
            'TXN_timestamp',
2353
            date('Y-m-d H:i:s', $start_date),
2354
            'Y-m-d H:i:s'
2355
        );
2356
        $end_date   = EEM_Transaction::instance()->convert_datetime_for_query(
2357
            'TXN_timestamp',
2358
            date('Y-m-d H:i:s', $end_date),
2359
            'Y-m-d H:i:s'
2360
        );
2361
2362
2363
        //set orderby
2364
        $this->_req_data['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : '';
2365
2366
        switch ($this->_req_data['orderby']) {
2367
            case 'TXN_ID':
2368
                $orderby = 'TXN_ID';
2369
                break;
2370
            case 'ATT_fname':
2371
                $orderby = 'Registration.Attendee.ATT_fname';
2372
                break;
2373
            case 'event_name':
2374
                $orderby = 'Registration.Event.EVT_name';
2375
                break;
2376
            default: //'TXN_timestamp'
2377
                $orderby = 'TXN_timestamp';
2378
        }
2379
2380
        $sort         = ! empty($this->_req_data['order']) ? $this->_req_data['order'] : 'DESC';
2381
        $current_page = ! empty($this->_req_data['paged']) ? $this->_req_data['paged'] : 1;
2382
        $per_page     = ! empty($perpage) ? $perpage : 10;
2383
        $per_page     = ! empty($this->_req_data['perpage']) ? $this->_req_data['perpage'] : $per_page;
2384
2385
        $offset = ($current_page - 1) * $per_page;
2386
        $limit  = array($offset, $per_page);
2387
2388
        $_where = array(
2389
            'TXN_timestamp'          => array('BETWEEN', array($start_date, $end_date)),
2390
            'Registration.REG_count' => 1,
2391
        );
2392
2393
        if (isset($this->_req_data['EVT_ID'])) {
2394
            $_where['Registration.EVT_ID'] = $this->_req_data['EVT_ID'];
2395
        }
2396
2397
        if (isset($this->_req_data['s'])) {
2398
            $search_string = '%' . $this->_req_data['s'] . '%';
2399
            $_where['OR']  = array(
2400
                'Registration.Event.EVT_name'         => array('LIKE', $search_string),
2401
                'Registration.Event.EVT_desc'         => array('LIKE', $search_string),
2402
                'Registration.Event.EVT_short_desc'   => array('LIKE', $search_string),
2403
                'Registration.Attendee.ATT_full_name' => array('LIKE', $search_string),
2404
                'Registration.Attendee.ATT_fname'     => array('LIKE', $search_string),
2405
                'Registration.Attendee.ATT_lname'     => array('LIKE', $search_string),
2406
                'Registration.Attendee.ATT_short_bio' => array('LIKE', $search_string),
2407
                'Registration.Attendee.ATT_email'     => array('LIKE', $search_string),
2408
                'Registration.Attendee.ATT_address'   => array('LIKE', $search_string),
2409
                'Registration.Attendee.ATT_address2'  => array('LIKE', $search_string),
2410
                'Registration.Attendee.ATT_city'      => array('LIKE', $search_string),
2411
                'Registration.REG_final_price'        => array('LIKE', $search_string),
2412
                'Registration.REG_code'               => array('LIKE', $search_string),
2413
                'Registration.REG_count'              => array('LIKE', $search_string),
2414
                'Registration.REG_group_size'         => array('LIKE', $search_string),
2415
                'Registration.Ticket.TKT_name'        => array('LIKE', $search_string),
2416
                'Registration.Ticket.TKT_description' => array('LIKE', $search_string),
2417
                'Payment.PAY_source'                  => array('LIKE', $search_string),
2418
                'Payment.Payment_Method.PMD_name'     => array('LIKE', $search_string),
2419
                'TXN_session_data'                    => array('LIKE', $search_string),
2420
                'Payment.PAY_txn_id_chq_nmbr'         => array('LIKE', $search_string),
2421
            );
2422
        }
2423
2424
        //failed transactions
2425
        $failed    = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'failed' && ! $count)
2426
                     || ($count && $view === 'failed');
2427
        $abandoned = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'abandoned' && ! $count)
2428
                     || ($count && $view === 'abandoned');
2429
2430
        if ($failed) {
2431
            $_where['STS_ID'] = EEM_Transaction::failed_status_code;
2432
        } else if ($abandoned) {
2433
            $_where['STS_ID'] = EEM_Transaction::abandoned_status_code;
2434
        } else {
2435
            $_where['STS_ID']  = array('!=', EEM_Transaction::failed_status_code);
2436
            $_where['STS_ID*'] = array('!=', EEM_Transaction::abandoned_status_code);
2437
        }
2438
2439
        $query_params = array(
2440
            $_where,
2441
            'order_by'                 => array($orderby => $sort),
2442
            'limit'                    => $limit,
2443
            'default_where_conditions' => EEM_Base::default_where_conditions_this_only,
2444
        );
2445
2446
        $transactions = $count
2447
            ? $TXN->count(array($_where), 'TXN_ID', true)
2448
            : $TXN->get_all($query_params);
2449
2450
        return $transactions;
2451
    }
2452
}
2453