-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathclass-wc-subscriptions-order.php
2464 lines (2077 loc) · 101 KB
/
class-wc-subscriptions-order.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Subscriptions Order Class
*
* Mirrors and overloads a few functions in the WC_Order class to work for subscriptions.
*
* @package WooCommerce Subscriptions
* @subpackage WC_Subscriptions_Order
* @category Class
*/
class WC_Subscriptions_Order {
/**
* A flag to indicate whether subscription price strings should include the subscription length
*/
public static $recurring_only_price_strings = false;
/**
* Bootstraps the class and hooks required actions & filters.
*
* @since 1.0.0 - Migrated from WooCommerce Subscriptions v1.0
*/
public static function init() {
add_action( 'woocommerce_thankyou', __CLASS__ . '::subscription_thank_you' );
add_action( 'manage_shop_order_posts_custom_column', __CLASS__ . '::add_contains_subscription_hidden_field', 10, 1 );
add_action( 'woocommerce_admin_order_data_after_order_details', __CLASS__ . '::contains_subscription_hidden_field', 10, 1 );
// Add column that indicates whether an order is parent or renewal for a subscription
add_filter( 'manage_edit-shop_order_columns', __CLASS__ . '::add_contains_subscription_column' );
add_action( 'manage_shop_order_posts_custom_column', __CLASS__ . '::add_contains_subscription_column_content', 10, 1 );
// HPOS - Add column that indicates whether an order is parent or renewal for a subscription.
add_filter( 'woocommerce_shop_order_list_table_columns', __CLASS__ . '::add_contains_subscription_column' );
add_action( 'woocommerce_shop_order_list_table_custom_column', __CLASS__ . '::add_contains_subscription_column_content_orders_table', 10, 2 );
// Record initial payment against the subscription & set start date based on that payment
add_action( 'woocommerce_order_status_changed', __CLASS__ . '::maybe_record_subscription_payment', 9, 3 );
// Sometimes, even if the order total is $0, the order still needs payment
add_filter( 'woocommerce_order_needs_payment', __CLASS__ . '::order_needs_payment', 10, 3 );
// Add subscription information to the order complete emails.
add_action( 'woocommerce_email_after_order_table', __CLASS__ . '::add_sub_info_email', 15, 3 );
// Add dropdown to admin orders screen to filter on order type
add_action( 'restrict_manage_posts', __CLASS__ . '::restrict_manage_subscriptions', 50 );
// For HPOS - Add dropdown to admin orders screen to filter on order type.
add_action( 'woocommerce_order_list_table_restrict_manage_orders', __CLASS__ . '::restrict_manage_subscriptions_hpos' );
// Add filter to queries on admin orders screen to filter on order type. To avoid WC overriding our query args, we need to hook on after them on 10.
add_filter( 'request', __CLASS__ . '::orders_by_type_query', 11 );
// HPOS - Add filter to queries on admin orders screen to filter on order type. Only triggered for the shop_order order type.
add_filter( 'woocommerce_shop_order_list_table_prepare_items_query_args', __CLASS__ . '::maybe_modify_orders_by_type_query_from_request', 11 );
// Don't display migrated order item meta on the Edit Order screen
add_filter( 'woocommerce_hidden_order_itemmeta', __CLASS__ . '::hide_order_itemmeta' );
add_action( 'woocommerce_order_details_after_order_table', __CLASS__ . '::add_subscriptions_to_view_order_templates', 10, 1 );
add_action( 'woocommerce_subscription_details_after_subscription_table', __CLASS__ . '::get_related_orders_template', 10, 1 );
add_filter( 'woocommerce_my_account_my_orders_actions', __CLASS__ . '::maybe_remove_pay_action', 10, 2 );
add_action( 'woocommerce_order_fully_refunded', __CLASS__ . '::maybe_cancel_subscription_on_full_refund' );
add_filter( 'woocommerce_order_needs_shipping_address', __CLASS__ . '::maybe_display_shipping_address', 10, 3 );
// Autocomplete subscription orders when they only contain a synchronised subscription or a resubscribe
add_filter( 'woocommerce_payment_complete_order_status', __CLASS__ . '::maybe_autocomplete_order', 10, 3 );
add_filter( 'woocommerce_order_data_store_cpt_get_orders_query', array( __CLASS__, 'add_subscription_order_query_args' ), 10, 2 );
add_filter( 'woocommerce_order_query_args', array( __CLASS__, 'map_order_query_args_for_subscriptions' ) );
add_filter( 'woocommerce_orders_table_query_clauses', [ __CLASS__, 'filter_orders_query_by_parent_orders' ], 10, 2 );
}
/*
* Helper functions for extracting the details of subscriptions in an order
*/
/**
* Returns the total amount to be charged for non-subscription products at the outset of a subscription.
*
* This may return 0 if there no non-subscription products in the cart, or otherwise it will be the sum of the
* line totals for each non-subscription product.
*
* @param mixed $order A WC_Order object or the ID of the order which the subscription was purchased in.
* @since 1.0.0 - Migrated from WooCommerce Subscriptions v1.5.3
*/
public static function get_non_subscription_total( $order ) {
if ( ! is_object( $order ) ) {
$order = wc_get_order( $order );
}
$non_subscription_total = 0;
foreach ( $order->get_items() as $order_item ) {
if ( ! self::is_item_subscription( $order, $order_item ) ) {
$non_subscription_total += $order_item['line_total'];
}
}
return apply_filters( 'woocommerce_subscriptions_order_non_subscription_total', $non_subscription_total, $order );
}
/**
* Returns the total sign-up fee for all subscriptions in an order.
*
* Similar to WC_Subscription::get_sign_up_fee() except that it sums the sign-up fees for all subscriptions purchased in an order.
*
* @param mixed $order A WC_Order object or the ID of the order which the subscription was purchased in.
* @param int $product_id (optional) The post ID of the subscription WC_Product object purchased in the order. Defaults to the ID of the first product purchased in the order.
* @return float The initial sign-up fee charged when the subscription product in the order was first purchased, if any.
* @since 1.0.0 - Migrated from WooCommerce Subscriptions v1.0
*/
public static function get_sign_up_fee( $order, $product_id = '' ) {
$sign_up_fee = 0;
foreach ( wcs_get_subscriptions_for_order( $order, array( 'order_type' => 'parent' ) ) as $subscription ) {
if ( empty( $product_id ) ) {
$sign_up_fee += $subscription->get_sign_up_fee();
} else {
// We only want sign-up fees for certain product
$order_item = self::get_item_by_product_id( $order, $product_id );
foreach ( $subscription->get_items() as $line_item ) {
if ( $line_item['product_id'] == $product_id || $line_item['variation_id'] == $product_id ) {
$sign_up_fee += $subscription->get_items_sign_up_fee( $line_item );
}
}
}
}
return apply_filters( 'woocommerce_subscriptions_sign_up_fee', $sign_up_fee, $order, $product_id );
}
/**
* Gets the product ID for an order item in a way that is backwards compatible with WC 1.x.
*
* Version 2.0 of WooCommerce changed the ID of an order item from its product ID to a unique ID for that particular item.
* This function checks if the 'product_id' field exists on an order item before falling back to 'id'.
*
* @param array $order_item An order item in the structure returned by WC_Order::get_items()
* @since 1.0.0 - Migrated from WooCommerce Subscriptions v1.2.5
*/
public static function get_items_product_id( $order_item ) {
return ( isset( $order_item['product_id'] ) ) ? $order_item['product_id'] : $order_item['id'];
}
/**
* Gets an item by product id from an order.
*
* @param WC_Order|int $order The WC_Order object or ID of the order for which the meta should be sought.
* @param int $product_id The product/post ID of a subscription product.
* @since 1.0.0 - Migrated from WooCommerce Subscriptions v1.2.5
*/
public static function get_item_by_product_id( $order, $product_id = '' ) {
if ( ! is_object( $order ) ) {
$order = wc_get_order( $order );
}
foreach ( $order->get_items() as $item ) {
if ( ( self::get_items_product_id( $item ) == $product_id || empty( $product_id ) ) && self::is_item_subscription( $order, $item ) ) {
return $item;
}
}
return array();
}
/**
* Gets an item by a subscription key of the form created by @see WC_Subscriptions_Manager::get_subscription_key().
*
* @param WC_Order|int $order The WC_Order object or ID of the order for which the meta should be sought.
* @param int $product_id The product/post ID of a subscription product.
* @since 1.0.0 - Migrated from WooCommerce Subscriptions v1.2.5
*/
public static function get_item_by_subscription_key( $subscription_key ) {
$item_id = self::get_item_id_by_subscription_key( $subscription_key );
$item = self::get_item_by_id( $item_id );
return $item;
}
/**
* Gets the ID of a subscription item which belongs to a subscription key of the form created
* by @see WC_Subscriptions_Manager::get_subscription_key().
*
* @param WC_Order|int $order The WC_Order object or ID of the order for which the meta should be sought.
* @param int $product_id The product/post ID of a subscription product.
* @since 1.0.0 - Migrated from WooCommerce Subscriptions v1.4
*/
public static function get_item_id_by_subscription_key( $subscription_key ) {
global $wpdb;
$order_and_product_ids = explode( '_', $subscription_key );
$item_id = $wpdb->get_var( $wpdb->prepare(
"SELECT `{$wpdb->prefix}woocommerce_order_items`.order_item_id FROM `{$wpdb->prefix}woocommerce_order_items`
INNER JOIN `{$wpdb->prefix}woocommerce_order_itemmeta` on `{$wpdb->prefix}woocommerce_order_items`.order_item_id = `{$wpdb->prefix}woocommerce_order_itemmeta`.order_item_id
AND `{$wpdb->prefix}woocommerce_order_itemmeta`.meta_key = '_product_id'
AND `{$wpdb->prefix}woocommerce_order_itemmeta`.meta_value = %d
WHERE `{$wpdb->prefix}woocommerce_order_items`.order_id = %d",
$order_and_product_ids[1],
$order_and_product_ids[0]
) );
return $item_id;
}
/**
* Gets an individual order item by ID without requiring the order ID associated with it.
*
* @param WC_Order|int $order The WC_Order object or ID of the order for which the meta should be sought.
* @param int $item_id The product/post ID of a subscription. Option - if no product id is provided, the first item's meta will be returned
* @return array $item An array containing the order_item_id, order_item_name, order_item_type, order_id and any item_meta. Array structure matches that returned by WC_Order::get_items()
* @since 1.0.0 - Migrated from WooCommerce Subscriptions v1.2.5
*/
public static function get_item_by_id( $order_item_id ) {
global $wpdb;
$item = $wpdb->get_row( $wpdb->prepare( "
SELECT order_item_id, order_item_name, order_item_type, order_id
FROM {$wpdb->prefix}woocommerce_order_items
WHERE order_item_id = %d
", $order_item_id ), ARRAY_A );
$order = wc_get_order( absint( $item['order_id'] ) );
$item['name'] = $item['order_item_name'];
$item['type'] = $item['order_item_type'];
$item['item_meta'] = wc_get_order_item_meta( $item['order_item_id'], '' );
// Put meta into item array
if ( is_array( $item['item_meta'] ) ) {
foreach ( $item['item_meta'] as $meta_name => $meta_value ) {
$key = substr( $meta_name, 0, 1 ) == '_' ? substr( $meta_name, 1 ) : $meta_name;
$item[ $key ] = maybe_unserialize( $meta_value[0] );
}
}
return $item;
}
/**
* A unified API for accessing product specific meta on an order.
*
* @param WC_Order|int $order The WC_Order object or ID of the order for which the meta should be sought.
* @param string $meta_key The key as stored in the post meta table for the meta item.
* @param int $product_id The product/post ID of a subscription. Option - if no product id is provided, we will loop through the order and find the subscription
* @param mixed $default (optional) The default value to return if the meta key does not exist. Default 0.
* @since 1.0.0 - Migrated from WooCommerce Subscriptions v1.2
*/
public static function get_item_meta( $order, $meta_key, $product_id = '', $default = 0 ) {
$meta_value = $default;
if ( '' == $product_id ) {
$items = self::get_recurring_items( $order );
foreach ( $items as $item ) {
$product_id = $item['product_id'];
break;
}
}
$item = self::get_item_by_product_id( $order, $product_id );
if ( ! empty( $item ) && isset( $item['item_meta'][ $meta_key ] ) ) {
$meta_value = $item['item_meta'][ $meta_key ][0];
}
return apply_filters( 'woocommerce_subscriptions_item_meta', $meta_value, $meta_key, $order, $product_id );
}
/**
* Access an individual piece of item metadata (@see woocommerce_get_order_item_meta returns all metadata for an item)
*
* You may think it would make sense if this function was called "get_item_meta", and you would be correct, but a function
* with that name was created before the item meta data API of WC 2.0, so it needs to persist with it's own different
* set of parameters.
*
* @param int $meta_id The order item meta data ID of the item you want to get.
* @since 1.0.0 - Migrated from WooCommerce Subscriptions v1.2.5
*/
public static function get_item_meta_data( $meta_id ) {
global $wpdb;
$item_meta = $wpdb->get_row( $wpdb->prepare( "
SELECT *
FROM {$wpdb->prefix}woocommerce_order_itemmeta
WHERE meta_id = %d
", $meta_id ) );
return $item_meta;
}
/**
* Gets the name of a subscription item by product ID from an order.
*
* @param WC_Order|int $order The WC_Order object or ID of the order for which the meta should be sought.
* @param int $product_id The product/post ID of a subscription. Option - if no product id is provided, it is expected that only one item exists and the last item's meta will be returned
* @since 1.0.0 - Migrated from WooCommerce Subscriptions v1.2
*/
public static function get_item_name( $order, $product_id = '' ) {
$item = self::get_item_by_product_id( $order, $product_id );
if ( isset( $item['name'] ) ) {
return $item['name'];
} else {
return '';
}
}
/**
* Displays a few details about what happens to their subscription. Hooked
* to the thank you page.
*
* @param int $order_id
*
* @since 1.0.0 - Migrated from WooCommerce Subscriptions v1.0
*/
public static function subscription_thank_you( $order_id ) {
if ( wcs_order_contains_subscription( $order_id, 'any' ) ) {
$subscriptions = wcs_get_subscriptions_for_order( $order_id, array( 'order_type' => 'any' ) );
$subscription_count = count( $subscriptions );
$thank_you_message = '';
$my_account_subscriptions_url = wc_get_endpoint_url( 'subscriptions', '', wc_get_page_permalink( 'myaccount' ) );
if ( $subscription_count ) {
foreach ( $subscriptions as $subscription ) {
if ( ! $subscription->has_status( 'active' ) ) {
$thank_you_message = '<p>' . _n( 'Your subscription will be activated when payment clears.', 'Your subscriptions will be activated when payment clears.', $subscription_count, 'woocommerce-subscriptions' ) . '</p>';
break;
}
}
}
// translators: placeholders are opening and closing link tags
$thank_you_message .= '<p>' . sprintf( _n( 'View the status of your subscription in %1$syour account%2$s.', 'View the status of your subscriptions in %1$syour account%2$s.', $subscription_count, 'woocommerce-subscriptions' ), '<a href="' . $my_account_subscriptions_url . '">', '</a>' ) . '</p>';
echo wp_kses(
apply_filters(
'woocommerce_subscriptions_thank_you_message',
$thank_you_message,
$order_id
),
array(
'a' => array(
'href' => array(),
'title' => array(),
),
'p' => array(),
'em' => array(),
'strong' => array(),
)
);
}
}
/**
* Output a hidden element in the order status of the orders list table to provide information about whether
* the order displayed in that row contains a subscription or not.
*
* It would be more semantically correct to display a hidden input element than a span element with data, but
* that can result in "requested URL's length exceeds the capacity limit" errors when bulk editing orders.
*
* @param string $column The string of the current column.
* @since 1.0.0 - Migrated from WooCommerce Subscriptions v1.1
*/
public static function add_contains_subscription_hidden_field( $column ) {
global $post;
if ( 'order_status' == $column ) {
$contains_subscription = wcs_order_contains_subscription( $post->ID, 'parent' ) ? 'true' : 'false';
printf( '<span class="contains_subscription" data-contains_subscription="%s" style="display: none;"></span>', esc_attr( $contains_subscription ) );
}
}
/**
* Output a hidden element on the Edit Order screen to provide information about whether the order displayed
* in that row contains a subscription or not.
*
* @param string $column The string of the current column.
* @since 1.0.0 - Migrated from WooCommerce Subscriptions v1.1
*/
public static function contains_subscription_hidden_field( $order_id ) {
$has_subscription = wcs_order_contains_subscription( $order_id, 'parent' ) ? 'true' : 'false';
echo '<input type="hidden" name="contains_subscription" value="' . esc_attr( $has_subscription ) . '">';
}
/**
* Add a column to the WooCommerce -> Orders admin screen to indicate whether an order is a
* parent of a subscription, a renewal order for a subscription, or a regular order.
*
* @param array $columns The current list of columns
* @since 1.0.0 - Migrated from WooCommerce Subscriptions v2.1
*/
public static function add_contains_subscription_column( $columns ) {
$column_header = '<span class="subscription_head tips" data-tip="' . esc_attr__( 'Subscription Relationship', 'woocommerce-subscriptions' ) . '">' . esc_attr__( 'Subscription Relationship', 'woocommerce-subscriptions' ) . '</span>';
$new_columns = wcs_array_insert_after( 'shipping_address', $columns, 'subscription_relationship', $column_header );
return $new_columns;
}
/**
* Add column content to the WooCommerce -> Orders admin screen to indicate whether an
* order is a parent of a subscription, a renewal order for a subscription, or a regular order.
*
* @see add_contains_subscription_column_content_orders_table For when HPOS is enabled.
*
* @param string $column The string of the current column
* @since 1.0.0 - Migrated from WooCommerce Subscriptions v2.1
*/
public static function add_contains_subscription_column_content( $column ) {
global $post;
if ( 'subscription_relationship' === $column ) {
self::render_contains_subscription_column_content( $post->ID );
}
}
/**
* Add column content to the WooCommerce -> Orders admin screen to indicate whether an
* order is a parent of a subscription, a renewal order for a subscription, or a regular order.
*
* @see add_contains_subscription_column_content For when HPOS is disabled.
*
* @since 6.3.0
*
* @param string $column_name Identifier for the custom column.
* @param WC_Order $order Current WooCommerce order object.
*/
public static function add_contains_subscription_column_content_orders_table( string $column_name, WC_Order $order ) {
if ( 'subscription_relationship' === $column_name ) {
self::render_contains_subscription_column_content( $order );
}
}
/**
* Records the initial payment against a subscription.
*
* This function is called when an order's status is changed to completed or processing
* for those gateways which never call @see WC_Order::payment_complete(), like the core
* WooCommerce Cheque and Bank Transfer gateways.
*
* It will also set the start date on the subscription to the time the payment is completed.
*
* @since 1.0.0 - Migrated from WooCommerce Subscriptions v2.0
*
* @param int|WC_Order $order_id The order ID or WC_Order object.
* @param string $old_order_status The old order status.
* @param string $new_order_status The new order status.
*/
public static function maybe_record_subscription_payment( $order_id, $old_order_status, $new_order_status ) {
if ( ! wcs_order_contains_subscription( $order_id, 'parent' ) ) {
return;
}
$subscriptions = wcs_get_subscriptions_for_order( $order_id, array( 'order_type' => 'parent' ) );
$was_activated = false;
$order = wc_get_order( $order_id );
$paid_statuses = array( apply_filters( 'woocommerce_payment_complete_order_status', 'processing', $order_id, $order ), 'processing', 'completed' );
$unpaid_statuses = apply_filters( 'woocommerce_valid_order_statuses_for_payment', array( 'pending', 'on-hold', 'failed' ), $order );
$order_completed = in_array( $new_order_status, $paid_statuses, true ) && in_array( $old_order_status, $unpaid_statuses, true );
/**
* Filter whether the subscription order is considered completed.
*
* Allow third party extensions to modify whether the order is considered
* completed and the subscription should activate. This allows for different
* treatment of orders and subscriptions during the completion flow.
*
* @since 6.9.0
*
* @param bool $order_completed Whether the order is considered completed.
* @param string $new_order_status The new order status.
* @param string $old_order_status The old order status.
* @param WC_Subscription[] $subscriptions The subscriptions in the order.
* @param WC_Order $order The order object.
*/
$order_completed = apply_filters( 'wcs_is_subscription_order_completed', $order_completed, $new_order_status, $old_order_status, $subscriptions, $order );
foreach ( $subscriptions as $subscription ) {
// A special case where payment completes after user cancels subscription
if ( $order_completed && $subscription->has_status( 'cancelled' ) ) {
// Store the actual cancelled_date so as to restore it after it is rewritten by update_status()
$cancelled_date = $subscription->get_date( 'cancelled' );
// Force set cancelled_date and end date to 0 temporarily so that next_payment_date can be calculated properly
// This next_payment_date will be the end of prepaid term that will be picked by action scheduler
$subscription->update_dates( array( 'cancelled' => 0, 'end' => 0 ) );
$next_payment_date = $subscription->calculate_date( 'next_payment' );
$subscription->update_dates( array( 'next_payment' => $next_payment_date ) );
$subscription->update_status( 'pending-cancel', __( 'Payment completed on order after subscription was cancelled.', 'woocommerce-subscriptions' ) );
// Restore the actual cancelled date
$subscription->update_dates( array( 'cancelled' => $cancelled_date ) );
}
// Do we need to activate a subscription?
if ( $order_completed && ! $subscription->has_status( wcs_get_subscription_ended_statuses() ) && ! $subscription->has_status( 'active' ) ) {
$new_start_date_offset = current_time( 'timestamp', true ) - $subscription->get_time( 'start' );
// if the payment has been processed more than an hour after the order was first created, let's update the dates on the subscription to account for that, because it may have even been processed days after it was first placed
if ( abs( $new_start_date_offset ) > HOUR_IN_SECONDS ) {
$dates = array( 'start' => current_time( 'mysql', true ) );
if ( WC_Subscriptions_Synchroniser::subscription_contains_synced_product( $subscription ) ) {
$trial_end = $subscription->get_time( 'trial_end' );
$next_payment = $subscription->get_time( 'next_payment' );
// if either there is a free trial date or a next payment date that falls before now, we need to recalculate all the sync'd dates
if ( ( $trial_end > 0 && $trial_end < wcs_date_to_time( $dates['start'] ) ) || ( $next_payment > 0 && $next_payment < wcs_date_to_time( $dates['start'] ) ) ) {
foreach ( $subscription->get_items() as $item ) {
$product_id = wcs_get_canonical_product_id( $item );
if ( WC_Subscriptions_Synchroniser::is_product_synced( $product_id ) ) {
$dates['trial_end'] = WC_Subscriptions_Product::get_trial_expiration_date( $product_id, $dates['start'] );
$dates['next_payment'] = WC_Subscriptions_Synchroniser::calculate_first_payment_date( $product_id, 'mysql', $dates['start'] );
$dates['end'] = WC_Subscriptions_Product::get_expiration_date( $product_id, $dates['start'] );
break;
}
}
}
} else {
// No sync'ing to mess about with, just add the offset to the existing dates
foreach ( array( 'trial_end', 'next_payment', 'end' ) as $date_type ) {
if ( 0 != $subscription->get_time( $date_type ) ) {
$dates[ $date_type ] = gmdate( 'Y-m-d H:i:s', $subscription->get_time( $date_type ) + $new_start_date_offset );
}
}
}
$subscription->update_dates( $dates );
}
$subscription->payment_complete_for_order( $order );
$was_activated = true;
} elseif ( 'failed' == $new_order_status ) {
$subscription->payment_failed();
}
}
if ( $was_activated ) {
do_action( 'subscriptions_activated_for_order', $order_id );
}
}
/* Order Price Getters */
/**
* Checks if a given order item matches a line item from a subscription purchased in the order.
*
* @param WC_Order|int $order A WC_Order object or ID of a WC_Order order.
* @param array $item | int An array representing an order item or a product ID of an item in an order (not an order item ID)
* @since 1.0.0 - Migrated from WooCommerce Subscriptions v1.2
*/
public static function is_item_subscription( $order, $order_item ) {
if ( ! is_array( $order_item ) ) {
$order_item = self::get_item_by_product_id( $order, $order_item );
}
$order_items_product_id = wcs_get_canonical_product_id( $order_item );
$item_is_subscription = false;
foreach ( wcs_get_subscriptions_for_order( $order, array( 'order_type' => 'parent' ) ) as $subscription ) {
foreach ( $subscription->get_items() as $line_item ) {
if ( wcs_get_canonical_product_id( $line_item ) == $order_items_product_id ) {
$item_is_subscription = true;
break 2;
}
}
}
return $item_is_subscription;
}
/* Edit Order Page Content */
/**
* Returns all parent subscription orders for a user, specified with $user_id
*
* @return array An array of order IDs.
* @since 1.0.0 - Migrated from WooCommerce Subscriptions v1.4
*/
public static function get_users_subscription_orders( $user_id = 0 ) {
global $wpdb;
if ( 0 === $user_id ) {
$user_id = get_current_user_id();
}
// Get all the customers orders which are not subscription renewal orders
$custom_query_var_handler = function( $query, $query_vars ) {
if ( ! empty( $query_vars['_non_subscription_renewal'] ) ) {
$query['meta_query'][] = array(
'key' => '_subscription_renewal',
'compare' => 'NOT EXISTS',
);
unset( $query_vars['_non_subscription_renewal'] );
}
return $query;
};
add_filter( 'woocommerce_order_data_store_cpt_get_orders_query', $custom_query_var_handler, 10, 2 );
$all_possible_statuses = array_values( array_unique( array_keys( wc_get_order_statuses() ) ) );
$args = array(
'type' => 'shop_order',
'status' => $all_possible_statuses,
'orderby' => 'date',
'order' => 'DESC',
'customer_id' => $user_id,
'return' => 'ids',
);
$args['_non_subscription_renewal'] = true;
$order_ids = wc_get_orders( $args );
remove_filter( 'woocommerce_order_data_store_cpt_get_orders_query', $custom_query_var_handler, 10 );
foreach ( $order_ids as $index => $order_id ) {
if ( ! wcs_order_contains_subscription( $order_id, 'parent' ) ) {
unset( $order_ids[ $index ] );
}
}
// Normalise array keys
$order_ids = array_values( $order_ids );
return apply_filters( 'users_subscription_orders', $order_ids, $user_id );
}
/**
* Check whether an order needs payment even if the order total is $0 (because it has a recurring total and
* automatic payments are not switched off)
*
* @param bool $needs_payment The existing flag for whether the cart needs payment or not.
* @param WC_Order $order A WooCommerce WC_Order object.
* @return bool
*/
public static function order_needs_payment( $needs_payment, $order, $valid_order_statuses ) {
// Skips checks if the order already needs payment.
if ( $needs_payment ) {
return $needs_payment;
}
// Skip checks if order doesn't contain a subscription product.
if ( ! wcs_order_contains_subscription( $order ) ) {
return $needs_payment;
}
// Skip checks if order total is greater than zero, or
// order status isn't valid for payment.
if ( $order->get_total() > 0 || ! $order->has_status( $valid_order_statuses ) ) {
return $needs_payment;
}
// Skip checks if manual renewal is required.
if ( wcs_is_manual_renewal_required() ) {
return $needs_payment;
}
// Check if there's a subscription attached to this order that will require a payment method.
foreach ( wcs_get_subscriptions_for_order( $order, [ 'order_type' => 'parent' ] ) as $subscription ) {
$has_next_payment = false;
$contains_expiring_limited_coupon = false;
$contains_free_trial = false;
$contains_synced = false;
// Check if there's a subscription with a recurring total that would require a payment method.
$recurring_total = (float) $subscription->get_total();
// Check that there is at least 1 subscription with a next payment that would require a payment method.
if ( $subscription->get_time( 'next_payment' ) ) {
$has_next_payment = true;
}
// Check if there's a subscription with a limited recurring coupon that is expiring that would require a payment method after the coupon expires.
if ( class_exists( 'WCS_Limited_Recurring_Coupon_Manager' ) && WCS_Limited_Recurring_Coupon_Manager::order_has_limited_recurring_coupon( $subscription ) ) {
$contains_expiring_limited_coupon = true;
}
// Check if there's a subscription with a free trial that would require a payment method after the trial ends.
if ( $subscription->get_time( 'trial_end' ) ) {
$contains_free_trial = true;
}
// Check if there's a subscription with a synced product that would require a payment method.
if ( WC_Subscriptions_Synchroniser::subscription_contains_synced_product( $subscription ) ) {
$contains_synced = true;
}
/**
* We need to collect a payment method if there's a subscription with a recurring total or a limited recurring coupon that is expiring and
* there's a next payment date or a free trial or a synced product.
*/
if ( ( $contains_expiring_limited_coupon || $recurring_total > 0 ) && ( $has_next_payment || $contains_free_trial || $contains_synced ) ) {
$needs_payment = true;
break; // We've found a subscription that requires a payment method.
}
}
return $needs_payment;
}
/**
* Adds the subscription information to our order emails.
*
* @since 1.0.0 - Migrated from WooCommerce Subscriptions v1.5
*/
public static function add_sub_info_email( $order, $is_admin_email, $plaintext = false, $skip_my_account_link = false ) {
$subscriptions = wcs_get_subscriptions_for_order( $order, array( 'order_type' => 'any' ) );
if ( ! empty( $subscriptions ) ) {
$template_base = WC_Subscriptions_Core_Plugin::instance()->get_subscriptions_core_directory( 'templates/' );
$template = ( $plaintext ) ? 'emails/plain/subscription-info.php' : 'emails/subscription-info.php';
wc_get_template(
$template,
array(
'order' => $order,
'subscriptions' => $subscriptions,
'is_admin_email' => $is_admin_email,
'plain_text' => $plaintext,
'skip_my_account_link' => $skip_my_account_link,
),
'',
$template_base
);
}
}
/**
* Add admin dropdown for order types to Woocommerce -> Orders screen
*
* @since 1.0.0 - Migrated from WooCommerce Subscriptions v1.5
*/
public static function restrict_manage_subscriptions() {
global $typenow;
if ( 'shop_order' !== $typenow ) {
return;
}
self::render_restrict_manage_subscriptions_dropdown();
}
/**
* When HPOS is active, adds admin dropdown for order types to Woocommerce -> Orders screen
*
* @since 6.3.0
*
* @param string $order_type The order type.
*/
public static function restrict_manage_subscriptions_hpos( string $order_type ) {
if ( 'shop_order' !== $order_type ) {
return;
}
self::render_restrict_manage_subscriptions_dropdown();
}
/**
* Add request filter for order types to Woocommerce -> Orders screen
*
* Including or excluding posts with a '_subscription_renewal' meta value includes or excludes
* renewal orders, as required.
*
* @since 1.0.0 - Migrated from WooCommerce Subscriptions v1.5
*/
public static function orders_by_type_query( $vars ) {
global $typenow;
if ( 'shop_order' === $typenow ) {
return self::maybe_modify_orders_by_type_query_from_request( $vars );
}
return $vars;
}
/**
* Filters the arguments to be passed to `wc_get_orders()` under the Woocommerce -> Orders screen.
*
* @since 6.3.0
*
* @param array $order_query_args Arguments to be passed to `wc_get_orders()`.
*
* @return array
*/
public static function maybe_modify_orders_by_type_query_from_request( array $order_query_args ): array {
// The order subtype selected by the user in the dropdown.
$selected_shop_order_subtype = isset( $_GET['shop_order_subtype'] ) ? wc_clean( wp_unslash( $_GET['shop_order_subtype'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
// Don't modify the query args if no order subtype was selected.
if ( empty( $selected_shop_order_subtype ) ) {
return $order_query_args;
}
if ( 'original' === $selected_shop_order_subtype || 'regular' === $selected_shop_order_subtype ) {
$order_query_args['meta_query']['relation'] = 'AND';
$order_query_args['meta_query'][] = array(
'key' => '_subscription_renewal',
'compare' => 'NOT EXISTS',
);
$order_query_args['meta_query'][] = array(
'key' => '_subscription_switch',
'compare' => 'NOT EXISTS',
);
} elseif ( 'parent' === $selected_shop_order_subtype ) {
if ( wcs_is_custom_order_tables_usage_enabled() ) {
$order_query_args['subscription_parent'] = true;
} else {
$order_query_args['post__in'] = wcs_get_subscription_orders();
}
} else {
switch ( $selected_shop_order_subtype ) {
case 'renewal':
$meta_key = '_subscription_renewal';
break;
case 'resubscribe':
$meta_key = '_subscription_resubscribe';
break;
case 'switch':
$meta_key = '_subscription_switch';
break;
default:
$meta_key = '';
break;
}
$meta_key = apply_filters( 'woocommerce_subscriptions_admin_order_type_filter_meta_key', $meta_key, $selected_shop_order_subtype );
if ( ! empty( $meta_key ) ) {
$order_query_args['meta_query'][] = array(
'key' => $meta_key,
'compare' => 'EXISTS',
);
}
}
// Also exclude parent orders from non-subscription query
if ( 'regular' === $selected_shop_order_subtype ) {
if ( wcs_is_custom_order_tables_usage_enabled() ) {
$order_query_args['subscription_parent'] = false;
} else {
$order_query_args['post__not_in'] = wcs_get_subscription_orders();
}
}
return $order_query_args;
}
/**
* Add related subscriptions below order details tables.
*
* @since 1.0.0 - Migrated from WooCommerce Subscriptions v2.0
*/
public static function add_subscriptions_to_view_order_templates( $order_id ) {
$template = 'myaccount/related-subscriptions.php';
$subscriptions = wcs_get_subscriptions_for_order( $order_id, array( 'order_type' => 'any' ) );
if ( ! empty( $subscriptions ) ) {
wc_get_template(
$template,
array(
'order_id' => $order_id,
'subscriptions' => $subscriptions,
),
'',
WC_Subscriptions_Core_Plugin::instance()->get_subscriptions_core_directory( 'templates/' )
);
}
}
/**
* Loads the related orders table on the view subscription page
*
* @since 1.0.0 - Migrated from WooCommerce Subscriptions v2.0
*/
public static function get_related_orders_template( $subscription ) {
$subscription_orders = $subscription->get_related_orders();
if ( 0 !== count( $subscription_orders ) ) {
wc_get_template(
'myaccount/related-orders.php',
array(
'subscription_orders' => $subscription_orders,
'subscription' => $subscription,
),
'',
WC_Subscriptions_Core_Plugin::instance()->get_subscriptions_core_directory( 'templates/' )
);
}
}
/**
* Unset pay action for an order if a more recent order exists
*
* @since 1.0.0 - Migrated from WooCommerce Subscriptions v2.2.9
*/
public static function maybe_remove_pay_action( $actions, $order ) {
if ( isset( $actions['pay'] ) && wcs_order_contains_subscription( $order, array( 'any' ) ) ) {
$subscriptions = wcs_get_subscriptions_for_order( wcs_get_objects_property( $order, 'id' ), array( 'order_type' => 'any' ) );
foreach ( $subscriptions as $subscription ) {
if ( wcs_get_objects_property( $order, 'id' ) != $subscription->get_last_order( 'ids', 'any' ) ) {
unset( $actions['pay'] );
break;
}
}
}
return $actions;
}
/**
* Allow subscription order items to be edited in WC 2.2. until Subscriptions 2.0 introduces
* its own WC_Subscription object.
*
* @since 1.0.0 - Migrated from WooCommerce Subscriptions v1.5.10
*/
public static function is_order_editable( $is_editable, $order ) {
_deprecated_function( __METHOD__, '2.0', 'WC_Subscription::is_editable()' );
return $is_editable;
}
/**
* Get a subscription that has an item with the same product/variation ID as an order item, if any.
*
* In Subscriptions v1.n, a subscription's meta data, like recurring total, billing period etc. were stored
* against the line item on the original order for that subscription.
*
* In v2.0, this data was moved to a distinct subscription object which had its own line items for those amounts.
* This function bridges the two data structures to support deprecated functions used to retrieve a subscription's
* meta data from the original order rather than the subscription itself.
*
* @param WC_Order $order A WC_Order object
* @param int $product_id The product/post ID of a subscription
* @return null|object A subscription from the order, either with an item to the product ID (if any) or just the first subscription purchase in the order.
* @since 1.0.0 - Migrated from WooCommerce Subscriptions v2.0
*/
private static function get_matching_subscription( $order, $product_id = '' ) {
$subscriptions = wcs_get_subscriptions_for_order( $order, array( 'order_type' => 'parent' ) );
$matching_subscription = null;
if ( ! empty( $product_id ) ) {
foreach ( $subscriptions as $subscription ) {
foreach ( $subscription->get_items() as $line_item ) {
if ( wcs_get_canonical_product_id( $line_item ) == $product_id ) {
$matching_subscription = $subscription;
break 2;
}
}
}
}