Plugin Directory

Changeset 2311211


Ignore:
Timestamp:
05/24/2020 08:05:01 PM (6 years ago)
Author:
casepress
Message:

7.2 update

Location:
wooms/trunk
Files:
2 added
8 edited

Legend:

Unmodified
Added
Removed
  • wooms/trunk/README.md

    r2260121 r2311211  
    11# WooMS - WooCommerce и МойСклад (интеграция, синхронизация, выгрузка, загрузка)
     2
     3## Вопросы и ответы
     4
     5https://github.com/wpcraft-ru/wooms/issues?q=label%3Aqa
    26
    37## Особенности
  • wooms/trunk/functions.php

    r2290417 r2311211  
    3434      'redirection' => 5,
    3535      'headers'     => array(
    36         "Content-Type"  => 'application/json',
     36        "Content-Type"  => 'application/json;charset=utf-8',
    3737        'Authorization' => 'Basic ' .
    3838                           base64_encode( get_option( 'woomss_login' ) . ':' . get_option( 'woomss_pass' ) ),
     
    4040      'body'        => $data,
    4141    );
    42  
     42
    4343    $request = wp_remote_request( $url, $args);
    4444    if ( is_wp_error( $request ) ) {
     
    4646        'wooms_logger_error',
    4747        $type = 'WooMS-Request',
    48         $title = 'Ошибка REST API',
     48        $title = 'Ошибка REST API WP Error',
    4949        $desc = $request->get_error_message()
    5050      );
     
    7070          'wooms_logger_error',
    7171          $type = 'WooMS-Request',
    72           $title = $error['error']
     72          $title = $url,
     73          $response
    7374        );
    7475      }
  • wooms/trunk/inc/ProductGallery.php

    r2290417 r2311211  
    1717
    1818  /**
    19    * WooMS_Import_Product_Images constructor.
     19   * the init
    2020   */
    2121  public static function init()
    2222  {
    2323
     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
    2436    add_action('gallery_images_download_schedule', [__CLASS__, 'download_images_from_metafield']);
    2537
     
    3042    add_action('init', [__CLASS__, 'add_schedule_hook']);
    3143
     44    add_action('wooms_main_walker_finish', [__CLASS__, 'restart']);
    3245
    3346    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');
    3556  }
    3657
     
    3960   * check disable option
    4061   */
    41   public static function is_disable(){
     62  public static function is_disable()
     63  {
    4264    if (empty(get_option('woomss_gallery_sync_enabled'))) {
    4365      return true;
     
    4769  }
    4870
     71
    4972  /**
    5073   * render_state_info
    5174   */
    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()) {
    5578      return;
    5679    }
     
    5881    $strings = [];
    5982
    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', 'в ожидании новых задач');
    6487    }
    6588
    6689    $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'));
    6790
    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) {
    6992      $strings[] = sprintf('Журнал обработки: <a href="%s">открыть</a>', admin_url('admin.php?page=wc-status&tab=logs&source=WooMS-ProductGallery'));
    7093    } else {
     
    7295    }
    7396
    74     ?>
     97?>
    7598    <hr>
    7699    <div>
     
    79102      <ul>
    80103        <li>
    81         <?php
    82         echo implode('</li><li>', $strings);
    83         ?>
     104          <?php
     105          echo implode('</li><li>', $strings);
     106          ?>
    84107        </li>
    85108      </ul>
    86109    </div>
    87   <?php
    88 
    89 
    90   }
     110<?php
     111  }
     112
    91113
    92114  /**
    93115   * update_product
    94116   */
    95   public static function update_product($product, $value, $data)
     117  public static function update_product($product, $data_api, $data)
    96118  {
    97119
     
    99121      return $product;
    100122    }
    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
    104137
    105138    return $product;
    106139  }
    107140
    108   public static function get_gallery_from_api($product_id)
    109   {
    110     // Getting data from mysklad product directly using id of product
    111     $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 image
    116     if (empty($data_api['rows']) || count($data_api['rows']) == 1) {
    117       return false;
    118     }
    119 
    120     // Making array with image data
    121     $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/4
    125       if ($key !== 0) {
    126         $product_gallery_data[$image['filename']] = $image['meta']['downloadHref'];
    127       }
    128     }
    129 
    130     // encoding array to json
    131     $product_gallery_data = json_encode($product_gallery_data);
    132 
    133     // check current meta is set already or not
    134     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   }
    140141
    141142  /**
     
    152153    }
    153154
    154     if(self::is_wait()){
     155    if (self::is_wait()) {
    155156      as_unschedule_all_actions(self::$walker_hook_name);
    156157      return;
     
    162163
    163164    // 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  {
    198174    if (get_transient('gallery_images_downloaded')) {
    199       return false;
    200     }
    201 
    202     return true;
    203   }
    204 
    205 
    206   /**
    207    * check new task for walker
    208    */
    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 download
    226     if (empty($list)) {
    227175      return true;
    228176    }
     
    230178    return false;
    231179  }
     180
    232181
    233182  /**
     
    266215
    267216      // Adding the option that all images downloaded and the sync is over
    268       set_transient('gallery_images_downloaded', true);
     217      set_transient('gallery_images_downloaded', time());
    269218
    270219      do_action(
     
    277226    }
    278227
    279     $result = [];
    280 
    281228    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
    291234
    292235  /**
     
    298241  public static function download_images_by_id($product_id, $all = false)
    299242  {
    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    }
    308252
    309253    $media_data_list = [];
    310254
    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;
    315262      }
    316 
    317       $media_id = self::uploadRemoteImageAndAttach($url, $product_id, $image_name);
    318263
    319264      if (!empty($media_id)) {
     
    327272      update_post_meta($product_id, '_product_image_gallery', implode(',', $media_data_list));
    328273
    329       // Delete meta for correct query work
    330       delete_post_meta($product_id, 'wooms_data_for_get_gallery');
    331 
    332274      do_action(
    333275        'wooms_logger',
    334276        __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'])
    336278      );
    337279    } else {
  • wooms/trunk/inc/ProductImage.php

    r2290417 r2311211  
    2222    public static function init()
    2323    {
     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
    2444        /**
    2545         * Обновление данных о продукте
     
    2949        add_action('admin_init', [__CLASS__, 'settings_init'], 50);
    3050
    31         add_action('init', [__CLASS__, 'add_schedule_hook']);
    32 
    33         add_action('wooms_product_image_sync', [__CLASS__, 'download_images_from_metafield']);
    3451
    3552        add_action('woomss_tool_actions_btns', [__CLASS__, 'ui_for_manual_start'], 15);
    3653        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    }
    4361
    4462
     
    4866    public static function update_product($product, $value, $data)
    4967    {
    50         if ( ! self::is_enable() ) {
     68        if (!self::is_enable()) {
    5169            return $product;
    5270        }
     
    5573
    5674        //Check image
    57         if (empty($value['image']['meta']['href'])) {
     75        if (empty($value['images']['meta']['size'])) {
    5876            return $product;
    5977        } else {
    60             $url = $value['image']['meta']['href'];
     78            $url = $value['images']['meta']['href'];
    6179        }
    6280
     
    6684        } else {
    6785            $product->update_meta_data('wooms_url_for_get_thumbnail', $url);
    68             $product->update_meta_data('wooms_image_data', $value['image']);
    6986        }
    7087
     
    7794    public static function add_schedule_hook($force = false)
    7895    {
    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');
    93109    }
    94110
     
    98114    public static function ui_action()
    99115    {
    100         $data = self::download_images_from_metafield();
     116        $data = self::batch_handler();
    101117
    102118        echo '<hr>';
     
    118134     * checking the option activation
    119135     */
    120     public static function is_enable(){
     136    public static function is_enable()
     137    {
    121138        if (empty(get_option('woomss_images_sync_enabled'))) {
    122139            return false;
     
    126143    }
    127144
    128    
     145
    129146    /**
    130147     * checking the pause state
    131148     */
    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        }
    134167
    135168        $args = array(
     
    150183
    151184        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());
    186187
    187188            do_action(
     
    191192            );
    192193
    193 
    194194            return false;
    195195        }
     
    198198
    199199        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)) {
    213201                $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                 );
    226202            }
     203
     204            delete_post_meta($value->ID, 'wooms_url_for_get_thumbnail');
    227205        }
    228206
     
    235213        }
    236214    }
     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
    237261
    238262    /**
     
    255279    public static function ui_for_manual_start()
    256280    {
    257         if ( ! self::is_enable()) {
    258             return;
    259         } 
    260        
     281        if (!self::is_enable()) {
     282            return;
     283        }
     284
    261285        $strings = [];
    262286
    263         if (as_next_scheduled_action(self::$walker_hook_name, null, 'WooMS') ) {
     287        if (as_next_scheduled_action(self::$walker_hook_name)) {
    264288            $strings[] = sprintf('<strong>Статус:</strong> %s', 'Выполняется очередями в фоне');
    265         } else{
     289        } else {
    266290            $strings[] = sprintf('<strong>Статус:</strong> %s', 'в ожидании новых задач');
    267291        }
    268292
    269293        $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?>
    278302
    279303        <h2>Изображения</h2>
     
    285309        ?>
    286310        <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>
    297322        </div>
    298         </div>
    299         <?php
     323<?php
    300324    }
    301325
  • wooms/trunk/inc/ProductsPrices.php

    r2250855 r2311211  
    11<?php
     2
    23namespace WooMS;
    34
    4 if ( ! defined( 'ABSPATH' ) ) {
     5if (!defined('ABSPATH')) {
    56    exit; // Exit if accessed directly
    67}
     
    910 * Select specific price is setup
    1011 */
    11 class ProductsPrices {
     12class ProductsPrices
     13{
    1214
    13   /**
    14    * The init
    15    */
    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);
    2325    }
    2426
     
    2729     * Check specifiec price and replace if isset price
    2830     */
    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');
    3034
    31         $price_name = get_option( 'wooms_price_id' );
    32         if ( empty( $price_name ) ) {
     35        if (empty($price_name)) {
    3336            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 price
    52      * Return 0 or value price
    53      */
    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;
    5937        }
    6038
    6139        $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"];
    6544            }
    6645        }
    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;
    7258    }
     59
    7360
    7461    /**
    7562     * Add settings
    7663     */
    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        );
    8674    }
    8775
    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    {
    9281        $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)));
    9483        echo '<p><small>Укажите наименование цены, если нужно выбрать специальный тип цен. Система будет проверять такой тип цены и если он указан то будет подставлять его вместо базового.</small></p>';
    9584    }
  • wooms/trunk/inc/ProductsWalker.php

    r2290417 r2311211  
    99/**
    1010 * Product Import Walker
    11  * do_action('wooms_product_import_row', $value, $key, $data);
    1211 */
    1312class ProductsWalker
    1413{
    1514
    16  
     15
    1716  public static $state_transient_key = 'wooms_products_walker_state';
    1817
    1918  public static $walker_hook_name = 'wooms_products_walker_batch';
    20  
     19
    2120
    2221  /**
     
    2524  public static function init()
    2625  {
     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
    2741    add_action('init', [__CLASS__, 'add_schedule_hook']);
    2842
     
    4256    //Other
    4357    add_action('add_meta_boxes', [__CLASS__, 'add_meta_boxes_post_type']);
    44    
    4558  }
    4659
     
    104117
    105118    //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));
    107120
    108121    $product_id = $product->save();
     
    161174    //Price Retail 'salePrices'
    162175    if (isset($data_of_source['salePrices'][0]['value'])) {
     176
     177
    163178      $price_source = floatval($data_of_source['salePrices'][0]['value']);
    164179      $price        = apply_filters('wooms_product_price', $price_source, $data_api, $product_id);
    165180
    166       $price = $price / 100;
     181
     182      $price = floatval($price) / 100;
    167183
    168184      $product->set_price($price);
     
    170186    }
    171187
    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    }
    177194
    178195    return $product;
     
    185202  public static function batch_handler($state = [])
    186203  {
    187     if(self::walker_is_waiting()){
    188       return;
    189     }
    190 
    191     //the lock stands if the handler is currently running
    192     set_transient('wooms_walker_lock', 1, 60);
    193 
    194     $count = apply_filters('wooms_iteration_size', 10);
    195204    $state = self::get_state();
    196205
    197206    //state reset for new session
    198     if(empty($state['timestamp'])){
     207    if (empty($state['timestamp'])) {
    199208
    200209      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');
    207210
    208211      $query_arg_default = [
    209212        'offset' => 0,
    210         'limit'  => $count,
    211         'scope'  => 'product',
     213        'limit'  => apply_filters('wooms_iteration_size', 20),
    212214      ];
    213215
     
    217219    $query_arg = self::get_state('query_arg');
    218220
    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';
    220225
    221226    $url = add_query_arg($query_arg, $url);
     
    223228    $url = apply_filters('wooms_url_get_products', $url);
    224229
     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
    225241    try {
    226242
    227      
    228243      $data = wooms_request($url);
     244      // dd($data);
    229245
    230246      do_action('wooms_logger', __CLASS__, sprintf('Отправлен запрос %s', $url));
     
    233249      if (isset($data['rows']) && empty($data['rows'])) {
    234250        self::walker_finish();
    235         delete_transient('wooms_walker_lock');
    236251        return;
    237252      }
    238253
    239254      do_action('wooms_walker_start_iteration', $data);
    240 
    241       /**
    242        * @TODO: deprecated. remove after tests
    243        */
    244       do_action('wooms_walker_start');
    245255
    246256      foreach ($data['rows'] as $key => $value) {
     
    267277
    268278      //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']));
    270280
    271281      //update offset
     
    273283      self::set_state('query_arg', $query_arg);
    274284
    275       delete_transient('wooms_walker_lock');
     285
    276286
    277287      self::add_schedule_hook(true);
    278288
     289      do_action('wooms_products_batch_end');
     290
    279291    } catch (\Exception $e) {
    280       delete_transient('wooms_walker_lock');
    281292
    282293      /**
     
    383394  public static function add_schedule_hook($force = false)
    384395  {
    385     if(self::walker_is_waiting()){
     396    if (self::is_wait()) {
    386397      return;
    387398    }
    388399
    389     if (as_next_scheduled_action(self::$walker_hook_name, null, 'WooMS') && ! $force) {
     400    if (as_next_scheduled_action(self::$walker_hook_name) && !$force) {
    390401      return;
    391402    }
    392403
    393     if($force){
     404    if ($force) {
    394405      self::set_state('force', 1);
    395406    }
    396407
    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');
    398409  }
    399410
     
    401412   * Проверяем стоит ли обработчик на паузе?
    402413   */
    403   public static function walker_is_waiting()
     414  public static function is_wait()
    404415  {
    405416    //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'))) {
    407418      delete_transient(self::$state_transient_key);
    408419    }
    409420
    410     if(self::get_state('end_timestamp')){
     421    if (self::get_state('end_timestamp')) {
    411422      return true;
    412423    }
    413424
    414     //the lock stands if the handler is currently running
    415     if(get_transient('wooms_walker_lock')){
    416       return true;
    417     }
    418425
    419426    return false;
     
    428435    $timestamp = date("YmdHis");
    429436    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');
    430443
    431444    do_action('wooms_main_walker_started');
     
    454467    do_action('wooms_recount_terms');
    455468
    456     /**
    457      * deprecated
    458      */
    459     do_action('wooms_walker_finish');
     469    as_unschedule_all_actions(self::$walker_hook_name);
    460470
    461471    do_action(
     
    473483  public static function start_manually()
    474484  {
    475 
    476     self::set_state('timestamp', 0);
    477485    delete_transient(self::$state_transient_key);
     486
     487    delete_transient('wooms_end_timestamp');
     488
     489    do_action('wooms_products_sync_manual_start');
     490
    478491    self::batch_handler();
    479 
    480     delete_transient('wooms_end_timestamp');
    481 
    482     do_action('wooms_products_sync_manual_start');
    483492
    484493    wp_redirect(admin_url('admin.php?page=moysklad'));
     
    506515    $strings = [];
    507516
    508     if (as_next_scheduled_action(self::$walker_hook_name, null, 'WooMS') ) {
     517    if (as_next_scheduled_action(self::$walker_hook_name)) {
    509518      $strings[] = sprintf('<strong>Статус:</strong> %s', 'Выполняется очередями в фоне');
    510519    }
    511520
    512     if($end_timestamp = self::get_state('end_timestamp')){
     521    if ($end_timestamp = self::get_state('end_timestamp')) {
    513522      $strings[] = sprintf('Последняя успешная синхронизация (отметка времени UTC): %s', $end_timestamp);
    514523    }
    515524
     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
    516533    $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) {
    519536      $strings[] = sprintf('Журнал обработки: <a href="%s">открыть</a>', admin_url('admin.php?page=wc-status&tab=logs&source=WooMS-ProductsWalker'));
    520537    } else {
     
    522539    }
    523540
    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 
    532541    $strings = apply_filters('wooms_main_walker_info_string', $strings);
    533542
    534     ?>
     543?>
    535544    <div class="wrap">
    536545      <div id="message" class="notice notice-warning">
    537         <?php 
    538 
    539         foreach($strings as $string){
     546        <?php
     547
     548        foreach ($strings as $string) {
    540549          printf('<p>%s</p>', $string);
    541         } 
    542        
    543         do_action('wooms_products_state_before'); 
     550        }
     551
     552        do_action('wooms_products_state_before');
    544553
    545554        ?>
    546555      </div>
    547556    </div>
    548     <?php
     557<?php
    549558  }
    550559
     
    557566    printf('<h2>%s</h2>', 'Продукты (Товары)');
    558567
    559     if (as_next_scheduled_action(self::$walker_hook_name, null, 'WooMS') ) {
     568    if (as_next_scheduled_action(self::$walker_hook_name)) {
    560569      printf('<a href="%s" class="button button-secondary">Остановить синхронизацию</a>', add_query_arg('a', 'wooms_products_stop_import', admin_url('admin.php?page=moysklad')));
    561570    } else {
    562      
     571
    563572      printf(
    564         "<p>%s</p>", 
     573        "<p>%s</p>",
    565574        'Нажмите на кнопку ниже, чтобы запустить синхронизацию данных о продуктах вручную'
    566575      );
    567576
    568577      printf(
    569         '<a href="%s" class="button button-primary">Запустить синхронизацию продуктов вручную</a>', 
     578        '<a href="%s" class="button button-primary">Запустить синхронизацию продуктов вручную</a>',
    570579        add_query_arg('a', 'wooms_products_start_import', admin_url('admin.php?page=moysklad'))
    571580      );
     
    573582
    574583    do_action('wooms_products_display_state');
    575 
    576584  }
    577585
     
    582590  public static function get_state($key = '')
    583591  {
    584     if( ! $state = get_transient(self::$state_transient_key)){
     592    if (!$state = get_transient(self::$state_transient_key)) {
    585593      $state = [];
    586594      set_transient(self::$state_transient_key, $state);
    587595    }
    588596
    589     if(empty($key)){
     597    if (empty($key)) {
    590598      return $state;
    591599    }
    592600
    593     if(empty($state[$key])){
     601    if (empty($state[$key])) {
    594602      return null;
    595603    }
    596604
    597605    return $state[$key];
    598    
    599606  }
    600607
     
    603610   * set state data
    604611   */
    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)) {
    608616      $state = [];
    609617    }
    610618
    611     if(is_array($state)){
     619    if (is_array($state)) {
    612620      $state[$key] = $value;
    613621    } else {
  • wooms/trunk/readme.txt

    r2290417 r2311211  
    8282
    8383== 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
    8494
    8595= 7.1 =
  • wooms/trunk/wooms.php

    r2290417 r2311211  
    11<?php
    2 
    32/**
    43 * Plugin Name: WooMS
     
    1817 * License: GPLv2 or later
    1918 * License URI: http://www.gnu.org/licenses/gpl-2.0.html
    20  * Version: 7.1
    21  * WooMS XT Latest: 7.1
     19 * Version: 7.2
     20 * WooMS XT Latest: 7.2
    2221 */
    2322
     
    5352    require_once __DIR__ . '/inc/Logger.php';
    5453    require_once __DIR__ . '/functions.php';
     54    require_once __DIR__ . '/inc/MSImagesTrait.php';
    5555
    5656    /**
     
    6565    });
    6666
     67
     68    require_once __DIR__ . '/migrations/7-2.php';
     69
     70
    6771    add_action('plugins_loaded', [__CLASS__, 'true_load_plugin_textdomain']);
    6872
     
    7276
    7377    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      }
    7484
    7585      /**
     
    8494      require_once __DIR__ . '/inc/ProductsHiding.php';
    8595
    86       require_once __DIR__ . '/inc/MSImagesTrait.php';
    8796      require_once __DIR__ . '/inc/ProductGallery.php';
    8897      require_once __DIR__ . '/inc/ProductImage.php';
     
    9099      require_once __DIR__ . '/inc/SiteHealthDebugSection.php';
    91100
    92 
    93      
    94101      add_action('admin_notices', array(__CLASS__, 'show_notices_35'));
    95102      add_action('admin_notices', array(__CLASS__, 'show_error_notice'));
     
    102109    add_action('init', [__CLASS__, 'delete_old_schedules']);
    103110  }
     111
    104112
    105113  /**
Note: See TracChangeset for help on using the changeset viewer.