Changeset 2311211
- Timestamp:
- 05/24/2020 08:05:01 PM (6 years ago)
- Location:
- wooms/trunk
- Files:
-
- 2 added
- 8 edited
-
README.md (modified) (1 diff)
-
functions.php (modified) (4 diffs)
-
inc/ProductGallery.php (modified) (15 diffs)
-
inc/ProductImage.php (modified) (15 diffs)
-
inc/ProductsPrices.php (modified) (3 diffs)
-
inc/ProductsWalker.php (modified) (23 diffs)
-
migrations (added)
-
migrations/7-2.php (added)
-
readme.txt (modified) (1 diff)
-
wooms.php (modified) (8 diffs)
Legend:
- Unmodified
- Added
- Removed
-
wooms/trunk/README.md
r2260121 r2311211 1 1 # WooMS - WooCommerce и МойСклад (интеграция, синхронизация, выгрузка, загрузка) 2 3 ## Вопросы и ответы 4 5 https://github.com/wpcraft-ru/wooms/issues?q=label%3Aqa 2 6 3 7 ## Особенности -
wooms/trunk/functions.php
r2290417 r2311211 34 34 'redirection' => 5, 35 35 'headers' => array( 36 "Content-Type" => 'application/json ',36 "Content-Type" => 'application/json;charset=utf-8', 37 37 'Authorization' => 'Basic ' . 38 38 base64_encode( get_option( 'woomss_login' ) . ':' . get_option( 'woomss_pass' ) ), … … 40 40 'body' => $data, 41 41 ); 42 42 43 43 $request = wp_remote_request( $url, $args); 44 44 if ( is_wp_error( $request ) ) { … … 46 46 'wooms_logger_error', 47 47 $type = 'WooMS-Request', 48 $title = 'Ошибка REST API ',48 $title = 'Ошибка REST API WP Error', 49 49 $desc = $request->get_error_message() 50 50 ); … … 70 70 'wooms_logger_error', 71 71 $type = 'WooMS-Request', 72 $title = $error['error'] 72 $title = $url, 73 $response 73 74 ); 74 75 } -
wooms/trunk/inc/ProductGallery.php
r2290417 r2311211 17 17 18 18 /** 19 * WooMS_Import_Product_Images constructor.19 * the init 20 20 */ 21 21 public static function init() 22 22 { 23 23 24 25 // add_action('init', function(){ 26 // if(!isset($_GET['dd'])){ 27 // return; 28 // } 29 30 // self::download_images_by_id(12237); 31 32 33 // dd(0); 34 // }); 35 24 36 add_action('gallery_images_download_schedule', [__CLASS__, 'download_images_from_metafield']); 25 37 … … 30 42 add_action('init', [__CLASS__, 'add_schedule_hook']); 31 43 44 add_action('wooms_main_walker_finish', [__CLASS__, 'restart']); 32 45 33 46 add_action('wooms_product_images_info', [__CLASS__, 'render_state_info']); 34 47 } 48 49 50 /** 51 * restart walker after finish main product walker 52 */ 53 public static function restart() 54 { 55 delete_transient('gallery_images_downloaded'); 35 56 } 36 57 … … 39 60 * check disable option 40 61 */ 41 public static function is_disable(){ 62 public static function is_disable() 63 { 42 64 if (empty(get_option('woomss_gallery_sync_enabled'))) { 43 65 return true; … … 47 69 } 48 70 71 49 72 /** 50 73 * render_state_info 51 74 */ 52 public static function render_state_info() {53 54 if (self::is_disable()){75 public static function render_state_info() 76 { 77 if (self::is_disable()) { 55 78 return; 56 79 } … … 58 81 $strings = []; 59 82 60 if (as_next_scheduled_action(self::$walker_hook_name) ) {61 $strings[] = sprintf('<strong>Статус:</strong> %s', 'Выполняется очередями в фоне');62 } else {63 $strings[] = sprintf('<strong>Статус:</strong> %s', 'в ожидании новых задач');83 if (as_next_scheduled_action(self::$walker_hook_name)) { 84 $strings[] = sprintf('<strong>Статус:</strong> %s', 'галлереи продуктов загружаются очередями в фоне'); 85 } else { 86 $strings[] = sprintf('<strong>Статус:</strong> %s', 'в ожидании новых задач'); 64 87 } 65 88 66 89 $strings[] = sprintf('Очередь задач: <a href="%s">открыть</a>', admin_url('admin.php?page=wc-status&tab=action-scheduler&s=gallery_images_download_schedule&orderby=schedule&order=desc')); 67 90 68 if (defined('WC_LOG_HANDLER') && 'WC_Log_Handler_DB' == WC_LOG_HANDLER){91 if (defined('WC_LOG_HANDLER') && 'WC_Log_Handler_DB' == WC_LOG_HANDLER) { 69 92 $strings[] = sprintf('Журнал обработки: <a href="%s">открыть</a>', admin_url('admin.php?page=wc-status&tab=logs&source=WooMS-ProductGallery')); 70 93 } else { … … 72 95 } 73 96 74 ?>97 ?> 75 98 <hr> 76 99 <div> … … 79 102 <ul> 80 103 <li> 81 <?php82 echo implode('</li><li>', $strings);83 ?>104 <?php 105 echo implode('</li><li>', $strings); 106 ?> 84 107 </li> 85 108 </ul> 86 109 </div> 87 <?php 88 89 90 } 110 <?php 111 } 112 91 113 92 114 /** 93 115 * update_product 94 116 */ 95 public static function update_product($product, $ value, $data)117 public static function update_product($product, $data_api, $data) 96 118 { 97 119 … … 99 121 return $product; 100 122 } 101 $product_id = $product->get_id(); 102 103 self::get_gallery_from_api($product_id); 123 124 if (empty($data_api['images']['meta']['size'])) { 125 return $product; 126 } 127 128 $img_count = $data_api['images']['meta']['size']; 129 $href = $data_api['images']['meta']['href']; 130 131 if ($img_count < 2) { 132 return $product; 133 } 134 135 $product->update_meta_data('wooms_data_for_get_gallery', $href); 136 104 137 105 138 return $product; 106 139 } 107 140 108 public static function get_gallery_from_api($product_id)109 {110 // Getting data from mysklad product directly using id of product111 $pm_id = get_post_meta($product_id, 'wooms_id', true);112 $url = sprintf('https://online.moysklad.ru/api/remap/1.2/entity/product/%s/images', $pm_id);113 $data_api = wooms_request($url);114 115 //Check image116 if (empty($data_api['rows']) || count($data_api['rows']) == 1) {117 return false;118 }119 120 // Making array with image data121 $product_gallery_data = [];122 123 foreach ($data_api['rows'] as $key => $image) {124 // First key is the first image that already downloading with another class https://github.com/uptimizt/dev-wms-local/issues/4125 if ($key !== 0) {126 $product_gallery_data[$image['filename']] = $image['meta']['downloadHref'];127 }128 }129 130 // encoding array to json131 $product_gallery_data = json_encode($product_gallery_data);132 133 // check current meta is set already or not134 if (!empty(get_post_meta($product_id, 'wooms_data_for_get_gallery'))) {135 return false;136 } else {137 update_post_meta($product_id, 'wooms_data_for_get_gallery', $product_gallery_data);138 }139 }140 141 141 142 /** … … 152 153 } 153 154 154 if (self::is_wait()){155 if (self::is_wait()) { 155 156 as_unschedule_all_actions(self::$walker_hook_name); 156 157 return; … … 162 163 163 164 // Adding schedule hook 164 as_schedule_recurring_action(time(), 60, self::$walker_hook_name, [], 'WooMS' ); 165 166 } 167 168 /** 169 * Checking if schedule can be created or not 170 * 171 * @return void 172 */ 173 public static function check_schedule_needed() 174 { 175 176 // If next schedule is not this one and the sync is active and the all gallery images is downloaded 177 if (as_next_scheduled_action('gallery_images_download_schedule', [], 'ProductGallery')) { 178 return false; 179 } 180 181 // Checking if there is any of this type pending schedules 182 $future_schedules = as_get_scheduled_actions( 183 [ 184 'hook' => 'gallery_images_download_schedule', 185 'status' => \ActionScheduler_Store::STATUS_PENDING, 186 'group' => 'ProductGallery' 187 ] 188 ); 189 190 if (!empty($future_schedules)) { 191 return false; 192 } 193 194 if (empty(get_transient('wooms_start_timestamp'))) { 195 return false; 196 } 197 165 as_schedule_recurring_action(time(), 60, self::$walker_hook_name, [], 'WooMS'); 166 } 167 168 169 /** 170 * check new task for walker 171 */ 172 public static function is_wait() 173 { 198 174 if (get_transient('gallery_images_downloaded')) { 199 return false;200 }201 202 return true;203 }204 205 206 /**207 * check new task for walker208 */209 public static function is_wait(){210 $args = array(211 'post_type' => 'product',212 'numberposts' => 1,213 'meta_query' => array(214 array(215 'key' => 'wooms_data_for_get_gallery',216 'compare' => 'EXISTS',217 ),218 ),219 'no_found_rows' => true,220 'cache_results' => false,221 );222 223 $list = get_posts($args);224 225 // If no images left to download226 if (empty($list)) {227 175 return true; 228 176 } … … 230 178 return false; 231 179 } 180 232 181 233 182 /** … … 266 215 267 216 // Adding the option that all images downloaded and the sync is over 268 set_transient('gallery_images_downloaded', t rue);217 set_transient('gallery_images_downloaded', time()); 269 218 270 219 do_action( … … 277 226 } 278 227 279 $result = [];280 281 228 foreach ($list as $key => $value) { 282 $result[] = self::download_images_by_id($value->ID); 283 } 284 285 if (empty($result)) { 286 return false; 287 } else { 288 return $result; 289 } 290 } 229 self::download_images_by_id($value->ID); 230 delete_post_meta($value->ID, 'wooms_data_for_get_gallery'); 231 } 232 } 233 291 234 292 235 /** … … 298 241 public static function download_images_by_id($product_id, $all = false) 299 242 { 300 $img_data_list = get_post_meta($product_id, 'wooms_data_for_get_gallery', true); 301 302 if (empty($img_data_list)) { 303 self::get_gallery_from_api($product_id); 304 $img_data_list = get_post_meta($product_id, 'wooms_data_for_get_gallery', true); 305 } 306 307 $img_data_list = json_decode($img_data_list, true); 243 $imgages_url = get_post_meta($product_id, 'wooms_data_for_get_gallery', true); 244 245 $img_data_list = $imgages_url; 246 247 $images_data = wooms_request($imgages_url); 248 249 if (empty($images_data['rows'])) { 250 return false; 251 } 308 252 309 253 $media_data_list = []; 310 254 311 foreach ($img_data_list as $image_name => $url) { 312 313 if ($check_id = self::check_exist_image_by_url($image_name)) { 314 return $check_id; 255 foreach ($images_data['rows'] as $key => $row) { 256 257 $url_download = $row['meta']['downloadHref']; 258 $media_id = self::uploadRemoteImageAndAttach($url_download, $product_id, $row['filename']); 259 260 if ($media_id == get_post_thumbnail_id($product_id)) { 261 continue; 315 262 } 316 317 $media_id = self::uploadRemoteImageAndAttach($url, $product_id, $image_name);318 263 319 264 if (!empty($media_id)) { … … 327 272 update_post_meta($product_id, '_product_image_gallery', implode(',', $media_data_list)); 328 273 329 // Delete meta for correct query work330 delete_post_meta($product_id, 'wooms_data_for_get_gallery');331 332 274 do_action( 333 275 'wooms_logger', 334 276 __CLASS__, 335 sprintf('Image is attach to the product %s (Image id list [%s], filename: %s)', $product_id, implode(',', $media_data_list), $ image_name)277 sprintf('Image is attach to the product %s (Image id list [%s], filename: %s)', $product_id, implode(',', $media_data_list), $row['filename']) 336 278 ); 337 279 } else { -
wooms/trunk/inc/ProductImage.php
r2290417 r2311211 22 22 public static function init() 23 23 { 24 25 26 // add_action('init', function(){ 27 // if(!isset($_GET['dd'])){ 28 // return; 29 // } 30 31 // // dd(get_transient('wooms_end_timestamp')); 32 // // self::set_state('timestamp', 0); 33 // self::product_image_download(11774); 34 // // self::batch_handler(); 35 36 // dd(0); 37 // }); 38 39 40 add_action('wooms_product_image_sync', [__CLASS__, 'batch_handler']); 41 add_action('init', [__CLASS__, 'add_schedule_hook']); 42 add_action('wooms_main_walker_finish', [__CLASS__, 'restart']); 43 24 44 /** 25 45 * Обновление данных о продукте … … 29 49 add_action('admin_init', [__CLASS__, 'settings_init'], 50); 30 50 31 add_action('init', [__CLASS__, 'add_schedule_hook']);32 33 add_action('wooms_product_image_sync', [__CLASS__, 'download_images_from_metafield']);34 51 35 52 add_action('woomss_tool_actions_btns', [__CLASS__, 'ui_for_manual_start'], 15); 36 53 add_action('woomss_tool_actions_wooms_products_images_manual_start', [__CLASS__, 'ui_action']); 37 38 39 40 } 41 42 54 } 55 56 57 public static function restart() 58 { 59 delete_transient('wooms_product_image_sync_finish'); 60 } 43 61 44 62 … … 48 66 public static function update_product($product, $value, $data) 49 67 { 50 if ( ! self::is_enable()) {68 if (!self::is_enable()) { 51 69 return $product; 52 70 } … … 55 73 56 74 //Check image 57 if (empty($value['image ']['meta']['href'])) {75 if (empty($value['images']['meta']['size'])) { 58 76 return $product; 59 77 } else { 60 $url = $value['image ']['meta']['href'];78 $url = $value['images']['meta']['href']; 61 79 } 62 80 … … 66 84 } else { 67 85 $product->update_meta_data('wooms_url_for_get_thumbnail', $url); 68 $product->update_meta_data('wooms_image_data', $value['image']);69 86 } 70 87 … … 77 94 public static function add_schedule_hook($force = false) 78 95 { 79 if ( ! self::is_enable() ) { 80 return; 81 } 82 83 if( self::is_wait()){ 84 return; 85 } 86 87 if (as_next_scheduled_action(self::$walker_hook_name) && ! $force) { 88 return; 89 } 90 91 as_schedule_single_action( time() + 11, self::$walker_hook_name, [], 'WooMS' ); 92 96 if (!self::is_enable()) { 97 return; 98 } 99 100 if (self::is_wait()) { 101 return; 102 } 103 104 if (as_next_scheduled_action(self::$walker_hook_name) && !$force) { 105 return; 106 } 107 108 as_schedule_single_action(time() + 11, self::$walker_hook_name, [], 'WooMS'); 93 109 } 94 110 … … 98 114 public static function ui_action() 99 115 { 100 $data = self:: download_images_from_metafield();116 $data = self::batch_handler(); 101 117 102 118 echo '<hr>'; … … 118 134 * checking the option activation 119 135 */ 120 public static function is_enable(){ 136 public static function is_enable() 137 { 121 138 if (empty(get_option('woomss_images_sync_enabled'))) { 122 139 return false; … … 126 143 } 127 144 128 145 129 146 /** 130 147 * checking the pause state 131 148 */ 132 public static function is_wait(){ 133 149 public static function is_wait() 150 { 151 if (get_transient('wooms_product_image_sync_finish')) { 152 return true; 153 } 154 155 return false; 156 } 157 158 159 /** 160 * Download images from meta 161 */ 162 public static function batch_handler() 163 { 164 if (!self::is_enable()) { 165 return; 166 } 134 167 135 168 $args = array( … … 150 183 151 184 if (empty($list)) { 152 return true; 153 } 154 155 return false; 156 157 } 158 159 160 /** 161 * Download images from meta 162 */ 163 public static function download_images_from_metafield() 164 { 165 if ( ! self::is_enable() ) { 166 return; 167 } 168 169 $args = array( 170 'post_type' => 'product', 171 'meta_query' => array( 172 array( 173 'key' => 'wooms_url_for_get_thumbnail', 174 'compare' => 'EXISTS', 175 ), 176 ), 177 'no_found_rows' => true, 178 'update_post_term_cache' => false, 179 'update_post_meta_cache' => false, 180 'cache_results' => false, 181 ); 182 183 $list = get_posts($args); 184 185 if (empty($list)) { 185 186 set_transient('wooms_product_image_sync_finish', time()); 186 187 187 188 do_action( … … 191 192 ); 192 193 193 194 194 return false; 195 195 } … … 198 198 199 199 foreach ($list as $key => $value) { 200 $url = get_post_meta($value->ID, 'wooms_url_for_get_thumbnail', true); 201 $image_data = get_post_meta($value->ID, 'wooms_image_data', true); 202 203 $image_name = $image_data['filename']; 204 205 //$check_id = self::download_img($url, $image_name, $value->ID); 206 $check_id = self::uploadRemoteImageAndAttach($url, $value->ID, $image_name); 207 208 if (!empty($check_id)) { 209 210 set_post_thumbnail($value->ID, $check_id); 211 delete_post_meta($value->ID, 'wooms_url_for_get_thumbnail'); 212 delete_post_meta($value->ID, 'wooms_image_data'); 200 if (self::product_image_download($value->ID)) { 213 201 $result[] = $value->ID; 214 215 do_action(216 'wooms_logger',217 __CLASS__,218 sprintf('Загружена картинка для продукта %s (ИД %s, filename: %s)', $value->ID, $check_id, $image_name)219 );220 } else {221 do_action(222 'wooms_logger_error',223 __CLASS__,224 sprintf('Ошибка назначения картинки для продукта %s (url %s, filename: %s)', $value->ID, $url, $image_name)225 );226 202 } 203 204 delete_post_meta($value->ID, 'wooms_url_for_get_thumbnail'); 227 205 } 228 206 … … 235 213 } 236 214 } 215 216 public static function product_image_download($product_id) 217 { 218 if (!$url = get_post_meta($product_id, 'wooms_url_for_get_thumbnail', true)) { 219 return false; 220 } 221 222 $images_data = wooms_request($url); 223 224 if (empty($images_data['rows'][0]['filename'])) { 225 do_action( 226 'wooms_logger_error', 227 __CLASS__, 228 sprintf('Ошибка получения картинки для продукта %s (url %s)', $product_id, $url ), 229 $images_data 230 ); 231 return false; 232 } 233 234 $image_name = $images_data['rows'][0]['filename']; 235 $url = $images_data['rows'][0]['meta']['downloadHref']; 236 237 $check_id = self::uploadRemoteImageAndAttach($url, $product_id, $image_name); 238 239 if (!empty($check_id)) { 240 241 set_post_thumbnail($product_id, $check_id); 242 delete_post_meta($product_id, 'wooms_url_for_get_thumbnail'); 243 delete_post_meta($product_id, 'wooms_image_data'); 244 245 do_action( 246 'wooms_logger', 247 __CLASS__, 248 sprintf('Загружена картинка для продукта %s (ИД %s, filename: %s)', $product_id, $check_id, $image_name) 249 ); 250 return true; 251 } else { 252 do_action( 253 'wooms_logger_error', 254 __CLASS__, 255 sprintf('Ошибка назначения картинки для продукта %s (url %s, filename: %s)', $product_id, $url, $image_name) 256 ); 257 return false; 258 } 259 } 260 237 261 238 262 /** … … 255 279 public static function ui_for_manual_start() 256 280 { 257 if ( !self::is_enable()) {258 return; 259 } 260 281 if (!self::is_enable()) { 282 return; 283 } 284 261 285 $strings = []; 262 286 263 if (as_next_scheduled_action(self::$walker_hook_name , null, 'WooMS')) {287 if (as_next_scheduled_action(self::$walker_hook_name)) { 264 288 $strings[] = sprintf('<strong>Статус:</strong> %s', 'Выполняется очередями в фоне'); 265 } else {289 } else { 266 290 $strings[] = sprintf('<strong>Статус:</strong> %s', 'в ожидании новых задач'); 267 291 } 268 292 269 293 $strings[] = sprintf('Очередь задач: <a href="%s">открыть</a>', admin_url('admin.php?page=wc-status&tab=action-scheduler&s=wooms_product_image_sync&orderby=schedule&order=desc')); 270 271 if (defined('WC_LOG_HANDLER') && 'WC_Log_Handler_DB' == WC_LOG_HANDLER){272 $strings[] = sprintf('Журнал обработки: <a href="%s">открыть</a>', admin_url('admin.php?page=wc-status&tab=logs&source=WooMS-ProductImage'));273 } else { 274 $strings[] = sprintf('Журнал обработки: <a href="%s">открыть</a>', admin_url('admin.php?page=wc-status&tab=logs'));275 } 276 277 ?>294 295 if (defined('WC_LOG_HANDLER') && 'WC_Log_Handler_DB' == WC_LOG_HANDLER) { 296 $strings[] = sprintf('Журнал обработки: <a href="%s">открыть</a>', admin_url('admin.php?page=wc-status&tab=logs&source=WooMS-ProductImage')); 297 } else { 298 $strings[] = sprintf('Журнал обработки: <a href="%s">открыть</a>', admin_url('admin.php?page=wc-status&tab=logs')); 299 } 300 301 ?> 278 302 279 303 <h2>Изображения</h2> … … 285 309 ?> 286 310 <div class="wrap"> 287 <div id="message" class="notice notice-warning"> 288 <?php 289 290 foreach($strings as $string){ 291 printf('<p>%s</p>', $string); 292 } 293 294 do_action('wooms_product_images_info'); 295 296 ?> 311 <div id="message" class="notice notice-warning"> 312 <?php 313 314 foreach ($strings as $string) { 315 printf('<p>%s</p>', $string); 316 } 317 318 do_action('wooms_product_images_info'); 319 320 ?> 321 </div> 297 322 </div> 298 </div> 299 <?php 323 <?php 300 324 } 301 325 -
wooms/trunk/inc/ProductsPrices.php
r2250855 r2311211 1 1 <?php 2 2 3 namespace WooMS; 3 4 4 if ( ! defined( 'ABSPATH' )) {5 if (!defined('ABSPATH')) { 5 6 exit; // Exit if accessed directly 6 7 } … … 9 10 * Select specific price is setup 10 11 */ 11 class ProductsPrices { 12 class ProductsPrices 13 { 12 14 13 /**14 * The init15 */16 public static function init() {17 18 /**19 * Обновление данных о ценах20 */21 add_filter( 'wooms_product_price', array( __CLASS__, 'chg_price' ), 10, 3);22 add_action( 'admin_init', array( __CLASS__, 'settings_init' ), $priority = 101, $accepted_args = 1);15 /** 16 * The init 17 */ 18 public static function init() 19 { 20 /** 21 * Обновление данных о ценах 22 */ 23 add_filter('wooms_product_price', array(__CLASS__, 'chg_price'), 10, 3); 24 add_action('admin_init', array(__CLASS__, 'settings_init'), $priority = 101, $accepted_args = 1); 23 25 } 24 26 … … 27 29 * Check specifiec price and replace if isset price 28 30 */ 29 public static function chg_price( $price, $data, $product_id ) { 31 public static function chg_price($price, $data, $product_id) 32 { 33 $price_name = get_option('wooms_price_id'); 30 34 31 $price_name = get_option( 'wooms_price_id' ); 32 if ( empty( $price_name ) ) { 35 if (empty($price_name)) { 33 36 return $price; 34 } else {35 36 $price_value = self::get_value_for_price_type( $data );37 38 do_action('wooms_logger', __CLASS__,39 sprintf('Выбрана цена "%s" = %s. Для продукта ИД: %s', $price_name, $price_value, $product_id)40 );41 42 if ( empty( $price_value ) ) {43 return $price;44 } else {45 return $price_value;46 }47 }48 }49 50 /**51 * Get specific price52 * Return 0 or value price53 */54 public static function get_value_for_price_type( $data ) {55 56 $price_name = get_option( 'wooms_price_id' );57 if ( empty( $price_name ) ) {58 return 0;59 37 } 60 38 61 39 $price_value = 0; 62 foreach ( $data["salePrices"] as $price ) { 63 if ( $price["priceType"] == $price_name ) { 64 $price_value = $price["value"]; 40 41 foreach ($data["salePrices"] as $price_item) { 42 if ($price_item["priceType"]['name'] == $price_name) { 43 $price_value = $price_item["value"]; 65 44 } 66 45 } 67 if ( empty( $price_value ) ) { 68 return 0; 69 } else { 70 return $price_value; 71 } 46 47 do_action( 48 'wooms_logger', 49 __CLASS__, 50 sprintf('Выбрана цена "%s" = %s. Для продукта ИД: %s', $price_name, $price_value, $product_id) 51 ); 52 53 if ($price_value == 0) { 54 return $price; 55 } 56 57 return $price_value; 72 58 } 59 73 60 74 61 /** 75 62 * Add settings 76 63 */ 77 public static function settings_init() { 78 register_setting( 'mss-settings', 'wooms_price_id' ); 79 add_settings_field( 80 $id = 'wooms_price_id', 81 $title = 'Тип Цены', 82 $callback = array(__CLASS__, 'display_field_wooms_price_id' ), 83 $page = 'mss-settings', 84 $section = 'woomss_section_other' 85 ); 64 public static function settings_init() 65 { 66 register_setting('mss-settings', 'wooms_price_id'); 67 add_settings_field( 68 $id = 'wooms_price_id', 69 $title = 'Тип Цены', 70 $callback = array(__CLASS__, 'display_field_wooms_price_id'), 71 $page = 'mss-settings', 72 $section = 'woomss_section_other' 73 ); 86 74 } 87 75 88 /** 89 * display_field_wooms_price_id 90 */ 91 public static function display_field_wooms_price_id() { 76 /** 77 * display_field_wooms_price_id 78 */ 79 public static function display_field_wooms_price_id() 80 { 92 81 $id = 'wooms_price_id'; 93 printf( '<input type="text" name="%s" value="%s" />', $id, sanitize_text_field( get_option( $id ) ));82 printf('<input type="text" name="%s" value="%s" />', $id, sanitize_text_field(get_option($id))); 94 83 echo '<p><small>Укажите наименование цены, если нужно выбрать специальный тип цен. Система будет проверять такой тип цены и если он указан то будет подставлять его вместо базового.</small></p>'; 95 84 } -
wooms/trunk/inc/ProductsWalker.php
r2290417 r2311211 9 9 /** 10 10 * Product Import Walker 11 * do_action('wooms_product_import_row', $value, $key, $data);12 11 */ 13 12 class ProductsWalker 14 13 { 15 14 16 15 17 16 public static $state_transient_key = 'wooms_products_walker_state'; 18 17 19 18 public static $walker_hook_name = 'wooms_products_walker_batch'; 20 19 21 20 22 21 /** … … 25 24 public static function init() 26 25 { 26 27 // add_action('init', function () { 28 // if (!isset($_GET['dd'])) { 29 // return; 30 // } 31 32 // // dd(get_transient('wooms_end_timestamp')); 33 // self::set_state('timestamp', 0); 34 35 // self::batch_handler(); 36 37 // dd(0); 38 // }); 39 40 27 41 add_action('init', [__CLASS__, 'add_schedule_hook']); 28 42 … … 42 56 //Other 43 57 add_action('add_meta_boxes', [__CLASS__, 'add_meta_boxes_post_type']); 44 45 58 } 46 59 … … 104 117 105 118 //save data of source 106 $product->update_meta_data('wooms_data_api', json_encode($data_api, JSON_PRETTY_PRINT ));119 $product->update_meta_data('wooms_data_api', json_encode($data_api, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); 107 120 108 121 $product_id = $product->save(); … … 161 174 //Price Retail 'salePrices' 162 175 if (isset($data_of_source['salePrices'][0]['value'])) { 176 177 163 178 $price_source = floatval($data_of_source['salePrices'][0]['value']); 164 179 $price = apply_filters('wooms_product_price', $price_source, $data_api, $product_id); 165 180 166 $price = $price / 100; 181 182 $price = floatval($price) / 100; 167 183 168 184 $product->set_price($price); … … 170 186 } 171 187 172 $product->set_catalog_visibility('visible'); 173 $product->set_stock_status('instock'); 174 $product->set_manage_stock('no'); 175 176 $product->set_status('publish'); 188 if($reset = apply_filters('wooms_reset_state_products', true)){ 189 $product->set_catalog_visibility('visible'); 190 $product->set_stock_status('instock'); 191 $product->set_manage_stock('no'); 192 $product->set_status('publish'); 193 } 177 194 178 195 return $product; … … 185 202 public static function batch_handler($state = []) 186 203 { 187 if(self::walker_is_waiting()){188 return;189 }190 191 //the lock stands if the handler is currently running192 set_transient('wooms_walker_lock', 1, 60);193 194 $count = apply_filters('wooms_iteration_size', 10);195 204 $state = self::get_state(); 196 205 197 206 //state reset for new session 198 if (empty($state['timestamp'])){207 if (empty($state['timestamp'])) { 199 208 200 209 self::walker_started(); 201 202 self::set_state('timestamp', date("YmdHis"));203 self::set_state('end_timestamp', 0);204 self::set_state('count', 0);205 206 delete_transient('wooms_end_timestamp');207 210 208 211 $query_arg_default = [ 209 212 'offset' => 0, 210 'limit' => $count, 211 'scope' => 'product', 213 'limit' => apply_filters('wooms_iteration_size', 20), 212 214 ]; 213 215 … … 217 219 $query_arg = self::get_state('query_arg'); 218 220 219 $url = 'https://online.moysklad.ru/api/remap/1.1/entity/assortment'; 221 /** 222 * issue https://github.com/wpcraft-ru/wooms/issues/296 223 */ 224 $url = 'https://online.moysklad.ru/api/remap/1.2/entity/product'; 220 225 221 226 $url = add_query_arg($query_arg, $url); … … 223 228 $url = apply_filters('wooms_url_get_products', $url); 224 229 230 $filters = [ 231 // 'pathName~=Диваны', 232 ]; 233 234 $filters = apply_filters('wooms_url_get_products_filters', $filters); 235 236 if (!empty($filters)) { 237 $filters = implode(';', $filters); 238 $url = add_query_arg('filter', $filters, $url); 239 } 240 225 241 try { 226 242 227 228 243 $data = wooms_request($url); 244 // dd($data); 229 245 230 246 do_action('wooms_logger', __CLASS__, sprintf('Отправлен запрос %s', $url)); … … 233 249 if (isset($data['rows']) && empty($data['rows'])) { 234 250 self::walker_finish(); 235 delete_transient('wooms_walker_lock');236 251 return; 237 252 } 238 253 239 254 do_action('wooms_walker_start_iteration', $data); 240 241 /**242 * @TODO: deprecated. remove after tests243 */244 do_action('wooms_walker_start');245 255 246 256 foreach ($data['rows'] as $key => $value) { … … 267 277 268 278 //update count 269 self::set_state( 'count', self::get_state('count') + count($data['rows']));279 self::set_state('count', self::get_state('count') + count($data['rows'])); 270 280 271 281 //update offset … … 273 283 self::set_state('query_arg', $query_arg); 274 284 275 delete_transient('wooms_walker_lock'); 285 276 286 277 287 self::add_schedule_hook(true); 278 288 289 do_action('wooms_products_batch_end'); 290 279 291 } catch (\Exception $e) { 280 delete_transient('wooms_walker_lock');281 292 282 293 /** … … 383 394 public static function add_schedule_hook($force = false) 384 395 { 385 if (self::walker_is_waiting()){396 if (self::is_wait()) { 386 397 return; 387 398 } 388 399 389 if (as_next_scheduled_action(self::$walker_hook_name , null, 'WooMS') && !$force) {400 if (as_next_scheduled_action(self::$walker_hook_name) && !$force) { 390 401 return; 391 402 } 392 403 393 if ($force){404 if ($force) { 394 405 self::set_state('force', 1); 395 406 } 396 407 397 as_schedule_single_action( time() + 11, self::$walker_hook_name, self::get_state(), 'WooMS');408 as_schedule_single_action(time() + 11, self::$walker_hook_name, self::get_state(), 'WooMS'); 398 409 } 399 410 … … 401 412 * Проверяем стоит ли обработчик на паузе? 402 413 */ 403 public static function walker_is_waiting()414 public static function is_wait() 404 415 { 405 416 //reset state if lock deleted and isset state 406 if ( empty(get_transient('wooms_end_timestamp')) and ! empty(self::get_state('end_timestamp')) ){417 if (empty(get_transient('wooms_end_timestamp')) and !empty(self::get_state('end_timestamp'))) { 407 418 delete_transient(self::$state_transient_key); 408 419 } 409 420 410 if (self::get_state('end_timestamp')){421 if (self::get_state('end_timestamp')) { 411 422 return true; 412 423 } 413 424 414 //the lock stands if the handler is currently running415 if(get_transient('wooms_walker_lock')){416 return true;417 }418 425 419 426 return false; … … 428 435 $timestamp = date("YmdHis"); 429 436 update_option('wooms_session_id', $timestamp, 'no'); //set id session sync 437 438 self::set_state('timestamp', date("YmdHis")); 439 self::set_state('end_timestamp', 0); 440 self::set_state('count', 0); 441 442 delete_transient('wooms_end_timestamp'); 430 443 431 444 do_action('wooms_main_walker_started'); … … 454 467 do_action('wooms_recount_terms'); 455 468 456 /** 457 * deprecated 458 */ 459 do_action('wooms_walker_finish'); 469 as_unschedule_all_actions(self::$walker_hook_name); 460 470 461 471 do_action( … … 473 483 public static function start_manually() 474 484 { 475 476 self::set_state('timestamp', 0);477 485 delete_transient(self::$state_transient_key); 486 487 delete_transient('wooms_end_timestamp'); 488 489 do_action('wooms_products_sync_manual_start'); 490 478 491 self::batch_handler(); 479 480 delete_transient('wooms_end_timestamp');481 482 do_action('wooms_products_sync_manual_start');483 492 484 493 wp_redirect(admin_url('admin.php?page=moysklad')); … … 506 515 $strings = []; 507 516 508 if (as_next_scheduled_action(self::$walker_hook_name , null, 'WooMS')) {517 if (as_next_scheduled_action(self::$walker_hook_name)) { 509 518 $strings[] = sprintf('<strong>Статус:</strong> %s', 'Выполняется очередями в фоне'); 510 519 } 511 520 512 if ($end_timestamp = self::get_state('end_timestamp')){521 if ($end_timestamp = self::get_state('end_timestamp')) { 513 522 $strings[] = sprintf('Последняя успешная синхронизация (отметка времени UTC): %s', $end_timestamp); 514 523 } 515 524 525 $strings[] = sprintf('Количество обработанных записей: %s', empty(self::get_state('count')) ? 0 : self::get_state('count')); 526 527 if ($session = get_option('wooms_session_id')) { 528 $strings[] = sprintf('Сессия (номер/дата): %s', $session); 529 } else { 530 $strings[] = sprintf('Сессия (номер/дата): %s', 'отсутствует'); 531 } 532 516 533 $strings[] = sprintf('Очередь задач: <a href="%s">открыть</a>', admin_url('admin.php?page=wc-status&tab=action-scheduler&s=wooms_products_walker_batch&orderby=schedule&order=desc')); 517 518 if (defined('WC_LOG_HANDLER') && 'WC_Log_Handler_DB' == WC_LOG_HANDLER){534 535 if (defined('WC_LOG_HANDLER') && 'WC_Log_Handler_DB' == WC_LOG_HANDLER) { 519 536 $strings[] = sprintf('Журнал обработки: <a href="%s">открыть</a>', admin_url('admin.php?page=wc-status&tab=logs&source=WooMS-ProductsWalker')); 520 537 } else { … … 522 539 } 523 540 524 $strings[] = sprintf('Количество обработанных записей: %s', empty(self::get_state('count')) ? 0 : self::get_state('count') );525 526 if($session = get_option('wooms_session_id')){527 $strings[] = sprintf('Сессия (номер/дата): %s', $session);528 } else {529 $strings[] = sprintf('Сессия (номер/дата): %s', 'отсутствует');530 }531 532 541 $strings = apply_filters('wooms_main_walker_info_string', $strings); 533 542 534 ?>543 ?> 535 544 <div class="wrap"> 536 545 <div id="message" class="notice notice-warning"> 537 <?php 538 539 foreach ($strings as $string){546 <?php 547 548 foreach ($strings as $string) { 540 549 printf('<p>%s</p>', $string); 541 } 542 543 do_action('wooms_products_state_before'); 550 } 551 552 do_action('wooms_products_state_before'); 544 553 545 554 ?> 546 555 </div> 547 556 </div> 548 <?php557 <?php 549 558 } 550 559 … … 557 566 printf('<h2>%s</h2>', 'Продукты (Товары)'); 558 567 559 if (as_next_scheduled_action(self::$walker_hook_name , null, 'WooMS')) {568 if (as_next_scheduled_action(self::$walker_hook_name)) { 560 569 printf('<a href="%s" class="button button-secondary">Остановить синхронизацию</a>', add_query_arg('a', 'wooms_products_stop_import', admin_url('admin.php?page=moysklad'))); 561 570 } else { 562 571 563 572 printf( 564 "<p>%s</p>", 573 "<p>%s</p>", 565 574 'Нажмите на кнопку ниже, чтобы запустить синхронизацию данных о продуктах вручную' 566 575 ); 567 576 568 577 printf( 569 '<a href="%s" class="button button-primary">Запустить синхронизацию продуктов вручную</a>', 578 '<a href="%s" class="button button-primary">Запустить синхронизацию продуктов вручную</a>', 570 579 add_query_arg('a', 'wooms_products_start_import', admin_url('admin.php?page=moysklad')) 571 580 ); … … 573 582 574 583 do_action('wooms_products_display_state'); 575 576 584 } 577 585 … … 582 590 public static function get_state($key = '') 583 591 { 584 if ( ! $state = get_transient(self::$state_transient_key)){592 if (!$state = get_transient(self::$state_transient_key)) { 585 593 $state = []; 586 594 set_transient(self::$state_transient_key, $state); 587 595 } 588 596 589 if (empty($key)){597 if (empty($key)) { 590 598 return $state; 591 599 } 592 600 593 if (empty($state[$key])){601 if (empty($state[$key])) { 594 602 return null; 595 603 } 596 604 597 605 return $state[$key]; 598 599 606 } 600 607 … … 603 610 * set state data 604 611 */ 605 public static function set_state($key, $value){ 606 607 if( ! $state = get_transient(self::$state_transient_key)){ 612 public static function set_state($key, $value) 613 { 614 615 if (!$state = get_transient(self::$state_transient_key)) { 608 616 $state = []; 609 617 } 610 618 611 if (is_array($state)){619 if (is_array($state)) { 612 620 $state[$key] = $value; 613 621 } else { -
wooms/trunk/readme.txt
r2290417 r2311211 82 82 83 83 == Changelog == 84 85 = 7.2 = 86 * Внимание! Большая часть обработчиков переведена на версию 1.2 REST API MoySklad и обновляться нужно осторожно и только обе версии сразу иначе могут быть проблемы https://github.com/wpcraft-ru/wooms/issues/296 87 * Изображения продукта для вариаций https://github.com/wpcraft-ru/wooms/issues/192 88 * Выбор нескольких групп для синхронизации https://github.com/wpcraft-ru/wooms/issues/297 89 * Кастомные статусы Заказов плохо передаются https://github.com/wpcraft-ru/wooms/issues/292 90 * Добавлена механика проверки данных по заказам отправленных в МойСклад https://github.com/wpcraft-ru/wooms/issues/290 91 * Разницы во времени создания заказа при синхронизации магазина и моего склада https://github.com/wpcraft-ru/wooms/issues/285 92 * Опция "Отправлять выбранный склад в Заказе" - улучшить инструкцию https://github.com/wpcraft-ru/wooms/issues/284 93 * Синхронизация заказов при каждом сохранении без опции https://github.com/wpcraft-ru/wooms/issues/289 84 94 85 95 = 7.1 = -
wooms/trunk/wooms.php
r2290417 r2311211 1 1 <?php 2 3 2 /** 4 3 * Plugin Name: WooMS … … 18 17 * License: GPLv2 or later 19 18 * License URI: http://www.gnu.org/licenses/gpl-2.0.html 20 * Version: 7. 121 * WooMS XT Latest: 7. 119 * Version: 7.2 20 * WooMS XT Latest: 7.2 22 21 */ 23 22 … … 53 52 require_once __DIR__ . '/inc/Logger.php'; 54 53 require_once __DIR__ . '/functions.php'; 54 require_once __DIR__ . '/inc/MSImagesTrait.php'; 55 55 56 56 /** … … 65 65 }); 66 66 67 68 require_once __DIR__ . '/migrations/7-2.php'; 69 70 67 71 add_action('plugins_loaded', [__CLASS__, 'true_load_plugin_textdomain']); 68 72 … … 72 76 73 77 add_action('plugins_loaded', function () { 78 79 80 //tmp solution for check https://github.com/wpcraft-ru/wooms/issues/296 81 if(get_option('wooms_db_version_check_7_2', 0)){ 82 return; 83 } 74 84 75 85 /** … … 84 94 require_once __DIR__ . '/inc/ProductsHiding.php'; 85 95 86 require_once __DIR__ . '/inc/MSImagesTrait.php';87 96 require_once __DIR__ . '/inc/ProductGallery.php'; 88 97 require_once __DIR__ . '/inc/ProductImage.php'; … … 90 99 require_once __DIR__ . '/inc/SiteHealthDebugSection.php'; 91 100 92 93 94 101 add_action('admin_notices', array(__CLASS__, 'show_notices_35')); 95 102 add_action('admin_notices', array(__CLASS__, 'show_error_notice')); … … 102 109 add_action('init', [__CLASS__, 'delete_old_schedules']); 103 110 } 111 104 112 105 113 /**
Note: See TracChangeset
for help on using the changeset viewer.