-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclass-migrator-cli-coupons.php
533 lines (472 loc) · 16.6 KB
/
class-migrator-cli-coupons.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
<?php
// phpcs:disable WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
class Migrator_CLI_Coupons {
/**
* Imports the coupons/discounts from Shopify into Woo.
* Not all types of discounts are supported yet.
*/
public function import( $assoc_args ) {
$imported = 0;
$limit = isset( $assoc_args['limit'] ) ? $assoc_args['limit'] : PHP_INT_MAX;
$cursor = isset( $assoc_args['cursor'] ) ? $assoc_args['cursor'] : '';
do {
$response_data = $this->get_next_discount( $cursor );
$discount = reset( $response_data->data->codeDiscountNodes->edges );
$cursor = $discount->cursor;
$discount = $discount->node->codeDiscount;
if ( ! empty( (array) $discount ) ) {
$this->create_or_update_coupon( $discount );
} else {
WP_CLI::line( WP_CLI::colorize( '%BInfo:%n ' ) . 'Discount was empty. Probably unsupported type: ' );
}
WP_CLI::line( WP_CLI::colorize( '%BInfo:%n ' ) . 'Cursor: ' . $cursor );
// Prevents api throttling.
sleep( 1 );
++$imported;
if ( $imported % 100 === 0 ) {
Migrator_CLI_Utils::reset_in_memory_cache();
}
} while ( $response_data->data->codeDiscountNodes->pageInfo->hasNextPage && $imported < $limit );
WP_CLI::line( WP_CLI::colorize( '%GDone%n' ) );
}
private function get_next_discount( $cursor ) {
if ( $cursor ) {
$cursor = 'after: "' . $cursor . '"';
}
$response = Migrator_CLI_Utils::graphql_request(
array(
'query' => '{
codeDiscountNodes(
first: 1
reverse: true
' . $cursor . '
) {
edges {
cursor
node {
id
codeDiscount {
... on DiscountCodeFreeShipping {
usageLimit
appliesOnOneTimePurchase
appliesOnSubscription
appliesOncePerCustomer
asyncUsageCount
codeCount
codes(first: 200) {
nodes {
asyncUsageCount
code
id
}
}
combinesWith {
orderDiscounts
productDiscounts
shippingDiscounts
}
updatedAt
createdAt
customerSelection {
... on DiscountCustomers {
customers {
email
}
}
... on DiscountCustomerSegments {
segments {
id
name
}
}
... on DiscountCustomerAll {
allCustomers
}
}
destinationSelection {
... on DiscountCountryAll {
allCountries
}
... on DiscountCountries {
countries
includeRestOfWorld
}
}
discountClass
endsAt
startsAt
maximumShippingPrice {
amount
}
minimumRequirement {
... on DiscountMinimumSubtotal {
greaterThanOrEqualToSubtotal {
amount
}
}
... on DiscountMinimumQuantity {
greaterThanOrEqualToQuantity
}
}
recurringCycleLimit
summary
title
}
... on DiscountCodeBasic {
appliesOncePerCustomer
asyncUsageCount
createdAt
discountClass
endsAt
hasTimelineComment
minimumRequirement {
... on DiscountMinimumSubtotal {
greaterThanOrEqualToSubtotal {
amount
currencyCode
}
}
... on DiscountMinimumQuantity {
greaterThanOrEqualToQuantity
}
}
recurringCycleLimit
shortSummary
startsAt
status
summary
title
updatedAt
usageLimit
codes(first: 200) {
nodes {
asyncUsageCount
code
id
}
}
combinesWith {
orderDiscounts
productDiscounts
shippingDiscounts
}
customerGets {
appliesOnOneTimePurchase
appliesOnSubscription
value {
... on DiscountPercentage {
percentage
}
... on DiscountOnQuantity {
effect {
... on DiscountPercentage {
percentage
}
}
quantity {
quantity
}
}
... on DiscountAmount {
appliesOnEachItem
amount {
amount
currencyCode
}
}
}
items {
... on DiscountProducts {
products(first: 100) {
nodes {
id
legacyResourceId
}
}
}
... on AllDiscountItems {
allItems
}
... on DiscountCollections {
collections(first: 100) {
nodes {
handle
}
}
}
}
}
customerSelection {
... on DiscountCustomerAll {
allCustomers
}
... on DiscountCustomers {
customers {
email
id
}
}
... on DiscountCustomerSegments {
segments {
id
name
}
}
}
}
}
}
}
pageInfo {
endCursor
hasNextPage
hasPreviousPage
startCursor
}
}
}',
)
);
$response_data = json_decode( wp_remote_retrieve_body( $response ) );
if ( isset( $response_data->errors ) ) {
WP_CLI::error( 'API Error: ' . $response_data->errors[0]->message );
}
if ( empty( $response_data->data->codeDiscountNodes ) ) {
WP_CLI::error( 'No coupons found.' );
}
return $response_data;
}
/**
* Creates or updates a coupon.
*
* @param object $discount the shopify discount data.
* @param object $child_code the child coupon code.
*/
private function create_or_update_coupon( $discount, $child_code = null ) {
WP_CLI::line( '=========================================================================' );
if ( $child_code ) {
$coupon_code = $child_code->code;
$usage = $child_code->asyncUsageCount;
} else {
$coupon_code = $discount->title;
$usage = $discount->asyncUsageCount;
if ( isset( $discount->codes->nodes[0] ) ) {
$coupon_code = $discount->codes->nodes[0]->code;
unset( $discount->codes->nodes[0] );
}
}
WP_CLI::line( WP_CLI::colorize( '%BInfo:%n ' ) . 'Processing coupon: ' . $coupon_code );
$coupon = new WC_Coupon( $coupon_code );
if ( 0 === $coupon->get_id() ) {
WP_CLI::line( "Coupon didn't exist yet creating a new one" );
} else {
WP_CLI::line( 'Coupon already exists updating' );
}
$this->cleanup( $coupon );
$coupon->set_code( $coupon_code );
$coupon->set_description( $discount->summary );
$coupon->set_date_created( $discount->createdAt );
$coupon->set_date_expires( $discount->endsAt );
$coupon->set_date_modified( $discount->updatedAt );
$coupon->set_usage_limit( $discount->usageLimit );
$coupon->set_usage_count( $usage );
$coupon->set_usage_limit_per_user( true === $discount->appliesOncePerCustomer ? 1 : null );
$this->check_unsupported_rules( $discount );
$this->set_restrictions( $coupon, $discount );
$this->set_limits( $coupon, $discount );
$this->set_discount_type( $coupon, $discount );
if ( 'SHIPPING' === $discount->discountClass ) {
$coupon->set_free_shipping( 1 );
}
$coupon->save();
if ( ! $child_code ) {
if ( count( $discount->codes->nodes ) >= 199 ) {
WP_CLI::line( WP_CLI::colorize( '%YWarning:%n ' ) . 'Only the first 200 codes will be processed for this coupon.' );
}
foreach ( $discount->codes->nodes as $code ) {
$this->create_or_update_coupon( $discount, $code );
}
}
}
/**
* Cleans up a coupon before it can be updated
* to prevent the wrong data from being saved.
*
* @param WC_Coupon $coupon the Woo coupon.
*/
private function cleanup( $coupon ) {
$coupon->set_minimum_amount( null );
$coupon->set_email_restrictions( null );
$coupon->set_free_shipping( null );
$coupon->set_discount_type( 'fixed_cart' );
$coupon->set_individual_use( true );
$coupon->update_meta_data( '_apply_to_first_cycle_only', 'no' );
$coupon->update_meta_data( '_allow_subscriptions', 'no' );
}
/**
* Checks rules that Woo does not support.
*
* @param object $discount the shopify discount data.
*/
private function check_unsupported_rules( $discount ) {
if ( new DateTime( $discount->startsAt ) > ( new DateTime( 'now' ) ) ) {
WP_CLI::line( WP_CLI::colorize( '%RError:%n ' ) . 'Woo does not support coupons with a start date in the future.' );
}
if ( isset( $discount->minimumRequirement->greaterThanOrEqualToQuantity ) && ! defined( 'WEBTOFFEE_SMARTCOUPON_VERSION' ) ) {
WP_CLI::line( WP_CLI::colorize( '%YWarning:%n ' ) . 'Minimum product quantity not supported by Woo. Install the free WebTofee`s Smart Coupon For WooCommerce Coupon plugin' );
}
if ( isset( $discount->customerSelection->segments ) ) {
WP_CLI::line( WP_CLI::colorize( '%YWarning:%n ' ) . 'Coupon customer segmentation not supported by Woo.' );
}
if ( true === $discount->combinesWith->orderDiscounts || true === $discount->combinesWith->productDiscounts || true === $discount->combinesWith->shippingDiscounts ) {
WP_CLI::line( WP_CLI::colorize( '%YWarning:%n ' ) . 'The importer does not handle combining discounts at the moment.' );
}
if ( 'SHIPPING' === $discount->discountClass ) {
if ( ! isset( $discount->destinationSelection->allCountries ) || true !== $discount->destinationSelection->allCountries ) {
WP_CLI::line( WP_CLI::colorize( '%YWarning:%n ' ) . 'Woo does not support free shipping coupons for specific countries only. This coupon will apply to all countries.' );
}
if ( null !== $discount->maximumShippingPrice ) {
WP_CLI::line( WP_CLI::colorize( '%YWarning:%n ' ) . 'Woo does not support limiting free shipping for a maximum shipping value.' );
}
}
}
/**
* Sets the coupon restrictions like minimum total,
* Products that the coupon applies.
*
* @param WC_Coupon $coupon the Woo coupon.
* @param object $discount the Shopify discount data.
*/
private function set_restrictions( $coupon, $discount ) {
// Minimum total
if ( isset( $discount->minimumRequirement->greaterThanOrEqualToSubtotal ) ) {
$coupon->set_minimum_amount( $discount->minimumRequirement->greaterThanOrEqualToSubtotal->amount );
}
// Products
if ( isset( $discount->customerGets->items ) && true !== isset( $discount->customerGets->items->allItems ) ) {
$meta_values = array();
if ( isset( $discount->customerGets->items->productVariants ) && count( $discount->customerGets->items->productVariants ) ) {
WP_CLI::line( WP_CLI::colorize( '%RError:%n ' ) . 'Product variants not supported yet' );
}
if ( isset( $discount->customerGets->items->collections ) ) {
WP_CLI::line( WP_CLI::colorize( '%RError:%n ' ) . 'Product collections not supported yet' );
}
if ( isset( $discount->customerGets->items->products ) ) {
foreach ( $discount->customerGets->items->products->nodes as $shopify_product ) {
$meta_values[] = $shopify_product->legacyResourceId;
}
add_filter( 'woocommerce_product_data_store_cpt_get_products_query', array( $this, 'handle_custom_query_var' ), 10, 2 );
$products = wc_get_products(
array(
'limit' => -1,
'_original_product_id' => $meta_values,
)
);
$product_ids = array();
foreach ( $products as $product ) {
$product_ids[] = $product->get_id();
}
$coupon->set_product_ids( $product_ids );
}
}
// Rules Supported by WebTofee`s Smart Coupons for WooCommerce.
if ( defined( 'WEBTOFFEE_SMARTCOUPON_VERSION' ) ) {
// Minimum product quantity.
if ( isset( $discount->minimumRequirement->greaterThanOrEqualToQuantity ) ) {
$coupon->update_meta_data( '_wt_min_matching_product_qty', $discount->minimumRequirement->greaterThanOrEqualToQuantity );
}
}
}
/**
* Adds a customer query var to search for products with one of the shopify products ids.
*
* @param array $query the query.
* @param array $query_vars the query vars.
* @return array
*/
public function handle_custom_query_var( $query, $query_vars ) {
if ( ! empty( $query_vars['_original_product_id'] ) ) {
$query['meta_query'][] = array(
'key' => '_original_product_id',
'value' => $query_vars['_original_product_id'],
'compare' => 'IN',
);
}
return $query;
}
/**
* Sets coupons limits like user emails and maximum number of cycles.
*
* @param WC_Coupon $coupon the Woo coupon.
* @param object $discount the shopify discount data.
*/
private function set_limits( $coupon, $discount ) {
// Limited to specific user emails
if ( isset( $discount->customerSelection->customers ) ) {
$emails = array();
foreach ( $discount->customerSelection->customers as $customer ) {
$emails[] = $customer->email;
}
$coupon->set_email_restrictions( $emails );
}
// Cycle limits, key from https://github.com/woocommerce/woocommerce-subscriptions/blob/b7e2a57ab730ab8a146b7a12e55efefa7f6fee1d/includes/class-wcs-limited-recurring-coupon-manager.php#L18
$coupon->update_meta_data( '_wcs_number_payments', $discount->recurringCycleLimit );
}
/**
* Sets the discount type. Shopify discount types are not a perfect match
* so they need to be loosely converted.
* When a discount is set to be used in both subscriptions and one time purchases
* converts them to subscriptions only.
*
* @param WC_Coupon $coupon the Woo coupon.
* @param object $discount the Shopify discount data.
*/
private function set_discount_type( WC_Coupon $coupon, $discount ) {
$is_subscription_and_one_time = false;
// Coupons used in both subscriptions and one time purchases.
if ( isset( $discount->customerGets ) && true === $discount->customerGets->appliesOnSubscription && true === $discount->customerGets->appliesOnOneTimePurchase ) {
if ( class_exists( 'Mixed_Coupons' ) ) {
$is_subscription_and_one_time = true;
$coupon->update_meta_data( '_allow_subscriptions', 'yes' );
if ( $discount->recurringCycleLimit > 1 ) {
WP_CLI::line( WP_CLI::colorize( '%RError:%n ' ) . 'Coupons need to be limited to one cycle only or be unlimited. Setting it up to unlimited' );
$coupon->update_meta_data( '_apply_to_first_cycle_only', 'no' );
} elseif ( 1 === $discount->recurringCycleLimit ) {
$coupon->update_meta_data( '_apply_to_first_cycle_only', 'yes' );
}
} else {
/**
* When both appliesOnOneTimePurchase and appliesOnSubscription
* are true Shopify coupons can be applied to both one time purchases and subscriptions
* but Woo only supports one or the other.
* As coupons are used to renewal subscriptions we set them as subscription coupons
* if appliesOnSubscription is set to true.
* This will cause problems for people that try to use those coupons for one time
* purchases after the migration.
*/
WP_CLI::line( WP_CLI::colorize( '%YWarning:%n ' ) . 'This coupon is set to be used both in one time purchases and subscriptions in Shopify but Woo does not support that. Setting it up as a subscriptions only coupon.' );
WP_CLI::line( WP_CLI::colorize( '%BInfo:%n ' ) . 'If you want to support both install: https://github.com/woocommerce/woo-mixed-coupons' );
}
}
// Percent discount.
if ( isset( $discount->customerGets->value->percentage ) ) {
$coupon->set_amount( $discount->customerGets->value->percentage * 100 );
$coupon->set_discount_type( 'percent' );
if ( ! $is_subscription_and_one_time && true === $discount->customerGets->appliesOnSubscription ) {
$coupon->set_discount_type( 'recurring_percent' );
}
}
// Fixed amount.
if ( isset( $discount->customerGets->value->amount ) ) {
$coupon->set_amount( $discount->customerGets->value->amount->amount );
$coupon->set_discount_type( 'fixed_cart' );
if ( true === $discount->customerGets->value->appliesOnEachItem ) {
$coupon->set_discount_type( 'fixed_product' );
}
if ( ! $is_subscription_and_one_time && true === $discount->customerGets->appliesOnSubscription ) {
$coupon->set_discount_type( 'recurring_fee' );
}
}
}
}
// phpcs:enable WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase