Completed
Branch FET/recalculate-line-items (ca7804)
by
unknown
52:45 queued 44:17
created
core/helpers/EEH_Line_Item.helper.php 1 patch
Indentation   +2041 added lines, -2041 removed lines patch added patch discarded remove patch
@@ -21,2045 +21,2045 @@
 block discarded – undo
21 21
 class EEH_Line_Item
22 22
 {
23 23
 
24
-    /**
25
-     * Adds a simple item (unrelated to any other model object) to the provided PARENT line item.
26
-     * Does NOT automatically re-calculate the line item totals or update the related transaction.
27
-     * You should call recalculate_total_including_taxes() on the grant total line item after this
28
-     * to update the subtotals, and EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
29
-     * to keep the registration final prices in-sync with the transaction's total.
30
-     *
31
-     * @param EE_Line_Item $parent_line_item
32
-     * @param string       $name
33
-     * @param float        $unit_price
34
-     * @param string       $description
35
-     * @param int          $quantity
36
-     * @param boolean      $taxable
37
-     * @param boolean      $code if set to a value, ensures there is only one line item with that code
38
-     * @return boolean success
39
-     * @throws EE_Error
40
-     * @throws InvalidArgumentException
41
-     * @throws InvalidDataTypeException
42
-     * @throws InvalidInterfaceException
43
-     * @throws ReflectionException
44
-     */
45
-    public static function add_unrelated_item(
46
-        EE_Line_Item $parent_line_item,
47
-        $name,
48
-        $unit_price,
49
-        $description = '',
50
-        $quantity = 1,
51
-        $taxable = false,
52
-        $code = null
53
-    ) {
54
-        $items_subtotal = self::get_pre_tax_subtotal($parent_line_item);
55
-        $line_item = EE_Line_Item::new_instance(array(
56
-            'LIN_name'       => $name,
57
-            'LIN_desc'       => $description,
58
-            'LIN_unit_price' => $unit_price,
59
-            'LIN_quantity'   => $quantity,
60
-            'LIN_percent'    => null,
61
-            'LIN_is_taxable' => $taxable,
62
-            'LIN_order'      => $items_subtotal instanceof EE_Line_Item ? count($items_subtotal->children()) : 0,
63
-            'LIN_total'      => (float) $unit_price * (int) $quantity,
64
-            'LIN_type'       => EEM_Line_Item::type_line_item,
65
-            'LIN_code'       => $code,
66
-        ));
67
-        $line_item = apply_filters(
68
-            'FHEE__EEH_Line_Item__add_unrelated_item__line_item',
69
-            $line_item,
70
-            $parent_line_item
71
-        );
72
-        return self::add_item($parent_line_item, $line_item);
73
-    }
74
-
75
-
76
-    /**
77
-     * Adds a simple item ( unrelated to any other model object) to the total line item,
78
-     * in the correct spot in the line item tree. Automatically
79
-     * re-calculates the line item totals and updates the related transaction. But
80
-     * DOES NOT automatically upgrade the transaction's registrations' final prices (which
81
-     * should probably change because of this).
82
-     * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
83
-     * after using this, to keep the registration final prices in-sync with the transaction's total.
84
-     *
85
-     * @param EE_Line_Item $parent_line_item
86
-     * @param string       $name
87
-     * @param float        $percentage_amount
88
-     * @param string       $description
89
-     * @param boolean      $taxable
90
-     * @return boolean success
91
-     * @throws EE_Error
92
-     */
93
-    public static function add_percentage_based_item(
94
-        EE_Line_Item $parent_line_item,
95
-        $name,
96
-        $percentage_amount,
97
-        $description = '',
98
-        $taxable = false
99
-    ) {
100
-        $line_item = EE_Line_Item::new_instance(array(
101
-            'LIN_name'       => $name,
102
-            'LIN_desc'       => $description,
103
-            'LIN_unit_price' => 0,
104
-            'LIN_percent'    => $percentage_amount,
105
-            'LIN_quantity'   => 1,
106
-            'LIN_is_taxable' => $taxable,
107
-            'LIN_total'      => (float) ($percentage_amount * ($parent_line_item->total() / 100)),
108
-            'LIN_type'       => EEM_Line_Item::type_line_item,
109
-            'LIN_parent'     => $parent_line_item->ID(),
110
-        ));
111
-        $line_item = apply_filters(
112
-            'FHEE__EEH_Line_Item__add_percentage_based_item__line_item',
113
-            $line_item
114
-        );
115
-        return $parent_line_item->add_child_line_item($line_item, false);
116
-    }
117
-
118
-
119
-    /**
120
-     * Returns the new line item created by adding a purchase of the ticket
121
-     * ensures that ticket line item is saved, and that cart total has been recalculated.
122
-     * If this ticket has already been purchased, just increments its count.
123
-     * Automatically re-calculates the line item totals and updates the related transaction. But
124
-     * DOES NOT automatically upgrade the transaction's registrations' final prices (which
125
-     * should probably change because of this).
126
-     * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
127
-     * after using this, to keep the registration final prices in-sync with the transaction's total.
128
-     *
129
-     * @param EE_Line_Item $total_line_item grand total line item of type EEM_Line_Item::type_total
130
-     * @param EE_Ticket    $ticket
131
-     * @param int          $qty
132
-     * @return EE_Line_Item
133
-     * @throws EE_Error
134
-     * @throws InvalidArgumentException
135
-     * @throws InvalidDataTypeException
136
-     * @throws InvalidInterfaceException
137
-     * @throws ReflectionException
138
-     */
139
-    public static function add_ticket_purchase(EE_Line_Item $total_line_item, EE_Ticket $ticket, $qty = 1)
140
-    {
141
-        if (! $total_line_item instanceof EE_Line_Item || ! $total_line_item->is_total()) {
142
-            throw new EE_Error(
143
-                sprintf(
144
-                    esc_html__(
145
-                        'A valid line item total is required in order to add tickets. A line item of type "%s" was passed.',
146
-                        'event_espresso'
147
-                    ),
148
-                    $ticket->ID(),
149
-                    $total_line_item->ID()
150
-                )
151
-            );
152
-        }
153
-        // either increment the qty for an existing ticket
154
-        $line_item = self::increment_ticket_qty_if_already_in_cart($total_line_item, $ticket, $qty);
155
-        // or add a new one
156
-        if (! $line_item instanceof EE_Line_Item) {
157
-            $line_item = self::create_ticket_line_item($total_line_item, $ticket, $qty);
158
-        }
159
-        $total_line_item->recalculate_total_including_taxes();
160
-        return $line_item;
161
-    }
162
-
163
-
164
-    /**
165
-     * Returns the new line item created by adding a purchase of the ticket
166
-     *
167
-     * @param EE_Line_Item $total_line_item
168
-     * @param EE_Ticket    $ticket
169
-     * @param int          $qty
170
-     * @return EE_Line_Item
171
-     * @throws EE_Error
172
-     * @throws InvalidArgumentException
173
-     * @throws InvalidDataTypeException
174
-     * @throws InvalidInterfaceException
175
-     * @throws ReflectionException
176
-     */
177
-    public static function increment_ticket_qty_if_already_in_cart(
178
-        EE_Line_Item $total_line_item,
179
-        EE_Ticket $ticket,
180
-        $qty = 1
181
-    ) {
182
-        $line_item = null;
183
-        if ($total_line_item instanceof EE_Line_Item && $total_line_item->is_total()) {
184
-            $ticket_line_items = EEH_Line_Item::get_ticket_line_items($total_line_item);
185
-            foreach ((array) $ticket_line_items as $ticket_line_item) {
186
-                if ($ticket_line_item instanceof EE_Line_Item
187
-                    && (int) $ticket_line_item->OBJ_ID() === (int) $ticket->ID()
188
-                ) {
189
-                    $line_item = $ticket_line_item;
190
-                    break;
191
-                }
192
-            }
193
-        }
194
-        if ($line_item instanceof EE_Line_Item) {
195
-            EEH_Line_Item::increment_quantity($line_item, $qty);
196
-            return $line_item;
197
-        }
198
-        return null;
199
-    }
200
-
201
-
202
-    /**
203
-     * Increments the line item and all its children's quantity by $qty (but percent line items are unaffected).
204
-     * Does NOT save or recalculate other line items totals
205
-     *
206
-     * @param EE_Line_Item $line_item
207
-     * @param int          $qty
208
-     * @return void
209
-     * @throws EE_Error
210
-     * @throws InvalidArgumentException
211
-     * @throws InvalidDataTypeException
212
-     * @throws InvalidInterfaceException
213
-     * @throws ReflectionException
214
-     */
215
-    public static function increment_quantity(EE_Line_Item $line_item, $qty = 1)
216
-    {
217
-        if (! $line_item->is_percent()) {
218
-            $qty += $line_item->quantity();
219
-            $line_item->set_quantity($qty);
220
-            $line_item->set_total($line_item->unit_price() * $qty);
221
-            $line_item->save();
222
-        }
223
-        foreach ($line_item->children() as $child) {
224
-            if ($child->is_sub_line_item()) {
225
-                EEH_Line_Item::update_quantity($child, $qty);
226
-            }
227
-        }
228
-    }
229
-
230
-
231
-    /**
232
-     * Decrements the line item and all its children's quantity by $qty (but percent line items are unaffected).
233
-     * Does NOT save or recalculate other line items totals
234
-     *
235
-     * @param EE_Line_Item $line_item
236
-     * @param int          $qty
237
-     * @return void
238
-     * @throws EE_Error
239
-     * @throws InvalidArgumentException
240
-     * @throws InvalidDataTypeException
241
-     * @throws InvalidInterfaceException
242
-     * @throws ReflectionException
243
-     */
244
-    public static function decrement_quantity(EE_Line_Item $line_item, $qty = 1)
245
-    {
246
-        if (! $line_item->is_percent()) {
247
-            $qty = $line_item->quantity() - $qty;
248
-            $qty = max($qty, 0);
249
-            $line_item->set_quantity($qty);
250
-            $line_item->set_total($line_item->unit_price() * $qty);
251
-            $line_item->save();
252
-        }
253
-        foreach ($line_item->children() as $child) {
254
-            if ($child->is_sub_line_item()) {
255
-                EEH_Line_Item::update_quantity($child, $qty);
256
-            }
257
-        }
258
-    }
259
-
260
-
261
-    /**
262
-     * Updates the line item and its children's quantities to the specified number.
263
-     * Does NOT save them or recalculate totals.
264
-     *
265
-     * @param EE_Line_Item $line_item
266
-     * @param int          $new_quantity
267
-     * @throws EE_Error
268
-     * @throws InvalidArgumentException
269
-     * @throws InvalidDataTypeException
270
-     * @throws InvalidInterfaceException
271
-     * @throws ReflectionException
272
-     */
273
-    public static function update_quantity(EE_Line_Item $line_item, $new_quantity)
274
-    {
275
-        if (! $line_item->is_percent()) {
276
-            $line_item->set_quantity($new_quantity);
277
-            $line_item->set_total($line_item->unit_price() * $new_quantity);
278
-            $line_item->save();
279
-        }
280
-        foreach ($line_item->children() as $child) {
281
-            if ($child->is_sub_line_item()) {
282
-                EEH_Line_Item::update_quantity($child, $new_quantity);
283
-            }
284
-        }
285
-    }
286
-
287
-
288
-    /**
289
-     * Returns the new line item created by adding a purchase of the ticket
290
-     *
291
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
292
-     * @param EE_Ticket    $ticket
293
-     * @param int          $qty
294
-     * @return EE_Line_Item
295
-     * @throws EE_Error
296
-     * @throws InvalidArgumentException
297
-     * @throws InvalidDataTypeException
298
-     * @throws InvalidInterfaceException
299
-     * @throws ReflectionException
300
-     */
301
-    public static function create_ticket_line_item(EE_Line_Item $total_line_item, EE_Ticket $ticket, $qty = 1)
302
-    {
303
-        $datetimes = $ticket->datetimes();
304
-        $first_datetime = reset($datetimes);
305
-        $first_datetime_name = esc_html__('Event', 'event_espresso');
306
-        if ($first_datetime instanceof EE_Datetime && $first_datetime->event() instanceof EE_Event) {
307
-            $first_datetime_name = $first_datetime->event()->name();
308
-        }
309
-        $event = sprintf(_x('(For %1$s)', '(For Event Name)', 'event_espresso'), $first_datetime_name);
310
-        // get event subtotal line
311
-        $events_sub_total = self::get_event_line_item_for_ticket($total_line_item, $ticket);
312
-        // add $ticket to cart
313
-        $line_item = EE_Line_Item::new_instance(array(
314
-            'LIN_name'       => $ticket->name(),
315
-            'LIN_desc'       => $ticket->description() !== '' ? $ticket->description() . ' ' . $event : $event,
316
-            'LIN_unit_price' => $ticket->price(),
317
-            'LIN_quantity'   => $qty,
318
-            'LIN_is_taxable' => $ticket->taxable(),
319
-            'LIN_order'      => count($events_sub_total->children()),
320
-            'LIN_total'      => $ticket->price() * $qty,
321
-            'LIN_type'       => EEM_Line_Item::type_line_item,
322
-            'OBJ_ID'         => $ticket->ID(),
323
-            'OBJ_type'       => EEM_Line_Item::OBJ_TYPE_TICKET,
324
-        ));
325
-        $line_item = apply_filters(
326
-            'FHEE__EEH_Line_Item__create_ticket_line_item__line_item',
327
-            $line_item
328
-        );
329
-        $events_sub_total->add_child_line_item($line_item);
330
-        // now add the sub-line items
331
-        $running_total_for_ticket = 0;
332
-        foreach ($ticket->prices(array('order_by' => array('PRC_order' => 'ASC'))) as $price) {
333
-            $sign = $price->is_discount() ? -1 : 1;
334
-            $price_total = $price->is_percent()
335
-                ? $running_total_for_ticket * $price->amount() / 100
336
-                : $price->amount() * $qty;
337
-            $sub_line_item = EE_Line_Item::new_instance(array(
338
-                'LIN_name'       => $price->name(),
339
-                'LIN_desc'       => $price->desc(),
340
-                'LIN_quantity'   => $price->is_percent() ? null : $qty,
341
-                'LIN_is_taxable' => false,
342
-                'LIN_order'      => $price->order(),
343
-                'LIN_total'      => $sign * $price_total,
344
-                'LIN_type'       => EEM_Line_Item::type_sub_line_item,
345
-                'OBJ_ID'         => $price->ID(),
346
-                'OBJ_type'       => EEM_Line_Item::OBJ_TYPE_PRICE,
347
-            ));
348
-            $sub_line_item = apply_filters(
349
-                'FHEE__EEH_Line_Item__create_ticket_line_item__sub_line_item',
350
-                $sub_line_item
351
-            );
352
-            if ($price->is_percent()) {
353
-                $sub_line_item->set_percent($sign * $price->amount());
354
-            } else {
355
-                $sub_line_item->set_unit_price($sign * $price->amount());
356
-            }
357
-            $running_total_for_ticket += $price_total;
358
-            $line_item->add_child_line_item($sub_line_item);
359
-        }
360
-        return $line_item;
361
-    }
362
-
363
-
364
-    /**
365
-     * Adds the specified item under the pre-tax-sub-total line item. Automatically
366
-     * re-calculates the line item totals and updates the related transaction. But
367
-     * DOES NOT automatically upgrade the transaction's registrations' final prices (which
368
-     * should probably change because of this).
369
-     * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
370
-     * after using this, to keep the registration final prices in-sync with the transaction's total.
371
-     *
372
-     * @param EE_Line_Item $total_line_item
373
-     * @param EE_Line_Item $item to be added
374
-     * @return boolean
375
-     * @throws EE_Error
376
-     * @throws InvalidArgumentException
377
-     * @throws InvalidDataTypeException
378
-     * @throws InvalidInterfaceException
379
-     * @throws ReflectionException
380
-     */
381
-    public static function add_item(EE_Line_Item $total_line_item, EE_Line_Item $item)
382
-    {
383
-        $pre_tax_subtotal = self::get_pre_tax_subtotal($total_line_item);
384
-        if ($pre_tax_subtotal instanceof EE_Line_Item) {
385
-            $success = $pre_tax_subtotal->add_child_line_item($item);
386
-        } else {
387
-            return false;
388
-        }
389
-        $total_line_item->recalculate_total_including_taxes();
390
-        return $success;
391
-    }
392
-
393
-
394
-    /**
395
-     * cancels an existing ticket line item,
396
-     * by decrementing it's quantity by 1 and adding a new "type_cancellation" sub-line-item.
397
-     * ALL totals and subtotals will NEED TO BE UPDATED after performing this action
398
-     *
399
-     * @param EE_Line_Item $ticket_line_item
400
-     * @param int          $qty
401
-     * @return bool success
402
-     * @throws EE_Error
403
-     * @throws InvalidArgumentException
404
-     * @throws InvalidDataTypeException
405
-     * @throws InvalidInterfaceException
406
-     * @throws ReflectionException
407
-     */
408
-    public static function cancel_ticket_line_item(EE_Line_Item $ticket_line_item, $qty = 1)
409
-    {
410
-        // validate incoming line_item
411
-        if ($ticket_line_item->OBJ_type() !== EEM_Line_Item::OBJ_TYPE_TICKET) {
412
-            throw new EE_Error(
413
-                sprintf(
414
-                    esc_html__(
415
-                        'The supplied line item must have an Object Type of "Ticket", not %1$s.',
416
-                        'event_espresso'
417
-                    ),
418
-                    $ticket_line_item->type()
419
-                )
420
-            );
421
-        }
422
-        if ($ticket_line_item->quantity() < $qty) {
423
-            throw new EE_Error(
424
-                sprintf(
425
-                    esc_html__(
426
-                        'Can not cancel %1$d ticket(s) because the supplied line item has a quantity of %2$d.',
427
-                        'event_espresso'
428
-                    ),
429
-                    $qty,
430
-                    $ticket_line_item->quantity()
431
-                )
432
-            );
433
-        }
434
-        // decrement ticket quantity; don't rely on auto-fixing when recalculating totals to do this
435
-        $ticket_line_item->set_quantity($ticket_line_item->quantity() - $qty);
436
-        foreach ($ticket_line_item->children() as $child_line_item) {
437
-            if ($child_line_item->is_sub_line_item()
438
-                && ! $child_line_item->is_percent()
439
-                && ! $child_line_item->is_cancellation()
440
-            ) {
441
-                $child_line_item->set_quantity($child_line_item->quantity() - $qty);
442
-            }
443
-        }
444
-        // get cancellation sub line item
445
-        $cancellation_line_item = EEH_Line_Item::get_descendants_of_type(
446
-            $ticket_line_item,
447
-            EEM_Line_Item::type_cancellation
448
-        );
449
-        $cancellation_line_item = reset($cancellation_line_item);
450
-        // verify that this ticket was indeed previously cancelled
451
-        if ($cancellation_line_item instanceof EE_Line_Item) {
452
-            // increment cancelled quantity
453
-            $cancellation_line_item->set_quantity($cancellation_line_item->quantity() + $qty);
454
-        } else {
455
-            // create cancellation sub line item
456
-            $cancellation_line_item = EE_Line_Item::new_instance(array(
457
-                'LIN_name'       => esc_html__('Cancellation', 'event_espresso'),
458
-                'LIN_desc'       => sprintf(
459
-                    esc_html_x(
460
-                        'Cancelled %1$s : %2$s',
461
-                        'Cancelled Ticket Name : 2015-01-01 11:11',
462
-                        'event_espresso'
463
-                    ),
464
-                    $ticket_line_item->name(),
465
-                    current_time(get_option('date_format') . ' ' . get_option('time_format'))
466
-                ),
467
-                'LIN_unit_price' => 0, // $ticket_line_item->unit_price()
468
-                'LIN_quantity'   => $qty,
469
-                'LIN_is_taxable' => $ticket_line_item->is_taxable(),
470
-                'LIN_order'      => count($ticket_line_item->children()),
471
-                'LIN_total'      => 0, // $ticket_line_item->unit_price()
472
-                'LIN_type'       => EEM_Line_Item::type_cancellation,
473
-            ));
474
-            $ticket_line_item->add_child_line_item($cancellation_line_item);
475
-        }
476
-        if ($ticket_line_item->save_this_and_descendants() > 0) {
477
-            // decrement parent line item quantity
478
-            $event_line_item = $ticket_line_item->parent();
479
-            if ($event_line_item instanceof EE_Line_Item
480
-                && $event_line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_EVENT
481
-            ) {
482
-                $event_line_item->set_quantity($event_line_item->quantity() - $qty);
483
-                $event_line_item->save();
484
-            }
485
-            EEH_Line_Item::get_grand_total_and_recalculate_everything($ticket_line_item);
486
-            return true;
487
-        }
488
-        return false;
489
-    }
490
-
491
-
492
-    /**
493
-     * reinstates (un-cancels?) a previously canceled ticket line item,
494
-     * by incrementing it's quantity by 1, and decrementing it's "type_cancellation" sub-line-item.
495
-     * ALL totals and subtotals will NEED TO BE UPDATED after performing this action
496
-     *
497
-     * @param EE_Line_Item $ticket_line_item
498
-     * @param int          $qty
499
-     * @return bool success
500
-     * @throws EE_Error
501
-     * @throws InvalidArgumentException
502
-     * @throws InvalidDataTypeException
503
-     * @throws InvalidInterfaceException
504
-     * @throws ReflectionException
505
-     */
506
-    public static function reinstate_canceled_ticket_line_item(EE_Line_Item $ticket_line_item, $qty = 1)
507
-    {
508
-        // validate incoming line_item
509
-        if ($ticket_line_item->OBJ_type() !== EEM_Line_Item::OBJ_TYPE_TICKET) {
510
-            throw new EE_Error(
511
-                sprintf(
512
-                    esc_html__(
513
-                        'The supplied line item must have an Object Type of "Ticket", not %1$s.',
514
-                        'event_espresso'
515
-                    ),
516
-                    $ticket_line_item->type()
517
-                )
518
-            );
519
-        }
520
-        // get cancellation sub line item
521
-        $cancellation_line_item = EEH_Line_Item::get_descendants_of_type(
522
-            $ticket_line_item,
523
-            EEM_Line_Item::type_cancellation
524
-        );
525
-        $cancellation_line_item = reset($cancellation_line_item);
526
-        // verify that this ticket was indeed previously cancelled
527
-        if (! $cancellation_line_item instanceof EE_Line_Item) {
528
-            return false;
529
-        }
530
-        if ($cancellation_line_item->quantity() > $qty) {
531
-            // decrement cancelled quantity
532
-            $cancellation_line_item->set_quantity($cancellation_line_item->quantity() - $qty);
533
-        } elseif ($cancellation_line_item->quantity() === $qty) {
534
-            // decrement cancelled quantity in case anyone still has the object kicking around
535
-            $cancellation_line_item->set_quantity($cancellation_line_item->quantity() - $qty);
536
-            // delete because quantity will end up as 0
537
-            $cancellation_line_item->delete();
538
-            // and attempt to destroy the object,
539
-            // even though PHP won't actually destroy it until it needs the memory
540
-            unset($cancellation_line_item);
541
-        } else {
542
-            // what ?!?! negative quantity ?!?!
543
-            throw new EE_Error(
544
-                sprintf(
545
-                    esc_html__(
546
-                        'Can not reinstate %1$d cancelled ticket(s) because the cancelled ticket quantity is only %2$d.',
547
-                        'event_espresso'
548
-                    ),
549
-                    $qty,
550
-                    $cancellation_line_item->quantity()
551
-                )
552
-            );
553
-        }
554
-        // increment ticket quantity
555
-        $ticket_line_item->set_quantity($ticket_line_item->quantity() + $qty);
556
-        if ($ticket_line_item->save_this_and_descendants() > 0) {
557
-            // increment parent line item quantity
558
-            $event_line_item = $ticket_line_item->parent();
559
-            if ($event_line_item instanceof EE_Line_Item
560
-                && $event_line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_EVENT
561
-            ) {
562
-                $event_line_item->set_quantity($event_line_item->quantity() + $qty);
563
-            }
564
-            EEH_Line_Item::get_grand_total_and_recalculate_everything($ticket_line_item);
565
-            return true;
566
-        }
567
-        return false;
568
-    }
569
-
570
-
571
-    /**
572
-     * calls EEH_Line_Item::find_transaction_grand_total_for_line_item()
573
-     * then EE_Line_Item::recalculate_total_including_taxes() on the result
574
-     *
575
-     * @param EE_Line_Item $line_item
576
-     * @return float
577
-     * @throws EE_Error
578
-     * @throws InvalidArgumentException
579
-     * @throws InvalidDataTypeException
580
-     * @throws InvalidInterfaceException
581
-     * @throws ReflectionException
582
-     */
583
-    public static function get_grand_total_and_recalculate_everything(EE_Line_Item $line_item)
584
-    {
585
-        $grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($line_item);
586
-        return $grand_total_line_item->recalculate_total_including_taxes();
587
-    }
588
-
589
-
590
-    /**
591
-     * Gets the line item which contains the subtotal of all the items
592
-     *
593
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
594
-     * @return EE_Line_Item
595
-     * @throws EE_Error
596
-     * @throws InvalidArgumentException
597
-     * @throws InvalidDataTypeException
598
-     * @throws InvalidInterfaceException
599
-     * @throws ReflectionException
600
-     */
601
-    public static function get_pre_tax_subtotal(EE_Line_Item $total_line_item)
602
-    {
603
-        $pre_tax_subtotal = $total_line_item->get_child_line_item('pre-tax-subtotal');
604
-        return $pre_tax_subtotal instanceof EE_Line_Item
605
-            ? $pre_tax_subtotal
606
-            : self::create_pre_tax_subtotal($total_line_item);
607
-    }
608
-
609
-
610
-    /**
611
-     * Gets the line item for the taxes subtotal
612
-     *
613
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
614
-     * @return EE_Line_Item
615
-     * @throws EE_Error
616
-     * @throws InvalidArgumentException
617
-     * @throws InvalidDataTypeException
618
-     * @throws InvalidInterfaceException
619
-     * @throws ReflectionException
620
-     */
621
-    public static function get_taxes_subtotal(EE_Line_Item $total_line_item)
622
-    {
623
-        $taxes = $total_line_item->get_child_line_item('taxes');
624
-        return $taxes ? $taxes : self::create_taxes_subtotal($total_line_item);
625
-    }
626
-
627
-
628
-    /**
629
-     * sets the TXN ID on an EE_Line_Item if passed a valid EE_Transaction object
630
-     *
631
-     * @param EE_Line_Item   $line_item
632
-     * @param EE_Transaction $transaction
633
-     * @return void
634
-     * @throws EE_Error
635
-     * @throws InvalidArgumentException
636
-     * @throws InvalidDataTypeException
637
-     * @throws InvalidInterfaceException
638
-     * @throws ReflectionException
639
-     */
640
-    public static function set_TXN_ID(EE_Line_Item $line_item, $transaction = null)
641
-    {
642
-        if ($transaction) {
643
-            /** @type EEM_Transaction $EEM_Transaction */
644
-            $EEM_Transaction = EE_Registry::instance()->load_model('Transaction');
645
-            $TXN_ID = $EEM_Transaction->ensure_is_ID($transaction);
646
-            $line_item->set_TXN_ID($TXN_ID);
647
-        }
648
-    }
649
-
650
-
651
-    /**
652
-     * Creates a new default total line item for the transaction,
653
-     * and its tickets subtotal and taxes subtotal line items (and adds the
654
-     * existing taxes as children of the taxes subtotal line item)
655
-     *
656
-     * @param EE_Transaction $transaction
657
-     * @return EE_Line_Item of type total
658
-     * @throws EE_Error
659
-     * @throws InvalidArgumentException
660
-     * @throws InvalidDataTypeException
661
-     * @throws InvalidInterfaceException
662
-     * @throws ReflectionException
663
-     */
664
-    public static function create_total_line_item($transaction = null)
665
-    {
666
-        $total_line_item = EE_Line_Item::new_instance(array(
667
-            'LIN_code' => 'total',
668
-            'LIN_name' => esc_html__('Grand Total', 'event_espresso'),
669
-            'LIN_type' => EEM_Line_Item::type_total,
670
-            'OBJ_type' => EEM_Line_Item::OBJ_TYPE_TRANSACTION,
671
-        ));
672
-        $total_line_item = apply_filters(
673
-            'FHEE__EEH_Line_Item__create_total_line_item__total_line_item',
674
-            $total_line_item
675
-        );
676
-        self::set_TXN_ID($total_line_item, $transaction);
677
-        self::create_pre_tax_subtotal($total_line_item, $transaction);
678
-        self::create_taxes_subtotal($total_line_item, $transaction);
679
-        return $total_line_item;
680
-    }
681
-
682
-
683
-    /**
684
-     * Creates a default items subtotal line item
685
-     *
686
-     * @param EE_Line_Item   $total_line_item
687
-     * @param EE_Transaction $transaction
688
-     * @return EE_Line_Item
689
-     * @throws EE_Error
690
-     * @throws InvalidArgumentException
691
-     * @throws InvalidDataTypeException
692
-     * @throws InvalidInterfaceException
693
-     * @throws ReflectionException
694
-     */
695
-    protected static function create_pre_tax_subtotal(EE_Line_Item $total_line_item, $transaction = null)
696
-    {
697
-        $pre_tax_line_item = EE_Line_Item::new_instance(array(
698
-            'LIN_code' => 'pre-tax-subtotal',
699
-            'LIN_name' => esc_html__('Pre-Tax Subtotal', 'event_espresso'),
700
-            'LIN_type' => EEM_Line_Item::type_sub_total,
701
-        ));
702
-        $pre_tax_line_item = apply_filters(
703
-            'FHEE__EEH_Line_Item__create_pre_tax_subtotal__pre_tax_line_item',
704
-            $pre_tax_line_item
705
-        );
706
-        self::set_TXN_ID($pre_tax_line_item, $transaction);
707
-        $total_line_item->add_child_line_item($pre_tax_line_item);
708
-        self::create_event_subtotal($pre_tax_line_item, $transaction);
709
-        return $pre_tax_line_item;
710
-    }
711
-
712
-
713
-    /**
714
-     * Creates a line item for the taxes subtotal and finds all the tax prices
715
-     * and applies taxes to it
716
-     *
717
-     * @param EE_Line_Item   $total_line_item of type EEM_Line_Item::type_total
718
-     * @param EE_Transaction $transaction
719
-     * @return EE_Line_Item
720
-     * @throws EE_Error
721
-     * @throws InvalidArgumentException
722
-     * @throws InvalidDataTypeException
723
-     * @throws InvalidInterfaceException
724
-     * @throws ReflectionException
725
-     */
726
-    protected static function create_taxes_subtotal(EE_Line_Item $total_line_item, $transaction = null)
727
-    {
728
-        $tax_line_item = EE_Line_Item::new_instance(array(
729
-            'LIN_code'  => 'taxes',
730
-            'LIN_name'  => esc_html__('Taxes', 'event_espresso'),
731
-            'LIN_type'  => EEM_Line_Item::type_tax_sub_total,
732
-            'LIN_order' => 1000,// this should always come last
733
-        ));
734
-        $tax_line_item = apply_filters(
735
-            'FHEE__EEH_Line_Item__create_taxes_subtotal__tax_line_item',
736
-            $tax_line_item
737
-        );
738
-        self::set_TXN_ID($tax_line_item, $transaction);
739
-        $total_line_item->add_child_line_item($tax_line_item);
740
-        // and lastly, add the actual taxes
741
-        self::apply_taxes($total_line_item);
742
-        return $tax_line_item;
743
-    }
744
-
745
-
746
-    /**
747
-     * Creates a default items subtotal line item
748
-     *
749
-     * @param EE_Line_Item   $pre_tax_line_item
750
-     * @param EE_Transaction $transaction
751
-     * @param EE_Event       $event
752
-     * @return EE_Line_Item
753
-     * @throws EE_Error
754
-     * @throws InvalidArgumentException
755
-     * @throws InvalidDataTypeException
756
-     * @throws InvalidInterfaceException
757
-     * @throws ReflectionException
758
-     */
759
-    public static function create_event_subtotal(EE_Line_Item $pre_tax_line_item, $transaction = null, $event = null)
760
-    {
761
-        $event_line_item = EE_Line_Item::new_instance(array(
762
-            'LIN_code' => self::get_event_code($event),
763
-            'LIN_name' => self::get_event_name($event),
764
-            'LIN_desc' => self::get_event_desc($event),
765
-            'LIN_type' => EEM_Line_Item::type_sub_total,
766
-            'OBJ_type' => EEM_Line_Item::OBJ_TYPE_EVENT,
767
-            'OBJ_ID'   => $event instanceof EE_Event ? $event->ID() : 0,
768
-        ));
769
-        $event_line_item = apply_filters(
770
-            'FHEE__EEH_Line_Item__create_event_subtotal__event_line_item',
771
-            $event_line_item
772
-        );
773
-        self::set_TXN_ID($event_line_item, $transaction);
774
-        $pre_tax_line_item->add_child_line_item($event_line_item);
775
-        return $event_line_item;
776
-    }
777
-
778
-
779
-    /**
780
-     * Gets what the event ticket's code SHOULD be
781
-     *
782
-     * @param EE_Event $event
783
-     * @return string
784
-     * @throws EE_Error
785
-     */
786
-    public static function get_event_code($event)
787
-    {
788
-        return 'event-' . ($event instanceof EE_Event ? $event->ID() : '0');
789
-    }
790
-
791
-
792
-    /**
793
-     * Gets the event name
794
-     *
795
-     * @param EE_Event $event
796
-     * @return string
797
-     * @throws EE_Error
798
-     */
799
-    public static function get_event_name($event)
800
-    {
801
-        return $event instanceof EE_Event
802
-            ? mb_substr($event->name(), 0, 245)
803
-            : esc_html__('Event', 'event_espresso');
804
-    }
805
-
806
-
807
-    /**
808
-     * Gets the event excerpt
809
-     *
810
-     * @param EE_Event $event
811
-     * @return string
812
-     * @throws EE_Error
813
-     */
814
-    public static function get_event_desc($event)
815
-    {
816
-        return $event instanceof EE_Event ? $event->short_description() : '';
817
-    }
818
-
819
-
820
-    /**
821
-     * Given the grand total line item and a ticket, finds the event sub-total
822
-     * line item the ticket's purchase should be added onto
823
-     *
824
-     * @access public
825
-     * @param EE_Line_Item $grand_total the grand total line item
826
-     * @param EE_Ticket    $ticket
827
-     * @return EE_Line_Item
828
-     * @throws EE_Error
829
-     * @throws InvalidArgumentException
830
-     * @throws InvalidDataTypeException
831
-     * @throws InvalidInterfaceException
832
-     * @throws ReflectionException
833
-     */
834
-    public static function get_event_line_item_for_ticket(EE_Line_Item $grand_total, EE_Ticket $ticket)
835
-    {
836
-        $first_datetime = $ticket->first_datetime();
837
-        if (! $first_datetime instanceof EE_Datetime) {
838
-            throw new EE_Error(
839
-                sprintf(
840
-                    __('The supplied ticket (ID %d) has no datetimes', 'event_espresso'),
841
-                    $ticket->ID()
842
-                )
843
-            );
844
-        }
845
-        $event = $first_datetime->event();
846
-        if (! $event instanceof EE_Event) {
847
-            throw new EE_Error(
848
-                sprintf(
849
-                    esc_html__(
850
-                        'The supplied ticket (ID %d) has no event data associated with it.',
851
-                        'event_espresso'
852
-                    ),
853
-                    $ticket->ID()
854
-                )
855
-            );
856
-        }
857
-        $events_sub_total = EEH_Line_Item::get_event_line_item($grand_total, $event);
858
-        if (! $events_sub_total instanceof EE_Line_Item) {
859
-            throw new EE_Error(
860
-                sprintf(
861
-                    esc_html__(
862
-                        'There is no events sub-total for ticket %s on total line item %d',
863
-                        'event_espresso'
864
-                    ),
865
-                    $ticket->ID(),
866
-                    $grand_total->ID()
867
-                )
868
-            );
869
-        }
870
-        return $events_sub_total;
871
-    }
872
-
873
-
874
-    /**
875
-     * Gets the event line item
876
-     *
877
-     * @param EE_Line_Item $grand_total
878
-     * @param EE_Event     $event
879
-     * @return EE_Line_Item for the event subtotal which is a child of $grand_total
880
-     * @throws EE_Error
881
-     * @throws InvalidArgumentException
882
-     * @throws InvalidDataTypeException
883
-     * @throws InvalidInterfaceException
884
-     * @throws ReflectionException
885
-     */
886
-    public static function get_event_line_item(EE_Line_Item $grand_total, $event)
887
-    {
888
-        /** @type EE_Event $event */
889
-        $event = EEM_Event::instance()->ensure_is_obj($event, true);
890
-        $event_line_item = null;
891
-        $found = false;
892
-        foreach (EEH_Line_Item::get_event_subtotals($grand_total) as $event_line_item) {
893
-            // default event subtotal, we should only ever find this the first time this method is called
894
-            if (! $event_line_item->OBJ_ID()) {
895
-                // let's use this! but first... set the event details
896
-                EEH_Line_Item::set_event_subtotal_details($event_line_item, $event);
897
-                $found = true;
898
-                break;
899
-            }
900
-            if ($event_line_item->OBJ_ID() === $event->ID()) {
901
-                // found existing line item for this event in the cart, so break out of loop and use this one
902
-                $found = true;
903
-                break;
904
-            }
905
-        }
906
-        if (! $found) {
907
-            // there is no event sub-total yet, so add it
908
-            $pre_tax_subtotal = EEH_Line_Item::get_pre_tax_subtotal($grand_total);
909
-            // create a new "event" subtotal below that
910
-            $event_line_item = EEH_Line_Item::create_event_subtotal($pre_tax_subtotal, null, $event);
911
-            // and set the event details
912
-            EEH_Line_Item::set_event_subtotal_details($event_line_item, $event);
913
-        }
914
-        return $event_line_item;
915
-    }
916
-
917
-
918
-    /**
919
-     * Creates a default items subtotal line item
920
-     *
921
-     * @param EE_Line_Item   $event_line_item
922
-     * @param EE_Event       $event
923
-     * @param EE_Transaction $transaction
924
-     * @return void
925
-     * @throws EE_Error
926
-     * @throws InvalidArgumentException
927
-     * @throws InvalidDataTypeException
928
-     * @throws InvalidInterfaceException
929
-     * @throws ReflectionException
930
-     */
931
-    public static function set_event_subtotal_details(
932
-        EE_Line_Item $event_line_item,
933
-        EE_Event $event,
934
-        $transaction = null
935
-    ) {
936
-        if ($event instanceof EE_Event) {
937
-            $event_line_item->set_code(self::get_event_code($event));
938
-            $event_line_item->set_name(self::get_event_name($event));
939
-            $event_line_item->set_desc(self::get_event_desc($event));
940
-            $event_line_item->set_OBJ_ID($event->ID());
941
-        }
942
-        self::set_TXN_ID($event_line_item, $transaction);
943
-    }
944
-
945
-
946
-    /**
947
-     * Finds what taxes should apply, adds them as tax line items under the taxes sub-total,
948
-     * and recalculates the taxes sub-total and the grand total. Resets the taxes, so
949
-     * any old taxes are removed
950
-     *
951
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
952
-     * @param bool         $update_txn_status
953
-     * @return bool
954
-     * @throws EE_Error
955
-     * @throws InvalidArgumentException
956
-     * @throws InvalidDataTypeException
957
-     * @throws InvalidInterfaceException
958
-     * @throws ReflectionException
959
-     * @throws RuntimeException
960
-     */
961
-    public static function apply_taxes(EE_Line_Item $total_line_item, $update_txn_status = false)
962
-    {
963
-        /** @type EEM_Price $EEM_Price */
964
-        $EEM_Price = EE_Registry::instance()->load_model('Price');
965
-        // get array of taxes via Price Model
966
-        $ordered_taxes = $EEM_Price->get_all_prices_that_are_taxes();
967
-        ksort($ordered_taxes);
968
-        $taxes_line_item = self::get_taxes_subtotal($total_line_item);
969
-        // just to be safe, remove its old tax line items
970
-        $deleted = $taxes_line_item->delete_children_line_items();
971
-        $updates = false;
972
-        // loop thru taxes
973
-        foreach ($ordered_taxes as $order => $taxes) {
974
-            foreach ($taxes as $tax) {
975
-                if ($tax instanceof EE_Price) {
976
-                    $tax_line_item = EE_Line_Item::new_instance(
977
-                        array(
978
-                            'LIN_name'       => $tax->name(),
979
-                            'LIN_desc'       => $tax->desc(),
980
-                            'LIN_percent'    => $tax->amount(),
981
-                            'LIN_is_taxable' => false,
982
-                            'LIN_order'      => $order,
983
-                            'LIN_total'      => 0,
984
-                            'LIN_type'       => EEM_Line_Item::type_tax,
985
-                            'OBJ_type'       => EEM_Line_Item::OBJ_TYPE_PRICE,
986
-                            'OBJ_ID'         => $tax->ID(),
987
-                        )
988
-                    );
989
-                    $tax_line_item = apply_filters(
990
-                        'FHEE__EEH_Line_Item__apply_taxes__tax_line_item',
991
-                        $tax_line_item
992
-                    );
993
-                    $updates = $taxes_line_item->add_child_line_item($tax_line_item) ?
994
-                        true :
995
-                        $updates;
996
-                }
997
-            }
998
-        }
999
-        // only recalculate totals if something changed
1000
-        if ($deleted || $updates) {
1001
-            $total_line_item->recalculate_total_including_taxes($update_txn_status);
1002
-            return true;
1003
-        }
1004
-        return false;
1005
-    }
1006
-
1007
-
1008
-    /**
1009
-     * Ensures that taxes have been applied to the order, if not applies them.
1010
-     * Returns the total amount of tax
1011
-     *
1012
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
1013
-     * @return float
1014
-     * @throws EE_Error
1015
-     * @throws InvalidArgumentException
1016
-     * @throws InvalidDataTypeException
1017
-     * @throws InvalidInterfaceException
1018
-     * @throws ReflectionException
1019
-     */
1020
-    public static function ensure_taxes_applied($total_line_item)
1021
-    {
1022
-        $taxes_subtotal = self::get_taxes_subtotal($total_line_item);
1023
-        if (! $taxes_subtotal->children()) {
1024
-            self::apply_taxes($total_line_item);
1025
-        }
1026
-        return $taxes_subtotal->total();
1027
-    }
1028
-
1029
-
1030
-    /**
1031
-     * Deletes ALL children of the passed line item
1032
-     *
1033
-     * @param EE_Line_Item $parent_line_item
1034
-     * @return bool
1035
-     * @throws EE_Error
1036
-     * @throws InvalidArgumentException
1037
-     * @throws InvalidDataTypeException
1038
-     * @throws InvalidInterfaceException
1039
-     * @throws ReflectionException
1040
-     */
1041
-    public static function delete_all_child_items(EE_Line_Item $parent_line_item)
1042
-    {
1043
-        $deleted = 0;
1044
-        foreach ($parent_line_item->children() as $child_line_item) {
1045
-            if ($child_line_item instanceof EE_Line_Item) {
1046
-                $deleted += EEH_Line_Item::delete_all_child_items($child_line_item);
1047
-                if ($child_line_item->ID()) {
1048
-                    $child_line_item->delete();
1049
-                    unset($child_line_item);
1050
-                } else {
1051
-                    $parent_line_item->delete_child_line_item($child_line_item->code());
1052
-                }
1053
-                $deleted++;
1054
-            }
1055
-        }
1056
-        return $deleted;
1057
-    }
1058
-
1059
-
1060
-    /**
1061
-     * Deletes the line items as indicated by the line item code(s) provided,
1062
-     * regardless of where they're found in the line item tree. Automatically
1063
-     * re-calculates the line item totals and updates the related transaction. But
1064
-     * DOES NOT automatically upgrade the transaction's registrations' final prices (which
1065
-     * should probably change because of this).
1066
-     * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
1067
-     * after using this, to keep the registration final prices in-sync with the transaction's total.
1068
-     *
1069
-     * @param EE_Line_Item      $total_line_item of type EEM_Line_Item::type_total
1070
-     * @param array|bool|string $line_item_codes
1071
-     * @return int number of items successfully removed
1072
-     * @throws EE_Error
1073
-     */
1074
-    public static function delete_items(EE_Line_Item $total_line_item, $line_item_codes = false)
1075
-    {
1076
-
1077
-        if ($total_line_item->type() !== EEM_Line_Item::type_total) {
1078
-            EE_Error::doing_it_wrong(
1079
-                'EEH_Line_Item::delete_items',
1080
-                esc_html__(
1081
-                    'This static method should only be called with a TOTAL line item, otherwise we won\'t recalculate the totals correctly',
1082
-                    'event_espresso'
1083
-                ),
1084
-                '4.6.18'
1085
-            );
1086
-        }
1087
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1088
-
1089
-        // check if only a single line_item_id was passed
1090
-        if (! empty($line_item_codes) && ! is_array($line_item_codes)) {
1091
-            // place single line_item_id in an array to appear as multiple line_item_ids
1092
-            $line_item_codes = array($line_item_codes);
1093
-        }
1094
-        $removals = 0;
1095
-        // cycle thru line_item_ids
1096
-        foreach ($line_item_codes as $line_item_id) {
1097
-            $removals += $total_line_item->delete_child_line_item($line_item_id);
1098
-        }
1099
-
1100
-        if ($removals > 0) {
1101
-            $total_line_item->recalculate_taxes_and_tax_total();
1102
-            return $removals;
1103
-        } else {
1104
-            return false;
1105
-        }
1106
-    }
1107
-
1108
-
1109
-    /**
1110
-     * Overwrites the previous tax by clearing out the old taxes, and creates a new
1111
-     * tax and updates the total line item accordingly
1112
-     *
1113
-     * @param EE_Line_Item $total_line_item
1114
-     * @param float        $amount
1115
-     * @param string       $name
1116
-     * @param string       $description
1117
-     * @param string       $code
1118
-     * @param boolean      $add_to_existing_line_item
1119
-     *                          if true, and a duplicate line item with the same code is found,
1120
-     *                          $amount will be added onto it; otherwise will simply set the taxes to match $amount
1121
-     * @return EE_Line_Item the new tax line item created
1122
-     * @throws EE_Error
1123
-     * @throws InvalidArgumentException
1124
-     * @throws InvalidDataTypeException
1125
-     * @throws InvalidInterfaceException
1126
-     * @throws ReflectionException
1127
-     */
1128
-    public static function set_total_tax_to(
1129
-        EE_Line_Item $total_line_item,
1130
-        $amount,
1131
-        $name = null,
1132
-        $description = null,
1133
-        $code = null,
1134
-        $add_to_existing_line_item = false
1135
-    ) {
1136
-        $tax_subtotal = self::get_taxes_subtotal($total_line_item);
1137
-        $taxable_total = $total_line_item->taxable_total();
1138
-
1139
-        if ($add_to_existing_line_item) {
1140
-            $new_tax = $tax_subtotal->get_child_line_item($code);
1141
-            EEM_Line_Item::instance()->delete(
1142
-                array(array('LIN_code' => array('!=', $code), 'LIN_parent' => $tax_subtotal->ID()))
1143
-            );
1144
-        } else {
1145
-            $new_tax = null;
1146
-            $tax_subtotal->delete_children_line_items();
1147
-        }
1148
-        if ($new_tax) {
1149
-            $new_tax->set_total($new_tax->total() + $amount);
1150
-            $new_tax->set_percent($taxable_total ? $new_tax->total() / $taxable_total * 100 : 0);
1151
-        } else {
1152
-            // no existing tax item. Create it
1153
-            $new_tax = EE_Line_Item::new_instance(array(
1154
-                'TXN_ID'      => $total_line_item->TXN_ID(),
1155
-                'LIN_name'    => $name ? $name : esc_html__('Tax', 'event_espresso'),
1156
-                'LIN_desc'    => $description ? $description : '',
1157
-                'LIN_percent' => $taxable_total ? ($amount / $taxable_total * 100) : 0,
1158
-                'LIN_total'   => $amount,
1159
-                'LIN_parent'  => $tax_subtotal->ID(),
1160
-                'LIN_type'    => EEM_Line_Item::type_tax,
1161
-                'LIN_code'    => $code,
1162
-            ));
1163
-        }
1164
-
1165
-        $new_tax = apply_filters(
1166
-            'FHEE__EEH_Line_Item__set_total_tax_to__new_tax_subtotal',
1167
-            $new_tax,
1168
-            $total_line_item
1169
-        );
1170
-        $new_tax->save();
1171
-        $tax_subtotal->set_total($new_tax->total());
1172
-        $tax_subtotal->save();
1173
-        $total_line_item->recalculate_total_including_taxes();
1174
-        return $new_tax;
1175
-    }
1176
-
1177
-
1178
-    /**
1179
-     * Makes all the line items which are children of $line_item taxable (or not).
1180
-     * Does NOT save the line items
1181
-     *
1182
-     * @param EE_Line_Item $line_item
1183
-     * @param boolean      $taxable
1184
-     * @param string       $code_substring_for_whitelist if this string is part of the line item's code
1185
-     *                                                   it will be whitelisted (ie, except from becoming taxable)
1186
-     * @throws EE_Error
1187
-     */
1188
-    public static function set_line_items_taxable(
1189
-        EE_Line_Item $line_item,
1190
-        $taxable = true,
1191
-        $code_substring_for_whitelist = null
1192
-    ) {
1193
-        $whitelisted = false;
1194
-        if ($code_substring_for_whitelist !== null) {
1195
-            $whitelisted = strpos($line_item->code(), $code_substring_for_whitelist) !== false;
1196
-        }
1197
-        if (! $whitelisted && $line_item->is_line_item()) {
1198
-            $line_item->set_is_taxable($taxable);
1199
-        }
1200
-        foreach ($line_item->children() as $child_line_item) {
1201
-            EEH_Line_Item::set_line_items_taxable(
1202
-                $child_line_item,
1203
-                $taxable,
1204
-                $code_substring_for_whitelist
1205
-            );
1206
-        }
1207
-    }
1208
-
1209
-
1210
-    /**
1211
-     * Gets all descendants that are event subtotals
1212
-     *
1213
-     * @uses  EEH_Line_Item::get_subtotals_of_object_type()
1214
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1215
-     * @return EE_Line_Item[]
1216
-     * @throws EE_Error
1217
-     */
1218
-    public static function get_event_subtotals(EE_Line_Item $parent_line_item)
1219
-    {
1220
-        return self::get_subtotals_of_object_type($parent_line_item, EEM_Line_Item::OBJ_TYPE_EVENT);
1221
-    }
1222
-
1223
-
1224
-    /**
1225
-     * Gets all descendants subtotals that match the supplied object type
1226
-     *
1227
-     * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1228
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1229
-     * @param string       $obj_type
1230
-     * @return EE_Line_Item[]
1231
-     * @throws EE_Error
1232
-     */
1233
-    public static function get_subtotals_of_object_type(EE_Line_Item $parent_line_item, $obj_type = '')
1234
-    {
1235
-        return self::_get_descendants_by_type_and_object_type(
1236
-            $parent_line_item,
1237
-            EEM_Line_Item::type_sub_total,
1238
-            $obj_type
1239
-        );
1240
-    }
1241
-
1242
-
1243
-    /**
1244
-     * Gets all descendants that are tickets
1245
-     *
1246
-     * @uses  EEH_Line_Item::get_line_items_of_object_type()
1247
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1248
-     * @return EE_Line_Item[]
1249
-     * @throws EE_Error
1250
-     */
1251
-    public static function get_ticket_line_items(EE_Line_Item $parent_line_item)
1252
-    {
1253
-        return self::get_line_items_of_object_type(
1254
-            $parent_line_item,
1255
-            EEM_Line_Item::OBJ_TYPE_TICKET
1256
-        );
1257
-    }
1258
-
1259
-
1260
-    /**
1261
-     * Gets all descendants subtotals that match the supplied object type
1262
-     *
1263
-     * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1264
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1265
-     * @param string       $obj_type
1266
-     * @return EE_Line_Item[]
1267
-     * @throws EE_Error
1268
-     */
1269
-    public static function get_line_items_of_object_type(EE_Line_Item $parent_line_item, $obj_type = '')
1270
-    {
1271
-        return self::_get_descendants_by_type_and_object_type(
1272
-            $parent_line_item,
1273
-            EEM_Line_Item::type_line_item,
1274
-            $obj_type
1275
-        );
1276
-    }
1277
-
1278
-
1279
-    /**
1280
-     * Gets all the descendants (ie, children or children of children etc) that are of the type 'tax'
1281
-     *
1282
-     * @uses  EEH_Line_Item::get_descendants_of_type()
1283
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1284
-     * @return EE_Line_Item[]
1285
-     * @throws EE_Error
1286
-     */
1287
-    public static function get_tax_descendants(EE_Line_Item $parent_line_item)
1288
-    {
1289
-        return EEH_Line_Item::get_descendants_of_type(
1290
-            $parent_line_item,
1291
-            EEM_Line_Item::type_tax
1292
-        );
1293
-    }
1294
-
1295
-
1296
-    /**
1297
-     * Gets all the real items purchased which are children of this item
1298
-     *
1299
-     * @uses  EEH_Line_Item::get_descendants_of_type()
1300
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1301
-     * @return EE_Line_Item[]
1302
-     * @throws EE_Error
1303
-     */
1304
-    public static function get_line_item_descendants(EE_Line_Item $parent_line_item)
1305
-    {
1306
-        return EEH_Line_Item::get_descendants_of_type(
1307
-            $parent_line_item,
1308
-            EEM_Line_Item::type_line_item
1309
-        );
1310
-    }
1311
-
1312
-
1313
-    /**
1314
-     * Gets all descendants of supplied line item that match the supplied line item type
1315
-     *
1316
-     * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1317
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1318
-     * @param string       $line_item_type   one of the EEM_Line_Item constants
1319
-     * @return EE_Line_Item[]
1320
-     * @throws EE_Error
1321
-     */
1322
-    public static function get_descendants_of_type(EE_Line_Item $parent_line_item, $line_item_type)
1323
-    {
1324
-        return self::_get_descendants_by_type_and_object_type(
1325
-            $parent_line_item,
1326
-            $line_item_type,
1327
-            null
1328
-        );
1329
-    }
1330
-
1331
-
1332
-    /**
1333
-     * Gets all descendants of supplied line item that match the supplied line item type and possibly the object type
1334
-     * as well
1335
-     *
1336
-     * @param EE_Line_Item  $parent_line_item - the line item to find descendants of
1337
-     * @param string        $line_item_type   one of the EEM_Line_Item constants
1338
-     * @param string | NULL $obj_type         object model class name (minus prefix) or NULL to ignore object type when
1339
-     *                                        searching
1340
-     * @return EE_Line_Item[]
1341
-     * @throws EE_Error
1342
-     */
1343
-    protected static function _get_descendants_by_type_and_object_type(
1344
-        EE_Line_Item $parent_line_item,
1345
-        $line_item_type,
1346
-        $obj_type = null
1347
-    ) {
1348
-        $objects = array();
1349
-        foreach ($parent_line_item->children() as $child_line_item) {
1350
-            if ($child_line_item instanceof EE_Line_Item) {
1351
-                if ($child_line_item->type() === $line_item_type
1352
-                    && (
1353
-                        $child_line_item->OBJ_type() === $obj_type || $obj_type === null
1354
-                    )
1355
-                ) {
1356
-                    $objects[] = $child_line_item;
1357
-                } else {
1358
-                    // go-through-all-its children looking for more matches
1359
-                    $objects = array_merge(
1360
-                        $objects,
1361
-                        self::_get_descendants_by_type_and_object_type(
1362
-                            $child_line_item,
1363
-                            $line_item_type,
1364
-                            $obj_type
1365
-                        )
1366
-                    );
1367
-                }
1368
-            }
1369
-        }
1370
-        return $objects;
1371
-    }
1372
-
1373
-
1374
-    /**
1375
-     * Gets all descendants subtotals that match the supplied object type
1376
-     *
1377
-     * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1378
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1379
-     * @param string       $OBJ_type         object type (like Event)
1380
-     * @param array        $OBJ_IDs          array of OBJ_IDs
1381
-     * @return EE_Line_Item[]
1382
-     * @throws EE_Error
1383
-     */
1384
-    public static function get_line_items_by_object_type_and_IDs(
1385
-        EE_Line_Item $parent_line_item,
1386
-        $OBJ_type = '',
1387
-        $OBJ_IDs = array()
1388
-    ) {
1389
-        return self::_get_descendants_by_object_type_and_object_ID(
1390
-            $parent_line_item,
1391
-            $OBJ_type,
1392
-            $OBJ_IDs
1393
-        );
1394
-    }
1395
-
1396
-
1397
-    /**
1398
-     * Gets all descendants of supplied line item that match the supplied line item type and possibly the object type
1399
-     * as well
1400
-     *
1401
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1402
-     * @param string       $OBJ_type         object type (like Event)
1403
-     * @param array        $OBJ_IDs          array of OBJ_IDs
1404
-     * @return EE_Line_Item[]
1405
-     * @throws EE_Error
1406
-     */
1407
-    protected static function _get_descendants_by_object_type_and_object_ID(
1408
-        EE_Line_Item $parent_line_item,
1409
-        $OBJ_type,
1410
-        $OBJ_IDs
1411
-    ) {
1412
-        $objects = array();
1413
-        foreach ($parent_line_item->children() as $child_line_item) {
1414
-            if ($child_line_item instanceof EE_Line_Item) {
1415
-                if ($child_line_item->OBJ_type() === $OBJ_type
1416
-                    && is_array($OBJ_IDs)
1417
-                    && in_array($child_line_item->OBJ_ID(), $OBJ_IDs)
1418
-                ) {
1419
-                    $objects[] = $child_line_item;
1420
-                } else {
1421
-                    // go-through-all-its children looking for more matches
1422
-                    $objects = array_merge(
1423
-                        $objects,
1424
-                        self::_get_descendants_by_object_type_and_object_ID(
1425
-                            $child_line_item,
1426
-                            $OBJ_type,
1427
-                            $OBJ_IDs
1428
-                        )
1429
-                    );
1430
-                }
1431
-            }
1432
-        }
1433
-        return $objects;
1434
-    }
1435
-
1436
-
1437
-    /**
1438
-     * Uses a breadth-first-search in order to find the nearest descendant of
1439
-     * the specified type and returns it, else NULL
1440
-     *
1441
-     * @uses  EEH_Line_Item::_get_nearest_descendant()
1442
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1443
-     * @param string       $type             like one of the EEM_Line_Item::type_*
1444
-     * @return EE_Line_Item
1445
-     * @throws EE_Error
1446
-     * @throws InvalidArgumentException
1447
-     * @throws InvalidDataTypeException
1448
-     * @throws InvalidInterfaceException
1449
-     * @throws ReflectionException
1450
-     */
1451
-    public static function get_nearest_descendant_of_type(EE_Line_Item $parent_line_item, $type)
1452
-    {
1453
-        return self::_get_nearest_descendant($parent_line_item, 'LIN_type', $type);
1454
-    }
1455
-
1456
-
1457
-    /**
1458
-     * Uses a breadth-first-search in order to find the nearest descendant
1459
-     * having the specified LIN_code and returns it, else NULL
1460
-     *
1461
-     * @uses  EEH_Line_Item::_get_nearest_descendant()
1462
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1463
-     * @param string       $code             any value used for LIN_code
1464
-     * @return EE_Line_Item
1465
-     * @throws EE_Error
1466
-     * @throws InvalidArgumentException
1467
-     * @throws InvalidDataTypeException
1468
-     * @throws InvalidInterfaceException
1469
-     * @throws ReflectionException
1470
-     */
1471
-    public static function get_nearest_descendant_having_code(EE_Line_Item $parent_line_item, $code)
1472
-    {
1473
-        return self::_get_nearest_descendant($parent_line_item, 'LIN_code', $code);
1474
-    }
1475
-
1476
-
1477
-    /**
1478
-     * Uses a breadth-first-search in order to find the nearest descendant
1479
-     * having the specified LIN_code and returns it, else NULL
1480
-     *
1481
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1482
-     * @param string       $search_field     name of EE_Line_Item property
1483
-     * @param string       $value            any value stored in $search_field
1484
-     * @return EE_Line_Item
1485
-     * @throws EE_Error
1486
-     * @throws InvalidArgumentException
1487
-     * @throws InvalidDataTypeException
1488
-     * @throws InvalidInterfaceException
1489
-     * @throws ReflectionException
1490
-     */
1491
-    protected static function _get_nearest_descendant(EE_Line_Item $parent_line_item, $search_field, $value)
1492
-    {
1493
-        foreach ($parent_line_item->children() as $child) {
1494
-            if ($child->get($search_field) == $value) {
1495
-                return $child;
1496
-            }
1497
-        }
1498
-        foreach ($parent_line_item->children() as $child) {
1499
-            $descendant_found = self::_get_nearest_descendant(
1500
-                $child,
1501
-                $search_field,
1502
-                $value
1503
-            );
1504
-            if ($descendant_found) {
1505
-                return $descendant_found;
1506
-            }
1507
-        }
1508
-        return null;
1509
-    }
1510
-
1511
-
1512
-    /**
1513
-     * if passed line item has a TXN ID, uses that to jump directly to the grand total line item for the transaction,
1514
-     * else recursively walks up the line item tree until a parent of type total is found,
1515
-     *
1516
-     * @param EE_Line_Item $line_item
1517
-     * @return EE_Line_Item
1518
-     * @throws EE_Error
1519
-     */
1520
-    public static function find_transaction_grand_total_for_line_item(EE_Line_Item $line_item)
1521
-    {
1522
-        if ($line_item->TXN_ID()) {
1523
-            $total_line_item = $line_item->transaction()->total_line_item(false);
1524
-            if ($total_line_item instanceof EE_Line_Item) {
1525
-                return $total_line_item;
1526
-            }
1527
-        } else {
1528
-            $line_item_parent = $line_item->parent();
1529
-            if ($line_item_parent instanceof EE_Line_Item) {
1530
-                if ($line_item_parent->is_total()) {
1531
-                    return $line_item_parent;
1532
-                }
1533
-                return EEH_Line_Item::find_transaction_grand_total_for_line_item($line_item_parent);
1534
-            }
1535
-        }
1536
-        throw new EE_Error(
1537
-            sprintf(
1538
-                esc_html__(
1539
-                    'A valid grand total for line item %1$d was not found.',
1540
-                    'event_espresso'
1541
-                ),
1542
-                $line_item->ID()
1543
-            )
1544
-        );
1545
-    }
1546
-
1547
-
1548
-    /**
1549
-     * Prints out a representation of the line item tree
1550
-     *
1551
-     * @param EE_Line_Item $line_item
1552
-     * @param int          $indentation
1553
-     * @return void
1554
-     * @throws EE_Error
1555
-     */
1556
-    public static function visualize(EE_Line_Item $line_item, $indentation = 0)
1557
-    {
1558
-        echo defined('EE_TESTS_DIR') ? "\n" : '<br />';
1559
-        if (! $indentation) {
1560
-            echo defined('EE_TESTS_DIR') ? "\n" : '<br />';
1561
-        }
1562
-        for ($i = 0; $i < $indentation; $i++) {
1563
-            echo '. ';
1564
-        }
1565
-        $breakdown = '';
1566
-        if ($line_item->is_line_item()) {
1567
-            if ($line_item->is_percent()) {
1568
-                $breakdown = "{$line_item->percent()}%";
1569
-            } else {
1570
-                $breakdown = '$' . "{$line_item->unit_price()} x {$line_item->quantity()}";
1571
-            }
1572
-        }
1573
-        echo $line_item->name();
1574
-        echo " [ ID:{$line_item->ID()} | qty:{$line_item->quantity()} ] {$line_item->type()} : ";
1575
-        echo '$' . (string) $line_item->total();
1576
-        if ($breakdown) {
1577
-            echo " ( {$breakdown} )";
1578
-        }
1579
-        if ($line_item->is_taxable()) {
1580
-            echo '  * taxable';
1581
-        }
1582
-        if ($line_item->children()) {
1583
-            foreach ($line_item->children() as $child) {
1584
-                self::visualize($child, $indentation + 1);
1585
-            }
1586
-        }
1587
-    }
1588
-
1589
-
1590
-    /**
1591
-     * Calculates the registration's final price, taking into account that they
1592
-     * need to not only help pay for their OWN ticket, but also any transaction-wide surcharges and taxes,
1593
-     * and receive a portion of any transaction-wide discounts.
1594
-     * eg1, if I buy a $1 ticket and brent buys a $9 ticket, and we receive a $5 discount
1595
-     * then I'll get 1/10 of that $5 discount, which is $0.50, and brent will get
1596
-     * 9/10ths of that $5 discount, which is $4.50. So my final price should be $0.50
1597
-     * and brent's final price should be $5.50.
1598
-     * In order to do this, we basically need to traverse the line item tree calculating
1599
-     * the running totals (just as if we were recalculating the total), but when we identify
1600
-     * regular line items, we need to keep track of their share of the grand total.
1601
-     * Also, we need to keep track of the TAXABLE total for each ticket purchase, so
1602
-     * we can know how to apply taxes to it. (Note: "taxable total" does not equal the "pretax total"
1603
-     * when there are non-taxable items; otherwise they would be the same)
1604
-     *
1605
-     * @param EE_Line_Item $line_item
1606
-     * @param array        $billable_ticket_quantities  array of EE_Ticket IDs and their corresponding quantity that
1607
-     *                                                  can be included in price calculations at this moment
1608
-     * @return array        keys are line items for tickets IDs and values are their share of the running total,
1609
-     *                                                  plus the key 'total', and 'taxable' which also has keys of all
1610
-     *                                                  the ticket IDs.
1611
-     *                                                  Eg array(
1612
-     *                                                      12 => 4.3
1613
-     *                                                      23 => 8.0
1614
-     *                                                      'total' => 16.6,
1615
-     *                                                      'taxable' => array(
1616
-     *                                                          12 => 10,
1617
-     *                                                          23 => 4
1618
-     *                                                      ).
1619
-     *                                                  So to find which registrations have which final price, we need
1620
-     *                                                  to find which line item is theirs, which can be done with
1621
-     *                                                  `EEM_Line_Item::instance()->get_line_item_for_registration(
1622
-     *                                                  $registration );`
1623
-     * @throws EE_Error
1624
-     * @throws InvalidArgumentException
1625
-     * @throws InvalidDataTypeException
1626
-     * @throws InvalidInterfaceException
1627
-     * @throws ReflectionException
1628
-     */
1629
-    public static function calculate_reg_final_prices_per_line_item(
1630
-        EE_Line_Item $line_item,
1631
-        $billable_ticket_quantities = array()
1632
-    ) {
1633
-        $running_totals = [
1634
-            'total'   => 0,
1635
-            'taxable' => ['total' => 0]
1636
-        ];
1637
-        foreach ($line_item->children() as $child_line_item) {
1638
-            switch ($child_line_item->type()) {
1639
-                case EEM_Line_Item::type_sub_total:
1640
-                    $running_totals_from_subtotal = EEH_Line_Item::calculate_reg_final_prices_per_line_item(
1641
-                        $child_line_item,
1642
-                        $billable_ticket_quantities
1643
-                    );
1644
-                    // combine arrays but preserve numeric keys
1645
-                    $running_totals = array_replace_recursive($running_totals_from_subtotal, $running_totals);
1646
-                    $running_totals['total'] += $running_totals_from_subtotal['total'];
1647
-                    $running_totals['taxable']['total'] += $running_totals_from_subtotal['taxable']['total'];
1648
-                    break;
1649
-
1650
-                case EEM_Line_Item::type_tax_sub_total:
1651
-                    // find how much the taxes percentage is
1652
-                    if ($child_line_item->percent() !== 0) {
1653
-                        $tax_percent_decimal = $child_line_item->percent() / 100;
1654
-                    } else {
1655
-                        $tax_percent_decimal = EE_Taxes::get_total_taxes_percentage() / 100;
1656
-                    }
1657
-                    // and apply to all the taxable totals, and add to the pretax totals
1658
-                    foreach ($running_totals as $line_item_id => $this_running_total) {
1659
-                        // "total" and "taxable" array key is an exception
1660
-                        if ($line_item_id === 'taxable') {
1661
-                            continue;
1662
-                        }
1663
-                        $taxable_total = $running_totals['taxable'][ $line_item_id ];
1664
-                        $running_totals[ $line_item_id ] += ($taxable_total * $tax_percent_decimal);
1665
-                    }
1666
-                    break;
1667
-
1668
-                case EEM_Line_Item::type_line_item:
1669
-                    // ticket line items or ????
1670
-                    if ($child_line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET) {
1671
-                        // kk it's a ticket
1672
-                        if (isset($running_totals[ $child_line_item->ID() ])) {
1673
-                            // huh? that shouldn't happen.
1674
-                            $running_totals['total'] += $child_line_item->total();
1675
-                        } else {
1676
-                            // its not in our running totals yet. great.
1677
-                            if ($child_line_item->is_taxable()) {
1678
-                                $taxable_amount = $child_line_item->unit_price();
1679
-                            } else {
1680
-                                $taxable_amount = 0;
1681
-                            }
1682
-                            // are we only calculating totals for some tickets?
1683
-                            if (isset($billable_ticket_quantities[ $child_line_item->OBJ_ID() ])) {
1684
-                                $quantity = $billable_ticket_quantities[ $child_line_item->OBJ_ID() ];
1685
-                                $running_totals[ $child_line_item->ID() ] = $quantity
1686
-                                    ? $child_line_item->unit_price()
1687
-                                    : 0;
1688
-                                $running_totals['taxable'][ $child_line_item->ID() ] = $quantity
1689
-                                    ? $taxable_amount
1690
-                                    : 0;
1691
-                            } else {
1692
-                                $quantity = $child_line_item->quantity();
1693
-                                $running_totals[ $child_line_item->ID() ] = $child_line_item->unit_price();
1694
-                                $running_totals['taxable'][ $child_line_item->ID() ] = $taxable_amount;
1695
-                            }
1696
-                            $running_totals['taxable']['total'] += $taxable_amount * $quantity;
1697
-                            $running_totals['total'] += $child_line_item->unit_price() * $quantity;
1698
-                        }
1699
-                    } else {
1700
-                        // it's some other type of item added to the cart
1701
-                        // it should affect the running totals
1702
-                        // basically we want to convert it into a PERCENT modifier. Because
1703
-                        // more clearly affect all registration's final price equally
1704
-                        $line_items_percent_of_running_total = $running_totals['total'] > 0
1705
-                            ? ($child_line_item->total() / $running_totals['total']) + 1
1706
-                            : 1;
1707
-                        foreach ($running_totals as $line_item_id => $this_running_total) {
1708
-                            // the "taxable" array key is an exception
1709
-                            if ($line_item_id === 'taxable') {
1710
-                                continue;
1711
-                            }
1712
-                            // update the running totals
1713
-                            // yes this actually even works for the running grand total!
1714
-                            $running_totals[ $line_item_id ] =
1715
-                                $line_items_percent_of_running_total * $this_running_total;
1716
-
1717
-                            if ($child_line_item->is_taxable()) {
1718
-                                $running_totals['taxable'][ $line_item_id ] =
1719
-                                    $line_items_percent_of_running_total * $running_totals['taxable'][ $line_item_id ];
1720
-                            }
1721
-                        }
1722
-                    }
1723
-                    break;
1724
-            }
1725
-        }
1726
-        return $running_totals;
1727
-    }
1728
-
1729
-
1730
-    /**
1731
-     * @param EE_Line_Item $total_line_item
1732
-     * @param EE_Line_Item $ticket_line_item
1733
-     * @return float | null
1734
-     * @throws EE_Error
1735
-     * @throws InvalidArgumentException
1736
-     * @throws InvalidDataTypeException
1737
-     * @throws InvalidInterfaceException
1738
-     * @throws OutOfRangeException
1739
-     * @throws ReflectionException
1740
-     */
1741
-    public static function calculate_final_price_for_ticket_line_item(
1742
-        EE_Line_Item $total_line_item,
1743
-        EE_Line_Item $ticket_line_item
1744
-    ) {
1745
-        static $final_prices_per_ticket_line_item = array();
1746
-        if (empty($final_prices_per_ticket_line_item)) {
1747
-            $final_prices_per_ticket_line_item = EEH_Line_Item::calculate_reg_final_prices_per_line_item(
1748
-                $total_line_item
1749
-            );
1750
-        }
1751
-        // ok now find this new registration's final price
1752
-        if (isset($final_prices_per_ticket_line_item[ $ticket_line_item->ID() ])) {
1753
-            return $final_prices_per_ticket_line_item[ $ticket_line_item->ID() ];
1754
-        }
1755
-        $message = sprintf(
1756
-            esc_html__(
1757
-                'The final price for the ticket line item (ID:%1$d) could not be calculated.',
1758
-                'event_espresso'
1759
-            ),
1760
-            $ticket_line_item->ID()
1761
-        );
1762
-        if (WP_DEBUG) {
1763
-            $message .= '<br>' . print_r($final_prices_per_ticket_line_item, true);
1764
-            throw new OutOfRangeException($message);
1765
-        }
1766
-        EE_Log::instance()->log(__CLASS__, __FUNCTION__, $message);
1767
-        return null;
1768
-    }
1769
-
1770
-
1771
-    /**
1772
-     * Creates a duplicate of the line item tree, except only includes billable items
1773
-     * and the portion of line items attributed to billable things
1774
-     *
1775
-     * @param EE_Line_Item      $line_item
1776
-     * @param EE_Registration[] $registrations
1777
-     * @return EE_Line_Item
1778
-     * @throws EE_Error
1779
-     * @throws InvalidArgumentException
1780
-     * @throws InvalidDataTypeException
1781
-     * @throws InvalidInterfaceException
1782
-     * @throws ReflectionException
1783
-     */
1784
-    public static function billable_line_item_tree(EE_Line_Item $line_item, $registrations)
1785
-    {
1786
-        $copy_li = EEH_Line_Item::billable_line_item($line_item, $registrations);
1787
-        foreach ($line_item->children() as $child_li) {
1788
-            $copy_li->add_child_line_item(
1789
-                EEH_Line_Item::billable_line_item_tree($child_li, $registrations)
1790
-            );
1791
-        }
1792
-        // if this is the grand total line item, make sure the totals all add up
1793
-        // (we could have duplicated this logic AS we copied the line items, but
1794
-        // it seems DRYer this way)
1795
-        if ($copy_li->type() === EEM_Line_Item::type_total) {
1796
-            $copy_li->recalculate_total_including_taxes();
1797
-        }
1798
-        return $copy_li;
1799
-    }
1800
-
1801
-
1802
-    /**
1803
-     * Creates a new, unsaved line item from $line_item that factors in the
1804
-     * number of billable registrations on $registrations.
1805
-     *
1806
-     * @param EE_Line_Item      $line_item
1807
-     * @param EE_Registration[] $registrations
1808
-     * @return EE_Line_Item
1809
-     * @throws EE_Error
1810
-     * @throws InvalidArgumentException
1811
-     * @throws InvalidDataTypeException
1812
-     * @throws InvalidInterfaceException
1813
-     * @throws ReflectionException
1814
-     */
1815
-    public static function billable_line_item(EE_Line_Item $line_item, $registrations)
1816
-    {
1817
-        $new_li_fields = $line_item->model_field_array();
1818
-        if ($line_item->type() === EEM_Line_Item::type_line_item &&
1819
-            $line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET
1820
-        ) {
1821
-            $count = 0;
1822
-            foreach ($registrations as $registration) {
1823
-                if ($line_item->OBJ_ID() === $registration->ticket_ID() &&
1824
-                    in_array(
1825
-                        $registration->status_ID(),
1826
-                        EEM_Registration::reg_statuses_that_allow_payment(),
1827
-                        true
1828
-                    )
1829
-                ) {
1830
-                    $count++;
1831
-                }
1832
-            }
1833
-            $new_li_fields['LIN_quantity'] = $count;
1834
-        }
1835
-        // don't set the total. We'll leave that up to the code that calculates it
1836
-        unset($new_li_fields['LIN_ID'], $new_li_fields['LIN_parent'], $new_li_fields['LIN_total']);
1837
-        return EE_Line_Item::new_instance($new_li_fields);
1838
-    }
1839
-
1840
-
1841
-    /**
1842
-     * Returns a modified line item tree where all the subtotals which have a total of 0
1843
-     * are removed, and line items with a quantity of 0
1844
-     *
1845
-     * @param EE_Line_Item $line_item |null
1846
-     * @return EE_Line_Item|null
1847
-     * @throws EE_Error
1848
-     * @throws InvalidArgumentException
1849
-     * @throws InvalidDataTypeException
1850
-     * @throws InvalidInterfaceException
1851
-     * @throws ReflectionException
1852
-     */
1853
-    public static function non_empty_line_items(EE_Line_Item $line_item)
1854
-    {
1855
-        $copied_li = EEH_Line_Item::non_empty_line_item($line_item);
1856
-        if ($copied_li === null) {
1857
-            return null;
1858
-        }
1859
-        // if this is an event subtotal, we want to only include it if it
1860
-        // has a non-zero total and at least one ticket line item child
1861
-        $ticket_children = 0;
1862
-        foreach ($line_item->children() as $child_li) {
1863
-            $child_li_copy = EEH_Line_Item::non_empty_line_items($child_li);
1864
-            if ($child_li_copy !== null) {
1865
-                $copied_li->add_child_line_item($child_li_copy);
1866
-                if ($child_li_copy->type() === EEM_Line_Item::type_line_item &&
1867
-                    $child_li_copy->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET
1868
-                ) {
1869
-                    $ticket_children++;
1870
-                }
1871
-            }
1872
-        }
1873
-        // if this is an event subtotal with NO ticket children
1874
-        // we basically want to ignore it
1875
-        if ($ticket_children === 0
1876
-            && $line_item->type() === EEM_Line_Item::type_sub_total
1877
-            && $line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_EVENT
1878
-            && $line_item->total() === 0
1879
-        ) {
1880
-            return null;
1881
-        }
1882
-        return $copied_li;
1883
-    }
1884
-
1885
-
1886
-    /**
1887
-     * Creates a new, unsaved line item, but if it's a ticket line item
1888
-     * with a total of 0, or a subtotal of 0, returns null instead
1889
-     *
1890
-     * @param EE_Line_Item $line_item
1891
-     * @return EE_Line_Item
1892
-     * @throws EE_Error
1893
-     * @throws InvalidArgumentException
1894
-     * @throws InvalidDataTypeException
1895
-     * @throws InvalidInterfaceException
1896
-     * @throws ReflectionException
1897
-     */
1898
-    public static function non_empty_line_item(EE_Line_Item $line_item)
1899
-    {
1900
-        if ($line_item->type() === EEM_Line_Item::type_line_item
1901
-            && $line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET
1902
-            && $line_item->quantity() === 0
1903
-        ) {
1904
-            return null;
1905
-        }
1906
-        $new_li_fields = $line_item->model_field_array();
1907
-        // don't set the total. We'll leave that up to the code that calculates it
1908
-        unset($new_li_fields['LIN_ID'], $new_li_fields['LIN_parent']);
1909
-        return EE_Line_Item::new_instance($new_li_fields);
1910
-    }
1911
-
1912
-
1913
-    /**
1914
-     * Cycles through all of the ticket line items for the supplied total line item
1915
-     * and ensures that the line item's "is_taxable" field matches that of its corresponding ticket
1916
-     *
1917
-     * @param EE_Line_Item $total_line_item
1918
-     * @since $VID:$
1919
-     * @throws EE_Error
1920
-     * @throws InvalidArgumentException
1921
-     * @throws InvalidDataTypeException
1922
-     * @throws InvalidInterfaceException
1923
-     * @throws ReflectionException
1924
-     */
1925
-    public static function resetIsTaxableForTickets(EE_Line_Item $total_line_item)
1926
-    {
1927
-        $ticket_line_items = self::get_ticket_line_items($total_line_item);
1928
-        foreach ($ticket_line_items as $ticket_line_item) {
1929
-            if ($ticket_line_item instanceof EE_Line_Item
1930
-                && $ticket_line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET
1931
-            ) {
1932
-                $ticket = $ticket_line_item->ticket();
1933
-                if ($ticket instanceof EE_Ticket && $ticket->taxable() !== $ticket_line_item->is_taxable()) {
1934
-                    $ticket_line_item->set_is_taxable($ticket->taxable());
1935
-                    $ticket_line_item->save();
1936
-                }
1937
-            }
1938
-        }
1939
-    }
1940
-
1941
-
1942
-
1943
-    /**************************************** @DEPRECATED METHODS *************************************** */
1944
-    /**
1945
-     * @deprecated
1946
-     * @param EE_Line_Item $total_line_item
1947
-     * @return EE_Line_Item
1948
-     * @throws EE_Error
1949
-     * @throws InvalidArgumentException
1950
-     * @throws InvalidDataTypeException
1951
-     * @throws InvalidInterfaceException
1952
-     * @throws ReflectionException
1953
-     */
1954
-    public static function get_items_subtotal(EE_Line_Item $total_line_item)
1955
-    {
1956
-        EE_Error::doing_it_wrong(
1957
-            'EEH_Line_Item::get_items_subtotal()',
1958
-            sprintf(
1959
-                esc_html__('Method replaced with %1$s', 'event_espresso'),
1960
-                'EEH_Line_Item::get_pre_tax_subtotal()'
1961
-            ),
1962
-            '4.6.0'
1963
-        );
1964
-        return self::get_pre_tax_subtotal($total_line_item);
1965
-    }
1966
-
1967
-
1968
-    /**
1969
-     * @deprecated
1970
-     * @param EE_Transaction $transaction
1971
-     * @return EE_Line_Item
1972
-     * @throws EE_Error
1973
-     * @throws InvalidArgumentException
1974
-     * @throws InvalidDataTypeException
1975
-     * @throws InvalidInterfaceException
1976
-     * @throws ReflectionException
1977
-     */
1978
-    public static function create_default_total_line_item($transaction = null)
1979
-    {
1980
-        EE_Error::doing_it_wrong(
1981
-            'EEH_Line_Item::create_default_total_line_item()',
1982
-            sprintf(
1983
-                esc_html__('Method replaced with %1$s', 'event_espresso'),
1984
-                'EEH_Line_Item::create_total_line_item()'
1985
-            ),
1986
-            '4.6.0'
1987
-        );
1988
-        return self::create_total_line_item($transaction);
1989
-    }
1990
-
1991
-
1992
-    /**
1993
-     * @deprecated
1994
-     * @param EE_Line_Item   $total_line_item
1995
-     * @param EE_Transaction $transaction
1996
-     * @return EE_Line_Item
1997
-     * @throws EE_Error
1998
-     * @throws InvalidArgumentException
1999
-     * @throws InvalidDataTypeException
2000
-     * @throws InvalidInterfaceException
2001
-     * @throws ReflectionException
2002
-     */
2003
-    public static function create_default_tickets_subtotal(EE_Line_Item $total_line_item, $transaction = null)
2004
-    {
2005
-        EE_Error::doing_it_wrong(
2006
-            'EEH_Line_Item::create_default_tickets_subtotal()',
2007
-            sprintf(
2008
-                esc_html__('Method replaced with %1$s', 'event_espresso'),
2009
-                'EEH_Line_Item::create_pre_tax_subtotal()'
2010
-            ),
2011
-            '4.6.0'
2012
-        );
2013
-        return self::create_pre_tax_subtotal($total_line_item, $transaction);
2014
-    }
2015
-
2016
-
2017
-    /**
2018
-     * @deprecated
2019
-     * @param EE_Line_Item   $total_line_item
2020
-     * @param EE_Transaction $transaction
2021
-     * @return EE_Line_Item
2022
-     * @throws EE_Error
2023
-     * @throws InvalidArgumentException
2024
-     * @throws InvalidDataTypeException
2025
-     * @throws InvalidInterfaceException
2026
-     * @throws ReflectionException
2027
-     */
2028
-    public static function create_default_taxes_subtotal(EE_Line_Item $total_line_item, $transaction = null)
2029
-    {
2030
-        EE_Error::doing_it_wrong(
2031
-            'EEH_Line_Item::create_default_taxes_subtotal()',
2032
-            sprintf(
2033
-                esc_html__('Method replaced with %1$s', 'event_espresso'),
2034
-                'EEH_Line_Item::create_taxes_subtotal()'
2035
-            ),
2036
-            '4.6.0'
2037
-        );
2038
-        return self::create_taxes_subtotal($total_line_item, $transaction);
2039
-    }
2040
-
2041
-
2042
-    /**
2043
-     * @deprecated
2044
-     * @param EE_Line_Item   $total_line_item
2045
-     * @param EE_Transaction $transaction
2046
-     * @return EE_Line_Item
2047
-     * @throws EE_Error
2048
-     * @throws InvalidArgumentException
2049
-     * @throws InvalidDataTypeException
2050
-     * @throws InvalidInterfaceException
2051
-     * @throws ReflectionException
2052
-     */
2053
-    public static function create_default_event_subtotal(EE_Line_Item $total_line_item, $transaction = null)
2054
-    {
2055
-        EE_Error::doing_it_wrong(
2056
-            'EEH_Line_Item::create_default_event_subtotal()',
2057
-            sprintf(
2058
-                esc_html__('Method replaced with %1$s', 'event_espresso'),
2059
-                'EEH_Line_Item::create_event_subtotal()'
2060
-            ),
2061
-            '4.6.0'
2062
-        );
2063
-        return self::create_event_subtotal($total_line_item, $transaction);
2064
-    }
24
+	/**
25
+	 * Adds a simple item (unrelated to any other model object) to the provided PARENT line item.
26
+	 * Does NOT automatically re-calculate the line item totals or update the related transaction.
27
+	 * You should call recalculate_total_including_taxes() on the grant total line item after this
28
+	 * to update the subtotals, and EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
29
+	 * to keep the registration final prices in-sync with the transaction's total.
30
+	 *
31
+	 * @param EE_Line_Item $parent_line_item
32
+	 * @param string       $name
33
+	 * @param float        $unit_price
34
+	 * @param string       $description
35
+	 * @param int          $quantity
36
+	 * @param boolean      $taxable
37
+	 * @param boolean      $code if set to a value, ensures there is only one line item with that code
38
+	 * @return boolean success
39
+	 * @throws EE_Error
40
+	 * @throws InvalidArgumentException
41
+	 * @throws InvalidDataTypeException
42
+	 * @throws InvalidInterfaceException
43
+	 * @throws ReflectionException
44
+	 */
45
+	public static function add_unrelated_item(
46
+		EE_Line_Item $parent_line_item,
47
+		$name,
48
+		$unit_price,
49
+		$description = '',
50
+		$quantity = 1,
51
+		$taxable = false,
52
+		$code = null
53
+	) {
54
+		$items_subtotal = self::get_pre_tax_subtotal($parent_line_item);
55
+		$line_item = EE_Line_Item::new_instance(array(
56
+			'LIN_name'       => $name,
57
+			'LIN_desc'       => $description,
58
+			'LIN_unit_price' => $unit_price,
59
+			'LIN_quantity'   => $quantity,
60
+			'LIN_percent'    => null,
61
+			'LIN_is_taxable' => $taxable,
62
+			'LIN_order'      => $items_subtotal instanceof EE_Line_Item ? count($items_subtotal->children()) : 0,
63
+			'LIN_total'      => (float) $unit_price * (int) $quantity,
64
+			'LIN_type'       => EEM_Line_Item::type_line_item,
65
+			'LIN_code'       => $code,
66
+		));
67
+		$line_item = apply_filters(
68
+			'FHEE__EEH_Line_Item__add_unrelated_item__line_item',
69
+			$line_item,
70
+			$parent_line_item
71
+		);
72
+		return self::add_item($parent_line_item, $line_item);
73
+	}
74
+
75
+
76
+	/**
77
+	 * Adds a simple item ( unrelated to any other model object) to the total line item,
78
+	 * in the correct spot in the line item tree. Automatically
79
+	 * re-calculates the line item totals and updates the related transaction. But
80
+	 * DOES NOT automatically upgrade the transaction's registrations' final prices (which
81
+	 * should probably change because of this).
82
+	 * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
83
+	 * after using this, to keep the registration final prices in-sync with the transaction's total.
84
+	 *
85
+	 * @param EE_Line_Item $parent_line_item
86
+	 * @param string       $name
87
+	 * @param float        $percentage_amount
88
+	 * @param string       $description
89
+	 * @param boolean      $taxable
90
+	 * @return boolean success
91
+	 * @throws EE_Error
92
+	 */
93
+	public static function add_percentage_based_item(
94
+		EE_Line_Item $parent_line_item,
95
+		$name,
96
+		$percentage_amount,
97
+		$description = '',
98
+		$taxable = false
99
+	) {
100
+		$line_item = EE_Line_Item::new_instance(array(
101
+			'LIN_name'       => $name,
102
+			'LIN_desc'       => $description,
103
+			'LIN_unit_price' => 0,
104
+			'LIN_percent'    => $percentage_amount,
105
+			'LIN_quantity'   => 1,
106
+			'LIN_is_taxable' => $taxable,
107
+			'LIN_total'      => (float) ($percentage_amount * ($parent_line_item->total() / 100)),
108
+			'LIN_type'       => EEM_Line_Item::type_line_item,
109
+			'LIN_parent'     => $parent_line_item->ID(),
110
+		));
111
+		$line_item = apply_filters(
112
+			'FHEE__EEH_Line_Item__add_percentage_based_item__line_item',
113
+			$line_item
114
+		);
115
+		return $parent_line_item->add_child_line_item($line_item, false);
116
+	}
117
+
118
+
119
+	/**
120
+	 * Returns the new line item created by adding a purchase of the ticket
121
+	 * ensures that ticket line item is saved, and that cart total has been recalculated.
122
+	 * If this ticket has already been purchased, just increments its count.
123
+	 * Automatically re-calculates the line item totals and updates the related transaction. But
124
+	 * DOES NOT automatically upgrade the transaction's registrations' final prices (which
125
+	 * should probably change because of this).
126
+	 * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
127
+	 * after using this, to keep the registration final prices in-sync with the transaction's total.
128
+	 *
129
+	 * @param EE_Line_Item $total_line_item grand total line item of type EEM_Line_Item::type_total
130
+	 * @param EE_Ticket    $ticket
131
+	 * @param int          $qty
132
+	 * @return EE_Line_Item
133
+	 * @throws EE_Error
134
+	 * @throws InvalidArgumentException
135
+	 * @throws InvalidDataTypeException
136
+	 * @throws InvalidInterfaceException
137
+	 * @throws ReflectionException
138
+	 */
139
+	public static function add_ticket_purchase(EE_Line_Item $total_line_item, EE_Ticket $ticket, $qty = 1)
140
+	{
141
+		if (! $total_line_item instanceof EE_Line_Item || ! $total_line_item->is_total()) {
142
+			throw new EE_Error(
143
+				sprintf(
144
+					esc_html__(
145
+						'A valid line item total is required in order to add tickets. A line item of type "%s" was passed.',
146
+						'event_espresso'
147
+					),
148
+					$ticket->ID(),
149
+					$total_line_item->ID()
150
+				)
151
+			);
152
+		}
153
+		// either increment the qty for an existing ticket
154
+		$line_item = self::increment_ticket_qty_if_already_in_cart($total_line_item, $ticket, $qty);
155
+		// or add a new one
156
+		if (! $line_item instanceof EE_Line_Item) {
157
+			$line_item = self::create_ticket_line_item($total_line_item, $ticket, $qty);
158
+		}
159
+		$total_line_item->recalculate_total_including_taxes();
160
+		return $line_item;
161
+	}
162
+
163
+
164
+	/**
165
+	 * Returns the new line item created by adding a purchase of the ticket
166
+	 *
167
+	 * @param EE_Line_Item $total_line_item
168
+	 * @param EE_Ticket    $ticket
169
+	 * @param int          $qty
170
+	 * @return EE_Line_Item
171
+	 * @throws EE_Error
172
+	 * @throws InvalidArgumentException
173
+	 * @throws InvalidDataTypeException
174
+	 * @throws InvalidInterfaceException
175
+	 * @throws ReflectionException
176
+	 */
177
+	public static function increment_ticket_qty_if_already_in_cart(
178
+		EE_Line_Item $total_line_item,
179
+		EE_Ticket $ticket,
180
+		$qty = 1
181
+	) {
182
+		$line_item = null;
183
+		if ($total_line_item instanceof EE_Line_Item && $total_line_item->is_total()) {
184
+			$ticket_line_items = EEH_Line_Item::get_ticket_line_items($total_line_item);
185
+			foreach ((array) $ticket_line_items as $ticket_line_item) {
186
+				if ($ticket_line_item instanceof EE_Line_Item
187
+					&& (int) $ticket_line_item->OBJ_ID() === (int) $ticket->ID()
188
+				) {
189
+					$line_item = $ticket_line_item;
190
+					break;
191
+				}
192
+			}
193
+		}
194
+		if ($line_item instanceof EE_Line_Item) {
195
+			EEH_Line_Item::increment_quantity($line_item, $qty);
196
+			return $line_item;
197
+		}
198
+		return null;
199
+	}
200
+
201
+
202
+	/**
203
+	 * Increments the line item and all its children's quantity by $qty (but percent line items are unaffected).
204
+	 * Does NOT save or recalculate other line items totals
205
+	 *
206
+	 * @param EE_Line_Item $line_item
207
+	 * @param int          $qty
208
+	 * @return void
209
+	 * @throws EE_Error
210
+	 * @throws InvalidArgumentException
211
+	 * @throws InvalidDataTypeException
212
+	 * @throws InvalidInterfaceException
213
+	 * @throws ReflectionException
214
+	 */
215
+	public static function increment_quantity(EE_Line_Item $line_item, $qty = 1)
216
+	{
217
+		if (! $line_item->is_percent()) {
218
+			$qty += $line_item->quantity();
219
+			$line_item->set_quantity($qty);
220
+			$line_item->set_total($line_item->unit_price() * $qty);
221
+			$line_item->save();
222
+		}
223
+		foreach ($line_item->children() as $child) {
224
+			if ($child->is_sub_line_item()) {
225
+				EEH_Line_Item::update_quantity($child, $qty);
226
+			}
227
+		}
228
+	}
229
+
230
+
231
+	/**
232
+	 * Decrements the line item and all its children's quantity by $qty (but percent line items are unaffected).
233
+	 * Does NOT save or recalculate other line items totals
234
+	 *
235
+	 * @param EE_Line_Item $line_item
236
+	 * @param int          $qty
237
+	 * @return void
238
+	 * @throws EE_Error
239
+	 * @throws InvalidArgumentException
240
+	 * @throws InvalidDataTypeException
241
+	 * @throws InvalidInterfaceException
242
+	 * @throws ReflectionException
243
+	 */
244
+	public static function decrement_quantity(EE_Line_Item $line_item, $qty = 1)
245
+	{
246
+		if (! $line_item->is_percent()) {
247
+			$qty = $line_item->quantity() - $qty;
248
+			$qty = max($qty, 0);
249
+			$line_item->set_quantity($qty);
250
+			$line_item->set_total($line_item->unit_price() * $qty);
251
+			$line_item->save();
252
+		}
253
+		foreach ($line_item->children() as $child) {
254
+			if ($child->is_sub_line_item()) {
255
+				EEH_Line_Item::update_quantity($child, $qty);
256
+			}
257
+		}
258
+	}
259
+
260
+
261
+	/**
262
+	 * Updates the line item and its children's quantities to the specified number.
263
+	 * Does NOT save them or recalculate totals.
264
+	 *
265
+	 * @param EE_Line_Item $line_item
266
+	 * @param int          $new_quantity
267
+	 * @throws EE_Error
268
+	 * @throws InvalidArgumentException
269
+	 * @throws InvalidDataTypeException
270
+	 * @throws InvalidInterfaceException
271
+	 * @throws ReflectionException
272
+	 */
273
+	public static function update_quantity(EE_Line_Item $line_item, $new_quantity)
274
+	{
275
+		if (! $line_item->is_percent()) {
276
+			$line_item->set_quantity($new_quantity);
277
+			$line_item->set_total($line_item->unit_price() * $new_quantity);
278
+			$line_item->save();
279
+		}
280
+		foreach ($line_item->children() as $child) {
281
+			if ($child->is_sub_line_item()) {
282
+				EEH_Line_Item::update_quantity($child, $new_quantity);
283
+			}
284
+		}
285
+	}
286
+
287
+
288
+	/**
289
+	 * Returns the new line item created by adding a purchase of the ticket
290
+	 *
291
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
292
+	 * @param EE_Ticket    $ticket
293
+	 * @param int          $qty
294
+	 * @return EE_Line_Item
295
+	 * @throws EE_Error
296
+	 * @throws InvalidArgumentException
297
+	 * @throws InvalidDataTypeException
298
+	 * @throws InvalidInterfaceException
299
+	 * @throws ReflectionException
300
+	 */
301
+	public static function create_ticket_line_item(EE_Line_Item $total_line_item, EE_Ticket $ticket, $qty = 1)
302
+	{
303
+		$datetimes = $ticket->datetimes();
304
+		$first_datetime = reset($datetimes);
305
+		$first_datetime_name = esc_html__('Event', 'event_espresso');
306
+		if ($first_datetime instanceof EE_Datetime && $first_datetime->event() instanceof EE_Event) {
307
+			$first_datetime_name = $first_datetime->event()->name();
308
+		}
309
+		$event = sprintf(_x('(For %1$s)', '(For Event Name)', 'event_espresso'), $first_datetime_name);
310
+		// get event subtotal line
311
+		$events_sub_total = self::get_event_line_item_for_ticket($total_line_item, $ticket);
312
+		// add $ticket to cart
313
+		$line_item = EE_Line_Item::new_instance(array(
314
+			'LIN_name'       => $ticket->name(),
315
+			'LIN_desc'       => $ticket->description() !== '' ? $ticket->description() . ' ' . $event : $event,
316
+			'LIN_unit_price' => $ticket->price(),
317
+			'LIN_quantity'   => $qty,
318
+			'LIN_is_taxable' => $ticket->taxable(),
319
+			'LIN_order'      => count($events_sub_total->children()),
320
+			'LIN_total'      => $ticket->price() * $qty,
321
+			'LIN_type'       => EEM_Line_Item::type_line_item,
322
+			'OBJ_ID'         => $ticket->ID(),
323
+			'OBJ_type'       => EEM_Line_Item::OBJ_TYPE_TICKET,
324
+		));
325
+		$line_item = apply_filters(
326
+			'FHEE__EEH_Line_Item__create_ticket_line_item__line_item',
327
+			$line_item
328
+		);
329
+		$events_sub_total->add_child_line_item($line_item);
330
+		// now add the sub-line items
331
+		$running_total_for_ticket = 0;
332
+		foreach ($ticket->prices(array('order_by' => array('PRC_order' => 'ASC'))) as $price) {
333
+			$sign = $price->is_discount() ? -1 : 1;
334
+			$price_total = $price->is_percent()
335
+				? $running_total_for_ticket * $price->amount() / 100
336
+				: $price->amount() * $qty;
337
+			$sub_line_item = EE_Line_Item::new_instance(array(
338
+				'LIN_name'       => $price->name(),
339
+				'LIN_desc'       => $price->desc(),
340
+				'LIN_quantity'   => $price->is_percent() ? null : $qty,
341
+				'LIN_is_taxable' => false,
342
+				'LIN_order'      => $price->order(),
343
+				'LIN_total'      => $sign * $price_total,
344
+				'LIN_type'       => EEM_Line_Item::type_sub_line_item,
345
+				'OBJ_ID'         => $price->ID(),
346
+				'OBJ_type'       => EEM_Line_Item::OBJ_TYPE_PRICE,
347
+			));
348
+			$sub_line_item = apply_filters(
349
+				'FHEE__EEH_Line_Item__create_ticket_line_item__sub_line_item',
350
+				$sub_line_item
351
+			);
352
+			if ($price->is_percent()) {
353
+				$sub_line_item->set_percent($sign * $price->amount());
354
+			} else {
355
+				$sub_line_item->set_unit_price($sign * $price->amount());
356
+			}
357
+			$running_total_for_ticket += $price_total;
358
+			$line_item->add_child_line_item($sub_line_item);
359
+		}
360
+		return $line_item;
361
+	}
362
+
363
+
364
+	/**
365
+	 * Adds the specified item under the pre-tax-sub-total line item. Automatically
366
+	 * re-calculates the line item totals and updates the related transaction. But
367
+	 * DOES NOT automatically upgrade the transaction's registrations' final prices (which
368
+	 * should probably change because of this).
369
+	 * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
370
+	 * after using this, to keep the registration final prices in-sync with the transaction's total.
371
+	 *
372
+	 * @param EE_Line_Item $total_line_item
373
+	 * @param EE_Line_Item $item to be added
374
+	 * @return boolean
375
+	 * @throws EE_Error
376
+	 * @throws InvalidArgumentException
377
+	 * @throws InvalidDataTypeException
378
+	 * @throws InvalidInterfaceException
379
+	 * @throws ReflectionException
380
+	 */
381
+	public static function add_item(EE_Line_Item $total_line_item, EE_Line_Item $item)
382
+	{
383
+		$pre_tax_subtotal = self::get_pre_tax_subtotal($total_line_item);
384
+		if ($pre_tax_subtotal instanceof EE_Line_Item) {
385
+			$success = $pre_tax_subtotal->add_child_line_item($item);
386
+		} else {
387
+			return false;
388
+		}
389
+		$total_line_item->recalculate_total_including_taxes();
390
+		return $success;
391
+	}
392
+
393
+
394
+	/**
395
+	 * cancels an existing ticket line item,
396
+	 * by decrementing it's quantity by 1 and adding a new "type_cancellation" sub-line-item.
397
+	 * ALL totals and subtotals will NEED TO BE UPDATED after performing this action
398
+	 *
399
+	 * @param EE_Line_Item $ticket_line_item
400
+	 * @param int          $qty
401
+	 * @return bool success
402
+	 * @throws EE_Error
403
+	 * @throws InvalidArgumentException
404
+	 * @throws InvalidDataTypeException
405
+	 * @throws InvalidInterfaceException
406
+	 * @throws ReflectionException
407
+	 */
408
+	public static function cancel_ticket_line_item(EE_Line_Item $ticket_line_item, $qty = 1)
409
+	{
410
+		// validate incoming line_item
411
+		if ($ticket_line_item->OBJ_type() !== EEM_Line_Item::OBJ_TYPE_TICKET) {
412
+			throw new EE_Error(
413
+				sprintf(
414
+					esc_html__(
415
+						'The supplied line item must have an Object Type of "Ticket", not %1$s.',
416
+						'event_espresso'
417
+					),
418
+					$ticket_line_item->type()
419
+				)
420
+			);
421
+		}
422
+		if ($ticket_line_item->quantity() < $qty) {
423
+			throw new EE_Error(
424
+				sprintf(
425
+					esc_html__(
426
+						'Can not cancel %1$d ticket(s) because the supplied line item has a quantity of %2$d.',
427
+						'event_espresso'
428
+					),
429
+					$qty,
430
+					$ticket_line_item->quantity()
431
+				)
432
+			);
433
+		}
434
+		// decrement ticket quantity; don't rely on auto-fixing when recalculating totals to do this
435
+		$ticket_line_item->set_quantity($ticket_line_item->quantity() - $qty);
436
+		foreach ($ticket_line_item->children() as $child_line_item) {
437
+			if ($child_line_item->is_sub_line_item()
438
+				&& ! $child_line_item->is_percent()
439
+				&& ! $child_line_item->is_cancellation()
440
+			) {
441
+				$child_line_item->set_quantity($child_line_item->quantity() - $qty);
442
+			}
443
+		}
444
+		// get cancellation sub line item
445
+		$cancellation_line_item = EEH_Line_Item::get_descendants_of_type(
446
+			$ticket_line_item,
447
+			EEM_Line_Item::type_cancellation
448
+		);
449
+		$cancellation_line_item = reset($cancellation_line_item);
450
+		// verify that this ticket was indeed previously cancelled
451
+		if ($cancellation_line_item instanceof EE_Line_Item) {
452
+			// increment cancelled quantity
453
+			$cancellation_line_item->set_quantity($cancellation_line_item->quantity() + $qty);
454
+		} else {
455
+			// create cancellation sub line item
456
+			$cancellation_line_item = EE_Line_Item::new_instance(array(
457
+				'LIN_name'       => esc_html__('Cancellation', 'event_espresso'),
458
+				'LIN_desc'       => sprintf(
459
+					esc_html_x(
460
+						'Cancelled %1$s : %2$s',
461
+						'Cancelled Ticket Name : 2015-01-01 11:11',
462
+						'event_espresso'
463
+					),
464
+					$ticket_line_item->name(),
465
+					current_time(get_option('date_format') . ' ' . get_option('time_format'))
466
+				),
467
+				'LIN_unit_price' => 0, // $ticket_line_item->unit_price()
468
+				'LIN_quantity'   => $qty,
469
+				'LIN_is_taxable' => $ticket_line_item->is_taxable(),
470
+				'LIN_order'      => count($ticket_line_item->children()),
471
+				'LIN_total'      => 0, // $ticket_line_item->unit_price()
472
+				'LIN_type'       => EEM_Line_Item::type_cancellation,
473
+			));
474
+			$ticket_line_item->add_child_line_item($cancellation_line_item);
475
+		}
476
+		if ($ticket_line_item->save_this_and_descendants() > 0) {
477
+			// decrement parent line item quantity
478
+			$event_line_item = $ticket_line_item->parent();
479
+			if ($event_line_item instanceof EE_Line_Item
480
+				&& $event_line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_EVENT
481
+			) {
482
+				$event_line_item->set_quantity($event_line_item->quantity() - $qty);
483
+				$event_line_item->save();
484
+			}
485
+			EEH_Line_Item::get_grand_total_and_recalculate_everything($ticket_line_item);
486
+			return true;
487
+		}
488
+		return false;
489
+	}
490
+
491
+
492
+	/**
493
+	 * reinstates (un-cancels?) a previously canceled ticket line item,
494
+	 * by incrementing it's quantity by 1, and decrementing it's "type_cancellation" sub-line-item.
495
+	 * ALL totals and subtotals will NEED TO BE UPDATED after performing this action
496
+	 *
497
+	 * @param EE_Line_Item $ticket_line_item
498
+	 * @param int          $qty
499
+	 * @return bool success
500
+	 * @throws EE_Error
501
+	 * @throws InvalidArgumentException
502
+	 * @throws InvalidDataTypeException
503
+	 * @throws InvalidInterfaceException
504
+	 * @throws ReflectionException
505
+	 */
506
+	public static function reinstate_canceled_ticket_line_item(EE_Line_Item $ticket_line_item, $qty = 1)
507
+	{
508
+		// validate incoming line_item
509
+		if ($ticket_line_item->OBJ_type() !== EEM_Line_Item::OBJ_TYPE_TICKET) {
510
+			throw new EE_Error(
511
+				sprintf(
512
+					esc_html__(
513
+						'The supplied line item must have an Object Type of "Ticket", not %1$s.',
514
+						'event_espresso'
515
+					),
516
+					$ticket_line_item->type()
517
+				)
518
+			);
519
+		}
520
+		// get cancellation sub line item
521
+		$cancellation_line_item = EEH_Line_Item::get_descendants_of_type(
522
+			$ticket_line_item,
523
+			EEM_Line_Item::type_cancellation
524
+		);
525
+		$cancellation_line_item = reset($cancellation_line_item);
526
+		// verify that this ticket was indeed previously cancelled
527
+		if (! $cancellation_line_item instanceof EE_Line_Item) {
528
+			return false;
529
+		}
530
+		if ($cancellation_line_item->quantity() > $qty) {
531
+			// decrement cancelled quantity
532
+			$cancellation_line_item->set_quantity($cancellation_line_item->quantity() - $qty);
533
+		} elseif ($cancellation_line_item->quantity() === $qty) {
534
+			// decrement cancelled quantity in case anyone still has the object kicking around
535
+			$cancellation_line_item->set_quantity($cancellation_line_item->quantity() - $qty);
536
+			// delete because quantity will end up as 0
537
+			$cancellation_line_item->delete();
538
+			// and attempt to destroy the object,
539
+			// even though PHP won't actually destroy it until it needs the memory
540
+			unset($cancellation_line_item);
541
+		} else {
542
+			// what ?!?! negative quantity ?!?!
543
+			throw new EE_Error(
544
+				sprintf(
545
+					esc_html__(
546
+						'Can not reinstate %1$d cancelled ticket(s) because the cancelled ticket quantity is only %2$d.',
547
+						'event_espresso'
548
+					),
549
+					$qty,
550
+					$cancellation_line_item->quantity()
551
+				)
552
+			);
553
+		}
554
+		// increment ticket quantity
555
+		$ticket_line_item->set_quantity($ticket_line_item->quantity() + $qty);
556
+		if ($ticket_line_item->save_this_and_descendants() > 0) {
557
+			// increment parent line item quantity
558
+			$event_line_item = $ticket_line_item->parent();
559
+			if ($event_line_item instanceof EE_Line_Item
560
+				&& $event_line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_EVENT
561
+			) {
562
+				$event_line_item->set_quantity($event_line_item->quantity() + $qty);
563
+			}
564
+			EEH_Line_Item::get_grand_total_and_recalculate_everything($ticket_line_item);
565
+			return true;
566
+		}
567
+		return false;
568
+	}
569
+
570
+
571
+	/**
572
+	 * calls EEH_Line_Item::find_transaction_grand_total_for_line_item()
573
+	 * then EE_Line_Item::recalculate_total_including_taxes() on the result
574
+	 *
575
+	 * @param EE_Line_Item $line_item
576
+	 * @return float
577
+	 * @throws EE_Error
578
+	 * @throws InvalidArgumentException
579
+	 * @throws InvalidDataTypeException
580
+	 * @throws InvalidInterfaceException
581
+	 * @throws ReflectionException
582
+	 */
583
+	public static function get_grand_total_and_recalculate_everything(EE_Line_Item $line_item)
584
+	{
585
+		$grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($line_item);
586
+		return $grand_total_line_item->recalculate_total_including_taxes();
587
+	}
588
+
589
+
590
+	/**
591
+	 * Gets the line item which contains the subtotal of all the items
592
+	 *
593
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
594
+	 * @return EE_Line_Item
595
+	 * @throws EE_Error
596
+	 * @throws InvalidArgumentException
597
+	 * @throws InvalidDataTypeException
598
+	 * @throws InvalidInterfaceException
599
+	 * @throws ReflectionException
600
+	 */
601
+	public static function get_pre_tax_subtotal(EE_Line_Item $total_line_item)
602
+	{
603
+		$pre_tax_subtotal = $total_line_item->get_child_line_item('pre-tax-subtotal');
604
+		return $pre_tax_subtotal instanceof EE_Line_Item
605
+			? $pre_tax_subtotal
606
+			: self::create_pre_tax_subtotal($total_line_item);
607
+	}
608
+
609
+
610
+	/**
611
+	 * Gets the line item for the taxes subtotal
612
+	 *
613
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
614
+	 * @return EE_Line_Item
615
+	 * @throws EE_Error
616
+	 * @throws InvalidArgumentException
617
+	 * @throws InvalidDataTypeException
618
+	 * @throws InvalidInterfaceException
619
+	 * @throws ReflectionException
620
+	 */
621
+	public static function get_taxes_subtotal(EE_Line_Item $total_line_item)
622
+	{
623
+		$taxes = $total_line_item->get_child_line_item('taxes');
624
+		return $taxes ? $taxes : self::create_taxes_subtotal($total_line_item);
625
+	}
626
+
627
+
628
+	/**
629
+	 * sets the TXN ID on an EE_Line_Item if passed a valid EE_Transaction object
630
+	 *
631
+	 * @param EE_Line_Item   $line_item
632
+	 * @param EE_Transaction $transaction
633
+	 * @return void
634
+	 * @throws EE_Error
635
+	 * @throws InvalidArgumentException
636
+	 * @throws InvalidDataTypeException
637
+	 * @throws InvalidInterfaceException
638
+	 * @throws ReflectionException
639
+	 */
640
+	public static function set_TXN_ID(EE_Line_Item $line_item, $transaction = null)
641
+	{
642
+		if ($transaction) {
643
+			/** @type EEM_Transaction $EEM_Transaction */
644
+			$EEM_Transaction = EE_Registry::instance()->load_model('Transaction');
645
+			$TXN_ID = $EEM_Transaction->ensure_is_ID($transaction);
646
+			$line_item->set_TXN_ID($TXN_ID);
647
+		}
648
+	}
649
+
650
+
651
+	/**
652
+	 * Creates a new default total line item for the transaction,
653
+	 * and its tickets subtotal and taxes subtotal line items (and adds the
654
+	 * existing taxes as children of the taxes subtotal line item)
655
+	 *
656
+	 * @param EE_Transaction $transaction
657
+	 * @return EE_Line_Item of type total
658
+	 * @throws EE_Error
659
+	 * @throws InvalidArgumentException
660
+	 * @throws InvalidDataTypeException
661
+	 * @throws InvalidInterfaceException
662
+	 * @throws ReflectionException
663
+	 */
664
+	public static function create_total_line_item($transaction = null)
665
+	{
666
+		$total_line_item = EE_Line_Item::new_instance(array(
667
+			'LIN_code' => 'total',
668
+			'LIN_name' => esc_html__('Grand Total', 'event_espresso'),
669
+			'LIN_type' => EEM_Line_Item::type_total,
670
+			'OBJ_type' => EEM_Line_Item::OBJ_TYPE_TRANSACTION,
671
+		));
672
+		$total_line_item = apply_filters(
673
+			'FHEE__EEH_Line_Item__create_total_line_item__total_line_item',
674
+			$total_line_item
675
+		);
676
+		self::set_TXN_ID($total_line_item, $transaction);
677
+		self::create_pre_tax_subtotal($total_line_item, $transaction);
678
+		self::create_taxes_subtotal($total_line_item, $transaction);
679
+		return $total_line_item;
680
+	}
681
+
682
+
683
+	/**
684
+	 * Creates a default items subtotal line item
685
+	 *
686
+	 * @param EE_Line_Item   $total_line_item
687
+	 * @param EE_Transaction $transaction
688
+	 * @return EE_Line_Item
689
+	 * @throws EE_Error
690
+	 * @throws InvalidArgumentException
691
+	 * @throws InvalidDataTypeException
692
+	 * @throws InvalidInterfaceException
693
+	 * @throws ReflectionException
694
+	 */
695
+	protected static function create_pre_tax_subtotal(EE_Line_Item $total_line_item, $transaction = null)
696
+	{
697
+		$pre_tax_line_item = EE_Line_Item::new_instance(array(
698
+			'LIN_code' => 'pre-tax-subtotal',
699
+			'LIN_name' => esc_html__('Pre-Tax Subtotal', 'event_espresso'),
700
+			'LIN_type' => EEM_Line_Item::type_sub_total,
701
+		));
702
+		$pre_tax_line_item = apply_filters(
703
+			'FHEE__EEH_Line_Item__create_pre_tax_subtotal__pre_tax_line_item',
704
+			$pre_tax_line_item
705
+		);
706
+		self::set_TXN_ID($pre_tax_line_item, $transaction);
707
+		$total_line_item->add_child_line_item($pre_tax_line_item);
708
+		self::create_event_subtotal($pre_tax_line_item, $transaction);
709
+		return $pre_tax_line_item;
710
+	}
711
+
712
+
713
+	/**
714
+	 * Creates a line item for the taxes subtotal and finds all the tax prices
715
+	 * and applies taxes to it
716
+	 *
717
+	 * @param EE_Line_Item   $total_line_item of type EEM_Line_Item::type_total
718
+	 * @param EE_Transaction $transaction
719
+	 * @return EE_Line_Item
720
+	 * @throws EE_Error
721
+	 * @throws InvalidArgumentException
722
+	 * @throws InvalidDataTypeException
723
+	 * @throws InvalidInterfaceException
724
+	 * @throws ReflectionException
725
+	 */
726
+	protected static function create_taxes_subtotal(EE_Line_Item $total_line_item, $transaction = null)
727
+	{
728
+		$tax_line_item = EE_Line_Item::new_instance(array(
729
+			'LIN_code'  => 'taxes',
730
+			'LIN_name'  => esc_html__('Taxes', 'event_espresso'),
731
+			'LIN_type'  => EEM_Line_Item::type_tax_sub_total,
732
+			'LIN_order' => 1000,// this should always come last
733
+		));
734
+		$tax_line_item = apply_filters(
735
+			'FHEE__EEH_Line_Item__create_taxes_subtotal__tax_line_item',
736
+			$tax_line_item
737
+		);
738
+		self::set_TXN_ID($tax_line_item, $transaction);
739
+		$total_line_item->add_child_line_item($tax_line_item);
740
+		// and lastly, add the actual taxes
741
+		self::apply_taxes($total_line_item);
742
+		return $tax_line_item;
743
+	}
744
+
745
+
746
+	/**
747
+	 * Creates a default items subtotal line item
748
+	 *
749
+	 * @param EE_Line_Item   $pre_tax_line_item
750
+	 * @param EE_Transaction $transaction
751
+	 * @param EE_Event       $event
752
+	 * @return EE_Line_Item
753
+	 * @throws EE_Error
754
+	 * @throws InvalidArgumentException
755
+	 * @throws InvalidDataTypeException
756
+	 * @throws InvalidInterfaceException
757
+	 * @throws ReflectionException
758
+	 */
759
+	public static function create_event_subtotal(EE_Line_Item $pre_tax_line_item, $transaction = null, $event = null)
760
+	{
761
+		$event_line_item = EE_Line_Item::new_instance(array(
762
+			'LIN_code' => self::get_event_code($event),
763
+			'LIN_name' => self::get_event_name($event),
764
+			'LIN_desc' => self::get_event_desc($event),
765
+			'LIN_type' => EEM_Line_Item::type_sub_total,
766
+			'OBJ_type' => EEM_Line_Item::OBJ_TYPE_EVENT,
767
+			'OBJ_ID'   => $event instanceof EE_Event ? $event->ID() : 0,
768
+		));
769
+		$event_line_item = apply_filters(
770
+			'FHEE__EEH_Line_Item__create_event_subtotal__event_line_item',
771
+			$event_line_item
772
+		);
773
+		self::set_TXN_ID($event_line_item, $transaction);
774
+		$pre_tax_line_item->add_child_line_item($event_line_item);
775
+		return $event_line_item;
776
+	}
777
+
778
+
779
+	/**
780
+	 * Gets what the event ticket's code SHOULD be
781
+	 *
782
+	 * @param EE_Event $event
783
+	 * @return string
784
+	 * @throws EE_Error
785
+	 */
786
+	public static function get_event_code($event)
787
+	{
788
+		return 'event-' . ($event instanceof EE_Event ? $event->ID() : '0');
789
+	}
790
+
791
+
792
+	/**
793
+	 * Gets the event name
794
+	 *
795
+	 * @param EE_Event $event
796
+	 * @return string
797
+	 * @throws EE_Error
798
+	 */
799
+	public static function get_event_name($event)
800
+	{
801
+		return $event instanceof EE_Event
802
+			? mb_substr($event->name(), 0, 245)
803
+			: esc_html__('Event', 'event_espresso');
804
+	}
805
+
806
+
807
+	/**
808
+	 * Gets the event excerpt
809
+	 *
810
+	 * @param EE_Event $event
811
+	 * @return string
812
+	 * @throws EE_Error
813
+	 */
814
+	public static function get_event_desc($event)
815
+	{
816
+		return $event instanceof EE_Event ? $event->short_description() : '';
817
+	}
818
+
819
+
820
+	/**
821
+	 * Given the grand total line item and a ticket, finds the event sub-total
822
+	 * line item the ticket's purchase should be added onto
823
+	 *
824
+	 * @access public
825
+	 * @param EE_Line_Item $grand_total the grand total line item
826
+	 * @param EE_Ticket    $ticket
827
+	 * @return EE_Line_Item
828
+	 * @throws EE_Error
829
+	 * @throws InvalidArgumentException
830
+	 * @throws InvalidDataTypeException
831
+	 * @throws InvalidInterfaceException
832
+	 * @throws ReflectionException
833
+	 */
834
+	public static function get_event_line_item_for_ticket(EE_Line_Item $grand_total, EE_Ticket $ticket)
835
+	{
836
+		$first_datetime = $ticket->first_datetime();
837
+		if (! $first_datetime instanceof EE_Datetime) {
838
+			throw new EE_Error(
839
+				sprintf(
840
+					__('The supplied ticket (ID %d) has no datetimes', 'event_espresso'),
841
+					$ticket->ID()
842
+				)
843
+			);
844
+		}
845
+		$event = $first_datetime->event();
846
+		if (! $event instanceof EE_Event) {
847
+			throw new EE_Error(
848
+				sprintf(
849
+					esc_html__(
850
+						'The supplied ticket (ID %d) has no event data associated with it.',
851
+						'event_espresso'
852
+					),
853
+					$ticket->ID()
854
+				)
855
+			);
856
+		}
857
+		$events_sub_total = EEH_Line_Item::get_event_line_item($grand_total, $event);
858
+		if (! $events_sub_total instanceof EE_Line_Item) {
859
+			throw new EE_Error(
860
+				sprintf(
861
+					esc_html__(
862
+						'There is no events sub-total for ticket %s on total line item %d',
863
+						'event_espresso'
864
+					),
865
+					$ticket->ID(),
866
+					$grand_total->ID()
867
+				)
868
+			);
869
+		}
870
+		return $events_sub_total;
871
+	}
872
+
873
+
874
+	/**
875
+	 * Gets the event line item
876
+	 *
877
+	 * @param EE_Line_Item $grand_total
878
+	 * @param EE_Event     $event
879
+	 * @return EE_Line_Item for the event subtotal which is a child of $grand_total
880
+	 * @throws EE_Error
881
+	 * @throws InvalidArgumentException
882
+	 * @throws InvalidDataTypeException
883
+	 * @throws InvalidInterfaceException
884
+	 * @throws ReflectionException
885
+	 */
886
+	public static function get_event_line_item(EE_Line_Item $grand_total, $event)
887
+	{
888
+		/** @type EE_Event $event */
889
+		$event = EEM_Event::instance()->ensure_is_obj($event, true);
890
+		$event_line_item = null;
891
+		$found = false;
892
+		foreach (EEH_Line_Item::get_event_subtotals($grand_total) as $event_line_item) {
893
+			// default event subtotal, we should only ever find this the first time this method is called
894
+			if (! $event_line_item->OBJ_ID()) {
895
+				// let's use this! but first... set the event details
896
+				EEH_Line_Item::set_event_subtotal_details($event_line_item, $event);
897
+				$found = true;
898
+				break;
899
+			}
900
+			if ($event_line_item->OBJ_ID() === $event->ID()) {
901
+				// found existing line item for this event in the cart, so break out of loop and use this one
902
+				$found = true;
903
+				break;
904
+			}
905
+		}
906
+		if (! $found) {
907
+			// there is no event sub-total yet, so add it
908
+			$pre_tax_subtotal = EEH_Line_Item::get_pre_tax_subtotal($grand_total);
909
+			// create a new "event" subtotal below that
910
+			$event_line_item = EEH_Line_Item::create_event_subtotal($pre_tax_subtotal, null, $event);
911
+			// and set the event details
912
+			EEH_Line_Item::set_event_subtotal_details($event_line_item, $event);
913
+		}
914
+		return $event_line_item;
915
+	}
916
+
917
+
918
+	/**
919
+	 * Creates a default items subtotal line item
920
+	 *
921
+	 * @param EE_Line_Item   $event_line_item
922
+	 * @param EE_Event       $event
923
+	 * @param EE_Transaction $transaction
924
+	 * @return void
925
+	 * @throws EE_Error
926
+	 * @throws InvalidArgumentException
927
+	 * @throws InvalidDataTypeException
928
+	 * @throws InvalidInterfaceException
929
+	 * @throws ReflectionException
930
+	 */
931
+	public static function set_event_subtotal_details(
932
+		EE_Line_Item $event_line_item,
933
+		EE_Event $event,
934
+		$transaction = null
935
+	) {
936
+		if ($event instanceof EE_Event) {
937
+			$event_line_item->set_code(self::get_event_code($event));
938
+			$event_line_item->set_name(self::get_event_name($event));
939
+			$event_line_item->set_desc(self::get_event_desc($event));
940
+			$event_line_item->set_OBJ_ID($event->ID());
941
+		}
942
+		self::set_TXN_ID($event_line_item, $transaction);
943
+	}
944
+
945
+
946
+	/**
947
+	 * Finds what taxes should apply, adds them as tax line items under the taxes sub-total,
948
+	 * and recalculates the taxes sub-total and the grand total. Resets the taxes, so
949
+	 * any old taxes are removed
950
+	 *
951
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
952
+	 * @param bool         $update_txn_status
953
+	 * @return bool
954
+	 * @throws EE_Error
955
+	 * @throws InvalidArgumentException
956
+	 * @throws InvalidDataTypeException
957
+	 * @throws InvalidInterfaceException
958
+	 * @throws ReflectionException
959
+	 * @throws RuntimeException
960
+	 */
961
+	public static function apply_taxes(EE_Line_Item $total_line_item, $update_txn_status = false)
962
+	{
963
+		/** @type EEM_Price $EEM_Price */
964
+		$EEM_Price = EE_Registry::instance()->load_model('Price');
965
+		// get array of taxes via Price Model
966
+		$ordered_taxes = $EEM_Price->get_all_prices_that_are_taxes();
967
+		ksort($ordered_taxes);
968
+		$taxes_line_item = self::get_taxes_subtotal($total_line_item);
969
+		// just to be safe, remove its old tax line items
970
+		$deleted = $taxes_line_item->delete_children_line_items();
971
+		$updates = false;
972
+		// loop thru taxes
973
+		foreach ($ordered_taxes as $order => $taxes) {
974
+			foreach ($taxes as $tax) {
975
+				if ($tax instanceof EE_Price) {
976
+					$tax_line_item = EE_Line_Item::new_instance(
977
+						array(
978
+							'LIN_name'       => $tax->name(),
979
+							'LIN_desc'       => $tax->desc(),
980
+							'LIN_percent'    => $tax->amount(),
981
+							'LIN_is_taxable' => false,
982
+							'LIN_order'      => $order,
983
+							'LIN_total'      => 0,
984
+							'LIN_type'       => EEM_Line_Item::type_tax,
985
+							'OBJ_type'       => EEM_Line_Item::OBJ_TYPE_PRICE,
986
+							'OBJ_ID'         => $tax->ID(),
987
+						)
988
+					);
989
+					$tax_line_item = apply_filters(
990
+						'FHEE__EEH_Line_Item__apply_taxes__tax_line_item',
991
+						$tax_line_item
992
+					);
993
+					$updates = $taxes_line_item->add_child_line_item($tax_line_item) ?
994
+						true :
995
+						$updates;
996
+				}
997
+			}
998
+		}
999
+		// only recalculate totals if something changed
1000
+		if ($deleted || $updates) {
1001
+			$total_line_item->recalculate_total_including_taxes($update_txn_status);
1002
+			return true;
1003
+		}
1004
+		return false;
1005
+	}
1006
+
1007
+
1008
+	/**
1009
+	 * Ensures that taxes have been applied to the order, if not applies them.
1010
+	 * Returns the total amount of tax
1011
+	 *
1012
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
1013
+	 * @return float
1014
+	 * @throws EE_Error
1015
+	 * @throws InvalidArgumentException
1016
+	 * @throws InvalidDataTypeException
1017
+	 * @throws InvalidInterfaceException
1018
+	 * @throws ReflectionException
1019
+	 */
1020
+	public static function ensure_taxes_applied($total_line_item)
1021
+	{
1022
+		$taxes_subtotal = self::get_taxes_subtotal($total_line_item);
1023
+		if (! $taxes_subtotal->children()) {
1024
+			self::apply_taxes($total_line_item);
1025
+		}
1026
+		return $taxes_subtotal->total();
1027
+	}
1028
+
1029
+
1030
+	/**
1031
+	 * Deletes ALL children of the passed line item
1032
+	 *
1033
+	 * @param EE_Line_Item $parent_line_item
1034
+	 * @return bool
1035
+	 * @throws EE_Error
1036
+	 * @throws InvalidArgumentException
1037
+	 * @throws InvalidDataTypeException
1038
+	 * @throws InvalidInterfaceException
1039
+	 * @throws ReflectionException
1040
+	 */
1041
+	public static function delete_all_child_items(EE_Line_Item $parent_line_item)
1042
+	{
1043
+		$deleted = 0;
1044
+		foreach ($parent_line_item->children() as $child_line_item) {
1045
+			if ($child_line_item instanceof EE_Line_Item) {
1046
+				$deleted += EEH_Line_Item::delete_all_child_items($child_line_item);
1047
+				if ($child_line_item->ID()) {
1048
+					$child_line_item->delete();
1049
+					unset($child_line_item);
1050
+				} else {
1051
+					$parent_line_item->delete_child_line_item($child_line_item->code());
1052
+				}
1053
+				$deleted++;
1054
+			}
1055
+		}
1056
+		return $deleted;
1057
+	}
1058
+
1059
+
1060
+	/**
1061
+	 * Deletes the line items as indicated by the line item code(s) provided,
1062
+	 * regardless of where they're found in the line item tree. Automatically
1063
+	 * re-calculates the line item totals and updates the related transaction. But
1064
+	 * DOES NOT automatically upgrade the transaction's registrations' final prices (which
1065
+	 * should probably change because of this).
1066
+	 * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
1067
+	 * after using this, to keep the registration final prices in-sync with the transaction's total.
1068
+	 *
1069
+	 * @param EE_Line_Item      $total_line_item of type EEM_Line_Item::type_total
1070
+	 * @param array|bool|string $line_item_codes
1071
+	 * @return int number of items successfully removed
1072
+	 * @throws EE_Error
1073
+	 */
1074
+	public static function delete_items(EE_Line_Item $total_line_item, $line_item_codes = false)
1075
+	{
1076
+
1077
+		if ($total_line_item->type() !== EEM_Line_Item::type_total) {
1078
+			EE_Error::doing_it_wrong(
1079
+				'EEH_Line_Item::delete_items',
1080
+				esc_html__(
1081
+					'This static method should only be called with a TOTAL line item, otherwise we won\'t recalculate the totals correctly',
1082
+					'event_espresso'
1083
+				),
1084
+				'4.6.18'
1085
+			);
1086
+		}
1087
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1088
+
1089
+		// check if only a single line_item_id was passed
1090
+		if (! empty($line_item_codes) && ! is_array($line_item_codes)) {
1091
+			// place single line_item_id in an array to appear as multiple line_item_ids
1092
+			$line_item_codes = array($line_item_codes);
1093
+		}
1094
+		$removals = 0;
1095
+		// cycle thru line_item_ids
1096
+		foreach ($line_item_codes as $line_item_id) {
1097
+			$removals += $total_line_item->delete_child_line_item($line_item_id);
1098
+		}
1099
+
1100
+		if ($removals > 0) {
1101
+			$total_line_item->recalculate_taxes_and_tax_total();
1102
+			return $removals;
1103
+		} else {
1104
+			return false;
1105
+		}
1106
+	}
1107
+
1108
+
1109
+	/**
1110
+	 * Overwrites the previous tax by clearing out the old taxes, and creates a new
1111
+	 * tax and updates the total line item accordingly
1112
+	 *
1113
+	 * @param EE_Line_Item $total_line_item
1114
+	 * @param float        $amount
1115
+	 * @param string       $name
1116
+	 * @param string       $description
1117
+	 * @param string       $code
1118
+	 * @param boolean      $add_to_existing_line_item
1119
+	 *                          if true, and a duplicate line item with the same code is found,
1120
+	 *                          $amount will be added onto it; otherwise will simply set the taxes to match $amount
1121
+	 * @return EE_Line_Item the new tax line item created
1122
+	 * @throws EE_Error
1123
+	 * @throws InvalidArgumentException
1124
+	 * @throws InvalidDataTypeException
1125
+	 * @throws InvalidInterfaceException
1126
+	 * @throws ReflectionException
1127
+	 */
1128
+	public static function set_total_tax_to(
1129
+		EE_Line_Item $total_line_item,
1130
+		$amount,
1131
+		$name = null,
1132
+		$description = null,
1133
+		$code = null,
1134
+		$add_to_existing_line_item = false
1135
+	) {
1136
+		$tax_subtotal = self::get_taxes_subtotal($total_line_item);
1137
+		$taxable_total = $total_line_item->taxable_total();
1138
+
1139
+		if ($add_to_existing_line_item) {
1140
+			$new_tax = $tax_subtotal->get_child_line_item($code);
1141
+			EEM_Line_Item::instance()->delete(
1142
+				array(array('LIN_code' => array('!=', $code), 'LIN_parent' => $tax_subtotal->ID()))
1143
+			);
1144
+		} else {
1145
+			$new_tax = null;
1146
+			$tax_subtotal->delete_children_line_items();
1147
+		}
1148
+		if ($new_tax) {
1149
+			$new_tax->set_total($new_tax->total() + $amount);
1150
+			$new_tax->set_percent($taxable_total ? $new_tax->total() / $taxable_total * 100 : 0);
1151
+		} else {
1152
+			// no existing tax item. Create it
1153
+			$new_tax = EE_Line_Item::new_instance(array(
1154
+				'TXN_ID'      => $total_line_item->TXN_ID(),
1155
+				'LIN_name'    => $name ? $name : esc_html__('Tax', 'event_espresso'),
1156
+				'LIN_desc'    => $description ? $description : '',
1157
+				'LIN_percent' => $taxable_total ? ($amount / $taxable_total * 100) : 0,
1158
+				'LIN_total'   => $amount,
1159
+				'LIN_parent'  => $tax_subtotal->ID(),
1160
+				'LIN_type'    => EEM_Line_Item::type_tax,
1161
+				'LIN_code'    => $code,
1162
+			));
1163
+		}
1164
+
1165
+		$new_tax = apply_filters(
1166
+			'FHEE__EEH_Line_Item__set_total_tax_to__new_tax_subtotal',
1167
+			$new_tax,
1168
+			$total_line_item
1169
+		);
1170
+		$new_tax->save();
1171
+		$tax_subtotal->set_total($new_tax->total());
1172
+		$tax_subtotal->save();
1173
+		$total_line_item->recalculate_total_including_taxes();
1174
+		return $new_tax;
1175
+	}
1176
+
1177
+
1178
+	/**
1179
+	 * Makes all the line items which are children of $line_item taxable (or not).
1180
+	 * Does NOT save the line items
1181
+	 *
1182
+	 * @param EE_Line_Item $line_item
1183
+	 * @param boolean      $taxable
1184
+	 * @param string       $code_substring_for_whitelist if this string is part of the line item's code
1185
+	 *                                                   it will be whitelisted (ie, except from becoming taxable)
1186
+	 * @throws EE_Error
1187
+	 */
1188
+	public static function set_line_items_taxable(
1189
+		EE_Line_Item $line_item,
1190
+		$taxable = true,
1191
+		$code_substring_for_whitelist = null
1192
+	) {
1193
+		$whitelisted = false;
1194
+		if ($code_substring_for_whitelist !== null) {
1195
+			$whitelisted = strpos($line_item->code(), $code_substring_for_whitelist) !== false;
1196
+		}
1197
+		if (! $whitelisted && $line_item->is_line_item()) {
1198
+			$line_item->set_is_taxable($taxable);
1199
+		}
1200
+		foreach ($line_item->children() as $child_line_item) {
1201
+			EEH_Line_Item::set_line_items_taxable(
1202
+				$child_line_item,
1203
+				$taxable,
1204
+				$code_substring_for_whitelist
1205
+			);
1206
+		}
1207
+	}
1208
+
1209
+
1210
+	/**
1211
+	 * Gets all descendants that are event subtotals
1212
+	 *
1213
+	 * @uses  EEH_Line_Item::get_subtotals_of_object_type()
1214
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1215
+	 * @return EE_Line_Item[]
1216
+	 * @throws EE_Error
1217
+	 */
1218
+	public static function get_event_subtotals(EE_Line_Item $parent_line_item)
1219
+	{
1220
+		return self::get_subtotals_of_object_type($parent_line_item, EEM_Line_Item::OBJ_TYPE_EVENT);
1221
+	}
1222
+
1223
+
1224
+	/**
1225
+	 * Gets all descendants subtotals that match the supplied object type
1226
+	 *
1227
+	 * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1228
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1229
+	 * @param string       $obj_type
1230
+	 * @return EE_Line_Item[]
1231
+	 * @throws EE_Error
1232
+	 */
1233
+	public static function get_subtotals_of_object_type(EE_Line_Item $parent_line_item, $obj_type = '')
1234
+	{
1235
+		return self::_get_descendants_by_type_and_object_type(
1236
+			$parent_line_item,
1237
+			EEM_Line_Item::type_sub_total,
1238
+			$obj_type
1239
+		);
1240
+	}
1241
+
1242
+
1243
+	/**
1244
+	 * Gets all descendants that are tickets
1245
+	 *
1246
+	 * @uses  EEH_Line_Item::get_line_items_of_object_type()
1247
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1248
+	 * @return EE_Line_Item[]
1249
+	 * @throws EE_Error
1250
+	 */
1251
+	public static function get_ticket_line_items(EE_Line_Item $parent_line_item)
1252
+	{
1253
+		return self::get_line_items_of_object_type(
1254
+			$parent_line_item,
1255
+			EEM_Line_Item::OBJ_TYPE_TICKET
1256
+		);
1257
+	}
1258
+
1259
+
1260
+	/**
1261
+	 * Gets all descendants subtotals that match the supplied object type
1262
+	 *
1263
+	 * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1264
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1265
+	 * @param string       $obj_type
1266
+	 * @return EE_Line_Item[]
1267
+	 * @throws EE_Error
1268
+	 */
1269
+	public static function get_line_items_of_object_type(EE_Line_Item $parent_line_item, $obj_type = '')
1270
+	{
1271
+		return self::_get_descendants_by_type_and_object_type(
1272
+			$parent_line_item,
1273
+			EEM_Line_Item::type_line_item,
1274
+			$obj_type
1275
+		);
1276
+	}
1277
+
1278
+
1279
+	/**
1280
+	 * Gets all the descendants (ie, children or children of children etc) that are of the type 'tax'
1281
+	 *
1282
+	 * @uses  EEH_Line_Item::get_descendants_of_type()
1283
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1284
+	 * @return EE_Line_Item[]
1285
+	 * @throws EE_Error
1286
+	 */
1287
+	public static function get_tax_descendants(EE_Line_Item $parent_line_item)
1288
+	{
1289
+		return EEH_Line_Item::get_descendants_of_type(
1290
+			$parent_line_item,
1291
+			EEM_Line_Item::type_tax
1292
+		);
1293
+	}
1294
+
1295
+
1296
+	/**
1297
+	 * Gets all the real items purchased which are children of this item
1298
+	 *
1299
+	 * @uses  EEH_Line_Item::get_descendants_of_type()
1300
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1301
+	 * @return EE_Line_Item[]
1302
+	 * @throws EE_Error
1303
+	 */
1304
+	public static function get_line_item_descendants(EE_Line_Item $parent_line_item)
1305
+	{
1306
+		return EEH_Line_Item::get_descendants_of_type(
1307
+			$parent_line_item,
1308
+			EEM_Line_Item::type_line_item
1309
+		);
1310
+	}
1311
+
1312
+
1313
+	/**
1314
+	 * Gets all descendants of supplied line item that match the supplied line item type
1315
+	 *
1316
+	 * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1317
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1318
+	 * @param string       $line_item_type   one of the EEM_Line_Item constants
1319
+	 * @return EE_Line_Item[]
1320
+	 * @throws EE_Error
1321
+	 */
1322
+	public static function get_descendants_of_type(EE_Line_Item $parent_line_item, $line_item_type)
1323
+	{
1324
+		return self::_get_descendants_by_type_and_object_type(
1325
+			$parent_line_item,
1326
+			$line_item_type,
1327
+			null
1328
+		);
1329
+	}
1330
+
1331
+
1332
+	/**
1333
+	 * Gets all descendants of supplied line item that match the supplied line item type and possibly the object type
1334
+	 * as well
1335
+	 *
1336
+	 * @param EE_Line_Item  $parent_line_item - the line item to find descendants of
1337
+	 * @param string        $line_item_type   one of the EEM_Line_Item constants
1338
+	 * @param string | NULL $obj_type         object model class name (minus prefix) or NULL to ignore object type when
1339
+	 *                                        searching
1340
+	 * @return EE_Line_Item[]
1341
+	 * @throws EE_Error
1342
+	 */
1343
+	protected static function _get_descendants_by_type_and_object_type(
1344
+		EE_Line_Item $parent_line_item,
1345
+		$line_item_type,
1346
+		$obj_type = null
1347
+	) {
1348
+		$objects = array();
1349
+		foreach ($parent_line_item->children() as $child_line_item) {
1350
+			if ($child_line_item instanceof EE_Line_Item) {
1351
+				if ($child_line_item->type() === $line_item_type
1352
+					&& (
1353
+						$child_line_item->OBJ_type() === $obj_type || $obj_type === null
1354
+					)
1355
+				) {
1356
+					$objects[] = $child_line_item;
1357
+				} else {
1358
+					// go-through-all-its children looking for more matches
1359
+					$objects = array_merge(
1360
+						$objects,
1361
+						self::_get_descendants_by_type_and_object_type(
1362
+							$child_line_item,
1363
+							$line_item_type,
1364
+							$obj_type
1365
+						)
1366
+					);
1367
+				}
1368
+			}
1369
+		}
1370
+		return $objects;
1371
+	}
1372
+
1373
+
1374
+	/**
1375
+	 * Gets all descendants subtotals that match the supplied object type
1376
+	 *
1377
+	 * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1378
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1379
+	 * @param string       $OBJ_type         object type (like Event)
1380
+	 * @param array        $OBJ_IDs          array of OBJ_IDs
1381
+	 * @return EE_Line_Item[]
1382
+	 * @throws EE_Error
1383
+	 */
1384
+	public static function get_line_items_by_object_type_and_IDs(
1385
+		EE_Line_Item $parent_line_item,
1386
+		$OBJ_type = '',
1387
+		$OBJ_IDs = array()
1388
+	) {
1389
+		return self::_get_descendants_by_object_type_and_object_ID(
1390
+			$parent_line_item,
1391
+			$OBJ_type,
1392
+			$OBJ_IDs
1393
+		);
1394
+	}
1395
+
1396
+
1397
+	/**
1398
+	 * Gets all descendants of supplied line item that match the supplied line item type and possibly the object type
1399
+	 * as well
1400
+	 *
1401
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1402
+	 * @param string       $OBJ_type         object type (like Event)
1403
+	 * @param array        $OBJ_IDs          array of OBJ_IDs
1404
+	 * @return EE_Line_Item[]
1405
+	 * @throws EE_Error
1406
+	 */
1407
+	protected static function _get_descendants_by_object_type_and_object_ID(
1408
+		EE_Line_Item $parent_line_item,
1409
+		$OBJ_type,
1410
+		$OBJ_IDs
1411
+	) {
1412
+		$objects = array();
1413
+		foreach ($parent_line_item->children() as $child_line_item) {
1414
+			if ($child_line_item instanceof EE_Line_Item) {
1415
+				if ($child_line_item->OBJ_type() === $OBJ_type
1416
+					&& is_array($OBJ_IDs)
1417
+					&& in_array($child_line_item->OBJ_ID(), $OBJ_IDs)
1418
+				) {
1419
+					$objects[] = $child_line_item;
1420
+				} else {
1421
+					// go-through-all-its children looking for more matches
1422
+					$objects = array_merge(
1423
+						$objects,
1424
+						self::_get_descendants_by_object_type_and_object_ID(
1425
+							$child_line_item,
1426
+							$OBJ_type,
1427
+							$OBJ_IDs
1428
+						)
1429
+					);
1430
+				}
1431
+			}
1432
+		}
1433
+		return $objects;
1434
+	}
1435
+
1436
+
1437
+	/**
1438
+	 * Uses a breadth-first-search in order to find the nearest descendant of
1439
+	 * the specified type and returns it, else NULL
1440
+	 *
1441
+	 * @uses  EEH_Line_Item::_get_nearest_descendant()
1442
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1443
+	 * @param string       $type             like one of the EEM_Line_Item::type_*
1444
+	 * @return EE_Line_Item
1445
+	 * @throws EE_Error
1446
+	 * @throws InvalidArgumentException
1447
+	 * @throws InvalidDataTypeException
1448
+	 * @throws InvalidInterfaceException
1449
+	 * @throws ReflectionException
1450
+	 */
1451
+	public static function get_nearest_descendant_of_type(EE_Line_Item $parent_line_item, $type)
1452
+	{
1453
+		return self::_get_nearest_descendant($parent_line_item, 'LIN_type', $type);
1454
+	}
1455
+
1456
+
1457
+	/**
1458
+	 * Uses a breadth-first-search in order to find the nearest descendant
1459
+	 * having the specified LIN_code and returns it, else NULL
1460
+	 *
1461
+	 * @uses  EEH_Line_Item::_get_nearest_descendant()
1462
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1463
+	 * @param string       $code             any value used for LIN_code
1464
+	 * @return EE_Line_Item
1465
+	 * @throws EE_Error
1466
+	 * @throws InvalidArgumentException
1467
+	 * @throws InvalidDataTypeException
1468
+	 * @throws InvalidInterfaceException
1469
+	 * @throws ReflectionException
1470
+	 */
1471
+	public static function get_nearest_descendant_having_code(EE_Line_Item $parent_line_item, $code)
1472
+	{
1473
+		return self::_get_nearest_descendant($parent_line_item, 'LIN_code', $code);
1474
+	}
1475
+
1476
+
1477
+	/**
1478
+	 * Uses a breadth-first-search in order to find the nearest descendant
1479
+	 * having the specified LIN_code and returns it, else NULL
1480
+	 *
1481
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1482
+	 * @param string       $search_field     name of EE_Line_Item property
1483
+	 * @param string       $value            any value stored in $search_field
1484
+	 * @return EE_Line_Item
1485
+	 * @throws EE_Error
1486
+	 * @throws InvalidArgumentException
1487
+	 * @throws InvalidDataTypeException
1488
+	 * @throws InvalidInterfaceException
1489
+	 * @throws ReflectionException
1490
+	 */
1491
+	protected static function _get_nearest_descendant(EE_Line_Item $parent_line_item, $search_field, $value)
1492
+	{
1493
+		foreach ($parent_line_item->children() as $child) {
1494
+			if ($child->get($search_field) == $value) {
1495
+				return $child;
1496
+			}
1497
+		}
1498
+		foreach ($parent_line_item->children() as $child) {
1499
+			$descendant_found = self::_get_nearest_descendant(
1500
+				$child,
1501
+				$search_field,
1502
+				$value
1503
+			);
1504
+			if ($descendant_found) {
1505
+				return $descendant_found;
1506
+			}
1507
+		}
1508
+		return null;
1509
+	}
1510
+
1511
+
1512
+	/**
1513
+	 * if passed line item has a TXN ID, uses that to jump directly to the grand total line item for the transaction,
1514
+	 * else recursively walks up the line item tree until a parent of type total is found,
1515
+	 *
1516
+	 * @param EE_Line_Item $line_item
1517
+	 * @return EE_Line_Item
1518
+	 * @throws EE_Error
1519
+	 */
1520
+	public static function find_transaction_grand_total_for_line_item(EE_Line_Item $line_item)
1521
+	{
1522
+		if ($line_item->TXN_ID()) {
1523
+			$total_line_item = $line_item->transaction()->total_line_item(false);
1524
+			if ($total_line_item instanceof EE_Line_Item) {
1525
+				return $total_line_item;
1526
+			}
1527
+		} else {
1528
+			$line_item_parent = $line_item->parent();
1529
+			if ($line_item_parent instanceof EE_Line_Item) {
1530
+				if ($line_item_parent->is_total()) {
1531
+					return $line_item_parent;
1532
+				}
1533
+				return EEH_Line_Item::find_transaction_grand_total_for_line_item($line_item_parent);
1534
+			}
1535
+		}
1536
+		throw new EE_Error(
1537
+			sprintf(
1538
+				esc_html__(
1539
+					'A valid grand total for line item %1$d was not found.',
1540
+					'event_espresso'
1541
+				),
1542
+				$line_item->ID()
1543
+			)
1544
+		);
1545
+	}
1546
+
1547
+
1548
+	/**
1549
+	 * Prints out a representation of the line item tree
1550
+	 *
1551
+	 * @param EE_Line_Item $line_item
1552
+	 * @param int          $indentation
1553
+	 * @return void
1554
+	 * @throws EE_Error
1555
+	 */
1556
+	public static function visualize(EE_Line_Item $line_item, $indentation = 0)
1557
+	{
1558
+		echo defined('EE_TESTS_DIR') ? "\n" : '<br />';
1559
+		if (! $indentation) {
1560
+			echo defined('EE_TESTS_DIR') ? "\n" : '<br />';
1561
+		}
1562
+		for ($i = 0; $i < $indentation; $i++) {
1563
+			echo '. ';
1564
+		}
1565
+		$breakdown = '';
1566
+		if ($line_item->is_line_item()) {
1567
+			if ($line_item->is_percent()) {
1568
+				$breakdown = "{$line_item->percent()}%";
1569
+			} else {
1570
+				$breakdown = '$' . "{$line_item->unit_price()} x {$line_item->quantity()}";
1571
+			}
1572
+		}
1573
+		echo $line_item->name();
1574
+		echo " [ ID:{$line_item->ID()} | qty:{$line_item->quantity()} ] {$line_item->type()} : ";
1575
+		echo '$' . (string) $line_item->total();
1576
+		if ($breakdown) {
1577
+			echo " ( {$breakdown} )";
1578
+		}
1579
+		if ($line_item->is_taxable()) {
1580
+			echo '  * taxable';
1581
+		}
1582
+		if ($line_item->children()) {
1583
+			foreach ($line_item->children() as $child) {
1584
+				self::visualize($child, $indentation + 1);
1585
+			}
1586
+		}
1587
+	}
1588
+
1589
+
1590
+	/**
1591
+	 * Calculates the registration's final price, taking into account that they
1592
+	 * need to not only help pay for their OWN ticket, but also any transaction-wide surcharges and taxes,
1593
+	 * and receive a portion of any transaction-wide discounts.
1594
+	 * eg1, if I buy a $1 ticket and brent buys a $9 ticket, and we receive a $5 discount
1595
+	 * then I'll get 1/10 of that $5 discount, which is $0.50, and brent will get
1596
+	 * 9/10ths of that $5 discount, which is $4.50. So my final price should be $0.50
1597
+	 * and brent's final price should be $5.50.
1598
+	 * In order to do this, we basically need to traverse the line item tree calculating
1599
+	 * the running totals (just as if we were recalculating the total), but when we identify
1600
+	 * regular line items, we need to keep track of their share of the grand total.
1601
+	 * Also, we need to keep track of the TAXABLE total for each ticket purchase, so
1602
+	 * we can know how to apply taxes to it. (Note: "taxable total" does not equal the "pretax total"
1603
+	 * when there are non-taxable items; otherwise they would be the same)
1604
+	 *
1605
+	 * @param EE_Line_Item $line_item
1606
+	 * @param array        $billable_ticket_quantities  array of EE_Ticket IDs and their corresponding quantity that
1607
+	 *                                                  can be included in price calculations at this moment
1608
+	 * @return array        keys are line items for tickets IDs and values are their share of the running total,
1609
+	 *                                                  plus the key 'total', and 'taxable' which also has keys of all
1610
+	 *                                                  the ticket IDs.
1611
+	 *                                                  Eg array(
1612
+	 *                                                      12 => 4.3
1613
+	 *                                                      23 => 8.0
1614
+	 *                                                      'total' => 16.6,
1615
+	 *                                                      'taxable' => array(
1616
+	 *                                                          12 => 10,
1617
+	 *                                                          23 => 4
1618
+	 *                                                      ).
1619
+	 *                                                  So to find which registrations have which final price, we need
1620
+	 *                                                  to find which line item is theirs, which can be done with
1621
+	 *                                                  `EEM_Line_Item::instance()->get_line_item_for_registration(
1622
+	 *                                                  $registration );`
1623
+	 * @throws EE_Error
1624
+	 * @throws InvalidArgumentException
1625
+	 * @throws InvalidDataTypeException
1626
+	 * @throws InvalidInterfaceException
1627
+	 * @throws ReflectionException
1628
+	 */
1629
+	public static function calculate_reg_final_prices_per_line_item(
1630
+		EE_Line_Item $line_item,
1631
+		$billable_ticket_quantities = array()
1632
+	) {
1633
+		$running_totals = [
1634
+			'total'   => 0,
1635
+			'taxable' => ['total' => 0]
1636
+		];
1637
+		foreach ($line_item->children() as $child_line_item) {
1638
+			switch ($child_line_item->type()) {
1639
+				case EEM_Line_Item::type_sub_total:
1640
+					$running_totals_from_subtotal = EEH_Line_Item::calculate_reg_final_prices_per_line_item(
1641
+						$child_line_item,
1642
+						$billable_ticket_quantities
1643
+					);
1644
+					// combine arrays but preserve numeric keys
1645
+					$running_totals = array_replace_recursive($running_totals_from_subtotal, $running_totals);
1646
+					$running_totals['total'] += $running_totals_from_subtotal['total'];
1647
+					$running_totals['taxable']['total'] += $running_totals_from_subtotal['taxable']['total'];
1648
+					break;
1649
+
1650
+				case EEM_Line_Item::type_tax_sub_total:
1651
+					// find how much the taxes percentage is
1652
+					if ($child_line_item->percent() !== 0) {
1653
+						$tax_percent_decimal = $child_line_item->percent() / 100;
1654
+					} else {
1655
+						$tax_percent_decimal = EE_Taxes::get_total_taxes_percentage() / 100;
1656
+					}
1657
+					// and apply to all the taxable totals, and add to the pretax totals
1658
+					foreach ($running_totals as $line_item_id => $this_running_total) {
1659
+						// "total" and "taxable" array key is an exception
1660
+						if ($line_item_id === 'taxable') {
1661
+							continue;
1662
+						}
1663
+						$taxable_total = $running_totals['taxable'][ $line_item_id ];
1664
+						$running_totals[ $line_item_id ] += ($taxable_total * $tax_percent_decimal);
1665
+					}
1666
+					break;
1667
+
1668
+				case EEM_Line_Item::type_line_item:
1669
+					// ticket line items or ????
1670
+					if ($child_line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET) {
1671
+						// kk it's a ticket
1672
+						if (isset($running_totals[ $child_line_item->ID() ])) {
1673
+							// huh? that shouldn't happen.
1674
+							$running_totals['total'] += $child_line_item->total();
1675
+						} else {
1676
+							// its not in our running totals yet. great.
1677
+							if ($child_line_item->is_taxable()) {
1678
+								$taxable_amount = $child_line_item->unit_price();
1679
+							} else {
1680
+								$taxable_amount = 0;
1681
+							}
1682
+							// are we only calculating totals for some tickets?
1683
+							if (isset($billable_ticket_quantities[ $child_line_item->OBJ_ID() ])) {
1684
+								$quantity = $billable_ticket_quantities[ $child_line_item->OBJ_ID() ];
1685
+								$running_totals[ $child_line_item->ID() ] = $quantity
1686
+									? $child_line_item->unit_price()
1687
+									: 0;
1688
+								$running_totals['taxable'][ $child_line_item->ID() ] = $quantity
1689
+									? $taxable_amount
1690
+									: 0;
1691
+							} else {
1692
+								$quantity = $child_line_item->quantity();
1693
+								$running_totals[ $child_line_item->ID() ] = $child_line_item->unit_price();
1694
+								$running_totals['taxable'][ $child_line_item->ID() ] = $taxable_amount;
1695
+							}
1696
+							$running_totals['taxable']['total'] += $taxable_amount * $quantity;
1697
+							$running_totals['total'] += $child_line_item->unit_price() * $quantity;
1698
+						}
1699
+					} else {
1700
+						// it's some other type of item added to the cart
1701
+						// it should affect the running totals
1702
+						// basically we want to convert it into a PERCENT modifier. Because
1703
+						// more clearly affect all registration's final price equally
1704
+						$line_items_percent_of_running_total = $running_totals['total'] > 0
1705
+							? ($child_line_item->total() / $running_totals['total']) + 1
1706
+							: 1;
1707
+						foreach ($running_totals as $line_item_id => $this_running_total) {
1708
+							// the "taxable" array key is an exception
1709
+							if ($line_item_id === 'taxable') {
1710
+								continue;
1711
+							}
1712
+							// update the running totals
1713
+							// yes this actually even works for the running grand total!
1714
+							$running_totals[ $line_item_id ] =
1715
+								$line_items_percent_of_running_total * $this_running_total;
1716
+
1717
+							if ($child_line_item->is_taxable()) {
1718
+								$running_totals['taxable'][ $line_item_id ] =
1719
+									$line_items_percent_of_running_total * $running_totals['taxable'][ $line_item_id ];
1720
+							}
1721
+						}
1722
+					}
1723
+					break;
1724
+			}
1725
+		}
1726
+		return $running_totals;
1727
+	}
1728
+
1729
+
1730
+	/**
1731
+	 * @param EE_Line_Item $total_line_item
1732
+	 * @param EE_Line_Item $ticket_line_item
1733
+	 * @return float | null
1734
+	 * @throws EE_Error
1735
+	 * @throws InvalidArgumentException
1736
+	 * @throws InvalidDataTypeException
1737
+	 * @throws InvalidInterfaceException
1738
+	 * @throws OutOfRangeException
1739
+	 * @throws ReflectionException
1740
+	 */
1741
+	public static function calculate_final_price_for_ticket_line_item(
1742
+		EE_Line_Item $total_line_item,
1743
+		EE_Line_Item $ticket_line_item
1744
+	) {
1745
+		static $final_prices_per_ticket_line_item = array();
1746
+		if (empty($final_prices_per_ticket_line_item)) {
1747
+			$final_prices_per_ticket_line_item = EEH_Line_Item::calculate_reg_final_prices_per_line_item(
1748
+				$total_line_item
1749
+			);
1750
+		}
1751
+		// ok now find this new registration's final price
1752
+		if (isset($final_prices_per_ticket_line_item[ $ticket_line_item->ID() ])) {
1753
+			return $final_prices_per_ticket_line_item[ $ticket_line_item->ID() ];
1754
+		}
1755
+		$message = sprintf(
1756
+			esc_html__(
1757
+				'The final price for the ticket line item (ID:%1$d) could not be calculated.',
1758
+				'event_espresso'
1759
+			),
1760
+			$ticket_line_item->ID()
1761
+		);
1762
+		if (WP_DEBUG) {
1763
+			$message .= '<br>' . print_r($final_prices_per_ticket_line_item, true);
1764
+			throw new OutOfRangeException($message);
1765
+		}
1766
+		EE_Log::instance()->log(__CLASS__, __FUNCTION__, $message);
1767
+		return null;
1768
+	}
1769
+
1770
+
1771
+	/**
1772
+	 * Creates a duplicate of the line item tree, except only includes billable items
1773
+	 * and the portion of line items attributed to billable things
1774
+	 *
1775
+	 * @param EE_Line_Item      $line_item
1776
+	 * @param EE_Registration[] $registrations
1777
+	 * @return EE_Line_Item
1778
+	 * @throws EE_Error
1779
+	 * @throws InvalidArgumentException
1780
+	 * @throws InvalidDataTypeException
1781
+	 * @throws InvalidInterfaceException
1782
+	 * @throws ReflectionException
1783
+	 */
1784
+	public static function billable_line_item_tree(EE_Line_Item $line_item, $registrations)
1785
+	{
1786
+		$copy_li = EEH_Line_Item::billable_line_item($line_item, $registrations);
1787
+		foreach ($line_item->children() as $child_li) {
1788
+			$copy_li->add_child_line_item(
1789
+				EEH_Line_Item::billable_line_item_tree($child_li, $registrations)
1790
+			);
1791
+		}
1792
+		// if this is the grand total line item, make sure the totals all add up
1793
+		// (we could have duplicated this logic AS we copied the line items, but
1794
+		// it seems DRYer this way)
1795
+		if ($copy_li->type() === EEM_Line_Item::type_total) {
1796
+			$copy_li->recalculate_total_including_taxes();
1797
+		}
1798
+		return $copy_li;
1799
+	}
1800
+
1801
+
1802
+	/**
1803
+	 * Creates a new, unsaved line item from $line_item that factors in the
1804
+	 * number of billable registrations on $registrations.
1805
+	 *
1806
+	 * @param EE_Line_Item      $line_item
1807
+	 * @param EE_Registration[] $registrations
1808
+	 * @return EE_Line_Item
1809
+	 * @throws EE_Error
1810
+	 * @throws InvalidArgumentException
1811
+	 * @throws InvalidDataTypeException
1812
+	 * @throws InvalidInterfaceException
1813
+	 * @throws ReflectionException
1814
+	 */
1815
+	public static function billable_line_item(EE_Line_Item $line_item, $registrations)
1816
+	{
1817
+		$new_li_fields = $line_item->model_field_array();
1818
+		if ($line_item->type() === EEM_Line_Item::type_line_item &&
1819
+			$line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET
1820
+		) {
1821
+			$count = 0;
1822
+			foreach ($registrations as $registration) {
1823
+				if ($line_item->OBJ_ID() === $registration->ticket_ID() &&
1824
+					in_array(
1825
+						$registration->status_ID(),
1826
+						EEM_Registration::reg_statuses_that_allow_payment(),
1827
+						true
1828
+					)
1829
+				) {
1830
+					$count++;
1831
+				}
1832
+			}
1833
+			$new_li_fields['LIN_quantity'] = $count;
1834
+		}
1835
+		// don't set the total. We'll leave that up to the code that calculates it
1836
+		unset($new_li_fields['LIN_ID'], $new_li_fields['LIN_parent'], $new_li_fields['LIN_total']);
1837
+		return EE_Line_Item::new_instance($new_li_fields);
1838
+	}
1839
+
1840
+
1841
+	/**
1842
+	 * Returns a modified line item tree where all the subtotals which have a total of 0
1843
+	 * are removed, and line items with a quantity of 0
1844
+	 *
1845
+	 * @param EE_Line_Item $line_item |null
1846
+	 * @return EE_Line_Item|null
1847
+	 * @throws EE_Error
1848
+	 * @throws InvalidArgumentException
1849
+	 * @throws InvalidDataTypeException
1850
+	 * @throws InvalidInterfaceException
1851
+	 * @throws ReflectionException
1852
+	 */
1853
+	public static function non_empty_line_items(EE_Line_Item $line_item)
1854
+	{
1855
+		$copied_li = EEH_Line_Item::non_empty_line_item($line_item);
1856
+		if ($copied_li === null) {
1857
+			return null;
1858
+		}
1859
+		// if this is an event subtotal, we want to only include it if it
1860
+		// has a non-zero total and at least one ticket line item child
1861
+		$ticket_children = 0;
1862
+		foreach ($line_item->children() as $child_li) {
1863
+			$child_li_copy = EEH_Line_Item::non_empty_line_items($child_li);
1864
+			if ($child_li_copy !== null) {
1865
+				$copied_li->add_child_line_item($child_li_copy);
1866
+				if ($child_li_copy->type() === EEM_Line_Item::type_line_item &&
1867
+					$child_li_copy->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET
1868
+				) {
1869
+					$ticket_children++;
1870
+				}
1871
+			}
1872
+		}
1873
+		// if this is an event subtotal with NO ticket children
1874
+		// we basically want to ignore it
1875
+		if ($ticket_children === 0
1876
+			&& $line_item->type() === EEM_Line_Item::type_sub_total
1877
+			&& $line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_EVENT
1878
+			&& $line_item->total() === 0
1879
+		) {
1880
+			return null;
1881
+		}
1882
+		return $copied_li;
1883
+	}
1884
+
1885
+
1886
+	/**
1887
+	 * Creates a new, unsaved line item, but if it's a ticket line item
1888
+	 * with a total of 0, or a subtotal of 0, returns null instead
1889
+	 *
1890
+	 * @param EE_Line_Item $line_item
1891
+	 * @return EE_Line_Item
1892
+	 * @throws EE_Error
1893
+	 * @throws InvalidArgumentException
1894
+	 * @throws InvalidDataTypeException
1895
+	 * @throws InvalidInterfaceException
1896
+	 * @throws ReflectionException
1897
+	 */
1898
+	public static function non_empty_line_item(EE_Line_Item $line_item)
1899
+	{
1900
+		if ($line_item->type() === EEM_Line_Item::type_line_item
1901
+			&& $line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET
1902
+			&& $line_item->quantity() === 0
1903
+		) {
1904
+			return null;
1905
+		}
1906
+		$new_li_fields = $line_item->model_field_array();
1907
+		// don't set the total. We'll leave that up to the code that calculates it
1908
+		unset($new_li_fields['LIN_ID'], $new_li_fields['LIN_parent']);
1909
+		return EE_Line_Item::new_instance($new_li_fields);
1910
+	}
1911
+
1912
+
1913
+	/**
1914
+	 * Cycles through all of the ticket line items for the supplied total line item
1915
+	 * and ensures that the line item's "is_taxable" field matches that of its corresponding ticket
1916
+	 *
1917
+	 * @param EE_Line_Item $total_line_item
1918
+	 * @since $VID:$
1919
+	 * @throws EE_Error
1920
+	 * @throws InvalidArgumentException
1921
+	 * @throws InvalidDataTypeException
1922
+	 * @throws InvalidInterfaceException
1923
+	 * @throws ReflectionException
1924
+	 */
1925
+	public static function resetIsTaxableForTickets(EE_Line_Item $total_line_item)
1926
+	{
1927
+		$ticket_line_items = self::get_ticket_line_items($total_line_item);
1928
+		foreach ($ticket_line_items as $ticket_line_item) {
1929
+			if ($ticket_line_item instanceof EE_Line_Item
1930
+				&& $ticket_line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET
1931
+			) {
1932
+				$ticket = $ticket_line_item->ticket();
1933
+				if ($ticket instanceof EE_Ticket && $ticket->taxable() !== $ticket_line_item->is_taxable()) {
1934
+					$ticket_line_item->set_is_taxable($ticket->taxable());
1935
+					$ticket_line_item->save();
1936
+				}
1937
+			}
1938
+		}
1939
+	}
1940
+
1941
+
1942
+
1943
+	/**************************************** @DEPRECATED METHODS *************************************** */
1944
+	/**
1945
+	 * @deprecated
1946
+	 * @param EE_Line_Item $total_line_item
1947
+	 * @return EE_Line_Item
1948
+	 * @throws EE_Error
1949
+	 * @throws InvalidArgumentException
1950
+	 * @throws InvalidDataTypeException
1951
+	 * @throws InvalidInterfaceException
1952
+	 * @throws ReflectionException
1953
+	 */
1954
+	public static function get_items_subtotal(EE_Line_Item $total_line_item)
1955
+	{
1956
+		EE_Error::doing_it_wrong(
1957
+			'EEH_Line_Item::get_items_subtotal()',
1958
+			sprintf(
1959
+				esc_html__('Method replaced with %1$s', 'event_espresso'),
1960
+				'EEH_Line_Item::get_pre_tax_subtotal()'
1961
+			),
1962
+			'4.6.0'
1963
+		);
1964
+		return self::get_pre_tax_subtotal($total_line_item);
1965
+	}
1966
+
1967
+
1968
+	/**
1969
+	 * @deprecated
1970
+	 * @param EE_Transaction $transaction
1971
+	 * @return EE_Line_Item
1972
+	 * @throws EE_Error
1973
+	 * @throws InvalidArgumentException
1974
+	 * @throws InvalidDataTypeException
1975
+	 * @throws InvalidInterfaceException
1976
+	 * @throws ReflectionException
1977
+	 */
1978
+	public static function create_default_total_line_item($transaction = null)
1979
+	{
1980
+		EE_Error::doing_it_wrong(
1981
+			'EEH_Line_Item::create_default_total_line_item()',
1982
+			sprintf(
1983
+				esc_html__('Method replaced with %1$s', 'event_espresso'),
1984
+				'EEH_Line_Item::create_total_line_item()'
1985
+			),
1986
+			'4.6.0'
1987
+		);
1988
+		return self::create_total_line_item($transaction);
1989
+	}
1990
+
1991
+
1992
+	/**
1993
+	 * @deprecated
1994
+	 * @param EE_Line_Item   $total_line_item
1995
+	 * @param EE_Transaction $transaction
1996
+	 * @return EE_Line_Item
1997
+	 * @throws EE_Error
1998
+	 * @throws InvalidArgumentException
1999
+	 * @throws InvalidDataTypeException
2000
+	 * @throws InvalidInterfaceException
2001
+	 * @throws ReflectionException
2002
+	 */
2003
+	public static function create_default_tickets_subtotal(EE_Line_Item $total_line_item, $transaction = null)
2004
+	{
2005
+		EE_Error::doing_it_wrong(
2006
+			'EEH_Line_Item::create_default_tickets_subtotal()',
2007
+			sprintf(
2008
+				esc_html__('Method replaced with %1$s', 'event_espresso'),
2009
+				'EEH_Line_Item::create_pre_tax_subtotal()'
2010
+			),
2011
+			'4.6.0'
2012
+		);
2013
+		return self::create_pre_tax_subtotal($total_line_item, $transaction);
2014
+	}
2015
+
2016
+
2017
+	/**
2018
+	 * @deprecated
2019
+	 * @param EE_Line_Item   $total_line_item
2020
+	 * @param EE_Transaction $transaction
2021
+	 * @return EE_Line_Item
2022
+	 * @throws EE_Error
2023
+	 * @throws InvalidArgumentException
2024
+	 * @throws InvalidDataTypeException
2025
+	 * @throws InvalidInterfaceException
2026
+	 * @throws ReflectionException
2027
+	 */
2028
+	public static function create_default_taxes_subtotal(EE_Line_Item $total_line_item, $transaction = null)
2029
+	{
2030
+		EE_Error::doing_it_wrong(
2031
+			'EEH_Line_Item::create_default_taxes_subtotal()',
2032
+			sprintf(
2033
+				esc_html__('Method replaced with %1$s', 'event_espresso'),
2034
+				'EEH_Line_Item::create_taxes_subtotal()'
2035
+			),
2036
+			'4.6.0'
2037
+		);
2038
+		return self::create_taxes_subtotal($total_line_item, $transaction);
2039
+	}
2040
+
2041
+
2042
+	/**
2043
+	 * @deprecated
2044
+	 * @param EE_Line_Item   $total_line_item
2045
+	 * @param EE_Transaction $transaction
2046
+	 * @return EE_Line_Item
2047
+	 * @throws EE_Error
2048
+	 * @throws InvalidArgumentException
2049
+	 * @throws InvalidDataTypeException
2050
+	 * @throws InvalidInterfaceException
2051
+	 * @throws ReflectionException
2052
+	 */
2053
+	public static function create_default_event_subtotal(EE_Line_Item $total_line_item, $transaction = null)
2054
+	{
2055
+		EE_Error::doing_it_wrong(
2056
+			'EEH_Line_Item::create_default_event_subtotal()',
2057
+			sprintf(
2058
+				esc_html__('Method replaced with %1$s', 'event_espresso'),
2059
+				'EEH_Line_Item::create_event_subtotal()'
2060
+			),
2061
+			'4.6.0'
2062
+		);
2063
+		return self::create_event_subtotal($total_line_item, $transaction);
2064
+	}
2065 2065
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Line_Item.class.php 1 patch
Indentation   +1735 added lines, -1735 removed lines patch added patch discarded remove patch
@@ -14,1739 +14,1739 @@
 block discarded – undo
14 14
 class EE_Line_Item extends EE_Base_Class implements EEI_Line_Item
15 15
 {
16 16
 
17
-    /**
18
-     * for children line items (currently not a normal relation)
19
-     *
20
-     * @type EE_Line_Item[]
21
-     */
22
-    protected $_children = array();
23
-
24
-    /**
25
-     * for the parent line item
26
-     *
27
-     * @var EE_Line_Item
28
-     */
29
-    protected $_parent;
30
-
31
-
32
-    /**
33
-     * @param array  $props_n_values          incoming values
34
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
35
-     *                                        used.)
36
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
37
-     *                                        date_format and the second value is the time format
38
-     * @return EE_Line_Item
39
-     * @throws EE_Error
40
-     * @throws InvalidArgumentException
41
-     * @throws InvalidDataTypeException
42
-     * @throws InvalidInterfaceException
43
-     * @throws ReflectionException
44
-     */
45
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
46
-    {
47
-        $has_object = parent::_check_for_object(
48
-            $props_n_values,
49
-            __CLASS__,
50
-            $timezone,
51
-            $date_formats
52
-        );
53
-        return $has_object
54
-            ? $has_object
55
-            : new self($props_n_values, false, $timezone);
56
-    }
57
-
58
-
59
-    /**
60
-     * @param array  $props_n_values  incoming values from the database
61
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
62
-     *                                the website will be used.
63
-     * @return EE_Line_Item
64
-     * @throws EE_Error
65
-     * @throws InvalidArgumentException
66
-     * @throws InvalidDataTypeException
67
-     * @throws InvalidInterfaceException
68
-     * @throws ReflectionException
69
-     */
70
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
71
-    {
72
-        return new self($props_n_values, true, $timezone);
73
-    }
74
-
75
-
76
-    /**
77
-     * Adds some defaults if they're not specified
78
-     *
79
-     * @param array  $fieldValues
80
-     * @param bool   $bydb
81
-     * @param string $timezone
82
-     * @throws EE_Error
83
-     * @throws InvalidArgumentException
84
-     * @throws InvalidDataTypeException
85
-     * @throws InvalidInterfaceException
86
-     * @throws ReflectionException
87
-     */
88
-    protected function __construct($fieldValues = array(), $bydb = false, $timezone = '')
89
-    {
90
-        parent::__construct($fieldValues, $bydb, $timezone);
91
-        if (! $this->get('LIN_code')) {
92
-            $this->set_code($this->generate_code());
93
-        }
94
-    }
95
-
96
-
97
-    /**
98
-     * Gets ID
99
-     *
100
-     * @return int
101
-     * @throws EE_Error
102
-     * @throws InvalidArgumentException
103
-     * @throws InvalidDataTypeException
104
-     * @throws InvalidInterfaceException
105
-     * @throws ReflectionException
106
-     */
107
-    public function ID()
108
-    {
109
-        return $this->get('LIN_ID');
110
-    }
111
-
112
-
113
-    /**
114
-     * Gets TXN_ID
115
-     *
116
-     * @return int
117
-     * @throws EE_Error
118
-     * @throws InvalidArgumentException
119
-     * @throws InvalidDataTypeException
120
-     * @throws InvalidInterfaceException
121
-     * @throws ReflectionException
122
-     */
123
-    public function TXN_ID()
124
-    {
125
-        return $this->get('TXN_ID');
126
-    }
127
-
128
-
129
-    /**
130
-     * Sets TXN_ID
131
-     *
132
-     * @param int $TXN_ID
133
-     * @throws EE_Error
134
-     * @throws InvalidArgumentException
135
-     * @throws InvalidDataTypeException
136
-     * @throws InvalidInterfaceException
137
-     * @throws ReflectionException
138
-     */
139
-    public function set_TXN_ID($TXN_ID)
140
-    {
141
-        $this->set('TXN_ID', $TXN_ID);
142
-    }
143
-
144
-
145
-    /**
146
-     * Gets name
147
-     *
148
-     * @return string
149
-     * @throws EE_Error
150
-     * @throws InvalidArgumentException
151
-     * @throws InvalidDataTypeException
152
-     * @throws InvalidInterfaceException
153
-     * @throws ReflectionException
154
-     */
155
-    public function name()
156
-    {
157
-        $name = $this->get('LIN_name');
158
-        if (! $name) {
159
-            $name = ucwords(str_replace('-', ' ', $this->type()));
160
-        }
161
-        return $name;
162
-    }
163
-
164
-
165
-    /**
166
-     * Sets name
167
-     *
168
-     * @param string $name
169
-     * @throws EE_Error
170
-     * @throws InvalidArgumentException
171
-     * @throws InvalidDataTypeException
172
-     * @throws InvalidInterfaceException
173
-     * @throws ReflectionException
174
-     */
175
-    public function set_name($name)
176
-    {
177
-        $this->set('LIN_name', $name);
178
-    }
179
-
180
-
181
-    /**
182
-     * Gets desc
183
-     *
184
-     * @return string
185
-     * @throws EE_Error
186
-     * @throws InvalidArgumentException
187
-     * @throws InvalidDataTypeException
188
-     * @throws InvalidInterfaceException
189
-     * @throws ReflectionException
190
-     */
191
-    public function desc()
192
-    {
193
-        return $this->get('LIN_desc');
194
-    }
195
-
196
-
197
-    /**
198
-     * Sets desc
199
-     *
200
-     * @param string $desc
201
-     * @throws EE_Error
202
-     * @throws InvalidArgumentException
203
-     * @throws InvalidDataTypeException
204
-     * @throws InvalidInterfaceException
205
-     * @throws ReflectionException
206
-     */
207
-    public function set_desc($desc)
208
-    {
209
-        $this->set('LIN_desc', $desc);
210
-    }
211
-
212
-
213
-    /**
214
-     * Gets quantity
215
-     *
216
-     * @return int
217
-     * @throws EE_Error
218
-     * @throws InvalidArgumentException
219
-     * @throws InvalidDataTypeException
220
-     * @throws InvalidInterfaceException
221
-     * @throws ReflectionException
222
-     */
223
-    public function quantity()
224
-    {
225
-        return $this->get('LIN_quantity');
226
-    }
227
-
228
-
229
-    /**
230
-     * Sets quantity
231
-     *
232
-     * @param int $quantity
233
-     * @throws EE_Error
234
-     * @throws InvalidArgumentException
235
-     * @throws InvalidDataTypeException
236
-     * @throws InvalidInterfaceException
237
-     * @throws ReflectionException
238
-     */
239
-    public function set_quantity($quantity)
240
-    {
241
-        $this->set('LIN_quantity', max($quantity, 0));
242
-    }
243
-
244
-
245
-    /**
246
-     * Gets item_id
247
-     *
248
-     * @return string
249
-     * @throws EE_Error
250
-     * @throws InvalidArgumentException
251
-     * @throws InvalidDataTypeException
252
-     * @throws InvalidInterfaceException
253
-     * @throws ReflectionException
254
-     */
255
-    public function OBJ_ID()
256
-    {
257
-        return $this->get('OBJ_ID');
258
-    }
259
-
260
-
261
-    /**
262
-     * Sets item_id
263
-     *
264
-     * @param string $item_id
265
-     * @throws EE_Error
266
-     * @throws InvalidArgumentException
267
-     * @throws InvalidDataTypeException
268
-     * @throws InvalidInterfaceException
269
-     * @throws ReflectionException
270
-     */
271
-    public function set_OBJ_ID($item_id)
272
-    {
273
-        $this->set('OBJ_ID', $item_id);
274
-    }
275
-
276
-
277
-    /**
278
-     * Gets item_type
279
-     *
280
-     * @return string
281
-     * @throws EE_Error
282
-     * @throws InvalidArgumentException
283
-     * @throws InvalidDataTypeException
284
-     * @throws InvalidInterfaceException
285
-     * @throws ReflectionException
286
-     */
287
-    public function OBJ_type()
288
-    {
289
-        return $this->get('OBJ_type');
290
-    }
291
-
292
-
293
-    /**
294
-     * Gets item_type
295
-     *
296
-     * @return string
297
-     * @throws EE_Error
298
-     * @throws InvalidArgumentException
299
-     * @throws InvalidDataTypeException
300
-     * @throws InvalidInterfaceException
301
-     * @throws ReflectionException
302
-     */
303
-    public function OBJ_type_i18n()
304
-    {
305
-        $obj_type = $this->OBJ_type();
306
-        switch ($obj_type) {
307
-            case EEM_Line_Item::OBJ_TYPE_EVENT:
308
-                $obj_type = esc_html__('Event', 'event_espresso');
309
-                break;
310
-            case EEM_Line_Item::OBJ_TYPE_PRICE:
311
-                $obj_type = esc_html__('Price', 'event_espresso');
312
-                break;
313
-            case EEM_Line_Item::OBJ_TYPE_PROMOTION:
314
-                $obj_type = esc_html__('Promotion', 'event_espresso');
315
-                break;
316
-            case EEM_Line_Item::OBJ_TYPE_TICKET:
317
-                $obj_type = esc_html__('Ticket', 'event_espresso');
318
-                break;
319
-            case EEM_Line_Item::OBJ_TYPE_TRANSACTION:
320
-                $obj_type = esc_html__('Transaction', 'event_espresso');
321
-                break;
322
-        }
323
-        return apply_filters('FHEE__EE_Line_Item__OBJ_type_i18n', $obj_type, $this);
324
-    }
325
-
326
-
327
-    /**
328
-     * Sets item_type
329
-     *
330
-     * @param string $OBJ_type
331
-     * @throws EE_Error
332
-     * @throws InvalidArgumentException
333
-     * @throws InvalidDataTypeException
334
-     * @throws InvalidInterfaceException
335
-     * @throws ReflectionException
336
-     */
337
-    public function set_OBJ_type($OBJ_type)
338
-    {
339
-        $this->set('OBJ_type', $OBJ_type);
340
-    }
341
-
342
-
343
-    /**
344
-     * Gets unit_price
345
-     *
346
-     * @return float
347
-     * @throws EE_Error
348
-     * @throws InvalidArgumentException
349
-     * @throws InvalidDataTypeException
350
-     * @throws InvalidInterfaceException
351
-     * @throws ReflectionException
352
-     */
353
-    public function unit_price()
354
-    {
355
-        return $this->get('LIN_unit_price');
356
-    }
357
-
358
-
359
-    /**
360
-     * Sets unit_price
361
-     *
362
-     * @param float $unit_price
363
-     * @throws EE_Error
364
-     * @throws InvalidArgumentException
365
-     * @throws InvalidDataTypeException
366
-     * @throws InvalidInterfaceException
367
-     * @throws ReflectionException
368
-     */
369
-    public function set_unit_price($unit_price)
370
-    {
371
-        $this->set('LIN_unit_price', $unit_price);
372
-    }
373
-
374
-
375
-    /**
376
-     * Checks if this item is a percentage modifier or not
377
-     *
378
-     * @return boolean
379
-     * @throws EE_Error
380
-     * @throws InvalidArgumentException
381
-     * @throws InvalidDataTypeException
382
-     * @throws InvalidInterfaceException
383
-     * @throws ReflectionException
384
-     */
385
-    public function is_percent()
386
-    {
387
-        if ($this->is_tax_sub_total()) {
388
-            // tax subtotals HAVE a percent on them, that percentage only applies
389
-            // to taxable items, so its' an exception. Treat it like a flat line item
390
-            return false;
391
-        }
392
-        $unit_price = abs($this->get('LIN_unit_price'));
393
-        $percent = abs($this->get('LIN_percent'));
394
-        if ($unit_price < .001 && $percent) {
395
-            return true;
396
-        }
397
-        if ($unit_price >= .001 && ! $percent) {
398
-            return false;
399
-        }
400
-        if ($unit_price >= .001 && $percent) {
401
-            throw new EE_Error(
402
-                sprintf(
403
-                    esc_html__(
404
-                        'A Line Item can not have a unit price of (%s) AND a percent (%s)!',
405
-                        'event_espresso'
406
-                    ),
407
-                    $unit_price,
408
-                    $percent
409
-                )
410
-            );
411
-        }
412
-        // if they're both 0, assume its not a percent item
413
-        return false;
414
-    }
415
-
416
-
417
-    /**
418
-     * Gets percent (between 100-.001)
419
-     *
420
-     * @return float
421
-     * @throws EE_Error
422
-     * @throws InvalidArgumentException
423
-     * @throws InvalidDataTypeException
424
-     * @throws InvalidInterfaceException
425
-     * @throws ReflectionException
426
-     */
427
-    public function percent()
428
-    {
429
-        return $this->get('LIN_percent');
430
-    }
431
-
432
-
433
-    /**
434
-     * Sets percent (between 100-0.01)
435
-     *
436
-     * @param float $percent
437
-     * @throws EE_Error
438
-     * @throws InvalidArgumentException
439
-     * @throws InvalidDataTypeException
440
-     * @throws InvalidInterfaceException
441
-     * @throws ReflectionException
442
-     */
443
-    public function set_percent($percent)
444
-    {
445
-        $this->set('LIN_percent', $percent);
446
-    }
447
-
448
-
449
-    /**
450
-     * Gets total
451
-     *
452
-     * @return float
453
-     * @throws EE_Error
454
-     * @throws InvalidArgumentException
455
-     * @throws InvalidDataTypeException
456
-     * @throws InvalidInterfaceException
457
-     * @throws ReflectionException
458
-     */
459
-    public function total()
460
-    {
461
-        return $this->get('LIN_total');
462
-    }
463
-
464
-
465
-    /**
466
-     * Sets total
467
-     *
468
-     * @param float $total
469
-     * @throws EE_Error
470
-     * @throws InvalidArgumentException
471
-     * @throws InvalidDataTypeException
472
-     * @throws InvalidInterfaceException
473
-     * @throws ReflectionException
474
-     */
475
-    public function set_total($total)
476
-    {
477
-        $this->set('LIN_total', $total);
478
-    }
479
-
480
-
481
-    /**
482
-     * Gets order
483
-     *
484
-     * @return int
485
-     * @throws EE_Error
486
-     * @throws InvalidArgumentException
487
-     * @throws InvalidDataTypeException
488
-     * @throws InvalidInterfaceException
489
-     * @throws ReflectionException
490
-     */
491
-    public function order()
492
-    {
493
-        return $this->get('LIN_order');
494
-    }
495
-
496
-
497
-    /**
498
-     * Sets order
499
-     *
500
-     * @param int $order
501
-     * @throws EE_Error
502
-     * @throws InvalidArgumentException
503
-     * @throws InvalidDataTypeException
504
-     * @throws InvalidInterfaceException
505
-     * @throws ReflectionException
506
-     */
507
-    public function set_order($order)
508
-    {
509
-        $this->set('LIN_order', $order);
510
-    }
511
-
512
-
513
-    /**
514
-     * Gets parent
515
-     *
516
-     * @return int
517
-     * @throws EE_Error
518
-     * @throws InvalidArgumentException
519
-     * @throws InvalidDataTypeException
520
-     * @throws InvalidInterfaceException
521
-     * @throws ReflectionException
522
-     */
523
-    public function parent_ID()
524
-    {
525
-        return $this->get('LIN_parent');
526
-    }
527
-
528
-
529
-    /**
530
-     * Sets parent
531
-     *
532
-     * @param int $parent
533
-     * @throws EE_Error
534
-     * @throws InvalidArgumentException
535
-     * @throws InvalidDataTypeException
536
-     * @throws InvalidInterfaceException
537
-     * @throws ReflectionException
538
-     */
539
-    public function set_parent_ID($parent)
540
-    {
541
-        $this->set('LIN_parent', $parent);
542
-    }
543
-
544
-
545
-    /**
546
-     * Gets type
547
-     *
548
-     * @return string
549
-     * @throws EE_Error
550
-     * @throws InvalidArgumentException
551
-     * @throws InvalidDataTypeException
552
-     * @throws InvalidInterfaceException
553
-     * @throws ReflectionException
554
-     */
555
-    public function type()
556
-    {
557
-        return $this->get('LIN_type');
558
-    }
559
-
560
-
561
-    /**
562
-     * Sets type
563
-     *
564
-     * @param string $type
565
-     * @throws EE_Error
566
-     * @throws InvalidArgumentException
567
-     * @throws InvalidDataTypeException
568
-     * @throws InvalidInterfaceException
569
-     * @throws ReflectionException
570
-     */
571
-    public function set_type($type)
572
-    {
573
-        $this->set('LIN_type', $type);
574
-    }
575
-
576
-
577
-    /**
578
-     * Gets the line item of which this item is a composite. Eg, if this is a subtotal, the parent might be a total\
579
-     * If this line item is saved to the DB, fetches the parent from the DB. However, if this line item isn't in the DB
580
-     * it uses its cached reference to its parent line item (which would have been set by `EE_Line_Item::set_parent()`
581
-     * or indirectly by `EE_Line_item::add_child_line_item()`)
582
-     *
583
-     * @return EE_Base_Class|EE_Line_Item
584
-     * @throws EE_Error
585
-     * @throws InvalidArgumentException
586
-     * @throws InvalidDataTypeException
587
-     * @throws InvalidInterfaceException
588
-     * @throws ReflectionException
589
-     */
590
-    public function parent()
591
-    {
592
-        return $this->ID()
593
-            ? $this->get_model()->get_one_by_ID($this->parent_ID())
594
-            : $this->_parent;
595
-    }
596
-
597
-
598
-    /**
599
-     * Gets ALL the children of this line item (ie, all the parts that contribute towards this total).
600
-     *
601
-     * @return EE_Base_Class[]|EE_Line_Item[]
602
-     * @throws EE_Error
603
-     * @throws InvalidArgumentException
604
-     * @throws InvalidDataTypeException
605
-     * @throws InvalidInterfaceException
606
-     * @throws ReflectionException
607
-     */
608
-    public function children()
609
-    {
610
-        if ($this->ID()) {
611
-            return $this->get_model()->get_all(
612
-                array(
613
-                    array('LIN_parent' => $this->ID()),
614
-                    'order_by' => array('LIN_order' => 'ASC'),
615
-                )
616
-            );
617
-        }
618
-        if (! is_array($this->_children)) {
619
-            $this->_children = array();
620
-        }
621
-        return $this->_children;
622
-    }
623
-
624
-
625
-    /**
626
-     * Gets code
627
-     *
628
-     * @return string
629
-     * @throws EE_Error
630
-     * @throws InvalidArgumentException
631
-     * @throws InvalidDataTypeException
632
-     * @throws InvalidInterfaceException
633
-     * @throws ReflectionException
634
-     */
635
-    public function code()
636
-    {
637
-        return $this->get('LIN_code');
638
-    }
639
-
640
-
641
-    /**
642
-     * Sets code
643
-     *
644
-     * @param string $code
645
-     * @throws EE_Error
646
-     * @throws InvalidArgumentException
647
-     * @throws InvalidDataTypeException
648
-     * @throws InvalidInterfaceException
649
-     * @throws ReflectionException
650
-     */
651
-    public function set_code($code)
652
-    {
653
-        $this->set('LIN_code', $code);
654
-    }
655
-
656
-
657
-    /**
658
-     * Gets is_taxable
659
-     *
660
-     * @return boolean
661
-     * @throws EE_Error
662
-     * @throws InvalidArgumentException
663
-     * @throws InvalidDataTypeException
664
-     * @throws InvalidInterfaceException
665
-     * @throws ReflectionException
666
-     */
667
-    public function is_taxable()
668
-    {
669
-        return $this->get('LIN_is_taxable');
670
-    }
671
-
672
-
673
-    /**
674
-     * Sets is_taxable
675
-     *
676
-     * @param boolean $is_taxable
677
-     * @throws EE_Error
678
-     * @throws InvalidArgumentException
679
-     * @throws InvalidDataTypeException
680
-     * @throws InvalidInterfaceException
681
-     * @throws ReflectionException
682
-     */
683
-    public function set_is_taxable($is_taxable)
684
-    {
685
-        $this->set('LIN_is_taxable', $is_taxable);
686
-    }
687
-
688
-
689
-    /**
690
-     * Gets the object that this model-joins-to.
691
-     * returns one of the model objects that the field OBJ_ID can point to... see the 'OBJ_ID' field on
692
-     * EEM_Promotion_Object
693
-     *        Eg, if this line item join model object is for a ticket, this will return the EE_Ticket object
694
-     *
695
-     * @return EE_Base_Class | NULL
696
-     * @throws EE_Error
697
-     * @throws InvalidArgumentException
698
-     * @throws InvalidDataTypeException
699
-     * @throws InvalidInterfaceException
700
-     * @throws ReflectionException
701
-     */
702
-    public function get_object()
703
-    {
704
-        $model_name_of_related_obj = $this->OBJ_type();
705
-        return $this->get_model()->has_relation($model_name_of_related_obj)
706
-            ? $this->get_first_related($model_name_of_related_obj)
707
-            : null;
708
-    }
709
-
710
-
711
-    /**
712
-     * Like EE_Line_Item::get_object(), but can only ever actually return an EE_Ticket.
713
-     * (IE, if this line item is for a price or something else, will return NULL)
714
-     *
715
-     * @param array $query_params
716
-     * @return EE_Base_Class|EE_Ticket
717
-     * @throws EE_Error
718
-     * @throws InvalidArgumentException
719
-     * @throws InvalidDataTypeException
720
-     * @throws InvalidInterfaceException
721
-     * @throws ReflectionException
722
-     */
723
-    public function ticket($query_params = array())
724
-    {
725
-        // we're going to assume that when this method is called
726
-        // we always want to receive the attached ticket EVEN if that ticket is archived.
727
-        // This can be overridden via the incoming $query_params argument
728
-        $remove_defaults = array('default_where_conditions' => 'none');
729
-        $query_params = array_merge($remove_defaults, $query_params);
730
-        return $this->get_first_related(EEM_Line_Item::OBJ_TYPE_TICKET, $query_params);
731
-    }
732
-
733
-
734
-    /**
735
-     * Gets the EE_Datetime that's related to the ticket, IF this is for a ticket
736
-     *
737
-     * @return EE_Datetime | NULL
738
-     * @throws EE_Error
739
-     * @throws InvalidArgumentException
740
-     * @throws InvalidDataTypeException
741
-     * @throws InvalidInterfaceException
742
-     * @throws ReflectionException
743
-     */
744
-    public function get_ticket_datetime()
745
-    {
746
-        if ($this->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET) {
747
-            $ticket = $this->ticket();
748
-            if ($ticket instanceof EE_Ticket) {
749
-                $datetime = $ticket->first_datetime();
750
-                if ($datetime instanceof EE_Datetime) {
751
-                    return $datetime;
752
-                }
753
-            }
754
-        }
755
-        return null;
756
-    }
757
-
758
-
759
-    /**
760
-     * Gets the event's name that's related to the ticket, if this is for
761
-     * a ticket
762
-     *
763
-     * @return string
764
-     * @throws EE_Error
765
-     * @throws InvalidArgumentException
766
-     * @throws InvalidDataTypeException
767
-     * @throws InvalidInterfaceException
768
-     * @throws ReflectionException
769
-     */
770
-    public function ticket_event_name()
771
-    {
772
-        $event_name = esc_html__('Unknown', 'event_espresso');
773
-        $event = $this->ticket_event();
774
-        if ($event instanceof EE_Event) {
775
-            $event_name = $event->name();
776
-        }
777
-        return $event_name;
778
-    }
779
-
780
-
781
-    /**
782
-     * Gets the event that's related to the ticket, if this line item represents a ticket.
783
-     *
784
-     * @return EE_Event|null
785
-     * @throws EE_Error
786
-     * @throws InvalidArgumentException
787
-     * @throws InvalidDataTypeException
788
-     * @throws InvalidInterfaceException
789
-     * @throws ReflectionException
790
-     */
791
-    public function ticket_event()
792
-    {
793
-        $event = null;
794
-        $ticket = $this->ticket();
795
-        if ($ticket instanceof EE_Ticket) {
796
-            $datetime = $ticket->first_datetime();
797
-            if ($datetime instanceof EE_Datetime) {
798
-                $event = $datetime->event();
799
-            }
800
-        }
801
-        return $event;
802
-    }
803
-
804
-
805
-    /**
806
-     * Gets the first datetime for this lien item, assuming it's for a ticket
807
-     *
808
-     * @param string $date_format
809
-     * @param string $time_format
810
-     * @return string
811
-     * @throws EE_Error
812
-     * @throws InvalidArgumentException
813
-     * @throws InvalidDataTypeException
814
-     * @throws InvalidInterfaceException
815
-     * @throws ReflectionException
816
-     */
817
-    public function ticket_datetime_start($date_format = '', $time_format = '')
818
-    {
819
-        $first_datetime_string = esc_html__('Unknown', 'event_espresso');
820
-        $datetime = $this->get_ticket_datetime();
821
-        if ($datetime) {
822
-            $first_datetime_string = $datetime->start_date_and_time($date_format, $time_format);
823
-        }
824
-        return $first_datetime_string;
825
-    }
826
-
827
-
828
-    /**
829
-     * Adds the line item as a child to this line item. If there is another child line
830
-     * item with the same LIN_code, it is overwritten by this new one
831
-     *
832
-     * @param EEI_Line_Item $line_item
833
-     * @param bool          $set_order
834
-     * @return bool success
835
-     * @throws EE_Error
836
-     * @throws InvalidArgumentException
837
-     * @throws InvalidDataTypeException
838
-     * @throws InvalidInterfaceException
839
-     * @throws ReflectionException
840
-     */
841
-    public function add_child_line_item(EEI_Line_Item $line_item, $set_order = true)
842
-    {
843
-        // should we calculate the LIN_order for this line item ?
844
-        if ($set_order || $line_item->order() === null) {
845
-            $line_item->set_order(count($this->children()));
846
-        }
847
-        if ($this->ID()) {
848
-            // check for any duplicate line items (with the same code), if so, this replaces it
849
-            $line_item_with_same_code = $this->get_child_line_item($line_item->code());
850
-            if ($line_item_with_same_code instanceof EE_Line_Item && $line_item_with_same_code !== $line_item) {
851
-                $this->delete_child_line_item($line_item_with_same_code->code());
852
-            }
853
-            $line_item->set_parent_ID($this->ID());
854
-            if ($this->TXN_ID()) {
855
-                $line_item->set_TXN_ID($this->TXN_ID());
856
-            }
857
-            return $line_item->save();
858
-        }
859
-        $this->_children[ $line_item->code() ] = $line_item;
860
-        if ($line_item->parent() !== $this) {
861
-            $line_item->set_parent($this);
862
-        }
863
-        return true;
864
-    }
865
-
866
-
867
-    /**
868
-     * Similar to EE_Base_Class::_add_relation_to, except this isn't a normal relation.
869
-     * If this line item is saved to the DB, this is just a wrapper for set_parent_ID() and save()
870
-     * However, if this line item is NOT saved to the DB, this just caches the parent on
871
-     * the EE_Line_Item::_parent property.
872
-     *
873
-     * @param EE_Line_Item $line_item
874
-     * @throws EE_Error
875
-     * @throws InvalidArgumentException
876
-     * @throws InvalidDataTypeException
877
-     * @throws InvalidInterfaceException
878
-     * @throws ReflectionException
879
-     */
880
-    public function set_parent($line_item)
881
-    {
882
-        if ($this->ID()) {
883
-            if (! $line_item->ID()) {
884
-                $line_item->save();
885
-            }
886
-            $this->set_parent_ID($line_item->ID());
887
-            $this->save();
888
-        } else {
889
-            $this->_parent = $line_item;
890
-            $this->set_parent_ID($line_item->ID());
891
-        }
892
-    }
893
-
894
-
895
-    /**
896
-     * Gets the child line item as specified by its code. Because this returns an object (by reference)
897
-     * you can modify this child line item and the parent (this object) can know about them
898
-     * because it also has a reference to that line item
899
-     *
900
-     * @param string $code
901
-     * @return EE_Base_Class|EE_Line_Item|EE_Soft_Delete_Base_Class|NULL
902
-     * @throws EE_Error
903
-     * @throws InvalidArgumentException
904
-     * @throws InvalidDataTypeException
905
-     * @throws InvalidInterfaceException
906
-     * @throws ReflectionException
907
-     */
908
-    public function get_child_line_item($code)
909
-    {
910
-        if ($this->ID()) {
911
-            return $this->get_model()->get_one(
912
-                array(array('LIN_parent' => $this->ID(), 'LIN_code' => $code))
913
-            );
914
-        }
915
-        return isset($this->_children[ $code ])
916
-            ? $this->_children[ $code ]
917
-            : null;
918
-    }
919
-
920
-
921
-    /**
922
-     * Returns how many items are deleted (or, if this item has not been saved ot the DB yet, just how many it HAD
923
-     * cached on it)
924
-     *
925
-     * @return int
926
-     * @throws EE_Error
927
-     * @throws InvalidArgumentException
928
-     * @throws InvalidDataTypeException
929
-     * @throws InvalidInterfaceException
930
-     * @throws ReflectionException
931
-     */
932
-    public function delete_children_line_items()
933
-    {
934
-        if ($this->ID()) {
935
-            return $this->get_model()->delete(array(array('LIN_parent' => $this->ID())));
936
-        }
937
-        $count = count($this->_children);
938
-        $this->_children = array();
939
-        return $count;
940
-    }
941
-
942
-
943
-    /**
944
-     * If this line item has been saved to the DB, deletes its child with LIN_code == $code. If this line
945
-     * HAS NOT been saved to the DB, removes the child line item with index $code.
946
-     * Also searches through the child's children for a matching line item. However, once a line item has been found
947
-     * and deleted, stops searching (so if there are line items with duplicate codes, only the first one found will be
948
-     * deleted)
949
-     *
950
-     * @param string $code
951
-     * @param bool   $stop_search_once_found
952
-     * @return int count of items deleted (or simply removed from the line item's cache, if not has not been saved to
953
-     *             the DB yet)
954
-     * @throws EE_Error
955
-     * @throws InvalidArgumentException
956
-     * @throws InvalidDataTypeException
957
-     * @throws InvalidInterfaceException
958
-     * @throws ReflectionException
959
-     */
960
-    public function delete_child_line_item($code, $stop_search_once_found = true)
961
-    {
962
-        if ($this->ID()) {
963
-            $items_deleted = 0;
964
-            if ($this->code() === $code) {
965
-                $items_deleted += EEH_Line_Item::delete_all_child_items($this);
966
-                $items_deleted += (int) $this->delete();
967
-                if ($stop_search_once_found) {
968
-                    return $items_deleted;
969
-                }
970
-            }
971
-            foreach ($this->children() as $child_line_item) {
972
-                $items_deleted += $child_line_item->delete_child_line_item($code, $stop_search_once_found);
973
-            }
974
-            return $items_deleted;
975
-        }
976
-        if (isset($this->_children[ $code ])) {
977
-            unset($this->_children[ $code ]);
978
-            return 1;
979
-        }
980
-        return 0;
981
-    }
982
-
983
-
984
-    /**
985
-     * If this line item is in the database, is of the type subtotal, and
986
-     * has no children, why do we have it? It should be deleted so this function
987
-     * does that
988
-     *
989
-     * @return boolean
990
-     * @throws EE_Error
991
-     * @throws InvalidArgumentException
992
-     * @throws InvalidDataTypeException
993
-     * @throws InvalidInterfaceException
994
-     * @throws ReflectionException
995
-     */
996
-    public function delete_if_childless_subtotal()
997
-    {
998
-        if ($this->ID() && $this->type() === EEM_Line_Item::type_sub_total && ! $this->children()) {
999
-            return $this->delete();
1000
-        }
1001
-        return false;
1002
-    }
1003
-
1004
-
1005
-    /**
1006
-     * Creates a code and returns a string. doesn't assign the code to this model object
1007
-     *
1008
-     * @return string
1009
-     * @throws EE_Error
1010
-     * @throws InvalidArgumentException
1011
-     * @throws InvalidDataTypeException
1012
-     * @throws InvalidInterfaceException
1013
-     * @throws ReflectionException
1014
-     */
1015
-    public function generate_code()
1016
-    {
1017
-        // each line item in the cart requires a unique identifier
1018
-        return md5($this->get('OBJ_type') . $this->get('OBJ_ID') . microtime());
1019
-    }
1020
-
1021
-
1022
-    /**
1023
-     * @return bool
1024
-     * @throws EE_Error
1025
-     * @throws InvalidArgumentException
1026
-     * @throws InvalidDataTypeException
1027
-     * @throws InvalidInterfaceException
1028
-     * @throws ReflectionException
1029
-     */
1030
-    public function is_tax()
1031
-    {
1032
-        return $this->type() === EEM_Line_Item::type_tax;
1033
-    }
1034
-
1035
-
1036
-    /**
1037
-     * @return bool
1038
-     * @throws EE_Error
1039
-     * @throws InvalidArgumentException
1040
-     * @throws InvalidDataTypeException
1041
-     * @throws InvalidInterfaceException
1042
-     * @throws ReflectionException
1043
-     */
1044
-    public function is_tax_sub_total()
1045
-    {
1046
-        return $this->type() === EEM_Line_Item::type_tax_sub_total;
1047
-    }
1048
-
1049
-
1050
-    /**
1051
-     * @return bool
1052
-     * @throws EE_Error
1053
-     * @throws InvalidArgumentException
1054
-     * @throws InvalidDataTypeException
1055
-     * @throws InvalidInterfaceException
1056
-     * @throws ReflectionException
1057
-     */
1058
-    public function is_line_item()
1059
-    {
1060
-        return $this->type() === EEM_Line_Item::type_line_item;
1061
-    }
1062
-
1063
-
1064
-    /**
1065
-     * @return bool
1066
-     * @throws EE_Error
1067
-     * @throws InvalidArgumentException
1068
-     * @throws InvalidDataTypeException
1069
-     * @throws InvalidInterfaceException
1070
-     * @throws ReflectionException
1071
-     */
1072
-    public function is_sub_line_item()
1073
-    {
1074
-        return $this->type() === EEM_Line_Item::type_sub_line_item;
1075
-    }
1076
-
1077
-
1078
-    /**
1079
-     * @return bool
1080
-     * @throws EE_Error
1081
-     * @throws InvalidArgumentException
1082
-     * @throws InvalidDataTypeException
1083
-     * @throws InvalidInterfaceException
1084
-     * @throws ReflectionException
1085
-     */
1086
-    public function is_sub_total()
1087
-    {
1088
-        return $this->type() === EEM_Line_Item::type_sub_total;
1089
-    }
1090
-
1091
-
1092
-    /**
1093
-     * Whether or not this line item is a cancellation line item
1094
-     *
1095
-     * @return boolean
1096
-     * @throws EE_Error
1097
-     * @throws InvalidArgumentException
1098
-     * @throws InvalidDataTypeException
1099
-     * @throws InvalidInterfaceException
1100
-     * @throws ReflectionException
1101
-     */
1102
-    public function is_cancellation()
1103
-    {
1104
-        return EEM_Line_Item::type_cancellation === $this->type();
1105
-    }
1106
-
1107
-
1108
-    /**
1109
-     * @return bool
1110
-     * @throws EE_Error
1111
-     * @throws InvalidArgumentException
1112
-     * @throws InvalidDataTypeException
1113
-     * @throws InvalidInterfaceException
1114
-     * @throws ReflectionException
1115
-     */
1116
-    public function is_total()
1117
-    {
1118
-        return $this->type() === EEM_Line_Item::type_total;
1119
-    }
1120
-
1121
-
1122
-    /**
1123
-     * @return bool
1124
-     * @throws EE_Error
1125
-     * @throws InvalidArgumentException
1126
-     * @throws InvalidDataTypeException
1127
-     * @throws InvalidInterfaceException
1128
-     * @throws ReflectionException
1129
-     */
1130
-    public function is_cancelled()
1131
-    {
1132
-        return $this->type() === EEM_Line_Item::type_cancellation;
1133
-    }
1134
-
1135
-
1136
-    /**
1137
-     * @return string like '2, 004.00', formatted according to the localized currency
1138
-     * @throws EE_Error
1139
-     * @throws InvalidArgumentException
1140
-     * @throws InvalidDataTypeException
1141
-     * @throws InvalidInterfaceException
1142
-     * @throws ReflectionException
1143
-     */
1144
-    public function unit_price_no_code()
1145
-    {
1146
-        return $this->get_pretty('LIN_unit_price', 'no_currency_code');
1147
-    }
1148
-
1149
-
1150
-    /**
1151
-     * @return string like '2, 004.00', formatted according to the localized currency
1152
-     * @throws EE_Error
1153
-     * @throws InvalidArgumentException
1154
-     * @throws InvalidDataTypeException
1155
-     * @throws InvalidInterfaceException
1156
-     * @throws ReflectionException
1157
-     */
1158
-    public function total_no_code()
1159
-    {
1160
-        return $this->get_pretty('LIN_total', 'no_currency_code');
1161
-    }
1162
-
1163
-
1164
-    /**
1165
-     * Gets the final total on this item, taking taxes into account.
1166
-     * Has the side-effect of setting the sub-total as it was just calculated.
1167
-     * If this is used on a grand-total line item, also updates the transaction's
1168
-     * TXN_total (provided this line item is allowed to persist, otherwise we don't
1169
-     * want to change a persistable transaction with info from a non-persistent line item)
1170
-     *
1171
-     * @param bool $update_txn_status
1172
-     * @return float
1173
-     * @throws EE_Error
1174
-     * @throws InvalidArgumentException
1175
-     * @throws InvalidDataTypeException
1176
-     * @throws InvalidInterfaceException
1177
-     * @throws ReflectionException
1178
-     * @throws RuntimeException
1179
-     */
1180
-    public function recalculate_total_including_taxes($update_txn_status = false)
1181
-    {
1182
-        $pre_tax_total = $this->recalculate_pre_tax_total();
1183
-        $tax_total = $this->recalculate_taxes_and_tax_total();
1184
-        $total = $pre_tax_total + $tax_total;
1185
-        // no negative totals plz
1186
-        $total = max($total, 0);
1187
-        $this->set_total($total);
1188
-        // only update the related transaction's total
1189
-        // if we intend to save this line item and its a grand total
1190
-        if ($this->allow_persist() && $this->type() === EEM_Line_Item::type_total
1191
-            && $this->transaction()
1192
-               instanceof
1193
-               EE_Transaction
1194
-        ) {
1195
-            $this->transaction()->set_total($total);
1196
-            if ($update_txn_status) {
1197
-                // don't save the TXN because that will be done below
1198
-                // and the following method only saves if the status changes
1199
-                $this->transaction()->update_status_based_on_total_paid(false);
1200
-            }
1201
-            if ($this->transaction()->ID()) {
1202
-                $this->transaction()->save();
1203
-            }
1204
-        }
1205
-        $this->maybe_save();
1206
-        return $total;
1207
-    }
1208
-
1209
-
1210
-    /**
1211
-     * Recursively goes through all the children and recalculates sub-totals EXCEPT for
1212
-     * tax-sub-totals (they're a an odd beast). Updates the 'total' on each line item according to either its
1213
-     * unit price * quantity or the total of all its children EXCEPT when we're only calculating the taxable total and
1214
-     * when this is called on the grand total
1215
-     *
1216
-     * @return float
1217
-     * @throws EE_Error
1218
-     * @throws InvalidArgumentException
1219
-     * @throws InvalidDataTypeException
1220
-     * @throws InvalidInterfaceException
1221
-     * @throws ReflectionException
1222
-     */
1223
-    public function recalculate_pre_tax_total()
1224
-    {
1225
-        $total = 0;
1226
-        $my_children = $this->children();
1227
-        $has_children = ! empty($my_children);
1228
-        if ($has_children && $this->is_line_item()) {
1229
-            $total = $this->_recalculate_pretax_total_for_line_item($total, $my_children);
1230
-        } elseif (! $has_children && ($this->is_sub_line_item() || $this->is_line_item())) {
1231
-            $total = $this->unit_price() * $this->quantity();
1232
-        } elseif ($this->is_sub_total() || $this->is_total()) {
1233
-            $total = $this->_recalculate_pretax_total_for_subtotal($total, $my_children);
1234
-        } elseif ($this->is_tax_sub_total() || $this->is_tax() || $this->is_cancelled()) {
1235
-            // completely ignore tax totals, tax sub-totals, and cancelled line items, when calculating the pre-tax-total
1236
-            return 0;
1237
-        }
1238
-        // ensure all non-line items and non-sub-line-items have a quantity of 1 (except for Events)
1239
-        if (! $this->is_line_item() && ! $this->is_sub_line_item() && ! $this->is_cancellation()
1240
-        ) {
1241
-            if ($this->OBJ_type() !== EEM_Line_Item::OBJ_TYPE_EVENT) {
1242
-                $this->set_quantity(1);
1243
-            }
1244
-            if (! $this->is_percent()) {
1245
-                $this->set_unit_price($total);
1246
-            }
1247
-        }
1248
-        // we don't want to bother saving grand totals, because that needs to factor in taxes anyways
1249
-        // so it ought to be
1250
-        if (! $this->is_total()) {
1251
-            $this->set_total($total);
1252
-            // if not a percent line item, make sure we keep the unit price in sync
1253
-            if ($has_children
1254
-                && $this->is_line_item()
1255
-                && ! $this->is_percent()
1256
-            ) {
1257
-                if ($this->quantity() === 0) {
1258
-                    $new_unit_price = 0;
1259
-                } else {
1260
-                    $new_unit_price = $this->total() / $this->quantity();
1261
-                }
1262
-                $this->set_unit_price($new_unit_price);
1263
-            }
1264
-            $this->maybe_save();
1265
-        }
1266
-        return $total;
1267
-    }
1268
-
1269
-
1270
-    /**
1271
-     * Calculates the pretax total when this line item is a subtotal or total line item.
1272
-     * Basically does a sum-then-round approach (ie, any percent line item that are children
1273
-     * will calculate their total based on the un-rounded total we're working with so far, and
1274
-     * THEN round the result; instead of rounding as we go like with sub-line-items)
1275
-     *
1276
-     * @param float          $calculated_total_so_far
1277
-     * @param EE_Line_Item[] $my_children
1278
-     * @return float
1279
-     * @throws EE_Error
1280
-     * @throws InvalidArgumentException
1281
-     * @throws InvalidDataTypeException
1282
-     * @throws InvalidInterfaceException
1283
-     * @throws ReflectionException
1284
-     */
1285
-    protected function _recalculate_pretax_total_for_subtotal($calculated_total_so_far, $my_children = null)
1286
-    {
1287
-        if ($my_children === null) {
1288
-            $my_children = $this->children();
1289
-        }
1290
-        $subtotal_quantity = 0;
1291
-        // get the total of all its children
1292
-        foreach ($my_children as $child_line_item) {
1293
-            if ($child_line_item instanceof EE_Line_Item && ! $child_line_item->is_cancellation()) {
1294
-                // percentage line items are based on total so far
1295
-                if ($child_line_item->is_percent()) {
1296
-                    // round as we go so that the line items add up ok
1297
-                    $percent_total = round(
1298
-                        $calculated_total_so_far * $child_line_item->percent() / 100,
1299
-                        EE_Registry::instance()->CFG->currency->dec_plc
1300
-                    );
1301
-                    $child_line_item->set_total($percent_total);
1302
-                    // so far all percent line items should have a quantity of 1
1303
-                    // (ie, no double percent discounts. Although that might be requested someday)
1304
-                    $child_line_item->set_quantity(1);
1305
-                    $child_line_item->maybe_save();
1306
-                    $calculated_total_so_far += $percent_total;
1307
-                } else {
1308
-                    // verify flat sub-line-item quantities match their parent
1309
-                    if ($child_line_item->is_sub_line_item()) {
1310
-                        $child_line_item->set_quantity($this->quantity());
1311
-                    }
1312
-                    $calculated_total_so_far += $child_line_item->recalculate_pre_tax_total();
1313
-                    $subtotal_quantity += $child_line_item->quantity();
1314
-                }
1315
-            }
1316
-        }
1317
-        if ($this->is_sub_total()) {
1318
-            // no negative totals plz
1319
-            $calculated_total_so_far = max($calculated_total_so_far, 0);
1320
-            $subtotal_quantity = $subtotal_quantity > 0 ? 1 : 0;
1321
-            $this->set_quantity($subtotal_quantity);
1322
-            $this->maybe_save();
1323
-        }
1324
-        return $calculated_total_so_far;
1325
-    }
1326
-
1327
-
1328
-    /**
1329
-     * Calculates the pretax total for a normal line item, in a round-then-sum approach
1330
-     * (where each sub-line-item is applied to the base price for the line item
1331
-     * and the result is immediately rounded, rather than summing all the sub-line-items
1332
-     * then rounding, like we do when recalculating pretax totals on totals and subtotals).
1333
-     *
1334
-     * @param float          $calculated_total_so_far
1335
-     * @param EE_Line_Item[] $my_children
1336
-     * @return float
1337
-     * @throws EE_Error
1338
-     * @throws InvalidArgumentException
1339
-     * @throws InvalidDataTypeException
1340
-     * @throws InvalidInterfaceException
1341
-     * @throws ReflectionException
1342
-     */
1343
-    protected function _recalculate_pretax_total_for_line_item($calculated_total_so_far, $my_children = null)
1344
-    {
1345
-        if ($my_children === null) {
1346
-            $my_children = $this->children();
1347
-        }
1348
-        // we need to keep track of the running total for a single item,
1349
-        // because we need to round as we go
1350
-        $unit_price_for_total = 0;
1351
-        $quantity_for_total = 1;
1352
-        // get the total of all its children
1353
-        foreach ($my_children as $child_line_item) {
1354
-            if ($child_line_item instanceof EE_Line_Item && ! $child_line_item->is_cancellation()) {
1355
-                if ($child_line_item->is_percent()) {
1356
-                    // it should be the unit-price-so-far multiplied by teh percent multiplied by the quantity
1357
-                    // not total multiplied by percent, because that ignores rounding along-the-way
1358
-                    $percent_unit_price = round(
1359
-                        $unit_price_for_total * $child_line_item->percent() / 100,
1360
-                        EE_Registry::instance()->CFG->currency->dec_plc
1361
-                    );
1362
-                    $percent_total = $percent_unit_price * $quantity_for_total;
1363
-                    $child_line_item->set_total($percent_total);
1364
-                    // so far all percent line items should have a quantity of 1
1365
-                    // (ie, no double percent discounts. Although that might be requested someday)
1366
-                    $child_line_item->set_quantity(1);
1367
-                    $child_line_item->maybe_save();
1368
-                    $calculated_total_so_far += $percent_total;
1369
-                    $unit_price_for_total += $percent_unit_price;
1370
-                } else {
1371
-                    // verify flat sub-line-item quantities match their parent
1372
-                    if ($child_line_item->is_sub_line_item()) {
1373
-                        $child_line_item->set_quantity($this->quantity());
1374
-                    }
1375
-                    $quantity_for_total = $child_line_item->quantity();
1376
-                    $calculated_total_so_far += $child_line_item->recalculate_pre_tax_total();
1377
-                    $unit_price_for_total += $child_line_item->unit_price();
1378
-                }
1379
-            }
1380
-        }
1381
-        return $calculated_total_so_far;
1382
-    }
1383
-
1384
-
1385
-    /**
1386
-     * Recalculates the total on each individual tax (based on a recalculation of the pre-tax total), sets
1387
-     * the totals on each tax calculated, and returns the final tax total. Re-saves tax line items
1388
-     * and tax sub-total if already in the DB
1389
-     *
1390
-     * @return float
1391
-     * @throws EE_Error
1392
-     * @throws InvalidArgumentException
1393
-     * @throws InvalidDataTypeException
1394
-     * @throws InvalidInterfaceException
1395
-     * @throws ReflectionException
1396
-     */
1397
-    public function recalculate_taxes_and_tax_total()
1398
-    {
1399
-        // get all taxes
1400
-        $taxes = $this->tax_descendants();
1401
-        // calculate the pretax total
1402
-        $taxable_total = $this->taxable_total();
1403
-        $tax_total = 0;
1404
-        foreach ($taxes as $tax) {
1405
-            $total_on_this_tax = $taxable_total * $tax->percent() / 100;
1406
-            // remember the total on this line item
1407
-            $tax->set_total($total_on_this_tax);
1408
-            $tax->maybe_save();
1409
-            $tax_total += $tax->total();
1410
-        }
1411
-        $this->_recalculate_tax_sub_total();
1412
-        return $tax_total;
1413
-    }
1414
-
1415
-
1416
-    /**
1417
-     * Simply forces all the tax-sub-totals to recalculate. Assumes the taxes have been calculated
1418
-     *
1419
-     * @return void
1420
-     * @throws EE_Error
1421
-     * @throws InvalidArgumentException
1422
-     * @throws InvalidDataTypeException
1423
-     * @throws InvalidInterfaceException
1424
-     * @throws ReflectionException
1425
-     */
1426
-    private function _recalculate_tax_sub_total()
1427
-    {
1428
-        if ($this->is_tax_sub_total()) {
1429
-            $total = 0;
1430
-            $total_percent = 0;
1431
-            // simply loop through all its children (which should be taxes) and sum their total
1432
-            foreach ($this->children() as $child_tax) {
1433
-                if ($child_tax instanceof EE_Line_Item) {
1434
-                    $total += $child_tax->total();
1435
-                    $total_percent += $child_tax->percent();
1436
-                }
1437
-            }
1438
-            $this->set_total($total);
1439
-            $this->set_percent($total_percent);
1440
-            $this->maybe_save();
1441
-        } elseif ($this->is_total()) {
1442
-            foreach ($this->children() as $maybe_tax_subtotal) {
1443
-                if ($maybe_tax_subtotal instanceof EE_Line_Item) {
1444
-                    $maybe_tax_subtotal->_recalculate_tax_sub_total();
1445
-                }
1446
-            }
1447
-        }
1448
-    }
1449
-
1450
-
1451
-    /**
1452
-     * Gets the total tax on this line item. Assumes taxes have already been calculated using
1453
-     * recalculate_taxes_and_total
1454
-     *
1455
-     * @return float
1456
-     * @throws EE_Error
1457
-     * @throws InvalidArgumentException
1458
-     * @throws InvalidDataTypeException
1459
-     * @throws InvalidInterfaceException
1460
-     * @throws ReflectionException
1461
-     */
1462
-    public function get_total_tax()
1463
-    {
1464
-        $this->_recalculate_tax_sub_total();
1465
-        $total = 0;
1466
-        foreach ($this->tax_descendants() as $tax_line_item) {
1467
-            if ($tax_line_item instanceof EE_Line_Item) {
1468
-                $total += $tax_line_item->total();
1469
-            }
1470
-        }
1471
-        return $total;
1472
-    }
1473
-
1474
-
1475
-    /**
1476
-     * Gets the total for all the items purchased only
1477
-     *
1478
-     * @return float
1479
-     * @throws EE_Error
1480
-     * @throws InvalidArgumentException
1481
-     * @throws InvalidDataTypeException
1482
-     * @throws InvalidInterfaceException
1483
-     * @throws ReflectionException
1484
-     */
1485
-    public function get_items_total()
1486
-    {
1487
-        // by default, let's make sure we're consistent with the existing line item
1488
-        if ($this->is_total()) {
1489
-            $pretax_subtotal_li = EEH_Line_Item::get_pre_tax_subtotal($this);
1490
-            if ($pretax_subtotal_li instanceof EE_Line_Item) {
1491
-                return $pretax_subtotal_li->total();
1492
-            }
1493
-        }
1494
-        $total = 0;
1495
-        foreach ($this->get_items() as $item) {
1496
-            if ($item instanceof EE_Line_Item) {
1497
-                $total += $item->total();
1498
-            }
1499
-        }
1500
-        return $total;
1501
-    }
1502
-
1503
-
1504
-    /**
1505
-     * Gets all the descendants (ie, children or children of children etc) that
1506
-     * are of the type 'tax'
1507
-     *
1508
-     * @return EE_Line_Item[]
1509
-     * @throws EE_Error
1510
-     */
1511
-    public function tax_descendants()
1512
-    {
1513
-        return EEH_Line_Item::get_tax_descendants($this);
1514
-    }
1515
-
1516
-
1517
-    /**
1518
-     * Gets all the real items purchased which are children of this item
1519
-     *
1520
-     * @return EE_Line_Item[]
1521
-     * @throws EE_Error
1522
-     */
1523
-    public function get_items()
1524
-    {
1525
-        return EEH_Line_Item::get_line_item_descendants($this);
1526
-    }
1527
-
1528
-
1529
-    /**
1530
-     * Returns the amount taxable among this line item's children (or if it has no children,
1531
-     * how much of it is taxable). Does not recalculate totals or subtotals.
1532
-     * If the taxable total is negative, (eg, if none of the tickets were taxable,
1533
-     * but there is a "Taxable" discount), returns 0.
1534
-     *
1535
-     * @return float
1536
-     * @throws EE_Error
1537
-     * @throws InvalidArgumentException
1538
-     * @throws InvalidDataTypeException
1539
-     * @throws InvalidInterfaceException
1540
-     * @throws ReflectionException
1541
-     */
1542
-    public function taxable_total()
1543
-    {
1544
-        $total = 0;
1545
-        if ($this->children()) {
1546
-            foreach ($this->children() as $child_line_item) {
1547
-                if ($child_line_item->type() === EEM_Line_Item::type_line_item && $child_line_item->is_taxable()) {
1548
-                    // if it's a percent item, only take into account the percent
1549
-                    // that's taxable too (the taxable total so far)
1550
-                    if ($child_line_item->is_percent()) {
1551
-                        $total += ($total * $child_line_item->percent() / 100);
1552
-                    } else {
1553
-                        $total += $child_line_item->total();
1554
-                    }
1555
-                } elseif ($child_line_item->type() === EEM_Line_Item::type_sub_total) {
1556
-                    $total += $child_line_item->taxable_total();
1557
-                }
1558
-            }
1559
-        }
1560
-        return max($total, 0);
1561
-    }
1562
-
1563
-
1564
-    /**
1565
-     * Gets the transaction for this line item
1566
-     *
1567
-     * @return EE_Base_Class|EE_Transaction
1568
-     * @throws EE_Error
1569
-     * @throws InvalidArgumentException
1570
-     * @throws InvalidDataTypeException
1571
-     * @throws InvalidInterfaceException
1572
-     * @throws ReflectionException
1573
-     */
1574
-    public function transaction()
1575
-    {
1576
-        return $this->get_first_related(EEM_Line_Item::OBJ_TYPE_TRANSACTION);
1577
-    }
1578
-
1579
-
1580
-    /**
1581
-     * Saves this line item to the DB, and recursively saves its descendants.
1582
-     * Because there currently is no proper parent-child relation on the model,
1583
-     * save_this_and_cached() will NOT save the descendants.
1584
-     * Also sets the transaction on this line item and all its descendants before saving
1585
-     *
1586
-     * @param int $txn_id if none is provided, assumes $this->TXN_ID()
1587
-     * @return int count of items saved
1588
-     * @throws EE_Error
1589
-     * @throws InvalidArgumentException
1590
-     * @throws InvalidDataTypeException
1591
-     * @throws InvalidInterfaceException
1592
-     * @throws ReflectionException
1593
-     */
1594
-    public function save_this_and_descendants_to_txn($txn_id = null)
1595
-    {
1596
-        $count = 0;
1597
-        if (! $txn_id) {
1598
-            $txn_id = $this->TXN_ID();
1599
-        }
1600
-        $this->set_TXN_ID($txn_id);
1601
-        $children = $this->children();
1602
-        $count += $this->save()
1603
-            ? 1
1604
-            : 0;
1605
-        foreach ($children as $child_line_item) {
1606
-            if ($child_line_item instanceof EE_Line_Item) {
1607
-                $child_line_item->set_parent_ID($this->ID());
1608
-                $count += $child_line_item->save_this_and_descendants_to_txn($txn_id);
1609
-            }
1610
-        }
1611
-        return $count;
1612
-    }
1613
-
1614
-
1615
-    /**
1616
-     * Saves this line item to the DB, and recursively saves its descendants.
1617
-     *
1618
-     * @return int count of items saved
1619
-     * @throws EE_Error
1620
-     * @throws InvalidArgumentException
1621
-     * @throws InvalidDataTypeException
1622
-     * @throws InvalidInterfaceException
1623
-     * @throws ReflectionException
1624
-     */
1625
-    public function save_this_and_descendants()
1626
-    {
1627
-        $count = 0;
1628
-        $children = $this->children();
1629
-        $count += $this->save()
1630
-            ? 1
1631
-            : 0;
1632
-        foreach ($children as $child_line_item) {
1633
-            if ($child_line_item instanceof EE_Line_Item) {
1634
-                $child_line_item->set_parent_ID($this->ID());
1635
-                $count += $child_line_item->save_this_and_descendants();
1636
-            }
1637
-        }
1638
-        return $count;
1639
-    }
1640
-
1641
-
1642
-    /**
1643
-     * returns the cancellation line item if this item was cancelled
1644
-     *
1645
-     * @return EE_Line_Item[]
1646
-     * @throws InvalidArgumentException
1647
-     * @throws InvalidInterfaceException
1648
-     * @throws InvalidDataTypeException
1649
-     * @throws ReflectionException
1650
-     * @throws EE_Error
1651
-     */
1652
-    public function get_cancellations()
1653
-    {
1654
-        EE_Registry::instance()->load_helper('Line_Item');
1655
-        return EEH_Line_Item::get_descendants_of_type($this, EEM_Line_Item::type_cancellation);
1656
-    }
1657
-
1658
-
1659
-    /**
1660
-     * If this item has an ID, then this saves it again to update the db
1661
-     *
1662
-     * @return int count of items saved
1663
-     * @throws EE_Error
1664
-     * @throws InvalidArgumentException
1665
-     * @throws InvalidDataTypeException
1666
-     * @throws InvalidInterfaceException
1667
-     * @throws ReflectionException
1668
-     */
1669
-    public function maybe_save()
1670
-    {
1671
-        if ($this->ID()) {
1672
-            return $this->save();
1673
-        }
1674
-        return false;
1675
-    }
1676
-
1677
-
1678
-    /**
1679
-     * clears the cached children and parent from the line item
1680
-     *
1681
-     * @return void
1682
-     */
1683
-    public function clear_related_line_item_cache()
1684
-    {
1685
-        $this->_children = array();
1686
-        $this->_parent = null;
1687
-    }
1688
-
1689
-
1690
-    /**
1691
-     * @param bool $raw
1692
-     * @return int
1693
-     * @throws EE_Error
1694
-     * @throws InvalidArgumentException
1695
-     * @throws InvalidDataTypeException
1696
-     * @throws InvalidInterfaceException
1697
-     * @throws ReflectionException
1698
-     */
1699
-    public function timestamp($raw = false)
1700
-    {
1701
-        return $raw
1702
-            ? $this->get_raw('LIN_timestamp')
1703
-            : $this->get('LIN_timestamp');
1704
-    }
1705
-
1706
-
1707
-
1708
-
1709
-    /************************* DEPRECATED *************************/
1710
-    /**
1711
-     * @deprecated 4.6.0
1712
-     * @param string $type one of the constants on EEM_Line_Item
1713
-     * @return EE_Line_Item[]
1714
-     * @throws EE_Error
1715
-     */
1716
-    protected function _get_descendants_of_type($type)
1717
-    {
1718
-        EE_Error::doing_it_wrong(
1719
-            'EE_Line_Item::_get_descendants_of_type()',
1720
-            sprintf(
1721
-                esc_html__('Method replaced with %1$s', 'event_espresso'),
1722
-                'EEH_Line_Item::get_descendants_of_type()'
1723
-            ),
1724
-            '4.6.0'
1725
-        );
1726
-        return EEH_Line_Item::get_descendants_of_type($this, $type);
1727
-    }
1728
-
1729
-
1730
-    /**
1731
-     * @deprecated 4.6.0
1732
-     * @param string $type like one of the EEM_Line_Item::type_*
1733
-     * @return EE_Line_Item
1734
-     * @throws EE_Error
1735
-     * @throws InvalidArgumentException
1736
-     * @throws InvalidDataTypeException
1737
-     * @throws InvalidInterfaceException
1738
-     * @throws ReflectionException
1739
-     */
1740
-    public function get_nearest_descendant_of_type($type)
1741
-    {
1742
-        EE_Error::doing_it_wrong(
1743
-            'EE_Line_Item::get_nearest_descendant_of_type()',
1744
-            sprintf(
1745
-                esc_html__('Method replaced with %1$s', 'event_espresso'),
1746
-                'EEH_Line_Item::get_nearest_descendant_of_type()'
1747
-            ),
1748
-            '4.6.0'
1749
-        );
1750
-        return EEH_Line_Item::get_nearest_descendant_of_type($this, $type);
1751
-    }
17
+	/**
18
+	 * for children line items (currently not a normal relation)
19
+	 *
20
+	 * @type EE_Line_Item[]
21
+	 */
22
+	protected $_children = array();
23
+
24
+	/**
25
+	 * for the parent line item
26
+	 *
27
+	 * @var EE_Line_Item
28
+	 */
29
+	protected $_parent;
30
+
31
+
32
+	/**
33
+	 * @param array  $props_n_values          incoming values
34
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
35
+	 *                                        used.)
36
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
37
+	 *                                        date_format and the second value is the time format
38
+	 * @return EE_Line_Item
39
+	 * @throws EE_Error
40
+	 * @throws InvalidArgumentException
41
+	 * @throws InvalidDataTypeException
42
+	 * @throws InvalidInterfaceException
43
+	 * @throws ReflectionException
44
+	 */
45
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
46
+	{
47
+		$has_object = parent::_check_for_object(
48
+			$props_n_values,
49
+			__CLASS__,
50
+			$timezone,
51
+			$date_formats
52
+		);
53
+		return $has_object
54
+			? $has_object
55
+			: new self($props_n_values, false, $timezone);
56
+	}
57
+
58
+
59
+	/**
60
+	 * @param array  $props_n_values  incoming values from the database
61
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
62
+	 *                                the website will be used.
63
+	 * @return EE_Line_Item
64
+	 * @throws EE_Error
65
+	 * @throws InvalidArgumentException
66
+	 * @throws InvalidDataTypeException
67
+	 * @throws InvalidInterfaceException
68
+	 * @throws ReflectionException
69
+	 */
70
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
71
+	{
72
+		return new self($props_n_values, true, $timezone);
73
+	}
74
+
75
+
76
+	/**
77
+	 * Adds some defaults if they're not specified
78
+	 *
79
+	 * @param array  $fieldValues
80
+	 * @param bool   $bydb
81
+	 * @param string $timezone
82
+	 * @throws EE_Error
83
+	 * @throws InvalidArgumentException
84
+	 * @throws InvalidDataTypeException
85
+	 * @throws InvalidInterfaceException
86
+	 * @throws ReflectionException
87
+	 */
88
+	protected function __construct($fieldValues = array(), $bydb = false, $timezone = '')
89
+	{
90
+		parent::__construct($fieldValues, $bydb, $timezone);
91
+		if (! $this->get('LIN_code')) {
92
+			$this->set_code($this->generate_code());
93
+		}
94
+	}
95
+
96
+
97
+	/**
98
+	 * Gets ID
99
+	 *
100
+	 * @return int
101
+	 * @throws EE_Error
102
+	 * @throws InvalidArgumentException
103
+	 * @throws InvalidDataTypeException
104
+	 * @throws InvalidInterfaceException
105
+	 * @throws ReflectionException
106
+	 */
107
+	public function ID()
108
+	{
109
+		return $this->get('LIN_ID');
110
+	}
111
+
112
+
113
+	/**
114
+	 * Gets TXN_ID
115
+	 *
116
+	 * @return int
117
+	 * @throws EE_Error
118
+	 * @throws InvalidArgumentException
119
+	 * @throws InvalidDataTypeException
120
+	 * @throws InvalidInterfaceException
121
+	 * @throws ReflectionException
122
+	 */
123
+	public function TXN_ID()
124
+	{
125
+		return $this->get('TXN_ID');
126
+	}
127
+
128
+
129
+	/**
130
+	 * Sets TXN_ID
131
+	 *
132
+	 * @param int $TXN_ID
133
+	 * @throws EE_Error
134
+	 * @throws InvalidArgumentException
135
+	 * @throws InvalidDataTypeException
136
+	 * @throws InvalidInterfaceException
137
+	 * @throws ReflectionException
138
+	 */
139
+	public function set_TXN_ID($TXN_ID)
140
+	{
141
+		$this->set('TXN_ID', $TXN_ID);
142
+	}
143
+
144
+
145
+	/**
146
+	 * Gets name
147
+	 *
148
+	 * @return string
149
+	 * @throws EE_Error
150
+	 * @throws InvalidArgumentException
151
+	 * @throws InvalidDataTypeException
152
+	 * @throws InvalidInterfaceException
153
+	 * @throws ReflectionException
154
+	 */
155
+	public function name()
156
+	{
157
+		$name = $this->get('LIN_name');
158
+		if (! $name) {
159
+			$name = ucwords(str_replace('-', ' ', $this->type()));
160
+		}
161
+		return $name;
162
+	}
163
+
164
+
165
+	/**
166
+	 * Sets name
167
+	 *
168
+	 * @param string $name
169
+	 * @throws EE_Error
170
+	 * @throws InvalidArgumentException
171
+	 * @throws InvalidDataTypeException
172
+	 * @throws InvalidInterfaceException
173
+	 * @throws ReflectionException
174
+	 */
175
+	public function set_name($name)
176
+	{
177
+		$this->set('LIN_name', $name);
178
+	}
179
+
180
+
181
+	/**
182
+	 * Gets desc
183
+	 *
184
+	 * @return string
185
+	 * @throws EE_Error
186
+	 * @throws InvalidArgumentException
187
+	 * @throws InvalidDataTypeException
188
+	 * @throws InvalidInterfaceException
189
+	 * @throws ReflectionException
190
+	 */
191
+	public function desc()
192
+	{
193
+		return $this->get('LIN_desc');
194
+	}
195
+
196
+
197
+	/**
198
+	 * Sets desc
199
+	 *
200
+	 * @param string $desc
201
+	 * @throws EE_Error
202
+	 * @throws InvalidArgumentException
203
+	 * @throws InvalidDataTypeException
204
+	 * @throws InvalidInterfaceException
205
+	 * @throws ReflectionException
206
+	 */
207
+	public function set_desc($desc)
208
+	{
209
+		$this->set('LIN_desc', $desc);
210
+	}
211
+
212
+
213
+	/**
214
+	 * Gets quantity
215
+	 *
216
+	 * @return int
217
+	 * @throws EE_Error
218
+	 * @throws InvalidArgumentException
219
+	 * @throws InvalidDataTypeException
220
+	 * @throws InvalidInterfaceException
221
+	 * @throws ReflectionException
222
+	 */
223
+	public function quantity()
224
+	{
225
+		return $this->get('LIN_quantity');
226
+	}
227
+
228
+
229
+	/**
230
+	 * Sets quantity
231
+	 *
232
+	 * @param int $quantity
233
+	 * @throws EE_Error
234
+	 * @throws InvalidArgumentException
235
+	 * @throws InvalidDataTypeException
236
+	 * @throws InvalidInterfaceException
237
+	 * @throws ReflectionException
238
+	 */
239
+	public function set_quantity($quantity)
240
+	{
241
+		$this->set('LIN_quantity', max($quantity, 0));
242
+	}
243
+
244
+
245
+	/**
246
+	 * Gets item_id
247
+	 *
248
+	 * @return string
249
+	 * @throws EE_Error
250
+	 * @throws InvalidArgumentException
251
+	 * @throws InvalidDataTypeException
252
+	 * @throws InvalidInterfaceException
253
+	 * @throws ReflectionException
254
+	 */
255
+	public function OBJ_ID()
256
+	{
257
+		return $this->get('OBJ_ID');
258
+	}
259
+
260
+
261
+	/**
262
+	 * Sets item_id
263
+	 *
264
+	 * @param string $item_id
265
+	 * @throws EE_Error
266
+	 * @throws InvalidArgumentException
267
+	 * @throws InvalidDataTypeException
268
+	 * @throws InvalidInterfaceException
269
+	 * @throws ReflectionException
270
+	 */
271
+	public function set_OBJ_ID($item_id)
272
+	{
273
+		$this->set('OBJ_ID', $item_id);
274
+	}
275
+
276
+
277
+	/**
278
+	 * Gets item_type
279
+	 *
280
+	 * @return string
281
+	 * @throws EE_Error
282
+	 * @throws InvalidArgumentException
283
+	 * @throws InvalidDataTypeException
284
+	 * @throws InvalidInterfaceException
285
+	 * @throws ReflectionException
286
+	 */
287
+	public function OBJ_type()
288
+	{
289
+		return $this->get('OBJ_type');
290
+	}
291
+
292
+
293
+	/**
294
+	 * Gets item_type
295
+	 *
296
+	 * @return string
297
+	 * @throws EE_Error
298
+	 * @throws InvalidArgumentException
299
+	 * @throws InvalidDataTypeException
300
+	 * @throws InvalidInterfaceException
301
+	 * @throws ReflectionException
302
+	 */
303
+	public function OBJ_type_i18n()
304
+	{
305
+		$obj_type = $this->OBJ_type();
306
+		switch ($obj_type) {
307
+			case EEM_Line_Item::OBJ_TYPE_EVENT:
308
+				$obj_type = esc_html__('Event', 'event_espresso');
309
+				break;
310
+			case EEM_Line_Item::OBJ_TYPE_PRICE:
311
+				$obj_type = esc_html__('Price', 'event_espresso');
312
+				break;
313
+			case EEM_Line_Item::OBJ_TYPE_PROMOTION:
314
+				$obj_type = esc_html__('Promotion', 'event_espresso');
315
+				break;
316
+			case EEM_Line_Item::OBJ_TYPE_TICKET:
317
+				$obj_type = esc_html__('Ticket', 'event_espresso');
318
+				break;
319
+			case EEM_Line_Item::OBJ_TYPE_TRANSACTION:
320
+				$obj_type = esc_html__('Transaction', 'event_espresso');
321
+				break;
322
+		}
323
+		return apply_filters('FHEE__EE_Line_Item__OBJ_type_i18n', $obj_type, $this);
324
+	}
325
+
326
+
327
+	/**
328
+	 * Sets item_type
329
+	 *
330
+	 * @param string $OBJ_type
331
+	 * @throws EE_Error
332
+	 * @throws InvalidArgumentException
333
+	 * @throws InvalidDataTypeException
334
+	 * @throws InvalidInterfaceException
335
+	 * @throws ReflectionException
336
+	 */
337
+	public function set_OBJ_type($OBJ_type)
338
+	{
339
+		$this->set('OBJ_type', $OBJ_type);
340
+	}
341
+
342
+
343
+	/**
344
+	 * Gets unit_price
345
+	 *
346
+	 * @return float
347
+	 * @throws EE_Error
348
+	 * @throws InvalidArgumentException
349
+	 * @throws InvalidDataTypeException
350
+	 * @throws InvalidInterfaceException
351
+	 * @throws ReflectionException
352
+	 */
353
+	public function unit_price()
354
+	{
355
+		return $this->get('LIN_unit_price');
356
+	}
357
+
358
+
359
+	/**
360
+	 * Sets unit_price
361
+	 *
362
+	 * @param float $unit_price
363
+	 * @throws EE_Error
364
+	 * @throws InvalidArgumentException
365
+	 * @throws InvalidDataTypeException
366
+	 * @throws InvalidInterfaceException
367
+	 * @throws ReflectionException
368
+	 */
369
+	public function set_unit_price($unit_price)
370
+	{
371
+		$this->set('LIN_unit_price', $unit_price);
372
+	}
373
+
374
+
375
+	/**
376
+	 * Checks if this item is a percentage modifier or not
377
+	 *
378
+	 * @return boolean
379
+	 * @throws EE_Error
380
+	 * @throws InvalidArgumentException
381
+	 * @throws InvalidDataTypeException
382
+	 * @throws InvalidInterfaceException
383
+	 * @throws ReflectionException
384
+	 */
385
+	public function is_percent()
386
+	{
387
+		if ($this->is_tax_sub_total()) {
388
+			// tax subtotals HAVE a percent on them, that percentage only applies
389
+			// to taxable items, so its' an exception. Treat it like a flat line item
390
+			return false;
391
+		}
392
+		$unit_price = abs($this->get('LIN_unit_price'));
393
+		$percent = abs($this->get('LIN_percent'));
394
+		if ($unit_price < .001 && $percent) {
395
+			return true;
396
+		}
397
+		if ($unit_price >= .001 && ! $percent) {
398
+			return false;
399
+		}
400
+		if ($unit_price >= .001 && $percent) {
401
+			throw new EE_Error(
402
+				sprintf(
403
+					esc_html__(
404
+						'A Line Item can not have a unit price of (%s) AND a percent (%s)!',
405
+						'event_espresso'
406
+					),
407
+					$unit_price,
408
+					$percent
409
+				)
410
+			);
411
+		}
412
+		// if they're both 0, assume its not a percent item
413
+		return false;
414
+	}
415
+
416
+
417
+	/**
418
+	 * Gets percent (between 100-.001)
419
+	 *
420
+	 * @return float
421
+	 * @throws EE_Error
422
+	 * @throws InvalidArgumentException
423
+	 * @throws InvalidDataTypeException
424
+	 * @throws InvalidInterfaceException
425
+	 * @throws ReflectionException
426
+	 */
427
+	public function percent()
428
+	{
429
+		return $this->get('LIN_percent');
430
+	}
431
+
432
+
433
+	/**
434
+	 * Sets percent (between 100-0.01)
435
+	 *
436
+	 * @param float $percent
437
+	 * @throws EE_Error
438
+	 * @throws InvalidArgumentException
439
+	 * @throws InvalidDataTypeException
440
+	 * @throws InvalidInterfaceException
441
+	 * @throws ReflectionException
442
+	 */
443
+	public function set_percent($percent)
444
+	{
445
+		$this->set('LIN_percent', $percent);
446
+	}
447
+
448
+
449
+	/**
450
+	 * Gets total
451
+	 *
452
+	 * @return float
453
+	 * @throws EE_Error
454
+	 * @throws InvalidArgumentException
455
+	 * @throws InvalidDataTypeException
456
+	 * @throws InvalidInterfaceException
457
+	 * @throws ReflectionException
458
+	 */
459
+	public function total()
460
+	{
461
+		return $this->get('LIN_total');
462
+	}
463
+
464
+
465
+	/**
466
+	 * Sets total
467
+	 *
468
+	 * @param float $total
469
+	 * @throws EE_Error
470
+	 * @throws InvalidArgumentException
471
+	 * @throws InvalidDataTypeException
472
+	 * @throws InvalidInterfaceException
473
+	 * @throws ReflectionException
474
+	 */
475
+	public function set_total($total)
476
+	{
477
+		$this->set('LIN_total', $total);
478
+	}
479
+
480
+
481
+	/**
482
+	 * Gets order
483
+	 *
484
+	 * @return int
485
+	 * @throws EE_Error
486
+	 * @throws InvalidArgumentException
487
+	 * @throws InvalidDataTypeException
488
+	 * @throws InvalidInterfaceException
489
+	 * @throws ReflectionException
490
+	 */
491
+	public function order()
492
+	{
493
+		return $this->get('LIN_order');
494
+	}
495
+
496
+
497
+	/**
498
+	 * Sets order
499
+	 *
500
+	 * @param int $order
501
+	 * @throws EE_Error
502
+	 * @throws InvalidArgumentException
503
+	 * @throws InvalidDataTypeException
504
+	 * @throws InvalidInterfaceException
505
+	 * @throws ReflectionException
506
+	 */
507
+	public function set_order($order)
508
+	{
509
+		$this->set('LIN_order', $order);
510
+	}
511
+
512
+
513
+	/**
514
+	 * Gets parent
515
+	 *
516
+	 * @return int
517
+	 * @throws EE_Error
518
+	 * @throws InvalidArgumentException
519
+	 * @throws InvalidDataTypeException
520
+	 * @throws InvalidInterfaceException
521
+	 * @throws ReflectionException
522
+	 */
523
+	public function parent_ID()
524
+	{
525
+		return $this->get('LIN_parent');
526
+	}
527
+
528
+
529
+	/**
530
+	 * Sets parent
531
+	 *
532
+	 * @param int $parent
533
+	 * @throws EE_Error
534
+	 * @throws InvalidArgumentException
535
+	 * @throws InvalidDataTypeException
536
+	 * @throws InvalidInterfaceException
537
+	 * @throws ReflectionException
538
+	 */
539
+	public function set_parent_ID($parent)
540
+	{
541
+		$this->set('LIN_parent', $parent);
542
+	}
543
+
544
+
545
+	/**
546
+	 * Gets type
547
+	 *
548
+	 * @return string
549
+	 * @throws EE_Error
550
+	 * @throws InvalidArgumentException
551
+	 * @throws InvalidDataTypeException
552
+	 * @throws InvalidInterfaceException
553
+	 * @throws ReflectionException
554
+	 */
555
+	public function type()
556
+	{
557
+		return $this->get('LIN_type');
558
+	}
559
+
560
+
561
+	/**
562
+	 * Sets type
563
+	 *
564
+	 * @param string $type
565
+	 * @throws EE_Error
566
+	 * @throws InvalidArgumentException
567
+	 * @throws InvalidDataTypeException
568
+	 * @throws InvalidInterfaceException
569
+	 * @throws ReflectionException
570
+	 */
571
+	public function set_type($type)
572
+	{
573
+		$this->set('LIN_type', $type);
574
+	}
575
+
576
+
577
+	/**
578
+	 * Gets the line item of which this item is a composite. Eg, if this is a subtotal, the parent might be a total\
579
+	 * If this line item is saved to the DB, fetches the parent from the DB. However, if this line item isn't in the DB
580
+	 * it uses its cached reference to its parent line item (which would have been set by `EE_Line_Item::set_parent()`
581
+	 * or indirectly by `EE_Line_item::add_child_line_item()`)
582
+	 *
583
+	 * @return EE_Base_Class|EE_Line_Item
584
+	 * @throws EE_Error
585
+	 * @throws InvalidArgumentException
586
+	 * @throws InvalidDataTypeException
587
+	 * @throws InvalidInterfaceException
588
+	 * @throws ReflectionException
589
+	 */
590
+	public function parent()
591
+	{
592
+		return $this->ID()
593
+			? $this->get_model()->get_one_by_ID($this->parent_ID())
594
+			: $this->_parent;
595
+	}
596
+
597
+
598
+	/**
599
+	 * Gets ALL the children of this line item (ie, all the parts that contribute towards this total).
600
+	 *
601
+	 * @return EE_Base_Class[]|EE_Line_Item[]
602
+	 * @throws EE_Error
603
+	 * @throws InvalidArgumentException
604
+	 * @throws InvalidDataTypeException
605
+	 * @throws InvalidInterfaceException
606
+	 * @throws ReflectionException
607
+	 */
608
+	public function children()
609
+	{
610
+		if ($this->ID()) {
611
+			return $this->get_model()->get_all(
612
+				array(
613
+					array('LIN_parent' => $this->ID()),
614
+					'order_by' => array('LIN_order' => 'ASC'),
615
+				)
616
+			);
617
+		}
618
+		if (! is_array($this->_children)) {
619
+			$this->_children = array();
620
+		}
621
+		return $this->_children;
622
+	}
623
+
624
+
625
+	/**
626
+	 * Gets code
627
+	 *
628
+	 * @return string
629
+	 * @throws EE_Error
630
+	 * @throws InvalidArgumentException
631
+	 * @throws InvalidDataTypeException
632
+	 * @throws InvalidInterfaceException
633
+	 * @throws ReflectionException
634
+	 */
635
+	public function code()
636
+	{
637
+		return $this->get('LIN_code');
638
+	}
639
+
640
+
641
+	/**
642
+	 * Sets code
643
+	 *
644
+	 * @param string $code
645
+	 * @throws EE_Error
646
+	 * @throws InvalidArgumentException
647
+	 * @throws InvalidDataTypeException
648
+	 * @throws InvalidInterfaceException
649
+	 * @throws ReflectionException
650
+	 */
651
+	public function set_code($code)
652
+	{
653
+		$this->set('LIN_code', $code);
654
+	}
655
+
656
+
657
+	/**
658
+	 * Gets is_taxable
659
+	 *
660
+	 * @return boolean
661
+	 * @throws EE_Error
662
+	 * @throws InvalidArgumentException
663
+	 * @throws InvalidDataTypeException
664
+	 * @throws InvalidInterfaceException
665
+	 * @throws ReflectionException
666
+	 */
667
+	public function is_taxable()
668
+	{
669
+		return $this->get('LIN_is_taxable');
670
+	}
671
+
672
+
673
+	/**
674
+	 * Sets is_taxable
675
+	 *
676
+	 * @param boolean $is_taxable
677
+	 * @throws EE_Error
678
+	 * @throws InvalidArgumentException
679
+	 * @throws InvalidDataTypeException
680
+	 * @throws InvalidInterfaceException
681
+	 * @throws ReflectionException
682
+	 */
683
+	public function set_is_taxable($is_taxable)
684
+	{
685
+		$this->set('LIN_is_taxable', $is_taxable);
686
+	}
687
+
688
+
689
+	/**
690
+	 * Gets the object that this model-joins-to.
691
+	 * returns one of the model objects that the field OBJ_ID can point to... see the 'OBJ_ID' field on
692
+	 * EEM_Promotion_Object
693
+	 *        Eg, if this line item join model object is for a ticket, this will return the EE_Ticket object
694
+	 *
695
+	 * @return EE_Base_Class | NULL
696
+	 * @throws EE_Error
697
+	 * @throws InvalidArgumentException
698
+	 * @throws InvalidDataTypeException
699
+	 * @throws InvalidInterfaceException
700
+	 * @throws ReflectionException
701
+	 */
702
+	public function get_object()
703
+	{
704
+		$model_name_of_related_obj = $this->OBJ_type();
705
+		return $this->get_model()->has_relation($model_name_of_related_obj)
706
+			? $this->get_first_related($model_name_of_related_obj)
707
+			: null;
708
+	}
709
+
710
+
711
+	/**
712
+	 * Like EE_Line_Item::get_object(), but can only ever actually return an EE_Ticket.
713
+	 * (IE, if this line item is for a price or something else, will return NULL)
714
+	 *
715
+	 * @param array $query_params
716
+	 * @return EE_Base_Class|EE_Ticket
717
+	 * @throws EE_Error
718
+	 * @throws InvalidArgumentException
719
+	 * @throws InvalidDataTypeException
720
+	 * @throws InvalidInterfaceException
721
+	 * @throws ReflectionException
722
+	 */
723
+	public function ticket($query_params = array())
724
+	{
725
+		// we're going to assume that when this method is called
726
+		// we always want to receive the attached ticket EVEN if that ticket is archived.
727
+		// This can be overridden via the incoming $query_params argument
728
+		$remove_defaults = array('default_where_conditions' => 'none');
729
+		$query_params = array_merge($remove_defaults, $query_params);
730
+		return $this->get_first_related(EEM_Line_Item::OBJ_TYPE_TICKET, $query_params);
731
+	}
732
+
733
+
734
+	/**
735
+	 * Gets the EE_Datetime that's related to the ticket, IF this is for a ticket
736
+	 *
737
+	 * @return EE_Datetime | NULL
738
+	 * @throws EE_Error
739
+	 * @throws InvalidArgumentException
740
+	 * @throws InvalidDataTypeException
741
+	 * @throws InvalidInterfaceException
742
+	 * @throws ReflectionException
743
+	 */
744
+	public function get_ticket_datetime()
745
+	{
746
+		if ($this->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET) {
747
+			$ticket = $this->ticket();
748
+			if ($ticket instanceof EE_Ticket) {
749
+				$datetime = $ticket->first_datetime();
750
+				if ($datetime instanceof EE_Datetime) {
751
+					return $datetime;
752
+				}
753
+			}
754
+		}
755
+		return null;
756
+	}
757
+
758
+
759
+	/**
760
+	 * Gets the event's name that's related to the ticket, if this is for
761
+	 * a ticket
762
+	 *
763
+	 * @return string
764
+	 * @throws EE_Error
765
+	 * @throws InvalidArgumentException
766
+	 * @throws InvalidDataTypeException
767
+	 * @throws InvalidInterfaceException
768
+	 * @throws ReflectionException
769
+	 */
770
+	public function ticket_event_name()
771
+	{
772
+		$event_name = esc_html__('Unknown', 'event_espresso');
773
+		$event = $this->ticket_event();
774
+		if ($event instanceof EE_Event) {
775
+			$event_name = $event->name();
776
+		}
777
+		return $event_name;
778
+	}
779
+
780
+
781
+	/**
782
+	 * Gets the event that's related to the ticket, if this line item represents a ticket.
783
+	 *
784
+	 * @return EE_Event|null
785
+	 * @throws EE_Error
786
+	 * @throws InvalidArgumentException
787
+	 * @throws InvalidDataTypeException
788
+	 * @throws InvalidInterfaceException
789
+	 * @throws ReflectionException
790
+	 */
791
+	public function ticket_event()
792
+	{
793
+		$event = null;
794
+		$ticket = $this->ticket();
795
+		if ($ticket instanceof EE_Ticket) {
796
+			$datetime = $ticket->first_datetime();
797
+			if ($datetime instanceof EE_Datetime) {
798
+				$event = $datetime->event();
799
+			}
800
+		}
801
+		return $event;
802
+	}
803
+
804
+
805
+	/**
806
+	 * Gets the first datetime for this lien item, assuming it's for a ticket
807
+	 *
808
+	 * @param string $date_format
809
+	 * @param string $time_format
810
+	 * @return string
811
+	 * @throws EE_Error
812
+	 * @throws InvalidArgumentException
813
+	 * @throws InvalidDataTypeException
814
+	 * @throws InvalidInterfaceException
815
+	 * @throws ReflectionException
816
+	 */
817
+	public function ticket_datetime_start($date_format = '', $time_format = '')
818
+	{
819
+		$first_datetime_string = esc_html__('Unknown', 'event_espresso');
820
+		$datetime = $this->get_ticket_datetime();
821
+		if ($datetime) {
822
+			$first_datetime_string = $datetime->start_date_and_time($date_format, $time_format);
823
+		}
824
+		return $first_datetime_string;
825
+	}
826
+
827
+
828
+	/**
829
+	 * Adds the line item as a child to this line item. If there is another child line
830
+	 * item with the same LIN_code, it is overwritten by this new one
831
+	 *
832
+	 * @param EEI_Line_Item $line_item
833
+	 * @param bool          $set_order
834
+	 * @return bool success
835
+	 * @throws EE_Error
836
+	 * @throws InvalidArgumentException
837
+	 * @throws InvalidDataTypeException
838
+	 * @throws InvalidInterfaceException
839
+	 * @throws ReflectionException
840
+	 */
841
+	public function add_child_line_item(EEI_Line_Item $line_item, $set_order = true)
842
+	{
843
+		// should we calculate the LIN_order for this line item ?
844
+		if ($set_order || $line_item->order() === null) {
845
+			$line_item->set_order(count($this->children()));
846
+		}
847
+		if ($this->ID()) {
848
+			// check for any duplicate line items (with the same code), if so, this replaces it
849
+			$line_item_with_same_code = $this->get_child_line_item($line_item->code());
850
+			if ($line_item_with_same_code instanceof EE_Line_Item && $line_item_with_same_code !== $line_item) {
851
+				$this->delete_child_line_item($line_item_with_same_code->code());
852
+			}
853
+			$line_item->set_parent_ID($this->ID());
854
+			if ($this->TXN_ID()) {
855
+				$line_item->set_TXN_ID($this->TXN_ID());
856
+			}
857
+			return $line_item->save();
858
+		}
859
+		$this->_children[ $line_item->code() ] = $line_item;
860
+		if ($line_item->parent() !== $this) {
861
+			$line_item->set_parent($this);
862
+		}
863
+		return true;
864
+	}
865
+
866
+
867
+	/**
868
+	 * Similar to EE_Base_Class::_add_relation_to, except this isn't a normal relation.
869
+	 * If this line item is saved to the DB, this is just a wrapper for set_parent_ID() and save()
870
+	 * However, if this line item is NOT saved to the DB, this just caches the parent on
871
+	 * the EE_Line_Item::_parent property.
872
+	 *
873
+	 * @param EE_Line_Item $line_item
874
+	 * @throws EE_Error
875
+	 * @throws InvalidArgumentException
876
+	 * @throws InvalidDataTypeException
877
+	 * @throws InvalidInterfaceException
878
+	 * @throws ReflectionException
879
+	 */
880
+	public function set_parent($line_item)
881
+	{
882
+		if ($this->ID()) {
883
+			if (! $line_item->ID()) {
884
+				$line_item->save();
885
+			}
886
+			$this->set_parent_ID($line_item->ID());
887
+			$this->save();
888
+		} else {
889
+			$this->_parent = $line_item;
890
+			$this->set_parent_ID($line_item->ID());
891
+		}
892
+	}
893
+
894
+
895
+	/**
896
+	 * Gets the child line item as specified by its code. Because this returns an object (by reference)
897
+	 * you can modify this child line item and the parent (this object) can know about them
898
+	 * because it also has a reference to that line item
899
+	 *
900
+	 * @param string $code
901
+	 * @return EE_Base_Class|EE_Line_Item|EE_Soft_Delete_Base_Class|NULL
902
+	 * @throws EE_Error
903
+	 * @throws InvalidArgumentException
904
+	 * @throws InvalidDataTypeException
905
+	 * @throws InvalidInterfaceException
906
+	 * @throws ReflectionException
907
+	 */
908
+	public function get_child_line_item($code)
909
+	{
910
+		if ($this->ID()) {
911
+			return $this->get_model()->get_one(
912
+				array(array('LIN_parent' => $this->ID(), 'LIN_code' => $code))
913
+			);
914
+		}
915
+		return isset($this->_children[ $code ])
916
+			? $this->_children[ $code ]
917
+			: null;
918
+	}
919
+
920
+
921
+	/**
922
+	 * Returns how many items are deleted (or, if this item has not been saved ot the DB yet, just how many it HAD
923
+	 * cached on it)
924
+	 *
925
+	 * @return int
926
+	 * @throws EE_Error
927
+	 * @throws InvalidArgumentException
928
+	 * @throws InvalidDataTypeException
929
+	 * @throws InvalidInterfaceException
930
+	 * @throws ReflectionException
931
+	 */
932
+	public function delete_children_line_items()
933
+	{
934
+		if ($this->ID()) {
935
+			return $this->get_model()->delete(array(array('LIN_parent' => $this->ID())));
936
+		}
937
+		$count = count($this->_children);
938
+		$this->_children = array();
939
+		return $count;
940
+	}
941
+
942
+
943
+	/**
944
+	 * If this line item has been saved to the DB, deletes its child with LIN_code == $code. If this line
945
+	 * HAS NOT been saved to the DB, removes the child line item with index $code.
946
+	 * Also searches through the child's children for a matching line item. However, once a line item has been found
947
+	 * and deleted, stops searching (so if there are line items with duplicate codes, only the first one found will be
948
+	 * deleted)
949
+	 *
950
+	 * @param string $code
951
+	 * @param bool   $stop_search_once_found
952
+	 * @return int count of items deleted (or simply removed from the line item's cache, if not has not been saved to
953
+	 *             the DB yet)
954
+	 * @throws EE_Error
955
+	 * @throws InvalidArgumentException
956
+	 * @throws InvalidDataTypeException
957
+	 * @throws InvalidInterfaceException
958
+	 * @throws ReflectionException
959
+	 */
960
+	public function delete_child_line_item($code, $stop_search_once_found = true)
961
+	{
962
+		if ($this->ID()) {
963
+			$items_deleted = 0;
964
+			if ($this->code() === $code) {
965
+				$items_deleted += EEH_Line_Item::delete_all_child_items($this);
966
+				$items_deleted += (int) $this->delete();
967
+				if ($stop_search_once_found) {
968
+					return $items_deleted;
969
+				}
970
+			}
971
+			foreach ($this->children() as $child_line_item) {
972
+				$items_deleted += $child_line_item->delete_child_line_item($code, $stop_search_once_found);
973
+			}
974
+			return $items_deleted;
975
+		}
976
+		if (isset($this->_children[ $code ])) {
977
+			unset($this->_children[ $code ]);
978
+			return 1;
979
+		}
980
+		return 0;
981
+	}
982
+
983
+
984
+	/**
985
+	 * If this line item is in the database, is of the type subtotal, and
986
+	 * has no children, why do we have it? It should be deleted so this function
987
+	 * does that
988
+	 *
989
+	 * @return boolean
990
+	 * @throws EE_Error
991
+	 * @throws InvalidArgumentException
992
+	 * @throws InvalidDataTypeException
993
+	 * @throws InvalidInterfaceException
994
+	 * @throws ReflectionException
995
+	 */
996
+	public function delete_if_childless_subtotal()
997
+	{
998
+		if ($this->ID() && $this->type() === EEM_Line_Item::type_sub_total && ! $this->children()) {
999
+			return $this->delete();
1000
+		}
1001
+		return false;
1002
+	}
1003
+
1004
+
1005
+	/**
1006
+	 * Creates a code and returns a string. doesn't assign the code to this model object
1007
+	 *
1008
+	 * @return string
1009
+	 * @throws EE_Error
1010
+	 * @throws InvalidArgumentException
1011
+	 * @throws InvalidDataTypeException
1012
+	 * @throws InvalidInterfaceException
1013
+	 * @throws ReflectionException
1014
+	 */
1015
+	public function generate_code()
1016
+	{
1017
+		// each line item in the cart requires a unique identifier
1018
+		return md5($this->get('OBJ_type') . $this->get('OBJ_ID') . microtime());
1019
+	}
1020
+
1021
+
1022
+	/**
1023
+	 * @return bool
1024
+	 * @throws EE_Error
1025
+	 * @throws InvalidArgumentException
1026
+	 * @throws InvalidDataTypeException
1027
+	 * @throws InvalidInterfaceException
1028
+	 * @throws ReflectionException
1029
+	 */
1030
+	public function is_tax()
1031
+	{
1032
+		return $this->type() === EEM_Line_Item::type_tax;
1033
+	}
1034
+
1035
+
1036
+	/**
1037
+	 * @return bool
1038
+	 * @throws EE_Error
1039
+	 * @throws InvalidArgumentException
1040
+	 * @throws InvalidDataTypeException
1041
+	 * @throws InvalidInterfaceException
1042
+	 * @throws ReflectionException
1043
+	 */
1044
+	public function is_tax_sub_total()
1045
+	{
1046
+		return $this->type() === EEM_Line_Item::type_tax_sub_total;
1047
+	}
1048
+
1049
+
1050
+	/**
1051
+	 * @return bool
1052
+	 * @throws EE_Error
1053
+	 * @throws InvalidArgumentException
1054
+	 * @throws InvalidDataTypeException
1055
+	 * @throws InvalidInterfaceException
1056
+	 * @throws ReflectionException
1057
+	 */
1058
+	public function is_line_item()
1059
+	{
1060
+		return $this->type() === EEM_Line_Item::type_line_item;
1061
+	}
1062
+
1063
+
1064
+	/**
1065
+	 * @return bool
1066
+	 * @throws EE_Error
1067
+	 * @throws InvalidArgumentException
1068
+	 * @throws InvalidDataTypeException
1069
+	 * @throws InvalidInterfaceException
1070
+	 * @throws ReflectionException
1071
+	 */
1072
+	public function is_sub_line_item()
1073
+	{
1074
+		return $this->type() === EEM_Line_Item::type_sub_line_item;
1075
+	}
1076
+
1077
+
1078
+	/**
1079
+	 * @return bool
1080
+	 * @throws EE_Error
1081
+	 * @throws InvalidArgumentException
1082
+	 * @throws InvalidDataTypeException
1083
+	 * @throws InvalidInterfaceException
1084
+	 * @throws ReflectionException
1085
+	 */
1086
+	public function is_sub_total()
1087
+	{
1088
+		return $this->type() === EEM_Line_Item::type_sub_total;
1089
+	}
1090
+
1091
+
1092
+	/**
1093
+	 * Whether or not this line item is a cancellation line item
1094
+	 *
1095
+	 * @return boolean
1096
+	 * @throws EE_Error
1097
+	 * @throws InvalidArgumentException
1098
+	 * @throws InvalidDataTypeException
1099
+	 * @throws InvalidInterfaceException
1100
+	 * @throws ReflectionException
1101
+	 */
1102
+	public function is_cancellation()
1103
+	{
1104
+		return EEM_Line_Item::type_cancellation === $this->type();
1105
+	}
1106
+
1107
+
1108
+	/**
1109
+	 * @return bool
1110
+	 * @throws EE_Error
1111
+	 * @throws InvalidArgumentException
1112
+	 * @throws InvalidDataTypeException
1113
+	 * @throws InvalidInterfaceException
1114
+	 * @throws ReflectionException
1115
+	 */
1116
+	public function is_total()
1117
+	{
1118
+		return $this->type() === EEM_Line_Item::type_total;
1119
+	}
1120
+
1121
+
1122
+	/**
1123
+	 * @return bool
1124
+	 * @throws EE_Error
1125
+	 * @throws InvalidArgumentException
1126
+	 * @throws InvalidDataTypeException
1127
+	 * @throws InvalidInterfaceException
1128
+	 * @throws ReflectionException
1129
+	 */
1130
+	public function is_cancelled()
1131
+	{
1132
+		return $this->type() === EEM_Line_Item::type_cancellation;
1133
+	}
1134
+
1135
+
1136
+	/**
1137
+	 * @return string like '2, 004.00', formatted according to the localized currency
1138
+	 * @throws EE_Error
1139
+	 * @throws InvalidArgumentException
1140
+	 * @throws InvalidDataTypeException
1141
+	 * @throws InvalidInterfaceException
1142
+	 * @throws ReflectionException
1143
+	 */
1144
+	public function unit_price_no_code()
1145
+	{
1146
+		return $this->get_pretty('LIN_unit_price', 'no_currency_code');
1147
+	}
1148
+
1149
+
1150
+	/**
1151
+	 * @return string like '2, 004.00', formatted according to the localized currency
1152
+	 * @throws EE_Error
1153
+	 * @throws InvalidArgumentException
1154
+	 * @throws InvalidDataTypeException
1155
+	 * @throws InvalidInterfaceException
1156
+	 * @throws ReflectionException
1157
+	 */
1158
+	public function total_no_code()
1159
+	{
1160
+		return $this->get_pretty('LIN_total', 'no_currency_code');
1161
+	}
1162
+
1163
+
1164
+	/**
1165
+	 * Gets the final total on this item, taking taxes into account.
1166
+	 * Has the side-effect of setting the sub-total as it was just calculated.
1167
+	 * If this is used on a grand-total line item, also updates the transaction's
1168
+	 * TXN_total (provided this line item is allowed to persist, otherwise we don't
1169
+	 * want to change a persistable transaction with info from a non-persistent line item)
1170
+	 *
1171
+	 * @param bool $update_txn_status
1172
+	 * @return float
1173
+	 * @throws EE_Error
1174
+	 * @throws InvalidArgumentException
1175
+	 * @throws InvalidDataTypeException
1176
+	 * @throws InvalidInterfaceException
1177
+	 * @throws ReflectionException
1178
+	 * @throws RuntimeException
1179
+	 */
1180
+	public function recalculate_total_including_taxes($update_txn_status = false)
1181
+	{
1182
+		$pre_tax_total = $this->recalculate_pre_tax_total();
1183
+		$tax_total = $this->recalculate_taxes_and_tax_total();
1184
+		$total = $pre_tax_total + $tax_total;
1185
+		// no negative totals plz
1186
+		$total = max($total, 0);
1187
+		$this->set_total($total);
1188
+		// only update the related transaction's total
1189
+		// if we intend to save this line item and its a grand total
1190
+		if ($this->allow_persist() && $this->type() === EEM_Line_Item::type_total
1191
+			&& $this->transaction()
1192
+			   instanceof
1193
+			   EE_Transaction
1194
+		) {
1195
+			$this->transaction()->set_total($total);
1196
+			if ($update_txn_status) {
1197
+				// don't save the TXN because that will be done below
1198
+				// and the following method only saves if the status changes
1199
+				$this->transaction()->update_status_based_on_total_paid(false);
1200
+			}
1201
+			if ($this->transaction()->ID()) {
1202
+				$this->transaction()->save();
1203
+			}
1204
+		}
1205
+		$this->maybe_save();
1206
+		return $total;
1207
+	}
1208
+
1209
+
1210
+	/**
1211
+	 * Recursively goes through all the children and recalculates sub-totals EXCEPT for
1212
+	 * tax-sub-totals (they're a an odd beast). Updates the 'total' on each line item according to either its
1213
+	 * unit price * quantity or the total of all its children EXCEPT when we're only calculating the taxable total and
1214
+	 * when this is called on the grand total
1215
+	 *
1216
+	 * @return float
1217
+	 * @throws EE_Error
1218
+	 * @throws InvalidArgumentException
1219
+	 * @throws InvalidDataTypeException
1220
+	 * @throws InvalidInterfaceException
1221
+	 * @throws ReflectionException
1222
+	 */
1223
+	public function recalculate_pre_tax_total()
1224
+	{
1225
+		$total = 0;
1226
+		$my_children = $this->children();
1227
+		$has_children = ! empty($my_children);
1228
+		if ($has_children && $this->is_line_item()) {
1229
+			$total = $this->_recalculate_pretax_total_for_line_item($total, $my_children);
1230
+		} elseif (! $has_children && ($this->is_sub_line_item() || $this->is_line_item())) {
1231
+			$total = $this->unit_price() * $this->quantity();
1232
+		} elseif ($this->is_sub_total() || $this->is_total()) {
1233
+			$total = $this->_recalculate_pretax_total_for_subtotal($total, $my_children);
1234
+		} elseif ($this->is_tax_sub_total() || $this->is_tax() || $this->is_cancelled()) {
1235
+			// completely ignore tax totals, tax sub-totals, and cancelled line items, when calculating the pre-tax-total
1236
+			return 0;
1237
+		}
1238
+		// ensure all non-line items and non-sub-line-items have a quantity of 1 (except for Events)
1239
+		if (! $this->is_line_item() && ! $this->is_sub_line_item() && ! $this->is_cancellation()
1240
+		) {
1241
+			if ($this->OBJ_type() !== EEM_Line_Item::OBJ_TYPE_EVENT) {
1242
+				$this->set_quantity(1);
1243
+			}
1244
+			if (! $this->is_percent()) {
1245
+				$this->set_unit_price($total);
1246
+			}
1247
+		}
1248
+		// we don't want to bother saving grand totals, because that needs to factor in taxes anyways
1249
+		// so it ought to be
1250
+		if (! $this->is_total()) {
1251
+			$this->set_total($total);
1252
+			// if not a percent line item, make sure we keep the unit price in sync
1253
+			if ($has_children
1254
+				&& $this->is_line_item()
1255
+				&& ! $this->is_percent()
1256
+			) {
1257
+				if ($this->quantity() === 0) {
1258
+					$new_unit_price = 0;
1259
+				} else {
1260
+					$new_unit_price = $this->total() / $this->quantity();
1261
+				}
1262
+				$this->set_unit_price($new_unit_price);
1263
+			}
1264
+			$this->maybe_save();
1265
+		}
1266
+		return $total;
1267
+	}
1268
+
1269
+
1270
+	/**
1271
+	 * Calculates the pretax total when this line item is a subtotal or total line item.
1272
+	 * Basically does a sum-then-round approach (ie, any percent line item that are children
1273
+	 * will calculate their total based on the un-rounded total we're working with so far, and
1274
+	 * THEN round the result; instead of rounding as we go like with sub-line-items)
1275
+	 *
1276
+	 * @param float          $calculated_total_so_far
1277
+	 * @param EE_Line_Item[] $my_children
1278
+	 * @return float
1279
+	 * @throws EE_Error
1280
+	 * @throws InvalidArgumentException
1281
+	 * @throws InvalidDataTypeException
1282
+	 * @throws InvalidInterfaceException
1283
+	 * @throws ReflectionException
1284
+	 */
1285
+	protected function _recalculate_pretax_total_for_subtotal($calculated_total_so_far, $my_children = null)
1286
+	{
1287
+		if ($my_children === null) {
1288
+			$my_children = $this->children();
1289
+		}
1290
+		$subtotal_quantity = 0;
1291
+		// get the total of all its children
1292
+		foreach ($my_children as $child_line_item) {
1293
+			if ($child_line_item instanceof EE_Line_Item && ! $child_line_item->is_cancellation()) {
1294
+				// percentage line items are based on total so far
1295
+				if ($child_line_item->is_percent()) {
1296
+					// round as we go so that the line items add up ok
1297
+					$percent_total = round(
1298
+						$calculated_total_so_far * $child_line_item->percent() / 100,
1299
+						EE_Registry::instance()->CFG->currency->dec_plc
1300
+					);
1301
+					$child_line_item->set_total($percent_total);
1302
+					// so far all percent line items should have a quantity of 1
1303
+					// (ie, no double percent discounts. Although that might be requested someday)
1304
+					$child_line_item->set_quantity(1);
1305
+					$child_line_item->maybe_save();
1306
+					$calculated_total_so_far += $percent_total;
1307
+				} else {
1308
+					// verify flat sub-line-item quantities match their parent
1309
+					if ($child_line_item->is_sub_line_item()) {
1310
+						$child_line_item->set_quantity($this->quantity());
1311
+					}
1312
+					$calculated_total_so_far += $child_line_item->recalculate_pre_tax_total();
1313
+					$subtotal_quantity += $child_line_item->quantity();
1314
+				}
1315
+			}
1316
+		}
1317
+		if ($this->is_sub_total()) {
1318
+			// no negative totals plz
1319
+			$calculated_total_so_far = max($calculated_total_so_far, 0);
1320
+			$subtotal_quantity = $subtotal_quantity > 0 ? 1 : 0;
1321
+			$this->set_quantity($subtotal_quantity);
1322
+			$this->maybe_save();
1323
+		}
1324
+		return $calculated_total_so_far;
1325
+	}
1326
+
1327
+
1328
+	/**
1329
+	 * Calculates the pretax total for a normal line item, in a round-then-sum approach
1330
+	 * (where each sub-line-item is applied to the base price for the line item
1331
+	 * and the result is immediately rounded, rather than summing all the sub-line-items
1332
+	 * then rounding, like we do when recalculating pretax totals on totals and subtotals).
1333
+	 *
1334
+	 * @param float          $calculated_total_so_far
1335
+	 * @param EE_Line_Item[] $my_children
1336
+	 * @return float
1337
+	 * @throws EE_Error
1338
+	 * @throws InvalidArgumentException
1339
+	 * @throws InvalidDataTypeException
1340
+	 * @throws InvalidInterfaceException
1341
+	 * @throws ReflectionException
1342
+	 */
1343
+	protected function _recalculate_pretax_total_for_line_item($calculated_total_so_far, $my_children = null)
1344
+	{
1345
+		if ($my_children === null) {
1346
+			$my_children = $this->children();
1347
+		}
1348
+		// we need to keep track of the running total for a single item,
1349
+		// because we need to round as we go
1350
+		$unit_price_for_total = 0;
1351
+		$quantity_for_total = 1;
1352
+		// get the total of all its children
1353
+		foreach ($my_children as $child_line_item) {
1354
+			if ($child_line_item instanceof EE_Line_Item && ! $child_line_item->is_cancellation()) {
1355
+				if ($child_line_item->is_percent()) {
1356
+					// it should be the unit-price-so-far multiplied by teh percent multiplied by the quantity
1357
+					// not total multiplied by percent, because that ignores rounding along-the-way
1358
+					$percent_unit_price = round(
1359
+						$unit_price_for_total * $child_line_item->percent() / 100,
1360
+						EE_Registry::instance()->CFG->currency->dec_plc
1361
+					);
1362
+					$percent_total = $percent_unit_price * $quantity_for_total;
1363
+					$child_line_item->set_total($percent_total);
1364
+					// so far all percent line items should have a quantity of 1
1365
+					// (ie, no double percent discounts. Although that might be requested someday)
1366
+					$child_line_item->set_quantity(1);
1367
+					$child_line_item->maybe_save();
1368
+					$calculated_total_so_far += $percent_total;
1369
+					$unit_price_for_total += $percent_unit_price;
1370
+				} else {
1371
+					// verify flat sub-line-item quantities match their parent
1372
+					if ($child_line_item->is_sub_line_item()) {
1373
+						$child_line_item->set_quantity($this->quantity());
1374
+					}
1375
+					$quantity_for_total = $child_line_item->quantity();
1376
+					$calculated_total_so_far += $child_line_item->recalculate_pre_tax_total();
1377
+					$unit_price_for_total += $child_line_item->unit_price();
1378
+				}
1379
+			}
1380
+		}
1381
+		return $calculated_total_so_far;
1382
+	}
1383
+
1384
+
1385
+	/**
1386
+	 * Recalculates the total on each individual tax (based on a recalculation of the pre-tax total), sets
1387
+	 * the totals on each tax calculated, and returns the final tax total. Re-saves tax line items
1388
+	 * and tax sub-total if already in the DB
1389
+	 *
1390
+	 * @return float
1391
+	 * @throws EE_Error
1392
+	 * @throws InvalidArgumentException
1393
+	 * @throws InvalidDataTypeException
1394
+	 * @throws InvalidInterfaceException
1395
+	 * @throws ReflectionException
1396
+	 */
1397
+	public function recalculate_taxes_and_tax_total()
1398
+	{
1399
+		// get all taxes
1400
+		$taxes = $this->tax_descendants();
1401
+		// calculate the pretax total
1402
+		$taxable_total = $this->taxable_total();
1403
+		$tax_total = 0;
1404
+		foreach ($taxes as $tax) {
1405
+			$total_on_this_tax = $taxable_total * $tax->percent() / 100;
1406
+			// remember the total on this line item
1407
+			$tax->set_total($total_on_this_tax);
1408
+			$tax->maybe_save();
1409
+			$tax_total += $tax->total();
1410
+		}
1411
+		$this->_recalculate_tax_sub_total();
1412
+		return $tax_total;
1413
+	}
1414
+
1415
+
1416
+	/**
1417
+	 * Simply forces all the tax-sub-totals to recalculate. Assumes the taxes have been calculated
1418
+	 *
1419
+	 * @return void
1420
+	 * @throws EE_Error
1421
+	 * @throws InvalidArgumentException
1422
+	 * @throws InvalidDataTypeException
1423
+	 * @throws InvalidInterfaceException
1424
+	 * @throws ReflectionException
1425
+	 */
1426
+	private function _recalculate_tax_sub_total()
1427
+	{
1428
+		if ($this->is_tax_sub_total()) {
1429
+			$total = 0;
1430
+			$total_percent = 0;
1431
+			// simply loop through all its children (which should be taxes) and sum their total
1432
+			foreach ($this->children() as $child_tax) {
1433
+				if ($child_tax instanceof EE_Line_Item) {
1434
+					$total += $child_tax->total();
1435
+					$total_percent += $child_tax->percent();
1436
+				}
1437
+			}
1438
+			$this->set_total($total);
1439
+			$this->set_percent($total_percent);
1440
+			$this->maybe_save();
1441
+		} elseif ($this->is_total()) {
1442
+			foreach ($this->children() as $maybe_tax_subtotal) {
1443
+				if ($maybe_tax_subtotal instanceof EE_Line_Item) {
1444
+					$maybe_tax_subtotal->_recalculate_tax_sub_total();
1445
+				}
1446
+			}
1447
+		}
1448
+	}
1449
+
1450
+
1451
+	/**
1452
+	 * Gets the total tax on this line item. Assumes taxes have already been calculated using
1453
+	 * recalculate_taxes_and_total
1454
+	 *
1455
+	 * @return float
1456
+	 * @throws EE_Error
1457
+	 * @throws InvalidArgumentException
1458
+	 * @throws InvalidDataTypeException
1459
+	 * @throws InvalidInterfaceException
1460
+	 * @throws ReflectionException
1461
+	 */
1462
+	public function get_total_tax()
1463
+	{
1464
+		$this->_recalculate_tax_sub_total();
1465
+		$total = 0;
1466
+		foreach ($this->tax_descendants() as $tax_line_item) {
1467
+			if ($tax_line_item instanceof EE_Line_Item) {
1468
+				$total += $tax_line_item->total();
1469
+			}
1470
+		}
1471
+		return $total;
1472
+	}
1473
+
1474
+
1475
+	/**
1476
+	 * Gets the total for all the items purchased only
1477
+	 *
1478
+	 * @return float
1479
+	 * @throws EE_Error
1480
+	 * @throws InvalidArgumentException
1481
+	 * @throws InvalidDataTypeException
1482
+	 * @throws InvalidInterfaceException
1483
+	 * @throws ReflectionException
1484
+	 */
1485
+	public function get_items_total()
1486
+	{
1487
+		// by default, let's make sure we're consistent with the existing line item
1488
+		if ($this->is_total()) {
1489
+			$pretax_subtotal_li = EEH_Line_Item::get_pre_tax_subtotal($this);
1490
+			if ($pretax_subtotal_li instanceof EE_Line_Item) {
1491
+				return $pretax_subtotal_li->total();
1492
+			}
1493
+		}
1494
+		$total = 0;
1495
+		foreach ($this->get_items() as $item) {
1496
+			if ($item instanceof EE_Line_Item) {
1497
+				$total += $item->total();
1498
+			}
1499
+		}
1500
+		return $total;
1501
+	}
1502
+
1503
+
1504
+	/**
1505
+	 * Gets all the descendants (ie, children or children of children etc) that
1506
+	 * are of the type 'tax'
1507
+	 *
1508
+	 * @return EE_Line_Item[]
1509
+	 * @throws EE_Error
1510
+	 */
1511
+	public function tax_descendants()
1512
+	{
1513
+		return EEH_Line_Item::get_tax_descendants($this);
1514
+	}
1515
+
1516
+
1517
+	/**
1518
+	 * Gets all the real items purchased which are children of this item
1519
+	 *
1520
+	 * @return EE_Line_Item[]
1521
+	 * @throws EE_Error
1522
+	 */
1523
+	public function get_items()
1524
+	{
1525
+		return EEH_Line_Item::get_line_item_descendants($this);
1526
+	}
1527
+
1528
+
1529
+	/**
1530
+	 * Returns the amount taxable among this line item's children (or if it has no children,
1531
+	 * how much of it is taxable). Does not recalculate totals or subtotals.
1532
+	 * If the taxable total is negative, (eg, if none of the tickets were taxable,
1533
+	 * but there is a "Taxable" discount), returns 0.
1534
+	 *
1535
+	 * @return float
1536
+	 * @throws EE_Error
1537
+	 * @throws InvalidArgumentException
1538
+	 * @throws InvalidDataTypeException
1539
+	 * @throws InvalidInterfaceException
1540
+	 * @throws ReflectionException
1541
+	 */
1542
+	public function taxable_total()
1543
+	{
1544
+		$total = 0;
1545
+		if ($this->children()) {
1546
+			foreach ($this->children() as $child_line_item) {
1547
+				if ($child_line_item->type() === EEM_Line_Item::type_line_item && $child_line_item->is_taxable()) {
1548
+					// if it's a percent item, only take into account the percent
1549
+					// that's taxable too (the taxable total so far)
1550
+					if ($child_line_item->is_percent()) {
1551
+						$total += ($total * $child_line_item->percent() / 100);
1552
+					} else {
1553
+						$total += $child_line_item->total();
1554
+					}
1555
+				} elseif ($child_line_item->type() === EEM_Line_Item::type_sub_total) {
1556
+					$total += $child_line_item->taxable_total();
1557
+				}
1558
+			}
1559
+		}
1560
+		return max($total, 0);
1561
+	}
1562
+
1563
+
1564
+	/**
1565
+	 * Gets the transaction for this line item
1566
+	 *
1567
+	 * @return EE_Base_Class|EE_Transaction
1568
+	 * @throws EE_Error
1569
+	 * @throws InvalidArgumentException
1570
+	 * @throws InvalidDataTypeException
1571
+	 * @throws InvalidInterfaceException
1572
+	 * @throws ReflectionException
1573
+	 */
1574
+	public function transaction()
1575
+	{
1576
+		return $this->get_first_related(EEM_Line_Item::OBJ_TYPE_TRANSACTION);
1577
+	}
1578
+
1579
+
1580
+	/**
1581
+	 * Saves this line item to the DB, and recursively saves its descendants.
1582
+	 * Because there currently is no proper parent-child relation on the model,
1583
+	 * save_this_and_cached() will NOT save the descendants.
1584
+	 * Also sets the transaction on this line item and all its descendants before saving
1585
+	 *
1586
+	 * @param int $txn_id if none is provided, assumes $this->TXN_ID()
1587
+	 * @return int count of items saved
1588
+	 * @throws EE_Error
1589
+	 * @throws InvalidArgumentException
1590
+	 * @throws InvalidDataTypeException
1591
+	 * @throws InvalidInterfaceException
1592
+	 * @throws ReflectionException
1593
+	 */
1594
+	public function save_this_and_descendants_to_txn($txn_id = null)
1595
+	{
1596
+		$count = 0;
1597
+		if (! $txn_id) {
1598
+			$txn_id = $this->TXN_ID();
1599
+		}
1600
+		$this->set_TXN_ID($txn_id);
1601
+		$children = $this->children();
1602
+		$count += $this->save()
1603
+			? 1
1604
+			: 0;
1605
+		foreach ($children as $child_line_item) {
1606
+			if ($child_line_item instanceof EE_Line_Item) {
1607
+				$child_line_item->set_parent_ID($this->ID());
1608
+				$count += $child_line_item->save_this_and_descendants_to_txn($txn_id);
1609
+			}
1610
+		}
1611
+		return $count;
1612
+	}
1613
+
1614
+
1615
+	/**
1616
+	 * Saves this line item to the DB, and recursively saves its descendants.
1617
+	 *
1618
+	 * @return int count of items saved
1619
+	 * @throws EE_Error
1620
+	 * @throws InvalidArgumentException
1621
+	 * @throws InvalidDataTypeException
1622
+	 * @throws InvalidInterfaceException
1623
+	 * @throws ReflectionException
1624
+	 */
1625
+	public function save_this_and_descendants()
1626
+	{
1627
+		$count = 0;
1628
+		$children = $this->children();
1629
+		$count += $this->save()
1630
+			? 1
1631
+			: 0;
1632
+		foreach ($children as $child_line_item) {
1633
+			if ($child_line_item instanceof EE_Line_Item) {
1634
+				$child_line_item->set_parent_ID($this->ID());
1635
+				$count += $child_line_item->save_this_and_descendants();
1636
+			}
1637
+		}
1638
+		return $count;
1639
+	}
1640
+
1641
+
1642
+	/**
1643
+	 * returns the cancellation line item if this item was cancelled
1644
+	 *
1645
+	 * @return EE_Line_Item[]
1646
+	 * @throws InvalidArgumentException
1647
+	 * @throws InvalidInterfaceException
1648
+	 * @throws InvalidDataTypeException
1649
+	 * @throws ReflectionException
1650
+	 * @throws EE_Error
1651
+	 */
1652
+	public function get_cancellations()
1653
+	{
1654
+		EE_Registry::instance()->load_helper('Line_Item');
1655
+		return EEH_Line_Item::get_descendants_of_type($this, EEM_Line_Item::type_cancellation);
1656
+	}
1657
+
1658
+
1659
+	/**
1660
+	 * If this item has an ID, then this saves it again to update the db
1661
+	 *
1662
+	 * @return int count of items saved
1663
+	 * @throws EE_Error
1664
+	 * @throws InvalidArgumentException
1665
+	 * @throws InvalidDataTypeException
1666
+	 * @throws InvalidInterfaceException
1667
+	 * @throws ReflectionException
1668
+	 */
1669
+	public function maybe_save()
1670
+	{
1671
+		if ($this->ID()) {
1672
+			return $this->save();
1673
+		}
1674
+		return false;
1675
+	}
1676
+
1677
+
1678
+	/**
1679
+	 * clears the cached children and parent from the line item
1680
+	 *
1681
+	 * @return void
1682
+	 */
1683
+	public function clear_related_line_item_cache()
1684
+	{
1685
+		$this->_children = array();
1686
+		$this->_parent = null;
1687
+	}
1688
+
1689
+
1690
+	/**
1691
+	 * @param bool $raw
1692
+	 * @return int
1693
+	 * @throws EE_Error
1694
+	 * @throws InvalidArgumentException
1695
+	 * @throws InvalidDataTypeException
1696
+	 * @throws InvalidInterfaceException
1697
+	 * @throws ReflectionException
1698
+	 */
1699
+	public function timestamp($raw = false)
1700
+	{
1701
+		return $raw
1702
+			? $this->get_raw('LIN_timestamp')
1703
+			: $this->get('LIN_timestamp');
1704
+	}
1705
+
1706
+
1707
+
1708
+
1709
+	/************************* DEPRECATED *************************/
1710
+	/**
1711
+	 * @deprecated 4.6.0
1712
+	 * @param string $type one of the constants on EEM_Line_Item
1713
+	 * @return EE_Line_Item[]
1714
+	 * @throws EE_Error
1715
+	 */
1716
+	protected function _get_descendants_of_type($type)
1717
+	{
1718
+		EE_Error::doing_it_wrong(
1719
+			'EE_Line_Item::_get_descendants_of_type()',
1720
+			sprintf(
1721
+				esc_html__('Method replaced with %1$s', 'event_espresso'),
1722
+				'EEH_Line_Item::get_descendants_of_type()'
1723
+			),
1724
+			'4.6.0'
1725
+		);
1726
+		return EEH_Line_Item::get_descendants_of_type($this, $type);
1727
+	}
1728
+
1729
+
1730
+	/**
1731
+	 * @deprecated 4.6.0
1732
+	 * @param string $type like one of the EEM_Line_Item::type_*
1733
+	 * @return EE_Line_Item
1734
+	 * @throws EE_Error
1735
+	 * @throws InvalidArgumentException
1736
+	 * @throws InvalidDataTypeException
1737
+	 * @throws InvalidInterfaceException
1738
+	 * @throws ReflectionException
1739
+	 */
1740
+	public function get_nearest_descendant_of_type($type)
1741
+	{
1742
+		EE_Error::doing_it_wrong(
1743
+			'EE_Line_Item::get_nearest_descendant_of_type()',
1744
+			sprintf(
1745
+				esc_html__('Method replaced with %1$s', 'event_espresso'),
1746
+				'EEH_Line_Item::get_nearest_descendant_of_type()'
1747
+			),
1748
+			'4.6.0'
1749
+		);
1750
+		return EEH_Line_Item::get_nearest_descendant_of_type($this, $type);
1751
+	}
1752 1752
 }
Please login to merge, or discard this patch.
admin_pages/transactions/Transactions_Admin_Page.core.php 1 patch
Indentation   +2558 added lines, -2558 removed lines patch added patch discarded remove patch
@@ -13,2562 +13,2562 @@
 block discarded – undo
13 13
 class Transactions_Admin_Page extends EE_Admin_Page
14 14
 {
15 15
 
16
-    /**
17
-     * @var EE_Transaction
18
-     */
19
-    private $_transaction;
20
-
21
-    /**
22
-     * @var EE_Session
23
-     */
24
-    private $_session;
25
-
26
-    /**
27
-     * @var array $_txn_status
28
-     */
29
-    private static $_txn_status;
30
-
31
-    /**
32
-     * @var array $_pay_status
33
-     */
34
-    private static $_pay_status;
35
-
36
-    /**
37
-     * @var array $_existing_reg_payment_REG_IDs
38
-     */
39
-    protected $_existing_reg_payment_REG_IDs;
40
-
41
-
42
-    /**
43
-     *    _init_page_props
44
-     *
45
-     * @return void
46
-     */
47
-    protected function _init_page_props()
48
-    {
49
-        $this->page_slug = TXN_PG_SLUG;
50
-        $this->page_label = esc_html__('Transactions', 'event_espresso');
51
-        $this->_admin_base_url = TXN_ADMIN_URL;
52
-        $this->_admin_base_path = TXN_ADMIN;
53
-    }
54
-
55
-
56
-    /**
57
-     *    _ajax_hooks
58
-     *
59
-     * @return void
60
-     */
61
-    protected function _ajax_hooks()
62
-    {
63
-        add_action('wp_ajax_espresso_apply_payment', array($this, 'apply_payments_or_refunds'));
64
-        add_action('wp_ajax_espresso_apply_refund', array($this, 'apply_payments_or_refunds'));
65
-        add_action('wp_ajax_espresso_delete_payment', array($this, 'delete_payment'));
66
-    }
67
-
68
-
69
-    /**
70
-     *    _define_page_props
71
-     *
72
-     * @return void
73
-     */
74
-    protected function _define_page_props()
75
-    {
76
-        $this->_admin_page_title = $this->page_label;
77
-        $this->_labels = array(
78
-            'buttons' => array(
79
-                'add'    => esc_html__('Add New Transaction', 'event_espresso'),
80
-                'edit'   => esc_html__('Edit Transaction', 'event_espresso'),
81
-                'delete' => esc_html__('Delete Transaction', 'event_espresso'),
82
-            ),
83
-        );
84
-    }
85
-
86
-
87
-    /**
88
-     *        grab url requests and route them
89
-     *
90
-     * @access private
91
-     * @return void
92
-     * @throws EE_Error
93
-     * @throws InvalidArgumentException
94
-     * @throws InvalidDataTypeException
95
-     * @throws InvalidInterfaceException
96
-     */
97
-    public function _set_page_routes()
98
-    {
99
-
100
-        $this->_set_transaction_status_array();
101
-
102
-        $txn_id = ! empty($this->_req_data['TXN_ID'])
103
-                  && ! is_array($this->_req_data['TXN_ID'])
104
-            ? $this->_req_data['TXN_ID']
105
-            : 0;
106
-
107
-        $this->_page_routes = array(
108
-
109
-            'default' => array(
110
-                'func'       => '_transactions_overview_list_table',
111
-                'capability' => 'ee_read_transactions',
112
-            ),
113
-
114
-            'view_transaction' => array(
115
-                'func'       => '_transaction_details',
116
-                'capability' => 'ee_read_transaction',
117
-                'obj_id'     => $txn_id,
118
-            ),
119
-
120
-            'send_payment_reminder' => array(
121
-                'func'       => '_send_payment_reminder',
122
-                'noheader'   => true,
123
-                'capability' => 'ee_send_message',
124
-            ),
125
-
126
-            'espresso_apply_payment' => array(
127
-                'func'       => 'apply_payments_or_refunds',
128
-                'noheader'   => true,
129
-                'capability' => 'ee_edit_payments',
130
-            ),
131
-
132
-            'espresso_apply_refund' => array(
133
-                'func'       => 'apply_payments_or_refunds',
134
-                'noheader'   => true,
135
-                'capability' => 'ee_edit_payments',
136
-            ),
137
-
138
-            'espresso_delete_payment' => array(
139
-                'func'       => 'delete_payment',
140
-                'noheader'   => true,
141
-                'capability' => 'ee_delete_payments',
142
-            ),
143
-
144
-            'espresso_recalculate_line_items' => array(
145
-                'func'       => 'recalculateLineItems',
146
-                'noheader'   => true,
147
-                'capability' => 'ee_edit_payments',
148
-            ),
149
-
150
-        );
151
-    }
152
-
153
-
154
-    protected function _set_page_config()
155
-    {
156
-        $this->_page_config = array(
157
-            'default'          => array(
158
-                'nav'           => array(
159
-                    'label' => esc_html__('Overview', 'event_espresso'),
160
-                    'order' => 10,
161
-                ),
162
-                'list_table'    => 'EE_Admin_Transactions_List_Table',
163
-                'help_tabs'     => array(
164
-                    'transactions_overview_help_tab'                       => array(
165
-                        'title'    => esc_html__('Transactions Overview', 'event_espresso'),
166
-                        'filename' => 'transactions_overview',
167
-                    ),
168
-                    'transactions_overview_table_column_headings_help_tab' => array(
169
-                        'title'    => esc_html__('Transactions Table Column Headings', 'event_espresso'),
170
-                        'filename' => 'transactions_overview_table_column_headings',
171
-                    ),
172
-                    'transactions_overview_views_filters_help_tab'         => array(
173
-                        'title'    => esc_html__('Transaction Views & Filters & Search', 'event_espresso'),
174
-                        'filename' => 'transactions_overview_views_filters_search',
175
-                    ),
176
-                ),
177
-                'help_tour'     => array('Transactions_Overview_Help_Tour'),
178
-                /**
179
-                 * commented out because currently we are not displaying tips for transaction list table status but this
180
-                 * may change in a later iteration so want to keep the code for then.
181
-                 */
182
-                // 'qtips' => array( 'Transactions_List_Table_Tips' ),
183
-                'require_nonce' => false,
184
-            ),
185
-            'view_transaction' => array(
186
-                'nav'       => array(
187
-                    'label'      => esc_html__('View Transaction', 'event_espresso'),
188
-                    'order'      => 5,
189
-                    'url'        => isset($this->_req_data['TXN_ID'])
190
-                        ? add_query_arg(array('TXN_ID' => $this->_req_data['TXN_ID']), $this->_current_page_view_url)
191
-                        : $this->_admin_base_url,
192
-                    'persistent' => false,
193
-                ),
194
-                'help_tabs' => array(
195
-                    'transactions_view_transaction_help_tab'                                              => array(
196
-                        'title'    => esc_html__('View Transaction', 'event_espresso'),
197
-                        'filename' => 'transactions_view_transaction',
198
-                    ),
199
-                    'transactions_view_transaction_transaction_details_table_help_tab'                    => array(
200
-                        'title'    => esc_html__('Transaction Details Table', 'event_espresso'),
201
-                        'filename' => 'transactions_view_transaction_transaction_details_table',
202
-                    ),
203
-                    'transactions_view_transaction_attendees_registered_help_tab'                         => array(
204
-                        'title'    => esc_html__('Attendees Registered', 'event_espresso'),
205
-                        'filename' => 'transactions_view_transaction_attendees_registered',
206
-                    ),
207
-                    'transactions_view_transaction_views_primary_registrant_billing_information_help_tab' => array(
208
-                        'title'    => esc_html__('Primary Registrant & Billing Information', 'event_espresso'),
209
-                        'filename' => 'transactions_view_transaction_primary_registrant_billing_information',
210
-                    ),
211
-                ),
212
-                'qtips'     => array('Transaction_Details_Tips'),
213
-                'help_tour' => array('Transaction_Details_Help_Tour'),
214
-                'metaboxes' => array('_transaction_details_metaboxes'),
215
-
216
-                'require_nonce' => false,
217
-            ),
218
-        );
219
-    }
220
-
221
-
222
-    /**
223
-     * The below methods aren't used by this class currently
224
-     */
225
-    protected function _add_screen_options()
226
-    {
227
-        // noop
228
-    }
229
-
230
-
231
-    protected function _add_feature_pointers()
232
-    {
233
-        // noop
234
-    }
235
-
236
-
237
-    public function admin_init()
238
-    {
239
-        // IF a registration was JUST added via the admin...
240
-        if (isset(
241
-            $this->_req_data['redirect_from'],
242
-            $this->_req_data['EVT_ID'],
243
-            $this->_req_data['event_name']
244
-        )) {
245
-            // then set a cookie so that we can block any attempts to use
246
-            // the back button as a way to enter another registration.
247
-            setcookie(
248
-                'ee_registration_added',
249
-                $this->_req_data['EVT_ID'],
250
-                time() + WEEK_IN_SECONDS,
251
-                '/'
252
-            );
253
-            // and update the global
254
-            $_COOKIE['ee_registration_added'] = $this->_req_data['EVT_ID'];
255
-        }
256
-        EE_Registry::$i18n_js_strings['invalid_server_response'] = esc_html__(
257
-            '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.',
258
-            'event_espresso'
259
-        );
260
-        EE_Registry::$i18n_js_strings['error_occurred'] = esc_html__(
261
-            'An error occurred! Please refresh the page and try again.',
262
-            'event_espresso'
263
-        );
264
-        EE_Registry::$i18n_js_strings['txn_status_array'] = self::$_txn_status;
265
-        EE_Registry::$i18n_js_strings['pay_status_array'] = self::$_pay_status;
266
-        EE_Registry::$i18n_js_strings['payments_total'] = esc_html__('Payments Total', 'event_espresso');
267
-        EE_Registry::$i18n_js_strings['transaction_overpaid'] = esc_html__(
268
-            'This transaction has been overpaid ! Payments Total',
269
-            'event_espresso'
270
-        );
271
-    }
272
-
273
-
274
-    public function admin_notices()
275
-    {
276
-        // noop
277
-    }
278
-
279
-
280
-    public function admin_footer_scripts()
281
-    {
282
-        // noop
283
-    }
284
-
285
-
286
-    /**
287
-     * _set_transaction_status_array
288
-     * sets list of transaction statuses
289
-     *
290
-     * @access private
291
-     * @return void
292
-     * @throws EE_Error
293
-     * @throws InvalidArgumentException
294
-     * @throws InvalidDataTypeException
295
-     * @throws InvalidInterfaceException
296
-     */
297
-    private function _set_transaction_status_array()
298
-    {
299
-        self::$_txn_status = EEM_Transaction::instance()->status_array(true);
300
-    }
301
-
302
-
303
-    /**
304
-     * get_transaction_status_array
305
-     * return the transaction status array for wp_list_table
306
-     *
307
-     * @access public
308
-     * @return array
309
-     */
310
-    public function get_transaction_status_array()
311
-    {
312
-        return self::$_txn_status;
313
-    }
314
-
315
-
316
-    /**
317
-     *    get list of payment statuses
318
-     *
319
-     * @access private
320
-     * @return void
321
-     * @throws EE_Error
322
-     * @throws InvalidArgumentException
323
-     * @throws InvalidDataTypeException
324
-     * @throws InvalidInterfaceException
325
-     */
326
-    private function _get_payment_status_array()
327
-    {
328
-        self::$_pay_status = EEM_Payment::instance()->status_array(true);
329
-        $this->_template_args['payment_status'] = self::$_pay_status;
330
-    }
331
-
332
-
333
-    /**
334
-     *    _add_screen_options_default
335
-     *
336
-     * @access protected
337
-     * @return void
338
-     * @throws InvalidArgumentException
339
-     * @throws InvalidDataTypeException
340
-     * @throws InvalidInterfaceException
341
-     */
342
-    protected function _add_screen_options_default()
343
-    {
344
-        $this->_per_page_screen_option();
345
-    }
346
-
347
-
348
-    /**
349
-     * load_scripts_styles
350
-     *
351
-     * @access public
352
-     * @return void
353
-     */
354
-    public function load_scripts_styles()
355
-    {
356
-        // enqueue style
357
-        wp_register_style(
358
-            'espresso_txn',
359
-            TXN_ASSETS_URL . 'espresso_transactions_admin.css',
360
-            array(),
361
-            EVENT_ESPRESSO_VERSION
362
-        );
363
-        wp_enqueue_style('espresso_txn');
364
-        // scripts
365
-        wp_register_script(
366
-            'espresso_txn',
367
-            TXN_ASSETS_URL . 'espresso_transactions_admin.js',
368
-            array(
369
-                'ee_admin_js',
370
-                'ee-datepicker',
371
-                'jquery-ui-datepicker',
372
-                'jquery-ui-draggable',
373
-                'ee-dialog',
374
-                'ee-accounting',
375
-                'ee-serialize-full-array',
376
-            ),
377
-            EVENT_ESPRESSO_VERSION,
378
-            true
379
-        );
380
-        wp_enqueue_script('espresso_txn');
381
-    }
382
-
383
-
384
-    /**
385
-     *    load_scripts_styles_view_transaction
386
-     *
387
-     * @access public
388
-     * @return void
389
-     */
390
-    public function load_scripts_styles_view_transaction()
391
-    {
392
-        // styles
393
-        wp_enqueue_style('espresso-ui-theme');
394
-    }
395
-
396
-
397
-    /**
398
-     *    load_scripts_styles_default
399
-     *
400
-     * @access public
401
-     * @return void
402
-     */
403
-    public function load_scripts_styles_default()
404
-    {
405
-        // styles
406
-        wp_enqueue_style('espresso-ui-theme');
407
-    }
408
-
409
-
410
-    /**
411
-     *    _set_list_table_views_default
412
-     *
413
-     * @access protected
414
-     * @return void
415
-     */
416
-    protected function _set_list_table_views_default()
417
-    {
418
-        $this->_views = array(
419
-            'all'        => array(
420
-                'slug'  => 'all',
421
-                'label' => esc_html__('View All Transactions', 'event_espresso'),
422
-                'count' => 0,
423
-            ),
424
-            'abandoned'  => array(
425
-                'slug'  => 'abandoned',
426
-                'label' => esc_html__('Abandoned Transactions', 'event_espresso'),
427
-                'count' => 0,
428
-            ),
429
-            'incomplete' => array(
430
-                'slug'  => 'incomplete',
431
-                'label' => esc_html__('Incomplete Transactions', 'event_espresso'),
432
-                'count' => 0,
433
-            ),
434
-        );
435
-        if (/**
436
-         * Filters whether a link to the "Failed Transactions" list table
437
-         * appears on the Transactions Admin Page list table.
438
-         * List display can be turned back on via the following:
439
-         * add_filter(
440
-         *     'FHEE__Transactions_Admin_Page___set_list_table_views_default__display_failed_txns_list',
441
-         *     '__return_true'
442
-         * );
443
-         *
444
-         * @since 4.9.70.p
445
-         * @param boolean                 $display_failed_txns_list
446
-         * @param Transactions_Admin_Page $this
447
-         */
448
-        apply_filters(
449
-            'FHEE__Transactions_Admin_Page___set_list_table_views_default__display_failed_txns_list',
450
-            false,
451
-            $this
452
-        )
453
-        ) {
454
-            $this->_views['failed'] = array(
455
-                'slug'  => 'failed',
456
-                'label' => esc_html__('Failed Transactions', 'event_espresso'),
457
-                'count' => 0,
458
-            );
459
-        }
460
-    }
461
-
462
-
463
-    /**
464
-     * _set_transaction_object
465
-     * This sets the _transaction property for the transaction details screen
466
-     *
467
-     * @access private
468
-     * @return void
469
-     * @throws EE_Error
470
-     * @throws InvalidArgumentException
471
-     * @throws RuntimeException
472
-     * @throws InvalidDataTypeException
473
-     * @throws InvalidInterfaceException
474
-     * @throws ReflectionException
475
-     */
476
-    private function _set_transaction_object()
477
-    {
478
-        if ($this->_transaction instanceof EE_Transaction) {
479
-            return;
480
-        } //get out we've already set the object
481
-
482
-        $TXN_ID = ! empty($this->_req_data['TXN_ID'])
483
-            ? absint($this->_req_data['TXN_ID'])
484
-            : false;
485
-
486
-        // get transaction object
487
-        $this->_transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
488
-        $this->_session = $this->_transaction instanceof EE_Transaction
489
-            ? $this->_transaction->session_data()
490
-            : null;
491
-        if ($this->_transaction instanceof EE_Transaction) {
492
-            $this->_transaction->verify_abandoned_transaction_status();
493
-        }
494
-
495
-        if (! $this->_transaction instanceof EE_Transaction) {
496
-            $error_msg = sprintf(
497
-                esc_html__(
498
-                    'An error occurred and the details for the transaction with the ID # %d could not be retrieved.',
499
-                    'event_espresso'
500
-                ),
501
-                $TXN_ID
502
-            );
503
-            EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
504
-        }
505
-    }
506
-
507
-
508
-    /**
509
-     *    _transaction_legend_items
510
-     *
511
-     * @access protected
512
-     * @return array
513
-     * @throws EE_Error
514
-     * @throws InvalidArgumentException
515
-     * @throws ReflectionException
516
-     * @throws InvalidDataTypeException
517
-     * @throws InvalidInterfaceException
518
-     */
519
-    protected function _transaction_legend_items()
520
-    {
521
-        EE_Registry::instance()->load_helper('MSG_Template');
522
-        $items = array();
523
-
524
-        if (EE_Registry::instance()->CAP->current_user_can(
525
-            'ee_read_global_messages',
526
-            'view_filtered_messages'
527
-        )) {
528
-            $related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
529
-            if (is_array($related_for_icon)
530
-                && isset($related_for_icon['css_class'], $related_for_icon['label'])
531
-            ) {
532
-                $items['view_related_messages'] = array(
533
-                    'class' => $related_for_icon['css_class'],
534
-                    'desc'  => $related_for_icon['label'],
535
-                );
536
-            }
537
-        }
538
-
539
-        $items = apply_filters(
540
-            'FHEE__Transactions_Admin_Page___transaction_legend_items__items',
541
-            array_merge(
542
-                $items,
543
-                array(
544
-                    'view_details'          => array(
545
-                        'class' => 'dashicons dashicons-cart',
546
-                        'desc'  => esc_html__('View Transaction Details', 'event_espresso'),
547
-                    ),
548
-                    'view_invoice'          => array(
549
-                        'class' => 'dashicons dashicons-media-spreadsheet',
550
-                        'desc'  => esc_html__('View Transaction Invoice', 'event_espresso'),
551
-                    ),
552
-                    'view_receipt'          => array(
553
-                        'class' => 'dashicons dashicons-media-default',
554
-                        'desc'  => esc_html__('View Transaction Receipt', 'event_espresso'),
555
-                    ),
556
-                    'view_registration'     => array(
557
-                        'class' => 'dashicons dashicons-clipboard',
558
-                        'desc'  => esc_html__('View Registration Details', 'event_espresso'),
559
-                    ),
560
-                    'payment_overview_link' => array(
561
-                        'class' => 'dashicons dashicons-money',
562
-                        'desc'  => esc_html__('Make Payment on Frontend', 'event_espresso'),
563
-                    ),
564
-                )
565
-            )
566
-        );
567
-
568
-        if (EEH_MSG_Template::is_mt_active('payment_reminder')
569
-            && EE_Registry::instance()->CAP->current_user_can(
570
-                'ee_send_message',
571
-                'espresso_transactions_send_payment_reminder'
572
-            )
573
-        ) {
574
-            $items['send_payment_reminder'] = array(
575
-                'class' => 'dashicons dashicons-email-alt',
576
-                'desc'  => esc_html__('Send Payment Reminder', 'event_espresso'),
577
-            );
578
-        } else {
579
-            $items['blank*'] = array(
580
-                'class' => '',
581
-                'desc'  => '',
582
-            );
583
-        }
584
-        $more_items = apply_filters(
585
-            'FHEE__Transactions_Admin_Page___transaction_legend_items__more_items',
586
-            array(
587
-                'overpaid'   => array(
588
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::overpaid_status_code,
589
-                    'desc'  => EEH_Template::pretty_status(
590
-                        EEM_Transaction::overpaid_status_code,
591
-                        false,
592
-                        'sentence'
593
-                    ),
594
-                ),
595
-                'complete'   => array(
596
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::complete_status_code,
597
-                    'desc'  => EEH_Template::pretty_status(
598
-                        EEM_Transaction::complete_status_code,
599
-                        false,
600
-                        'sentence'
601
-                    ),
602
-                ),
603
-                'incomplete' => array(
604
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::incomplete_status_code,
605
-                    'desc'  => EEH_Template::pretty_status(
606
-                        EEM_Transaction::incomplete_status_code,
607
-                        false,
608
-                        'sentence'
609
-                    ),
610
-                ),
611
-                'abandoned'  => array(
612
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::abandoned_status_code,
613
-                    'desc'  => EEH_Template::pretty_status(
614
-                        EEM_Transaction::abandoned_status_code,
615
-                        false,
616
-                        'sentence'
617
-                    ),
618
-                ),
619
-                'failed'     => array(
620
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::failed_status_code,
621
-                    'desc'  => EEH_Template::pretty_status(
622
-                        EEM_Transaction::failed_status_code,
623
-                        false,
624
-                        'sentence'
625
-                    ),
626
-                ),
627
-            )
628
-        );
629
-
630
-        return array_merge($items, $more_items);
631
-    }
632
-
633
-
634
-    /**
635
-     *    _transactions_overview_list_table
636
-     *
637
-     * @access protected
638
-     * @return void
639
-     * @throws DomainException
640
-     * @throws EE_Error
641
-     * @throws InvalidArgumentException
642
-     * @throws InvalidDataTypeException
643
-     * @throws InvalidInterfaceException
644
-     * @throws ReflectionException
645
-     */
646
-    protected function _transactions_overview_list_table()
647
-    {
648
-        $this->_admin_page_title = esc_html__('Transactions', 'event_espresso');
649
-        $event = isset($this->_req_data['EVT_ID'])
650
-            ? EEM_Event::instance()->get_one_by_ID($this->_req_data['EVT_ID'])
651
-            : null;
652
-        $this->_template_args['admin_page_header'] = $event instanceof EE_Event
653
-            ? sprintf(
654
-                esc_html__(
655
-                    '%sViewing Transactions for the Event: %s%s',
656
-                    'event_espresso'
657
-                ),
658
-                '<h3>',
659
-                '<a href="'
660
-                . EE_Admin_Page::add_query_args_and_nonce(
661
-                    array('action' => 'edit', 'post' => $event->ID()),
662
-                    EVENTS_ADMIN_URL
663
-                )
664
-                . '" title="'
665
-                . esc_attr__(
666
-                    'Click to Edit event',
667
-                    'event_espresso'
668
-                )
669
-                . '">' . $event->name() . '</a>',
670
-                '</h3>'
671
-            )
672
-            : '';
673
-        $this->_template_args['after_list_table'] = $this->_display_legend($this->_transaction_legend_items());
674
-        $this->display_admin_list_table_page_with_no_sidebar();
675
-    }
676
-
677
-
678
-    /**
679
-     *    _transaction_details
680
-     * generates HTML for the View Transaction Details Admin page
681
-     *
682
-     * @access protected
683
-     * @return void
684
-     * @throws DomainException
685
-     * @throws EE_Error
686
-     * @throws InvalidArgumentException
687
-     * @throws InvalidDataTypeException
688
-     * @throws InvalidInterfaceException
689
-     * @throws RuntimeException
690
-     * @throws ReflectionException
691
-     */
692
-    protected function _transaction_details()
693
-    {
694
-        do_action('AHEE__Transactions_Admin_Page__transaction_details__start', $this->_transaction);
695
-
696
-        $this->_set_transaction_status_array();
697
-
698
-        $this->_template_args = array();
699
-        $this->_template_args['transactions_page'] = $this->_wp_page_slug;
700
-
701
-        $this->_set_transaction_object();
702
-
703
-        if (! $this->_transaction instanceof EE_Transaction) {
704
-            return;
705
-        }
706
-        $primary_registration = $this->_transaction->primary_registration();
707
-        $attendee = $primary_registration instanceof EE_Registration
708
-            ? $primary_registration->attendee()
709
-            : null;
710
-
711
-        $this->_template_args['txn_nmbr']['value'] = $this->_transaction->ID();
712
-        $this->_template_args['txn_nmbr']['label'] = esc_html__('Transaction Number', 'event_espresso');
713
-
714
-        $this->_template_args['txn_datetime']['value'] = $this->_transaction->get_i18n_datetime('TXN_timestamp');
715
-        $this->_template_args['txn_datetime']['label'] = esc_html__('Date', 'event_espresso');
716
-
717
-        $this->_template_args['txn_status']['value'] = self::$_txn_status[ $this->_transaction->status_ID() ];
718
-        $this->_template_args['txn_status']['label'] = esc_html__('Transaction Status', 'event_espresso');
719
-        $this->_template_args['txn_status']['class'] = 'status-' . $this->_transaction->status_ID();
720
-
721
-        $this->_template_args['grand_total'] = $this->_transaction->total();
722
-        $this->_template_args['total_paid'] = $this->_transaction->paid();
723
-
724
-        $amount_due = $this->_transaction->total() - $this->_transaction->paid();
725
-        $this->_template_args['amount_due'] = EEH_Template::format_currency(
726
-            $amount_due,
727
-            true
728
-        );
729
-        if (EE_Registry::instance()->CFG->currency->sign_b4) {
730
-            $this->_template_args['amount_due'] = EE_Registry::instance()->CFG->currency->sign
731
-                                                  . $this->_template_args['amount_due'];
732
-        } else {
733
-            $this->_template_args['amount_due'] .= EE_Registry::instance()->CFG->currency->sign;
734
-        }
735
-        $this->_template_args['amount_due_class'] = '';
736
-
737
-        if ($this->_transaction->paid() === $this->_transaction->total()) {
738
-            // paid in full
739
-            $this->_template_args['amount_due'] = false;
740
-        } elseif ($this->_transaction->paid() > $this->_transaction->total()) {
741
-            // overpaid
742
-            $this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn';
743
-        } elseif ($this->_transaction->total() > (float) 0) {
744
-            if ($this->_transaction->paid() > (float) 0) {
745
-                // monies owing
746
-                $this->_template_args['amount_due_class'] = 'txn-overview-part-payment-spn';
747
-            } elseif ($this->_transaction->paid() === (float) 0) {
748
-                // no payments made yet
749
-                $this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn';
750
-            }
751
-        } elseif ($this->_transaction->total() === (float) 0) {
752
-            // free event
753
-            $this->_template_args['amount_due'] = false;
754
-        }
755
-
756
-        $payment_method = $this->_transaction->payment_method();
757
-
758
-        $this->_template_args['method_of_payment_name'] = $payment_method instanceof EE_Payment_Method
759
-            ? $payment_method->admin_name()
760
-            : esc_html__('Unknown', 'event_espresso');
761
-
762
-        $this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
763
-        // link back to overview
764
-        $this->_template_args['txn_overview_url'] = ! empty($_SERVER['HTTP_REFERER'])
765
-            ? $_SERVER['HTTP_REFERER']
766
-            : TXN_ADMIN_URL;
767
-
768
-
769
-        // next link
770
-        $next_txn = $this->_transaction->next(
771
-            null,
772
-            array(array('STS_ID' => array('!=', EEM_Transaction::failed_status_code))),
773
-            'TXN_ID'
774
-        );
775
-        $this->_template_args['next_transaction'] = $next_txn
776
-            ? $this->_next_link(
777
-                EE_Admin_Page::add_query_args_and_nonce(
778
-                    array('action' => 'view_transaction', 'TXN_ID' => $next_txn['TXN_ID']),
779
-                    TXN_ADMIN_URL
780
-                ),
781
-                'dashicons dashicons-arrow-right ee-icon-size-22'
782
-            )
783
-            : '';
784
-        // previous link
785
-        $previous_txn = $this->_transaction->previous(
786
-            null,
787
-            array(array('STS_ID' => array('!=', EEM_Transaction::failed_status_code))),
788
-            'TXN_ID'
789
-        );
790
-        $this->_template_args['previous_transaction'] = $previous_txn
791
-            ? $this->_previous_link(
792
-                EE_Admin_Page::add_query_args_and_nonce(
793
-                    array('action' => 'view_transaction', 'TXN_ID' => $previous_txn['TXN_ID']),
794
-                    TXN_ADMIN_URL
795
-                ),
796
-                'dashicons dashicons-arrow-left ee-icon-size-22'
797
-            )
798
-            : '';
799
-
800
-        // were we just redirected here after adding a new registration ???
801
-        if (isset(
802
-            $this->_req_data['redirect_from'],
803
-            $this->_req_data['EVT_ID'],
804
-            $this->_req_data['event_name']
805
-        )) {
806
-            if (EE_Registry::instance()->CAP->current_user_can(
807
-                'ee_edit_registrations',
808
-                'espresso_registrations_new_registration',
809
-                $this->_req_data['EVT_ID']
810
-            )) {
811
-                $this->_admin_page_title .= '<a id="add-new-registration" class="add-new-h2 button-primary" href="';
812
-                $this->_admin_page_title .= EE_Admin_Page::add_query_args_and_nonce(
813
-                    array(
814
-                        'page'     => 'espresso_registrations',
815
-                        'action'   => 'new_registration',
816
-                        'return'   => 'default',
817
-                        'TXN_ID'   => $this->_transaction->ID(),
818
-                        'event_id' => $this->_req_data['EVT_ID'],
819
-                    ),
820
-                    REG_ADMIN_URL
821
-                );
822
-                $this->_admin_page_title .= '">';
823
-
824
-                $this->_admin_page_title .= sprintf(
825
-                    esc_html__('Add Another New Registration to Event: "%1$s" ?', 'event_espresso'),
826
-                    htmlentities(urldecode($this->_req_data['event_name']), ENT_QUOTES, 'UTF-8')
827
-                );
828
-                $this->_admin_page_title .= '</a>';
829
-            }
830
-            EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
831
-        }
832
-        // grab messages at the last second
833
-        $this->_template_args['notices'] = EE_Error::get_notices();
834
-        // path to template
835
-        $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_header.template.php';
836
-        $this->_template_args['admin_page_header'] = EEH_Template::display_template(
837
-            $template_path,
838
-            $this->_template_args,
839
-            true
840
-        );
841
-
842
-        // the details template wrapper
843
-        $this->display_admin_page_with_sidebar();
844
-    }
845
-
846
-
847
-    /**
848
-     *        _transaction_details_metaboxes
849
-     *
850
-     * @access protected
851
-     * @return void
852
-     * @throws EE_Error
853
-     * @throws InvalidArgumentException
854
-     * @throws InvalidDataTypeException
855
-     * @throws InvalidInterfaceException
856
-     * @throws RuntimeException
857
-     * @throws ReflectionException
858
-     */
859
-    protected function _transaction_details_metaboxes()
860
-    {
861
-
862
-        $this->_set_transaction_object();
863
-
864
-        if (! $this->_transaction instanceof EE_Transaction) {
865
-            return;
866
-        }
867
-        add_meta_box(
868
-            'edit-txn-details-mbox',
869
-            esc_html__('Transaction Details', 'event_espresso'),
870
-            array($this, 'txn_details_meta_box'),
871
-            $this->_wp_page_slug,
872
-            'normal',
873
-            'high'
874
-        );
875
-        add_meta_box(
876
-            'edit-txn-attendees-mbox',
877
-            esc_html__('Attendees Registered in this Transaction', 'event_espresso'),
878
-            array($this, 'txn_attendees_meta_box'),
879
-            $this->_wp_page_slug,
880
-            'normal',
881
-            'high',
882
-            array('TXN_ID' => $this->_transaction->ID())
883
-        );
884
-        add_meta_box(
885
-            'edit-txn-registrant-mbox',
886
-            esc_html__('Primary Contact', 'event_espresso'),
887
-            array($this, 'txn_registrant_side_meta_box'),
888
-            $this->_wp_page_slug,
889
-            'side',
890
-            'high'
891
-        );
892
-        add_meta_box(
893
-            'edit-txn-billing-info-mbox',
894
-            esc_html__('Billing Information', 'event_espresso'),
895
-            array($this, 'txn_billing_info_side_meta_box'),
896
-            $this->_wp_page_slug,
897
-            'side',
898
-            'high'
899
-        );
900
-    }
901
-
902
-
903
-    /**
904
-     * Callback for transaction actions metabox.
905
-     *
906
-     * @param EE_Transaction|null $transaction
907
-     * @return string
908
-     * @throws DomainException
909
-     * @throws EE_Error
910
-     * @throws InvalidArgumentException
911
-     * @throws InvalidDataTypeException
912
-     * @throws InvalidInterfaceException
913
-     * @throws ReflectionException
914
-     * @throws RuntimeException
915
-     */
916
-    public function getActionButtons(EE_Transaction $transaction = null)
917
-    {
918
-        $content = '';
919
-        $actions = array();
920
-        if (! $transaction instanceof EE_Transaction) {
921
-            return $content;
922
-        }
923
-        /** @var EE_Registration $primary_registration */
924
-        $primary_registration = $transaction->primary_registration();
925
-        $attendee = $primary_registration instanceof EE_Registration
926
-            ? $primary_registration->attendee()
927
-            : null;
928
-
929
-        if ($attendee instanceof EE_Attendee
930
-            && EE_Registry::instance()->CAP->current_user_can(
931
-                'ee_send_message',
932
-                'espresso_transactions_send_payment_reminder'
933
-            )
934
-        ) {
935
-            $actions['payment_reminder'] =
936
-                EEH_MSG_Template::is_mt_active('payment_reminder')
937
-                && $this->_transaction->status_ID() !== EEM_Transaction::complete_status_code
938
-                && $this->_transaction->status_ID() !== EEM_Transaction::overpaid_status_code
939
-                    ? EEH_Template::get_button_or_link(
940
-                        EE_Admin_Page::add_query_args_and_nonce(
941
-                            array(
942
-                                'action'      => 'send_payment_reminder',
943
-                                'TXN_ID'      => $this->_transaction->ID(),
944
-                                'redirect_to' => 'view_transaction',
945
-                            ),
946
-                            TXN_ADMIN_URL
947
-                        ),
948
-                        esc_html__(' Send Payment Reminder', 'event_espresso'),
949
-                        'button secondary-button',
950
-                        'dashicons dashicons-email-alt'
951
-                    )
952
-                    : '';
953
-        }
954
-
955
-        if (EE_Registry::instance()->CAP->current_user_can(
956
-            'ee_edit_payments',
957
-            'espresso_transactions_recalculate_line_items'
958
-        )
959
-        ) {
960
-            $actions['recalculate_line_items'] = EEH_Template::get_button_or_link(
961
-                EE_Admin_Page::add_query_args_and_nonce(
962
-                    array(
963
-                        'action'      => 'espresso_recalculate_line_items',
964
-                        'TXN_ID'      => $this->_transaction->ID(),
965
-                        'redirect_to' => 'view_transaction',
966
-                    ),
967
-                    TXN_ADMIN_URL
968
-                ),
969
-                esc_html__(' Recalculate Taxes and Total', 'event_espresso'),
970
-                'button secondary-button',
971
-                'dashicons dashicons-update'
972
-            );
973
-        }
974
-
975
-        if ($primary_registration instanceof EE_Registration
976
-            && EEH_MSG_Template::is_mt_active('receipt')
977
-        ) {
978
-            $actions['receipt'] = EEH_Template::get_button_or_link(
979
-                $primary_registration->receipt_url(),
980
-                esc_html__('View Receipt', 'event_espresso'),
981
-                'button secondary-button',
982
-                'dashicons dashicons-media-default'
983
-            );
984
-        }
985
-
986
-        if ($primary_registration instanceof EE_Registration
987
-            && EEH_MSG_Template::is_mt_active('invoice')
988
-        ) {
989
-            $actions['invoice'] = EEH_Template::get_button_or_link(
990
-                $primary_registration->invoice_url(),
991
-                esc_html__('View Invoice', 'event_espresso'),
992
-                'button secondary-button',
993
-                'dashicons dashicons-media-spreadsheet'
994
-            );
995
-        }
996
-        $actions = array_filter(
997
-            apply_filters('FHEE__Transactions_Admin_Page__getActionButtons__actions', $actions, $transaction)
998
-        );
999
-        if ($actions) {
1000
-            $content = '<ul>';
1001
-            $content .= '<li>' . implode('</li><li>', $actions) . '</li>';
1002
-            $content .= '</uL>';
1003
-        }
1004
-        return $content;
1005
-    }
1006
-
1007
-
1008
-    /**
1009
-     * txn_details_meta_box
1010
-     * generates HTML for the Transaction main meta box
1011
-     *
1012
-     * @return void
1013
-     * @throws DomainException
1014
-     * @throws EE_Error
1015
-     * @throws InvalidArgumentException
1016
-     * @throws InvalidDataTypeException
1017
-     * @throws InvalidInterfaceException
1018
-     * @throws RuntimeException
1019
-     * @throws ReflectionException
1020
-     */
1021
-    public function txn_details_meta_box()
1022
-    {
1023
-        $this->_set_transaction_object();
1024
-        $this->_template_args['TXN_ID'] = $this->_transaction->ID();
1025
-        $this->_template_args['attendee'] = $this->_transaction->primary_registration() instanceof EE_Registration
1026
-            ? $this->_transaction->primary_registration()->attendee()
1027
-            : null;
1028
-        $this->_template_args['can_edit_payments'] = EE_Registry::instance()->CAP->current_user_can(
1029
-            'ee_edit_payments',
1030
-            'apply_payment_or_refund_from_registration_details'
1031
-        );
1032
-        $this->_template_args['can_delete_payments'] = EE_Registry::instance()->CAP->current_user_can(
1033
-            'ee_delete_payments',
1034
-            'delete_payment_from_registration_details'
1035
-        );
1036
-
1037
-        // get line table
1038
-        EEH_Autoloader::register_line_item_display_autoloaders();
1039
-        $Line_Item_Display = new EE_Line_Item_Display(
1040
-            'admin_table',
1041
-            'EE_Admin_Table_Line_Item_Display_Strategy'
1042
-        );
1043
-        $this->_template_args['line_item_table'] = $Line_Item_Display->display_line_item(
1044
-            $this->_transaction->total_line_item()
1045
-        );
1046
-        $this->_template_args['REG_code'] = $this->_transaction->primary_registration()->reg_code();
1047
-
1048
-        // process taxes
1049
-        $taxes = $this->_transaction->line_items(array(array('LIN_type' => EEM_Line_Item::type_tax)));
1050
-        $this->_template_args['taxes'] = ! empty($taxes) ? $taxes : false;
1051
-
1052
-        $this->_template_args['grand_total'] = EEH_Template::format_currency(
1053
-            $this->_transaction->total(),
1054
-            false,
1055
-            false
1056
-        );
1057
-        $this->_template_args['grand_raw_total'] = $this->_transaction->total();
1058
-        $this->_template_args['TXN_status'] = $this->_transaction->status_ID();
1059
-
1060
-        // process payment details
1061
-        $payments = $this->_transaction->payments();
1062
-        if (! empty($payments)) {
1063
-            $this->_template_args['payments'] = $payments;
1064
-            $this->_template_args['existing_reg_payments'] = $this->_get_registration_payment_IDs($payments);
1065
-        } else {
1066
-            $this->_template_args['payments'] = false;
1067
-            $this->_template_args['existing_reg_payments'] = array();
1068
-        }
1069
-
1070
-        $this->_template_args['edit_payment_url'] = add_query_arg(array('action' => 'edit_payment'), TXN_ADMIN_URL);
1071
-        $this->_template_args['delete_payment_url'] = add_query_arg(
1072
-            array('action' => 'espresso_delete_payment'),
1073
-            TXN_ADMIN_URL
1074
-        );
1075
-
1076
-        if (isset($txn_details['invoice_number'])) {
1077
-            $this->_template_args['txn_details']['invoice_number']['value'] = $this->_template_args['REG_code'];
1078
-            $this->_template_args['txn_details']['invoice_number']['label'] = esc_html__(
1079
-                'Invoice Number',
1080
-                'event_espresso'
1081
-            );
1082
-        }
1083
-
1084
-        $this->_template_args['txn_details']['registration_session']['value'] = $this->_transaction
1085
-            ->primary_registration()
1086
-            ->session_ID();
1087
-        $this->_template_args['txn_details']['registration_session']['label'] = esc_html__(
1088
-            'Registration Session',
1089
-            'event_espresso'
1090
-        );
1091
-
1092
-        $this->_template_args['txn_details']['ip_address']['value'] = isset($this->_session['ip_address'])
1093
-            ? $this->_session['ip_address']
1094
-            : '';
1095
-        $this->_template_args['txn_details']['ip_address']['label'] = esc_html__(
1096
-            'Transaction placed from IP',
1097
-            'event_espresso'
1098
-        );
1099
-
1100
-        $this->_template_args['txn_details']['user_agent']['value'] = isset($this->_session['user_agent'])
1101
-            ? $this->_session['user_agent']
1102
-            : '';
1103
-        $this->_template_args['txn_details']['user_agent']['label'] = esc_html__(
1104
-            'Registrant User Agent',
1105
-            'event_espresso'
1106
-        );
1107
-
1108
-        $reg_steps = '<ul>';
1109
-        foreach ($this->_transaction->reg_steps() as $reg_step => $reg_step_status) {
1110
-            if ($reg_step_status === true) {
1111
-                $reg_steps .= '<li style="color:#70cc50">'
1112
-                              . sprintf(
1113
-                                  esc_html__('%1$s : Completed', 'event_espresso'),
1114
-                                  ucwords(str_replace('_', ' ', $reg_step))
1115
-                              )
1116
-                              . '</li>';
1117
-            } elseif (is_numeric($reg_step_status) && $reg_step_status !== false) {
1118
-                $reg_steps .= '<li style="color:#2EA2CC">'
1119
-                              . sprintf(
1120
-                                  esc_html__('%1$s : Initiated %2$s', 'event_espresso'),
1121
-                                  ucwords(str_replace('_', ' ', $reg_step)),
1122
-                                  date(
1123
-                                      get_option('date_format') . ' ' . get_option('time_format'),
1124
-                                      $reg_step_status + (get_option('gmt_offset') * HOUR_IN_SECONDS)
1125
-                                  )
1126
-                              )
1127
-                              . '</li>';
1128
-            } else {
1129
-                $reg_steps .= '<li style="color:#E76700">'
1130
-                              . sprintf(
1131
-                                  esc_html__('%1$s : Never Initiated', 'event_espresso'),
1132
-                                  ucwords(str_replace('_', ' ', $reg_step))
1133
-                              )
1134
-                              . '</li>';
1135
-            }
1136
-        }
1137
-        $reg_steps .= '</ul>';
1138
-        $this->_template_args['txn_details']['reg_steps']['value'] = $reg_steps;
1139
-        $this->_template_args['txn_details']['reg_steps']['label'] = esc_html__(
1140
-            'Registration Step Progress',
1141
-            'event_espresso'
1142
-        );
1143
-
1144
-
1145
-        $this->_get_registrations_to_apply_payment_to();
1146
-        $this->_get_payment_methods($payments);
1147
-        $this->_get_payment_status_array();
1148
-        $this->_get_reg_status_selection(); // sets up the template args for the reg status array for the transaction.
1149
-
1150
-        $this->_template_args['transaction_form_url'] = add_query_arg(
1151
-            array(
1152
-                'action'  => 'edit_transaction',
1153
-                'process' => 'transaction',
1154
-            ),
1155
-            TXN_ADMIN_URL
1156
-        );
1157
-        $this->_template_args['apply_payment_form_url'] = add_query_arg(
1158
-            array(
1159
-                'page'   => 'espresso_transactions',
1160
-                'action' => 'espresso_apply_payment',
1161
-            ),
1162
-            WP_AJAX_URL
1163
-        );
1164
-        $this->_template_args['delete_payment_form_url'] = add_query_arg(
1165
-            array(
1166
-                'page'   => 'espresso_transactions',
1167
-                'action' => 'espresso_delete_payment',
1168
-            ),
1169
-            WP_AJAX_URL
1170
-        );
1171
-
1172
-        $this->_template_args['action_buttons'] = $this->getActionButtons($this->_transaction);
1173
-
1174
-        // 'espresso_delete_payment_nonce'
1175
-
1176
-        $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_txn_details.template.php';
1177
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);
1178
-    }
1179
-
1180
-
1181
-    /**
1182
-     * _get_registration_payment_IDs
1183
-     *    generates an array of Payment IDs and their corresponding Registration IDs
1184
-     *
1185
-     * @access protected
1186
-     * @param EE_Payment[] $payments
1187
-     * @return array
1188
-     * @throws EE_Error
1189
-     * @throws InvalidArgumentException
1190
-     * @throws InvalidDataTypeException
1191
-     * @throws InvalidInterfaceException
1192
-     * @throws ReflectionException
1193
-     */
1194
-    protected function _get_registration_payment_IDs($payments = array())
1195
-    {
1196
-        $existing_reg_payments = array();
1197
-        // get all reg payments for these payments
1198
-        $reg_payments = EEM_Registration_Payment::instance()->get_all(
1199
-            array(
1200
-                array(
1201
-                    'PAY_ID' => array(
1202
-                        'IN',
1203
-                        array_keys($payments),
1204
-                    ),
1205
-                ),
1206
-            )
1207
-        );
1208
-        if (! empty($reg_payments)) {
1209
-            foreach ($payments as $payment) {
1210
-                if (! $payment instanceof EE_Payment) {
1211
-                    continue;
1212
-                } elseif (! isset($existing_reg_payments[ $payment->ID() ])) {
1213
-                    $existing_reg_payments[ $payment->ID() ] = array();
1214
-                }
1215
-                foreach ($reg_payments as $reg_payment) {
1216
-                    if ($reg_payment instanceof EE_Registration_Payment
1217
-                        && $reg_payment->payment_ID() === $payment->ID()
1218
-                    ) {
1219
-                        $existing_reg_payments[ $payment->ID() ][] = $reg_payment->registration_ID();
1220
-                    }
1221
-                }
1222
-            }
1223
-        }
1224
-
1225
-        return $existing_reg_payments;
1226
-    }
1227
-
1228
-
1229
-    /**
1230
-     * _get_registrations_to_apply_payment_to
1231
-     *    generates HTML for displaying a series of checkboxes in the admin payment modal window
1232
-     * which allows the admin to only apply the payment to the specific registrations
1233
-     *
1234
-     * @access protected
1235
-     * @return void
1236
-     * @throws EE_Error
1237
-     * @throws InvalidArgumentException
1238
-     * @throws InvalidDataTypeException
1239
-     * @throws InvalidInterfaceException
1240
-     * @throws ReflectionException
1241
-     */
1242
-    protected function _get_registrations_to_apply_payment_to()
1243
-    {
1244
-        // we want any registration with an active status (ie: not deleted or cancelled)
1245
-        $query_params = array(
1246
-            array(
1247
-                'STS_ID' => array(
1248
-                    'IN',
1249
-                    array(
1250
-                        EEM_Registration::status_id_approved,
1251
-                        EEM_Registration::status_id_pending_payment,
1252
-                        EEM_Registration::status_id_not_approved,
1253
-                    ),
1254
-                ),
1255
-            ),
1256
-        );
1257
-        $registrations_to_apply_payment_to = EEH_HTML::br() . EEH_HTML::div(
1258
-            '',
1259
-            'txn-admin-apply-payment-to-registrations-dv',
1260
-            '',
1261
-            'clear: both; margin: 1.5em 0 0; display: none;'
1262
-        );
1263
-        $registrations_to_apply_payment_to .= EEH_HTML::br() . EEH_HTML::div('', '', 'admin-primary-mbox-tbl-wrap');
1264
-        $registrations_to_apply_payment_to .= EEH_HTML::table('', '', 'admin-primary-mbox-tbl');
1265
-        $registrations_to_apply_payment_to .= EEH_HTML::thead(
1266
-            EEH_HTML::tr(
1267
-                EEH_HTML::th(esc_html__('ID', 'event_espresso')) .
1268
-                EEH_HTML::th(esc_html__('Registrant', 'event_espresso')) .
1269
-                EEH_HTML::th(esc_html__('Ticket', 'event_espresso')) .
1270
-                EEH_HTML::th(esc_html__('Event', 'event_espresso')) .
1271
-                EEH_HTML::th(esc_html__('Paid', 'event_espresso'), '', 'txn-admin-payment-paid-td jst-cntr') .
1272
-                EEH_HTML::th(esc_html__('Owing', 'event_espresso'), '', 'txn-admin-payment-owing-td jst-cntr') .
1273
-                EEH_HTML::th(esc_html__('Apply', 'event_espresso'), '', 'jst-cntr')
1274
-            )
1275
-        );
1276
-        $registrations_to_apply_payment_to .= EEH_HTML::tbody();
1277
-        // get registrations for TXN
1278
-        $registrations = $this->_transaction->registrations($query_params);
1279
-        $existing_reg_payments = $this->_template_args['existing_reg_payments'];
1280
-        foreach ($registrations as $registration) {
1281
-            if ($registration instanceof EE_Registration) {
1282
-                $attendee_name = $registration->attendee() instanceof EE_Attendee
1283
-                    ? $registration->attendee()->full_name()
1284
-                    : esc_html__('Unknown Attendee', 'event_espresso');
1285
-                $owing = $registration->final_price() - $registration->paid();
1286
-                $taxable = $registration->ticket()->taxable()
1287
-                    ? ' <span class="smaller-text lt-grey-text"> ' . esc_html__('+ tax', 'event_espresso') . '</span>'
1288
-                    : '';
1289
-                $checked = empty($existing_reg_payments)
1290
-                           || in_array($registration->ID(), $existing_reg_payments, true)
1291
-                    ? ' checked="checked"'
1292
-                    : '';
1293
-                $disabled = $registration->final_price() > 0 ? '' : ' disabled';
1294
-                $registrations_to_apply_payment_to .= EEH_HTML::tr(
1295
-                    EEH_HTML::td($registration->ID()) .
1296
-                    EEH_HTML::td($attendee_name) .
1297
-                    EEH_HTML::td(
1298
-                        $registration->ticket()->name() . ' : ' . $registration->ticket()->pretty_price() . $taxable
1299
-                    ) .
1300
-                    EEH_HTML::td($registration->event_name()) .
1301
-                    EEH_HTML::td($registration->pretty_paid(), '', 'txn-admin-payment-paid-td jst-cntr') .
1302
-                    EEH_HTML::td(
1303
-                        EEH_Template::format_currency($owing),
1304
-                        '',
1305
-                        'txn-admin-payment-owing-td jst-cntr'
1306
-                    ) .
1307
-                    EEH_HTML::td(
1308
-                        '<input type="checkbox" value="' . $registration->ID()
1309
-                        . '" name="txn_admin_payment[registrations]"'
1310
-                        . $checked . $disabled . '>',
1311
-                        '',
1312
-                        'jst-cntr'
1313
-                    ),
1314
-                    'apply-payment-registration-row-' . $registration->ID()
1315
-                );
1316
-            }
1317
-        }
1318
-        $registrations_to_apply_payment_to .= EEH_HTML::tbodyx();
1319
-        $registrations_to_apply_payment_to .= EEH_HTML::tablex();
1320
-        $registrations_to_apply_payment_to .= EEH_HTML::divx();
1321
-        $registrations_to_apply_payment_to .= EEH_HTML::p(
1322
-            esc_html__(
1323
-                '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.',
1324
-                'event_espresso'
1325
-            ),
1326
-            '',
1327
-            'clear description'
1328
-        );
1329
-        $registrations_to_apply_payment_to .= EEH_HTML::divx();
1330
-        $this->_template_args['registrations_to_apply_payment_to'] = $registrations_to_apply_payment_to;
1331
-    }
1332
-
1333
-
1334
-    /**
1335
-     * _get_reg_status_selection
1336
-     *
1337
-     * @todo   this will need to be adjusted either once MER comes along OR we move default reg status to tickets
1338
-     *         instead of events.
1339
-     * @access protected
1340
-     * @return void
1341
-     * @throws EE_Error
1342
-     */
1343
-    protected function _get_reg_status_selection()
1344
-    {
1345
-        // first get all possible statuses
1346
-        $statuses = EEM_Registration::reg_status_array(array(), true);
1347
-        // let's add a "don't change" option.
1348
-        $status_array['NAN'] = esc_html__('Leave the Same', 'event_espresso');
1349
-        $status_array = array_merge($status_array, $statuses);
1350
-        $this->_template_args['status_change_select'] = EEH_Form_Fields::select_input(
1351
-            'txn_reg_status_change[reg_status]',
1352
-            $status_array,
1353
-            'NAN',
1354
-            'id="txn-admin-payment-reg-status-inp"',
1355
-            'txn-reg-status-change-reg-status'
1356
-        );
1357
-        $this->_template_args['delete_status_change_select'] = EEH_Form_Fields::select_input(
1358
-            'delete_txn_reg_status_change[reg_status]',
1359
-            $status_array,
1360
-            'NAN',
1361
-            'delete-txn-admin-payment-reg-status-inp',
1362
-            'delete-txn-reg-status-change-reg-status'
1363
-        );
1364
-    }
1365
-
1366
-
1367
-    /**
1368
-     *    _get_payment_methods
1369
-     * Gets all the payment methods available generally, or the ones that are already
1370
-     * selected on these payments (in case their payment methods are no longer active).
1371
-     * Has the side-effect of updating the template args' payment_methods item
1372
-     *
1373
-     * @access private
1374
-     * @param EE_Payment[] to show on this page
1375
-     * @return void
1376
-     * @throws EE_Error
1377
-     * @throws InvalidArgumentException
1378
-     * @throws InvalidDataTypeException
1379
-     * @throws InvalidInterfaceException
1380
-     * @throws ReflectionException
1381
-     */
1382
-    private function _get_payment_methods($payments = array())
1383
-    {
1384
-        $payment_methods_of_payments = array();
1385
-        foreach ($payments as $payment) {
1386
-            if ($payment instanceof EE_Payment) {
1387
-                $payment_methods_of_payments[] = $payment->ID();
1388
-            }
1389
-        }
1390
-        if ($payment_methods_of_payments) {
1391
-            $query_args = array(
1392
-                array(
1393
-                    'OR*payment_method_for_payment' => array(
1394
-                        'PMD_ID'    => array('IN', $payment_methods_of_payments),
1395
-                        'PMD_scope' => array('LIKE', '%' . EEM_Payment_Method::scope_admin . '%'),
1396
-                    ),
1397
-                ),
1398
-            );
1399
-        } else {
1400
-            $query_args = array(array('PMD_scope' => array('LIKE', '%' . EEM_Payment_Method::scope_admin . '%')));
1401
-        }
1402
-        $this->_template_args['payment_methods'] = EEM_Payment_Method::instance()->get_all($query_args);
1403
-    }
1404
-
1405
-
1406
-    /**
1407
-     * txn_attendees_meta_box
1408
-     *    generates HTML for the Attendees Transaction main meta box
1409
-     *
1410
-     * @access public
1411
-     * @param WP_Post $post
1412
-     * @param array   $metabox
1413
-     * @return void
1414
-     * @throws DomainException
1415
-     * @throws EE_Error
1416
-     * @throws InvalidArgumentException
1417
-     * @throws InvalidDataTypeException
1418
-     * @throws InvalidInterfaceException
1419
-     * @throws ReflectionException
1420
-     */
1421
-    public function txn_attendees_meta_box($post, $metabox = array('args' => array()))
1422
-    {
1423
-
1424
-        /** @noinspection NonSecureExtractUsageInspection */
1425
-        extract($metabox['args']);
1426
-        $this->_template_args['post'] = $post;
1427
-        $this->_template_args['event_attendees'] = array();
1428
-        // process items in cart
1429
-        $line_items = $this->_transaction->get_many_related(
1430
-            'Line_Item',
1431
-            array(array('LIN_type' => 'line-item'))
1432
-        );
1433
-        if (! empty($line_items)) {
1434
-            foreach ($line_items as $item) {
1435
-                if ($item instanceof EE_Line_Item) {
1436
-                    switch ($item->OBJ_type()) {
1437
-                        case 'Event':
1438
-                            break;
1439
-                        case 'Ticket':
1440
-                            $ticket = $item->ticket();
1441
-                            // right now we're only handling tickets here.
1442
-                            // Cause its expected that only tickets will have attendees right?
1443
-                            if (! $ticket instanceof EE_Ticket) {
1444
-                                break;
1445
-                            }
1446
-                            try {
1447
-                                $event_name = $ticket->get_event_name();
1448
-                            } catch (Exception $e) {
1449
-                                EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1450
-                                $event_name = esc_html__('Unknown Event', 'event_espresso');
1451
-                            }
1452
-                            $event_name .= ' - ' . $item->name();
1453
-                            $ticket_price = EEH_Template::format_currency($item->unit_price());
1454
-                            // now get all of the registrations for this transaction that use this ticket
1455
-                            $registrations = $ticket->registrations(
1456
-                                array(array('TXN_ID' => $this->_transaction->ID()))
1457
-                            );
1458
-                            foreach ($registrations as $registration) {
1459
-                                if (! $registration instanceof EE_Registration) {
1460
-                                    break;
1461
-                                }
1462
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['STS_ID']
1463
-                                    = $registration->status_ID();
1464
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['att_num']
1465
-                                    = $registration->count();
1466
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['event_ticket_name']
1467
-                                    = $event_name;
1468
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['ticket_price']
1469
-                                    = $ticket_price;
1470
-                                // attendee info
1471
-                                $attendee = $registration->get_first_related('Attendee');
1472
-                                if ($attendee instanceof EE_Attendee) {
1473
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['att_id']
1474
-                                        = $attendee->ID();
1475
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['attendee']
1476
-                                        = $attendee->full_name();
1477
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['email']
1478
-                                        = '<a href="mailto:' . $attendee->email() . '?subject=' . $event_name
1479
-                                          . esc_html__(
1480
-                                              ' Event',
1481
-                                              'event_espresso'
1482
-                                          )
1483
-                                          . '">' . $attendee->email() . '</a>';
1484
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['address']
1485
-                                        = EEH_Address::format($attendee, 'inline', false, false);
1486
-                                } else {
1487
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['att_id'] = '';
1488
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['attendee'] = '';
1489
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['email'] = '';
1490
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['address'] = '';
1491
-                                }
1492
-                            }
1493
-                            break;
1494
-                    }
1495
-                }
1496
-            }
1497
-
1498
-            $this->_template_args['transaction_form_url'] = add_query_arg(
1499
-                array(
1500
-                    'action'  => 'edit_transaction',
1501
-                    'process' => 'attendees',
1502
-                ),
1503
-                TXN_ADMIN_URL
1504
-            );
1505
-            echo EEH_Template::display_template(
1506
-                TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_attendees.template.php',
1507
-                $this->_template_args,
1508
-                true
1509
-            );
1510
-        } else {
1511
-            echo sprintf(
1512
-                esc_html__(
1513
-                    '%1$sFor some reason, there are no attendees registered for this transaction. Likely the registration was abandoned in process.%2$s',
1514
-                    'event_espresso'
1515
-                ),
1516
-                '<p class="important-notice">',
1517
-                '</p>'
1518
-            );
1519
-        }
1520
-    }
1521
-
1522
-
1523
-    /**
1524
-     * txn_registrant_side_meta_box
1525
-     * generates HTML for the Edit Transaction side meta box
1526
-     *
1527
-     * @access public
1528
-     * @return void
1529
-     * @throws DomainException
1530
-     * @throws EE_Error
1531
-     * @throws InvalidArgumentException
1532
-     * @throws InvalidDataTypeException
1533
-     * @throws InvalidInterfaceException
1534
-     * @throws ReflectionException
1535
-     */
1536
-    public function txn_registrant_side_meta_box()
1537
-    {
1538
-        $primary_att = $this->_transaction->primary_registration() instanceof EE_Registration
1539
-            ? $this->_transaction->primary_registration()->get_first_related('Attendee')
1540
-            : null;
1541
-        if (! $primary_att instanceof EE_Attendee) {
1542
-            $this->_template_args['no_attendee_message'] = esc_html__(
1543
-                'There is no attached contact for this transaction.  The transaction either failed due to an error or was abandoned.',
1544
-                'event_espresso'
1545
-            );
1546
-            $primary_att = EEM_Attendee::instance()->create_default_object();
1547
-        }
1548
-        $this->_template_args['ATT_ID'] = $primary_att->ID();
1549
-        $this->_template_args['prime_reg_fname'] = $primary_att->fname();
1550
-        $this->_template_args['prime_reg_lname'] = $primary_att->lname();
1551
-        $this->_template_args['prime_reg_email'] = $primary_att->email();
1552
-        $this->_template_args['prime_reg_phone'] = $primary_att->phone();
1553
-        $this->_template_args['edit_attendee_url'] = EE_Admin_Page::add_query_args_and_nonce(
1554
-            array(
1555
-                'action' => 'edit_attendee',
1556
-                'post'   => $primary_att->ID(),
1557
-            ),
1558
-            REG_ADMIN_URL
1559
-        );
1560
-        // get formatted address for registrant
1561
-        $this->_template_args['formatted_address'] = EEH_Address::format($primary_att);
1562
-        echo EEH_Template::display_template(
1563
-            TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_registrant.template.php',
1564
-            $this->_template_args,
1565
-            true
1566
-        );
1567
-    }
1568
-
1569
-
1570
-    /**
1571
-     * txn_billing_info_side_meta_box
1572
-     *    generates HTML for the Edit Transaction side meta box
1573
-     *
1574
-     * @access public
1575
-     * @return void
1576
-     * @throws DomainException
1577
-     * @throws EE_Error
1578
-     */
1579
-    public function txn_billing_info_side_meta_box()
1580
-    {
1581
-
1582
-        $this->_template_args['billing_form'] = $this->_transaction->billing_info();
1583
-        $this->_template_args['billing_form_url'] = add_query_arg(
1584
-            array('action' => 'edit_transaction', 'process' => 'billing'),
1585
-            TXN_ADMIN_URL
1586
-        );
1587
-
1588
-        $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_billing_info.template.php';
1589
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);
1590
-    }
1591
-
1592
-
1593
-    /**
1594
-     * apply_payments_or_refunds
1595
-     *    registers a payment or refund made towards a transaction
1596
-     *
1597
-     * @access public
1598
-     * @return void
1599
-     * @throws EE_Error
1600
-     * @throws InvalidArgumentException
1601
-     * @throws ReflectionException
1602
-     * @throws RuntimeException
1603
-     * @throws InvalidDataTypeException
1604
-     * @throws InvalidInterfaceException
1605
-     */
1606
-    public function apply_payments_or_refunds()
1607
-    {
1608
-        $json_response_data = array('return_data' => false);
1609
-        $valid_data = $this->_validate_payment_request_data();
1610
-        $has_access = EE_Registry::instance()->CAP->current_user_can(
1611
-            'ee_edit_payments',
1612
-            'apply_payment_or_refund_from_registration_details'
1613
-        );
1614
-        if (! empty($valid_data) && $has_access) {
1615
-            $PAY_ID = $valid_data['PAY_ID'];
1616
-            // save  the new payment
1617
-            $payment = $this->_create_payment_from_request_data($valid_data);
1618
-            // get the TXN for this payment
1619
-            $transaction = $payment->transaction();
1620
-            // verify transaction
1621
-            if ($transaction instanceof EE_Transaction) {
1622
-                // calculate_total_payments_and_update_status
1623
-                $this->_process_transaction_payments($transaction);
1624
-                $REG_IDs = $this->_get_REG_IDs_to_apply_payment_to($payment);
1625
-                $this->_remove_existing_registration_payments($payment, $PAY_ID);
1626
-                // apply payment to registrations (if applicable)
1627
-                if (! empty($REG_IDs)) {
1628
-                    $this->_update_registration_payments($transaction, $payment, $REG_IDs);
1629
-                    $this->_maybe_send_notifications();
1630
-                    // now process status changes for the same registrations
1631
-                    $this->_process_registration_status_change($transaction, $REG_IDs);
1632
-                }
1633
-                $this->_maybe_send_notifications($payment);
1634
-                // prepare to render page
1635
-                $json_response_data['return_data'] = $this->_build_payment_json_response($payment, $REG_IDs);
1636
-                do_action(
1637
-                    'AHEE__Transactions_Admin_Page__apply_payments_or_refund__after_recording',
1638
-                    $transaction,
1639
-                    $payment
1640
-                );
1641
-            } else {
1642
-                EE_Error::add_error(
1643
-                    esc_html__(
1644
-                        'A valid Transaction for this payment could not be retrieved.',
1645
-                        'event_espresso'
1646
-                    ),
1647
-                    __FILE__,
1648
-                    __FUNCTION__,
1649
-                    __LINE__
1650
-                );
1651
-            }
1652
-        } elseif ($has_access) {
1653
-            EE_Error::add_error(
1654
-                esc_html__(
1655
-                    'The payment form data could not be processed. Please try again.',
1656
-                    'event_espresso'
1657
-                ),
1658
-                __FILE__,
1659
-                __FUNCTION__,
1660
-                __LINE__
1661
-            );
1662
-        } else {
1663
-            EE_Error::add_error(
1664
-                esc_html__(
1665
-                    'You do not have access to apply payments or refunds to a registration.',
1666
-                    'event_espresso'
1667
-                ),
1668
-                __FILE__,
1669
-                __FUNCTION__,
1670
-                __LINE__
1671
-            );
1672
-        }
1673
-        $notices = EE_Error::get_notices(
1674
-            false,
1675
-            false,
1676
-            false
1677
-        );
1678
-        $this->_template_args = array(
1679
-            'data'    => $json_response_data,
1680
-            'error'   => $notices['errors'],
1681
-            'success' => $notices['success'],
1682
-        );
1683
-        $this->_return_json();
1684
-    }
1685
-
1686
-
1687
-    /**
1688
-     * _validate_payment_request_data
1689
-     *
1690
-     * @return array
1691
-     * @throws EE_Error
1692
-     * @throws InvalidArgumentException
1693
-     * @throws InvalidDataTypeException
1694
-     * @throws InvalidInterfaceException
1695
-     */
1696
-    protected function _validate_payment_request_data()
1697
-    {
1698
-        if (! isset($this->_req_data['txn_admin_payment'])) {
1699
-            return array();
1700
-        }
1701
-        $payment_form = $this->_generate_payment_form_section();
1702
-        try {
1703
-            if ($payment_form->was_submitted()) {
1704
-                $payment_form->receive_form_submission();
1705
-                if (! $payment_form->is_valid()) {
1706
-                    $submission_error_messages = array();
1707
-                    foreach ($payment_form->get_validation_errors_accumulated() as $validation_error) {
1708
-                        if ($validation_error instanceof EE_Validation_Error) {
1709
-                            $submission_error_messages[] = sprintf(
1710
-                                _x('%s : %s', 'Form Section Name : Form Validation Error', 'event_espresso'),
1711
-                                $validation_error->get_form_section()->html_label_text(),
1712
-                                $validation_error->getMessage()
1713
-                            );
1714
-                        }
1715
-                    }
1716
-                    EE_Error::add_error(
1717
-                        implode('<br />', $submission_error_messages),
1718
-                        __FILE__,
1719
-                        __FUNCTION__,
1720
-                        __LINE__
1721
-                    );
1722
-                    return array();
1723
-                }
1724
-            }
1725
-        } catch (EE_Error $e) {
1726
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1727
-            return array();
1728
-        }
1729
-
1730
-        return $payment_form->valid_data();
1731
-    }
1732
-
1733
-
1734
-    /**
1735
-     * _generate_payment_form_section
1736
-     *
1737
-     * @return EE_Form_Section_Proper
1738
-     * @throws EE_Error
1739
-     */
1740
-    protected function _generate_payment_form_section()
1741
-    {
1742
-        return new EE_Form_Section_Proper(
1743
-            array(
1744
-                'name'        => 'txn_admin_payment',
1745
-                'subsections' => array(
1746
-                    'PAY_ID'          => new EE_Text_Input(
1747
-                        array(
1748
-                            'default'               => 0,
1749
-                            'required'              => false,
1750
-                            'html_label_text'       => esc_html__('Payment ID', 'event_espresso'),
1751
-                            'validation_strategies' => array(new EE_Int_Normalization()),
1752
-                        )
1753
-                    ),
1754
-                    'TXN_ID'          => new EE_Text_Input(
1755
-                        array(
1756
-                            'default'               => 0,
1757
-                            'required'              => true,
1758
-                            'html_label_text'       => esc_html__('Transaction ID', 'event_espresso'),
1759
-                            'validation_strategies' => array(new EE_Int_Normalization()),
1760
-                        )
1761
-                    ),
1762
-                    'type'            => new EE_Text_Input(
1763
-                        array(
1764
-                            'default'               => 1,
1765
-                            'required'              => true,
1766
-                            'html_label_text'       => esc_html__('Payment or Refund', 'event_espresso'),
1767
-                            'validation_strategies' => array(new EE_Int_Normalization()),
1768
-                        )
1769
-                    ),
1770
-                    'amount'          => new EE_Text_Input(
1771
-                        array(
1772
-                            'default'               => 0,
1773
-                            'required'              => true,
1774
-                            'html_label_text'       => esc_html__('Payment amount', 'event_espresso'),
1775
-                            'validation_strategies' => array(new EE_Float_Normalization()),
1776
-                        )
1777
-                    ),
1778
-                    'status'          => new EE_Text_Input(
1779
-                        array(
1780
-                            'default'         => EEM_Payment::status_id_approved,
1781
-                            'required'        => true,
1782
-                            'html_label_text' => esc_html__('Payment status', 'event_espresso'),
1783
-                        )
1784
-                    ),
1785
-                    'PMD_ID'          => new EE_Text_Input(
1786
-                        array(
1787
-                            'default'               => 2,
1788
-                            'required'              => true,
1789
-                            'html_label_text'       => esc_html__('Payment Method', 'event_espresso'),
1790
-                            'validation_strategies' => array(new EE_Int_Normalization()),
1791
-                        )
1792
-                    ),
1793
-                    'date'            => new EE_Text_Input(
1794
-                        array(
1795
-                            'default'         => time(),
1796
-                            'required'        => true,
1797
-                            'html_label_text' => esc_html__('Payment date', 'event_espresso'),
1798
-                        )
1799
-                    ),
1800
-                    'txn_id_chq_nmbr' => new EE_Text_Input(
1801
-                        array(
1802
-                            'default'               => '',
1803
-                            'required'              => false,
1804
-                            'html_label_text'       => esc_html__('Transaction or Cheque Number', 'event_espresso'),
1805
-                            'validation_strategies' => array(
1806
-                                new EE_Max_Length_Validation_Strategy(
1807
-                                    esc_html__('Input too long', 'event_espresso'),
1808
-                                    100
1809
-                                ),
1810
-                            ),
1811
-                        )
1812
-                    ),
1813
-                    'po_number'       => new EE_Text_Input(
1814
-                        array(
1815
-                            'default'               => '',
1816
-                            'required'              => false,
1817
-                            'html_label_text'       => esc_html__('Purchase Order Number', 'event_espresso'),
1818
-                            'validation_strategies' => array(
1819
-                                new EE_Max_Length_Validation_Strategy(
1820
-                                    esc_html__('Input too long', 'event_espresso'),
1821
-                                    100
1822
-                                ),
1823
-                            ),
1824
-                        )
1825
-                    ),
1826
-                    'accounting'      => new EE_Text_Input(
1827
-                        array(
1828
-                            'default'               => '',
1829
-                            'required'              => false,
1830
-                            'html_label_text'       => esc_html__('Extra Field for Accounting', 'event_espresso'),
1831
-                            'validation_strategies' => array(
1832
-                                new EE_Max_Length_Validation_Strategy(
1833
-                                    esc_html__('Input too long', 'event_espresso'),
1834
-                                    100
1835
-                                ),
1836
-                            ),
1837
-                        )
1838
-                    ),
1839
-                ),
1840
-            )
1841
-        );
1842
-    }
1843
-
1844
-
1845
-    /**
1846
-     * _create_payment_from_request_data
1847
-     *
1848
-     * @param array $valid_data
1849
-     * @return EE_Payment
1850
-     * @throws EE_Error
1851
-     * @throws InvalidArgumentException
1852
-     * @throws InvalidDataTypeException
1853
-     * @throws InvalidInterfaceException
1854
-     * @throws ReflectionException
1855
-     */
1856
-    protected function _create_payment_from_request_data($valid_data)
1857
-    {
1858
-        $PAY_ID = $valid_data['PAY_ID'];
1859
-        // get payment amount
1860
-        $amount = $valid_data['amount'] ? abs($valid_data['amount']) : 0;
1861
-        // payments have a type value of 1 and refunds have a type value of -1
1862
-        // so multiplying amount by type will give a positive value for payments, and negative values for refunds
1863
-        $amount = $valid_data['type'] < 0 ? $amount * -1 : $amount;
1864
-        // for some reason the date string coming in has extra spaces between the date and time.  This fixes that.
1865
-        $date = $valid_data['date']
1866
-            ? preg_replace('/\s+/', ' ', $valid_data['date'])
1867
-            : date('Y-m-d g:i a', current_time('timestamp'));
1868
-        $payment = EE_Payment::new_instance(
1869
-            array(
1870
-                'TXN_ID'              => $valid_data['TXN_ID'],
1871
-                'STS_ID'              => $valid_data['status'],
1872
-                'PAY_timestamp'       => $date,
1873
-                'PAY_source'          => EEM_Payment_Method::scope_admin,
1874
-                'PMD_ID'              => $valid_data['PMD_ID'],
1875
-                'PAY_amount'          => $amount,
1876
-                'PAY_txn_id_chq_nmbr' => $valid_data['txn_id_chq_nmbr'],
1877
-                'PAY_po_number'       => $valid_data['po_number'],
1878
-                'PAY_extra_accntng'   => $valid_data['accounting'],
1879
-                'PAY_details'         => $valid_data,
1880
-                'PAY_ID'              => $PAY_ID,
1881
-            ),
1882
-            '',
1883
-            array('Y-m-d', 'g:i a')
1884
-        );
1885
-
1886
-        if (! $payment->save()) {
1887
-            EE_Error::add_error(
1888
-                sprintf(
1889
-                    esc_html__('Payment %1$d has not been successfully saved to the database.', 'event_espresso'),
1890
-                    $payment->ID()
1891
-                ),
1892
-                __FILE__,
1893
-                __FUNCTION__,
1894
-                __LINE__
1895
-            );
1896
-        }
1897
-
1898
-        return $payment;
1899
-    }
1900
-
1901
-
1902
-    /**
1903
-     * _process_transaction_payments
1904
-     *
1905
-     * @param \EE_Transaction $transaction
1906
-     * @return void
1907
-     * @throws EE_Error
1908
-     * @throws InvalidArgumentException
1909
-     * @throws ReflectionException
1910
-     * @throws InvalidDataTypeException
1911
-     * @throws InvalidInterfaceException
1912
-     */
1913
-    protected function _process_transaction_payments(EE_Transaction $transaction)
1914
-    {
1915
-        /** @type EE_Transaction_Payments $transaction_payments */
1916
-        $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
1917
-        // update the transaction with this payment
1918
-        if ($transaction_payments->calculate_total_payments_and_update_status($transaction)) {
1919
-            EE_Error::add_success(
1920
-                esc_html__(
1921
-                    'The payment has been processed successfully.',
1922
-                    'event_espresso'
1923
-                ),
1924
-                __FILE__,
1925
-                __FUNCTION__,
1926
-                __LINE__
1927
-            );
1928
-        } else {
1929
-            EE_Error::add_error(
1930
-                esc_html__(
1931
-                    'The payment was processed successfully but the amount paid for the transaction was not updated.',
1932
-                    'event_espresso'
1933
-                ),
1934
-                __FILE__,
1935
-                __FUNCTION__,
1936
-                __LINE__
1937
-            );
1938
-        }
1939
-    }
1940
-
1941
-
1942
-    /**
1943
-     * _get_REG_IDs_to_apply_payment_to
1944
-     * returns a list of registration IDs that the payment will apply to
1945
-     *
1946
-     * @param \EE_Payment $payment
1947
-     * @return array
1948
-     * @throws EE_Error
1949
-     * @throws InvalidArgumentException
1950
-     * @throws InvalidDataTypeException
1951
-     * @throws InvalidInterfaceException
1952
-     * @throws ReflectionException
1953
-     */
1954
-    protected function _get_REG_IDs_to_apply_payment_to(EE_Payment $payment)
1955
-    {
1956
-        $REG_IDs = array();
1957
-        // grab array of IDs for specific registrations to apply changes to
1958
-        if (isset($this->_req_data['txn_admin_payment']['registrations'])) {
1959
-            $REG_IDs = (array) $this->_req_data['txn_admin_payment']['registrations'];
1960
-        }
1961
-        // nothing specified ? then get all reg IDs
1962
-        if (empty($REG_IDs)) {
1963
-            $registrations = $payment->transaction()->registrations();
1964
-            $REG_IDs = ! empty($registrations)
1965
-                ? array_keys($registrations)
1966
-                : $this->_get_existing_reg_payment_REG_IDs($payment);
1967
-        }
1968
-
1969
-        // ensure that REG_IDs are integers and NOT strings
1970
-        return array_map('intval', $REG_IDs);
1971
-    }
1972
-
1973
-
1974
-    /**
1975
-     * @return array
1976
-     */
1977
-    public function existing_reg_payment_REG_IDs()
1978
-    {
1979
-        return $this->_existing_reg_payment_REG_IDs;
1980
-    }
1981
-
1982
-
1983
-    /**
1984
-     * @param array $existing_reg_payment_REG_IDs
1985
-     */
1986
-    public function set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs = null)
1987
-    {
1988
-        $this->_existing_reg_payment_REG_IDs = $existing_reg_payment_REG_IDs;
1989
-    }
1990
-
1991
-
1992
-    /**
1993
-     * _get_existing_reg_payment_REG_IDs
1994
-     * returns a list of registration IDs that the payment is currently related to
1995
-     * as recorded in the database
1996
-     *
1997
-     * @param \EE_Payment $payment
1998
-     * @return array
1999
-     * @throws EE_Error
2000
-     * @throws InvalidArgumentException
2001
-     * @throws InvalidDataTypeException
2002
-     * @throws InvalidInterfaceException
2003
-     * @throws ReflectionException
2004
-     */
2005
-    protected function _get_existing_reg_payment_REG_IDs(EE_Payment $payment)
2006
-    {
2007
-        if ($this->existing_reg_payment_REG_IDs() === null) {
2008
-            // let's get any existing reg payment records for this payment
2009
-            $existing_reg_payment_REG_IDs = $payment->get_many_related('Registration');
2010
-            // but we only want the REG IDs, so grab the array keys
2011
-            $existing_reg_payment_REG_IDs = ! empty($existing_reg_payment_REG_IDs)
2012
-                ? array_keys($existing_reg_payment_REG_IDs)
2013
-                : array();
2014
-            $this->set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs);
2015
-        }
2016
-
2017
-        return $this->existing_reg_payment_REG_IDs();
2018
-    }
2019
-
2020
-
2021
-    /**
2022
-     * _remove_existing_registration_payments
2023
-     * this calculates the difference between existing relations
2024
-     * to the supplied payment and the new list registration IDs,
2025
-     * removes any related registrations that no longer apply,
2026
-     * and then updates the registration paid fields
2027
-     *
2028
-     * @param \EE_Payment $payment
2029
-     * @param int         $PAY_ID
2030
-     * @return bool;
2031
-     * @throws EE_Error
2032
-     * @throws InvalidArgumentException
2033
-     * @throws ReflectionException
2034
-     * @throws InvalidDataTypeException
2035
-     * @throws InvalidInterfaceException
2036
-     */
2037
-    protected function _remove_existing_registration_payments(EE_Payment $payment, $PAY_ID = 0)
2038
-    {
2039
-        // newly created payments will have nothing recorded for $PAY_ID
2040
-        if (absint($PAY_ID) === 0) {
2041
-            return false;
2042
-        }
2043
-        $existing_reg_payment_REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment);
2044
-        if (empty($existing_reg_payment_REG_IDs)) {
2045
-            return false;
2046
-        }
2047
-        /** @type EE_Transaction_Payments $transaction_payments */
2048
-        $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
2049
-
2050
-        return $transaction_payments->delete_registration_payments_and_update_registrations(
2051
-            $payment,
2052
-            array(
2053
-                array(
2054
-                    'PAY_ID' => $payment->ID(),
2055
-                    'REG_ID' => array('IN', $existing_reg_payment_REG_IDs),
2056
-                ),
2057
-            )
2058
-        );
2059
-    }
2060
-
2061
-
2062
-    /**
2063
-     * _update_registration_payments
2064
-     * this applies the payments to the selected registrations
2065
-     * but only if they have not already been paid for
2066
-     *
2067
-     * @param  EE_Transaction $transaction
2068
-     * @param \EE_Payment     $payment
2069
-     * @param array           $REG_IDs
2070
-     * @return void
2071
-     * @throws EE_Error
2072
-     * @throws InvalidArgumentException
2073
-     * @throws ReflectionException
2074
-     * @throws RuntimeException
2075
-     * @throws InvalidDataTypeException
2076
-     * @throws InvalidInterfaceException
2077
-     */
2078
-    protected function _update_registration_payments(
2079
-        EE_Transaction $transaction,
2080
-        EE_Payment $payment,
2081
-        $REG_IDs = array()
2082
-    ) {
2083
-        // we can pass our own custom set of registrations to EE_Payment_Processor::process_registration_payments()
2084
-        // so let's do that using our set of REG_IDs from the form
2085
-        $registration_query_where_params = array(
2086
-            'REG_ID' => array('IN', $REG_IDs),
2087
-        );
2088
-        // but add in some conditions regarding payment,
2089
-        // so that we don't apply payments to registrations that are free or have already been paid for
2090
-        // but ONLY if the payment is NOT a refund ( ie: the payment amount is not negative )
2091
-        if (! $payment->is_a_refund()) {
2092
-            $registration_query_where_params['REG_final_price'] = array('!=', 0);
2093
-            $registration_query_where_params['REG_final_price*'] = array('!=', 'REG_paid', true);
2094
-        }
2095
-        $registrations = $transaction->registrations(array($registration_query_where_params));
2096
-        if (! empty($registrations)) {
2097
-            /** @type EE_Payment_Processor $payment_processor */
2098
-            $payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2099
-            $payment_processor->process_registration_payments($transaction, $payment, $registrations);
2100
-        }
2101
-    }
2102
-
2103
-
2104
-    /**
2105
-     * _process_registration_status_change
2106
-     * This processes requested registration status changes for all the registrations
2107
-     * on a given transaction and (optionally) sends out notifications for the changes.
2108
-     *
2109
-     * @param  EE_Transaction $transaction
2110
-     * @param array           $REG_IDs
2111
-     * @return bool
2112
-     * @throws EE_Error
2113
-     * @throws InvalidArgumentException
2114
-     * @throws ReflectionException
2115
-     * @throws InvalidDataTypeException
2116
-     * @throws InvalidInterfaceException
2117
-     */
2118
-    protected function _process_registration_status_change(EE_Transaction $transaction, $REG_IDs = array())
2119
-    {
2120
-        // first if there is no change in status then we get out.
2121
-        if (! isset($this->_req_data['txn_reg_status_change']['reg_status'])
2122
-            || $this->_req_data['txn_reg_status_change']['reg_status'] === 'NAN'
2123
-        ) {
2124
-            // no error message, no change requested, just nothing to do man.
2125
-            return false;
2126
-        }
2127
-        /** @type EE_Transaction_Processor $transaction_processor */
2128
-        $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
2129
-
2130
-        // made it here dude?  Oh WOW.  K, let's take care of changing the statuses
2131
-        return $transaction_processor->manually_update_registration_statuses(
2132
-            $transaction,
2133
-            sanitize_text_field($this->_req_data['txn_reg_status_change']['reg_status']),
2134
-            array(array('REG_ID' => array('IN', $REG_IDs)))
2135
-        );
2136
-    }
2137
-
2138
-
2139
-    /**
2140
-     * _build_payment_json_response
2141
-     *
2142
-     * @access public
2143
-     * @param \EE_Payment $payment
2144
-     * @param array       $REG_IDs
2145
-     * @param bool | null $delete_txn_reg_status_change
2146
-     * @return array
2147
-     * @throws EE_Error
2148
-     * @throws InvalidArgumentException
2149
-     * @throws InvalidDataTypeException
2150
-     * @throws InvalidInterfaceException
2151
-     * @throws ReflectionException
2152
-     */
2153
-    protected function _build_payment_json_response(
2154
-        EE_Payment $payment,
2155
-        $REG_IDs = array(),
2156
-        $delete_txn_reg_status_change = null
2157
-    ) {
2158
-        // was the payment deleted ?
2159
-        if (is_bool($delete_txn_reg_status_change)) {
2160
-            return array(
2161
-                'PAY_ID'                       => $payment->ID(),
2162
-                'amount'                       => $payment->amount(),
2163
-                'total_paid'                   => $payment->transaction()->paid(),
2164
-                'txn_status'                   => $payment->transaction()->status_ID(),
2165
-                'pay_status'                   => $payment->STS_ID(),
2166
-                'registrations'                => $this->_registration_payment_data_array($REG_IDs),
2167
-                'delete_txn_reg_status_change' => $delete_txn_reg_status_change,
2168
-            );
2169
-        } else {
2170
-            $this->_get_payment_status_array();
2171
-
2172
-            return array(
2173
-                'amount'           => $payment->amount(),
2174
-                'total_paid'       => $payment->transaction()->paid(),
2175
-                'txn_status'       => $payment->transaction()->status_ID(),
2176
-                'pay_status'       => $payment->STS_ID(),
2177
-                'PAY_ID'           => $payment->ID(),
2178
-                'STS_ID'           => $payment->STS_ID(),
2179
-                'status'           => self::$_pay_status[ $payment->STS_ID() ],
2180
-                'date'             => $payment->timestamp('Y-m-d', 'h:i a'),
2181
-                'method'           => strtoupper($payment->source()),
2182
-                'PM_ID'            => $payment->payment_method() ? $payment->payment_method()->ID() : 1,
2183
-                'gateway'          => $payment->payment_method()
2184
-                    ? $payment->payment_method()->admin_name()
2185
-                    : esc_html__('Unknown', 'event_espresso'),
2186
-                'gateway_response' => $payment->gateway_response(),
2187
-                'txn_id_chq_nmbr'  => $payment->txn_id_chq_nmbr(),
2188
-                'po_number'        => $payment->po_number(),
2189
-                'extra_accntng'    => $payment->extra_accntng(),
2190
-                'registrations'    => $this->_registration_payment_data_array($REG_IDs),
2191
-            );
2192
-        }
2193
-    }
2194
-
2195
-
2196
-    /**
2197
-     * delete_payment
2198
-     *    delete a payment or refund made towards a transaction
2199
-     *
2200
-     * @access public
2201
-     * @return void
2202
-     * @throws EE_Error
2203
-     * @throws InvalidArgumentException
2204
-     * @throws ReflectionException
2205
-     * @throws InvalidDataTypeException
2206
-     * @throws InvalidInterfaceException
2207
-     */
2208
-    public function delete_payment()
2209
-    {
2210
-        $json_response_data = array('return_data' => false);
2211
-        $PAY_ID = isset($this->_req_data['delete_txn_admin_payment']['PAY_ID'])
2212
-            ? absint($this->_req_data['delete_txn_admin_payment']['PAY_ID'])
2213
-            : 0;
2214
-        $can_delete = EE_Registry::instance()->CAP->current_user_can(
2215
-            'ee_delete_payments',
2216
-            'delete_payment_from_registration_details'
2217
-        );
2218
-        if ($PAY_ID && $can_delete) {
2219
-            $delete_txn_reg_status_change = isset($this->_req_data['delete_txn_reg_status_change'])
2220
-                ? $this->_req_data['delete_txn_reg_status_change']
2221
-                : false;
2222
-            $payment = EEM_Payment::instance()->get_one_by_ID($PAY_ID);
2223
-            if ($payment instanceof EE_Payment) {
2224
-                $REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment);
2225
-                /** @type EE_Transaction_Payments $transaction_payments */
2226
-                $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
2227
-                if ($transaction_payments->delete_payment_and_update_transaction($payment)) {
2228
-                    $json_response_data['return_data'] = $this->_build_payment_json_response(
2229
-                        $payment,
2230
-                        $REG_IDs,
2231
-                        $delete_txn_reg_status_change
2232
-                    );
2233
-                    if ($delete_txn_reg_status_change) {
2234
-                        $this->_req_data['txn_reg_status_change'] = $delete_txn_reg_status_change;
2235
-                        // MAKE sure we also add the delete_txn_req_status_change to the
2236
-                        // $_REQUEST global because that's how messages will be looking for it.
2237
-                        $_REQUEST['txn_reg_status_change'] = $delete_txn_reg_status_change;
2238
-                        $this->_maybe_send_notifications();
2239
-                        $this->_process_registration_status_change($payment->transaction(), $REG_IDs);
2240
-                    }
2241
-                }
2242
-            } else {
2243
-                EE_Error::add_error(
2244
-                    esc_html__('Valid Payment data could not be retrieved from the database.', 'event_espresso'),
2245
-                    __FILE__,
2246
-                    __FUNCTION__,
2247
-                    __LINE__
2248
-                );
2249
-            }
2250
-        } elseif ($can_delete) {
2251
-            EE_Error::add_error(
2252
-                esc_html__(
2253
-                    'A valid Payment ID was not received, therefore payment form data could not be loaded.',
2254
-                    'event_espresso'
2255
-                ),
2256
-                __FILE__,
2257
-                __FUNCTION__,
2258
-                __LINE__
2259
-            );
2260
-        } else {
2261
-            EE_Error::add_error(
2262
-                esc_html__(
2263
-                    'You do not have access to delete a payment.',
2264
-                    'event_espresso'
2265
-                ),
2266
-                __FILE__,
2267
-                __FUNCTION__,
2268
-                __LINE__
2269
-            );
2270
-        }
2271
-        $notices = EE_Error::get_notices(false, false, false);
2272
-        $this->_template_args = array(
2273
-            'data'      => $json_response_data,
2274
-            'success'   => $notices['success'],
2275
-            'error'     => $notices['errors'],
2276
-            'attention' => $notices['attention'],
2277
-        );
2278
-        $this->_return_json();
2279
-    }
2280
-
2281
-
2282
-    /**
2283
-     * _registration_payment_data_array
2284
-     * adds info for 'owing' and 'paid' for each registration to the json response
2285
-     *
2286
-     * @access protected
2287
-     * @param array $REG_IDs
2288
-     * @return array
2289
-     * @throws EE_Error
2290
-     * @throws InvalidArgumentException
2291
-     * @throws InvalidDataTypeException
2292
-     * @throws InvalidInterfaceException
2293
-     * @throws ReflectionException
2294
-     */
2295
-    protected function _registration_payment_data_array($REG_IDs)
2296
-    {
2297
-        $registration_payment_data = array();
2298
-        // if non empty reg_ids lets get an array of registrations and update the values for the apply_payment/refund rows.
2299
-        if (! empty($REG_IDs)) {
2300
-            $registrations = EEM_Registration::instance()->get_all(array(array('REG_ID' => array('IN', $REG_IDs))));
2301
-            foreach ($registrations as $registration) {
2302
-                if ($registration instanceof EE_Registration) {
2303
-                    $registration_payment_data[ $registration->ID() ] = array(
2304
-                        'paid'  => $registration->pretty_paid(),
2305
-                        'owing' => EEH_Template::format_currency($registration->final_price() - $registration->paid()),
2306
-                    );
2307
-                }
2308
-            }
2309
-        }
2310
-
2311
-        return $registration_payment_data;
2312
-    }
2313
-
2314
-
2315
-    /**
2316
-     * _maybe_send_notifications
2317
-     * determines whether or not the admin has indicated that notifications should be sent.
2318
-     * If so, will toggle a filter switch for delivering registration notices.
2319
-     * If passed an EE_Payment object, then it will trigger payment notifications instead.
2320
-     *
2321
-     * @access protected
2322
-     * @param \EE_Payment | null $payment
2323
-     */
2324
-    protected function _maybe_send_notifications($payment = null)
2325
-    {
2326
-        switch ($payment instanceof EE_Payment) {
2327
-            // payment notifications
2328
-            case true:
2329
-                if (isset($this->_req_data['txn_payments']['send_notifications'])
2330
-                    && filter_var(
2331
-                        $this->_req_data['txn_payments']['send_notifications'],
2332
-                        FILTER_VALIDATE_BOOLEAN
2333
-                    )
2334
-                ) {
2335
-                    $this->_process_payment_notification($payment);
2336
-                }
2337
-                break;
2338
-            // registration notifications
2339
-            case false:
2340
-                if (isset($this->_req_data['txn_reg_status_change']['send_notifications'])
2341
-                    && filter_var(
2342
-                        $this->_req_data['txn_reg_status_change']['send_notifications'],
2343
-                        FILTER_VALIDATE_BOOLEAN
2344
-                    )
2345
-                ) {
2346
-                    add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
2347
-                }
2348
-                break;
2349
-        }
2350
-    }
2351
-
2352
-
2353
-    /**
2354
-     * _send_payment_reminder
2355
-     *    generates HTML for the View Transaction Details Admin page
2356
-     *
2357
-     * @access protected
2358
-     * @return void
2359
-     * @throws EE_Error
2360
-     * @throws InvalidArgumentException
2361
-     * @throws InvalidDataTypeException
2362
-     * @throws InvalidInterfaceException
2363
-     */
2364
-    protected function _send_payment_reminder()
2365
-    {
2366
-        $TXN_ID = ! empty($this->_req_data['TXN_ID']) ? absint($this->_req_data['TXN_ID']) : false;
2367
-        $transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
2368
-        $query_args = isset($this->_req_data['redirect_to']) ? array(
2369
-            'action' => $this->_req_data['redirect_to'],
2370
-            'TXN_ID' => $this->_req_data['TXN_ID'],
2371
-        ) : array();
2372
-        do_action(
2373
-            'AHEE__Transactions_Admin_Page___send_payment_reminder__process_admin_payment_reminder',
2374
-            $transaction
2375
-        );
2376
-        $this->_redirect_after_action(
2377
-            false,
2378
-            esc_html__('payment reminder', 'event_espresso'),
2379
-            esc_html__('sent', 'event_espresso'),
2380
-            $query_args,
2381
-            true
2382
-        );
2383
-    }
2384
-
2385
-
2386
-    /**
2387
-     *  get_transactions
2388
-     *    get transactions for given parameters (used by list table)
2389
-     *
2390
-     * @param  int     $perpage how many transactions displayed per page
2391
-     * @param  boolean $count   return the count or objects
2392
-     * @param string   $view
2393
-     * @return mixed int = count || array of transaction objects
2394
-     * @throws EE_Error
2395
-     * @throws InvalidArgumentException
2396
-     * @throws InvalidDataTypeException
2397
-     * @throws InvalidInterfaceException
2398
-     */
2399
-    public function get_transactions($perpage, $count = false, $view = '')
2400
-    {
2401
-
2402
-        $TXN = EEM_Transaction::instance();
2403
-
2404
-        $start_date = isset($this->_req_data['txn-filter-start-date'])
2405
-            ? wp_strip_all_tags($this->_req_data['txn-filter-start-date'])
2406
-            : date(
2407
-                'm/d/Y',
2408
-                strtotime('-10 year')
2409
-            );
2410
-        $end_date = isset($this->_req_data['txn-filter-end-date'])
2411
-            ? wp_strip_all_tags($this->_req_data['txn-filter-end-date'])
2412
-            : date('m/d/Y');
2413
-
2414
-        // make sure our timestamps start and end right at the boundaries for each day
2415
-        $start_date = date('Y-m-d', strtotime($start_date)) . ' 00:00:00';
2416
-        $end_date = date('Y-m-d', strtotime($end_date)) . ' 23:59:59';
2417
-
2418
-
2419
-        // convert to timestamps
2420
-        $start_date = strtotime($start_date);
2421
-        $end_date = strtotime($end_date);
2422
-
2423
-        // makes sure start date is the lowest value and vice versa
2424
-        $start_date = min($start_date, $end_date);
2425
-        $end_date = max($start_date, $end_date);
2426
-
2427
-        // convert to correct format for query
2428
-        $start_date = EEM_Transaction::instance()->convert_datetime_for_query(
2429
-            'TXN_timestamp',
2430
-            date('Y-m-d H:i:s', $start_date),
2431
-            'Y-m-d H:i:s'
2432
-        );
2433
-        $end_date = EEM_Transaction::instance()->convert_datetime_for_query(
2434
-            'TXN_timestamp',
2435
-            date('Y-m-d H:i:s', $end_date),
2436
-            'Y-m-d H:i:s'
2437
-        );
2438
-
2439
-
2440
-        // set orderby
2441
-        $this->_req_data['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : '';
2442
-
2443
-        switch ($this->_req_data['orderby']) {
2444
-            case 'TXN_ID':
2445
-                $orderby = 'TXN_ID';
2446
-                break;
2447
-            case 'ATT_fname':
2448
-                $orderby = 'Registration.Attendee.ATT_fname';
2449
-                break;
2450
-            case 'event_name':
2451
-                $orderby = 'Registration.Event.EVT_name';
2452
-                break;
2453
-            default: // 'TXN_timestamp'
2454
-                $orderby = 'TXN_timestamp';
2455
-        }
2456
-
2457
-        $sort = ! empty($this->_req_data['order']) ? $this->_req_data['order'] : 'DESC';
2458
-        $current_page = ! empty($this->_req_data['paged']) ? $this->_req_data['paged'] : 1;
2459
-        $per_page = ! empty($perpage) ? $perpage : 10;
2460
-        $per_page = ! empty($this->_req_data['perpage']) ? $this->_req_data['perpage'] : $per_page;
2461
-
2462
-        $offset = ($current_page - 1) * $per_page;
2463
-        $limit = array($offset, $per_page);
2464
-
2465
-        $_where = array(
2466
-            'TXN_timestamp'          => array('BETWEEN', array($start_date, $end_date)),
2467
-            'Registration.REG_count' => 1,
2468
-        );
2469
-
2470
-        if (isset($this->_req_data['EVT_ID'])) {
2471
-            $_where['Registration.EVT_ID'] = $this->_req_data['EVT_ID'];
2472
-        }
2473
-
2474
-        if (isset($this->_req_data['s'])) {
2475
-            $search_string = '%' . $this->_req_data['s'] . '%';
2476
-            $_where['OR'] = array(
2477
-                'Registration.Event.EVT_name'         => array('LIKE', $search_string),
2478
-                'Registration.Event.EVT_desc'         => array('LIKE', $search_string),
2479
-                'Registration.Event.EVT_short_desc'   => array('LIKE', $search_string),
2480
-                'Registration.Attendee.ATT_full_name' => array('LIKE', $search_string),
2481
-                'Registration.Attendee.ATT_fname'     => array('LIKE', $search_string),
2482
-                'Registration.Attendee.ATT_lname'     => array('LIKE', $search_string),
2483
-                'Registration.Attendee.ATT_short_bio' => array('LIKE', $search_string),
2484
-                'Registration.Attendee.ATT_email'     => array('LIKE', $search_string),
2485
-                'Registration.Attendee.ATT_address'   => array('LIKE', $search_string),
2486
-                'Registration.Attendee.ATT_address2'  => array('LIKE', $search_string),
2487
-                'Registration.Attendee.ATT_city'      => array('LIKE', $search_string),
2488
-                'Registration.REG_final_price'        => array('LIKE', $search_string),
2489
-                'Registration.REG_code'               => array('LIKE', $search_string),
2490
-                'Registration.REG_count'              => array('LIKE', $search_string),
2491
-                'Registration.REG_group_size'         => array('LIKE', $search_string),
2492
-                'Registration.Ticket.TKT_name'        => array('LIKE', $search_string),
2493
-                'Registration.Ticket.TKT_description' => array('LIKE', $search_string),
2494
-                'Payment.PAY_source'                  => array('LIKE', $search_string),
2495
-                'Payment.Payment_Method.PMD_name'     => array('LIKE', $search_string),
2496
-                'TXN_session_data'                    => array('LIKE', $search_string),
2497
-                'Payment.PAY_txn_id_chq_nmbr'         => array('LIKE', $search_string),
2498
-            );
2499
-        }
2500
-
2501
-        // failed transactions
2502
-        $failed = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'failed' && ! $count)
2503
-                  || ($count && $view === 'failed');
2504
-        $abandoned = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'abandoned' && ! $count)
2505
-                     || ($count && $view === 'abandoned');
2506
-        $incomplete = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'incomplete' && ! $count)
2507
-                      || ($count && $view === 'incomplete');
2508
-
2509
-        if ($failed) {
2510
-            $_where['STS_ID'] = EEM_Transaction::failed_status_code;
2511
-        } elseif ($abandoned) {
2512
-            $_where['STS_ID'] = EEM_Transaction::abandoned_status_code;
2513
-        } elseif ($incomplete) {
2514
-            $_where['STS_ID'] = EEM_Transaction::incomplete_status_code;
2515
-        } else {
2516
-            $_where['STS_ID'] = array('!=', EEM_Transaction::failed_status_code);
2517
-            $_where['STS_ID*'] = array('!=', EEM_Transaction::abandoned_status_code);
2518
-        }
2519
-
2520
-        $query_params = apply_filters(
2521
-            'FHEE__Transactions_Admin_Page___get_transactions_query_params',
2522
-            array(
2523
-                $_where,
2524
-                'order_by'                 => array($orderby => $sort),
2525
-                'limit'                    => $limit,
2526
-                'default_where_conditions' => EEM_Base::default_where_conditions_this_only,
2527
-            ),
2528
-            $this->_req_data,
2529
-            $view,
2530
-            $count
2531
-        );
2532
-
2533
-        $transactions = $count
2534
-            ? $TXN->count(array($query_params[0]), 'TXN_ID', true)
2535
-            : $TXN->get_all($query_params);
2536
-
2537
-        return $transactions;
2538
-    }
2539
-
2540
-
2541
-    /**
2542
-     * @since $VID:$
2543
-     * @throws EE_Error
2544
-     * @throws InvalidArgumentException
2545
-     * @throws InvalidDataTypeException
2546
-     * @throws InvalidInterfaceException
2547
-     * @throws ReflectionException
2548
-     * @throws RuntimeException
2549
-     */
2550
-    public function recalculateLineItems()
2551
-    {
2552
-        $TXN_ID = ! empty($this->_req_data['TXN_ID']) ? absint($this->_req_data['TXN_ID']) : false;
2553
-        /** @var EE_Transaction $transaction */
2554
-        $transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
2555
-        $total_line_item = $transaction->total_line_item(false);
2556
-        $success = false;
2557
-        if ($total_line_item instanceof EE_Line_Item) {
2558
-            EEH_Line_Item::resetIsTaxableForTickets($total_line_item);
2559
-            $success = EEH_Line_Item::apply_taxes($total_line_item, true);
2560
-        }
2561
-        $this->_redirect_after_action(
2562
-            (bool) $success,
2563
-            esc_html__('Transaction taxes and totals', 'event_espresso'),
2564
-            esc_html__('recalculated', 'event_espresso'),
2565
-            isset($this->_req_data['redirect_to'])
2566
-                ? array(
2567
-                'action' => $this->_req_data['redirect_to'],
2568
-                'TXN_ID' => $this->_req_data['TXN_ID'],
2569
-            )
2570
-                : array(),
2571
-            true
2572
-        );
2573
-    }
16
+	/**
17
+	 * @var EE_Transaction
18
+	 */
19
+	private $_transaction;
20
+
21
+	/**
22
+	 * @var EE_Session
23
+	 */
24
+	private $_session;
25
+
26
+	/**
27
+	 * @var array $_txn_status
28
+	 */
29
+	private static $_txn_status;
30
+
31
+	/**
32
+	 * @var array $_pay_status
33
+	 */
34
+	private static $_pay_status;
35
+
36
+	/**
37
+	 * @var array $_existing_reg_payment_REG_IDs
38
+	 */
39
+	protected $_existing_reg_payment_REG_IDs;
40
+
41
+
42
+	/**
43
+	 *    _init_page_props
44
+	 *
45
+	 * @return void
46
+	 */
47
+	protected function _init_page_props()
48
+	{
49
+		$this->page_slug = TXN_PG_SLUG;
50
+		$this->page_label = esc_html__('Transactions', 'event_espresso');
51
+		$this->_admin_base_url = TXN_ADMIN_URL;
52
+		$this->_admin_base_path = TXN_ADMIN;
53
+	}
54
+
55
+
56
+	/**
57
+	 *    _ajax_hooks
58
+	 *
59
+	 * @return void
60
+	 */
61
+	protected function _ajax_hooks()
62
+	{
63
+		add_action('wp_ajax_espresso_apply_payment', array($this, 'apply_payments_or_refunds'));
64
+		add_action('wp_ajax_espresso_apply_refund', array($this, 'apply_payments_or_refunds'));
65
+		add_action('wp_ajax_espresso_delete_payment', array($this, 'delete_payment'));
66
+	}
67
+
68
+
69
+	/**
70
+	 *    _define_page_props
71
+	 *
72
+	 * @return void
73
+	 */
74
+	protected function _define_page_props()
75
+	{
76
+		$this->_admin_page_title = $this->page_label;
77
+		$this->_labels = array(
78
+			'buttons' => array(
79
+				'add'    => esc_html__('Add New Transaction', 'event_espresso'),
80
+				'edit'   => esc_html__('Edit Transaction', 'event_espresso'),
81
+				'delete' => esc_html__('Delete Transaction', 'event_espresso'),
82
+			),
83
+		);
84
+	}
85
+
86
+
87
+	/**
88
+	 *        grab url requests and route them
89
+	 *
90
+	 * @access private
91
+	 * @return void
92
+	 * @throws EE_Error
93
+	 * @throws InvalidArgumentException
94
+	 * @throws InvalidDataTypeException
95
+	 * @throws InvalidInterfaceException
96
+	 */
97
+	public function _set_page_routes()
98
+	{
99
+
100
+		$this->_set_transaction_status_array();
101
+
102
+		$txn_id = ! empty($this->_req_data['TXN_ID'])
103
+				  && ! is_array($this->_req_data['TXN_ID'])
104
+			? $this->_req_data['TXN_ID']
105
+			: 0;
106
+
107
+		$this->_page_routes = array(
108
+
109
+			'default' => array(
110
+				'func'       => '_transactions_overview_list_table',
111
+				'capability' => 'ee_read_transactions',
112
+			),
113
+
114
+			'view_transaction' => array(
115
+				'func'       => '_transaction_details',
116
+				'capability' => 'ee_read_transaction',
117
+				'obj_id'     => $txn_id,
118
+			),
119
+
120
+			'send_payment_reminder' => array(
121
+				'func'       => '_send_payment_reminder',
122
+				'noheader'   => true,
123
+				'capability' => 'ee_send_message',
124
+			),
125
+
126
+			'espresso_apply_payment' => array(
127
+				'func'       => 'apply_payments_or_refunds',
128
+				'noheader'   => true,
129
+				'capability' => 'ee_edit_payments',
130
+			),
131
+
132
+			'espresso_apply_refund' => array(
133
+				'func'       => 'apply_payments_or_refunds',
134
+				'noheader'   => true,
135
+				'capability' => 'ee_edit_payments',
136
+			),
137
+
138
+			'espresso_delete_payment' => array(
139
+				'func'       => 'delete_payment',
140
+				'noheader'   => true,
141
+				'capability' => 'ee_delete_payments',
142
+			),
143
+
144
+			'espresso_recalculate_line_items' => array(
145
+				'func'       => 'recalculateLineItems',
146
+				'noheader'   => true,
147
+				'capability' => 'ee_edit_payments',
148
+			),
149
+
150
+		);
151
+	}
152
+
153
+
154
+	protected function _set_page_config()
155
+	{
156
+		$this->_page_config = array(
157
+			'default'          => array(
158
+				'nav'           => array(
159
+					'label' => esc_html__('Overview', 'event_espresso'),
160
+					'order' => 10,
161
+				),
162
+				'list_table'    => 'EE_Admin_Transactions_List_Table',
163
+				'help_tabs'     => array(
164
+					'transactions_overview_help_tab'                       => array(
165
+						'title'    => esc_html__('Transactions Overview', 'event_espresso'),
166
+						'filename' => 'transactions_overview',
167
+					),
168
+					'transactions_overview_table_column_headings_help_tab' => array(
169
+						'title'    => esc_html__('Transactions Table Column Headings', 'event_espresso'),
170
+						'filename' => 'transactions_overview_table_column_headings',
171
+					),
172
+					'transactions_overview_views_filters_help_tab'         => array(
173
+						'title'    => esc_html__('Transaction Views & Filters & Search', 'event_espresso'),
174
+						'filename' => 'transactions_overview_views_filters_search',
175
+					),
176
+				),
177
+				'help_tour'     => array('Transactions_Overview_Help_Tour'),
178
+				/**
179
+				 * commented out because currently we are not displaying tips for transaction list table status but this
180
+				 * may change in a later iteration so want to keep the code for then.
181
+				 */
182
+				// 'qtips' => array( 'Transactions_List_Table_Tips' ),
183
+				'require_nonce' => false,
184
+			),
185
+			'view_transaction' => array(
186
+				'nav'       => array(
187
+					'label'      => esc_html__('View Transaction', 'event_espresso'),
188
+					'order'      => 5,
189
+					'url'        => isset($this->_req_data['TXN_ID'])
190
+						? add_query_arg(array('TXN_ID' => $this->_req_data['TXN_ID']), $this->_current_page_view_url)
191
+						: $this->_admin_base_url,
192
+					'persistent' => false,
193
+				),
194
+				'help_tabs' => array(
195
+					'transactions_view_transaction_help_tab'                                              => array(
196
+						'title'    => esc_html__('View Transaction', 'event_espresso'),
197
+						'filename' => 'transactions_view_transaction',
198
+					),
199
+					'transactions_view_transaction_transaction_details_table_help_tab'                    => array(
200
+						'title'    => esc_html__('Transaction Details Table', 'event_espresso'),
201
+						'filename' => 'transactions_view_transaction_transaction_details_table',
202
+					),
203
+					'transactions_view_transaction_attendees_registered_help_tab'                         => array(
204
+						'title'    => esc_html__('Attendees Registered', 'event_espresso'),
205
+						'filename' => 'transactions_view_transaction_attendees_registered',
206
+					),
207
+					'transactions_view_transaction_views_primary_registrant_billing_information_help_tab' => array(
208
+						'title'    => esc_html__('Primary Registrant & Billing Information', 'event_espresso'),
209
+						'filename' => 'transactions_view_transaction_primary_registrant_billing_information',
210
+					),
211
+				),
212
+				'qtips'     => array('Transaction_Details_Tips'),
213
+				'help_tour' => array('Transaction_Details_Help_Tour'),
214
+				'metaboxes' => array('_transaction_details_metaboxes'),
215
+
216
+				'require_nonce' => false,
217
+			),
218
+		);
219
+	}
220
+
221
+
222
+	/**
223
+	 * The below methods aren't used by this class currently
224
+	 */
225
+	protected function _add_screen_options()
226
+	{
227
+		// noop
228
+	}
229
+
230
+
231
+	protected function _add_feature_pointers()
232
+	{
233
+		// noop
234
+	}
235
+
236
+
237
+	public function admin_init()
238
+	{
239
+		// IF a registration was JUST added via the admin...
240
+		if (isset(
241
+			$this->_req_data['redirect_from'],
242
+			$this->_req_data['EVT_ID'],
243
+			$this->_req_data['event_name']
244
+		)) {
245
+			// then set a cookie so that we can block any attempts to use
246
+			// the back button as a way to enter another registration.
247
+			setcookie(
248
+				'ee_registration_added',
249
+				$this->_req_data['EVT_ID'],
250
+				time() + WEEK_IN_SECONDS,
251
+				'/'
252
+			);
253
+			// and update the global
254
+			$_COOKIE['ee_registration_added'] = $this->_req_data['EVT_ID'];
255
+		}
256
+		EE_Registry::$i18n_js_strings['invalid_server_response'] = esc_html__(
257
+			'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.',
258
+			'event_espresso'
259
+		);
260
+		EE_Registry::$i18n_js_strings['error_occurred'] = esc_html__(
261
+			'An error occurred! Please refresh the page and try again.',
262
+			'event_espresso'
263
+		);
264
+		EE_Registry::$i18n_js_strings['txn_status_array'] = self::$_txn_status;
265
+		EE_Registry::$i18n_js_strings['pay_status_array'] = self::$_pay_status;
266
+		EE_Registry::$i18n_js_strings['payments_total'] = esc_html__('Payments Total', 'event_espresso');
267
+		EE_Registry::$i18n_js_strings['transaction_overpaid'] = esc_html__(
268
+			'This transaction has been overpaid ! Payments Total',
269
+			'event_espresso'
270
+		);
271
+	}
272
+
273
+
274
+	public function admin_notices()
275
+	{
276
+		// noop
277
+	}
278
+
279
+
280
+	public function admin_footer_scripts()
281
+	{
282
+		// noop
283
+	}
284
+
285
+
286
+	/**
287
+	 * _set_transaction_status_array
288
+	 * sets list of transaction statuses
289
+	 *
290
+	 * @access private
291
+	 * @return void
292
+	 * @throws EE_Error
293
+	 * @throws InvalidArgumentException
294
+	 * @throws InvalidDataTypeException
295
+	 * @throws InvalidInterfaceException
296
+	 */
297
+	private function _set_transaction_status_array()
298
+	{
299
+		self::$_txn_status = EEM_Transaction::instance()->status_array(true);
300
+	}
301
+
302
+
303
+	/**
304
+	 * get_transaction_status_array
305
+	 * return the transaction status array for wp_list_table
306
+	 *
307
+	 * @access public
308
+	 * @return array
309
+	 */
310
+	public function get_transaction_status_array()
311
+	{
312
+		return self::$_txn_status;
313
+	}
314
+
315
+
316
+	/**
317
+	 *    get list of payment statuses
318
+	 *
319
+	 * @access private
320
+	 * @return void
321
+	 * @throws EE_Error
322
+	 * @throws InvalidArgumentException
323
+	 * @throws InvalidDataTypeException
324
+	 * @throws InvalidInterfaceException
325
+	 */
326
+	private function _get_payment_status_array()
327
+	{
328
+		self::$_pay_status = EEM_Payment::instance()->status_array(true);
329
+		$this->_template_args['payment_status'] = self::$_pay_status;
330
+	}
331
+
332
+
333
+	/**
334
+	 *    _add_screen_options_default
335
+	 *
336
+	 * @access protected
337
+	 * @return void
338
+	 * @throws InvalidArgumentException
339
+	 * @throws InvalidDataTypeException
340
+	 * @throws InvalidInterfaceException
341
+	 */
342
+	protected function _add_screen_options_default()
343
+	{
344
+		$this->_per_page_screen_option();
345
+	}
346
+
347
+
348
+	/**
349
+	 * load_scripts_styles
350
+	 *
351
+	 * @access public
352
+	 * @return void
353
+	 */
354
+	public function load_scripts_styles()
355
+	{
356
+		// enqueue style
357
+		wp_register_style(
358
+			'espresso_txn',
359
+			TXN_ASSETS_URL . 'espresso_transactions_admin.css',
360
+			array(),
361
+			EVENT_ESPRESSO_VERSION
362
+		);
363
+		wp_enqueue_style('espresso_txn');
364
+		// scripts
365
+		wp_register_script(
366
+			'espresso_txn',
367
+			TXN_ASSETS_URL . 'espresso_transactions_admin.js',
368
+			array(
369
+				'ee_admin_js',
370
+				'ee-datepicker',
371
+				'jquery-ui-datepicker',
372
+				'jquery-ui-draggable',
373
+				'ee-dialog',
374
+				'ee-accounting',
375
+				'ee-serialize-full-array',
376
+			),
377
+			EVENT_ESPRESSO_VERSION,
378
+			true
379
+		);
380
+		wp_enqueue_script('espresso_txn');
381
+	}
382
+
383
+
384
+	/**
385
+	 *    load_scripts_styles_view_transaction
386
+	 *
387
+	 * @access public
388
+	 * @return void
389
+	 */
390
+	public function load_scripts_styles_view_transaction()
391
+	{
392
+		// styles
393
+		wp_enqueue_style('espresso-ui-theme');
394
+	}
395
+
396
+
397
+	/**
398
+	 *    load_scripts_styles_default
399
+	 *
400
+	 * @access public
401
+	 * @return void
402
+	 */
403
+	public function load_scripts_styles_default()
404
+	{
405
+		// styles
406
+		wp_enqueue_style('espresso-ui-theme');
407
+	}
408
+
409
+
410
+	/**
411
+	 *    _set_list_table_views_default
412
+	 *
413
+	 * @access protected
414
+	 * @return void
415
+	 */
416
+	protected function _set_list_table_views_default()
417
+	{
418
+		$this->_views = array(
419
+			'all'        => array(
420
+				'slug'  => 'all',
421
+				'label' => esc_html__('View All Transactions', 'event_espresso'),
422
+				'count' => 0,
423
+			),
424
+			'abandoned'  => array(
425
+				'slug'  => 'abandoned',
426
+				'label' => esc_html__('Abandoned Transactions', 'event_espresso'),
427
+				'count' => 0,
428
+			),
429
+			'incomplete' => array(
430
+				'slug'  => 'incomplete',
431
+				'label' => esc_html__('Incomplete Transactions', 'event_espresso'),
432
+				'count' => 0,
433
+			),
434
+		);
435
+		if (/**
436
+		 * Filters whether a link to the "Failed Transactions" list table
437
+		 * appears on the Transactions Admin Page list table.
438
+		 * List display can be turned back on via the following:
439
+		 * add_filter(
440
+		 *     'FHEE__Transactions_Admin_Page___set_list_table_views_default__display_failed_txns_list',
441
+		 *     '__return_true'
442
+		 * );
443
+		 *
444
+		 * @since 4.9.70.p
445
+		 * @param boolean                 $display_failed_txns_list
446
+		 * @param Transactions_Admin_Page $this
447
+		 */
448
+		apply_filters(
449
+			'FHEE__Transactions_Admin_Page___set_list_table_views_default__display_failed_txns_list',
450
+			false,
451
+			$this
452
+		)
453
+		) {
454
+			$this->_views['failed'] = array(
455
+				'slug'  => 'failed',
456
+				'label' => esc_html__('Failed Transactions', 'event_espresso'),
457
+				'count' => 0,
458
+			);
459
+		}
460
+	}
461
+
462
+
463
+	/**
464
+	 * _set_transaction_object
465
+	 * This sets the _transaction property for the transaction details screen
466
+	 *
467
+	 * @access private
468
+	 * @return void
469
+	 * @throws EE_Error
470
+	 * @throws InvalidArgumentException
471
+	 * @throws RuntimeException
472
+	 * @throws InvalidDataTypeException
473
+	 * @throws InvalidInterfaceException
474
+	 * @throws ReflectionException
475
+	 */
476
+	private function _set_transaction_object()
477
+	{
478
+		if ($this->_transaction instanceof EE_Transaction) {
479
+			return;
480
+		} //get out we've already set the object
481
+
482
+		$TXN_ID = ! empty($this->_req_data['TXN_ID'])
483
+			? absint($this->_req_data['TXN_ID'])
484
+			: false;
485
+
486
+		// get transaction object
487
+		$this->_transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
488
+		$this->_session = $this->_transaction instanceof EE_Transaction
489
+			? $this->_transaction->session_data()
490
+			: null;
491
+		if ($this->_transaction instanceof EE_Transaction) {
492
+			$this->_transaction->verify_abandoned_transaction_status();
493
+		}
494
+
495
+		if (! $this->_transaction instanceof EE_Transaction) {
496
+			$error_msg = sprintf(
497
+				esc_html__(
498
+					'An error occurred and the details for the transaction with the ID # %d could not be retrieved.',
499
+					'event_espresso'
500
+				),
501
+				$TXN_ID
502
+			);
503
+			EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
504
+		}
505
+	}
506
+
507
+
508
+	/**
509
+	 *    _transaction_legend_items
510
+	 *
511
+	 * @access protected
512
+	 * @return array
513
+	 * @throws EE_Error
514
+	 * @throws InvalidArgumentException
515
+	 * @throws ReflectionException
516
+	 * @throws InvalidDataTypeException
517
+	 * @throws InvalidInterfaceException
518
+	 */
519
+	protected function _transaction_legend_items()
520
+	{
521
+		EE_Registry::instance()->load_helper('MSG_Template');
522
+		$items = array();
523
+
524
+		if (EE_Registry::instance()->CAP->current_user_can(
525
+			'ee_read_global_messages',
526
+			'view_filtered_messages'
527
+		)) {
528
+			$related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
529
+			if (is_array($related_for_icon)
530
+				&& isset($related_for_icon['css_class'], $related_for_icon['label'])
531
+			) {
532
+				$items['view_related_messages'] = array(
533
+					'class' => $related_for_icon['css_class'],
534
+					'desc'  => $related_for_icon['label'],
535
+				);
536
+			}
537
+		}
538
+
539
+		$items = apply_filters(
540
+			'FHEE__Transactions_Admin_Page___transaction_legend_items__items',
541
+			array_merge(
542
+				$items,
543
+				array(
544
+					'view_details'          => array(
545
+						'class' => 'dashicons dashicons-cart',
546
+						'desc'  => esc_html__('View Transaction Details', 'event_espresso'),
547
+					),
548
+					'view_invoice'          => array(
549
+						'class' => 'dashicons dashicons-media-spreadsheet',
550
+						'desc'  => esc_html__('View Transaction Invoice', 'event_espresso'),
551
+					),
552
+					'view_receipt'          => array(
553
+						'class' => 'dashicons dashicons-media-default',
554
+						'desc'  => esc_html__('View Transaction Receipt', 'event_espresso'),
555
+					),
556
+					'view_registration'     => array(
557
+						'class' => 'dashicons dashicons-clipboard',
558
+						'desc'  => esc_html__('View Registration Details', 'event_espresso'),
559
+					),
560
+					'payment_overview_link' => array(
561
+						'class' => 'dashicons dashicons-money',
562
+						'desc'  => esc_html__('Make Payment on Frontend', 'event_espresso'),
563
+					),
564
+				)
565
+			)
566
+		);
567
+
568
+		if (EEH_MSG_Template::is_mt_active('payment_reminder')
569
+			&& EE_Registry::instance()->CAP->current_user_can(
570
+				'ee_send_message',
571
+				'espresso_transactions_send_payment_reminder'
572
+			)
573
+		) {
574
+			$items['send_payment_reminder'] = array(
575
+				'class' => 'dashicons dashicons-email-alt',
576
+				'desc'  => esc_html__('Send Payment Reminder', 'event_espresso'),
577
+			);
578
+		} else {
579
+			$items['blank*'] = array(
580
+				'class' => '',
581
+				'desc'  => '',
582
+			);
583
+		}
584
+		$more_items = apply_filters(
585
+			'FHEE__Transactions_Admin_Page___transaction_legend_items__more_items',
586
+			array(
587
+				'overpaid'   => array(
588
+					'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::overpaid_status_code,
589
+					'desc'  => EEH_Template::pretty_status(
590
+						EEM_Transaction::overpaid_status_code,
591
+						false,
592
+						'sentence'
593
+					),
594
+				),
595
+				'complete'   => array(
596
+					'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::complete_status_code,
597
+					'desc'  => EEH_Template::pretty_status(
598
+						EEM_Transaction::complete_status_code,
599
+						false,
600
+						'sentence'
601
+					),
602
+				),
603
+				'incomplete' => array(
604
+					'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::incomplete_status_code,
605
+					'desc'  => EEH_Template::pretty_status(
606
+						EEM_Transaction::incomplete_status_code,
607
+						false,
608
+						'sentence'
609
+					),
610
+				),
611
+				'abandoned'  => array(
612
+					'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::abandoned_status_code,
613
+					'desc'  => EEH_Template::pretty_status(
614
+						EEM_Transaction::abandoned_status_code,
615
+						false,
616
+						'sentence'
617
+					),
618
+				),
619
+				'failed'     => array(
620
+					'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::failed_status_code,
621
+					'desc'  => EEH_Template::pretty_status(
622
+						EEM_Transaction::failed_status_code,
623
+						false,
624
+						'sentence'
625
+					),
626
+				),
627
+			)
628
+		);
629
+
630
+		return array_merge($items, $more_items);
631
+	}
632
+
633
+
634
+	/**
635
+	 *    _transactions_overview_list_table
636
+	 *
637
+	 * @access protected
638
+	 * @return void
639
+	 * @throws DomainException
640
+	 * @throws EE_Error
641
+	 * @throws InvalidArgumentException
642
+	 * @throws InvalidDataTypeException
643
+	 * @throws InvalidInterfaceException
644
+	 * @throws ReflectionException
645
+	 */
646
+	protected function _transactions_overview_list_table()
647
+	{
648
+		$this->_admin_page_title = esc_html__('Transactions', 'event_espresso');
649
+		$event = isset($this->_req_data['EVT_ID'])
650
+			? EEM_Event::instance()->get_one_by_ID($this->_req_data['EVT_ID'])
651
+			: null;
652
+		$this->_template_args['admin_page_header'] = $event instanceof EE_Event
653
+			? sprintf(
654
+				esc_html__(
655
+					'%sViewing Transactions for the Event: %s%s',
656
+					'event_espresso'
657
+				),
658
+				'<h3>',
659
+				'<a href="'
660
+				. EE_Admin_Page::add_query_args_and_nonce(
661
+					array('action' => 'edit', 'post' => $event->ID()),
662
+					EVENTS_ADMIN_URL
663
+				)
664
+				. '" title="'
665
+				. esc_attr__(
666
+					'Click to Edit event',
667
+					'event_espresso'
668
+				)
669
+				. '">' . $event->name() . '</a>',
670
+				'</h3>'
671
+			)
672
+			: '';
673
+		$this->_template_args['after_list_table'] = $this->_display_legend($this->_transaction_legend_items());
674
+		$this->display_admin_list_table_page_with_no_sidebar();
675
+	}
676
+
677
+
678
+	/**
679
+	 *    _transaction_details
680
+	 * generates HTML for the View Transaction Details Admin page
681
+	 *
682
+	 * @access protected
683
+	 * @return void
684
+	 * @throws DomainException
685
+	 * @throws EE_Error
686
+	 * @throws InvalidArgumentException
687
+	 * @throws InvalidDataTypeException
688
+	 * @throws InvalidInterfaceException
689
+	 * @throws RuntimeException
690
+	 * @throws ReflectionException
691
+	 */
692
+	protected function _transaction_details()
693
+	{
694
+		do_action('AHEE__Transactions_Admin_Page__transaction_details__start', $this->_transaction);
695
+
696
+		$this->_set_transaction_status_array();
697
+
698
+		$this->_template_args = array();
699
+		$this->_template_args['transactions_page'] = $this->_wp_page_slug;
700
+
701
+		$this->_set_transaction_object();
702
+
703
+		if (! $this->_transaction instanceof EE_Transaction) {
704
+			return;
705
+		}
706
+		$primary_registration = $this->_transaction->primary_registration();
707
+		$attendee = $primary_registration instanceof EE_Registration
708
+			? $primary_registration->attendee()
709
+			: null;
710
+
711
+		$this->_template_args['txn_nmbr']['value'] = $this->_transaction->ID();
712
+		$this->_template_args['txn_nmbr']['label'] = esc_html__('Transaction Number', 'event_espresso');
713
+
714
+		$this->_template_args['txn_datetime']['value'] = $this->_transaction->get_i18n_datetime('TXN_timestamp');
715
+		$this->_template_args['txn_datetime']['label'] = esc_html__('Date', 'event_espresso');
716
+
717
+		$this->_template_args['txn_status']['value'] = self::$_txn_status[ $this->_transaction->status_ID() ];
718
+		$this->_template_args['txn_status']['label'] = esc_html__('Transaction Status', 'event_espresso');
719
+		$this->_template_args['txn_status']['class'] = 'status-' . $this->_transaction->status_ID();
720
+
721
+		$this->_template_args['grand_total'] = $this->_transaction->total();
722
+		$this->_template_args['total_paid'] = $this->_transaction->paid();
723
+
724
+		$amount_due = $this->_transaction->total() - $this->_transaction->paid();
725
+		$this->_template_args['amount_due'] = EEH_Template::format_currency(
726
+			$amount_due,
727
+			true
728
+		);
729
+		if (EE_Registry::instance()->CFG->currency->sign_b4) {
730
+			$this->_template_args['amount_due'] = EE_Registry::instance()->CFG->currency->sign
731
+												  . $this->_template_args['amount_due'];
732
+		} else {
733
+			$this->_template_args['amount_due'] .= EE_Registry::instance()->CFG->currency->sign;
734
+		}
735
+		$this->_template_args['amount_due_class'] = '';
736
+
737
+		if ($this->_transaction->paid() === $this->_transaction->total()) {
738
+			// paid in full
739
+			$this->_template_args['amount_due'] = false;
740
+		} elseif ($this->_transaction->paid() > $this->_transaction->total()) {
741
+			// overpaid
742
+			$this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn';
743
+		} elseif ($this->_transaction->total() > (float) 0) {
744
+			if ($this->_transaction->paid() > (float) 0) {
745
+				// monies owing
746
+				$this->_template_args['amount_due_class'] = 'txn-overview-part-payment-spn';
747
+			} elseif ($this->_transaction->paid() === (float) 0) {
748
+				// no payments made yet
749
+				$this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn';
750
+			}
751
+		} elseif ($this->_transaction->total() === (float) 0) {
752
+			// free event
753
+			$this->_template_args['amount_due'] = false;
754
+		}
755
+
756
+		$payment_method = $this->_transaction->payment_method();
757
+
758
+		$this->_template_args['method_of_payment_name'] = $payment_method instanceof EE_Payment_Method
759
+			? $payment_method->admin_name()
760
+			: esc_html__('Unknown', 'event_espresso');
761
+
762
+		$this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
763
+		// link back to overview
764
+		$this->_template_args['txn_overview_url'] = ! empty($_SERVER['HTTP_REFERER'])
765
+			? $_SERVER['HTTP_REFERER']
766
+			: TXN_ADMIN_URL;
767
+
768
+
769
+		// next link
770
+		$next_txn = $this->_transaction->next(
771
+			null,
772
+			array(array('STS_ID' => array('!=', EEM_Transaction::failed_status_code))),
773
+			'TXN_ID'
774
+		);
775
+		$this->_template_args['next_transaction'] = $next_txn
776
+			? $this->_next_link(
777
+				EE_Admin_Page::add_query_args_and_nonce(
778
+					array('action' => 'view_transaction', 'TXN_ID' => $next_txn['TXN_ID']),
779
+					TXN_ADMIN_URL
780
+				),
781
+				'dashicons dashicons-arrow-right ee-icon-size-22'
782
+			)
783
+			: '';
784
+		// previous link
785
+		$previous_txn = $this->_transaction->previous(
786
+			null,
787
+			array(array('STS_ID' => array('!=', EEM_Transaction::failed_status_code))),
788
+			'TXN_ID'
789
+		);
790
+		$this->_template_args['previous_transaction'] = $previous_txn
791
+			? $this->_previous_link(
792
+				EE_Admin_Page::add_query_args_and_nonce(
793
+					array('action' => 'view_transaction', 'TXN_ID' => $previous_txn['TXN_ID']),
794
+					TXN_ADMIN_URL
795
+				),
796
+				'dashicons dashicons-arrow-left ee-icon-size-22'
797
+			)
798
+			: '';
799
+
800
+		// were we just redirected here after adding a new registration ???
801
+		if (isset(
802
+			$this->_req_data['redirect_from'],
803
+			$this->_req_data['EVT_ID'],
804
+			$this->_req_data['event_name']
805
+		)) {
806
+			if (EE_Registry::instance()->CAP->current_user_can(
807
+				'ee_edit_registrations',
808
+				'espresso_registrations_new_registration',
809
+				$this->_req_data['EVT_ID']
810
+			)) {
811
+				$this->_admin_page_title .= '<a id="add-new-registration" class="add-new-h2 button-primary" href="';
812
+				$this->_admin_page_title .= EE_Admin_Page::add_query_args_and_nonce(
813
+					array(
814
+						'page'     => 'espresso_registrations',
815
+						'action'   => 'new_registration',
816
+						'return'   => 'default',
817
+						'TXN_ID'   => $this->_transaction->ID(),
818
+						'event_id' => $this->_req_data['EVT_ID'],
819
+					),
820
+					REG_ADMIN_URL
821
+				);
822
+				$this->_admin_page_title .= '">';
823
+
824
+				$this->_admin_page_title .= sprintf(
825
+					esc_html__('Add Another New Registration to Event: "%1$s" ?', 'event_espresso'),
826
+					htmlentities(urldecode($this->_req_data['event_name']), ENT_QUOTES, 'UTF-8')
827
+				);
828
+				$this->_admin_page_title .= '</a>';
829
+			}
830
+			EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
831
+		}
832
+		// grab messages at the last second
833
+		$this->_template_args['notices'] = EE_Error::get_notices();
834
+		// path to template
835
+		$template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_header.template.php';
836
+		$this->_template_args['admin_page_header'] = EEH_Template::display_template(
837
+			$template_path,
838
+			$this->_template_args,
839
+			true
840
+		);
841
+
842
+		// the details template wrapper
843
+		$this->display_admin_page_with_sidebar();
844
+	}
845
+
846
+
847
+	/**
848
+	 *        _transaction_details_metaboxes
849
+	 *
850
+	 * @access protected
851
+	 * @return void
852
+	 * @throws EE_Error
853
+	 * @throws InvalidArgumentException
854
+	 * @throws InvalidDataTypeException
855
+	 * @throws InvalidInterfaceException
856
+	 * @throws RuntimeException
857
+	 * @throws ReflectionException
858
+	 */
859
+	protected function _transaction_details_metaboxes()
860
+	{
861
+
862
+		$this->_set_transaction_object();
863
+
864
+		if (! $this->_transaction instanceof EE_Transaction) {
865
+			return;
866
+		}
867
+		add_meta_box(
868
+			'edit-txn-details-mbox',
869
+			esc_html__('Transaction Details', 'event_espresso'),
870
+			array($this, 'txn_details_meta_box'),
871
+			$this->_wp_page_slug,
872
+			'normal',
873
+			'high'
874
+		);
875
+		add_meta_box(
876
+			'edit-txn-attendees-mbox',
877
+			esc_html__('Attendees Registered in this Transaction', 'event_espresso'),
878
+			array($this, 'txn_attendees_meta_box'),
879
+			$this->_wp_page_slug,
880
+			'normal',
881
+			'high',
882
+			array('TXN_ID' => $this->_transaction->ID())
883
+		);
884
+		add_meta_box(
885
+			'edit-txn-registrant-mbox',
886
+			esc_html__('Primary Contact', 'event_espresso'),
887
+			array($this, 'txn_registrant_side_meta_box'),
888
+			$this->_wp_page_slug,
889
+			'side',
890
+			'high'
891
+		);
892
+		add_meta_box(
893
+			'edit-txn-billing-info-mbox',
894
+			esc_html__('Billing Information', 'event_espresso'),
895
+			array($this, 'txn_billing_info_side_meta_box'),
896
+			$this->_wp_page_slug,
897
+			'side',
898
+			'high'
899
+		);
900
+	}
901
+
902
+
903
+	/**
904
+	 * Callback for transaction actions metabox.
905
+	 *
906
+	 * @param EE_Transaction|null $transaction
907
+	 * @return string
908
+	 * @throws DomainException
909
+	 * @throws EE_Error
910
+	 * @throws InvalidArgumentException
911
+	 * @throws InvalidDataTypeException
912
+	 * @throws InvalidInterfaceException
913
+	 * @throws ReflectionException
914
+	 * @throws RuntimeException
915
+	 */
916
+	public function getActionButtons(EE_Transaction $transaction = null)
917
+	{
918
+		$content = '';
919
+		$actions = array();
920
+		if (! $transaction instanceof EE_Transaction) {
921
+			return $content;
922
+		}
923
+		/** @var EE_Registration $primary_registration */
924
+		$primary_registration = $transaction->primary_registration();
925
+		$attendee = $primary_registration instanceof EE_Registration
926
+			? $primary_registration->attendee()
927
+			: null;
928
+
929
+		if ($attendee instanceof EE_Attendee
930
+			&& EE_Registry::instance()->CAP->current_user_can(
931
+				'ee_send_message',
932
+				'espresso_transactions_send_payment_reminder'
933
+			)
934
+		) {
935
+			$actions['payment_reminder'] =
936
+				EEH_MSG_Template::is_mt_active('payment_reminder')
937
+				&& $this->_transaction->status_ID() !== EEM_Transaction::complete_status_code
938
+				&& $this->_transaction->status_ID() !== EEM_Transaction::overpaid_status_code
939
+					? EEH_Template::get_button_or_link(
940
+						EE_Admin_Page::add_query_args_and_nonce(
941
+							array(
942
+								'action'      => 'send_payment_reminder',
943
+								'TXN_ID'      => $this->_transaction->ID(),
944
+								'redirect_to' => 'view_transaction',
945
+							),
946
+							TXN_ADMIN_URL
947
+						),
948
+						esc_html__(' Send Payment Reminder', 'event_espresso'),
949
+						'button secondary-button',
950
+						'dashicons dashicons-email-alt'
951
+					)
952
+					: '';
953
+		}
954
+
955
+		if (EE_Registry::instance()->CAP->current_user_can(
956
+			'ee_edit_payments',
957
+			'espresso_transactions_recalculate_line_items'
958
+		)
959
+		) {
960
+			$actions['recalculate_line_items'] = EEH_Template::get_button_or_link(
961
+				EE_Admin_Page::add_query_args_and_nonce(
962
+					array(
963
+						'action'      => 'espresso_recalculate_line_items',
964
+						'TXN_ID'      => $this->_transaction->ID(),
965
+						'redirect_to' => 'view_transaction',
966
+					),
967
+					TXN_ADMIN_URL
968
+				),
969
+				esc_html__(' Recalculate Taxes and Total', 'event_espresso'),
970
+				'button secondary-button',
971
+				'dashicons dashicons-update'
972
+			);
973
+		}
974
+
975
+		if ($primary_registration instanceof EE_Registration
976
+			&& EEH_MSG_Template::is_mt_active('receipt')
977
+		) {
978
+			$actions['receipt'] = EEH_Template::get_button_or_link(
979
+				$primary_registration->receipt_url(),
980
+				esc_html__('View Receipt', 'event_espresso'),
981
+				'button secondary-button',
982
+				'dashicons dashicons-media-default'
983
+			);
984
+		}
985
+
986
+		if ($primary_registration instanceof EE_Registration
987
+			&& EEH_MSG_Template::is_mt_active('invoice')
988
+		) {
989
+			$actions['invoice'] = EEH_Template::get_button_or_link(
990
+				$primary_registration->invoice_url(),
991
+				esc_html__('View Invoice', 'event_espresso'),
992
+				'button secondary-button',
993
+				'dashicons dashicons-media-spreadsheet'
994
+			);
995
+		}
996
+		$actions = array_filter(
997
+			apply_filters('FHEE__Transactions_Admin_Page__getActionButtons__actions', $actions, $transaction)
998
+		);
999
+		if ($actions) {
1000
+			$content = '<ul>';
1001
+			$content .= '<li>' . implode('</li><li>', $actions) . '</li>';
1002
+			$content .= '</uL>';
1003
+		}
1004
+		return $content;
1005
+	}
1006
+
1007
+
1008
+	/**
1009
+	 * txn_details_meta_box
1010
+	 * generates HTML for the Transaction main meta box
1011
+	 *
1012
+	 * @return void
1013
+	 * @throws DomainException
1014
+	 * @throws EE_Error
1015
+	 * @throws InvalidArgumentException
1016
+	 * @throws InvalidDataTypeException
1017
+	 * @throws InvalidInterfaceException
1018
+	 * @throws RuntimeException
1019
+	 * @throws ReflectionException
1020
+	 */
1021
+	public function txn_details_meta_box()
1022
+	{
1023
+		$this->_set_transaction_object();
1024
+		$this->_template_args['TXN_ID'] = $this->_transaction->ID();
1025
+		$this->_template_args['attendee'] = $this->_transaction->primary_registration() instanceof EE_Registration
1026
+			? $this->_transaction->primary_registration()->attendee()
1027
+			: null;
1028
+		$this->_template_args['can_edit_payments'] = EE_Registry::instance()->CAP->current_user_can(
1029
+			'ee_edit_payments',
1030
+			'apply_payment_or_refund_from_registration_details'
1031
+		);
1032
+		$this->_template_args['can_delete_payments'] = EE_Registry::instance()->CAP->current_user_can(
1033
+			'ee_delete_payments',
1034
+			'delete_payment_from_registration_details'
1035
+		);
1036
+
1037
+		// get line table
1038
+		EEH_Autoloader::register_line_item_display_autoloaders();
1039
+		$Line_Item_Display = new EE_Line_Item_Display(
1040
+			'admin_table',
1041
+			'EE_Admin_Table_Line_Item_Display_Strategy'
1042
+		);
1043
+		$this->_template_args['line_item_table'] = $Line_Item_Display->display_line_item(
1044
+			$this->_transaction->total_line_item()
1045
+		);
1046
+		$this->_template_args['REG_code'] = $this->_transaction->primary_registration()->reg_code();
1047
+
1048
+		// process taxes
1049
+		$taxes = $this->_transaction->line_items(array(array('LIN_type' => EEM_Line_Item::type_tax)));
1050
+		$this->_template_args['taxes'] = ! empty($taxes) ? $taxes : false;
1051
+
1052
+		$this->_template_args['grand_total'] = EEH_Template::format_currency(
1053
+			$this->_transaction->total(),
1054
+			false,
1055
+			false
1056
+		);
1057
+		$this->_template_args['grand_raw_total'] = $this->_transaction->total();
1058
+		$this->_template_args['TXN_status'] = $this->_transaction->status_ID();
1059
+
1060
+		// process payment details
1061
+		$payments = $this->_transaction->payments();
1062
+		if (! empty($payments)) {
1063
+			$this->_template_args['payments'] = $payments;
1064
+			$this->_template_args['existing_reg_payments'] = $this->_get_registration_payment_IDs($payments);
1065
+		} else {
1066
+			$this->_template_args['payments'] = false;
1067
+			$this->_template_args['existing_reg_payments'] = array();
1068
+		}
1069
+
1070
+		$this->_template_args['edit_payment_url'] = add_query_arg(array('action' => 'edit_payment'), TXN_ADMIN_URL);
1071
+		$this->_template_args['delete_payment_url'] = add_query_arg(
1072
+			array('action' => 'espresso_delete_payment'),
1073
+			TXN_ADMIN_URL
1074
+		);
1075
+
1076
+		if (isset($txn_details['invoice_number'])) {
1077
+			$this->_template_args['txn_details']['invoice_number']['value'] = $this->_template_args['REG_code'];
1078
+			$this->_template_args['txn_details']['invoice_number']['label'] = esc_html__(
1079
+				'Invoice Number',
1080
+				'event_espresso'
1081
+			);
1082
+		}
1083
+
1084
+		$this->_template_args['txn_details']['registration_session']['value'] = $this->_transaction
1085
+			->primary_registration()
1086
+			->session_ID();
1087
+		$this->_template_args['txn_details']['registration_session']['label'] = esc_html__(
1088
+			'Registration Session',
1089
+			'event_espresso'
1090
+		);
1091
+
1092
+		$this->_template_args['txn_details']['ip_address']['value'] = isset($this->_session['ip_address'])
1093
+			? $this->_session['ip_address']
1094
+			: '';
1095
+		$this->_template_args['txn_details']['ip_address']['label'] = esc_html__(
1096
+			'Transaction placed from IP',
1097
+			'event_espresso'
1098
+		);
1099
+
1100
+		$this->_template_args['txn_details']['user_agent']['value'] = isset($this->_session['user_agent'])
1101
+			? $this->_session['user_agent']
1102
+			: '';
1103
+		$this->_template_args['txn_details']['user_agent']['label'] = esc_html__(
1104
+			'Registrant User Agent',
1105
+			'event_espresso'
1106
+		);
1107
+
1108
+		$reg_steps = '<ul>';
1109
+		foreach ($this->_transaction->reg_steps() as $reg_step => $reg_step_status) {
1110
+			if ($reg_step_status === true) {
1111
+				$reg_steps .= '<li style="color:#70cc50">'
1112
+							  . sprintf(
1113
+								  esc_html__('%1$s : Completed', 'event_espresso'),
1114
+								  ucwords(str_replace('_', ' ', $reg_step))
1115
+							  )
1116
+							  . '</li>';
1117
+			} elseif (is_numeric($reg_step_status) && $reg_step_status !== false) {
1118
+				$reg_steps .= '<li style="color:#2EA2CC">'
1119
+							  . sprintf(
1120
+								  esc_html__('%1$s : Initiated %2$s', 'event_espresso'),
1121
+								  ucwords(str_replace('_', ' ', $reg_step)),
1122
+								  date(
1123
+									  get_option('date_format') . ' ' . get_option('time_format'),
1124
+									  $reg_step_status + (get_option('gmt_offset') * HOUR_IN_SECONDS)
1125
+								  )
1126
+							  )
1127
+							  . '</li>';
1128
+			} else {
1129
+				$reg_steps .= '<li style="color:#E76700">'
1130
+							  . sprintf(
1131
+								  esc_html__('%1$s : Never Initiated', 'event_espresso'),
1132
+								  ucwords(str_replace('_', ' ', $reg_step))
1133
+							  )
1134
+							  . '</li>';
1135
+			}
1136
+		}
1137
+		$reg_steps .= '</ul>';
1138
+		$this->_template_args['txn_details']['reg_steps']['value'] = $reg_steps;
1139
+		$this->_template_args['txn_details']['reg_steps']['label'] = esc_html__(
1140
+			'Registration Step Progress',
1141
+			'event_espresso'
1142
+		);
1143
+
1144
+
1145
+		$this->_get_registrations_to_apply_payment_to();
1146
+		$this->_get_payment_methods($payments);
1147
+		$this->_get_payment_status_array();
1148
+		$this->_get_reg_status_selection(); // sets up the template args for the reg status array for the transaction.
1149
+
1150
+		$this->_template_args['transaction_form_url'] = add_query_arg(
1151
+			array(
1152
+				'action'  => 'edit_transaction',
1153
+				'process' => 'transaction',
1154
+			),
1155
+			TXN_ADMIN_URL
1156
+		);
1157
+		$this->_template_args['apply_payment_form_url'] = add_query_arg(
1158
+			array(
1159
+				'page'   => 'espresso_transactions',
1160
+				'action' => 'espresso_apply_payment',
1161
+			),
1162
+			WP_AJAX_URL
1163
+		);
1164
+		$this->_template_args['delete_payment_form_url'] = add_query_arg(
1165
+			array(
1166
+				'page'   => 'espresso_transactions',
1167
+				'action' => 'espresso_delete_payment',
1168
+			),
1169
+			WP_AJAX_URL
1170
+		);
1171
+
1172
+		$this->_template_args['action_buttons'] = $this->getActionButtons($this->_transaction);
1173
+
1174
+		// 'espresso_delete_payment_nonce'
1175
+
1176
+		$template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_txn_details.template.php';
1177
+		echo EEH_Template::display_template($template_path, $this->_template_args, true);
1178
+	}
1179
+
1180
+
1181
+	/**
1182
+	 * _get_registration_payment_IDs
1183
+	 *    generates an array of Payment IDs and their corresponding Registration IDs
1184
+	 *
1185
+	 * @access protected
1186
+	 * @param EE_Payment[] $payments
1187
+	 * @return array
1188
+	 * @throws EE_Error
1189
+	 * @throws InvalidArgumentException
1190
+	 * @throws InvalidDataTypeException
1191
+	 * @throws InvalidInterfaceException
1192
+	 * @throws ReflectionException
1193
+	 */
1194
+	protected function _get_registration_payment_IDs($payments = array())
1195
+	{
1196
+		$existing_reg_payments = array();
1197
+		// get all reg payments for these payments
1198
+		$reg_payments = EEM_Registration_Payment::instance()->get_all(
1199
+			array(
1200
+				array(
1201
+					'PAY_ID' => array(
1202
+						'IN',
1203
+						array_keys($payments),
1204
+					),
1205
+				),
1206
+			)
1207
+		);
1208
+		if (! empty($reg_payments)) {
1209
+			foreach ($payments as $payment) {
1210
+				if (! $payment instanceof EE_Payment) {
1211
+					continue;
1212
+				} elseif (! isset($existing_reg_payments[ $payment->ID() ])) {
1213
+					$existing_reg_payments[ $payment->ID() ] = array();
1214
+				}
1215
+				foreach ($reg_payments as $reg_payment) {
1216
+					if ($reg_payment instanceof EE_Registration_Payment
1217
+						&& $reg_payment->payment_ID() === $payment->ID()
1218
+					) {
1219
+						$existing_reg_payments[ $payment->ID() ][] = $reg_payment->registration_ID();
1220
+					}
1221
+				}
1222
+			}
1223
+		}
1224
+
1225
+		return $existing_reg_payments;
1226
+	}
1227
+
1228
+
1229
+	/**
1230
+	 * _get_registrations_to_apply_payment_to
1231
+	 *    generates HTML for displaying a series of checkboxes in the admin payment modal window
1232
+	 * which allows the admin to only apply the payment to the specific registrations
1233
+	 *
1234
+	 * @access protected
1235
+	 * @return void
1236
+	 * @throws EE_Error
1237
+	 * @throws InvalidArgumentException
1238
+	 * @throws InvalidDataTypeException
1239
+	 * @throws InvalidInterfaceException
1240
+	 * @throws ReflectionException
1241
+	 */
1242
+	protected function _get_registrations_to_apply_payment_to()
1243
+	{
1244
+		// we want any registration with an active status (ie: not deleted or cancelled)
1245
+		$query_params = array(
1246
+			array(
1247
+				'STS_ID' => array(
1248
+					'IN',
1249
+					array(
1250
+						EEM_Registration::status_id_approved,
1251
+						EEM_Registration::status_id_pending_payment,
1252
+						EEM_Registration::status_id_not_approved,
1253
+					),
1254
+				),
1255
+			),
1256
+		);
1257
+		$registrations_to_apply_payment_to = EEH_HTML::br() . EEH_HTML::div(
1258
+			'',
1259
+			'txn-admin-apply-payment-to-registrations-dv',
1260
+			'',
1261
+			'clear: both; margin: 1.5em 0 0; display: none;'
1262
+		);
1263
+		$registrations_to_apply_payment_to .= EEH_HTML::br() . EEH_HTML::div('', '', 'admin-primary-mbox-tbl-wrap');
1264
+		$registrations_to_apply_payment_to .= EEH_HTML::table('', '', 'admin-primary-mbox-tbl');
1265
+		$registrations_to_apply_payment_to .= EEH_HTML::thead(
1266
+			EEH_HTML::tr(
1267
+				EEH_HTML::th(esc_html__('ID', 'event_espresso')) .
1268
+				EEH_HTML::th(esc_html__('Registrant', 'event_espresso')) .
1269
+				EEH_HTML::th(esc_html__('Ticket', 'event_espresso')) .
1270
+				EEH_HTML::th(esc_html__('Event', 'event_espresso')) .
1271
+				EEH_HTML::th(esc_html__('Paid', 'event_espresso'), '', 'txn-admin-payment-paid-td jst-cntr') .
1272
+				EEH_HTML::th(esc_html__('Owing', 'event_espresso'), '', 'txn-admin-payment-owing-td jst-cntr') .
1273
+				EEH_HTML::th(esc_html__('Apply', 'event_espresso'), '', 'jst-cntr')
1274
+			)
1275
+		);
1276
+		$registrations_to_apply_payment_to .= EEH_HTML::tbody();
1277
+		// get registrations for TXN
1278
+		$registrations = $this->_transaction->registrations($query_params);
1279
+		$existing_reg_payments = $this->_template_args['existing_reg_payments'];
1280
+		foreach ($registrations as $registration) {
1281
+			if ($registration instanceof EE_Registration) {
1282
+				$attendee_name = $registration->attendee() instanceof EE_Attendee
1283
+					? $registration->attendee()->full_name()
1284
+					: esc_html__('Unknown Attendee', 'event_espresso');
1285
+				$owing = $registration->final_price() - $registration->paid();
1286
+				$taxable = $registration->ticket()->taxable()
1287
+					? ' <span class="smaller-text lt-grey-text"> ' . esc_html__('+ tax', 'event_espresso') . '</span>'
1288
+					: '';
1289
+				$checked = empty($existing_reg_payments)
1290
+						   || in_array($registration->ID(), $existing_reg_payments, true)
1291
+					? ' checked="checked"'
1292
+					: '';
1293
+				$disabled = $registration->final_price() > 0 ? '' : ' disabled';
1294
+				$registrations_to_apply_payment_to .= EEH_HTML::tr(
1295
+					EEH_HTML::td($registration->ID()) .
1296
+					EEH_HTML::td($attendee_name) .
1297
+					EEH_HTML::td(
1298
+						$registration->ticket()->name() . ' : ' . $registration->ticket()->pretty_price() . $taxable
1299
+					) .
1300
+					EEH_HTML::td($registration->event_name()) .
1301
+					EEH_HTML::td($registration->pretty_paid(), '', 'txn-admin-payment-paid-td jst-cntr') .
1302
+					EEH_HTML::td(
1303
+						EEH_Template::format_currency($owing),
1304
+						'',
1305
+						'txn-admin-payment-owing-td jst-cntr'
1306
+					) .
1307
+					EEH_HTML::td(
1308
+						'<input type="checkbox" value="' . $registration->ID()
1309
+						. '" name="txn_admin_payment[registrations]"'
1310
+						. $checked . $disabled . '>',
1311
+						'',
1312
+						'jst-cntr'
1313
+					),
1314
+					'apply-payment-registration-row-' . $registration->ID()
1315
+				);
1316
+			}
1317
+		}
1318
+		$registrations_to_apply_payment_to .= EEH_HTML::tbodyx();
1319
+		$registrations_to_apply_payment_to .= EEH_HTML::tablex();
1320
+		$registrations_to_apply_payment_to .= EEH_HTML::divx();
1321
+		$registrations_to_apply_payment_to .= EEH_HTML::p(
1322
+			esc_html__(
1323
+				'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.',
1324
+				'event_espresso'
1325
+			),
1326
+			'',
1327
+			'clear description'
1328
+		);
1329
+		$registrations_to_apply_payment_to .= EEH_HTML::divx();
1330
+		$this->_template_args['registrations_to_apply_payment_to'] = $registrations_to_apply_payment_to;
1331
+	}
1332
+
1333
+
1334
+	/**
1335
+	 * _get_reg_status_selection
1336
+	 *
1337
+	 * @todo   this will need to be adjusted either once MER comes along OR we move default reg status to tickets
1338
+	 *         instead of events.
1339
+	 * @access protected
1340
+	 * @return void
1341
+	 * @throws EE_Error
1342
+	 */
1343
+	protected function _get_reg_status_selection()
1344
+	{
1345
+		// first get all possible statuses
1346
+		$statuses = EEM_Registration::reg_status_array(array(), true);
1347
+		// let's add a "don't change" option.
1348
+		$status_array['NAN'] = esc_html__('Leave the Same', 'event_espresso');
1349
+		$status_array = array_merge($status_array, $statuses);
1350
+		$this->_template_args['status_change_select'] = EEH_Form_Fields::select_input(
1351
+			'txn_reg_status_change[reg_status]',
1352
+			$status_array,
1353
+			'NAN',
1354
+			'id="txn-admin-payment-reg-status-inp"',
1355
+			'txn-reg-status-change-reg-status'
1356
+		);
1357
+		$this->_template_args['delete_status_change_select'] = EEH_Form_Fields::select_input(
1358
+			'delete_txn_reg_status_change[reg_status]',
1359
+			$status_array,
1360
+			'NAN',
1361
+			'delete-txn-admin-payment-reg-status-inp',
1362
+			'delete-txn-reg-status-change-reg-status'
1363
+		);
1364
+	}
1365
+
1366
+
1367
+	/**
1368
+	 *    _get_payment_methods
1369
+	 * Gets all the payment methods available generally, or the ones that are already
1370
+	 * selected on these payments (in case their payment methods are no longer active).
1371
+	 * Has the side-effect of updating the template args' payment_methods item
1372
+	 *
1373
+	 * @access private
1374
+	 * @param EE_Payment[] to show on this page
1375
+	 * @return void
1376
+	 * @throws EE_Error
1377
+	 * @throws InvalidArgumentException
1378
+	 * @throws InvalidDataTypeException
1379
+	 * @throws InvalidInterfaceException
1380
+	 * @throws ReflectionException
1381
+	 */
1382
+	private function _get_payment_methods($payments = array())
1383
+	{
1384
+		$payment_methods_of_payments = array();
1385
+		foreach ($payments as $payment) {
1386
+			if ($payment instanceof EE_Payment) {
1387
+				$payment_methods_of_payments[] = $payment->ID();
1388
+			}
1389
+		}
1390
+		if ($payment_methods_of_payments) {
1391
+			$query_args = array(
1392
+				array(
1393
+					'OR*payment_method_for_payment' => array(
1394
+						'PMD_ID'    => array('IN', $payment_methods_of_payments),
1395
+						'PMD_scope' => array('LIKE', '%' . EEM_Payment_Method::scope_admin . '%'),
1396
+					),
1397
+				),
1398
+			);
1399
+		} else {
1400
+			$query_args = array(array('PMD_scope' => array('LIKE', '%' . EEM_Payment_Method::scope_admin . '%')));
1401
+		}
1402
+		$this->_template_args['payment_methods'] = EEM_Payment_Method::instance()->get_all($query_args);
1403
+	}
1404
+
1405
+
1406
+	/**
1407
+	 * txn_attendees_meta_box
1408
+	 *    generates HTML for the Attendees Transaction main meta box
1409
+	 *
1410
+	 * @access public
1411
+	 * @param WP_Post $post
1412
+	 * @param array   $metabox
1413
+	 * @return void
1414
+	 * @throws DomainException
1415
+	 * @throws EE_Error
1416
+	 * @throws InvalidArgumentException
1417
+	 * @throws InvalidDataTypeException
1418
+	 * @throws InvalidInterfaceException
1419
+	 * @throws ReflectionException
1420
+	 */
1421
+	public function txn_attendees_meta_box($post, $metabox = array('args' => array()))
1422
+	{
1423
+
1424
+		/** @noinspection NonSecureExtractUsageInspection */
1425
+		extract($metabox['args']);
1426
+		$this->_template_args['post'] = $post;
1427
+		$this->_template_args['event_attendees'] = array();
1428
+		// process items in cart
1429
+		$line_items = $this->_transaction->get_many_related(
1430
+			'Line_Item',
1431
+			array(array('LIN_type' => 'line-item'))
1432
+		);
1433
+		if (! empty($line_items)) {
1434
+			foreach ($line_items as $item) {
1435
+				if ($item instanceof EE_Line_Item) {
1436
+					switch ($item->OBJ_type()) {
1437
+						case 'Event':
1438
+							break;
1439
+						case 'Ticket':
1440
+							$ticket = $item->ticket();
1441
+							// right now we're only handling tickets here.
1442
+							// Cause its expected that only tickets will have attendees right?
1443
+							if (! $ticket instanceof EE_Ticket) {
1444
+								break;
1445
+							}
1446
+							try {
1447
+								$event_name = $ticket->get_event_name();
1448
+							} catch (Exception $e) {
1449
+								EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1450
+								$event_name = esc_html__('Unknown Event', 'event_espresso');
1451
+							}
1452
+							$event_name .= ' - ' . $item->name();
1453
+							$ticket_price = EEH_Template::format_currency($item->unit_price());
1454
+							// now get all of the registrations for this transaction that use this ticket
1455
+							$registrations = $ticket->registrations(
1456
+								array(array('TXN_ID' => $this->_transaction->ID()))
1457
+							);
1458
+							foreach ($registrations as $registration) {
1459
+								if (! $registration instanceof EE_Registration) {
1460
+									break;
1461
+								}
1462
+								$this->_template_args['event_attendees'][ $registration->ID() ]['STS_ID']
1463
+									= $registration->status_ID();
1464
+								$this->_template_args['event_attendees'][ $registration->ID() ]['att_num']
1465
+									= $registration->count();
1466
+								$this->_template_args['event_attendees'][ $registration->ID() ]['event_ticket_name']
1467
+									= $event_name;
1468
+								$this->_template_args['event_attendees'][ $registration->ID() ]['ticket_price']
1469
+									= $ticket_price;
1470
+								// attendee info
1471
+								$attendee = $registration->get_first_related('Attendee');
1472
+								if ($attendee instanceof EE_Attendee) {
1473
+									$this->_template_args['event_attendees'][ $registration->ID() ]['att_id']
1474
+										= $attendee->ID();
1475
+									$this->_template_args['event_attendees'][ $registration->ID() ]['attendee']
1476
+										= $attendee->full_name();
1477
+									$this->_template_args['event_attendees'][ $registration->ID() ]['email']
1478
+										= '<a href="mailto:' . $attendee->email() . '?subject=' . $event_name
1479
+										  . esc_html__(
1480
+											  ' Event',
1481
+											  'event_espresso'
1482
+										  )
1483
+										  . '">' . $attendee->email() . '</a>';
1484
+									$this->_template_args['event_attendees'][ $registration->ID() ]['address']
1485
+										= EEH_Address::format($attendee, 'inline', false, false);
1486
+								} else {
1487
+									$this->_template_args['event_attendees'][ $registration->ID() ]['att_id'] = '';
1488
+									$this->_template_args['event_attendees'][ $registration->ID() ]['attendee'] = '';
1489
+									$this->_template_args['event_attendees'][ $registration->ID() ]['email'] = '';
1490
+									$this->_template_args['event_attendees'][ $registration->ID() ]['address'] = '';
1491
+								}
1492
+							}
1493
+							break;
1494
+					}
1495
+				}
1496
+			}
1497
+
1498
+			$this->_template_args['transaction_form_url'] = add_query_arg(
1499
+				array(
1500
+					'action'  => 'edit_transaction',
1501
+					'process' => 'attendees',
1502
+				),
1503
+				TXN_ADMIN_URL
1504
+			);
1505
+			echo EEH_Template::display_template(
1506
+				TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_attendees.template.php',
1507
+				$this->_template_args,
1508
+				true
1509
+			);
1510
+		} else {
1511
+			echo sprintf(
1512
+				esc_html__(
1513
+					'%1$sFor some reason, there are no attendees registered for this transaction. Likely the registration was abandoned in process.%2$s',
1514
+					'event_espresso'
1515
+				),
1516
+				'<p class="important-notice">',
1517
+				'</p>'
1518
+			);
1519
+		}
1520
+	}
1521
+
1522
+
1523
+	/**
1524
+	 * txn_registrant_side_meta_box
1525
+	 * generates HTML for the Edit Transaction side meta box
1526
+	 *
1527
+	 * @access public
1528
+	 * @return void
1529
+	 * @throws DomainException
1530
+	 * @throws EE_Error
1531
+	 * @throws InvalidArgumentException
1532
+	 * @throws InvalidDataTypeException
1533
+	 * @throws InvalidInterfaceException
1534
+	 * @throws ReflectionException
1535
+	 */
1536
+	public function txn_registrant_side_meta_box()
1537
+	{
1538
+		$primary_att = $this->_transaction->primary_registration() instanceof EE_Registration
1539
+			? $this->_transaction->primary_registration()->get_first_related('Attendee')
1540
+			: null;
1541
+		if (! $primary_att instanceof EE_Attendee) {
1542
+			$this->_template_args['no_attendee_message'] = esc_html__(
1543
+				'There is no attached contact for this transaction.  The transaction either failed due to an error or was abandoned.',
1544
+				'event_espresso'
1545
+			);
1546
+			$primary_att = EEM_Attendee::instance()->create_default_object();
1547
+		}
1548
+		$this->_template_args['ATT_ID'] = $primary_att->ID();
1549
+		$this->_template_args['prime_reg_fname'] = $primary_att->fname();
1550
+		$this->_template_args['prime_reg_lname'] = $primary_att->lname();
1551
+		$this->_template_args['prime_reg_email'] = $primary_att->email();
1552
+		$this->_template_args['prime_reg_phone'] = $primary_att->phone();
1553
+		$this->_template_args['edit_attendee_url'] = EE_Admin_Page::add_query_args_and_nonce(
1554
+			array(
1555
+				'action' => 'edit_attendee',
1556
+				'post'   => $primary_att->ID(),
1557
+			),
1558
+			REG_ADMIN_URL
1559
+		);
1560
+		// get formatted address for registrant
1561
+		$this->_template_args['formatted_address'] = EEH_Address::format($primary_att);
1562
+		echo EEH_Template::display_template(
1563
+			TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_registrant.template.php',
1564
+			$this->_template_args,
1565
+			true
1566
+		);
1567
+	}
1568
+
1569
+
1570
+	/**
1571
+	 * txn_billing_info_side_meta_box
1572
+	 *    generates HTML for the Edit Transaction side meta box
1573
+	 *
1574
+	 * @access public
1575
+	 * @return void
1576
+	 * @throws DomainException
1577
+	 * @throws EE_Error
1578
+	 */
1579
+	public function txn_billing_info_side_meta_box()
1580
+	{
1581
+
1582
+		$this->_template_args['billing_form'] = $this->_transaction->billing_info();
1583
+		$this->_template_args['billing_form_url'] = add_query_arg(
1584
+			array('action' => 'edit_transaction', 'process' => 'billing'),
1585
+			TXN_ADMIN_URL
1586
+		);
1587
+
1588
+		$template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_billing_info.template.php';
1589
+		echo EEH_Template::display_template($template_path, $this->_template_args, true);
1590
+	}
1591
+
1592
+
1593
+	/**
1594
+	 * apply_payments_or_refunds
1595
+	 *    registers a payment or refund made towards a transaction
1596
+	 *
1597
+	 * @access public
1598
+	 * @return void
1599
+	 * @throws EE_Error
1600
+	 * @throws InvalidArgumentException
1601
+	 * @throws ReflectionException
1602
+	 * @throws RuntimeException
1603
+	 * @throws InvalidDataTypeException
1604
+	 * @throws InvalidInterfaceException
1605
+	 */
1606
+	public function apply_payments_or_refunds()
1607
+	{
1608
+		$json_response_data = array('return_data' => false);
1609
+		$valid_data = $this->_validate_payment_request_data();
1610
+		$has_access = EE_Registry::instance()->CAP->current_user_can(
1611
+			'ee_edit_payments',
1612
+			'apply_payment_or_refund_from_registration_details'
1613
+		);
1614
+		if (! empty($valid_data) && $has_access) {
1615
+			$PAY_ID = $valid_data['PAY_ID'];
1616
+			// save  the new payment
1617
+			$payment = $this->_create_payment_from_request_data($valid_data);
1618
+			// get the TXN for this payment
1619
+			$transaction = $payment->transaction();
1620
+			// verify transaction
1621
+			if ($transaction instanceof EE_Transaction) {
1622
+				// calculate_total_payments_and_update_status
1623
+				$this->_process_transaction_payments($transaction);
1624
+				$REG_IDs = $this->_get_REG_IDs_to_apply_payment_to($payment);
1625
+				$this->_remove_existing_registration_payments($payment, $PAY_ID);
1626
+				// apply payment to registrations (if applicable)
1627
+				if (! empty($REG_IDs)) {
1628
+					$this->_update_registration_payments($transaction, $payment, $REG_IDs);
1629
+					$this->_maybe_send_notifications();
1630
+					// now process status changes for the same registrations
1631
+					$this->_process_registration_status_change($transaction, $REG_IDs);
1632
+				}
1633
+				$this->_maybe_send_notifications($payment);
1634
+				// prepare to render page
1635
+				$json_response_data['return_data'] = $this->_build_payment_json_response($payment, $REG_IDs);
1636
+				do_action(
1637
+					'AHEE__Transactions_Admin_Page__apply_payments_or_refund__after_recording',
1638
+					$transaction,
1639
+					$payment
1640
+				);
1641
+			} else {
1642
+				EE_Error::add_error(
1643
+					esc_html__(
1644
+						'A valid Transaction for this payment could not be retrieved.',
1645
+						'event_espresso'
1646
+					),
1647
+					__FILE__,
1648
+					__FUNCTION__,
1649
+					__LINE__
1650
+				);
1651
+			}
1652
+		} elseif ($has_access) {
1653
+			EE_Error::add_error(
1654
+				esc_html__(
1655
+					'The payment form data could not be processed. Please try again.',
1656
+					'event_espresso'
1657
+				),
1658
+				__FILE__,
1659
+				__FUNCTION__,
1660
+				__LINE__
1661
+			);
1662
+		} else {
1663
+			EE_Error::add_error(
1664
+				esc_html__(
1665
+					'You do not have access to apply payments or refunds to a registration.',
1666
+					'event_espresso'
1667
+				),
1668
+				__FILE__,
1669
+				__FUNCTION__,
1670
+				__LINE__
1671
+			);
1672
+		}
1673
+		$notices = EE_Error::get_notices(
1674
+			false,
1675
+			false,
1676
+			false
1677
+		);
1678
+		$this->_template_args = array(
1679
+			'data'    => $json_response_data,
1680
+			'error'   => $notices['errors'],
1681
+			'success' => $notices['success'],
1682
+		);
1683
+		$this->_return_json();
1684
+	}
1685
+
1686
+
1687
+	/**
1688
+	 * _validate_payment_request_data
1689
+	 *
1690
+	 * @return array
1691
+	 * @throws EE_Error
1692
+	 * @throws InvalidArgumentException
1693
+	 * @throws InvalidDataTypeException
1694
+	 * @throws InvalidInterfaceException
1695
+	 */
1696
+	protected function _validate_payment_request_data()
1697
+	{
1698
+		if (! isset($this->_req_data['txn_admin_payment'])) {
1699
+			return array();
1700
+		}
1701
+		$payment_form = $this->_generate_payment_form_section();
1702
+		try {
1703
+			if ($payment_form->was_submitted()) {
1704
+				$payment_form->receive_form_submission();
1705
+				if (! $payment_form->is_valid()) {
1706
+					$submission_error_messages = array();
1707
+					foreach ($payment_form->get_validation_errors_accumulated() as $validation_error) {
1708
+						if ($validation_error instanceof EE_Validation_Error) {
1709
+							$submission_error_messages[] = sprintf(
1710
+								_x('%s : %s', 'Form Section Name : Form Validation Error', 'event_espresso'),
1711
+								$validation_error->get_form_section()->html_label_text(),
1712
+								$validation_error->getMessage()
1713
+							);
1714
+						}
1715
+					}
1716
+					EE_Error::add_error(
1717
+						implode('<br />', $submission_error_messages),
1718
+						__FILE__,
1719
+						__FUNCTION__,
1720
+						__LINE__
1721
+					);
1722
+					return array();
1723
+				}
1724
+			}
1725
+		} catch (EE_Error $e) {
1726
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1727
+			return array();
1728
+		}
1729
+
1730
+		return $payment_form->valid_data();
1731
+	}
1732
+
1733
+
1734
+	/**
1735
+	 * _generate_payment_form_section
1736
+	 *
1737
+	 * @return EE_Form_Section_Proper
1738
+	 * @throws EE_Error
1739
+	 */
1740
+	protected function _generate_payment_form_section()
1741
+	{
1742
+		return new EE_Form_Section_Proper(
1743
+			array(
1744
+				'name'        => 'txn_admin_payment',
1745
+				'subsections' => array(
1746
+					'PAY_ID'          => new EE_Text_Input(
1747
+						array(
1748
+							'default'               => 0,
1749
+							'required'              => false,
1750
+							'html_label_text'       => esc_html__('Payment ID', 'event_espresso'),
1751
+							'validation_strategies' => array(new EE_Int_Normalization()),
1752
+						)
1753
+					),
1754
+					'TXN_ID'          => new EE_Text_Input(
1755
+						array(
1756
+							'default'               => 0,
1757
+							'required'              => true,
1758
+							'html_label_text'       => esc_html__('Transaction ID', 'event_espresso'),
1759
+							'validation_strategies' => array(new EE_Int_Normalization()),
1760
+						)
1761
+					),
1762
+					'type'            => new EE_Text_Input(
1763
+						array(
1764
+							'default'               => 1,
1765
+							'required'              => true,
1766
+							'html_label_text'       => esc_html__('Payment or Refund', 'event_espresso'),
1767
+							'validation_strategies' => array(new EE_Int_Normalization()),
1768
+						)
1769
+					),
1770
+					'amount'          => new EE_Text_Input(
1771
+						array(
1772
+							'default'               => 0,
1773
+							'required'              => true,
1774
+							'html_label_text'       => esc_html__('Payment amount', 'event_espresso'),
1775
+							'validation_strategies' => array(new EE_Float_Normalization()),
1776
+						)
1777
+					),
1778
+					'status'          => new EE_Text_Input(
1779
+						array(
1780
+							'default'         => EEM_Payment::status_id_approved,
1781
+							'required'        => true,
1782
+							'html_label_text' => esc_html__('Payment status', 'event_espresso'),
1783
+						)
1784
+					),
1785
+					'PMD_ID'          => new EE_Text_Input(
1786
+						array(
1787
+							'default'               => 2,
1788
+							'required'              => true,
1789
+							'html_label_text'       => esc_html__('Payment Method', 'event_espresso'),
1790
+							'validation_strategies' => array(new EE_Int_Normalization()),
1791
+						)
1792
+					),
1793
+					'date'            => new EE_Text_Input(
1794
+						array(
1795
+							'default'         => time(),
1796
+							'required'        => true,
1797
+							'html_label_text' => esc_html__('Payment date', 'event_espresso'),
1798
+						)
1799
+					),
1800
+					'txn_id_chq_nmbr' => new EE_Text_Input(
1801
+						array(
1802
+							'default'               => '',
1803
+							'required'              => false,
1804
+							'html_label_text'       => esc_html__('Transaction or Cheque Number', 'event_espresso'),
1805
+							'validation_strategies' => array(
1806
+								new EE_Max_Length_Validation_Strategy(
1807
+									esc_html__('Input too long', 'event_espresso'),
1808
+									100
1809
+								),
1810
+							),
1811
+						)
1812
+					),
1813
+					'po_number'       => new EE_Text_Input(
1814
+						array(
1815
+							'default'               => '',
1816
+							'required'              => false,
1817
+							'html_label_text'       => esc_html__('Purchase Order Number', 'event_espresso'),
1818
+							'validation_strategies' => array(
1819
+								new EE_Max_Length_Validation_Strategy(
1820
+									esc_html__('Input too long', 'event_espresso'),
1821
+									100
1822
+								),
1823
+							),
1824
+						)
1825
+					),
1826
+					'accounting'      => new EE_Text_Input(
1827
+						array(
1828
+							'default'               => '',
1829
+							'required'              => false,
1830
+							'html_label_text'       => esc_html__('Extra Field for Accounting', 'event_espresso'),
1831
+							'validation_strategies' => array(
1832
+								new EE_Max_Length_Validation_Strategy(
1833
+									esc_html__('Input too long', 'event_espresso'),
1834
+									100
1835
+								),
1836
+							),
1837
+						)
1838
+					),
1839
+				),
1840
+			)
1841
+		);
1842
+	}
1843
+
1844
+
1845
+	/**
1846
+	 * _create_payment_from_request_data
1847
+	 *
1848
+	 * @param array $valid_data
1849
+	 * @return EE_Payment
1850
+	 * @throws EE_Error
1851
+	 * @throws InvalidArgumentException
1852
+	 * @throws InvalidDataTypeException
1853
+	 * @throws InvalidInterfaceException
1854
+	 * @throws ReflectionException
1855
+	 */
1856
+	protected function _create_payment_from_request_data($valid_data)
1857
+	{
1858
+		$PAY_ID = $valid_data['PAY_ID'];
1859
+		// get payment amount
1860
+		$amount = $valid_data['amount'] ? abs($valid_data['amount']) : 0;
1861
+		// payments have a type value of 1 and refunds have a type value of -1
1862
+		// so multiplying amount by type will give a positive value for payments, and negative values for refunds
1863
+		$amount = $valid_data['type'] < 0 ? $amount * -1 : $amount;
1864
+		// for some reason the date string coming in has extra spaces between the date and time.  This fixes that.
1865
+		$date = $valid_data['date']
1866
+			? preg_replace('/\s+/', ' ', $valid_data['date'])
1867
+			: date('Y-m-d g:i a', current_time('timestamp'));
1868
+		$payment = EE_Payment::new_instance(
1869
+			array(
1870
+				'TXN_ID'              => $valid_data['TXN_ID'],
1871
+				'STS_ID'              => $valid_data['status'],
1872
+				'PAY_timestamp'       => $date,
1873
+				'PAY_source'          => EEM_Payment_Method::scope_admin,
1874
+				'PMD_ID'              => $valid_data['PMD_ID'],
1875
+				'PAY_amount'          => $amount,
1876
+				'PAY_txn_id_chq_nmbr' => $valid_data['txn_id_chq_nmbr'],
1877
+				'PAY_po_number'       => $valid_data['po_number'],
1878
+				'PAY_extra_accntng'   => $valid_data['accounting'],
1879
+				'PAY_details'         => $valid_data,
1880
+				'PAY_ID'              => $PAY_ID,
1881
+			),
1882
+			'',
1883
+			array('Y-m-d', 'g:i a')
1884
+		);
1885
+
1886
+		if (! $payment->save()) {
1887
+			EE_Error::add_error(
1888
+				sprintf(
1889
+					esc_html__('Payment %1$d has not been successfully saved to the database.', 'event_espresso'),
1890
+					$payment->ID()
1891
+				),
1892
+				__FILE__,
1893
+				__FUNCTION__,
1894
+				__LINE__
1895
+			);
1896
+		}
1897
+
1898
+		return $payment;
1899
+	}
1900
+
1901
+
1902
+	/**
1903
+	 * _process_transaction_payments
1904
+	 *
1905
+	 * @param \EE_Transaction $transaction
1906
+	 * @return void
1907
+	 * @throws EE_Error
1908
+	 * @throws InvalidArgumentException
1909
+	 * @throws ReflectionException
1910
+	 * @throws InvalidDataTypeException
1911
+	 * @throws InvalidInterfaceException
1912
+	 */
1913
+	protected function _process_transaction_payments(EE_Transaction $transaction)
1914
+	{
1915
+		/** @type EE_Transaction_Payments $transaction_payments */
1916
+		$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
1917
+		// update the transaction with this payment
1918
+		if ($transaction_payments->calculate_total_payments_and_update_status($transaction)) {
1919
+			EE_Error::add_success(
1920
+				esc_html__(
1921
+					'The payment has been processed successfully.',
1922
+					'event_espresso'
1923
+				),
1924
+				__FILE__,
1925
+				__FUNCTION__,
1926
+				__LINE__
1927
+			);
1928
+		} else {
1929
+			EE_Error::add_error(
1930
+				esc_html__(
1931
+					'The payment was processed successfully but the amount paid for the transaction was not updated.',
1932
+					'event_espresso'
1933
+				),
1934
+				__FILE__,
1935
+				__FUNCTION__,
1936
+				__LINE__
1937
+			);
1938
+		}
1939
+	}
1940
+
1941
+
1942
+	/**
1943
+	 * _get_REG_IDs_to_apply_payment_to
1944
+	 * returns a list of registration IDs that the payment will apply to
1945
+	 *
1946
+	 * @param \EE_Payment $payment
1947
+	 * @return array
1948
+	 * @throws EE_Error
1949
+	 * @throws InvalidArgumentException
1950
+	 * @throws InvalidDataTypeException
1951
+	 * @throws InvalidInterfaceException
1952
+	 * @throws ReflectionException
1953
+	 */
1954
+	protected function _get_REG_IDs_to_apply_payment_to(EE_Payment $payment)
1955
+	{
1956
+		$REG_IDs = array();
1957
+		// grab array of IDs for specific registrations to apply changes to
1958
+		if (isset($this->_req_data['txn_admin_payment']['registrations'])) {
1959
+			$REG_IDs = (array) $this->_req_data['txn_admin_payment']['registrations'];
1960
+		}
1961
+		// nothing specified ? then get all reg IDs
1962
+		if (empty($REG_IDs)) {
1963
+			$registrations = $payment->transaction()->registrations();
1964
+			$REG_IDs = ! empty($registrations)
1965
+				? array_keys($registrations)
1966
+				: $this->_get_existing_reg_payment_REG_IDs($payment);
1967
+		}
1968
+
1969
+		// ensure that REG_IDs are integers and NOT strings
1970
+		return array_map('intval', $REG_IDs);
1971
+	}
1972
+
1973
+
1974
+	/**
1975
+	 * @return array
1976
+	 */
1977
+	public function existing_reg_payment_REG_IDs()
1978
+	{
1979
+		return $this->_existing_reg_payment_REG_IDs;
1980
+	}
1981
+
1982
+
1983
+	/**
1984
+	 * @param array $existing_reg_payment_REG_IDs
1985
+	 */
1986
+	public function set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs = null)
1987
+	{
1988
+		$this->_existing_reg_payment_REG_IDs = $existing_reg_payment_REG_IDs;
1989
+	}
1990
+
1991
+
1992
+	/**
1993
+	 * _get_existing_reg_payment_REG_IDs
1994
+	 * returns a list of registration IDs that the payment is currently related to
1995
+	 * as recorded in the database
1996
+	 *
1997
+	 * @param \EE_Payment $payment
1998
+	 * @return array
1999
+	 * @throws EE_Error
2000
+	 * @throws InvalidArgumentException
2001
+	 * @throws InvalidDataTypeException
2002
+	 * @throws InvalidInterfaceException
2003
+	 * @throws ReflectionException
2004
+	 */
2005
+	protected function _get_existing_reg_payment_REG_IDs(EE_Payment $payment)
2006
+	{
2007
+		if ($this->existing_reg_payment_REG_IDs() === null) {
2008
+			// let's get any existing reg payment records for this payment
2009
+			$existing_reg_payment_REG_IDs = $payment->get_many_related('Registration');
2010
+			// but we only want the REG IDs, so grab the array keys
2011
+			$existing_reg_payment_REG_IDs = ! empty($existing_reg_payment_REG_IDs)
2012
+				? array_keys($existing_reg_payment_REG_IDs)
2013
+				: array();
2014
+			$this->set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs);
2015
+		}
2016
+
2017
+		return $this->existing_reg_payment_REG_IDs();
2018
+	}
2019
+
2020
+
2021
+	/**
2022
+	 * _remove_existing_registration_payments
2023
+	 * this calculates the difference between existing relations
2024
+	 * to the supplied payment and the new list registration IDs,
2025
+	 * removes any related registrations that no longer apply,
2026
+	 * and then updates the registration paid fields
2027
+	 *
2028
+	 * @param \EE_Payment $payment
2029
+	 * @param int         $PAY_ID
2030
+	 * @return bool;
2031
+	 * @throws EE_Error
2032
+	 * @throws InvalidArgumentException
2033
+	 * @throws ReflectionException
2034
+	 * @throws InvalidDataTypeException
2035
+	 * @throws InvalidInterfaceException
2036
+	 */
2037
+	protected function _remove_existing_registration_payments(EE_Payment $payment, $PAY_ID = 0)
2038
+	{
2039
+		// newly created payments will have nothing recorded for $PAY_ID
2040
+		if (absint($PAY_ID) === 0) {
2041
+			return false;
2042
+		}
2043
+		$existing_reg_payment_REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment);
2044
+		if (empty($existing_reg_payment_REG_IDs)) {
2045
+			return false;
2046
+		}
2047
+		/** @type EE_Transaction_Payments $transaction_payments */
2048
+		$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
2049
+
2050
+		return $transaction_payments->delete_registration_payments_and_update_registrations(
2051
+			$payment,
2052
+			array(
2053
+				array(
2054
+					'PAY_ID' => $payment->ID(),
2055
+					'REG_ID' => array('IN', $existing_reg_payment_REG_IDs),
2056
+				),
2057
+			)
2058
+		);
2059
+	}
2060
+
2061
+
2062
+	/**
2063
+	 * _update_registration_payments
2064
+	 * this applies the payments to the selected registrations
2065
+	 * but only if they have not already been paid for
2066
+	 *
2067
+	 * @param  EE_Transaction $transaction
2068
+	 * @param \EE_Payment     $payment
2069
+	 * @param array           $REG_IDs
2070
+	 * @return void
2071
+	 * @throws EE_Error
2072
+	 * @throws InvalidArgumentException
2073
+	 * @throws ReflectionException
2074
+	 * @throws RuntimeException
2075
+	 * @throws InvalidDataTypeException
2076
+	 * @throws InvalidInterfaceException
2077
+	 */
2078
+	protected function _update_registration_payments(
2079
+		EE_Transaction $transaction,
2080
+		EE_Payment $payment,
2081
+		$REG_IDs = array()
2082
+	) {
2083
+		// we can pass our own custom set of registrations to EE_Payment_Processor::process_registration_payments()
2084
+		// so let's do that using our set of REG_IDs from the form
2085
+		$registration_query_where_params = array(
2086
+			'REG_ID' => array('IN', $REG_IDs),
2087
+		);
2088
+		// but add in some conditions regarding payment,
2089
+		// so that we don't apply payments to registrations that are free or have already been paid for
2090
+		// but ONLY if the payment is NOT a refund ( ie: the payment amount is not negative )
2091
+		if (! $payment->is_a_refund()) {
2092
+			$registration_query_where_params['REG_final_price'] = array('!=', 0);
2093
+			$registration_query_where_params['REG_final_price*'] = array('!=', 'REG_paid', true);
2094
+		}
2095
+		$registrations = $transaction->registrations(array($registration_query_where_params));
2096
+		if (! empty($registrations)) {
2097
+			/** @type EE_Payment_Processor $payment_processor */
2098
+			$payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2099
+			$payment_processor->process_registration_payments($transaction, $payment, $registrations);
2100
+		}
2101
+	}
2102
+
2103
+
2104
+	/**
2105
+	 * _process_registration_status_change
2106
+	 * This processes requested registration status changes for all the registrations
2107
+	 * on a given transaction and (optionally) sends out notifications for the changes.
2108
+	 *
2109
+	 * @param  EE_Transaction $transaction
2110
+	 * @param array           $REG_IDs
2111
+	 * @return bool
2112
+	 * @throws EE_Error
2113
+	 * @throws InvalidArgumentException
2114
+	 * @throws ReflectionException
2115
+	 * @throws InvalidDataTypeException
2116
+	 * @throws InvalidInterfaceException
2117
+	 */
2118
+	protected function _process_registration_status_change(EE_Transaction $transaction, $REG_IDs = array())
2119
+	{
2120
+		// first if there is no change in status then we get out.
2121
+		if (! isset($this->_req_data['txn_reg_status_change']['reg_status'])
2122
+			|| $this->_req_data['txn_reg_status_change']['reg_status'] === 'NAN'
2123
+		) {
2124
+			// no error message, no change requested, just nothing to do man.
2125
+			return false;
2126
+		}
2127
+		/** @type EE_Transaction_Processor $transaction_processor */
2128
+		$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
2129
+
2130
+		// made it here dude?  Oh WOW.  K, let's take care of changing the statuses
2131
+		return $transaction_processor->manually_update_registration_statuses(
2132
+			$transaction,
2133
+			sanitize_text_field($this->_req_data['txn_reg_status_change']['reg_status']),
2134
+			array(array('REG_ID' => array('IN', $REG_IDs)))
2135
+		);
2136
+	}
2137
+
2138
+
2139
+	/**
2140
+	 * _build_payment_json_response
2141
+	 *
2142
+	 * @access public
2143
+	 * @param \EE_Payment $payment
2144
+	 * @param array       $REG_IDs
2145
+	 * @param bool | null $delete_txn_reg_status_change
2146
+	 * @return array
2147
+	 * @throws EE_Error
2148
+	 * @throws InvalidArgumentException
2149
+	 * @throws InvalidDataTypeException
2150
+	 * @throws InvalidInterfaceException
2151
+	 * @throws ReflectionException
2152
+	 */
2153
+	protected function _build_payment_json_response(
2154
+		EE_Payment $payment,
2155
+		$REG_IDs = array(),
2156
+		$delete_txn_reg_status_change = null
2157
+	) {
2158
+		// was the payment deleted ?
2159
+		if (is_bool($delete_txn_reg_status_change)) {
2160
+			return array(
2161
+				'PAY_ID'                       => $payment->ID(),
2162
+				'amount'                       => $payment->amount(),
2163
+				'total_paid'                   => $payment->transaction()->paid(),
2164
+				'txn_status'                   => $payment->transaction()->status_ID(),
2165
+				'pay_status'                   => $payment->STS_ID(),
2166
+				'registrations'                => $this->_registration_payment_data_array($REG_IDs),
2167
+				'delete_txn_reg_status_change' => $delete_txn_reg_status_change,
2168
+			);
2169
+		} else {
2170
+			$this->_get_payment_status_array();
2171
+
2172
+			return array(
2173
+				'amount'           => $payment->amount(),
2174
+				'total_paid'       => $payment->transaction()->paid(),
2175
+				'txn_status'       => $payment->transaction()->status_ID(),
2176
+				'pay_status'       => $payment->STS_ID(),
2177
+				'PAY_ID'           => $payment->ID(),
2178
+				'STS_ID'           => $payment->STS_ID(),
2179
+				'status'           => self::$_pay_status[ $payment->STS_ID() ],
2180
+				'date'             => $payment->timestamp('Y-m-d', 'h:i a'),
2181
+				'method'           => strtoupper($payment->source()),
2182
+				'PM_ID'            => $payment->payment_method() ? $payment->payment_method()->ID() : 1,
2183
+				'gateway'          => $payment->payment_method()
2184
+					? $payment->payment_method()->admin_name()
2185
+					: esc_html__('Unknown', 'event_espresso'),
2186
+				'gateway_response' => $payment->gateway_response(),
2187
+				'txn_id_chq_nmbr'  => $payment->txn_id_chq_nmbr(),
2188
+				'po_number'        => $payment->po_number(),
2189
+				'extra_accntng'    => $payment->extra_accntng(),
2190
+				'registrations'    => $this->_registration_payment_data_array($REG_IDs),
2191
+			);
2192
+		}
2193
+	}
2194
+
2195
+
2196
+	/**
2197
+	 * delete_payment
2198
+	 *    delete a payment or refund made towards a transaction
2199
+	 *
2200
+	 * @access public
2201
+	 * @return void
2202
+	 * @throws EE_Error
2203
+	 * @throws InvalidArgumentException
2204
+	 * @throws ReflectionException
2205
+	 * @throws InvalidDataTypeException
2206
+	 * @throws InvalidInterfaceException
2207
+	 */
2208
+	public function delete_payment()
2209
+	{
2210
+		$json_response_data = array('return_data' => false);
2211
+		$PAY_ID = isset($this->_req_data['delete_txn_admin_payment']['PAY_ID'])
2212
+			? absint($this->_req_data['delete_txn_admin_payment']['PAY_ID'])
2213
+			: 0;
2214
+		$can_delete = EE_Registry::instance()->CAP->current_user_can(
2215
+			'ee_delete_payments',
2216
+			'delete_payment_from_registration_details'
2217
+		);
2218
+		if ($PAY_ID && $can_delete) {
2219
+			$delete_txn_reg_status_change = isset($this->_req_data['delete_txn_reg_status_change'])
2220
+				? $this->_req_data['delete_txn_reg_status_change']
2221
+				: false;
2222
+			$payment = EEM_Payment::instance()->get_one_by_ID($PAY_ID);
2223
+			if ($payment instanceof EE_Payment) {
2224
+				$REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment);
2225
+				/** @type EE_Transaction_Payments $transaction_payments */
2226
+				$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
2227
+				if ($transaction_payments->delete_payment_and_update_transaction($payment)) {
2228
+					$json_response_data['return_data'] = $this->_build_payment_json_response(
2229
+						$payment,
2230
+						$REG_IDs,
2231
+						$delete_txn_reg_status_change
2232
+					);
2233
+					if ($delete_txn_reg_status_change) {
2234
+						$this->_req_data['txn_reg_status_change'] = $delete_txn_reg_status_change;
2235
+						// MAKE sure we also add the delete_txn_req_status_change to the
2236
+						// $_REQUEST global because that's how messages will be looking for it.
2237
+						$_REQUEST['txn_reg_status_change'] = $delete_txn_reg_status_change;
2238
+						$this->_maybe_send_notifications();
2239
+						$this->_process_registration_status_change($payment->transaction(), $REG_IDs);
2240
+					}
2241
+				}
2242
+			} else {
2243
+				EE_Error::add_error(
2244
+					esc_html__('Valid Payment data could not be retrieved from the database.', 'event_espresso'),
2245
+					__FILE__,
2246
+					__FUNCTION__,
2247
+					__LINE__
2248
+				);
2249
+			}
2250
+		} elseif ($can_delete) {
2251
+			EE_Error::add_error(
2252
+				esc_html__(
2253
+					'A valid Payment ID was not received, therefore payment form data could not be loaded.',
2254
+					'event_espresso'
2255
+				),
2256
+				__FILE__,
2257
+				__FUNCTION__,
2258
+				__LINE__
2259
+			);
2260
+		} else {
2261
+			EE_Error::add_error(
2262
+				esc_html__(
2263
+					'You do not have access to delete a payment.',
2264
+					'event_espresso'
2265
+				),
2266
+				__FILE__,
2267
+				__FUNCTION__,
2268
+				__LINE__
2269
+			);
2270
+		}
2271
+		$notices = EE_Error::get_notices(false, false, false);
2272
+		$this->_template_args = array(
2273
+			'data'      => $json_response_data,
2274
+			'success'   => $notices['success'],
2275
+			'error'     => $notices['errors'],
2276
+			'attention' => $notices['attention'],
2277
+		);
2278
+		$this->_return_json();
2279
+	}
2280
+
2281
+
2282
+	/**
2283
+	 * _registration_payment_data_array
2284
+	 * adds info for 'owing' and 'paid' for each registration to the json response
2285
+	 *
2286
+	 * @access protected
2287
+	 * @param array $REG_IDs
2288
+	 * @return array
2289
+	 * @throws EE_Error
2290
+	 * @throws InvalidArgumentException
2291
+	 * @throws InvalidDataTypeException
2292
+	 * @throws InvalidInterfaceException
2293
+	 * @throws ReflectionException
2294
+	 */
2295
+	protected function _registration_payment_data_array($REG_IDs)
2296
+	{
2297
+		$registration_payment_data = array();
2298
+		// if non empty reg_ids lets get an array of registrations and update the values for the apply_payment/refund rows.
2299
+		if (! empty($REG_IDs)) {
2300
+			$registrations = EEM_Registration::instance()->get_all(array(array('REG_ID' => array('IN', $REG_IDs))));
2301
+			foreach ($registrations as $registration) {
2302
+				if ($registration instanceof EE_Registration) {
2303
+					$registration_payment_data[ $registration->ID() ] = array(
2304
+						'paid'  => $registration->pretty_paid(),
2305
+						'owing' => EEH_Template::format_currency($registration->final_price() - $registration->paid()),
2306
+					);
2307
+				}
2308
+			}
2309
+		}
2310
+
2311
+		return $registration_payment_data;
2312
+	}
2313
+
2314
+
2315
+	/**
2316
+	 * _maybe_send_notifications
2317
+	 * determines whether or not the admin has indicated that notifications should be sent.
2318
+	 * If so, will toggle a filter switch for delivering registration notices.
2319
+	 * If passed an EE_Payment object, then it will trigger payment notifications instead.
2320
+	 *
2321
+	 * @access protected
2322
+	 * @param \EE_Payment | null $payment
2323
+	 */
2324
+	protected function _maybe_send_notifications($payment = null)
2325
+	{
2326
+		switch ($payment instanceof EE_Payment) {
2327
+			// payment notifications
2328
+			case true:
2329
+				if (isset($this->_req_data['txn_payments']['send_notifications'])
2330
+					&& filter_var(
2331
+						$this->_req_data['txn_payments']['send_notifications'],
2332
+						FILTER_VALIDATE_BOOLEAN
2333
+					)
2334
+				) {
2335
+					$this->_process_payment_notification($payment);
2336
+				}
2337
+				break;
2338
+			// registration notifications
2339
+			case false:
2340
+				if (isset($this->_req_data['txn_reg_status_change']['send_notifications'])
2341
+					&& filter_var(
2342
+						$this->_req_data['txn_reg_status_change']['send_notifications'],
2343
+						FILTER_VALIDATE_BOOLEAN
2344
+					)
2345
+				) {
2346
+					add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
2347
+				}
2348
+				break;
2349
+		}
2350
+	}
2351
+
2352
+
2353
+	/**
2354
+	 * _send_payment_reminder
2355
+	 *    generates HTML for the View Transaction Details Admin page
2356
+	 *
2357
+	 * @access protected
2358
+	 * @return void
2359
+	 * @throws EE_Error
2360
+	 * @throws InvalidArgumentException
2361
+	 * @throws InvalidDataTypeException
2362
+	 * @throws InvalidInterfaceException
2363
+	 */
2364
+	protected function _send_payment_reminder()
2365
+	{
2366
+		$TXN_ID = ! empty($this->_req_data['TXN_ID']) ? absint($this->_req_data['TXN_ID']) : false;
2367
+		$transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
2368
+		$query_args = isset($this->_req_data['redirect_to']) ? array(
2369
+			'action' => $this->_req_data['redirect_to'],
2370
+			'TXN_ID' => $this->_req_data['TXN_ID'],
2371
+		) : array();
2372
+		do_action(
2373
+			'AHEE__Transactions_Admin_Page___send_payment_reminder__process_admin_payment_reminder',
2374
+			$transaction
2375
+		);
2376
+		$this->_redirect_after_action(
2377
+			false,
2378
+			esc_html__('payment reminder', 'event_espresso'),
2379
+			esc_html__('sent', 'event_espresso'),
2380
+			$query_args,
2381
+			true
2382
+		);
2383
+	}
2384
+
2385
+
2386
+	/**
2387
+	 *  get_transactions
2388
+	 *    get transactions for given parameters (used by list table)
2389
+	 *
2390
+	 * @param  int     $perpage how many transactions displayed per page
2391
+	 * @param  boolean $count   return the count or objects
2392
+	 * @param string   $view
2393
+	 * @return mixed int = count || array of transaction objects
2394
+	 * @throws EE_Error
2395
+	 * @throws InvalidArgumentException
2396
+	 * @throws InvalidDataTypeException
2397
+	 * @throws InvalidInterfaceException
2398
+	 */
2399
+	public function get_transactions($perpage, $count = false, $view = '')
2400
+	{
2401
+
2402
+		$TXN = EEM_Transaction::instance();
2403
+
2404
+		$start_date = isset($this->_req_data['txn-filter-start-date'])
2405
+			? wp_strip_all_tags($this->_req_data['txn-filter-start-date'])
2406
+			: date(
2407
+				'm/d/Y',
2408
+				strtotime('-10 year')
2409
+			);
2410
+		$end_date = isset($this->_req_data['txn-filter-end-date'])
2411
+			? wp_strip_all_tags($this->_req_data['txn-filter-end-date'])
2412
+			: date('m/d/Y');
2413
+
2414
+		// make sure our timestamps start and end right at the boundaries for each day
2415
+		$start_date = date('Y-m-d', strtotime($start_date)) . ' 00:00:00';
2416
+		$end_date = date('Y-m-d', strtotime($end_date)) . ' 23:59:59';
2417
+
2418
+
2419
+		// convert to timestamps
2420
+		$start_date = strtotime($start_date);
2421
+		$end_date = strtotime($end_date);
2422
+
2423
+		// makes sure start date is the lowest value and vice versa
2424
+		$start_date = min($start_date, $end_date);
2425
+		$end_date = max($start_date, $end_date);
2426
+
2427
+		// convert to correct format for query
2428
+		$start_date = EEM_Transaction::instance()->convert_datetime_for_query(
2429
+			'TXN_timestamp',
2430
+			date('Y-m-d H:i:s', $start_date),
2431
+			'Y-m-d H:i:s'
2432
+		);
2433
+		$end_date = EEM_Transaction::instance()->convert_datetime_for_query(
2434
+			'TXN_timestamp',
2435
+			date('Y-m-d H:i:s', $end_date),
2436
+			'Y-m-d H:i:s'
2437
+		);
2438
+
2439
+
2440
+		// set orderby
2441
+		$this->_req_data['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : '';
2442
+
2443
+		switch ($this->_req_data['orderby']) {
2444
+			case 'TXN_ID':
2445
+				$orderby = 'TXN_ID';
2446
+				break;
2447
+			case 'ATT_fname':
2448
+				$orderby = 'Registration.Attendee.ATT_fname';
2449
+				break;
2450
+			case 'event_name':
2451
+				$orderby = 'Registration.Event.EVT_name';
2452
+				break;
2453
+			default: // 'TXN_timestamp'
2454
+				$orderby = 'TXN_timestamp';
2455
+		}
2456
+
2457
+		$sort = ! empty($this->_req_data['order']) ? $this->_req_data['order'] : 'DESC';
2458
+		$current_page = ! empty($this->_req_data['paged']) ? $this->_req_data['paged'] : 1;
2459
+		$per_page = ! empty($perpage) ? $perpage : 10;
2460
+		$per_page = ! empty($this->_req_data['perpage']) ? $this->_req_data['perpage'] : $per_page;
2461
+
2462
+		$offset = ($current_page - 1) * $per_page;
2463
+		$limit = array($offset, $per_page);
2464
+
2465
+		$_where = array(
2466
+			'TXN_timestamp'          => array('BETWEEN', array($start_date, $end_date)),
2467
+			'Registration.REG_count' => 1,
2468
+		);
2469
+
2470
+		if (isset($this->_req_data['EVT_ID'])) {
2471
+			$_where['Registration.EVT_ID'] = $this->_req_data['EVT_ID'];
2472
+		}
2473
+
2474
+		if (isset($this->_req_data['s'])) {
2475
+			$search_string = '%' . $this->_req_data['s'] . '%';
2476
+			$_where['OR'] = array(
2477
+				'Registration.Event.EVT_name'         => array('LIKE', $search_string),
2478
+				'Registration.Event.EVT_desc'         => array('LIKE', $search_string),
2479
+				'Registration.Event.EVT_short_desc'   => array('LIKE', $search_string),
2480
+				'Registration.Attendee.ATT_full_name' => array('LIKE', $search_string),
2481
+				'Registration.Attendee.ATT_fname'     => array('LIKE', $search_string),
2482
+				'Registration.Attendee.ATT_lname'     => array('LIKE', $search_string),
2483
+				'Registration.Attendee.ATT_short_bio' => array('LIKE', $search_string),
2484
+				'Registration.Attendee.ATT_email'     => array('LIKE', $search_string),
2485
+				'Registration.Attendee.ATT_address'   => array('LIKE', $search_string),
2486
+				'Registration.Attendee.ATT_address2'  => array('LIKE', $search_string),
2487
+				'Registration.Attendee.ATT_city'      => array('LIKE', $search_string),
2488
+				'Registration.REG_final_price'        => array('LIKE', $search_string),
2489
+				'Registration.REG_code'               => array('LIKE', $search_string),
2490
+				'Registration.REG_count'              => array('LIKE', $search_string),
2491
+				'Registration.REG_group_size'         => array('LIKE', $search_string),
2492
+				'Registration.Ticket.TKT_name'        => array('LIKE', $search_string),
2493
+				'Registration.Ticket.TKT_description' => array('LIKE', $search_string),
2494
+				'Payment.PAY_source'                  => array('LIKE', $search_string),
2495
+				'Payment.Payment_Method.PMD_name'     => array('LIKE', $search_string),
2496
+				'TXN_session_data'                    => array('LIKE', $search_string),
2497
+				'Payment.PAY_txn_id_chq_nmbr'         => array('LIKE', $search_string),
2498
+			);
2499
+		}
2500
+
2501
+		// failed transactions
2502
+		$failed = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'failed' && ! $count)
2503
+				  || ($count && $view === 'failed');
2504
+		$abandoned = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'abandoned' && ! $count)
2505
+					 || ($count && $view === 'abandoned');
2506
+		$incomplete = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'incomplete' && ! $count)
2507
+					  || ($count && $view === 'incomplete');
2508
+
2509
+		if ($failed) {
2510
+			$_where['STS_ID'] = EEM_Transaction::failed_status_code;
2511
+		} elseif ($abandoned) {
2512
+			$_where['STS_ID'] = EEM_Transaction::abandoned_status_code;
2513
+		} elseif ($incomplete) {
2514
+			$_where['STS_ID'] = EEM_Transaction::incomplete_status_code;
2515
+		} else {
2516
+			$_where['STS_ID'] = array('!=', EEM_Transaction::failed_status_code);
2517
+			$_where['STS_ID*'] = array('!=', EEM_Transaction::abandoned_status_code);
2518
+		}
2519
+
2520
+		$query_params = apply_filters(
2521
+			'FHEE__Transactions_Admin_Page___get_transactions_query_params',
2522
+			array(
2523
+				$_where,
2524
+				'order_by'                 => array($orderby => $sort),
2525
+				'limit'                    => $limit,
2526
+				'default_where_conditions' => EEM_Base::default_where_conditions_this_only,
2527
+			),
2528
+			$this->_req_data,
2529
+			$view,
2530
+			$count
2531
+		);
2532
+
2533
+		$transactions = $count
2534
+			? $TXN->count(array($query_params[0]), 'TXN_ID', true)
2535
+			: $TXN->get_all($query_params);
2536
+
2537
+		return $transactions;
2538
+	}
2539
+
2540
+
2541
+	/**
2542
+	 * @since $VID:$
2543
+	 * @throws EE_Error
2544
+	 * @throws InvalidArgumentException
2545
+	 * @throws InvalidDataTypeException
2546
+	 * @throws InvalidInterfaceException
2547
+	 * @throws ReflectionException
2548
+	 * @throws RuntimeException
2549
+	 */
2550
+	public function recalculateLineItems()
2551
+	{
2552
+		$TXN_ID = ! empty($this->_req_data['TXN_ID']) ? absint($this->_req_data['TXN_ID']) : false;
2553
+		/** @var EE_Transaction $transaction */
2554
+		$transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
2555
+		$total_line_item = $transaction->total_line_item(false);
2556
+		$success = false;
2557
+		if ($total_line_item instanceof EE_Line_Item) {
2558
+			EEH_Line_Item::resetIsTaxableForTickets($total_line_item);
2559
+			$success = EEH_Line_Item::apply_taxes($total_line_item, true);
2560
+		}
2561
+		$this->_redirect_after_action(
2562
+			(bool) $success,
2563
+			esc_html__('Transaction taxes and totals', 'event_espresso'),
2564
+			esc_html__('recalculated', 'event_espresso'),
2565
+			isset($this->_req_data['redirect_to'])
2566
+				? array(
2567
+				'action' => $this->_req_data['redirect_to'],
2568
+				'TXN_ID' => $this->_req_data['TXN_ID'],
2569
+			)
2570
+				: array(),
2571
+			true
2572
+		);
2573
+	}
2574 2574
 }
Please login to merge, or discard this patch.