-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathProductSyncer.php
364 lines (313 loc) · 11.9 KB
/
ProductSyncer.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
<?php
declare( strict_types=1 );
namespace Automattic\WooCommerce\GoogleListingsAndAds\Product;
use Automattic\WooCommerce\GoogleListingsAndAds\Exception\InvalidValue;
use Automattic\WooCommerce\GoogleListingsAndAds\Google\BatchInvalidProductEntry;
use Automattic\WooCommerce\GoogleListingsAndAds\Google\BatchProductIDRequestEntry;
use Automattic\WooCommerce\GoogleListingsAndAds\Google\BatchProductRequestEntry;
use Automattic\WooCommerce\GoogleListingsAndAds\Google\BatchProductResponse;
use Automattic\WooCommerce\GoogleListingsAndAds\Google\GoogleProductService;
use Automattic\WooCommerce\GoogleListingsAndAds\Infrastructure\Service;
use Automattic\WooCommerce\GoogleListingsAndAds\MerchantCenter\MerchantCenterService;
use Automattic\WooCommerce\GoogleListingsAndAds\Proxies\WC;
use Exception;
use WC_Product;
defined( 'ABSPATH' ) || exit;
/**
* Class ProductSyncer
*
* @package Automattic\WooCommerce\GoogleListingsAndAds\Product
*/
class ProductSyncer implements Service {
public const FAILURE_THRESHOLD = 5; // Number of failed attempts allowed per FAILURE_THRESHOLD_WINDOW
public const FAILURE_THRESHOLD_WINDOW = '3 hours'; // PHP supported Date and Time format: https://www.php.net/manual/en/datetime.formats.php
/**
* @var GoogleProductService
*/
protected $google_service;
/**
* @var BatchProductHelper
*/
protected $batch_helper;
/**
* @var ProductHelper
*/
protected $product_helper;
/**
* @var MerchantCenterService
*/
protected $merchant_center;
/**
* @var WC
*/
protected $wc;
/**
* ProductSyncer constructor.
*
* @param GoogleProductService $google_service
* @param BatchProductHelper $batch_helper
* @param ProductHelper $product_helper
* @param MerchantCenterService $merchant_center
* @param WC $wc
*/
public function __construct(
GoogleProductService $google_service,
BatchProductHelper $batch_helper,
ProductHelper $product_helper,
MerchantCenterService $merchant_center,
WC $wc
) {
$this->google_service = $google_service;
$this->batch_helper = $batch_helper;
$this->product_helper = $product_helper;
$this->merchant_center = $merchant_center;
$this->wc = $wc;
}
/**
* Submits an array of WooCommerce products to Google Merchant Center.
*
* @param WC_Product[] $products
*
* @return BatchProductResponse Containing both the synced and invalid products.
*
* @throws ProductSyncerException If there are any errors while syncing products with Google Merchant Center.
*/
public function update( array $products ): BatchProductResponse {
$this->validate_merchant_center_setup();
// prepare and validate products
$product_entries = $this->batch_helper->validate_and_generate_update_request_entries( $products );
return $this->update_by_batch_requests( $product_entries );
}
/**
* Submits an array of WooCommerce products to Google Merchant Center.
*
* @param BatchProductRequestEntry[] $product_entries
*
* @return BatchProductResponse Containing both the synced and invalid products.
*
* @throws ProductSyncerException If there are any errors while syncing products with Google Merchant Center.
*/
public function update_by_batch_requests( array $product_entries ): BatchProductResponse {
$this->validate_merchant_center_setup();
// bail if no valid products provided
if ( empty( $product_entries ) ) {
return new BatchProductResponse( [], [] );
}
$updated_products = [];
$invalid_products = [];
foreach ( array_chunk( $product_entries, GoogleProductService::BATCH_SIZE ) as $batch_entries ) {
try {
$response = $this->google_service->insert_batch( $batch_entries );
$updated_products = array_merge( $updated_products, $response->get_products() );
$invalid_products = array_merge( $invalid_products, $response->get_errors() );
// update the meta data for the synced and invalid products
array_walk( $updated_products, [ $this->batch_helper, 'mark_as_synced' ] );
array_walk( $invalid_products, [ $this->batch_helper, 'mark_as_invalid' ] );
} catch ( Exception $exception ) {
do_action( 'woocommerce_gla_exception', $exception, __METHOD__ );
throw new ProductSyncerException( sprintf( 'Error updating Google products: %s', $exception->getMessage() ), 0, $exception );
}
}
$this->handle_update_errors( $invalid_products );
do_action(
'woocommerce_gla_batch_updated_products',
$updated_products,
$invalid_products
);
do_action(
'woocommerce_gla_debug_message',
sprintf(
"Submitted %s products:\n%s",
count( $updated_products ),
json_encode( $updated_products )
),
__METHOD__
);
if ( ! empty( $invalid_products ) ) {
do_action(
'woocommerce_gla_debug_message',
sprintf(
"%s products failed to sync with Merchant Center:\n%s",
count( $invalid_products ),
json_encode( $invalid_products )
),
__METHOD__
);
}
return new BatchProductResponse( $updated_products, $invalid_products );
}
/**
* Deletes an array of WooCommerce products from Google Merchant Center.
*
* @param WC_Product[] $products
*
* @return BatchProductResponse Containing both the deleted and invalid products.
*
* @throws ProductSyncerException If there are any errors while deleting products from Google Merchant Center.
*/
public function delete( array $products ): BatchProductResponse {
$this->validate_merchant_center_setup();
$synced_products = $this->batch_helper->filter_synced_products( $products );
$product_entries = $this->batch_helper->generate_delete_request_entries( $synced_products );
return $this->delete_by_batch_requests( $product_entries );
}
/**
* Deletes an array of WooCommerce products from Google Merchant Center.
*
* Note: This method does not automatically delete variations of a parent product. They each must be provided via the $product_entries argument.
*
* @param BatchProductIDRequestEntry[] $product_entries
*
* @return BatchProductResponse Containing both the deleted and invalid products (including their variation).
*
* @throws ProductSyncerException If there are any errors while deleting products from Google Merchant Center.
*/
public function delete_by_batch_requests( array $product_entries ): BatchProductResponse {
$this->validate_merchant_center_setup();
// return empty response if no synced product found
if ( empty( $product_entries ) ) {
return new BatchProductResponse( [], [] );
}
$deleted_products = [];
$invalid_products = [];
foreach ( array_chunk( $product_entries, GoogleProductService::BATCH_SIZE ) as $batch_entries ) {
try {
$response = $this->google_service->delete_batch( $batch_entries );
$deleted_products = array_merge( $deleted_products, $response->get_products() );
$invalid_products = array_merge( $invalid_products, $response->get_errors() );
array_walk( $deleted_products, [ $this->batch_helper, 'mark_as_unsynced' ] );
} catch ( Exception $exception ) {
do_action( 'woocommerce_gla_exception', $exception, __METHOD__ );
throw new ProductSyncerException( sprintf( 'Error deleting Google products: %s', $exception->getMessage() ), 0, $exception );
}
}
$this->handle_delete_errors( $invalid_products );
do_action(
'woocommerce_gla_batch_deleted_products',
$deleted_products,
$invalid_products
);
do_action(
'woocommerce_gla_debug_message',
sprintf(
"Deleted %s products:\n%s",
count( $deleted_products ),
json_encode( $deleted_products ),
),
__METHOD__
);
if ( ! empty( $invalid_products ) ) {
do_action(
'woocommerce_gla_debug_message',
sprintf(
"Failed to delete %s products from Merchant Center:\n%s",
count( $invalid_products ),
json_encode( $invalid_products )
),
__METHOD__
);
}
return new BatchProductResponse( $deleted_products, $invalid_products );
}
/**
* Return the list of supported product types.
*
* @return array
*/
public static function get_supported_product_types(): array {
return (array) apply_filters( 'woocommerce_gla_supported_product_types', [ 'simple', 'variable', 'variation' ] );
}
/**
* Return the list of product types we will hide functionality for (default none).
*
* @since 1.2.0
*
* @return array
*/
public static function get_hidden_product_types(): array {
return (array) apply_filters( 'woocommerce_gla_hidden_product_types', [] );
}
/**
* @param BatchInvalidProductEntry[] $invalid_products
*/
protected function handle_update_errors( array $invalid_products ) {
$error_products = [];
foreach ( $invalid_products as $invalid_product ) {
if ( $invalid_product->has_error( GoogleProductService::INTERNAL_ERROR_REASON ) ) {
$wc_product_id = $invalid_product->get_wc_product_id();
$wc_product = $this->wc->maybe_get_product( $wc_product_id );
// Only schedule for retry if the failure threshold has not been reached.
if (
$wc_product instanceof WC_Product &&
! $this->product_helper->is_update_failed_threshold_reached( $wc_product )
) {
$error_products[ $wc_product_id ] = $wc_product_id;
}
}
}
if ( ! empty( $error_products ) && apply_filters( 'woocommerce_gla_products_update_retry_on_failure', true, $invalid_products ) ) {
do_action( 'woocommerce_gla_batch_retry_update_products', $error_products );
do_action(
'woocommerce_gla_error',
sprintf( 'Internal API errors while submitting the following products: %s', join( ', ', $error_products ) ),
__METHOD__
);
}
}
/**
* @param BatchInvalidProductEntry[] $invalid_products
*/
protected function handle_delete_errors( array $invalid_products ) {
$internal_error_ids = [];
foreach ( $invalid_products as $invalid_product ) {
$google_product_id = $invalid_product->get_google_product_id();
$wc_product_id = $invalid_product->get_wc_product_id();
$wc_product = $this->wc->maybe_get_product( $wc_product_id );
if ( ! $wc_product instanceof WC_Product || empty( $google_product_id ) ) {
continue;
}
// not found
if ( $invalid_product->has_error( GoogleProductService::NOT_FOUND_ERROR_REASON ) ) {
do_action(
'woocommerce_gla_error',
sprintf(
'Attempted to delete product "%s" (WooCommerce Product ID: %s) but it did not exist in Google Merchant Center, removing the synced product ID from database.',
$google_product_id,
$wc_product_id
),
__METHOD__
);
$this->product_helper->remove_google_id( $wc_product, $google_product_id );
}
// internal error
if ( $invalid_product->has_error( GoogleProductService::INTERNAL_ERROR_REASON ) ) {
$this->product_helper->increment_failed_delete_attempt( $wc_product );
// Only schedule for retry if the failure threshold has not been reached.
if ( ! $this->product_helper->is_delete_failed_threshold_reached( $wc_product ) ) {
$internal_error_ids[ $google_product_id ] = $wc_product_id;
}
}
}
// call an action to retry if any products with internal errors exist
if ( ! empty( $internal_error_ids ) && apply_filters( 'woocommerce_gla_products_delete_retry_on_failure', true, $invalid_products ) ) {
do_action( 'woocommerce_gla_batch_retry_delete_products', $internal_error_ids );
do_action(
'woocommerce_gla_error',
// phpcs:ignore WordPress.PHP.DevelopmentFunctions
sprintf( 'Internal API errors while deleting the following products: %s', print_r( $internal_error_ids, true ) ),
__METHOD__
);
}
}
/**
* Validates whether Merchant Center is connected and ready for syncing data.
*
* @throws ProductSyncerException If the Google Merchant Center connection is not ready.
*/
protected function validate_merchant_center_setup(): void {
if ( ! $this->merchant_center->is_ready_for_syncing() ) {
do_action( 'woocommerce_gla_error', 'Cannot sync any products before setting up Google Merchant Center.', __METHOD__ );
throw new ProductSyncerException( __( 'Google Merchant Center has not been set up correctly. Please review your configuration.', 'google-listings-and-ads' ) );
}
}
}