Plugin Directory

Changeset 2984550


Ignore:
Timestamp:
10/26/2023 05:35:06 PM (2 years ago)
Author:
casepress
Message:

Update to version 9.5 from GitHub

Location:
wooms
Files:
14 edited
1 copied

Legend:

Unmodified
Added
Removed
  • wooms/tags/9.5/includes/Orders.php

    r2981815 r2984550  
    4949        add_filter('wooms_order_data', [__CLASS__, 'add_currency'], 11, 3);
    5050        add_filter('wooms_order_data', [__CLASS__, 'add_positions'], 11, 3);
    51         // add_filter('wooms_order_send_data', [__CLASS__, 'add_positions'], 10, 3);
    5251        add_filter('wooms_order_data', [__CLASS__, 'add_moment'], 11, 3);
    5352        add_filter('wooms_order_data', [__CLASS__, 'add_client_as_agent'], 22, 3);
  • wooms/tags/9.5/includes/Products.php

    r2979725 r2984550  
    55use function WooMS\request;
    66use function Testeroid\ddcli;
    7 use Error, Throwable;
     7use Error, Throwable, WC_Product;
    88
    99defined( 'ABSPATH' ) || exit;
     
    302302/**
    303303 * to replace load_product
     304 *
     305 * @return WC_Product
    304306 */
    305307function product_update( array $row, array $data = [] ) {
  • wooms/tags/9.5/includes/ProductsCategories.php

    r2981815 r2984550  
    33namespace WooMS;
    44
    5 defined('ABSPATH') || exit;
     5use Error;
     6
     7defined( 'ABSPATH' ) || exit;
    68
    79/**
    810 * Import Product Categories from MoySklad
    911 */
    10 class ProductsCategories
    11 {
    12 
    13   /**
    14    * WooMS_Import_Product_Categories constructor.
    15    */
    16   public static function init()
    17   {
    18 
    19     add_filter('wooms_product_save', array(__CLASS__, 'product_save'), 10, 3);
    20     add_filter('wooms_product_save', array(__CLASS__, 'add_ancestors'), 15, 2);
    21 
    22     add_action('admin_init', array(__CLASS__, 'add_settings'), 50);
    23     add_action('product_cat_edit_form_fields', array(__CLASS__, 'display_data_category'), 30);
    24   }
    25 
    26   /**
    27    * add ancestors
    28    *
    29    * issue https://github.com/wpcraft-ru/wooms/issues/282
    30    */
    31   public static function add_ancestors($product, $data_api)
    32   {
    33     if (!get_option('wooms_categories_include_children')) {
    34       return $product;
    35     }
    36 
    37     if (empty($data_api['productFolder']['meta']['href'])) {
    38       return $product;
    39     }
    40 
    41     if (!$term_id = self::check_term_by_ms_uuid($data_api['productFolder']['meta']['href'])) {
    42       return $product;
    43     }
    44 
    45     // $product = wc_get_product($product);
    46 
    47     $term_ancestors = get_ancestors($term_id, 'product_cat', 'taxonomy');
    48 
    49     $term_ancestors[] = $term_id;
    50     $product->set_category_ids($term_ancestors);
    51 
    52     return $product;
    53   }
    54 
    55   /**
    56    * Загрузка данных категории для продукта
    57    */
    58   public static function product_save($product, $value, $data)
    59   {
    60 
    61     //Если опция отключена - пропускаем обработку
    62     if (self::is_disable()) {
    63       return $product;
    64     }
    65 
    66     if (empty($value['productFolder']['meta']['href'])) {
    67       return $product;
    68     }
    69 
    70     $product_id = $product->get_id();
    71 
    72     $url = $value['productFolder']['meta']['href'];
    73 
    74     if ($term_id = self::update_category($url)) {
    75 
    76       $result = $product->set_category_ids(array($term_id));
    77 
    78       if (is_wp_error($result)) {
    79         do_action('wooms_logger_error', __CLASS__, $result->get_error_code(), $result->get_error_message());
    80       } elseif ($result === false) {
    81         do_action('wooms_logger_error', __CLASS__, 'Не удалось выбрать категорию', $term_id);
    82       } else {
    83         do_action(
    84           'wooms_logger',
    85           __CLASS__,
    86           sprintf('Выбор категории продукта %s (id %s)', $product->get_name(), $product->get_id()),
    87           [
    88             '$url' => $url,
    89             '$term_id' => $term_id,
    90             'term_name' => get_term_by('id', $term_id, 'product_cat')->name,
    91             '$product_id' => $product_id,
    92             'select_cat_pid' => $product_id,
    93           ]
    94         );
    95       }
    96     }
    97 
    98     return $product;
    99   }
    100 
    101   /**
    102    * If isset term return term_id, else return false
    103    */
    104   public static function check_term_by_ms_uuid($id)
    105   {
    106     //if uuid as url - get uuid only
    107     $id = str_replace('https://online.moysklad.ru/api/remap/1.2/entity/productfolder/', '', $id);
    108     $id = str_replace('https://api.moysklad.ru/api/remap/1.2/entity/productfolder/', '', $id);
    109 
    110     $terms = get_terms(array(
    111       'taxonomy'   => array('product_cat'),
    112       'hide_empty' => false,
    113       'meta_query' => array(
    114         array(
    115           'key'   => 'wooms_id',
    116           'value' => $id,
    117         ),
    118       ),
    119     ));
    120 
    121     if (is_wp_error($terms) or empty($terms)) {
    122       return false;
    123     } else {
    124       foreach ($terms as $term) {
    125         if (isset($term->term_id)) {
    126           return $term->term_id;
    127         } else {
    128           return false;
    129         }
    130       }
    131     }
    132   }
    133 
    134 
    135   /**
    136    * Create and update categories
    137    *
    138    * @param $url
    139    */
    140   public static function update_category($url)
    141   {
    142     /**
    143      * Если указана группа для синхронизации,
    144      * и совпадает с запрошенной, то вернуть false, чтобы прекратить рекурсию создания родителей
    145      */
    146     if ($url == get_option('woomss_include_categories_sync')) {
    147       return false;
    148     }
    149 
    150     $data = wooms_request($url);
    151 
    152     if(empty($data['id'])){
    153       return false;
    154     }
    155 
    156     if ($term_id = self::check_term_by_ms_uuid($data['id'])) {
    157 
    158       do_action('wooms_update_category', $term_id);
    159 
    160       $args_update = array();
    161       $url_parent = '';
    162 
    163       if (isset($data['productFolder']['meta']['href'])) {
    164         $url_parent = $data['productFolder']['meta']['href'];
    165         if ($term_id_parent = self::update_category($url_parent)) {
    166           $args_update['parent'] = isset($term_id_parent) ? intval($term_id_parent) : 0;
    167         }
    168       }
    169 
    170       if (apply_filters('wooms_skip_update_select_category', true, $url_parent)) {
    171         $args_update = apply_filters('wooms_update_category_args', $args_update, $term_id, $data);
    172         $term = wp_update_term($term_id, 'product_cat', $args_update);
    173       }
    174 
    175       wp_update_term_count($term_id, $taxonomy = 'product_cat');
    176 
    177       update_term_meta($term_id, 'wooms_updated_category', $data['updated']);
    178 
    179       if (is_array($term) && !empty($term["term_id"])) {
    180         return $term["term_id"];
    181       } else {
    182         return false;
    183       }
    184     } else {
    185 
    186       $args = array();
    187 
    188       $term_new = array(
    189         'wooms_id' => $data['id'],
    190         'name'     => $data['name'],
    191         'archived' => $data['archived'],
    192       );
    193 
    194       if (isset($data['productFolder']['meta']['href'])) {
    195         $url_parent = $data['productFolder']['meta']['href'];
    196         if ($term_id_parent = self::update_category($url_parent)) {
    197           $args['parent'] = intval($term_id_parent);
    198         }
    199       }
    200 
    201       $url_parent = isset($data['productFolder']['meta']['href']) ? $data['productFolder']['meta']['href'] : '';
    202       $path_name  = isset($data['pathName']) ? $data['pathName'] : null;
    203 
    204       if (apply_filters('wooms_skip_categories', true, $url_parent, $path_name)) {
    205 
    206         $term = wp_insert_term($term_new['name'], $taxonomy = 'product_cat', $args);
    207         if (is_wp_error($term)) {
    208 
    209           if (isset($term->error_data['term_exists'])) {
    210             $msg = $term->get_error_message();
    211             $msg .= PHP_EOL . sprintf('Имя указанное при создании термина: %s', $term_new['name']);
    212             $msg .= PHP_EOL . sprintf('Существующий термин: %s', $term->error_data['term_exists']);
    213             $msg .= PHP_EOL . sprintf('Аргументы создания термина: %s', print_r($args, true));
    214             $msg .= PHP_EOL . sprintf('URL API: %s', $url);
    215           } else {
    216             $msg = $term->get_error_message();
    217             $msg .= PHP_EOL . print_r($args, true);
    218           }
    219           do_action('wooms_logger_error', __CLASS__, $term->get_error_code(), $msg);
    220         } else {
    221           do_action(
    222             'wooms_logger',
    223             __CLASS__,
    224             sprintf('Добавлен термин %s', $term_new['name']),
    225             sprintf('Результат обработки %s', PHP_EOL . print_r($term, true))
    226           );
    227         }
    228       }
    229 
    230       if (isset($term->errors["term_exists"])) {
    231         $term_id = intval($term->error_data['term_exists']);
    232         if (empty($term_id)) {
    233           return false;
    234         }
    235       } elseif (isset($term->term_id)) {
    236         $term_id = $term->term_id;
    237       } elseif (is_array($term) && !empty($term["term_id"])) {
    238         $term_id = $term["term_id"];
    239       } else {
    240         return false;
    241       }
    242 
    243       update_term_meta($term_id, 'wooms_id', $term_new['wooms_id']);
    244 
    245       update_term_meta($term_id, 'wooms_updated_category', $data['updated']);
    246 
    247       if ($session_id = get_option('wooms_session_id')) {
    248         update_term_meta($term_id, 'wooms_session_id', $session_id);
    249       }
    250 
    251       do_action('wooms_add_category', $term, $url_parent, $path_name);
    252 
    253       return $term_id;
    254     }
    255   }
    256 
    257   /**
    258    * Meta box in category
    259    *
    260    * @since 2.1.2
    261    *
    262    * @param $term
    263    */
    264   public static function display_data_category($term)
    265   {
    266 
    267     $meta_data         = get_term_meta($term->term_id, 'wooms_id', true);
    268     $meta_data_updated = get_term_meta($term->term_id, 'wooms_updated_category', true);
    269 
    270 ?>
    271     <tr class="form-field term-meta-text-wrap">
    272       <td colspan="2" style="padding: 0;">
    273         <h3 style="margin: 0;">МойСклад</h3>
    274       </td>
    275     </tr>
    276     <?php
    277 
    278     if ($meta_data) : ?>
    279       <tr class="form-field term-meta-text-wrap">
    280         <th scope="row">
    281           <label for="term-meta-text">ID категории в МойСклад</label>
    282         </th>
    283         <td>
    284           <strong><?php echo $meta_data ?></strong>
    285         </td>
    286       </tr>
    287       <tr class="form-field term-meta-text-wrap">
    288         <th scope="row">
    289           <label for="term-meta-text">Ссылка на категорию</label>
    290         </th>
    291         <td>
    292           <a href="https://online.moysklad.ru/app/#good/edit?id=<?php echo $meta_data ?>" target="_blank">Посмотреть категорию в МойСклад</a>
    293         </td>
    294       </tr>
    295     <?php else : ?>
    296       <tr class="form-field term-meta-text-wrap">
    297         <th scope="row">
    298           <label for="term-meta-text">ID категории в МойСклад</label>
    299         </th>
    300         <td>
    301           <strong>Категория еще не синхронизирована</strong>
    302         </td>
    303       </tr>
    304     <?php endif;
    305 
    306     if ($meta_data_updated) : ?>
    307       <tr class="form-field term-meta-text-wrap">
    308         <th scope="row">
    309           <label for="term-meta-text">Дата последнего обновления в МойСклад</label>
    310         </th>
    311         <td>
    312           <strong><?php echo $meta_data_updated; ?></strong>
    313         </td>
    314       </tr>
    315 <?php
    316     endif;
    317   }
    318 
    319   /**
    320    * Settings UI
    321    */
    322   public static function add_settings()
    323   {
    324 
    325     add_settings_section('wooms_product_cat', 'Категории продуктов', __return_empty_string(), 'mss-settings');
    326 
    327     self::add_setting_categories_sync_enabled();
    328     self::add_setting_include_children();
    329   }
    330 
    331   /**
    332    * add_setting_include_children
    333    *
    334    * issue https://github.com/wpcraft-ru/wooms/issues/282
    335    */
    336   public static function add_setting_include_children()
    337   {
    338     $option_name = 'wooms_categories_include_children';
    339 
    340     register_setting('mss-settings', $option_name);
    341     add_settings_field(
    342       $id = $option_name,
    343       $title = 'Выбор всех категорий в дереве',
    344       $callback = function ($args) {
    345         printf('<input type="checkbox" name="%s" value="1" %s />', $args['key'], checked(1, $args['value'], false));
    346         printf('<p>%s</p>', 'Опция позволяет указывать категории у продукта с учетом всего дерева - от верхнего предка, до всех потомков');
    347         printf('<p>Подробнее: <a href="%s" target="_blank">https://github.com/wpcraft-ru/wooms/issues/282</a></p>', 'https://github.com/wpcraft-ru/wooms/issues/282');
    348       },
    349       $page = 'mss-settings',
    350       $section = 'wooms_product_cat',
    351       $args = [
    352         'key' => $option_name,
    353         'value' => get_option($option_name)
    354       ]
    355     );
    356   }
    357 
    358   /**
    359    * is_disable
    360    */
    361   public static function is_disable()
    362   {
    363     if (get_option('woomss_categories_sync_enabled')) {
    364       return true;
    365     }
    366 
    367     return false;
    368   }
    369 
    370   /**
    371    * add_setting_categories_sync_enabled
    372    */
    373   public static function add_setting_categories_sync_enabled()
    374   {
    375 
    376     /**
    377      * TODO заменить woomss_categories_sync_enabled на wooms_categories_sync_disable
    378      */
    379     $option_name = 'woomss_categories_sync_enabled';
    380 
    381     register_setting('mss-settings', $option_name);
    382     add_settings_field(
    383       $id = $option_name,
    384       $title = 'Отключить синхронизацию категорий',
    385       $callback = function ($args) {
    386         printf('<input type="checkbox" name="%s" value="1" %s />', $args['key'], checked(1, $args['value'], false));
    387         printf('<small>%s</small>', 'Если включить опцию, то при обновлении продуктов категории не будут учтываться в соответствии с группами МойСклад.');
    388       },
    389       $page = 'mss-settings',
    390       $section = 'wooms_product_cat',
    391       $args = [
    392         'key' => $option_name,
    393         'value' => get_option($option_name)
    394       ]
    395     );
    396   }
     12class ProductsCategories {
     13
     14    public static function init() {
     15
     16        add_action( 'wooms_main_walker_started', array( __CLASS__, 'reset' ) );
     17
     18        add_filter( 'wooms_product_update', [ __CLASS__, 'update' ], 10, 3 );
     19        add_filter( 'wooms_product_update', [ __CLASS__, 'add_ancestors' ], 15, 3 );
     20
     21        add_action( 'admin_init', array( __CLASS__, 'add_settings' ), 50 );
     22        add_action( 'product_cat_edit_form_fields', array( __CLASS__, 'display_data_category' ), 30 );
     23    }
     24
     25
     26
     27    public static function update( $product, $row, $data ) {
     28        if ( self::is_disable() ) {
     29            return $product;
     30        }
     31
     32        $term_id = self::check_term_by_ms_uuid( $row['productFolder']['meta']['href'] );
     33
     34        if ( empty( $term_id ) ) {
     35            throw new Error( 'ProductsCategories - update - empty($term_id)' );
     36        }
     37
     38        $product->set_category_ids( array( $term_id ) );
     39
     40        return $product;
     41    }
     42
     43
     44
     45    /**
     46     * add ancestors
     47     *
     48     * issue https://github.com/wpcraft-ru/wooms/issues/282
     49     */
     50    public static function add_ancestors( \WC_Product $product, $row, $data ) {
     51        if ( ! get_option( 'wooms_categories_include_children' ) ) {
     52            return $product;
     53        }
     54
     55        if ( empty( $row['productFolder']['meta']['href'] ) ) {
     56            return $product;
     57        }
     58
     59        if ( ! $term_id = self::check_term_by_ms_uuid( $row['productFolder']['meta']['href'] ) ) {
     60            return $product;
     61        }
     62
     63        $term_ancestors = get_ancestors( $term_id, 'product_cat', 'taxonomy' );
     64
     65        $term_ancestors[] = $term_id;
     66        $product->set_category_ids( $term_ancestors );
     67
     68
     69        return $product;
     70    }
     71
     72
     73
     74    public static function product_categories_update( $productfolder ) {
     75
     76        if ( empty( $productfolder['rows'] ) ) {
     77            throw new Error( 'No categories for products', 500 );
     78        }
     79
     80
     81        if ( count( $productfolder['rows'] ) < 1 ) {
     82            throw new Error( 'No categories for products', 500 );
     83        }
     84
     85
     86        $list = [];
     87        foreach ( $productfolder['rows'] as $row ) {
     88            $list[] = self::product_category_update( $row, $productfolder );
     89        }
     90
     91        if ( empty( $list ) ) {
     92            throw new Error( 'product_category_update = empty $list[]' );
     93        }
     94
     95
     96        return $list;
     97
     98    }
     99
     100    public static function product_category_update( $row, $productfolder ) {
     101
     102        if ( empty( $row['id'] ) ) {
     103            // throw new Error( 'product_category_update = no $row[id]' );
     104        }
     105
     106        $term_id = self::check_term_by_ms_uuid( $row['id'] );
     107
     108        if ( $term_id ) {
     109
     110            update_term_meta( $term_id, 'wooms_updated_category', $row['updated'] );
     111
     112            $args = [];
     113
     114            if ( isset( $row['productFolder']['meta']['href'] ) ) {
     115                $url_parent = $row['productFolder']['meta']['href'];
     116                foreach ( $productfolder['rows'] as $parent_row ) {
     117                    if ( $parent_row['meta']['href'] == $url_parent ) {
     118                        $term_id_parent = self::product_category_update( $parent_row, $productfolder );
     119                        $args['parent'] = $term_id_parent;
     120                        break;
     121                    }
     122                }
     123            }
     124
     125            wp_update_term( $term_id, $taxonomy = 'product_cat', $args );
     126
     127            return $term_id;
     128        } else {
     129
     130            $args = array();
     131
     132            $term_new = array(
     133                'wooms_id' => $row['id'],
     134                'name' => $row['name'],
     135                'archived' => $row['archived'],
     136            );
     137
     138            if ( isset( $row['productFolder']['meta']['href'] ) ) {
     139                $url_parent = $row['productFolder']['meta']['href'];
     140                foreach ( $productfolder['rows'] as $parent_row ) {
     141                    if ( $parent_row['meta']['href'] == $url_parent ) {
     142                        $term_id_parent = self::product_category_update( $parent_row, $productfolder );
     143                        $args['parent'] = $term_id_parent;
     144                        break;
     145                    }
     146                }
     147            }
     148
     149            $url_parent = isset( $row['productFolder']['meta']['href'] ) ? $row['productFolder']['meta']['href'] : '';
     150            $path_name = isset( $row['pathName'] ) ? $row['pathName'] : null;
     151
     152            if ( apply_filters( 'wooms_skip_categories', true, $url_parent, $path_name ) ) {
     153
     154                $term = wp_insert_term( $term_new['name'], $taxonomy = 'product_cat', $args );
     155                if ( is_wp_error( $term ) ) {
     156
     157                    if ( isset( $term->error_data['term_exists'] ) ) {
     158                        $msg = $term->get_error_message();
     159                        $msg .= PHP_EOL . sprintf( 'Имя указанное при создании термина: %s', $term_new['name'] );
     160                        $msg .= PHP_EOL . sprintf( 'Существующий термин: %s', $term->error_data['term_exists'] );
     161                        $msg .= PHP_EOL . sprintf( 'Аргументы создания термина: %s', print_r( $args, true ) );
     162
     163                    } else {
     164                        $msg = $term->get_error_message();
     165                        $msg .= PHP_EOL . print_r( $args, true );
     166                    }
     167                    do_action( 'wooms_logger_error', __CLASS__, $term->get_error_code(), $msg );
     168                } else {
     169                    do_action(
     170                        'wooms_logger',
     171                        __CLASS__,
     172                        sprintf( 'Добавлен термин %s', $term_new['name'] ),
     173                        sprintf( 'Результат обработки %s', PHP_EOL . print_r( $term, true ) )
     174                    );
     175                }
     176            }
     177
     178            if ( isset( $term->errors["term_exists"] ) ) {
     179                $term_id = intval( $term->error_data['term_exists'] );
     180                if ( empty( $term_id ) ) {
     181                    return false;
     182                }
     183            } elseif ( isset( $term->term_id ) ) {
     184                $term_id = $term->term_id;
     185            } elseif ( is_array( $term ) && ! empty( $term["term_id"] ) ) {
     186                $term_id = $term["term_id"];
     187            } else {
     188                return false;
     189            }
     190
     191            update_term_meta( $term_id, 'wooms_id', $row['id'] );
     192
     193            update_term_meta( $term_id, 'wooms_updated_category', $row['updated'] );
     194
     195            if ( $session_id = get_option( 'wooms_session_id' ) ) {
     196                update_term_meta( $term_id, 'wooms_session_id', $session_id );
     197            }
     198
     199            do_action( 'wooms_add_category', $term, $url_parent, $path_name );
     200
     201            return $term_id;
     202        }
     203
     204    }
     205
     206
     207    public static function prepare( $data, $row ) {
     208
     209        return $data;
     210
     211    }
     212
     213
     214    public static function reset() {
     215        $productfolder = request( 'entity/productfolder' );
     216
     217        self::product_categories_update( $productfolder );
     218
     219    }
     220
     221
     222    /**
     223     * If isset term return term_id, else return false
     224     */
     225    public static function check_term_by_ms_uuid( $id ) {
     226
     227        //if uuid as url - get uuid only
     228        $id = str_replace( 'https://online.moysklad.ru/api/remap/1.2/entity/productfolder/', '', $id );
     229        $id = str_replace( 'https://api.moysklad.ru/api/remap/1.2/entity/productfolder/', '', $id );
     230
     231
     232        $terms = get_terms( array(
     233            'taxonomy' => array( 'product_cat' ),
     234            'hide_empty' => false,
     235            'meta_query' => array(
     236                array(
     237                    'key' => 'wooms_id',
     238                    'value' => $id,
     239                ),
     240            ),
     241        ) );
     242
     243        if ( empty( $terms[0] ) ) {
     244            return null;
     245        }
     246        return $terms[0]->term_id;
     247    }
     248
     249
     250    /**
     251     * Meta box in category
     252     *
     253     * @since 2.1.2
     254     *
     255     * @param $term
     256     */
     257    public static function display_data_category( $term ) {
     258
     259        $meta_data = get_term_meta( $term->term_id, 'wooms_id', true );
     260        $meta_data_updated = get_term_meta( $term->term_id, 'wooms_updated_category', true );
     261
     262        ?>
     263        <tr class="form-field term-meta-text-wrap">
     264            <td colspan="2" style="padding: 0;">
     265                <h3 style="margin: 0;">МойСклад</h3>
     266            </td>
     267        </tr>
     268        <?php
     269
     270        if ( $meta_data ) : ?>
     271            <tr class="form-field term-meta-text-wrap">
     272                <th scope="row">
     273                    <label for="term-meta-text">ID категории в МойСклад</label>
     274                </th>
     275                <td>
     276                    <strong>
     277                        <?php echo $meta_data ?>
     278                    </strong>
     279                </td>
     280            </tr>
     281            <tr class="form-field term-meta-text-wrap">
     282                <th scope="row">
     283                    <label for="term-meta-text">Ссылка на категорию</label>
     284                </th>
     285                <td>
     286                    <a href="https://online.moysklad.ru/app/#good/edit?id=<?php echo $meta_data ?>" target="_blank">Посмотреть
     287                        категорию в МойСклад</a>
     288                </td>
     289            </tr>
     290        <?php else : ?>
     291            <tr class="form-field term-meta-text-wrap">
     292                <th scope="row">
     293                    <label for="term-meta-text">ID категории в МойСклад</label>
     294                </th>
     295                <td>
     296                    <strong>Категория еще не синхронизирована</strong>
     297                </td>
     298            </tr>
     299        <?php endif;
     300
     301        if ( $meta_data_updated ) : ?>
     302            <tr class="form-field term-meta-text-wrap">
     303                <th scope="row">
     304                    <label for="term-meta-text">Дата последнего обновления в МойСклад</label>
     305                </th>
     306                <td>
     307                    <strong>
     308                        <?php echo $meta_data_updated; ?>
     309                    </strong>
     310                </td>
     311            </tr>
     312            <?php
     313        endif;
     314    }
     315
     316    /**
     317     * Settings UI
     318     */
     319    public static function add_settings() {
     320
     321        add_settings_section( 'wooms_product_cat', 'Категории продуктов', __return_empty_string(), 'mss-settings' );
     322
     323        self::add_setting_categories_sync_enabled();
     324        self::add_setting_include_children();
     325    }
     326
     327    /**
     328     * add_setting_include_children
     329     *
     330     * issue https://github.com/wpcraft-ru/wooms/issues/282
     331     */
     332    public static function add_setting_include_children() {
     333        $option_name = 'wooms_categories_include_children';
     334
     335        register_setting( 'mss-settings', $option_name );
     336        add_settings_field(
     337            $id = $option_name,
     338            $title = 'Выбор всех категорий в дереве',
     339            $callback = function ($args) {
     340                printf( '<input type="checkbox" name="%s" value="1" %s />', $args['key'], checked( 1, $args['value'], false ) );
     341                printf( '<p>%s</p>', 'Опция позволяет указывать категории у продукта с учетом всего дерева - от верхнего предка, до всех потомков' );
     342                printf( '<p>Подробнее: <a href="%s" target="_blank">https://github.com/wpcraft-ru/wooms/issues/282</a></p>', 'https://github.com/wpcraft-ru/wooms/issues/282' );
     343            },
     344            $page = 'mss-settings',
     345            $section = 'wooms_product_cat',
     346            $args = [
     347                'key' => $option_name,
     348                'value' => get_option( $option_name )
     349            ]
     350        );
     351    }
     352
     353    /**
     354     * is_disable
     355     */
     356    public static function is_disable() {
     357        if ( get_option( 'woomss_categories_sync_enabled' ) ) {
     358            return true;
     359        }
     360
     361        return false;
     362    }
     363
     364    /**
     365     * add_setting_categories_sync_enabled
     366     */
     367    public static function add_setting_categories_sync_enabled() {
     368
     369        /**
     370         * TODO заменить woomss_categories_sync_enabled на wooms_categories_sync_disable
     371         */
     372        $option_name = 'woomss_categories_sync_enabled';
     373
     374        register_setting( 'mss-settings', $option_name );
     375        add_settings_field(
     376            $id = $option_name,
     377            $title = 'Отключить синхронизацию категорий',
     378            $callback = function ($args) {
     379                printf( '<input type="checkbox" name="%s" value="1" %s />', $args['key'], checked( 1, $args['value'], false ) );
     380                printf( '<small>%s</small>', 'Если включить опцию, то при обновлении продуктов категории не будут учтываться в соответствии с группами МойСклад.' );
     381            },
     382            $page = 'mss-settings',
     383            $section = 'wooms_product_cat',
     384            $args = [
     385                'key' => $option_name,
     386                'value' => get_option( $option_name )
     387            ]
     388        );
     389    }
    397390}
    398391
  • wooms/tags/9.5/includes/ProductsImage.php

    r2979725 r2984550  
    44
    55const HOOK_NAME = 'wooms_product_image_sync';
     6
     7/**
     8 * @todo добавить проверку по урл изображения - если урл поменялся - обновлять, иначе - не делать лишние запросы
     9 */
    610
    711add_action('init', function () {
    812    add_action('wooms_product_image_sync', __NAMESPACE__ . '\\walker');
    9     add_filter('wooms_product_save', __NAMESPACE__ . '\\add_image_task_to_product', 35, 2);
     13    add_filter('wooms_product_update', __NAMESPACE__ . '\\add_image_task_to_product', 35, 2);
    1014    add_action('wooms_tools_sections', __NAMESPACE__ . '\\render_ui', 15);
    1115    add_action('admin_init', __NAMESPACE__ . '\\add_settings', 50);
     
    184188    }
    185189
    186     $images_data = wooms_request($url);
    187 
     190    $images_data = \WooMS\request( $url );
    188191
    189192    if (empty($images_data['rows'][0]['filename'])) {
     
    264267 * add image to metafield for download
    265268 */
    266 function add_image_task_to_product($product, $value)
     269function add_image_task_to_product($product, $row)
    267270{
    268271    if (!is_enable()) {
     
    270273    }
    271274
    272     $product_id = $product->get_id();
    273 
    274275    //Check image
    275     if (empty($value['images']['meta']['size'])) {
     276    if (empty($row['images']['meta']['size'])) {
    276277        return $product;
    277278    } else {
    278         $url = $value['images']['meta']['href'];
     279        $url = $row['images']['meta']['href'];
    279280    }
    280281    $product->update_meta_data('test_wooms_url_for_get_thumbnail', $url);
    281282    //check current thumbnail. if isset - break, or add url for next downloading
    282     if ($id = get_post_thumbnail_id($product_id) && empty(get_option('woomss_images_replace_to_sync'))) {
     283    if ($id = get_post_thumbnail_id($product->get_id()) && empty(get_option('woomss_images_replace_to_sync'))) {
    283284        return $product;
    284285    } else {
  • wooms/tags/9.5/includes/ProductsServices.php

    r2981815 r2984550  
    1111
    1212/**
    13  * Select specific price is setup
     13 * @todo refactoring
    1414 */
    1515class ProductsServices extends AbstractWalker
  • wooms/tags/9.5/readme.txt

    r2981815 r2984550  
    7676
    7777== Changelog ==
     78
     79= 9.5 =
     80- Исправлено: Не работает синхронизация категорий https://github.com/wpcraft-ru/wooms/issues/450
     81- Доработана логика API - теперь все работает по новому
     82
    7883
    7984= 9.4 =
  • wooms/tags/9.5/wooms.php

    r2981815 r2984550  
    2020 * WC tested up to: 7.2.2
    2121 *
    22  * Version: 9.4
     22 * Version: 9.5
    2323 */
    2424
  • wooms/trunk/includes/Orders.php

    r2981815 r2984550  
    4949        add_filter('wooms_order_data', [__CLASS__, 'add_currency'], 11, 3);
    5050        add_filter('wooms_order_data', [__CLASS__, 'add_positions'], 11, 3);
    51         // add_filter('wooms_order_send_data', [__CLASS__, 'add_positions'], 10, 3);
    5251        add_filter('wooms_order_data', [__CLASS__, 'add_moment'], 11, 3);
    5352        add_filter('wooms_order_data', [__CLASS__, 'add_client_as_agent'], 22, 3);
  • wooms/trunk/includes/Products.php

    r2979725 r2984550  
    55use function WooMS\request;
    66use function Testeroid\ddcli;
    7 use Error, Throwable;
     7use Error, Throwable, WC_Product;
    88
    99defined( 'ABSPATH' ) || exit;
     
    302302/**
    303303 * to replace load_product
     304 *
     305 * @return WC_Product
    304306 */
    305307function product_update( array $row, array $data = [] ) {
  • wooms/trunk/includes/ProductsCategories.php

    r2981815 r2984550  
    33namespace WooMS;
    44
    5 defined('ABSPATH') || exit;
     5use Error;
     6
     7defined( 'ABSPATH' ) || exit;
    68
    79/**
    810 * Import Product Categories from MoySklad
    911 */
    10 class ProductsCategories
    11 {
    12 
    13   /**
    14    * WooMS_Import_Product_Categories constructor.
    15    */
    16   public static function init()
    17   {
    18 
    19     add_filter('wooms_product_save', array(__CLASS__, 'product_save'), 10, 3);
    20     add_filter('wooms_product_save', array(__CLASS__, 'add_ancestors'), 15, 2);
    21 
    22     add_action('admin_init', array(__CLASS__, 'add_settings'), 50);
    23     add_action('product_cat_edit_form_fields', array(__CLASS__, 'display_data_category'), 30);
    24   }
    25 
    26   /**
    27    * add ancestors
    28    *
    29    * issue https://github.com/wpcraft-ru/wooms/issues/282
    30    */
    31   public static function add_ancestors($product, $data_api)
    32   {
    33     if (!get_option('wooms_categories_include_children')) {
    34       return $product;
    35     }
    36 
    37     if (empty($data_api['productFolder']['meta']['href'])) {
    38       return $product;
    39     }
    40 
    41     if (!$term_id = self::check_term_by_ms_uuid($data_api['productFolder']['meta']['href'])) {
    42       return $product;
    43     }
    44 
    45     // $product = wc_get_product($product);
    46 
    47     $term_ancestors = get_ancestors($term_id, 'product_cat', 'taxonomy');
    48 
    49     $term_ancestors[] = $term_id;
    50     $product->set_category_ids($term_ancestors);
    51 
    52     return $product;
    53   }
    54 
    55   /**
    56    * Загрузка данных категории для продукта
    57    */
    58   public static function product_save($product, $value, $data)
    59   {
    60 
    61     //Если опция отключена - пропускаем обработку
    62     if (self::is_disable()) {
    63       return $product;
    64     }
    65 
    66     if (empty($value['productFolder']['meta']['href'])) {
    67       return $product;
    68     }
    69 
    70     $product_id = $product->get_id();
    71 
    72     $url = $value['productFolder']['meta']['href'];
    73 
    74     if ($term_id = self::update_category($url)) {
    75 
    76       $result = $product->set_category_ids(array($term_id));
    77 
    78       if (is_wp_error($result)) {
    79         do_action('wooms_logger_error', __CLASS__, $result->get_error_code(), $result->get_error_message());
    80       } elseif ($result === false) {
    81         do_action('wooms_logger_error', __CLASS__, 'Не удалось выбрать категорию', $term_id);
    82       } else {
    83         do_action(
    84           'wooms_logger',
    85           __CLASS__,
    86           sprintf('Выбор категории продукта %s (id %s)', $product->get_name(), $product->get_id()),
    87           [
    88             '$url' => $url,
    89             '$term_id' => $term_id,
    90             'term_name' => get_term_by('id', $term_id, 'product_cat')->name,
    91             '$product_id' => $product_id,
    92             'select_cat_pid' => $product_id,
    93           ]
    94         );
    95       }
    96     }
    97 
    98     return $product;
    99   }
    100 
    101   /**
    102    * If isset term return term_id, else return false
    103    */
    104   public static function check_term_by_ms_uuid($id)
    105   {
    106     //if uuid as url - get uuid only
    107     $id = str_replace('https://online.moysklad.ru/api/remap/1.2/entity/productfolder/', '', $id);
    108     $id = str_replace('https://api.moysklad.ru/api/remap/1.2/entity/productfolder/', '', $id);
    109 
    110     $terms = get_terms(array(
    111       'taxonomy'   => array('product_cat'),
    112       'hide_empty' => false,
    113       'meta_query' => array(
    114         array(
    115           'key'   => 'wooms_id',
    116           'value' => $id,
    117         ),
    118       ),
    119     ));
    120 
    121     if (is_wp_error($terms) or empty($terms)) {
    122       return false;
    123     } else {
    124       foreach ($terms as $term) {
    125         if (isset($term->term_id)) {
    126           return $term->term_id;
    127         } else {
    128           return false;
    129         }
    130       }
    131     }
    132   }
    133 
    134 
    135   /**
    136    * Create and update categories
    137    *
    138    * @param $url
    139    */
    140   public static function update_category($url)
    141   {
    142     /**
    143      * Если указана группа для синхронизации,
    144      * и совпадает с запрошенной, то вернуть false, чтобы прекратить рекурсию создания родителей
    145      */
    146     if ($url == get_option('woomss_include_categories_sync')) {
    147       return false;
    148     }
    149 
    150     $data = wooms_request($url);
    151 
    152     if(empty($data['id'])){
    153       return false;
    154     }
    155 
    156     if ($term_id = self::check_term_by_ms_uuid($data['id'])) {
    157 
    158       do_action('wooms_update_category', $term_id);
    159 
    160       $args_update = array();
    161       $url_parent = '';
    162 
    163       if (isset($data['productFolder']['meta']['href'])) {
    164         $url_parent = $data['productFolder']['meta']['href'];
    165         if ($term_id_parent = self::update_category($url_parent)) {
    166           $args_update['parent'] = isset($term_id_parent) ? intval($term_id_parent) : 0;
    167         }
    168       }
    169 
    170       if (apply_filters('wooms_skip_update_select_category', true, $url_parent)) {
    171         $args_update = apply_filters('wooms_update_category_args', $args_update, $term_id, $data);
    172         $term = wp_update_term($term_id, 'product_cat', $args_update);
    173       }
    174 
    175       wp_update_term_count($term_id, $taxonomy = 'product_cat');
    176 
    177       update_term_meta($term_id, 'wooms_updated_category', $data['updated']);
    178 
    179       if (is_array($term) && !empty($term["term_id"])) {
    180         return $term["term_id"];
    181       } else {
    182         return false;
    183       }
    184     } else {
    185 
    186       $args = array();
    187 
    188       $term_new = array(
    189         'wooms_id' => $data['id'],
    190         'name'     => $data['name'],
    191         'archived' => $data['archived'],
    192       );
    193 
    194       if (isset($data['productFolder']['meta']['href'])) {
    195         $url_parent = $data['productFolder']['meta']['href'];
    196         if ($term_id_parent = self::update_category($url_parent)) {
    197           $args['parent'] = intval($term_id_parent);
    198         }
    199       }
    200 
    201       $url_parent = isset($data['productFolder']['meta']['href']) ? $data['productFolder']['meta']['href'] : '';
    202       $path_name  = isset($data['pathName']) ? $data['pathName'] : null;
    203 
    204       if (apply_filters('wooms_skip_categories', true, $url_parent, $path_name)) {
    205 
    206         $term = wp_insert_term($term_new['name'], $taxonomy = 'product_cat', $args);
    207         if (is_wp_error($term)) {
    208 
    209           if (isset($term->error_data['term_exists'])) {
    210             $msg = $term->get_error_message();
    211             $msg .= PHP_EOL . sprintf('Имя указанное при создании термина: %s', $term_new['name']);
    212             $msg .= PHP_EOL . sprintf('Существующий термин: %s', $term->error_data['term_exists']);
    213             $msg .= PHP_EOL . sprintf('Аргументы создания термина: %s', print_r($args, true));
    214             $msg .= PHP_EOL . sprintf('URL API: %s', $url);
    215           } else {
    216             $msg = $term->get_error_message();
    217             $msg .= PHP_EOL . print_r($args, true);
    218           }
    219           do_action('wooms_logger_error', __CLASS__, $term->get_error_code(), $msg);
    220         } else {
    221           do_action(
    222             'wooms_logger',
    223             __CLASS__,
    224             sprintf('Добавлен термин %s', $term_new['name']),
    225             sprintf('Результат обработки %s', PHP_EOL . print_r($term, true))
    226           );
    227         }
    228       }
    229 
    230       if (isset($term->errors["term_exists"])) {
    231         $term_id = intval($term->error_data['term_exists']);
    232         if (empty($term_id)) {
    233           return false;
    234         }
    235       } elseif (isset($term->term_id)) {
    236         $term_id = $term->term_id;
    237       } elseif (is_array($term) && !empty($term["term_id"])) {
    238         $term_id = $term["term_id"];
    239       } else {
    240         return false;
    241       }
    242 
    243       update_term_meta($term_id, 'wooms_id', $term_new['wooms_id']);
    244 
    245       update_term_meta($term_id, 'wooms_updated_category', $data['updated']);
    246 
    247       if ($session_id = get_option('wooms_session_id')) {
    248         update_term_meta($term_id, 'wooms_session_id', $session_id);
    249       }
    250 
    251       do_action('wooms_add_category', $term, $url_parent, $path_name);
    252 
    253       return $term_id;
    254     }
    255   }
    256 
    257   /**
    258    * Meta box in category
    259    *
    260    * @since 2.1.2
    261    *
    262    * @param $term
    263    */
    264   public static function display_data_category($term)
    265   {
    266 
    267     $meta_data         = get_term_meta($term->term_id, 'wooms_id', true);
    268     $meta_data_updated = get_term_meta($term->term_id, 'wooms_updated_category', true);
    269 
    270 ?>
    271     <tr class="form-field term-meta-text-wrap">
    272       <td colspan="2" style="padding: 0;">
    273         <h3 style="margin: 0;">МойСклад</h3>
    274       </td>
    275     </tr>
    276     <?php
    277 
    278     if ($meta_data) : ?>
    279       <tr class="form-field term-meta-text-wrap">
    280         <th scope="row">
    281           <label for="term-meta-text">ID категории в МойСклад</label>
    282         </th>
    283         <td>
    284           <strong><?php echo $meta_data ?></strong>
    285         </td>
    286       </tr>
    287       <tr class="form-field term-meta-text-wrap">
    288         <th scope="row">
    289           <label for="term-meta-text">Ссылка на категорию</label>
    290         </th>
    291         <td>
    292           <a href="https://online.moysklad.ru/app/#good/edit?id=<?php echo $meta_data ?>" target="_blank">Посмотреть категорию в МойСклад</a>
    293         </td>
    294       </tr>
    295     <?php else : ?>
    296       <tr class="form-field term-meta-text-wrap">
    297         <th scope="row">
    298           <label for="term-meta-text">ID категории в МойСклад</label>
    299         </th>
    300         <td>
    301           <strong>Категория еще не синхронизирована</strong>
    302         </td>
    303       </tr>
    304     <?php endif;
    305 
    306     if ($meta_data_updated) : ?>
    307       <tr class="form-field term-meta-text-wrap">
    308         <th scope="row">
    309           <label for="term-meta-text">Дата последнего обновления в МойСклад</label>
    310         </th>
    311         <td>
    312           <strong><?php echo $meta_data_updated; ?></strong>
    313         </td>
    314       </tr>
    315 <?php
    316     endif;
    317   }
    318 
    319   /**
    320    * Settings UI
    321    */
    322   public static function add_settings()
    323   {
    324 
    325     add_settings_section('wooms_product_cat', 'Категории продуктов', __return_empty_string(), 'mss-settings');
    326 
    327     self::add_setting_categories_sync_enabled();
    328     self::add_setting_include_children();
    329   }
    330 
    331   /**
    332    * add_setting_include_children
    333    *
    334    * issue https://github.com/wpcraft-ru/wooms/issues/282
    335    */
    336   public static function add_setting_include_children()
    337   {
    338     $option_name = 'wooms_categories_include_children';
    339 
    340     register_setting('mss-settings', $option_name);
    341     add_settings_field(
    342       $id = $option_name,
    343       $title = 'Выбор всех категорий в дереве',
    344       $callback = function ($args) {
    345         printf('<input type="checkbox" name="%s" value="1" %s />', $args['key'], checked(1, $args['value'], false));
    346         printf('<p>%s</p>', 'Опция позволяет указывать категории у продукта с учетом всего дерева - от верхнего предка, до всех потомков');
    347         printf('<p>Подробнее: <a href="%s" target="_blank">https://github.com/wpcraft-ru/wooms/issues/282</a></p>', 'https://github.com/wpcraft-ru/wooms/issues/282');
    348       },
    349       $page = 'mss-settings',
    350       $section = 'wooms_product_cat',
    351       $args = [
    352         'key' => $option_name,
    353         'value' => get_option($option_name)
    354       ]
    355     );
    356   }
    357 
    358   /**
    359    * is_disable
    360    */
    361   public static function is_disable()
    362   {
    363     if (get_option('woomss_categories_sync_enabled')) {
    364       return true;
    365     }
    366 
    367     return false;
    368   }
    369 
    370   /**
    371    * add_setting_categories_sync_enabled
    372    */
    373   public static function add_setting_categories_sync_enabled()
    374   {
    375 
    376     /**
    377      * TODO заменить woomss_categories_sync_enabled на wooms_categories_sync_disable
    378      */
    379     $option_name = 'woomss_categories_sync_enabled';
    380 
    381     register_setting('mss-settings', $option_name);
    382     add_settings_field(
    383       $id = $option_name,
    384       $title = 'Отключить синхронизацию категорий',
    385       $callback = function ($args) {
    386         printf('<input type="checkbox" name="%s" value="1" %s />', $args['key'], checked(1, $args['value'], false));
    387         printf('<small>%s</small>', 'Если включить опцию, то при обновлении продуктов категории не будут учтываться в соответствии с группами МойСклад.');
    388       },
    389       $page = 'mss-settings',
    390       $section = 'wooms_product_cat',
    391       $args = [
    392         'key' => $option_name,
    393         'value' => get_option($option_name)
    394       ]
    395     );
    396   }
     12class ProductsCategories {
     13
     14    public static function init() {
     15
     16        add_action( 'wooms_main_walker_started', array( __CLASS__, 'reset' ) );
     17
     18        add_filter( 'wooms_product_update', [ __CLASS__, 'update' ], 10, 3 );
     19        add_filter( 'wooms_product_update', [ __CLASS__, 'add_ancestors' ], 15, 3 );
     20
     21        add_action( 'admin_init', array( __CLASS__, 'add_settings' ), 50 );
     22        add_action( 'product_cat_edit_form_fields', array( __CLASS__, 'display_data_category' ), 30 );
     23    }
     24
     25
     26
     27    public static function update( $product, $row, $data ) {
     28        if ( self::is_disable() ) {
     29            return $product;
     30        }
     31
     32        $term_id = self::check_term_by_ms_uuid( $row['productFolder']['meta']['href'] );
     33
     34        if ( empty( $term_id ) ) {
     35            throw new Error( 'ProductsCategories - update - empty($term_id)' );
     36        }
     37
     38        $product->set_category_ids( array( $term_id ) );
     39
     40        return $product;
     41    }
     42
     43
     44
     45    /**
     46     * add ancestors
     47     *
     48     * issue https://github.com/wpcraft-ru/wooms/issues/282
     49     */
     50    public static function add_ancestors( \WC_Product $product, $row, $data ) {
     51        if ( ! get_option( 'wooms_categories_include_children' ) ) {
     52            return $product;
     53        }
     54
     55        if ( empty( $row['productFolder']['meta']['href'] ) ) {
     56            return $product;
     57        }
     58
     59        if ( ! $term_id = self::check_term_by_ms_uuid( $row['productFolder']['meta']['href'] ) ) {
     60            return $product;
     61        }
     62
     63        $term_ancestors = get_ancestors( $term_id, 'product_cat', 'taxonomy' );
     64
     65        $term_ancestors[] = $term_id;
     66        $product->set_category_ids( $term_ancestors );
     67
     68
     69        return $product;
     70    }
     71
     72
     73
     74    public static function product_categories_update( $productfolder ) {
     75
     76        if ( empty( $productfolder['rows'] ) ) {
     77            throw new Error( 'No categories for products', 500 );
     78        }
     79
     80
     81        if ( count( $productfolder['rows'] ) < 1 ) {
     82            throw new Error( 'No categories for products', 500 );
     83        }
     84
     85
     86        $list = [];
     87        foreach ( $productfolder['rows'] as $row ) {
     88            $list[] = self::product_category_update( $row, $productfolder );
     89        }
     90
     91        if ( empty( $list ) ) {
     92            throw new Error( 'product_category_update = empty $list[]' );
     93        }
     94
     95
     96        return $list;
     97
     98    }
     99
     100    public static function product_category_update( $row, $productfolder ) {
     101
     102        if ( empty( $row['id'] ) ) {
     103            // throw new Error( 'product_category_update = no $row[id]' );
     104        }
     105
     106        $term_id = self::check_term_by_ms_uuid( $row['id'] );
     107
     108        if ( $term_id ) {
     109
     110            update_term_meta( $term_id, 'wooms_updated_category', $row['updated'] );
     111
     112            $args = [];
     113
     114            if ( isset( $row['productFolder']['meta']['href'] ) ) {
     115                $url_parent = $row['productFolder']['meta']['href'];
     116                foreach ( $productfolder['rows'] as $parent_row ) {
     117                    if ( $parent_row['meta']['href'] == $url_parent ) {
     118                        $term_id_parent = self::product_category_update( $parent_row, $productfolder );
     119                        $args['parent'] = $term_id_parent;
     120                        break;
     121                    }
     122                }
     123            }
     124
     125            wp_update_term( $term_id, $taxonomy = 'product_cat', $args );
     126
     127            return $term_id;
     128        } else {
     129
     130            $args = array();
     131
     132            $term_new = array(
     133                'wooms_id' => $row['id'],
     134                'name' => $row['name'],
     135                'archived' => $row['archived'],
     136            );
     137
     138            if ( isset( $row['productFolder']['meta']['href'] ) ) {
     139                $url_parent = $row['productFolder']['meta']['href'];
     140                foreach ( $productfolder['rows'] as $parent_row ) {
     141                    if ( $parent_row['meta']['href'] == $url_parent ) {
     142                        $term_id_parent = self::product_category_update( $parent_row, $productfolder );
     143                        $args['parent'] = $term_id_parent;
     144                        break;
     145                    }
     146                }
     147            }
     148
     149            $url_parent = isset( $row['productFolder']['meta']['href'] ) ? $row['productFolder']['meta']['href'] : '';
     150            $path_name = isset( $row['pathName'] ) ? $row['pathName'] : null;
     151
     152            if ( apply_filters( 'wooms_skip_categories', true, $url_parent, $path_name ) ) {
     153
     154                $term = wp_insert_term( $term_new['name'], $taxonomy = 'product_cat', $args );
     155                if ( is_wp_error( $term ) ) {
     156
     157                    if ( isset( $term->error_data['term_exists'] ) ) {
     158                        $msg = $term->get_error_message();
     159                        $msg .= PHP_EOL . sprintf( 'Имя указанное при создании термина: %s', $term_new['name'] );
     160                        $msg .= PHP_EOL . sprintf( 'Существующий термин: %s', $term->error_data['term_exists'] );
     161                        $msg .= PHP_EOL . sprintf( 'Аргументы создания термина: %s', print_r( $args, true ) );
     162
     163                    } else {
     164                        $msg = $term->get_error_message();
     165                        $msg .= PHP_EOL . print_r( $args, true );
     166                    }
     167                    do_action( 'wooms_logger_error', __CLASS__, $term->get_error_code(), $msg );
     168                } else {
     169                    do_action(
     170                        'wooms_logger',
     171                        __CLASS__,
     172                        sprintf( 'Добавлен термин %s', $term_new['name'] ),
     173                        sprintf( 'Результат обработки %s', PHP_EOL . print_r( $term, true ) )
     174                    );
     175                }
     176            }
     177
     178            if ( isset( $term->errors["term_exists"] ) ) {
     179                $term_id = intval( $term->error_data['term_exists'] );
     180                if ( empty( $term_id ) ) {
     181                    return false;
     182                }
     183            } elseif ( isset( $term->term_id ) ) {
     184                $term_id = $term->term_id;
     185            } elseif ( is_array( $term ) && ! empty( $term["term_id"] ) ) {
     186                $term_id = $term["term_id"];
     187            } else {
     188                return false;
     189            }
     190
     191            update_term_meta( $term_id, 'wooms_id', $row['id'] );
     192
     193            update_term_meta( $term_id, 'wooms_updated_category', $row['updated'] );
     194
     195            if ( $session_id = get_option( 'wooms_session_id' ) ) {
     196                update_term_meta( $term_id, 'wooms_session_id', $session_id );
     197            }
     198
     199            do_action( 'wooms_add_category', $term, $url_parent, $path_name );
     200
     201            return $term_id;
     202        }
     203
     204    }
     205
     206
     207    public static function prepare( $data, $row ) {
     208
     209        return $data;
     210
     211    }
     212
     213
     214    public static function reset() {
     215        $productfolder = request( 'entity/productfolder' );
     216
     217        self::product_categories_update( $productfolder );
     218
     219    }
     220
     221
     222    /**
     223     * If isset term return term_id, else return false
     224     */
     225    public static function check_term_by_ms_uuid( $id ) {
     226
     227        //if uuid as url - get uuid only
     228        $id = str_replace( 'https://online.moysklad.ru/api/remap/1.2/entity/productfolder/', '', $id );
     229        $id = str_replace( 'https://api.moysklad.ru/api/remap/1.2/entity/productfolder/', '', $id );
     230
     231
     232        $terms = get_terms( array(
     233            'taxonomy' => array( 'product_cat' ),
     234            'hide_empty' => false,
     235            'meta_query' => array(
     236                array(
     237                    'key' => 'wooms_id',
     238                    'value' => $id,
     239                ),
     240            ),
     241        ) );
     242
     243        if ( empty( $terms[0] ) ) {
     244            return null;
     245        }
     246        return $terms[0]->term_id;
     247    }
     248
     249
     250    /**
     251     * Meta box in category
     252     *
     253     * @since 2.1.2
     254     *
     255     * @param $term
     256     */
     257    public static function display_data_category( $term ) {
     258
     259        $meta_data = get_term_meta( $term->term_id, 'wooms_id', true );
     260        $meta_data_updated = get_term_meta( $term->term_id, 'wooms_updated_category', true );
     261
     262        ?>
     263        <tr class="form-field term-meta-text-wrap">
     264            <td colspan="2" style="padding: 0;">
     265                <h3 style="margin: 0;">МойСклад</h3>
     266            </td>
     267        </tr>
     268        <?php
     269
     270        if ( $meta_data ) : ?>
     271            <tr class="form-field term-meta-text-wrap">
     272                <th scope="row">
     273                    <label for="term-meta-text">ID категории в МойСклад</label>
     274                </th>
     275                <td>
     276                    <strong>
     277                        <?php echo $meta_data ?>
     278                    </strong>
     279                </td>
     280            </tr>
     281            <tr class="form-field term-meta-text-wrap">
     282                <th scope="row">
     283                    <label for="term-meta-text">Ссылка на категорию</label>
     284                </th>
     285                <td>
     286                    <a href="https://online.moysklad.ru/app/#good/edit?id=<?php echo $meta_data ?>" target="_blank">Посмотреть
     287                        категорию в МойСклад</a>
     288                </td>
     289            </tr>
     290        <?php else : ?>
     291            <tr class="form-field term-meta-text-wrap">
     292                <th scope="row">
     293                    <label for="term-meta-text">ID категории в МойСклад</label>
     294                </th>
     295                <td>
     296                    <strong>Категория еще не синхронизирована</strong>
     297                </td>
     298            </tr>
     299        <?php endif;
     300
     301        if ( $meta_data_updated ) : ?>
     302            <tr class="form-field term-meta-text-wrap">
     303                <th scope="row">
     304                    <label for="term-meta-text">Дата последнего обновления в МойСклад</label>
     305                </th>
     306                <td>
     307                    <strong>
     308                        <?php echo $meta_data_updated; ?>
     309                    </strong>
     310                </td>
     311            </tr>
     312            <?php
     313        endif;
     314    }
     315
     316    /**
     317     * Settings UI
     318     */
     319    public static function add_settings() {
     320
     321        add_settings_section( 'wooms_product_cat', 'Категории продуктов', __return_empty_string(), 'mss-settings' );
     322
     323        self::add_setting_categories_sync_enabled();
     324        self::add_setting_include_children();
     325    }
     326
     327    /**
     328     * add_setting_include_children
     329     *
     330     * issue https://github.com/wpcraft-ru/wooms/issues/282
     331     */
     332    public static function add_setting_include_children() {
     333        $option_name = 'wooms_categories_include_children';
     334
     335        register_setting( 'mss-settings', $option_name );
     336        add_settings_field(
     337            $id = $option_name,
     338            $title = 'Выбор всех категорий в дереве',
     339            $callback = function ($args) {
     340                printf( '<input type="checkbox" name="%s" value="1" %s />', $args['key'], checked( 1, $args['value'], false ) );
     341                printf( '<p>%s</p>', 'Опция позволяет указывать категории у продукта с учетом всего дерева - от верхнего предка, до всех потомков' );
     342                printf( '<p>Подробнее: <a href="%s" target="_blank">https://github.com/wpcraft-ru/wooms/issues/282</a></p>', 'https://github.com/wpcraft-ru/wooms/issues/282' );
     343            },
     344            $page = 'mss-settings',
     345            $section = 'wooms_product_cat',
     346            $args = [
     347                'key' => $option_name,
     348                'value' => get_option( $option_name )
     349            ]
     350        );
     351    }
     352
     353    /**
     354     * is_disable
     355     */
     356    public static function is_disable() {
     357        if ( get_option( 'woomss_categories_sync_enabled' ) ) {
     358            return true;
     359        }
     360
     361        return false;
     362    }
     363
     364    /**
     365     * add_setting_categories_sync_enabled
     366     */
     367    public static function add_setting_categories_sync_enabled() {
     368
     369        /**
     370         * TODO заменить woomss_categories_sync_enabled на wooms_categories_sync_disable
     371         */
     372        $option_name = 'woomss_categories_sync_enabled';
     373
     374        register_setting( 'mss-settings', $option_name );
     375        add_settings_field(
     376            $id = $option_name,
     377            $title = 'Отключить синхронизацию категорий',
     378            $callback = function ($args) {
     379                printf( '<input type="checkbox" name="%s" value="1" %s />', $args['key'], checked( 1, $args['value'], false ) );
     380                printf( '<small>%s</small>', 'Если включить опцию, то при обновлении продуктов категории не будут учтываться в соответствии с группами МойСклад.' );
     381            },
     382            $page = 'mss-settings',
     383            $section = 'wooms_product_cat',
     384            $args = [
     385                'key' => $option_name,
     386                'value' => get_option( $option_name )
     387            ]
     388        );
     389    }
    397390}
    398391
  • wooms/trunk/includes/ProductsImage.php

    r2979725 r2984550  
    44
    55const HOOK_NAME = 'wooms_product_image_sync';
     6
     7/**
     8 * @todo добавить проверку по урл изображения - если урл поменялся - обновлять, иначе - не делать лишние запросы
     9 */
    610
    711add_action('init', function () {
    812    add_action('wooms_product_image_sync', __NAMESPACE__ . '\\walker');
    9     add_filter('wooms_product_save', __NAMESPACE__ . '\\add_image_task_to_product', 35, 2);
     13    add_filter('wooms_product_update', __NAMESPACE__ . '\\add_image_task_to_product', 35, 2);
    1014    add_action('wooms_tools_sections', __NAMESPACE__ . '\\render_ui', 15);
    1115    add_action('admin_init', __NAMESPACE__ . '\\add_settings', 50);
     
    184188    }
    185189
    186     $images_data = wooms_request($url);
    187 
     190    $images_data = \WooMS\request( $url );
    188191
    189192    if (empty($images_data['rows'][0]['filename'])) {
     
    264267 * add image to metafield for download
    265268 */
    266 function add_image_task_to_product($product, $value)
     269function add_image_task_to_product($product, $row)
    267270{
    268271    if (!is_enable()) {
     
    270273    }
    271274
    272     $product_id = $product->get_id();
    273 
    274275    //Check image
    275     if (empty($value['images']['meta']['size'])) {
     276    if (empty($row['images']['meta']['size'])) {
    276277        return $product;
    277278    } else {
    278         $url = $value['images']['meta']['href'];
     279        $url = $row['images']['meta']['href'];
    279280    }
    280281    $product->update_meta_data('test_wooms_url_for_get_thumbnail', $url);
    281282    //check current thumbnail. if isset - break, or add url for next downloading
    282     if ($id = get_post_thumbnail_id($product_id) && empty(get_option('woomss_images_replace_to_sync'))) {
     283    if ($id = get_post_thumbnail_id($product->get_id()) && empty(get_option('woomss_images_replace_to_sync'))) {
    283284        return $product;
    284285    } else {
  • wooms/trunk/includes/ProductsServices.php

    r2981815 r2984550  
    1111
    1212/**
    13  * Select specific price is setup
     13 * @todo refactoring
    1414 */
    1515class ProductsServices extends AbstractWalker
  • wooms/trunk/readme.txt

    r2981815 r2984550  
    7676
    7777== Changelog ==
     78
     79= 9.5 =
     80- Исправлено: Не работает синхронизация категорий https://github.com/wpcraft-ru/wooms/issues/450
     81- Доработана логика API - теперь все работает по новому
     82
    7883
    7984= 9.4 =
  • wooms/trunk/wooms.php

    r2981815 r2984550  
    2020 * WC tested up to: 7.2.2
    2121 *
    22  * Version: 9.4
     22 * Version: 9.5
    2323 */
    2424
Note: See TracChangeset for help on using the changeset viewer.