diff --git a/.babelrc b/.babelrc new file mode 100644 index 00000000000..47de40687da --- /dev/null +++ b/.babelrc @@ -0,0 +1,9 @@ +{ + "presets": [ + "es2015", + "stage-2" + ], + "plugins": [ + "add-module-exports" + ] +} diff --git a/.codeclimate.yml b/.codeclimate.yml new file mode 100644 index 00000000000..a11de13a5c8 --- /dev/null +++ b/.codeclimate.yml @@ -0,0 +1,37 @@ +engines: + phpcodesniffer: + enabled: true + config: + standard: "WordPress" + eslint: + enabled: true + scss-lint: + enabled: true + duplication: + enabled: true + config: + languages: + - php + - javascript +ratings: + paths: + - "includes/*" +exclude_paths: + - tests/* + - apigen/* + - dummy-data/* + - i18n/* + - includes/api/legacy/* + - includes/libraries/* + - includes/updates/* + - includes/gateways/simplify-commerce/* + - includes/shipping/legacy-* + - includes/wc-deprecated-functions.php + - includes/class-wc-legacy-api.php + - assets/js/accounting/** + - assets/js/jquery-* + - assets/js/prettyPhoto/* + - assets/js/round/* + - assets/js/select2/* + - assets/js/stupidtable/* + - assets/js/zeroclipboard/* diff --git a/.editorconfig b/.editorconfig index d3b0b247108..c3dfa83750f 100644 --- a/.editorconfig +++ b/.editorconfig @@ -2,7 +2,7 @@ # editorconfig.org # WordPress Coding Standards -# http://make.wordpress.org/core/handbook/coding-standards/ +# https://make.wordpress.org/core/handbook/coding-standards/ root = true diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000000..5e8686b5f3a --- /dev/null +++ b/.gitattributes @@ -0,0 +1,10 @@ +/.* export-ignore +apigen* export-ignore +CHANGELOG.txt export-ignore +composer.* export-ignore +Gruntfile.js export-ignore +package.json export-ignore +phpcs.ruleset.xml export-ignore +phpunit.* export-ignore +README.md export-ignore +tests export-ignore diff --git a/CONTRIBUTING.md b/.github/CONTRIBUTING.md similarity index 83% rename from CONTRIBUTING.md rename to .github/CONTRIBUTING.md index 689ae2a2296..97fcc742bbd 100644 --- a/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -6,23 +6,23 @@ When contributing please ensure you follow the guidelines below to help us keep __Please Note:__ -GitHub is for _bug reports and contributions only_ - if you have a support question or a request for a customization this is not the right place to post it. Use [WooThemes Support](http://support.woothemes.com) for customer support, [WordPress.org](http://wordpress.org/support/plugin/woocommerce) for community support, and for customizations we recommend one of the following services: +GitHub is for _bug reports and contributions only_ - if you have a support question or a request for a customization this is not the right place to post it. Use [WooCommerce Support](https://support.woocommerce.com) for customer support, [WordPress.org](https://wordpress.org/support/plugin/woocommerce) for community support, and for customizations we recommend one of the following services: -- [WooExperts](http://www.woothemes.com/experts/) +- [WooExperts](https://woocommerce.com/experts/) - [Codeable](https://codeable.io/) ## Contributing To The Core ### Reporting Issues -Reporting issues is a great way to became a contributor as it doesn't require technical skills. In fact you don't even need to know a programming language or to be able to check the code itself, you just need to make sure that everything works as expected and [submit an issue report](https://github.com/woothemes/woocommerce/issues/new) if you spot a bug. Sound like something you're up for? Go for it! +Reporting issues is a great way to became a contributor as it doesn't require technical skills. In fact you don't even need to know a programming language or to be able to check the code itself, you just need to make sure that everything works as expected and [submit an issue report](https://github.com/woocommerce/woocommerce/issues/new) if you spot a bug. Sound like something you're up for? Go for it! #### How To Submit An Issue Report If something isn't working, congratulations you've found a bug! Help us fix it by submitting an issue report: * Make sure you have a [GitHub account](https://github.com/signup/free) -* Search the [Existing Issues](https://github.com/woothemes/woocommerce/issues) to be sure that the one you've noticed isn't already there +* Search the [Existing Issues](https://github.com/woocommerce/woocommerce/issues) to be sure that the one you've noticed isn't already there * Submit a report for your issue * Clearly describe the issue (including steps to reproduce it if it's a bug) * Make sure you fill in the earliest version that you know has the issue. @@ -37,7 +37,7 @@ If you think something could be improved and you're able to do so, make your cha * Fork the repository on GitHub * Make the changes to your forked repository - * **Ensure you stick to the [WordPress Coding Standards](http://make.wordpress.org/core/handbook/coding-standards/php/).** + * **Ensure you stick to the [WordPress Coding Standards](https://make.wordpress.org/core/handbook/coding-standards/php/).** * Ensure you use LF line endings - no crazy Windows line endings please :) * When committing, reference your issue number (#1234) and include a note about the fix * Push the changes to your fork and submit a pull request on the master branch of the WooCommerce repository. Existing maintenance branches will be maintained by WooCommerce developers @@ -86,14 +86,14 @@ If WooCommerce is already 100% translated for your language, join the team anywa ### Translating Video Tutorials -Another valuable way to help is by translating our growing library of WooCommerce video tutorials. Check out our [Video SRTs project](https://www.transifex.com/projects/p/video-srts/) and join the team for your language. If there isn't one, please request the new language and we will add it for you. +Another valuable way to help is by translating our growing library of WooCommerce video tutorials. Check out the [Translating Our Videos](https://docs.woocommerce.com/document/translating-our-videos/) doc and join in! By translating video tutorials you'll be helping non-English speaking users and people affected by disabilities to get to grips with using WooCommerce for the first time, and to go on and create their businesses and make a living! That's something to be proud of and if you choose to dive into this area, we salute you. # Additional Resources -* [General GitHub documentation](http://help.github.com/) -* [GitHub pull request documentation](http://help.github.com/send-pull-requests/) +* [General GitHub documentation](https://help.github.com/) +* [GitHub pull request documentation](https://help.github.com/articles/about-pull-requests/) * [Translator Handbook](https://make.wordpress.org/polyglots/handbook/) -* [WooCommerce Docs](http://docs.woothemes.com/) -* [WooThemes Support](http://support.woothemes.com) +* [WooCommerce Docs](https://docs.woocommerce.com/) +* [WooCommerce Support](https://support.woocommerce.com) diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md new file mode 100644 index 00000000000..0d1135a372b --- /dev/null +++ b/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,31 @@ +### EXPLANATION OF THE ISSUE + + + +### STEPS TO REPRODUCE THE ISSUE + + + +### SYSTEM STATUS + +
+``` +Grab the system status report from WooCommerce > System Status and paste it here between the `details` tags. +``` +
+ + diff --git a/.github/wiki.png b/.github/wiki.png new file mode 100644 index 00000000000..539760052fa Binary files /dev/null and b/.github/wiki.png differ diff --git a/.gitignore b/.gitignore index 2ba87075ebf..0612a52c0cf 100644 --- a/.gitignore +++ b/.gitignore @@ -22,9 +22,20 @@ Thumbs.db # ApiGen /wc-apidocs/ +# Behat/CLI Tests +tests/cli/installer +tests/cli/composer.phar +tests/cli/composer.lock +tests/cli/composer.json +tests/cli/vendor + # Unit tests /tmp /tests/bin/tmp +/tests/e2e-tests/config/local-*.json # Logs /logs + +# Composer +/vendor/ diff --git a/.scrutinizer.yml b/.scrutinizer.yml index a98f292be23..07af2c45c90 100644 --- a/.scrutinizer.yml +++ b/.scrutinizer.yml @@ -4,11 +4,14 @@ filter: - apigen/* - dummy-data/* - i18n/* - - includes/api/v1/* - - includes/api/v2/* + - includes/api/legacy/* + - includes/legacy/* - includes/libraries/* - includes/updates/* - - includes/gateways/simplify-commerce/includes/* + - includes/gateways/simplify-commerce/* + - includes/shipping/legacy-* + - includes/wc-deprecated-functions.php + - includes/class-wc-legacy-api.php checks: php: diff --git a/.stylelintrc b/.stylelintrc new file mode 100644 index 00000000000..4c93dd4476d --- /dev/null +++ b/.stylelintrc @@ -0,0 +1,60 @@ +{ + "rules": { + "indentation": "tab", + "color-hex-case": "lower", + "color-no-invalid-hex": true, + + "function-calc-no-unspaced-operator": true, + "function-comma-space-after": "always-single-line", + "function-comma-space-before": "never", + "function-name-case": "lower", + "function-url-quotes": "always", + "function-whitespace-after": "always", + + "number-leading-zero": "always", + "number-no-trailing-zeros": true, + "length-zero-no-unit": true, + + "string-no-newline": true, + "string-quotes": "single", + + "unit-case": "lower", + "unit-no-unknown": true, + "unit-whitelist": ["px", "%", "deg", "ms", "em", "vh", "vw", "rem", "s", "ex", "pt", "cm"], + + "value-list-comma-space-after": "always-single-line", + "value-list-comma-space-before": "never", + + "shorthand-property-no-redundant-values": true, + + "property-case": "lower", + + "declaration-block-no-duplicate-properties": [true, { "severity": "warning" } ], + "declaration-block-no-ignored-properties": [true, { "severity": "warning" } ], + "declaration-block-trailing-semicolon": "always", + "declaration-block-single-line-max-declarations": 0, + "declaration-block-semicolon-space-before": "never", + "declaration-block-semicolon-space-after": "always-single-line", + "declaration-block-semicolon-newline-before": "never-multi-line", + "declaration-block-semicolon-newline-after": "always-multi-line", + + "block-closing-brace-newline-after": "always", + "block-closing-brace-newline-before": "always-multi-line", + "block-no-empty": true, + "block-opening-brace-newline-after": "always-multi-line", + "block-opening-brace-space-before": "always", + + "selector-attribute-brackets-space-inside": "never", + "selector-attribute-operator-space-after": "never", + "selector-attribute-operator-space-before": "never", + "selector-combinator-space-after": "always", + "selector-combinator-space-before": "always", + "selector-pseudo-class-case": "lower", + "selector-pseudo-class-parentheses-space-inside": "always", + "selector-pseudo-element-case": "lower", + "selector-pseudo-element-colon-notation": "double", + "selector-pseudo-element-no-unknown": true, + "selector-type-case": "lower", + "selector-no-id": [true, { "severity": "warning" } ], + } +} diff --git a/.travis.yml b/.travis.yml index 5f81048b168..b6cd8bce848 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,30 +2,32 @@ language: php sudo: false +# Test main supported versions of PHP and HHVM against latest WP. 5.2 is min supported version. php: + - 5.2 - 5.3 - - 5.4 - - 5.5 - 5.6 - 7.0 + - 7.1 + - hhvm env: - - WP_VERSION=latest WP_MULTISITE=0 - - WP_VERSION=4.3 WP_MULTISITE=0 - - WP_VERSION=4.2 WP_MULTISITE=0 - - WP_VERSION=4.1 WP_MULTISITE=0 - - WP_VERSION=4.0 WP_MULTISITE=0 + - WP_VERSION=latest WP_MULTISITE=0 PHP_LATEST_STABLE=7.1 +# Additonal tests against stable PHP (min recommended version is 5.6) and past supported versions of WP. matrix: include: - - php: 5.3 - env: WP_VERSION=latest WP_MULTISITE=1 + - php: 5.6 + env: WP_VERSION=latest WP_MULTISITE=1 PHP_LATEST_STABLE=7.1 before_script: + - export PATH="$HOME/.composer/vendor/bin:$PATH" - bash tests/bin/install.sh woocommerce_test root '' localhost $WP_VERSION - bash tests/bin/travis.sh before -script: phpunit -c phpunit.xml.dist +script: + - bash tests/bin/phpunit.sh + - bash tests/bin/travis.sh during after_script: - bash tests/bin/travis.sh after diff --git a/.wordpress-org/banner-1544x500.png b/.wordpress-org/banner-1544x500.png new file mode 100644 index 00000000000..d515d551fcc Binary files /dev/null and b/.wordpress-org/banner-1544x500.png differ diff --git a/.wordpress-org/banner-772x250.png b/.wordpress-org/banner-772x250.png new file mode 100644 index 00000000000..aa1f423b1bd Binary files /dev/null and b/.wordpress-org/banner-772x250.png differ diff --git a/.wordpress-org/icon-128x128.png b/.wordpress-org/icon-128x128.png new file mode 100644 index 00000000000..60918af4695 Binary files /dev/null and b/.wordpress-org/icon-128x128.png differ diff --git a/.wordpress-org/icon-256x256.png b/.wordpress-org/icon-256x256.png new file mode 100644 index 00000000000..2390aa84fff Binary files /dev/null and b/.wordpress-org/icon-256x256.png differ diff --git a/.wordpress-org/screenshot-1.png b/.wordpress-org/screenshot-1.png new file mode 100644 index 00000000000..9b90d4fd05d Binary files /dev/null and b/.wordpress-org/screenshot-1.png differ diff --git a/.wordpress-org/screenshot-2.png b/.wordpress-org/screenshot-2.png new file mode 100644 index 00000000000..995273936b3 Binary files /dev/null and b/.wordpress-org/screenshot-2.png differ diff --git a/.wordpress-org/screenshot-3.png b/.wordpress-org/screenshot-3.png new file mode 100644 index 00000000000..84c39b4c4e3 Binary files /dev/null and b/.wordpress-org/screenshot-3.png differ diff --git a/.wordpress-org/screenshot-4.png b/.wordpress-org/screenshot-4.png new file mode 100644 index 00000000000..9865f3351bb Binary files /dev/null and b/.wordpress-org/screenshot-4.png differ diff --git a/.wordpress-org/screenshot-5.png b/.wordpress-org/screenshot-5.png new file mode 100644 index 00000000000..ed40c7f4743 Binary files /dev/null and b/.wordpress-org/screenshot-5.png differ diff --git a/.wordpress-org/screenshot-6.png b/.wordpress-org/screenshot-6.png new file mode 100644 index 00000000000..ba6dea591e0 Binary files /dev/null and b/.wordpress-org/screenshot-6.png differ diff --git a/CHANGELOG.txt b/CHANGELOG.txt index a7a57476294..c7aa5904ee1 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -1,12 +1,647 @@ == Changelog == -= 2.4.12 - 9/12/2015 = += 3.0.5 - 2017-04-28 = +* Fix - Tooltip display within shipping zone modals. +* Fix - Fix missing title for actions column on mobile. +* Fix - Allow forward slash in telephone field. +* Fix - Sort grouped products by menu order when displaying. +* Fix - Fix term exclusion in term count queries. +* Fix - Filter invalid products before returning them for wc_get_products. +* Fix - Prevent orders being their own parent (causes errors). +* Fix - Correctly migrate legacy shipping taxes data. +* Fix - Make sure the meta data cache is not shared among instances. +* Fix - Correct the stock display notice when a variable product manages stock for it's children. +* Fix - On multisite, add user to blog during checkout if not a user to prevent errors. +* Fix - Correct sale price date handling with some timezone setups. +* Fix - wc_attribute_taxonomy_id_by_name needs to use lowercase attribute slug to work. +* Fix - Make changes to the buyer's company name in the shipping section of checkout persist. +* Tweak - Add required placeholder for meta fields in backend. +* Tweak - Don't strtolower address strings on checkout validation messages. +* REST API - Prevent password change notification when creating a customer. +* REST API - Removed duplicated items returned in shipping and checkout endpoints. +* CLI - Fixed missing shipping zones route. +* Dev - Make get_price_html handling match 2.6 and pass all values through woocommerce_get_price_html filter. +* Dev - Legacy customer class missing get_address / get_address_2 functions. +* Dev - Restored filter `woocommerce_checkout_customer_id` during checkout validation. +* Dev - Adds missing `$this` argument for all `woocommerce_payment_complete_order_status` filters. + += 3.0.4 - 2017-04-20 = +* Fix - Variations were not inheriting the product image and shipping class ID. +* Fix - Prevent rating/review counts being duplicated when duplicating products. +* Fix - Fixed gallery navigation between images with long captions. +* Fix - Support transparent PNG in the gallery by setting a background color. +* Fix - Removed name/company from the shipping address Google map links. +* Fix - Fixed the address field sorting script on the checkout. +* Fix - Fixed the upgrade routine for grouped products so that parents are unset. +* Fix - Fixed support for WordPress 4.7 user locale settings. +* Fix - Fixed default option filter for product types in the product meta box. +* Fix - Improved the css in Twenty Seventeen for dark color schemes. +* Fix - Fixed display of refunds in sales report. +* Fix - Updated `single-product/add-to-cart/variable.php` template version to 3.0.0 since it had changes since 2.6. +* Fix - Fixed warnings when product attribute do not exists. +* Fix - Used a div for comment-form-rating to prevent invalid nested markup. +* Fix - Fixed some logic that checks if order taxes are compound. +* Fix - Fixed SKU checks to only exclude products that are trashed. +* Fix - Fixed display of download permissions in first email sent after checkout. +* Fix - Hidden the backorder notification stock text when notification is disabled. +* Fix - Fixed incorrect stock numbers in low stock emails. +* Tweak - Removed the non-functional order total input box, and combined the recalculation buttons into one working button. +* Tweak - Updated Guided Tour videos. +* Tweak - Updated js-cookie.js to 2.1.4. +* Tweak - Updated schema.org URLs to use HTTPS. +* Tweak - Status report request timeouts. +* REST API - Fixed an issue that prevented deleting a term if errors were thrown during creation. +* REST API - Fixed reports endpoint when querying by date. +* REST API - Fixed ignored order parameters when changing order status. +* Dev - Support guest orders in `wc_get_orders` function. +* Dev - Fixed downloadable variation filters for download URLs. +* Dev - Added safeguards to prevent infinite loops while saving coupons, products and orders in admin. +* Dev - Added a fallback for `queue_transactional_email` if background sending is disabled. +* Dev - Added `has_shipping_address` helper method. +* Dev - Introduced `woocommerce_order_item_get_formatted_meta_data` filter. +* Dev - Made wc_add_order_item pass correct values to woocommerce_new_order_item. +* Dev - Fixed `legacy_posted_data` access in checkout class. +* Dev - Fixed undefined property notice in `WC_Order_Item::offsetGet`. +* Dev - Fixed PHP 7.1 warnings when using non-float values to `wc_get_weight()`. +* Dev - Fixed incorrect variable name in `wc_add_order_item()`. + += 3.0.3 - 2017-04-13 = +* Fix - Fixed an issue with variation tax-classes when set to 'parent'. This made taxes apply on top of the tax inclusive price in certain setups. +* Fix - Escaped attribute translations in the `cart.php` template and bumped the template version to match. +* Fix - Corrected the display of refund dates on the order screen. +* Fix - Fixed the grouped product visibility check in the grouped.php template and bumped the template version to match. +* Fix - Fixed the sale badge display for grouped products. +* Fix - Added the `itemReviewed` structured data for product reviews to make it validate. +* Fix - Made the `get_attribute` method work on variation objects. +* Tweak - Turned off the deferred email sending by default which was added in 3.0. Whilst it does improve performance, there were compatibility problems on some servers. It can be enabled with a filter if desired. +* Dev - Added backtrace information to the deprecation messages to help find problem plugins. + += 3.0.2 - 2017-04-12 = +* Fix - Removed required states for GP, GF, KW, LB, MQ, RE and YT countries. +* Fix - Made cache in the [products] shortcode respect filters from plugins. +* Fix - Added missing `woocommerce_cross_sells_columns` filter. +* Fix - Fixed shortcode rendering on the shop page. +* Fix - Fixed incorrect sale dates when bulk editing variations. +* Fix - Fixed calls to wc_reduce_stock_levels in PayPal and Simplify gateways. +* Fix - Exclude "location" meta when reading customer meta data. +* Fix - Updated `emails/email-addresses.php`, `emails/email-order-details.php`, `content-single-product.php`, `checkout/form-shipping.php`, `myaccount/form-add-payment-method.php`, `myaccount/form-edit-address.php`, `myaccount/form-lost-password.php`, `myaccount/form-reset-password.php`, `myaccount/orders.php` and `myaccount/view-order.php` template version to 3.0.0 since they had changes since 2.6. +* Fix - Fixed default behavior of variation tax classes when originally set to "parent". +* Fix - When duplicating products, do not copy slug, append "(Copy)" to the product name, correctly copy all meta data, and prevent children of grouped products being duplicated too. +* Fix - Removed duplicated items when outputting cross sells on the cart page. +* Fix - Fixed output of default "add to cart" text of external products in loops. +* Fix - Fixed backwards compatibility of guest checkout rules when being altered by plugins directly. +* Fix - Use correct thumbnail sizes for variation images in the new gallery. +* Fix - Fixed captions on thumbnails and main image in the new gallery. +* Fix - Trigger wc_fragments_loaded after add to cart fragment refresh. +* Fix - Download permissions; Convert dates to timestamp on read so UTC is preserved. +* Fix - Fixed notices under PHP 7.1 when sorting products by name (numeric). +* Fix - Added additional checks to ensure objects are read before using class methods to avoid errors. +* Fix - Removed legacy suggest.js code which was causing JS error on bulk edit. +* Fix - Fixed warnings on the "Lost password" page and when loading a product with invalid attributes. +* Fix - Made background emailer update the queue after a successful send so duplicate mails are less likely. +* Fix - Typo in flexslider_enabled option in new gallery script. +* Fix - woocommerce_notify_low_stock and woocommerce_notify_no_stock options had no effect. +* Tweak - For downloadable files, only validate file type when dealing with relative paths. +* Tweak - Improved automatic variation name generation. +* Dev - Added product visibility terms to system status report to help debug. +* Dev - Introduced `woocommerce_admin_order_date_format` filter to replace missing `post_date_column_time`. +* Dev - Introduced `woocommerce_update_customer_args` filter to prevent updates to user objects if needed. +* REST API - Fixed saving of variations in legacy REST API v3. +* REST API - Fixed backwards compatibility of line_items meta in legacy REST API. + += 3.0.1 - 2017-04-06 = +* Fix - Show catalog hidden products within grouped products. +* Fix - Fade in the gallery in if no images are set or it's custom. +* Fix - Use wc_deprecated_function in WC_Deprecated_Hooks so notices aren't output in ajax requests. +* Fix - Added back the ability to include extra items to the System Status using the `woocommerce_system_status_environment_rows` filter. +* Fix - Coupon category restrictions and limits for variations. +* Fix - Allow shortcodes and HTML in variation descriptions like in 2.6. +* Fix - Unset post date when duplicating products. +* Fix - Show a sale price on variable products if on sale and all prices are the same. +* Fix - Corrected download links when a product has multiple downloads. +* Fix - Prevented potential errors if the product type was not posted for any reason on save. +* Fix - Updated `single-product/up-sells.php`, `loop/add-to-cart.php`, `loop/rating.php`, `checkout/form-billing.php`, and `content-product.php` template version to 3.0.0. +* Fix - Included clearfixes on billing and shipping field wrappers, +* Fix - Fixed styling of logs table in some languages. +* Fix - Fixed display of variation attributes on old orders. +* Fix - Use placeholder text for external products add to cart button text if left blank. +* Fix - Fallback to home URL if no shop page is set for system status security check for HTTPS. +* Fix - For variations, pull tax status and sold individually from the parent since there is no UI to set this at variation level. +* Fix - Moved cron emails to background processing to avoid multiple sends. +* Fix - Wrapped structured data in a hidden element when added to emails. +* Fix - Missing gateway information in queued emails. +* Fix - Fixed a bug that caused pages to permanently reload if "Default customer location" was set to "Geolocate (with page caching support)". +* Fix - When forcing shipping to billing, set the shipping fields in the order itself. +* Fix - Check for invalid objects in WC_Register_WP_Admin_Settings. +* Fix - Check for error object in wc_get_object_terms. +* Fix - Removed slashes in shipping meta data on the order edit screen. +* Fix - Prevented permalink rewrites for attributes with missing names. +* Fix - Fixed saving of meta data when multiple extensions use the `save_post` action. +* Fix - Allow search customers by ID in edit order screen. +* Fix - Prevents session data overwriting customer data on login. +* Fix - Fixed cross-sell column display and variation support. +* Fix - Fixed variable product stock syncing on save. +* Fix - Included try/catch wrapper to prevent issues with Select2. +* Fix - Prevented a bug that deleted all variations when the product type was change from variable to simple. +* Fix - Switched to WPDB to quicker update when syncing titles for variations. +* Fix - Exclude deprecated properties when loading a customer object. +* Fix - Fixed notices while trying to order again. +* Fix - Fixed notices when `$wpdb->prefix` is empty. +* Fix - Prevent errors when loading a product with an invalid download file types. +* REST API - Fixed missing array declaration in CRUD controller. +* REST API - Removed extra `exclude`, `include` and `search` parameters from taxes endpoint. +* REST API - Fixed variation description formatting. +* REST API - Fixed incorrect attribute check in products endpoint in Legacy REST API. +* REST API - Allow variation image to be unset. + += 3.0.0 - 2017-04-04 = +* New gallery on single product pages with better mobile support, using PhotoSwipe and Zoom. Declare support with add_theme_support() - wc-product-gallery-zoom, wc-product-gallery-lightbox, wc-product-gallery-slider +* Made the store notice dismissible on the frontend. +* Variable products no longer show striked out prices in combination with ranges for clarity when on sale. +* Prices no longer display as 'free' instead of 0, to fix issues with ranges and localization and for consistency. +* Improved structured product data by using JSON-LD instead of inline Microdata. +* Improved downloads list layout (template file). +* Respect stock status and prevent the "out of stock threshold" setting affecting existing in-stock products. +* Improved handling of shop page rewrite rules to allow subpages. +* Redirect to login after password reset. +* When using authorizations in PayPal Standard, automatically capture funds when the order goes processing/completed. +* On multisite, when a user logs into a store with an account on a site, but not the current site, rather than error, add the user to the current site as a customer. +* Show variable weights/dimensions even when parent values are not set. +* Automatically sort tax rates rather than allow clunky manual sorting. +* When deleting a tax rate class, remove it's tax rates. +* Made WC_Logger pluggable via wc_get_logger function. +* Use 'average rating' post meta for 'rating' product sorting option. +* Show better labels in nav menus metabox. +* Sort “Recently Viewed” products by the view order. +* Removed internal scroll from log viewer. +* Add reply-to to admin emails. +* Improved the zone setup flow. +* Made wc_get_wildcard_postcodes return the orignal postcode plus * since wildcards should match empty strings too. +* Use all paid statuses in $customer->get_total_spent(). +* Move location of billing email field to work with password managers. +* Option to restrict selling locations by country. +* Added tool to clear orphaned variations in system status. +* Remove checkbox options in system status tools and replace with constants. +* Added security section in system status report. +* Add image_url setting to PayPal Standard. +* Fixed attribute registration. Attributes are non-hierarchical by default (parent is not supported). +* Add sort parameter to checkout fields to aid with sorting per locale. +* Merged percent and percent product coupon types (they provide the same discount). +* Prevent payment details being cleared after update_checkout events. +* Performance - Converted _featured and _visibility meta data to terms for faster catalog queries. Upgrade routine handles migration. Developers may need to update queries to reflect this change. +* Includes product attributes archives links in "Additional Information" tab. +* Select2 has been upgraded to v4. +* Improved logging system for extensions. +* Tax suffix is now hidden on non-taxable products. +* Grouped products are linked from the parent rather than the children. Children can be in more than one group. +* Removed coupon usage link in coupons admin screen. +* Performance - Converted rating filters to visibility terms. +* Performance - Added visibility term for outofstock products to speed those queries up also. +* Performance - Introduced a new CRUD (create, read, update, delete) system for Products, Orders, Customers and Shipping Zones. +* Performance - Optimised variable product sync. Upper/lower price meta is no longer stored, just the main prices, if a child has weight, and if a child has dimensions. +* Performance - Removed WP_Query from up-sells.php and related.php and replaced with PHP foreach loop (since we already have the product IDs). +* Performance - Removed the feature where old orders get access to new downloads on product edit. Looping potentially thousands of orders to do this is too much of a performance burden for stores and this can sometimes be unexpected behavior too. This does however updates *edited* downloads. +* Performance - Removed 'items' column on orders screen due to loading excessive data. +* Performance - Deferred email sending for faster checkouts. Now uses CRON. +* API - New Rest API v2 with support for meta_data amongst other things. +* API - Removed last order from customers part of the API due to performance concerns - use orders endpoint instead. Other order data on the endpoint is now transient cached. +* API - Allow oAuth1.0a authentication using headers. +* API - New Shipping Zones endpoints. +* API - New variations endpoints. +* API - New settings endpoints. +* API - Payment gateways and shipping methods endpoints. +* API - Prevented the (broken) ability to manipulate variations directly on the products endpoints. +* CLI - New CLI which uses the REST API endpoints rather than it's own functions. +* Localization - Improved RTL support. +* Localization - Added a language independent permalink setting function. +* Localization - Added inline comments for placeholder strings. +* Localization - Added Nigerian and Pakistan Provinces to i18n/state. +* Localization - US and Poland postcode validation. +* To read more about this release, see our dev blog announcement here: http://wp.me/p6wtcw-Uo + += 2.6.14 - 2017-02-02 = +* Fix - Ensure product exists in wc_update_product_stock. +* Fix - Send emails using the site language. +* Fix - Remove tilde typo. +* Fix - Fixed notice in get_rating_count. +* Tweak - Define arg and return data types, added extra descriptions, and correctly cast IDs in the Rest API. +* Tweak - Handle custom error data in WC_REST_Exception. +* Tweak - Display conflicted product ID when using a duplicate SKU via the API. +* Localization - Add Finnish defaults to the installer. + += 2.6.13 - 2017-01-18 = +* Fix - Demo store banner styling in 2017. +* Fix - Removed default instructions from COD, BACS and Check gateways so displayed messages can be unset. +* Fix - Made variation options update on first load. +* Localization - Added Romanian locale to the installer. + += 2.6.12 - 2017-01-12 = +* Fix - Make images shown up on pageload when using ajax variations. +* Fix - Allow variations options to be deselected in IE11. +* Fix - Disabled-button and pagination styling in 2017. +* Fix - PHP 7.1 compatibility issues with non-numeric math operations. +* Fix - Fix notices in abstract class when price is empty. + += 2.6.11 - 2016-12-22 = +* Fix - Variation form compatibility with quotes in attribute values, and initial variation image fadeIn on certain configs. + += 2.6.10 - 2016-12-22 = +* Fix - Flat rate no class costs when no shipping classes exist. +* Fix - Returned REST API coupon expiry date. +* Fix - reviews_allowed being set to false in Rest API. +* Fix - Sales date series for some custom ranges. +* Fix - Missing attributes when an option is chosen by default on variations. This was the result of a Firefox 50 compatibility fix. In order to support both Firefox, Chrome, IE, and Edge we've done some refactoring of the variation add to cart scripts. +* Tweak - Updated Geo IP API services. +* Dev - Added support for WP VIP/VIP GO GEO IP headers. +* Dev - API - Throw error messages when product image ID is not a valid WordPress attachment ID. + += 2.6.9 - 2016-12-07 = +* Theme - Added support for Twenty Seventeen Theme. +* Fix - Excluded webhook delivery logs from comments count. +* Fix - Included password strength meter in "Lost Password" page. +* Fix - Order fee currency in admin screen. +* Fix - Variation selection on Firefox 40. +* Fix - Don't prevent submission when table is not found on cart. +* Fix - Improved layered nav counts on attribute archives. +* Fix - Fixed pagination when removing layered nav items via widget. +* Fix - Default BE tax rate. +* Fix - Downloads should store variation ID rather than product if set. Also fixes link on account page. +* Fix - Use wp_list_sort instead of _usort_terms_by_ID to be compatible with 4.7. +* Fix - Only return empty string if empty for weight and dimension functions. +* Fix - Added correct fallbacks for logout/lost password URLs when endpoints are not defined. +* Security - Wrapped admin tax rate table values in _escape to thwart evil CSVs an admin user could upload. Vulnerability was discovered by Fortinet’s FortiGuard Labs. +* Dev - API - Only update categories menu order and display if defined. +* Dev - Fixed when should deliver wp_trash_post webhooks. + += 2.6.8 - 2016-11-10 = +* Fix - REQUEST_URI was missing a trailing slash when being compared in the cache prevention functions. +* Fix - Prevent issues when sending empty prices to PayPal. +* Fix - Invalid email check. +* Tweak - New extensions screen. + += 2.6.7 - 2016-10-26 = +* Fix - Use FLOOR and CEIL to get price filter values. Fixes the issue where max price is capped at 99. +* Fix - Hide "Sales this month" information from Dashboard widget for users that don't have `view_woocommerce_reports` capability. +* Fix - Remove notices only once on cart so subsequent notices do not remove older notices. +* Tweak - Improve credit card fields for better mobile experience. + += 2.6.6 - 2016-10-20 = +* Fix - Conflict with Local Pickup Plus extension due to 2.7.x code in has_shipping_method(). +* Fix - Shipping method display order on frontend. + += 2.6.5 - 2016-10-19 = +* Fix - Shipping classes URL in admin. +* Fix - Notice in reports when using custom date ranges. +* Fix - When checking needs_shipping, ignore anything after : in the method ID. +* Fix - Allow has_shipping_method to work with instances. +* Fix - Potential notice in wc_add_to_cart_message(). +* Fix - Prevent notice in wpdb_table_fix if termmeta table is not used. +* Fix - Payment method box fixes e.g. maintain previously selected payment method after update. +* Fix - Prevent multiple password validation methods at once on my account page. +* Fix - Ship to specific counties option had no effect. +* Fix - Broken Webhook delivery due to use of post_date_gmt which does not exist for drafts. +* Fix - Use method title in admin shipping dropdown. +* Fix - Fixed downloadable variable product URL. +* Fix - Handle object when generate_cart_id is used to prevent notices. +* Fix - Set header link color in emails. +* Fix - Rest of the world ID 0 zone handling when using CRUD classes. +* Fix - Cast prices as decimal when querying prices in price filter widget. +* Fix - API - Fix coupon description field. +* Fix - API - ID needs to be capitalized to allow correct sorting. +* Fix - API - Fixed undefined order ID. +* Fix - API - Allow API to save refund reason. +* Fix - API - Resolved encoding issues with attribute and variation slugs. +* Fix - API - get_attributes should return term name, not slug. +* Fix - API - Product "filter" and "sku" parameters. +* Fix - Handle info notices in cart, not just error messages. +* Fix - Don't remove hyphens in attribute labels. +* Fix - Start sales on variations after they are saved, if applicable. +* Fix - Made the text showing max variations you can link match the actual filtered value. +* Fix - Add missing tables to wpmu_drop_tables function. +* Fix - When syncing variation stock, ensure post is a variation. +* Fix - Resolved some sales by date sum issues. +* Fix - Fix cart update in IE when enter key is pressed. +* Fix - Variation is_on_backorder when parent manages stock. +* Fix - Fix variation script malfunctioning when show_option_none arg is set to false. +* Fix - Fire tokenisation event on load for pay page. +* Fix - Populate attribute dropdown when empty. +* Fix - Fix email check on my account page. +* Fix - Send processing email on on-hold to processing transition. +* Fix - Incompatibility with SQLite databases. +* Fix - KGS and ISK currency symbols. +* Tweak - Password reset now uses WP functions. +* Tweak - Format US 9-digit postcodes. + += 2.6.4 - 2016-07-26 = +* Fix - Security - Only allow image MIME type upload via REST APIs. +* Fix - Shipping method title display in COD settings. +* Fix - Order date input in Edge browser. +* Fix - Ensure value is not null in variations to support empty show_option_none setting. +* Fix - get_the_title does not need escape in grouped template file. +* Fix - Ensure WC_ROUNDING_PRECISION is defined and use it as a low precision boundary in wc_get_rounding_precision(). +* Fix - Response body should be a string in webhook class. +* Fix - Use h2 instead of h3 headings in profile screen. +* Dev - API - Allow Allow meta_key/value filters for products. +* Dev - CLI - Explode tags and category IDs to allow multiple comma separated values. +* Dev - add $order arg to woocommerce_admin_order_item_class and woocommerce_admin_html_order_item_class filters. + += 2.6.3 - 2016-07-19 = +* Fix - Security - Escape captions in product-thumbnail and product-image templates (template versions have been bumped). +* Fix - Fixed how we calculate shipping tax rates when using more than one tax class. +* Fix - When duplicating product variations, set title, name, and guid. +* Fix - Normalized 'read more' buttons. +* Fix - Add to cart notices for grouped products. +* Fix - Do not sanitize passwords in the settings API. +* Fix - Handle shipping zone location range conversion during update (dashes to ...). +* Fix - Always remove commas while processing flat rate costs. +* Fix - Ensures account page layout is only applied to desktop-sized displays. +* Fix - When getting layered nav counts, take search parameters into consideration. +* Fix - Free shipping show/hide javascript. +* Fix - Strip hash characters when exporting reports. +* Fix - Use permission id to revoke access to downloads to prevent removing wrong rows. +* Fix - When duplicating product variations, set title, name, and guid. +* Fix - Set more appropriate default rounding precision based on currency decimal places. +* Fix - Fix message styles for empty carts. +* Fix - Fixed the load of the WC_Email_Customer_On_Hold_Order class. +* Fix - Don't perform cart update on search submit. +* Dev - API - Added support for WP REST API with custom URL prefixes. +* Dev - API - Delete variations when deleting a variable product. +* Dev - API - Fixed how we check for product types. +* Dev - Added woocommerce_cart_id filter. +* Dev - Add shortcode name param to shortcode_atts function calls. +* Dev - Post custom data when fetching a variation via ajax. +* Dev - Include child prices in grouped_price_html filter. +* Dev - Allow filtering of variation stock quantity. +* Dev - Added $_product argument to 'woocommerce_restock_refunded_item' hook. +* Dev - Added a filter hook for the wc_ajax endpoint url. +* Tweak - Include account page link in new customer account emails. +* Tweak - Updated all URLs from WooThemes.com to WooCommerce.com. +* Tweak - Cache the result of WC_Comments::wp_count_comments() in a transient (improves performance). + += 2.6.2 - 2016-06-30 = +* Fix - Set max index length on woocommerce_payment_tokenmeta table for utf8mb4 support. +* Fix - is_available check for legacy shipping methods. +* Fix - wc_add_to_cart_message() when non-array is passed. +* Fix - Maximum coupon check should allow the 'maximum' value. +* Fix - Product coupon logic to avoid applying non-applicable coupons. +* Fix - Potential notices when leaving out 'default' field for shipping instances. +* Fix - wp_cache_flush after term meta migration/update. +* Fix - wc_add_to_cart_message() when non-array is passed. +* Fix - woocommerce_redirect_single_search_result type check was incorrect. +* Fix - Javascript show/hide of option in free shipping method. +* Fix - Convert ellipsis to three periods when saving postcodes. +* Fix - Prevent get_terms returning duplicates. +* Fix - Removed non-existent country (Netherlands Antilles) from https://en.wikipedia.org/wiki/ISO_3166-1. +* Fix - Grouped product range display when child is free. +* Fix - Remove discount when checking free shipping min amount. +* Fix - Prevent blocking the same element multiple times on cart page. +* Fix - Don't sync ratings right after a new comment to prevent rating sync whilst rating meta does not exist yet. +* Fix - Fix product RSS feeds when using shop base. +* Fix - woocommerce_local_pickup_methods comparison by stripping instance IDs before the check. +* Fix - During password resets, use cookie to store reset key and user login to avoid them being exposed in the URL/referer headers. +* Dev - API - Fixed variable product stock at product level. +* Dev - CLI - Introduces `woocommerce_cli_get_product_variable_types` filter. +* Dev - Allow notices to be grouped on checkout after certain events. +* Dev - API - Allows save images by ID with product variations. +* Tweak - Made customer pay link display if order needs_payment() rather than checking pending status. +* Tweak - Zones - Wording clarifications. +* Tweak - Zones - Match zones with postcodes but no country. +* Tweak - Zones - Match zones with no regions as 'everywhere'. +* Tweak - Added view_admin_dashboard cap for disabling the admin access restriction in custom roles. +* Tweak - Revised stock display based on feedback to hide 'in stock' message if stock management is off and only show available on backorder if notifying customer. +* Tweak - Allow external product SKUs. +* Tweak - PT (Portugal) and JP (Japan) postcode formats. +* Tweak - Sort products from the `[product_category]` shortcode by menu order. +* Tweak - Improve wc_orders_count() performance by running a query to count only posts of the given status. +* Tweak - To allow my account page tabs to be disabled without code, you can now set the endpoint value to a blank string. + += 2.6.1 - 2016-06-16 = +* Fix - Added missing localized format for line taxes in orders screen to prevent total miscalculation in manual orders. +* Fix - Improved the hour and time fields validation pattern on the orders screen. +* Fix - PayPal does not allow free products, but paid shipping. Workaround by sending shipping as a line item if it is the only cost. +* Fix - SKUs prop on products shortcode. +* Fix - Layered nav counts when term_id does not match term_taxonomy_id (before splitting). +* Fix - Fixed referer links from cart messages in WP 4.4. +* Fix - Fix the showing/hiding of panels when terms do not exist by using wc_get_product_types() for retrieving product types. +* Dev - content-product.php and content-product_cat.php contained the wrong version. +* Dev - Show "matching zone" notice on the frontend when shipping debug mode is on. +* Dev - Restored missing WC_Settings_API::init_form_fields() method to prevent potential errors in 3rd party gateways. +* Dev - API - Fixed returned data from product images (changed `title` to `name`). +* Dev - API - Fixed products schema for `grouped_products`. +* Dev - API - Fixed products attribute options when contains `,`. +* Tweak - Hide 'payment methods' screen if no methods support it. +* Tweak - If shipping method count changes, reset to default. +* Tweak - Avoid normalization of zone postcodes so wildcard matching can be performed on postcodes with spaces. E.g. SP1 * +* Tweak - Allow max_fee in addition to min_fee in flat rate costs fields. +* Tweak - Wrap order_schema_markup() output in hidden div in case script tag is stripped. + += 2.6.0 - 2016-06-14 = +* Feature - Introduced Shipping Zone functionality, and re-usable instance based shipping methods. +* Feature - Tabbed "My Account" area. +* Feature - Cart operations now use ajax (item quantities/remove, coupon apply/remove, shipping options). +* Feature - Layered nav; filter by rating. +* Feature - On-hold order emails. +* Dev - All new REST API based on the WP REST API. The old WC REST API is still available, but the new one is preferred. +* Dev - Added ability for shipping methods to store meta data to the order. +* Dev - Added Payment Gateway Tokenization API for storing and retrieving tokens in a standardized manner. +* Dev - Migrated custom term meta implementation to WP Term Meta. +* Dev - Added new wc_get_orders() function to get order objects and ids instead of direct get_posts() calls. +* Dev - Made coupon optional in cart has_discount() method. +* Dev - Made the review template more editable. +* Dev - Allowed product constructors to throw exceptions if invalid. +* Dev - Wrapped currency symbols in a span to allow styling or replacement. +* Fix - Update download permission user and email when changed. +* Fix - Fixed shipping method unregistration. +* Fix - Stopped create and update webhooks firing at the same time for products. +* Fix - Allow COD to set on-hold status if the order contains downloads. +* Fix - Force CURL to use TLS 1.2 for PayPal connections. +* Tweak - Improved lost password flow. +* Tweak - Show payment dates on order screen. +* Tweak - Ignore catalog visibility on products shortcode when specifying IDs or SKUs. +* Tweak - Added context to checkout error messages. +* Tweak - Added SKU field to grouped products. +* Tweak - Moved SKU field to inventory tab. +* Tweak - Support qty display in cart messages. +* Tweak - Hide min order amount field when not needed in shipping settings. +* Tweak - If shipping < 999.99, use 'shipping' arg when passing values to PayPal. +* Tweak - Show net sales on dashboard. +* Tweak - Replaced credit card icons with SVG. +* Tweak - Enqueue scripts on pages with checkout shortcodes. +* Tweak - Color code the manual, system and customer notes. +* Tweak - Layered Nav Refactoring to improve performance. +* Tweak - Removed tag/cat classes from loops since WP does the same. +* Tweak - Added hash check for orders so that if the cart changes before payment, a new order is made. +* Tweak - Removed unused 'view mode' under screen options. +* Tweak - Added 110 new currencies (including Bitcoin). +* Tweak - New background updater for data upgrades. +* Tweak - Blank slates in admin post screens. +* Tweak - Added blockui when variations are being retrieved via ajax. +* Tweak - Hide empty taxes by default (filterable). +* Tweak - Allow failed orders to be edited. +* Tweak - If there are no shipping methods setup, don’t prompt for shipping at checkout. +* Tweak - Allowed country exclusion, rather than just inclusion, in ‘sell to’ setting. +* Lots, lots more - [see the comparison here](https://github.com/woocommerce/woocommerce/compare/2.5.5...2.6.0). + += 2.5.5 - 2016-03-11 = +* Fix - Before running dbdelta, drop indexes to prevent duplicate key notices. +* Fix - Prevent notice when unsetting terms on product edit screen. +* Tweak - zeroclipboard fallback for firefox on system status report. +* Tweak - Check valid product ID is provided on add_to_cart shortcode. + += 2.5.4 - 2016-03-10 = +* Fix - Fix table creation when using utf8mb4 charset. +* Fix - Have wp_insert_post return WP_Error when creating our coupon, so the is_wp_error check can catch it. +* Fix - Clear sale price on save if sale is no longer valid. +* Fix - Round refund values to ensure refunds can be performed. +* Fix - When getting coupon by code used twice, latest should be queried. +* Fix - CLI improvements for setting up variations and deleting orders. +* Fix - Allow big selects when getting variations to support larger queries. +* Fix - Trigger webhook when user edits addresses on frontend. +* Fix - Hide shipping row when calculator is disabled, and shipping costs are hidden. +* Fix - Unset deleted attributes when updating products. +* Tweak - Update date for paid orders during non-manual updates only. +* Tweak - wc_get_page_permalink - if the page ID is not set, redirect home instead to prevent white screens. +* Tweak - Remove log dir from system status report. +* Tweak - When sorting by date, fallback to ID. +* Tweak - Rename pay link for clarity. +* Tweak - Provide a fallback message if copying to the clipboard fails in system status report. + += 2.5.3 - 2016-03-01 = +* Fix - Correct the 'unavailable template' call for variations so the message is displayed correctly, fixing a JS error. +* Fix - Add 'media-models' dependency to write panel scripts. +* Fix - Fix hide empty check in category walkers. +* Fix - Current class fix on some servers when empty. +* Fix - Multibyte safe trim string function. +* Fix - Prevent a notice by stopping a loop in woocommerce_products_will_display from stomping on other variables. +* Fix - If an attribute meta key is not set, technically its 'any', so should match. Prevents issues when meta data is missing after renaming attributes. +* Fix - Make wc_get_product_variation_attributes ignore non variation attributes. +* Fix - Notice when no order notes exist. +* Fix - Removed extra tab from plain email shipping address. +* Fix - Round shipping after tax calculation instead of before to prevent wrong taxes being calculated. +* Fix - State input box was not reappearing when switching from a hidden input to a text input. +* Fix - Don't duplicate rating and review counts. +* Fix - CLI - Allow setting of a single category. +* Fix - API - Replace term_taxonomy_id for term_id whilst creating/editing terms. +* Fix - API - Fix parent_id and menu_order for variations. +* Fix - Combine update post calls when update_status is ran. +* Fix - Total number of comments in the admin panel. +* Tweak - Show customer details for logged in users only on thanks page to prevent customer details being revealed if someone finds out the URL. +* Tweak - Wrap status report in backticks to stop people breaking .org forums. +* Tweak - Error handling for screen ids. +* Tweak - Use $wpdb->replace instead of doing a select and then deciding to do an update or insert in session handler. +* Tweak - Added check for private WooCommerce pages in status report. +* Tweak - Transactional emails for failed -> on hold. +* Dev - Include new triggers when removing and adding the password strength meter. +* Dev - Allow pass objects and arrays as webhook callbacks. + += 2.5.2 - 2016-02-01 = +* Fix - Compatibility with w3 total cache inline minification. +* Fix - Remove stock bw compat code which was preventing manage stock being disabled at variation level. +* Fix - When calculating shipping total, force rounding. +* Fix - Make save button clickable in tax rate table after using autocomplete field. +* Fix - Fix passed image_size variable in email templates. +* Fix - Don't show purchase note to admin in emails. +* Fix - Fix 'hide empty' setting in category widget
. +* Fix - Prevent notice in get_allowed_countries. +* Fix - Prevent add-to-cart querystring in pagination links. +* Tweak - Allow propagation in variation script. +* Tweak - Product image alt text. +* Tweak - Remove notice and add styling for add payment page. +* Tweak - Set input margin and label display for compatibility with themes using bootstrap CSS. +* Tweak - Add context to category term localization. +* Tweak - Moved cart URL functions to core-functions file to make them available in admin area. +* Tweak - Added password hint text and error messages when showing the password strength meter in forms. +* Tweak - Added Saudi Riyal currency. +* Tweak - Added Russian Ruble symbol. +* Tweak - When COOKIEPATH is an empty string, set to '/' so cookies work across all pages. +* Dev - Template - Pass $category into wc_product_cat_class() in content-product_cat.php + += 2.5.1 - 2016-01-25 = +* Fix - Remove usage of get_currentuserinfo() which is deprecated in WordPress 4.5. +* Fix - Fix responsive product sizes when the columns class is missing. +* Fix - Fix function exists check for woocommerce_template_loop_category_title. +* Fix - check_version on all requests so that the installer runs after remote plugin updates. +* Fix - Only show the "add payment method" button when needed, and check for required fields on the add payment method page. +* Fix - Correctly block UI to prevent attribute issues in backend when adding multiple attributes in quick succession. +* Fix - Show SKU in admin emails. +* Fix - Don't show downloads in admin emails. +* Fix - Fix query/missing variable in validate_user_usage_limit function. +* Fix - Prevent endless loading on checkout when reload_checkout session variable was used. +* Fix - Correctly display html entities in tax screen autocomplete. +* Fix - Do sales reports based on refund line items rather than fully refunded orders to prevent double refunds being reported. +* Fix - Qty button can be hidden for variable products sold individually. +* Fix - Show the taxable country rather than base country in "estimated for" text during checkout. +* Fix - Prevent select2 gaining focus on IOS7 scroll. +* Fix - API - Fix indexes on decimal and thousand values. +* Tweak - Clear cron jobs on uninstall
. +* Tweak - Don't disable place order button on checkout if a weak password is used. +* Tweak - Added password strength meter in lost password and edit accout pages. +* Tweak - Pass $args to woocommerce_dropdown_variation_attribute_options_html hook. + += 2.5.0 - 2016-01-18 = +* Feature - New default session handler. Uses custom table to store data rather than the options table for performance and scalability reasons. https://woocommerce.wordpress.com/2015/10/07/new-session-handler-in-2-5/ +* Feature - New tax settings UI - faster, enhanced with ajax, searchable. +* Feature - WP CLI Support. https://woocommerce.wordpress.com/2015/10/01/sneak-peek-wp-cli-support-in-woocommerce/ +* Feature - Added terms and conditions checkbox to pay page. +* Feature - Password strength indicators. +* Feature - Added 'pay' link to order screen. +* Feature - Added admin order/payment failed notification. +* Fix - Check for existence of global attribute when you get_attributes() for a product. +* Fix - Show order by template on product search. +* Fix - Search variation skus in backend search. +* Tweak - For coupons with category restrictions, respect the category hierarchy. +* Tweak - Added wc_array_cartesian function to generate variations in a logical order. +* Tweak - Revised email settings screens to show emails in a table and avoid a long sub-nav. +* Tweak - Default customer role capabilities. +* Tweak - Expire mini-cart cache after 24 hours. +* Tweak - Improved refund error messages in PayPal Standard. +* Tweak - Removed language pack downloader in favour of translate.wordpress.org. +* Tweak - Added onboarding wizard button to the contextual help so it can be accessed again. +* Tweak - When a WordPress user is deleted, turn any orders they have into Guest orders. +* Tweak - When calculating order taxes, respect tax settings and default to base country. +* Tweak - Fade in variation images to avoid flicker during load. +* Tweak - Display 2 averages on report (net and gross). +* Tweak - Improve product search and use WPDB instead of several get_posts queries for performance. +* Tweak - Use SKU for stock order notes. +* Tweak - Added order notes for manual email sends. +* Tweak - Sanitize shipping method labels/titles. +* Tweak - Only display the coupon form on the checkout if a coupon hasn't been applied. +* Tweak - Added billing address column to order screen (off for new users). +* Tweak - Created function to disable author archives for customers. +* Tweak - When updating cart hash, refresh all open tabs. +* Tweak - Use new "question" mark icon font for help tips. +* Tweak - Improved review verification status retrieval. +* Tweak - Improve appearance when only 1 gateway is active. +* Tweak - Aligned terms box left and added required asterisk. +* Tweak - Removed dropdown display mode for cart shipping methods - radios are more flexible. +* Dev - API - Added /products/shipping_classes endpoint. +* Dev - API - Added support to POST, PUT, and DELETE categories and tags. +* Dev - API - Added support to filter products by tag, category, shipping class, and attribute. +* Dev - API - Added tax and tax_class endpoints. +* Dev - Template - New star ratings. The old one was 5 separate buttons. This new one consolidates the 5 options into one element making it leaner visually and more intuitive. Works in IE9+ with a graceful degradation for IE8. +* Dev - Template - Added `data-title` attribute to cart table. +* Dev - Template - Product archive anchors are now hooked into templates rather than hard coded. +* Dev - Template - Added template files for the customer details list in emails. emails/email-customer-details.php +* Dev - Template - Revised single variation cart template. Template files now exist for variations, and the cart button will display (disabled) when no selections are made. +* Dev - Template - Made "my orders" columns fully customizable with filters. +* Dev - Template - Unified email template order details tables to use a single template. +* Dev - Allow wc_clean to support arrays. +* Dev - Added a manual update trigger for checkout. +* Dev - Added woocommerce_is_price_filter_active filter to Query class. +* Dev - Replaced some cart methods with dedicated functions. e.g. wc_ship_to_billing_address_only(). +* Localisation - Add Kenyan currency and symbol. + += 2.4.13 - 2016-01-11 = +* Fix - Potential redirect loop when using 'unforce ssl' setting and a https home URL. +* Fix - Escape option names when cleaning up sessions. + += 2.4.12 - 2015-12-9 = * Fix - 4.4 - Permission error when editing attribute terms. * Fix - 4.4 - Missing variation images when wp_get_attachment_image_srcset() returns false instead of a string. * Fix - 4.4 - Use post-thumbnail size in admin to avoid srcset. * Fix - Webhook status not changed after save with active object-cache. -= 2.4.11 - 7/12/2015 = += 2.4.11 - 2015-12-7 = * Fix - WordPress 4.4 support. * Fix - Removes Switzerland from EU VAT definition
. * Fix - Fix auth endpoint urls. @@ -22,13 +657,13 @@ * Tweak - 4.4 - Support for srcset/sizes and responsive images. * Tweak - 4.4 - Support for Twenty Sixteen. -= 2.4.10 - 10/11/2015 = += 2.4.10 - 2015-11-10 = * Fix - Geo IP - Correctly parse .dat files. * Fix - Geo IP - Ensure WC_Logger class exists before logging errors. * Fix - Geo IP - Prevent notices in ipv6 methods. * Tweak - Add information about credit card address for Simplify Commerce. -= 2.4.9 - 09/11/2015 = += 2.4.9 - 2015-11-09 = * Fix - Check abspath exists in more files to prevent errors on direct access. * Fix - Hide SQL errors during ajax requests. * Fix - Fixed redirection loop on customizer screen. @@ -37,9 +672,9 @@ * Fix - Check for child themes in System Status. * Fix - API - Warnings when create attributes. * Fix - System Report: Template version check path. -* Fix - Potential XSS within price.php fixed with escape on get_price() (would require edit/admin permissions to take advantage of). Discovered by FortiGuard Labs (http://www.fortiguard.com/). Template version has been bumped. +* Fix - Potential XSS within price.php fixed with escape on get_price() (would require edit/admin permissions to take advantage of). Discovered by FortiGuard Labs (https://www.fortiguard.com/). Template version has been bumped. -= 2.4.8 - 26/10/2015 = += 2.4.8 - 2015-10-26 = * Fix - Help tips in variations admin. * Fix - API - Fixed customer count method. * Fix - Locale switching for city field. @@ -60,7 +695,7 @@ * Tweak - API - Allow variable products to get retrieved by SKU. * Tweak - API - Allow edit variations without define the product type to variable. -= 2.4.7 - 21/09/2015 = += 2.4.7 - 2015-09-21 = * Fix - Handle Switzerland in get_european_union_countries. * Fix - For geolocation with static cache support, ensure hash is appended during form submission. * Fix - To prevent discounts being applied in 'random' order (based on order added to cart), sort cart items based on subtotal during calculate_totals. @@ -75,7 +710,7 @@ * Fix - Added monthly cron schedule. * Fix - Remove use of 'input' event in checkout scripts to prevent IE11 triggering updates on placeholder change. * Fix - AJAX variations not being found in some cases when product version was < 2.4, but attributes were updated after sync(). -* Fix - Changed the way variable product prices get cached for greater plugin compatibility. See http://wp.me/p6wtcw-5x +* Fix - Changed the way variable product prices get cached for greater plugin compatibility. See https://wp.me/p6wtcw-5x * Fix - Highlighting of reports chart. * Fix - Network activated plugins not showing up in system status report. * Fix - Tax fields showing on bulk/quick edit when disabled the tax system. @@ -98,7 +733,7 @@ * Template - Removed 'Payment' heading in `templates/checkout/form-pay.php`. * Template - Removed unnecessary clearing div in `templates/checkout/payment.php`. -= 2.4.6 - 24/08/2015 = += 2.4.6 - 2015-08-24 = * Fix - menu_order notices on IIS. * Fix - Grouped product is_purchasable check during add to cart. * Fix - Subscriptions 2.0 (unreleased) compatibility. @@ -117,7 +752,7 @@ * Tweak - WC Setup wizard: Add spinner/loading indication between onboarding steps. * Tweak - Allow HTML in store notice. -= 2.4.5 - 20/08/2015 = += 2.4.5 - 2015-08-20 = * Fix - Global text based attribute saving on product page. * Fix - save_account_details should check display name of current user. * Fix - Show the right 'no shipping available' message when a country does not have states. @@ -136,7 +771,7 @@ * Tweak - Improved download numbering in emails and order page. * Tweak - Allowed users to install translations for the current language during the Setup Wizard. -= 2.4.4 - 14/08/2015 = += 2.4.4 - 2015-08-14 = * Fix - Ajax variation handling when 'any' attribute is set. * Fix - Run html_entity_decode over text attributes to fix problems with quote characters. * Fix - COD: remove shipping check if the cart is 100% virtual. @@ -144,7 +779,7 @@ * Tweak - Include attribute archives support in the breadcrumbs. * Tweak - woocommerce_variable_children_args hook. -= 2.4.3 - 12/08/2015 = += 2.4.3 - 2015-08-12 = * Fix - Query within wc_customer_bought_product(). * Fix - Tab hiding with some theme markup. * Fix - Ajax variations: stripslashes to fix attributes with quotes. @@ -155,7 +790,7 @@ * Tweak - When merging shipping taxes with a shipping rate taxes, ensure shipping rate taxes is not malformed. * Tweak - Improved refund email events and woocommerce_order_fully_refunded hook. -= 2.4.2 - 11/08/2015 = += 2.4.2 - 2015-08-11 = * Fix - If all variations are out of stock, maintain pricing display. * Fix - Prevent double add to cart due to ajax endpoints. * Fix - ordering_args in product_category shortcode. @@ -167,12 +802,12 @@ * Tweak - Hide get_formatted_legacy notices when doing ajax. * Tweak - use shop_single instead of full image size for variations. -= 2.4.1 - 10/08/2015 = += 2.4.1 - 2015-08-10 = * Fix - Tweaked the 2.4 upgrade routine to disable refund emails during update. * Fix - Notices when calling get_shipping_classes(). * Fix - Added upgrade routine to ensure _stock_status meta exists for variations created before WooCommerce 2.2 -= 2.4.0 - 10/08/2015 = += 2.4.0 - 2015-08-10 = * Feature - Onboarding/setup wizard for new users to handle basic store settings and installation. * Feature - Improved help tabs with inline video tutorials where applicable. * Feature - New AJAX powered variations interface to improve edit product page loading times and posting large amounts of data. @@ -211,14 +846,14 @@ * Dev - API - Deprecated /product/sku endpoint from v3. * Dev - API - Created the /products/id/orders endpoint to fetch orders containing a specific product. * Localisation - Added Argentine currency and provinces. -* [Various other small fixes and enhancements.](https://github.com/woothemes/woocommerce/issues?q=is%3Aissue+milestone%3A%222.4+Helpful+Hedgehog%22+is%3Aclosed) +* [Various other small fixes and enhancements.](https://github.com/woocommerce/woocommerce/issues?q=is%3Aissue+milestone%3A%222.4+Helpful+Hedgehog%22+is%3Aclosed) -= 2.3.13 - 07/07/2015 = += 2.3.13 - 2015-07-07 = * Fix - Improved the email settings save and tabs for 3rd party plugins. * Fix - Datepicker range for variations. -= 2.3.12 - 06/07/2015 = -* Fix - Fixed Google Chrome forcing to use SSL. This can cause some issues on websites behind load balancers or reverse proxies. [Read more](http://docs.woothemes.com/document/ssl-and-https/#websites-behind-load-balancers-or-reverse-proxies). += 2.3.12 - 2015-07-06 = +* Fix - Fixed Google Chrome forcing to use SSL. This can cause some issues on websites behind load balancers or reverse proxies. [Read more](https://docs.woocommerce.com/document/ssl-and-https/#websites-behind-load-balancers-or-reverse-proxies). * Fix - Escaped shop url in empty cart template. * Fix - Escaped product tabs titles. * Fix - Removed deprecated PHP4 constructor on Widget classes. @@ -230,7 +865,7 @@ * Fix - Flat rate shipping costs should ignore virtual items. * Tweak - Keep product quantity when happens some error while add product on the cart. -= 2.3.11 - 10/06/2015 = += 2.3.11 - 2015-06-10 = * Fix - Check if rating is enabled before check if rating is required to a review. * Fix - get_discounted_price needs to check if taxes are enabled. * Fix - Fixed filetype check for digital downloads. @@ -244,7 +879,7 @@ * Fix - API - Fixed the sanitization for downloadable files on products endpoint. * Tweak - woocommerce_downloadable_file_exists filter. -= 2.3.10 - 01/06/2015 = += 2.3.10 - 2015-06-01 = * Fix - Fixed theme check notice for core supported themes. * Fix - Add RTL direction to emails. * Fix - Fixed product category media upload modal. @@ -285,7 +920,7 @@ * Tweak - Error prevention when showing customer orders on the frontend. * Tweak - Added PH states. -= 2.3.9 - 19/05/2015 = += 2.3.9 - 2015-05-19 = * Fix - Fixed language upgrader verification. * Fix - Refund reporting #8010 * Fix - Redirect after bulk editing. @@ -298,7 +933,7 @@ * Fix - Move action to prevent infinite recursion on login/restoring saved carts. * Fix - Update PrettyPhoto to 3.1.6 to resolve XSS security issue https://github.com/scaron/prettyphoto/issues/149 -= 2.3.8 - 20/04/2015 = += 2.3.8 - 2015-04-20 = * Fix - Ensure coupon taxes are reset when calculating totals. * Fix - Downloads url sanitization to work correctly with shortcodes and urls. * Fix - State/Country select2 issues with Internet Explorer. @@ -324,7 +959,7 @@ * Tweak - Only automatically cancel orders created via checkout + allow post_parent to be set. * Tweak - Deny all access to revisions through API. -= 2.3.7 - 18/03/2015 = += 2.3.7 - 2015-03-18 = * Fix - Allow saving of empty download expiry date on orders. * Fix - get_total_discount() function with certain tax setups. * Fix - stock management for variations for Products API. @@ -335,7 +970,7 @@ * Tweak - Revised how discounts/discount taxes are stored for consistency. Always store ex. tax to make data retrieval easier, and to ensure totals are correct after settings changes. Backwards compatibility maintained through use of order versioning. * Tweak - Delete product attachments when the Products API fails. -= 2.3.6 - 13/03/2015 = += 2.3.6 - 2015-03-13 = * Fix - Removal of coupons containing spaces. * Fix - Unclosed div in profile page. * Fix - Export report CSV. @@ -350,7 +985,7 @@ * Tweak - Use 30 days instead of year for transients to avoid bugs in memcache plugins. * Tweak - Add reports menu item if user can access reports but not the main WC section. * Tweak - Improve grouped product quantity inputs. -* Tweak - Load the persistant cart if cart is empty. +* Tweak - Load the persistent cart if cart is empty. * Tweak - Prevent cart being cleared when accessing the login page. * Tweak - Shipping calculator - Made state/postcode respect country locale like checkout. * Tweak - Move default customer location to general settings tab. @@ -364,7 +999,7 @@ * Tweak - Increase wc_get_weight precision. * Dev - API - reports/sales now also returns total refunds. -= 2.3.5 - 20/02/2015 = += 2.3.5 - 2015-02-20 = * Fix - Plain text address formatting. * Fix - Detect shortcodes when saving URLs. * Fix - Unhook wc_page_endpoint_title after it is ran once (main page title). @@ -376,7 +1011,7 @@ * Tweak - Improve category coupon message. * Tweak - Don't download GeoIP Database until geolocation option is enabled in settings. -= 2.3.4 - 17/02/2015 = += 2.3.4 - 2015-02-17 = * Fix - limit_usage_to_x_items option in coupons. * Fix - Run coupon codes through html_entity_decode. * Fix - Tax by code report for refunds. @@ -404,7 +1039,7 @@ * Tweak - Restock items AFTER refund, not before. * Tweak - If logged in, populate customer data from user meta. -= 2.3.3 - 12/02/2015 = += 2.3.3 - 2015-02-12 = * Fix - Potential notice with preg_match wildcard search, if used incorrectly. * Fix - Typo in get_from_name method. * Fix - Fix errors during checkout when mb_convert_encoding() is not supported. @@ -413,7 +1048,7 @@ * Fix - Query in uninstall script. * Tweak - Only run the uninstaller if the "Uninstall on Delete" option is checked in system status. -= 2.3.2 - 12/02/2015 = += 2.3.2 - 2015-02-12 = * Fix - Item meta removal query in order class. * Fix - Pass correct shipping cost to PayPal. * Fix - Flat rate extra costs when costs are an array. @@ -423,7 +1058,7 @@ * Fix - Average product rating when ratings are not required. * Fix - attribute_public option. -= 2.3.1 - 11/02/2015 = += 2.3.1 - 2015-02-11 = * Fix - When the geolocation database cannot download, ensure the correct method is used to log the error. * Fix - Notice in woocommerce_form_field(). * Fix - attribute_public notice before DB upgrade. @@ -432,8 +1067,8 @@ * Fix - is_available() check in local pickup. * Fix - Added WC version of GEOIP classes to prevent conflicts with other plugins. -= 2.3.0 - 11/02/2015 = -* Feature - Option to geo-locate the customer's inital location. += 2.3.0 - 2015-02-11 = +* Feature - Option to geo-locate the customer's initial location. * Feature - Display taxes in store based on the customer location, rather than the shop base. * Feature - Made tax importer expand postcode ranges. * Feature - Print styles for reports. @@ -484,16 +1119,16 @@ * Localisation - Add Ukrainian currency and symbol. * Localisation - Greece regions. -= 2.2.11 - 29/01/2015 = += 2.2.11 - 2015-01-29 = * Add - URL in Usage/Limit column in Coupons table to query for orders. * Fix - esc_url() applied to prevent potential XSS issues. * Fix - "Link all variations" button. -= 2.2.10 - 16/12/2014 = += 2.2.10 - 2014-12-16 = * Fix - Stock status on quick and bulk edit. * Fix - Incorrect clearing of error messages. -= 2.2.9 - 15/12/2014 = += 2.2.9 - 2014-12-15 = * Add - API - parent_id for products endpoint. * Fix - Processing and On-hold order links in WooCommerce Status dashboard widget. * Fix - Orders API when query orders with deleted products. @@ -521,7 +1156,7 @@ * Tweak - Added result and message keys to order_review AJAX call. * Tweak - Added get_cart_item to WC_Cart class. -= 2.2.8 - 29/10/2014 = += 2.2.8 - 2014-10-29 = * Fix - Image crop option. * Fix - Display of order note date. * Fix - API POST/PUT products attributes values. @@ -537,7 +1172,7 @@ * Tweak - Use current user ID for refunds. * Tweak - Allow API edit_product method to update post_name (slug). -= 2.2.7 - 22/10/2014 = += 2.2.7 - 2014-10-22 = * Fix - Fix refund date. * Fix - Fixed various notices. * Fix - Make updater set parent backorder status. @@ -563,7 +1198,7 @@ * Tweak - Update simplify commerce to use new $order->get_status(). * Tweak - Only show integrations subnav when there are multiple integrations. -= 2.2.6 - 08/10/2014 = += 2.2.6 - 2014-10-08 = * Fix - Notices in the cache helper. * Fix - Prevent bulk edit from breaking sale price scheduled dates. * Fix - Prevent address fields being empty when editing an address within an order. @@ -573,7 +1208,7 @@ * Tweak - Added filter for shipping tax. * Tweak - Product attribute shortcode should return columns css class. -= 2.2.5 - 07/10/2014 = += 2.2.5 - 2014-10-07 = * Fix - Filters in admin screen for coupons and orders. * Fix - When bulk editing, don't allow sale price to be negative. * Fix - When manually adding items to an order, show tax columns. @@ -597,7 +1232,7 @@ * Tweak - Tweak load_plugin_textdomain to be relative - this falls back to WP_LANG_DIR automatically. Can prevent "open_basedir restriction in effect". * Tweak - Added acceptance marks to PayPal Standard where applicable to replace generic PayPal icon. -= 2.2.4 - 18/09/2014 = += 2.2.4 - 2014-09-18 = * Fix - Prevent errors when adding 'zero-rated' tax on checkout. * Fix - Fixed a varation product width inheritance bug. * Fix - Totals in taxes by date report. @@ -609,7 +1244,7 @@ * Localisation - Nepal States. * Localisation - Mexico states. -= 2.2.3 - 16/09/2014 = += 2.2.3 - 2014-09-16 = * Fix - Order status translation in admin and account page. * Fix - Ensure shipping address gets displayed - fixes needs_shipping_address() method. * Fix - Escaping of country names in tax settings. @@ -636,17 +1271,17 @@ * Tweak - Display of h4 in settings pages. * Dev - Added woocommerce_get_settings_ID filters. -= 2.2.2 - 11/09/2014 = += 2.2.2 - 2014-09-11 = * Fix - Saving of variation stock when parent stock management is disabled. * Fix - "open_basedir restriction in effect" error caused on install when trying to create the WC logging directory. * Fix - For regular products, ensure stock level saves on product creation. -= 2.2.1 - 10/09/2014 = += 2.2.1 - 2014-09-10 = * Fix - Small tweak to the installer to prevent errors caused by outdated plugins. * Fix - Mijireh Checkout update link. * Tweak - Small tweak to update notification to remind users to update old plugins prior to install. -= 2.2.0 - 10/09/2014 = += 2.2.0 - 2014-09-10 = * Feature - Refunds system for orders. * Feature - New orders panel for managing line items + totals. * Feature - Language pack downloader. po and mo files removed from core (too heavy). @@ -692,7 +1327,7 @@ * Dev - Introduces the WC_Order::needs_shipping_address() method. * Dev - Gateways can set transaction ID for the order. * Dev - Gateways can do refunds via the Payment Gateway API. -* Refactor - Changed the method in which order statuses are stored. Previously, order status was a taxonomy. This caused issues when unique term slugs differed from what we were expecting, and also added additonal overhead to order queries in reports. https://github.com/woothemes/woocommerce/issues/3064 Order status is now stored as post status - several new post statuses have been added. Order class variables are backwards compatible. The only thing to note (for devs) is that any query must use the order status instead of 'publish' when getting orders and querying by post_status. THe shop_order_status has also been removed. +* Refactor - Changed the method in which order statuses are stored. Previously, order status was a taxonomy. This caused issues when unique term slugs differed from what we were expecting, and also added additional overhead to order queries in reports. https://github.com/woocommerce/woocommerce/issues/3064 Order status is now stored as post status - several new post statuses have been added. Order class variables are backwards compatible. The only thing to note (for devs) is that any query must use the order status instead of 'publish' when getting orders and querying by post_status. THe shop_order_status has also been removed. * Refactor - Update stock amounts with DB queries. * Refactor - Simplified attribute name sanitisation which maintains UTF8 char integrity. * Refactor - Country class return methods. @@ -701,7 +1336,7 @@ * Localisation - Address format of Taiwan. * Localisation - Removed language files from core to made the package lighter (see language pack downloader feature). -= 2.1.12 - 01/07/2014 = += 2.1.12 - 2014-07-01 = * Fix - Total tax should be +, not -. * Fix - Address format in plain text emails to use line breaks, not commas. * Fix - order item count fix and tr class filters. @@ -709,12 +1344,12 @@ * Fix - Correctly clear transients, including sale transient. * Tweak - woocommerce_get_order_item_totals_excl_free_fees hook. -= 2.1.11 - 09/06/2014 = += 2.1.11 - 2014-06-09 = * Fix - Plain text email display of customer address. * Fix - Saving tax rates threw notices (missing git cherry pick). -= 2.1.10 - 03/06/2014 = -* Fix - Removed unecessary localization from edit account. += 2.1.10 - 2014-06-03 = +* Fix - Removed unnecessary localization from edit account. * Fix - Admin welcome screen css. * Fix - Fixed my account setting values to wrong user submitted strings. * Fix - Menu order terms were coming back empty. @@ -731,7 +1366,7 @@ * Tweak - Stronger session ID generation. * Dev - Add action hooks when saving tax rates. -= 2.1.9 - 14/05/2014 = += 2.1.9 - 2014-05-14 = * Fix - fix case-insensitive matching for coupon posts with uppercase chars. * Fix - Make the welcome page RTL compatible. * Fix - Sanitize, but decode, flat rate shipping method ids. UTF-8 Friendly. @@ -757,7 +1392,7 @@ * Dev - Add $package to is_available shipping method hooks. * Dev - Add tool for disabling shipping rate cache for debug. -= 2.1.8 - 30/04/2014 = += 2.1.8 - 2014-04-30 = * Fix - Prevent saving duplicate skus in quick edit. * Fix - Sorting of downloads on my account page. * Fix - Clear cached API reports when deleting other order transients. @@ -777,7 +1412,7 @@ * Tweak - Improved Abstract product constructor. * Tweak - Add COD instructions to emails. -= 2.1.7 - 10/04/2014 = += 2.1.7 - 2014-04-10 = * Fix - Allow WC API to generate API keys for different user than the one that is making request. * Fix - Fix the SKU search logic so it works with other filters. * Fix - Correctly round shipping + shipping tax together when passes the tax inclusive total to paypal. @@ -818,7 +1453,7 @@ * Tweak - get_image_id method for use in email template. Shows correct variation images. * Tweak - added validation when save the frontend colors. -= 2.1.6 - 25/03/2014 = += 2.1.6 - 2014-03-25 = * Fix - Fixed a bug where cron events are scheduled using a function name rather than a hook name. * Fix - Given transients not required on all pages expiration times to prevent autoloading. * Fix - Don't trailingslash Order Cancel URLs with a Query String. @@ -863,7 +1498,7 @@ * Localisation - Bangladeshi states (districts). * Localisation - Croatian currency symbol. -= 2.1.5 - 06/03/2014 = += 2.1.5 - 2014-03-06 = * Fix - Prevent notices on new plain text email parameter for BACS and Cheque gateways * Fix - Fixed issue where variation prices were hidden when variation stock management wasn't set * Fix - Discounts fixed_product are now properly multiplied by quantity @@ -873,7 +1508,7 @@ * Tweak - Fallback for when add ons page is not loading * Tweak - Hide price suffix in admin panel lists -= 2.1.4 - 05/03/2014 = += 2.1.4 - 2014-03-05 = * Fix - Prevent duplicate loading of functions files * Fix - Fixed breaking timeline for reports * Fix - Category widget ordering @@ -899,7 +1534,7 @@ * Tweak - Improved styles for tab views * Refactor - Hardened code base and fixed strict standards notices -= 2.1.3 - 27/02/2014 = += 2.1.3 - 2014-02-27 = * Fix - Use correct thresholds to calculate out of stock number in dashboard widget * Fix - Admin screen strings sanitised to work with Chinese characters * Fix - REST API OAuth signature fixed when using filter params @@ -954,7 +1589,7 @@ * Refactor - Changed all text strings without explicit domain, to use the 'woocommerce' text domain * Refactor - Speed improvements in various places -= 2.1.2 - 13/02/2014 = += 2.1.2 - 2014-02-13 = * Fix - Removed nl2br function from plain text email-order-items email template * Fix - Made static string translatable in email-order-items email template * Fix - Added missing third parameter to _doing_it_wrong call @@ -977,7 +1612,7 @@ * Refactor - Removed obsolete view order shortcode class * Localization - Multiple localization updates -= 2.1.1 - 12/02/2014 = += 2.1.1 - 2014-02-12 = * Feature - Show notice if template files are out of date for themes including WooCommerce template files * Feature - Introducing supporting is_wc_endpoint_url function * Fix - During install, register all post types and endpoints so that the rewrite rules are correctly generated. @@ -1001,7 +1636,7 @@ * Refactor - Several function dockblocks improved * Refactor - Stripped out some unused variables -= 2.1.0 - 10/02/2014 = += 2.1.0 - 2014-02-10 = * Feature - New REST API * Feature - Define whether prices should be shown incl. or excl. of tax, and add an optional suffix. * Feature - Show grouped or itemized taxes during checkout. @@ -1013,7 +1648,7 @@ * Feature - Customer list reports. * Feature - Reports - New design, export csvs, more data. * Feature - Ability to link past orders to a customer (before they registered). -* Feature - Authorize option for paypal standard. +* Feature - Authorize option for PayPal Standard. * Feature - Separate options for countries you can ship to and sell to. * Feature - BACS supports multiple account details. * Feature - PayPal PDT support (as alternative to IPN). @@ -1044,7 +1679,7 @@ * Tweak - Filterable page installer. * Tweak - Order details optimised for small screens. * Tweak - Streamlined account process - username and passwords are optional and can be automatically generated. -* Tweak - Updated/new dummy data (including .csv files to be used with [Product CSV Import Suite](http://www.woothemes.com/products/product-csv-import-suite/)). +* Tweak - Updated/new dummy data (including .csv files to be used with [Product CSV Import Suite](https://woocommerce.com/products/product-csv-import-suite/)). * Tweak - Product shortcodes columns parameter now affects layout correctly. * Tweak - Disabled button styles. * Tweak - Hooks for overriding default email inline styles. @@ -1054,7 +1689,7 @@ * Tweak - Make shipping methods check if taxable, so when customer is VAT excempt taxes are not included in price. * Tweak - Coupon in admin bar new menu #3974 * Tweak - Shortcode tag filters + updated menu names to make white labelling easier. -* Tweak - Removed placeholder polyfill. Use this plugin to replace functionality if required: http://wordpress.org/plugins/html5-placeholder-polyfill/ +* Tweak - Removed placeholder polyfill. Use this plugin to replace functionality if required: https://wordpress.org/plugins/html5-placeholder-polyfill/ * Tweak - Replaced all instances of → and ← in frontent using wc icon font plus .wc-forward and .wc-backward utility classes. * Tweak - Add review form no longer opens in lightbox. * Tweak - Move average rating outside of hidden tab for google #3867. @@ -1066,8 +1701,8 @@ * Fix - Tweaked popularity sorting to work better when no sales are present. * Fix - Quote encoding in email subjects. * Fix - Added $wp_error parameter during checkout process to ensure WP_Error object is returned on error and checkout process is properly stopped. -* Refactor - Taken out Piwik integration, use http://wordpress.org/extend/plugins/woocommerce-piwik-integration/ from now on. -* Refactor - Taken out ShareYourCart integration, use http://wordpress.org/extend/plugins/shareyourcart/ from now on. +* Refactor - Taken out Piwik integration, use https://wordpress.org/plugins/woocommerce-piwik-integration/ from now on. +* Refactor - Taken out ShareYourCart integration, use https://wordpress.org/plugins/shareyourcart/ from now on. * Refactor - Moved woocommerce_get_formatted_product_name function into WC_Product class. * Refactor - Improved parameter handling in woocommerce_related_products() function. * Refactor - Widget classes (added abstract and combined similar widgets). @@ -1080,13 +1715,13 @@ * Localization - Spanish translation by Luis Giménez. * Localization - French, Spanish, Romanian, Danish, Korean, Czech, Arabic, Hungarian updates. -= 2.0.20 - 21/11/2013 = += 2.0.20 - 2013-11-21 = * Tweaked paypal request * Check for WP Error when getting terms in breadcrumb file * Sanitize when searching in admin * Fix yard to cm conversion -= 2.0.19 - 04/11/2013 = += 2.0.19 - 2013-11-04 = * Fix - get_item_subtotal() logic * Fix - Pass number of products variable to get_related for more then 5 related products * Fix - Email fatal error for orders with missing products @@ -1095,7 +1730,7 @@ * Tweak - Added wordwrap to order notes * Localisation - Updated Portuguese, Slovak, French, Lithuanian, Finnish -= 2.0.18 - 21/10/2013 = += 2.0.18 - 2013-10-21 = * Fix - Escaped the "hide-wc-extensions-message" link in admin. * Fix - CSS -mox- prefix. #3953 * Fix - Remove sorting args after main query #3969 @@ -1105,7 +1740,7 @@ * Tweak - Show layered nav widgets on any product taxonomy page * Localisation - Various corrections -= 2.0.17 - 17/10/2013 = += 2.0.17 - 2013-10-17 = * Fix - Add missing doctype for email header #3921 * Fix - 2 notices on the cart/checkout related to tax #3922 * Fix - Allowed more tags to be saved in sharethis code @@ -1117,12 +1752,12 @@ * Tweak - Key value pairs for order_meta (woocommerce_email_order_meta_keys) * Tweak - Added wc_variation_form trigger to variations javascript for 3rd party plugins -= 2.0.16 - 14/10/2013 = += 2.0.16 - 2013-10-14 = * Fix - woocommerce_change_term_counts needs to always return terms. Fixes category display. * Fix - Attribute label display. * Fix - add_to_cart shortcode correct use of setup_product_data -= 2.0.15 - 14/10/2013 = += 2.0.15 - 2013-10-14 = * Fix - Added missing line break in plain text email. * Fix - Strict standards warnings in category walkers * Fix - Remember which attributes get registered to minimize conflicts @@ -1145,7 +1780,7 @@ * Fix - Remove accents from taxonomy names + run through filters #3832 * Tweak - Always show returning customer login box. -= 2.0.14 - 05/09/2013 = += 2.0.14 - 2013-09-05 = * Tweak - Update cart performance improvements * Fix - Google Analytics no longer identifies users using custom vars * Fix - Send tax inclusive, rounded item price to Google Analytics @@ -1159,11 +1794,11 @@ * Fix - Refresh when creating an account to prevent nonce issues * Other minor fixes -= 2.0.13 - 19/07/2013 = += 2.0.13 - 2013-07-19 = * Tweak - Allow users with edit rights to add draft products to cart (and nobody else) * Tweak - Handle pending status for paypal * Tweak - Only refresh fragment when cart cookie > 0 -* Tweak - Updated/new dummy data (including .csv files to be used with [Product CSV Import Suite](http://www.woothemes.com/products/product-csv-import-suite/)). +* Tweak - Updated/new dummy data (including .csv files to be used with [Product CSV Import Suite](https://woocommerce.com/products/product-csv-import-suite/)). * Fix - Extra escaping on layered nav variables to prevent injection * Fix - Improved sanitization of option fields * Fix - Add fee total to cart total @@ -1177,13 +1812,13 @@ * Fix - Sanitized shipping calc form to fix persistent XSS issue. * Localisation - ES States -= 2.0.12 - 17/06/2013 = += 2.0.12 - 2013-06-17 = * Tweak - Add actions for attribute create/update/delete * Fix - Fixed bug in cross sells loading in product data write panel * Fix - Fixed posting shipping method when only one is available * Fix - Fixed query breaking when using some product widgets -= 2.0.11 - 13/06/2013 = += 2.0.11 - 2013-06-13 = * Tweak - Handling for multiselect fields on checkout, and a filter for third party handling * Fix - Duplicate param keys for sale_product shortcodes * Fix - Google Analytics tracking use get_order_number() method instead of id @@ -1194,7 +1829,7 @@ * Fix - Extra data sanitization in some places * Fix - Offer tax class option per variation to use same tax class as parent -= 2.0.10 - 15/05/2013 = += 2.0.10 - 2013-05-15 = * Tweak - Searching for SKU in admin panel can also be done via lowercase 'sku:' instead of just 'SKU:' * Fix - Cast term_id as int in product data write panel that will resolve issues with numerical attributes * Fix - Correct label for RUB symbol - added a dot after it @@ -1208,7 +1843,7 @@ * Fix - PayPal has a 9 item limit * Fix - Replace deprecated wp_convert_bytes_to_hr() with size_format() -= 2.0.9 - 02/05/2013 = += 2.0.9 - 2013-05-02 = * Feature - Added is_product_taxonomy() conditional. * Tweak - Notices during checkout for admin users if the checkout is mis-configured. * Tweak - Named charts on report page to make modifications easier. @@ -1228,7 +1863,7 @@ * Localization - Added RUB currency. * Other minor fixes and localisation updates. -= 2.0.8 - 17/04/2013 = += 2.0.8 - 2013-04-17 = * Feature - Related products shortcode. * Tweak - Order item meta - skip serialized fields. * Tweak - Support for the city field in shipping calc (filterable). @@ -1247,7 +1882,7 @@ * Localization - Romanian updates by Aurel Roman * Localization - Finnish updates by arhipaiva -= 2.0.7 - 12/04/2013 = += 2.0.7 - 2013-04-12 = * Feature - Option for GA _setDomainName. * Tweak - Removed rounding when option to round at subtotal is set. * Fix - Allow extra flat rate options even if main rate is 0. @@ -1256,7 +1891,7 @@ * Fix - Sanitize terms when linking all variations. * Fix - Sanitize coupon code names before checking/applying. -= 2.0.6 - 10/04/2013 = += 2.0.6 - 2013-04-10 = * Tweak/Fix - Merge taxes by CODE so totals are displayed clearer. Also added additional function for getting merged tax totals, and to keep compatibility with themes. * Tweak/Fix - Recent reviews show actual review stars, and allowed get_rating_html() to be passed a rating. Also removed unused $location var. * Fix - Saving of meta values from paypal after payment. @@ -1290,7 +1925,7 @@ * Localisation - NZ States * Other minor fixes and localisation updates. -= 2.0.5 - 26/03/2013 = += 2.0.5 - 2013-03-26 = * Tweak - Made no shipping available messages filterable via woocommerce_cart_no_shipping_available_html and woocommerce_no_shipping_available_html. * Tweak - disabled keyboard shortcuts in prettyPhoto. * Tweak - woocommerce_date_format() function. @@ -1304,10 +1939,10 @@ * Fix - Cancel order function now looks at post_modified instead of post_date. * Other minor fixes and localisation updates. -= 2.0.4 - 18/03/2013 = += 2.0.4 - 2013-03-18 = * Tweak - Like my account, added order_count attribute to view order shortcode. * Tweak - Moved WC_Order_Item_Meta into own file. -* Tweak - PayPal standard gateway - no longer needs sandbox fix, and notify-validate should be first in the requests. +* Tweak - PayPal Standard gateway - no longer needs sandbox fix, and notify-validate should be first in the requests. * Tweak - Flat rate interface tidy up. * Tweak - Add order_id to woocommerce_download_product hook * Tweak - Disabled prettyPhoto deeplinking @@ -1334,13 +1969,13 @@ * Fix - Product tabs when a product type doesn't exist yet. * Fix - Saving of variation download paths with special chars. * Fix - Unset parent of children when deleting a grouped product. -* Fix - Removed Sidebar Login Widget. Use http://wordpress.org/extend/plugins/sidebar-login/ instead. A potential security issue was found regarding logging of passwords (since GET was used instead of POST). Sidebar Login 2.5 resolves this and the widget has been removed from WC to prevent needing to maintain two (virtually identical) codebases. +* Fix - Removed Sidebar Login Widget. Use https://wordpress.org/extend/plugins/sidebar-login/ instead. A potential security issue was found regarding logging of passwords (since GET was used instead of POST). Sidebar Login 2.5 resolves this and the widget has been removed from WC to prevent needing to maintain two (virtually identical) codebases. * Localization - Added indian rupees * Localization - Updated French translation by absoluteweb * Localization - Updated Brazilian translation by Claudio Sanches * Localization - Updated Hungarian translation by béla. -= 2.0.3 - 11/03/2013 = += 2.0.3 - 2013-03-11 = * Feature - Added products by attribute shortcode, e.g. [product_attribute attribute="color" filter="blue"] * Tweak - Made coupon label more clear. * Tweak - woocommerce_cart_redirect_after_error hook. @@ -1363,7 +1998,7 @@ * Fix - Added legacy paypal IPN handling. * Localization - Finnish translation by Arhi Paivarinta. -= 2.0.2 - 06/03/2013 = += 2.0.2 - 2013-03-06 = * Fix - Frontpage shop when 'orderby' is set. * Fix - Fix add-to-cart for grouped products which are sold individually. * Fix - Payment method animation on the checkout. @@ -1375,10 +2010,10 @@ * Fix - FROM prices now ignore blank strings for variations. * Fix - Ensure order contents are saved before mailing via admin interface. -= 2.0.1 - 04/03/2013 = += 2.0.1 - 2013-03-04 = * Fix - Added an extra permalink flush after upgrade to save needing to do it manually. -= 2.0.0 - 04/03/2013 = += 2.0.0 - 2013-03-04 = * Feature - Sucuri audited and secured. * Feature - Added sales by category report. * Feature - Added sales by coupon report (kudos Max Rice). @@ -1401,12 +2036,12 @@ * Feature - Allow setting the product post type slug to a static (non-translatable) text, mainly to be used for translating and WPML setups. * Feature - Added lost password shortcode / email notification (thanks Max Rice). * Feature - Simplified permalink/base settings now found in Settings > Permalinks. -* Feature - Support more permalink structures (from http://codex.wordpress.org/Using_Permalinks) +* Feature - Support more permalink structures (from https://codex.wordpress.org/Using_Permalinks) * Feature - Added option to resend order emails, checkboxes select which one. * Feature - New layered nav current filters widget. This lists active filters from all layered nav for de-selection. * Feature - Added the option to sell products individually (only allow 1 in the cart). * Feature - New shop page/category archive display settings, and the ability to change display per-category. -* Feature - Allow shipping tax classes to be defined independent of items. https://github.com/woothemes/woocommerce/issues/1625 +* Feature - Allow shipping tax classes to be defined independent of items. https://github.com/woocommerce/woocommerce/issues/1625 * Feature - Redone order item storage making them easier (and faster) to access for reporting, and querying purchases. Huge performance gains for reports. Order items are no longer serialised - they are stored in their own table with meta. Existing data can be be updated on upgrade. * Feature - Update weights/dimensions for variations if they differ. * Feature - is_order_received_page() courtesy of Lee Willis. @@ -1417,7 +2052,7 @@ * Feature - Filter coupons in admin by type. * Feature - Append view cart link on ajax buttons. * Feature - Revised the way coupons are stored per order and added new coupon reports on usage. -* Feature - Updated/new dummy data (including .csv files to be used with [Product CSV Import Suite](http://www.woothemes.com/products/product-csv-import-suite/)). +* Feature - Updated/new dummy data (including .csv files to be used with [Product CSV Import Suite](https://woocommerce.com/products/product-csv-import-suite/)). * Feature - Option to hold stock for unpaid orders (defaults to 60mins). When this time limit is reached, and the order is not paid for, stock is released and the order is cancelled. * Feature - Added set_stock() method to product class. * Feature - Linking to mydomain.com/product#review_form will now open the review form on load (if WooCommerce lightbox is turned on) diff --git a/Gruntfile.js b/Gruntfile.js index 9b68e9972f7..c1fe72644e8 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -28,10 +28,22 @@ module.exports = function( grunt ) { ] }, + // Sass linting with Stylelint. + stylelint: { + options: { + configFile: '.stylelintrc' + }, + all: [ + '<%= dirs.css %>/*.scss', + '!<%= dirs.css %>/select2.scss' + ] + }, + // Minify .js files. uglify: { options: { - preserveComments: 'some' + // Preserve comments that start with a bang. + preserveComments: /^!/ }, admin: { files: [{ @@ -50,6 +62,7 @@ module.exports = function( grunt ) { '<%= dirs.js %>/accounting/accounting.min.js': ['<%= dirs.js %>/accounting/accounting.js'], '<%= dirs.js %>/jquery-blockui/jquery.blockUI.min.js': ['<%= dirs.js %>/jquery-blockui/jquery.blockUI.js'], '<%= dirs.js %>/jquery-cookie/jquery.cookie.min.js': ['<%= dirs.js %>/jquery-cookie/jquery.cookie.js'], + '<%= dirs.js %>/js-cookie/js.cookie.min.js': ['<%= dirs.js %>/js-cookie/js.cookie.js'], '<%= dirs.js %>/jquery-flot/jquery.flot.min.js': ['<%= dirs.js %>/jquery-flot/jquery.flot.js'], '<%= dirs.js %>/jquery-flot/jquery.flot.pie.min.js': ['<%= dirs.js %>/jquery-flot/jquery.flot.pie.js'], '<%= dirs.js %>/jquery-flot/jquery.flot.resize.min.js': ['<%= dirs.js %>/jquery-flot/jquery.flot.resize.js'], @@ -62,6 +75,10 @@ module.exports = function( grunt ) { '<%= dirs.js %>/jquery-ui-touch-punch/jquery-ui-touch-punch.min.js': ['<%= dirs.js %>/jquery-ui-touch-punch/jquery-ui-touch-punch.js'], '<%= dirs.js %>/prettyPhoto/jquery.prettyPhoto.init.min.js': ['<%= dirs.js %>/prettyPhoto/jquery.prettyPhoto.init.js'], '<%= dirs.js %>/prettyPhoto/jquery.prettyPhoto.min.js': ['<%= dirs.js %>/prettyPhoto/jquery.prettyPhoto.js'], + '<%= dirs.js %>/flexslider/jquery.flexslider.min.js': ['<%= dirs.js %>/flexslider/jquery.flexslider.js'], + '<%= dirs.js %>/zoom/jquery.zoom.min.js': ['<%= dirs.js %>/zoom/jquery.zoom.js'], + '<%= dirs.js %>/photoswipe/photoswipe.min.js': ['<%= dirs.js %>/photoswipe/photoswipe.js'], + '<%= dirs.js %>/photoswipe/photoswipe-ui-default.min.js': ['<%= dirs.js %>/photoswipe/photoswipe-ui-default.js'], '<%= dirs.js %>/round/round.min.js': ['<%= dirs.js %>/round/round.js'], '<%= dirs.js %>/select2/select2.min.js': ['<%= dirs.js %>/select2/select2.js'], '<%= dirs.js %>/stupidtable/stupidtable.min.js': ['<%= dirs.js %>/stupidtable/stupidtable.js'], @@ -111,6 +128,21 @@ module.exports = function( grunt ) { } }, + // Generate RTL .css files + rtlcss: { + woocommerce: { + expand: true, + cwd: '<%= dirs.css %>', + src: [ + '*.css', + '!select2.css', + '!*-rtl.css' + ], + dest: '<%= dirs.css %>/', + ext: '-rtl.css' + } + }, + // Minify all .css files. cssmin: { minify: { @@ -122,11 +154,21 @@ module.exports = function( grunt ) { } }, + // Concatenate select2.css onto the admin.css files. + concat: { + admin: { + files: { + '<%= dirs.css %>/admin.css' : ['<%= dirs.css %>/select2.css', '<%= dirs.css %>/admin.css'], + '<%= dirs.css %>/admin-rtl.css' : ['<%= dirs.css %>/select2.css', '<%= dirs.css %>/admin-rtl.css'] + } + } + }, + // Watch changes for assets. watch: { css: { files: ['<%= dirs.css %>/*.scss'], - tasks: ['sass', 'cssmin'] + tasks: ['sass', 'rtlcss', 'cssmin', 'concat'] }, js: { files: [ @@ -145,7 +187,7 @@ module.exports = function( grunt ) { type: 'wp-plugin', domainPath: 'i18n/languages', potHeaders: { - 'report-msgid-bugs-to': 'https://github.com/woothemes/woocommerce/issues', + 'report-msgid-bugs-to': 'https://github.com/woocommerce/woocommerce/issues', 'language-team': 'LANGUAGE ' } }, @@ -184,11 +226,12 @@ module.exports = function( grunt ) { }, files: { src: [ - '**/*.php', // Include all files - '!apigen/**', // Exclude apigen/ + '**/*.php', // Include all files + '!apigen/**', // Exclude apigen/ '!node_modules/**', // Exclude node_modules/ - '!tests/**', // Exclude tests/ - '!tmp/**' // Exclude tmp/ + '!tests/**', // Exclude tests/ + '!vendor/**', // Exclude vendor/ + '!tmp/**' // Exclude tmp/ ], expand: true } @@ -202,10 +245,16 @@ module.exports = function( grunt ) { }, apigen: { command: [ - 'apigen generate', + 'apigen generate -q', 'cd apigen', 'php hook-docs.php' ].join( '&&' ) + }, + e2e_test: { + command: 'npm run --silent test:single tests/e2e-tests/' + grunt.option( 'file' ) + }, + e2e_tests: { + command: 'npm run --silent test' } }, @@ -214,19 +263,65 @@ module.exports = function( grunt ) { apigen: { src: [ 'wc-apidocs' ] } + }, + + // PHP Code Sniffer. + phpcs: { + options: { + bin: 'vendor/bin/phpcs', + standard: './phpcs.ruleset.xml' + }, + dist: { + src: [ + '**/*.php', // Include all files + '!apigen/**', // Exclude apigen/ + '!includes/api/legacy/**', // Exclude legacy REST API + '!includes/gateways/simplify-commerce/includes/Simplify/**', // Exclude simplify commerce SDK + '!includes/libraries/**', // Exclude libraries/ + '!node_modules/**', // Exclude node_modules/ + '!tests/cli/**', // Exclude tests/cli/ + '!tmp/**', // Exclude tmp/ + '!vendor/**' // Exclude vendor/ + ] + } + }, + + // Autoprefixer. + postcss: { + options: { + processors: [ + require( 'autoprefixer' )({ + browsers: [ + '> 0.1%', + 'ie 8', + 'ie 9' + ] + }) + ] + }, + dist: { + src: [ + '<%= dirs.css %>/*.css' + ] + } } }); // Load NPM tasks to be used here grunt.loadNpmTasks( 'grunt-shell' ); grunt.loadNpmTasks( 'grunt-wp-i18n' ); + grunt.loadNpmTasks( 'grunt-rtlcss' ); grunt.loadNpmTasks( 'grunt-checktextdomain' ); grunt.loadNpmTasks( 'grunt-contrib-jshint' ); grunt.loadNpmTasks( 'grunt-contrib-uglify' ); grunt.loadNpmTasks( 'grunt-contrib-sass' ); grunt.loadNpmTasks( 'grunt-contrib-cssmin' ); + grunt.loadNpmTasks( 'grunt-contrib-concat' ); grunt.loadNpmTasks( 'grunt-contrib-watch' ); grunt.loadNpmTasks( 'grunt-contrib-clean' ); + grunt.loadNpmTasks( 'grunt-stylelint' ); + grunt.loadNpmTasks( 'grunt-phpcs' ); + grunt.loadNpmTasks( 'grunt-postcss' ); // Register tasks grunt.registerTask( 'default', [ @@ -235,9 +330,18 @@ module.exports = function( grunt ) { 'css' ]); + grunt.registerTask( 'js', [ + 'jshint', + 'uglify:admin', + 'uglify:frontend' + ]); + grunt.registerTask( 'css', [ 'sass', - 'cssmin' + 'rtlcss', + 'postcss', + 'cssmin', + 'concat' ]); grunt.registerTask( 'docs', [ @@ -249,4 +353,12 @@ module.exports = function( grunt ) { 'default', 'makepot' ]); + + grunt.registerTask( 'e2e-tests', [ + 'shell:e2e_tests' + ]); + + grunt.registerTask( 'e2e-test', [ + 'shell:e2e_test' + ]); }; diff --git a/README.md b/README.md index 493386aa4f8..57b074cb901 100644 --- a/README.md +++ b/README.md @@ -1,24 +1,24 @@ -# [WooCommerce](http://www.woothemes.com/woocommerce/) [![Built with Grunt](https://cdn.gruntjs.com/builtwith.png)](http://gruntjs.com/) [![Build Status](https://api.travis-ci.org/woothemes/woocommerce.svg?branch=master)](http://travis-ci.org/woothemes/woocommerce) [![Coverage Status](https://coveralls.io/repos/woothemes/woocommerce/badge.svg?branch=master&service=github)](https://coveralls.io/github/woothemes/woocommerce?branch=master) +# [WooCommerce](https://woocommerce.com/) [![Built with Grunt](https://cdn.gruntjs.com/builtwith.png)](http://gruntjs.com/) [![Build Status](https://travis-ci.org/woocommerce/woocommerce.svg?branch=master)](https://travis-ci.org/woocommerce/woocommerce) [![Code Coverage](https://scrutinizer-ci.com/g/woocommerce/woocommerce/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/woocommerce/woocommerce/?branch=master) [![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/woocommerce/woocommerce/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/woocommerce/woocommerce/?branch=master) [![Code Climate](https://codeclimate.com/github/woocommerce/woocommerce/badges/gpa.svg)](https://codeclimate.com/github/woocommerce/woocommerce) Welcome to the WooCommerce repository on GitHub. Here you can browse the source, look at open issues and keep track of development. We recommend all developers to follow the [WooCommerce development blog](https://woocommerce.wordpress.com/) to stay up to date about everything happening in the project. You can also [follow @DevelopWC](https://twitter.com/DevelopWC) on Twitter for the latest development updates. -If you are not a developer, please use the [WooCommerce plugin page](http://wordpress.org/plugins/woocommerce/) on WordPress.org. +If you are not a developer, please use the [WooCommerce plugin page](https://wordpress.org/plugins/woocommerce/) on WordPress.org. ## Documentation -* [WooCommerce Documentation](http://docs.woothemes.com/documentation/plugins/woocommerce/) -* [WooCommerce Knowledge Base](https://support.woothemes.com/hc/en-us/categories/200146917-WooCommerce) -* [WooCommerce Code Reference](http://docs.woothemes.com/wc-apidocs/) -* [WooCommerce REST API Docs](http://woothemes.github.io/woocommerce-rest-api-docs/) +* [WooCommerce Documentation](https://docs.woocommerce.com/documentation/plugins/woocommerce/) +* [WooCommerce Code Reference](https://docs.woocommerce.com/wc-apidocs/) +* [WooCommerce REST API Docs](https://woocommerce.github.io/woocommerce-rest-api-docs/) + +## Reporting Security Issues +To disclose a security issue to our team, [please submit a report via HackerOne here](https://hackerone.com/automattic/). ## Support -This repository is not suitable for support. Please don't use our issue tracker for support requests, but for core WooCommerce issues only. Support can take place in the appropriate channels: +This repository is not suitable for support. Please don't use our issue tracker for support requests, but for core, WooCommerce issues only. Support can take place through the appropriate channels: -* The [WooThemes premium support portal](http://support.woothemes.com/) for customers who have purchased themes or extensions. +* The [WooCommerce premium support portal](https://woocommerce.com/my-account/create-a-ticket/) for customers who have purchased themes or extensions. * [Our community forum on wp.org](https://wordpress.org/support/plugin/woocommerce) which is available for all WooCommerce users. Support requests in issues on this repository will be closed on sight. ## Contributing to WooCommerce -If you have a patch, or stumbled upon an issue with WooCommerce core, you can contribute this back to the code. Please read our [contributor guidelines](https://github.com/woothemes/woocommerce/blob/master/CONTRIBUTING.md) for more information how you can do this. - -If you have an idea for WooCommerce, see the [Roadmap Trello board](https://trello.com/b/YgRbpuze/woocommerce-roadmap). +If you have a patch or have stumbled upon an issue with WooCommerce core, you can contribute this back to the code. Please read our [contributor guidelines](https://github.com/woocommerce/woocommerce/blob/master/.github/CONTRIBUTING.md) for more information how you can do this. diff --git a/apigen.neon b/apigen.neon index aec9743d1bc..d8a09352fd7 100644 --- a/apigen.neon +++ b/apigen.neon @@ -10,7 +10,7 @@ extensions: [php] # directories and files matching this file mask will not be parsed exclude: - includes/libraries/ - - api/ + - includes/api/legacy/ - i18n/ - node_modules/ - wc-apidocs/ @@ -26,10 +26,10 @@ charset: [UTF-8] main: WC # title of generated documentation -title: WooCommerce 2.5.x Code Reference +title: WooCommerce 3.0.x Code Reference # base url used for sitemap (useful for public doc) -baseUrl: http://docs.woothemes.com/wc-apidocs/ +baseUrl: https://docs.woocommerce.com/wc-apidocs/ # choose ApiGen template theme templateTheme: default @@ -46,7 +46,7 @@ tree: true # generate documentation for deprecated elements deprecated: true -# generate list of tasks with @todo annotation +# generate list of tasks with @ todo annotation todo: true # add link to ZIP archive of documentation diff --git a/apigen/hook-docs.php b/apigen/hook-docs.php index 5da84ac48e1..7de5461a75d 100644 --- a/apigen/hook-docs.php +++ b/apigen/hook-docs.php @@ -12,44 +12,46 @@ class WC_HookFinder { private static function get_files( $pattern, $flags = 0, $path = '' ) { - if ( ! $path && ( $dir = dirname( $pattern ) ) != '.' ) { + if ( ! $path && ( $dir = dirname( $pattern ) ) != '.' ) { - if ($dir == '\\' || $dir == '/') { $dir = ''; } // End IF Statement + if ( '\\' == $dir || '/' == $dir ) { + $dir = ''; + } - return self::get_files(basename( $pattern ), $flags, $dir . '/' ); + return self::get_files( basename( $pattern ), $flags, $dir . '/' ); - } // End IF Statement + } // End IF Statement - $paths = glob( $path . '*', GLOB_ONLYDIR | GLOB_NOSORT ); - $files = glob( $path . $pattern, $flags ); + $paths = glob( $path . '*', GLOB_ONLYDIR | GLOB_NOSORT ); + $files = glob( $path . $pattern, $flags ); - if ( is_array( $paths ) ) { - foreach ( $paths as $p ) { - $found_files = array(); - $retrieved_files = (array) self::get_files( $pattern, $flags, $p . '/' ); - foreach ( $retrieved_files as $file ) { - if ( ! in_array( $file, self::$found_files ) ) - $found_files[] = $file; - } + if ( is_array( $paths ) ) { + foreach ( $paths as $p ) { + $found_files = array(); + $retrieved_files = (array) self::get_files( $pattern, $flags, $p . '/' ); + foreach ( $retrieved_files as $file ) { + if ( ! in_array( $file, self::$found_files ) ) { + $found_files[] = $file; + } + } - self::$found_files = array_merge( self::$found_files, $found_files ); + self::$found_files = array_merge( self::$found_files, $found_files ); - if ( is_array( $files ) && is_array( $found_files ) ) { - $files = array_merge( $files, $found_files ); - } - - } // End FOREACH Loop - } - return $files; - } + if ( is_array( $files ) && is_array( $found_files ) ) { + $files = array_merge( $files, $found_files ); + } + } // End FOREACH Loop + } + return $files; + } private static function get_hook_link( $hook, $details = array() ) { if ( ! empty( $details['class'] ) ) { - $link = 'http://docs.woothemes.com/wc-apidocs/source-class-' . $details['class'] . '.html#' . $details['line']; + $link = 'http://docs.woocommerce.com/wc-apidocs/source-class-' . $details['class'] . '.html#' . $details['line']; } elseif ( ! empty( $details['function'] ) ) { - $link = 'http://docs.woothemes.com/wc-apidocs/source-function-' . $details['function'] . '.html#' . $details['line']; + $link = 'http://docs.woocommerce.com/wc-apidocs/source-function-' . $details['function'] . '.html#' . $details['line']; } else { - $link = 'https://github.com/woothemes/woocommerce/search?utf8=%E2%9C%93&q=' . $hook; + $link = 'https://github.com/woocommerce/woocommerce/search?utf8=%E2%9C%93&q=' . $hook; } return '' . $hook . ''; @@ -103,15 +105,16 @@ class WC_HookFinder { foreach ( $tokens as $index => $token ) { if ( is_array( $token ) ) { - if ( $token[0] == T_CLASS ) { + $trimmed_token_1 = trim( $token[1] ); + if ( T_CLASS == $token[0] ) { $token_type = 'class'; - } elseif ( $token[0] == T_FUNCTION ) { + } elseif ( T_FUNCTION == $token[0] ) { $token_type = 'function'; - } elseif ( $token[1] === 'do_action' ) { + } elseif ( 'do_action' === $token[1] ) { $token_type = 'action'; - } elseif ( $token[1] === 'apply_filters' ) { + } elseif ( 'apply_filters' === $token[1] ) { $token_type = 'filter'; - } elseif ( $token_type && ! empty( trim( $token[1] ) ) ) { + } elseif ( $token_type && ! empty( $trimmed_token_1 ) ) { switch ( $token_type ) { case 'class' : $current_class = $token[1]; @@ -122,15 +125,54 @@ class WC_HookFinder { case 'filter' : case 'action' : $hook = trim( $token[1], "'" ); + $loop = 0; + + if ( '_' === substr( $hook, '-1', 1 ) ) { + $hook .= '{'; + $open = true; + // Keep adding to hook until we find a comma or colon + while ( 1 ) { + $loop ++; + $next_hook = trim( trim( is_string( $tokens[ $index + $loop ] ) ? $tokens[ $index + $loop ] : $tokens[ $index + $loop ][1], '"' ), "'" ); + + if ( in_array( $next_hook, array( '.', '{', '}', '"', "'", ' ' ) ) ) { + continue; + } + + $hook_first = substr( $next_hook, 0, 1 ); + $hook_last = substr( $next_hook, -1, 1 ); + + if ( in_array( $next_hook, array( ',', ';' ) ) ) { + if ( $open ) { + $hook .= '}'; + $open = false; + } + break; + } + + if ( '_' === $hook_first ) { + $next_hook = '}' . $next_hook; + $open = false; + } + + if ( '_' === $hook_last ) { + $next_hook .= '{'; + $open = true; + } + + $hook .= $next_hook; + } + } + if ( isset( self::$custom_hooks_found[ $hook ] ) ) { self::$custom_hooks_found[ $hook ]['file'][] = self::$current_file; } else { - self::$custom_hooks_found[ $hook ] = array( + self::$custom_hooks_found[ $hook ] = array( 'line' => $token[2], 'class' => $current_class, 'function' => $current_function, 'file' => array( self::$current_file ), - 'type' => $token_type + 'type' => $token_type, ); } break; @@ -169,13 +211,13 @@ class WC_HookFinder { echo '");c.unblock()}})}});new b}(jQuery); \ No newline at end of file +!function(a){var b=Backbone.View.extend({el:a("#key-fields"),events:{"click input#update_api_key":"saveKey"},initialize:function(){_.bindAll(this,"saveKey")},block:function(){a(this.el).block({message:null,overlayCSS:{background:"#fff",opacity:.6}})},unblock:function(){a(this.el).unblock()},initTipTip:function(b){a(document.body).on("aftercopy",b,function(c){!0===c.success["text/plain"]?(a("#copy-error").text(""),a(b).tipTip({attribute:"data-tip",activation:"focus",fadeIn:50,fadeOut:50,delay:0}).focus()):(a(b).parent().find("input").focus().select(),a("#copy-error").text(woocommerce_admin_api_keys.clipboard_failed))}).on("click",b,function(){document.queryCommandSupported("copy")||(a(b).parent().find("input").focus().select(),a("#copy-error").text(woocommerce_admin_api_keys.clipboard_failed))}).on("copy",b,function(b){a("#copy-error").text(""),b.clipboardData.clearData(),b.clipboardData.setData("text/plain",a.trim(a(this).prev("input").val())),b.preventDefault()})},createQRCode:function(b,c){a("#keys-qrcode").qrcode({text:b+"|"+c,width:120,height:120})},saveKey:function(b){b.preventDefault();var c=this;c.block(),Backbone.ajax({method:"POST",dataType:"json",url:woocommerce_admin_api_keys.ajax_url,data:{action:"woocommerce_update_api_key",security:woocommerce_admin_api_keys.update_api_nonce,key_id:a("#key_id",c.el).val(),description:a("#key_description",c.el).val(),user:a("#key_user",c.el).val(),permissions:a("#key_permissions",c.el).val()},success:function(b){if(a(".wc-api-message",c.el).remove(),b.success){var d=b.data;if(a("h3",c.el).first().append('

'+d.message+"

"),0

'+b.data.message+"

");c.unblock()}})}});new b}(jQuery); \ No newline at end of file diff --git a/assets/js/admin/order-backbone-modal.js b/assets/js/admin/backbone-modal.js similarity index 80% rename from assets/js/admin/order-backbone-modal.js rename to assets/js/admin/backbone-modal.js index b8d8eb62260..ea5fe16baaf 100644 --- a/assets/js/admin/order-backbone-modal.js +++ b/assets/js/admin/backbone-modal.js @@ -53,15 +53,28 @@ _string: undefined, events: { 'click .modal-close': 'closeButton', - 'click #btn-ok': 'addButton', + 'click #btn-ok' : 'addButton', 'touchstart #btn-ok': 'addButton', - 'keydown': 'keyboardActions' + 'keydown' : 'keyboardActions' + }, + resizeContent: function() { + var $content = $( '.wc-backbone-modal-content' ).find( 'article' ); + var max_h = $( window ).height() * 0.75; + + $content.css({ + 'max-height': max_h + 'px' + }); }, initialize: function( data ) { + var view = this; this._target = data.target; this._string = data.string; _.bindAll( this, 'render' ); this.render(); + + $( window ).resize(function() { + view.resizeContent(); + }); }, render: function() { var template = wp.template( this._target ); @@ -74,30 +87,9 @@ 'overflow': 'hidden' }).append( this.$el ); - var $content = $( '.wc-backbone-modal-content' ).find( 'article' ); - var content_h = ( $content.height() < 90 ) ? 90 : $content.height(); - var max_h = $( window ).height() - 200; - - if ( max_h > 400 ) { - max_h = 400; - } - - if ( content_h > max_h ) { - $content.css({ - 'overflow': 'auto', - height: max_h + 'px' - }); - } else { - $content.css({ - 'overflow': 'visible', - height: ( content_h > 90 ) ? 'auto' : content_h + 'px' - }); - } - - $( '.wc-backbone-modal-content' ).css({ - 'margin-top': '-' + ( $( '.wc-backbone-modal-content' ).height() / 2 ) + 'px', - 'margin-left': '-' + ( $( '.wc-backbone-modal-content' ).width() / 2 ) + 'px' - }); + this.resizeContent(); + this.$el.focus(); + $( document.body ).trigger( 'init_tooltips' ); $( document.body ).trigger( 'wc_backbone_modal_loaded', this._target ); }, @@ -122,7 +114,8 @@ $( document.body ).trigger( 'wc_backbone_modal_before_update', this._target ); $.each( $( 'form', this.$el ).serializeArray(), function( index, item ) { - if ( data.hasOwnProperty( item.name ) ) { + if ( item.name.indexOf( '[]' ) !== -1 ) { + item.name = item.name.replace( '[]', '' ); data[ item.name ] = $.makeArray( data[ item.name ] ); data[ item.name ].push( item.value ); } else { diff --git a/assets/js/admin/backbone-modal.min.js b/assets/js/admin/backbone-modal.min.js new file mode 100644 index 00000000000..740c80c5c95 --- /dev/null +++ b/assets/js/admin/backbone-modal.min.js @@ -0,0 +1 @@ +!function(a,b,c){"use strict";a.fn.WCBackboneModal=function(b){return this.each(function(){new a.WCBackboneModal(a(this),b)})},a.WCBackboneModal=function(b,c){var d=a.extend({},a.WCBackboneModal.defaultOptions,c);d.template&&new a.WCBackboneModal.View({target:d.template,string:d.variable})},a.WCBackboneModal.defaultOptions={template:"",variable:{}},a.WCBackboneModal.View=b.View.extend({tagName:"div",id:"wc-backbone-modal-dialog",_target:void 0,_string:void 0,events:{"click .modal-close":"closeButton","click #btn-ok":"addButton","touchstart #btn-ok":"addButton",keydown:"keyboardActions"},resizeContent:function(){var b=a(".wc-backbone-modal-content").find("article"),c=.75*a(window).height();b.css({"max-height":c+"px"})},initialize:function(b){var d=this;this._target=b.target,this._string=b.string,c.bindAll(this,"render"),this.render(),a(window).resize(function(){d.resizeContent()})},render:function(){var b=wp.template(this._target);this.$el.attr("tabindex","0").append(b(this._string)),a(document.body).css({overflow:"hidden"}).append(this.$el),this.resizeContent(),this.$el.focus(),a(document.body).trigger("init_tooltips"),a(document.body).trigger("wc_backbone_modal_loaded",this._target)},closeButton:function(b){b.preventDefault(),a(document.body).trigger("wc_backbone_modal_before_remove",this._target),this.undelegateEvents(),a(document).off("focusin"),a(document.body).css({overflow:"auto"}),this.remove(),a(document.body).trigger("wc_backbone_modal_removed",this._target)},addButton:function(b){a(document.body).trigger("wc_backbone_modal_response",[this._target,this.getFormData()]),this.closeButton(b)},getFormData:function(){var b={};return a(document.body).trigger("wc_backbone_modal_before_update",this._target),a.each(a("form",this.$el).serializeArray(),function(c,d){d.name.indexOf("[]")!==-1?(d.name=d.name.replace("[]",""),b[d.name]=a.makeArray(b[d.name]),b[d.name].push(d.value)):b[d.name]=d.value}),b},keyboardActions:function(a){var b=a.keyCode||a.which;13!==b||a.target.tagName&&("input"===a.target.tagName.toLowerCase()||"textarea"===a.target.tagName.toLowerCase())||this.addButton(a),27===b&&this.closeButton(a)}})}(jQuery,Backbone,_); \ No newline at end of file diff --git a/assets/js/admin/meta-boxes-coupon.js b/assets/js/admin/meta-boxes-coupon.js index fec1100539c..4e5377c3abb 100644 --- a/assets/js/admin/meta-boxes-coupon.js +++ b/assets/js/admin/meta-boxes-coupon.js @@ -21,7 +21,7 @@ jQuery(function( $ ) { // Get value var select_val = $( this ).val(); - if ( select_val === 'fixed_product' || select_val === 'percent_product' ) { + if ( select_val !== 'fixed_cart' ) { $( '.limit_usage_to_x_items_field' ).show(); } else { $( '.limit_usage_to_x_items_field' ).hide(); diff --git a/assets/js/admin/meta-boxes-coupon.min.js b/assets/js/admin/meta-boxes-coupon.min.js index e9de32aad06..7d39b599dfd 100644 --- a/assets/js/admin/meta-boxes-coupon.min.js +++ b/assets/js/admin/meta-boxes-coupon.min.js @@ -1 +1 @@ -jQuery(function(a){var b={init:function(){a("select#discount_type").on("change",this.type_options).change()},type_options:function(){var b=a(this).val();"fixed_product"===b||"percent_product"===b?a(".limit_usage_to_x_items_field").show():a(".limit_usage_to_x_items_field").hide()}};b.init()}); \ No newline at end of file +jQuery(function(a){var b={init:function(){a("select#discount_type").on("change",this.type_options).change()},type_options:function(){var b=a(this).val();"fixed_cart"!==b?a(".limit_usage_to_x_items_field").show():a(".limit_usage_to_x_items_field").hide()}};b.init()}); \ No newline at end of file diff --git a/assets/js/admin/meta-boxes-order.js b/assets/js/admin/meta-boxes-order.js index f250f1b53c9..68eed9fa703 100644 --- a/assets/js/admin/meta-boxes-order.js +++ b/assets/js/admin/meta-boxes-order.js @@ -99,10 +99,26 @@ jQuery( function ( $ ) { edit_address: function( e ) { e.preventDefault(); - $( this ).hide(); - $( this ).parent().find( 'a:not(.edit_address)' ).show(); - $( this ).closest( '.order_data_column' ).find( 'div.address' ).hide(); - $( this ).closest( '.order_data_column' ).find( 'div.edit_address' ).show(); + + var $this = $( this ), + $wrapper = $this.closest( '.order_data_column' ), + $edit_address = $wrapper.find( 'div.edit_address' ), + $address = $wrapper.find( 'div.address' ), + $country_input = $edit_address.find( '.js_field-country' ), + $state_input = $edit_address.find( '.js_field-state' ); + + $address.hide(); + $this.parent().find( 'a' ).toggle(); + + if ( ! $country_input.val() ) { + $country_input.val( woocommerce_admin_meta_boxes_order.default_country ).change(); + } + + if ( ! $state_input.val() ) { + $state_input.val( woocommerce_admin_meta_boxes_order.default_state ).change(); + } + + $edit_address.show(); }, change_customer_user: function() { @@ -125,10 +141,9 @@ jQuery( function ( $ ) { } var data = { - user_id: user_id, - type_to_load: 'billing', - action: 'woocommerce_get_customer_details', - security: woocommerce_admin_meta_boxes.get_customer_details_nonce + user_id : user_id, + action : 'woocommerce_get_customer_details', + security: woocommerce_admin_meta_boxes.get_customer_details_nonce }; $( this ).closest( 'div.edit_address' ).block({ @@ -144,9 +159,9 @@ jQuery( function ( $ ) { data: data, type: 'POST', success: function( response ) { - if ( response ) { - $.each( response, function( key, data ) { - $( ':input#_' + key ).val( data ).change(); + if ( response && response.billing ) { + $.each( response.billing, function( key, data ) { + $( ':input#_billing_' + key ).val( data ).change(); }); } $( 'div.edit_address' ).unblock(); @@ -169,7 +184,6 @@ jQuery( function ( $ ) { var data = { user_id: user_id, - type_to_load: 'shipping', action: 'woocommerce_get_customer_details', security: woocommerce_admin_meta_boxes.get_customer_details_nonce }; @@ -187,9 +201,9 @@ jQuery( function ( $ ) { data: data, type: 'POST', success: function( response ) { - if ( response ) { - $.each( response, function( key, data ) { - $( ':input#_' + key ).val( data ).change(); + if ( response && response.billing ) { + $.each( response.shipping, function( key, data ) { + $( ':input#_shipping_' + key ).val( data ).change(); }); } $( 'div.edit_address' ).unblock(); @@ -226,14 +240,16 @@ jQuery( function ( $ ) { .on( 'click', 'button.add-order-fee', this.add_fee ) .on( 'click', 'button.add-order-shipping', this.add_shipping ) .on( 'click', 'button.add-order-tax', this.add_tax ) - .on( 'click', 'input.check-column', this.bulk_actions.check_column ) - .on( 'click', '.do_bulk_action', this.bulk_actions.do_bulk_action ) - .on( 'click', 'button.calculate-action', this.calculate_totals ) .on( 'click', 'button.save-action', this.save_line_items ) .on( 'click', 'a.delete-order-tax', this.delete_tax ) - .on( 'click', 'button.calculate-tax-action', this.calculate_tax ) + .on( 'click', 'button.calculate-action', this.recalculate ) .on( 'click', 'a.edit-order-item', this.edit_item ) .on( 'click', 'a.delete-order-item', this.delete_item ) + .on( 'click', 'tr.item, tr.fee, tr.shipping, tr.refund', this.select_row ) + .on( 'click', 'tr.item :input, tr.fee :input, tr.shipping :input, tr.refund :input, tr.item a, tr.fee a, tr.shipping a, tr.refund a', this.select_row_child ) + .on( 'click', 'button.bulk-delete-items', this.bulk_actions.do_delete ) + .on( 'click', 'button.bulk-increase-stock', this.bulk_actions.do_increase_stock ) + .on( 'click', 'button.bulk-decrease-stock', this.bulk_actions.do_reduce_stock ) // Refunds .on( 'click', '.delete_refund', this.refunds.delete_refund ) @@ -246,14 +262,14 @@ jQuery( function ( $ ) { .on( 'change', 'input.quantity', this.quantity_changed ) // Subtotal/total - .on( 'keyup', '.woocommerce_order_items .split-input input:eq(0)', function() { - var $subtotal = $( this ).next(); - if ( $subtotal.val() === '' || $subtotal.is( '.match-total' ) ) { + .on( 'keyup change', '.split-input :input', function() { + var $subtotal = $( this ).parent().prev().find(':input'); + if ( $subtotal && ( $subtotal.val() === '' || $subtotal.is( '.match-total' ) ) ) { $subtotal.val( $( this ).val() ).addClass( 'match-total' ); } }) - .on( 'keyup', '.woocommerce_order_items .split-input input:eq(1)', function() { + .on( 'keyup', '.split-input :input', function() { $( this ).removeClass( 'match-total' ); }) @@ -327,21 +343,23 @@ jQuery( function ( $ ) { ); // Taxes - $( 'td.line_tax', $row ).each(function() { - var line_total_tax = $( 'input.line_tax', $( this ) ); - var unit_total_tax = accounting.unformat( line_total_tax.attr( 'data-total_tax' ), woocommerce_admin.mon_decimal_point ) / o_qty; + $( 'input.line_tax', $row ).each( function() { + var $line_total_tax = $( this ); + var tax_id = $line_total_tax.data( 'tax_id' ); + var unit_total_tax = accounting.unformat( $line_total_tax.attr( 'data-total_tax' ), woocommerce_admin.mon_decimal_point ) / o_qty; + var $line_subtotal_tax = $( 'input.line_subtotal_tax[data-tax_id="' + tax_id + '"]', $row ); + var unit_subtotal_tax = accounting.unformat( $line_subtotal_tax.attr( 'data-subtotal_tax' ), woocommerce_admin.mon_decimal_point ) / o_qty; + if ( 0 < unit_total_tax ) { - line_total_tax.val( + $line_total_tax.val( parseFloat( accounting.formatNumber( unit_total_tax * qty, woocommerce_admin_meta_boxes.rounding_precision, '' ) ) .toString() .replace( '.', woocommerce_admin.mon_decimal_point ) ); } - var line_subtotal_tax = $( 'input.line_subtotal_tax', $( this ) ); - var unit_subtotal_tax = accounting.unformat( line_subtotal_tax.attr( 'data-subtotal_tax' ), woocommerce_admin.mon_decimal_point ) / o_qty; if ( 0 < unit_subtotal_tax ) { - line_subtotal_tax.val( + $line_subtotal_tax.val( parseFloat( accounting.formatNumber( unit_subtotal_tax * qty, woocommerce_admin_meta_boxes.rounding_precision, '' ) ) .toString() .replace( '.', woocommerce_admin.mon_decimal_point ) @@ -354,13 +372,13 @@ jQuery( function ( $ ) { add_line_item: function() { $( 'div.wc-order-add-item' ).slideDown(); - $( 'div.wc-order-bulk-actions' ).slideUp(); + $( 'div.wc-order-data-row-toggle' ).not( 'div.wc-order-add-item' ).slideUp(); return false; }, refund_items: function() { $( 'div.wc-order-refund-items' ).slideDown(); - $( 'div.wc-order-bulk-actions' ).slideUp(); + $( 'div.wc-order-data-row-toggle' ).not( 'div.wc-order-refund-items' ).slideUp(); $( 'div.wc-order-totals-items' ).slideUp(); $( '#woocommerce-order-items' ).find( 'div.refund' ).show(); $( '.wc-order-edit-line-item .wc-order-edit-line-item-actions' ).hide(); @@ -368,7 +386,7 @@ jQuery( function ( $ ) { }, cancel: function() { - $( this ).closest( 'div.wc-order-data-row' ).slideUp(); + $( 'div.wc-order-data-row-toggle' ).not( 'div.wc-order-bulk-actions' ).slideUp(); $( 'div.wc-order-bulk-actions' ).slideDown(); $( 'div.wc-order-totals-items' ).slideDown(); $( '#woocommerce-order-items' ).find( 'div.refund' ).hide(); @@ -394,13 +412,18 @@ jQuery( function ( $ ) { wc_meta_boxes_order_items.block(); var data = { - action: 'woocommerce_add_order_fee', - order_id: woocommerce_admin_meta_boxes.post_id, - security: woocommerce_admin_meta_boxes.order_item_nonce + action : 'woocommerce_add_order_fee', + order_id : woocommerce_admin_meta_boxes.post_id, + dataType : 'json', + security : woocommerce_admin_meta_boxes.order_item_nonce }; $.post( woocommerce_admin_meta_boxes.ajax_url, data, function( response ) { - $( 'table.woocommerce_order_items tbody#order_fee_line_items' ).append( response ); + if ( response.success ) { + $( 'table.woocommerce_order_items tbody#order_fee_line_items' ).append( response.data.html ); + } else { + window.alert( response.data.error ); + } wc_meta_boxes_order_items.unblock(); }); @@ -411,13 +434,18 @@ jQuery( function ( $ ) { wc_meta_boxes_order_items.block(); var data = { - action: 'woocommerce_add_order_shipping', - order_id: woocommerce_admin_meta_boxes.post_id, - security: woocommerce_admin_meta_boxes.order_item_nonce + action : 'woocommerce_add_order_shipping', + order_id : woocommerce_admin_meta_boxes.post_id, + security : woocommerce_admin_meta_boxes.order_item_nonce, + dataType : 'json' }; $.post( woocommerce_admin_meta_boxes.ajax_url, data, function( response ) { - $( 'table.woocommerce_order_items tbody#order_shipping_line_items' ).append( response ); + if ( response.success ) { + $( 'table.woocommerce_order_items tbody#order_shipping_line_items' ).append( response.data.html ); + } else { + window.alert( response.data.error ); + } wc_meta_boxes_order_items.unblock(); }); @@ -495,8 +523,8 @@ jQuery( function ( $ ) { return false; }, - calculate_tax: function() { - if ( window.confirm( woocommerce_admin_meta_boxes.calc_line_taxes ) ) { + recalculate: function() { + if ( window.confirm( woocommerce_admin_meta_boxes.calc_totals ) ) { wc_meta_boxes_order_items.block(); var country = ''; @@ -546,49 +574,6 @@ jQuery( function ( $ ) { return false; }, - calculate_totals: function() { - if ( window.confirm( woocommerce_admin_meta_boxes.calc_totals ) ) { - - wc_meta_boxes_order_items.block(); - - // Get row totals - var line_totals = 0; - var tax = 0; - var shipping = 0; - - $( '.woocommerce_order_items tr.shipping input.line_total' ).each(function() { - var cost = $( this ).val() || '0'; - cost = accounting.unformat( cost, woocommerce_admin.mon_decimal_point ); - shipping = shipping + parseFloat( cost ); - }); - - $( '.woocommerce_order_items input.line_tax' ).each(function() { - var cost = $( this ).val() || '0'; - cost = accounting.unformat( cost, woocommerce_admin.mon_decimal_point ); - tax = tax + parseFloat( cost ); - }); - - $( '.woocommerce_order_items tr.item, .woocommerce_order_items tr.fee' ).each(function() { - var line_total = $( this ).find( 'input.line_total' ).val() || '0'; - line_totals = line_totals + accounting.unformat( line_total.replace( ',', '.' ) ); - }); - - // Tax - if ( 'yes' === woocommerce_admin_meta_boxes.round_at_subtotal ) { - tax = parseFloat( accounting.toFixed( tax, woocommerce_admin_meta_boxes.rounding_precision ) ); - } - - // Set Total - $( '#_order_total' ) - .val( accounting.formatNumber( line_totals + tax + shipping, woocommerce_admin_meta_boxes.currency_format_num_decimals, '', woocommerce_admin.mon_decimal_point ) ) - .change(); - - $( 'button.save-action' ).click(); - } - - return false; - }, - save_line_items: function() { var data = { order_id: woocommerce_admin_meta_boxes.post_id, @@ -666,7 +651,7 @@ jQuery( function ( $ ) { line_item_totals: JSON.stringify( line_item_totals, null, '' ), line_item_tax_totals: JSON.stringify( line_item_tax_totals, null, '' ), api_refund: $( this ).is( '.do-api-refund' ), - restock_refunded_items: $( '#restock_refunded_items:checked' ).size() ? 'true' : 'false', + restock_refunded_items: $( '#restock_refunded_items:checked' ).length ? 'true' : 'false', security: woocommerce_admin_meta_boxes.order_item_nonce }; @@ -766,19 +751,20 @@ jQuery( function ( $ ) { ).change(); // Taxes - $( 'td.line_tax', $row ).each( function() { - var line_total_tax = $( 'input.line_tax', $( this ) ); - var refund_line_total_tax = $( 'input.refund_line_tax', $( this ) ); - var unit_total_tax = accounting.unformat( line_total_tax.attr( 'data-total_tax' ), woocommerce_admin.mon_decimal_point ) / qty; + $( '.refund_line_tax', $row ).each( function() { + var $refund_line_total_tax = $( this ); + var tax_id = $refund_line_total_tax.data( 'tax_id' ); + var line_total_tax = $( 'input.line_tax[data-tax_id="' + tax_id + '"]', $row ); + var unit_total_tax = accounting.unformat( line_total_tax.data( 'total_tax' ), woocommerce_admin.mon_decimal_point ) / qty; if ( 0 < unit_total_tax ) { - refund_line_total_tax.val( + $refund_line_total_tax.val( parseFloat( accounting.formatNumber( unit_total_tax * refund_qty, woocommerce_admin_meta_boxes.rounding_precision, '' ) ) .toString() .replace( '.', woocommerce_admin.mon_decimal_point ) ).change(); } else { - refund_line_total_tax.val( 0 ).change(); + $refund_line_total_tax.val( 0 ).change(); } }); @@ -802,25 +788,17 @@ jQuery( function ( $ ) { add: function() { var $button = $( this ); - var $item = $button.closest( 'tr.item' ); - - var data = { - order_item_id: $item.attr( 'data-order_item_id' ), - action: 'woocommerce_add_order_item_meta', - security: woocommerce_admin_meta_boxes.order_item_nonce - }; - - wc_meta_boxes_order_items.block(); - - $.ajax({ - url: woocommerce_admin_meta_boxes.ajax_url, - data: data, - type: 'POST', - success: function( response ) { - $item.find('tbody.meta_items').append( response ); - wc_meta_boxes_order_items.unblock(); - } - }); + var $item = $button.closest( 'tr.item, tr.shipping' ); + var $items = $item.find('tbody.meta_items'); + var index = $items.find('tr').length + 1; + var $row = '' + + '' + + '' + + '' + + '' + + '' + + ''; + $items.append( $row ); return false; }, @@ -828,100 +806,131 @@ jQuery( function ( $ ) { remove: function() { if ( window.confirm( woocommerce_admin_meta_boxes.remove_item_meta ) ) { var $row = $( this ).closest( 'tr' ); - - var data = { - meta_id: $row.attr( 'data-meta_id' ), - action: 'woocommerce_remove_order_item_meta', - security: woocommerce_admin_meta_boxes.order_item_nonce - }; - - wc_meta_boxes_order_items.block(); - - $.ajax({ - url: woocommerce_admin_meta_boxes.ajax_url, - data: data, - type: 'POST', - success: function() { - $row.hide(); - wc_meta_boxes_order_items.unblock(); - } - }); + $row.find( ':input' ).val( '' ); + $row.hide(); } return false; } }, - bulk_actions: { + select_row: function() { + var $row = false; + if ( $( this ).is( 'tr' ) ) { + $row = $( this ); + } else { + $row = $( this ).closest( 'tr' ); + } + var $table = $( this ).closest( 'table' ); - check_column: function() { - if ( $( this ).is( ':checked' ) ) { - $( '#woocommerce-order-items' ).find( '.check-column input' ).attr( 'checked', 'checked' ); - } else { - $( '#woocommerce-order-items' ).find( '.check-column input' ).removeAttr( 'checked' ); - } - }, + if ( $row.is( '.selected' ) ) { + $row.removeClass( 'selected' ); + } else { + $row.addClass( 'selected' ); + } - do_bulk_action: function() { - var action = $( this ).closest( '.bulk-actions' ).find( 'select' ).val(); - var selected_rows = $( '#woocommerce-order-items' ).find( '.check-column input:checked' ); - var item_ids = []; + var $rows = $table.find( 'tr.selected' ); - $( selected_rows ).each( function() { - var $item = $( this ).closest( 'tr' ); + if ( $rows.length ) { + $( 'div.wc-order-item-bulk-edit' ).slideDown(); - if ( $item.attr( 'data-order_item_id' ) ) { - item_ids.push( $item.attr( 'data-order_item_id' ) ); + var selected_product = false; + + $rows.each( function() { + if ( $( this ).is( 'tr.item' ) ) { + selected_product = true; } } ); - if ( item_ids.length === 0 ) { - window.alert( woocommerce_admin_meta_boxes.i18n_select_items ); - return; + if ( selected_product ) { + $( '.bulk-increase-stock, .bulk-decrease-stock' ).show(); + } else { + $( '.bulk-increase-stock, .bulk-decrease-stock' ).hide(); } + } else { + $( 'div.wc-order-item-bulk-edit' ).slideUp(); + } + }, - if ( wc_meta_boxes_order_items.bulk_actions[ 'do_' + action ] ) { - wc_meta_boxes_order_items.bulk_actions[ 'do_' + action ]( selected_rows, item_ids ); - } + select_row_child: function( e ) { + e.stopPropagation(); + }, - return false; - }, + bulk_actions: { - do_delete: function( selected_rows, item_ids ) { - if ( window.confirm( woocommerce_admin_meta_boxes.remove_item_notice ) ) { + do_delete: function( e ) { + e.preventDefault(); + var $table = $( 'table.woocommerce_order_items' ); + var $rows = $table.find( 'tr.selected' ); + + if ( $rows.length && window.confirm( woocommerce_admin_meta_boxes.remove_item_notice ) ) { wc_meta_boxes_order_items.block(); - var data = { - order_item_ids: item_ids, - action: 'woocommerce_remove_order_item', - security: woocommerce_admin_meta_boxes.order_item_nonce - }; + var delete_items = []; + var delete_refunds = []; + var deferred = []; - $.ajax({ - url: woocommerce_admin_meta_boxes.ajax_url, - data: data, - type: 'POST', - success: function() { - $( selected_rows ).each(function() { - $( this ).closest( 'tr' ).remove(); - }); - wc_meta_boxes_order_items.unblock(); + $.map( $rows, function( row ) { + var $row = $( row ); + + if ( $row.is( '.refund' ) ) { + delete_refunds.push( parseInt( $( $row ).data( 'order_refund_id' ), 10 ) ); + } else { + delete_items.push( parseInt( $( $row ).data( 'order_item_id' ), 10 ) ); } + return ; }); + + if ( delete_items.length ) { + deferred.push( $.ajax({ + url : woocommerce_admin_meta_boxes.ajax_url, + data: { + order_item_ids: delete_items, + action: 'woocommerce_remove_order_item', + security: woocommerce_admin_meta_boxes.order_item_nonce + }, + type: 'POST' + } ) ); + } + + if ( delete_refunds.length ) { + deferred.push( $.ajax( { + url : woocommerce_admin_meta_boxes.ajax_url, + data: { + action: 'woocommerce_delete_refund', + refund_id: delete_refunds, + security: woocommerce_admin_meta_boxes.order_item_nonce + }, + type: 'POST' + } ) ); + } + + if ( deferred ) { + $.when.apply( $, deferred ).done( function() { + wc_meta_boxes_order_items.reload_items(); + wc_meta_boxes_order_items.unblock(); + } ); + } else { + wc_meta_boxes_order_items.unblock(); + } } }, - do_increase_stock: function( selected_rows, item_ids ) { + do_increase_stock: function( e ) { + e.preventDefault(); wc_meta_boxes_order_items.block(); + var $table = $( 'table.woocommerce_order_items' ); + var $rows = $table.find( 'tr.selected' ); var quantities = {}; + var item_ids = $.map( $rows, function( $row ) { + return parseInt( $( $row ).data( 'order_item_id' ), 10 ); + }); - $( selected_rows ).each(function() { - - var $item = $( this ).closest( 'tr.item, tr.fee' ); - var $qty = $item.find( 'input.quantity' ); - - quantities[ $item.attr( 'data-order_item_id' ) ] = $qty.val(); + $rows.each(function() { + if ( $( this ).find( 'input.quantity' ).length ) { + quantities[ $( this ).attr( 'data-order_item_id' ) ] = $( this ).find( 'input.quantity' ).val(); + } }); var data = { @@ -943,17 +952,21 @@ jQuery( function ( $ ) { }); }, - do_reduce_stock: function( selected_rows, item_ids ) { + do_reduce_stock: function( e ) { + e.preventDefault(); wc_meta_boxes_order_items.block(); + var $table = $( 'table.woocommerce_order_items' ); + var $rows = $table.find( 'tr.selected' ); var quantities = {}; + var item_ids = $.map( $rows, function( $row ) { + return parseInt( $( $row ).data( 'order_item_id' ), 10 ); + }); - $( selected_rows ).each(function() { - - var $item = $( this ).closest( 'tr.item, tr.fee' ); - var $qty = $item.find( 'input.quantity' ); - - quantities[ $item.attr( 'data-order_item_id' ) ] = $qty.val(); + $rows.each(function() { + if ( $( this ).find( 'input.quantity' ).length ) { + quantities[ $( this ).attr( 'data-order_item_id' ) ] = $( this ).find( 'input.quantity' ).val(); + } }); var data = { @@ -1001,34 +1014,27 @@ jQuery( function ( $ ) { }, add_item: function( add_item_ids ) { - add_item_ids = add_item_ids.split( ',' ); - if ( add_item_ids ) { - - var count = add_item_ids.length; - wc_meta_boxes_order_items.block(); - $.each( add_item_ids, function( index, value ) { + var data = { + action : 'woocommerce_add_order_item', + item_to_add: add_item_ids, + dataType : 'json', + order_id : woocommerce_admin_meta_boxes.post_id, + security : woocommerce_admin_meta_boxes.order_item_nonce + }; - var data = { - action: 'woocommerce_add_order_item', - item_to_add: value, - order_id: woocommerce_admin_meta_boxes.post_id, - security: woocommerce_admin_meta_boxes.order_item_nonce - }; - - $.post( woocommerce_admin_meta_boxes.ajax_url, data, function( response ) { - $( 'table.woocommerce_order_items tbody#order_line_items' ).append( response ); - - if ( !--count ) { - wc_meta_boxes_order.init_tiptip(); - wc_meta_boxes_order_items.unblock(); - } - }); + $.post( woocommerce_admin_meta_boxes.ajax_url, data, function( response ) { + if ( response.success ) { + $( 'table.woocommerce_order_items tbody#order_line_items' ).append( response.data.html ); + } else { + window.alert( response.data.error ); + } + wc_meta_boxes_order.init_tiptip(); + wc_meta_boxes_order_items.unblock(); }); - } }, @@ -1057,15 +1063,20 @@ jQuery( function ( $ ) { }; $.ajax({ - url: woocommerce_admin_meta_boxes.ajax_url, - data: data, - type: 'POST', - success: function( response ) { - $( '#woocommerce-order-items' ).find( '.inside' ).empty(); - $( '#woocommerce-order-items' ).find( '.inside' ).append( response ); - wc_meta_boxes_order.init_tiptip(); + url : woocommerce_admin_meta_boxes.ajax_url, + data : data, + dataType : 'json', + type : 'POST', + success : function( response ) { + if ( response.success ) { + $( '#woocommerce-order-items' ).find( '.inside' ).empty(); + $( '#woocommerce-order-items' ).find( '.inside' ).append( response.data.html ); + wc_meta_boxes_order.init_tiptip(); + wc_meta_boxes_order_items.stupidtable.init(); + } else { + window.alert( response.data.error ); + } wc_meta_boxes_order_items.unblock(); - wc_meta_boxes_order_items.stupidtable.init(); } }); } else { @@ -1076,18 +1087,14 @@ jQuery( function ( $ ) { stupidtable: { init: function() { - $( '.woocommerce_order_items' ).stupidtable().on( 'aftertablesort', this.add_arrows ); + $( '.woocommerce_order_items' ).stupidtable(); + $( '.woocommerce_order_items' ).on( 'aftertablesort', this.add_arrows ); }, add_arrows: function( event, data ) { var th = $( this ).find( 'th' ); var arrow = data.direction === 'asc' ? '↑' : '↓'; var index = data.column; - - if ( 1 < index ) { - index = index - 1; - } - th.find( '.wc-arrow' ).remove(); th.eq( index ).append( '' + arrow + '' ); } @@ -1100,7 +1107,7 @@ jQuery( function ( $ ) { var wc_meta_boxes_order_notes = { init: function() { $( '#woocommerce-order-notes' ) - .on( 'click', 'a.add_note', this.add_order_note ) + .on( 'click', 'button.add_note', this.add_order_note ) .on( 'click', 'a.delete_note', this.delete_order_note ); }, @@ -1136,25 +1143,27 @@ jQuery( function ( $ ) { }, delete_order_note: function() { - var note = $( this ).closest( 'li.note' ); + if ( window.confirm( woocommerce_admin_meta_boxes.i18n_delete_note ) ) { + var note = $( this ).closest( 'li.note' ); - $( note ).block({ - message: null, - overlayCSS: { - background: '#fff', - opacity: 0.6 - } - }); + $( note ).block({ + message: null, + overlayCSS: { + background: '#fff', + opacity: 0.6 + } + }); - var data = { - action: 'woocommerce_delete_order_note', - note_id: $( note ).attr( 'rel' ), - security: woocommerce_admin_meta_boxes.delete_order_note_nonce - }; + var data = { + action: 'woocommerce_delete_order_note', + note_id: $( note ).attr( 'rel' ), + security: woocommerce_admin_meta_boxes.delete_order_note_nonce + }; - $.post( woocommerce_admin_meta_boxes.ajax_url, data, function() { - $( note ).remove(); - }); + $.post( woocommerce_admin_meta_boxes.ajax_url, data, function() { + $( note ).remove(); + }); + } return false; } @@ -1188,7 +1197,7 @@ jQuery( function ( $ ) { var data = { action: 'woocommerce_grant_access_to_download', product_ids: products, - loop: $('.order_download_permissions .wc-metabox').size(), + loop: $('.order_download_permissions .wc-metabox').length, order_id: woocommerce_admin_meta_boxes.post_id, security: woocommerce_admin_meta_boxes.grant_access_nonce }; @@ -1211,9 +1220,10 @@ jQuery( function ( $ ) { revoke_access: function () { if ( window.confirm( woocommerce_admin_meta_boxes.i18n_permission_revoke ) ) { - var el = $( this ).parent().parent(); - var product = $( this ).attr( 'rel' ).split( ',' )[0]; - var file = $( this ).attr( 'rel' ).split( ',' )[1]; + var el = $( this ).parent().parent(); + var product = $( this ).attr( 'rel' ).split( ',' )[0]; + var file = $( this ).attr( 'rel' ).split( ',' )[1]; + var permission_id = $( this ).data( 'permission_id' ); if ( product > 0 ) { $( el ).block({ @@ -1225,11 +1235,12 @@ jQuery( function ( $ ) { }); var data = { - action: 'woocommerce_revoke_access_to_download', - product_id: product, - download_id: file, - order_id: woocommerce_admin_meta_boxes.post_id, - security: woocommerce_admin_meta_boxes.revoke_access_nonce + action: 'woocommerce_revoke_access_to_download', + product_id: product, + download_id: file, + permission_id: permission_id, + order_id: woocommerce_admin_meta_boxes.post_id, + security: woocommerce_admin_meta_boxes.revoke_access_nonce }; $.post( woocommerce_admin_meta_boxes.ajax_url, data, function() { diff --git a/assets/js/admin/meta-boxes-order.min.js b/assets/js/admin/meta-boxes-order.min.js index 9e5ffc6dca9..a54fdb8207f 100644 --- a/assets/js/admin/meta-boxes-order.min.js +++ b/assets/js/admin/meta-boxes-order.min.js @@ -1 +1 @@ -jQuery(function(a){var b={states:null,init:function(){"undefined"!=typeof woocommerce_admin_meta_boxes_order&&"undefined"!=typeof woocommerce_admin_meta_boxes_order.countries&&(this.states=a.parseJSON(woocommerce_admin_meta_boxes_order.countries.replace(/"/g,'"'))),a(".js_field-country").select2().change(this.change_country),a(".js_field-country").trigger("change",[!0]),a(document.body).on("change","select.js_field-state",this.change_state),a("#woocommerce-order-actions input, #woocommerce-order-actions a").click(function(){window.onbeforeunload=""}),a("a.edit_address").click(this.edit_address),a("a.billing-same-as-shipping").on("click",this.copy_billing_to_shipping),a("a.load_customer_billing").on("click",this.load_billing),a("a.load_customer_shipping").on("click",this.load_shipping),a("#customer_user").on("change",this.change_customer_user)},change_country:function(c,d){if("undefined"==typeof d&&(d=!1),null!==b.states){var e=a(this),f=e.val(),g=e.parents("div.edit_address").find(":input.js_field-state"),h=g.parent(),i=g.attr("name"),j=g.attr("id"),k=e.data("woocommerce.stickState-"+f)?e.data("woocommerce.stickState-"+f):g.val(),l=g.attr("placeholder");if(d&&e.data("woocommerce.stickState-"+f,k),h.show().find(".select2-container").remove(),a.isEmptyObject(b.states[f]))g.replaceWith('');else{var m=a(''),n=b.states[f];m.append(a('")),a.each(n,function(b){m.append(a('"))}),m.val(k),g.replaceWith(m),m.show().select2().hide().change()}a(document.body).trigger("contry-change.woocommerce",[f,a(this).closest("div")]),a(document.body).trigger("country-change.woocommerce",[f,a(this).closest("div")])}},change_state:function(){var b=a(this),c=b.val(),d=b.parents("div.edit_address").find(":input.js_field-country"),e=d.val();d.data("woocommerce.stickState-"+e,c)},init_tiptip:function(){a("#tiptip_holder").removeAttr("style"),a("#tiptip_arrow").removeAttr("style"),a(".tips").tipTip({attribute:"data-tip",fadeIn:50,fadeOut:50,delay:200})},edit_address:function(b){b.preventDefault(),a(this).hide(),a(this).parent().find("a:not(.edit_address)").show(),a(this).closest(".order_data_column").find("div.address").hide(),a(this).closest(".order_data_column").find("div.edit_address").show()},change_customer_user:function(){a("#_billing_country").val()||(a("a.edit_address").click(),b.load_billing(!0),b.load_shipping(!0))},load_billing:function(b){if(!0===b||window.confirm(woocommerce_admin_meta_boxes.load_billing)){var c=a("#customer_user").val();if(!c)return window.alert(woocommerce_admin_meta_boxes.no_customer_selected),!1;var d={user_id:c,type_to_load:"billing",action:"woocommerce_get_customer_details",security:woocommerce_admin_meta_boxes.get_customer_details_nonce};a(this).closest("div.edit_address").block({message:null,overlayCSS:{background:"#fff",opacity:.6}}),a.ajax({url:woocommerce_admin_meta_boxes.ajax_url,data:d,type:"POST",success:function(b){b&&a.each(b,function(b,c){a(":input#_"+b).val(c).change()}),a("div.edit_address").unblock()}})}return!1},load_shipping:function(b){if(!0===b||window.confirm(woocommerce_admin_meta_boxes.load_shipping)){var c=a("#customer_user").val();if(!c)return window.alert(woocommerce_admin_meta_boxes.no_customer_selected),!1;var d={user_id:c,type_to_load:"shipping",action:"woocommerce_get_customer_details",security:woocommerce_admin_meta_boxes.get_customer_details_nonce};a(this).closest("div.edit_address").block({message:null,overlayCSS:{background:"#fff",opacity:.6}}),a.ajax({url:woocommerce_admin_meta_boxes.ajax_url,data:d,type:"POST",success:function(b){b&&a.each(b,function(b,c){a(":input#_"+b).val(c).change()}),a("div.edit_address").unblock()}})}return!1},copy_billing_to_shipping:function(){return window.confirm(woocommerce_admin_meta_boxes.copy_billing)&&a('.order_data_column :input[name^="_billing_"]').each(function(){var b=a(this).attr("name");b=b.replace("_billing_","_shipping_"),a(":input#"+b).val(a(this).val()).change()}),!1}},c={init:function(){this.stupidtable.init(),a("#woocommerce-order-items").on("click","button.add-line-item",this.add_line_item).on("click","button.refund-items",this.refund_items).on("click",".cancel-action",this.cancel).on("click","button.add-order-item",this.add_item).on("click","button.add-order-fee",this.add_fee).on("click","button.add-order-shipping",this.add_shipping).on("click","button.add-order-tax",this.add_tax).on("click","input.check-column",this.bulk_actions.check_column).on("click",".do_bulk_action",this.bulk_actions.do_bulk_action).on("click","button.calculate-action",this.calculate_totals).on("click","button.save-action",this.save_line_items).on("click","a.delete-order-tax",this.delete_tax).on("click","button.calculate-tax-action",this.calculate_tax).on("click","a.edit-order-item",this.edit_item).on("click","a.delete-order-item",this.delete_item).on("click",".delete_refund",this.refunds.delete_refund).on("click","button.do-api-refund, button.do-manual-refund",this.refunds.do_refund).on("change",".refund input.refund_line_total, .refund input.refund_line_tax",this.refunds.input_changed).on("change keyup",".wc-order-refund-items #refund_amount",this.refunds.amount_changed).on("change","input.refund_order_item_qty",this.refunds.refund_quantity_changed).on("change","input.quantity",this.quantity_changed).on("keyup",".woocommerce_order_items .split-input input:eq(0)",function(){var b=a(this).next();(""===b.val()||b.is(".match-total"))&&b.val(a(this).val()).addClass("match-total")}).on("keyup",".woocommerce_order_items .split-input input:eq(1)",function(){a(this).removeClass("match-total")}).on("click","button.add_order_item_meta",this.item_meta.add).on("click","button.remove_order_item_meta",this.item_meta.remove),a(document.body).on("wc_backbone_modal_loaded",this.backbone.init).on("wc_backbone_modal_response",this.backbone.response)},block:function(){a("#woocommerce-order-items").block({message:null,overlayCSS:{background:"#fff",opacity:.6}})},unblock:function(){a("#woocommerce-order-items").unblock()},reload_items:function(){var d={order_id:woocommerce_admin_meta_boxes.post_id,action:"woocommerce_load_order_items",security:woocommerce_admin_meta_boxes.order_item_nonce};c.block(),a.ajax({url:woocommerce_admin_meta_boxes.ajax_url,data:d,type:"POST",success:function(d){a("#woocommerce-order-items").find(".inside").empty(),a("#woocommerce-order-items").find(".inside").append(d),b.init_tiptip(),c.unblock(),c.stupidtable.init()}})},quantity_changed:function(){var b=a(this).closest("tr.item"),c=a(this).val(),d=a(this).attr("data-qty"),e=a("input.line_total",b),f=a("input.line_subtotal",b),g=accounting.unformat(e.attr("data-total"),woocommerce_admin.mon_decimal_point)/d;e.val(parseFloat(accounting.formatNumber(g*c,woocommerce_admin_meta_boxes.rounding_precision,"")).toString().replace(".",woocommerce_admin.mon_decimal_point));var h=accounting.unformat(f.attr("data-subtotal"),woocommerce_admin.mon_decimal_point)/d;f.val(parseFloat(accounting.formatNumber(h*c,woocommerce_admin_meta_boxes.rounding_precision,"")).toString().replace(".",woocommerce_admin.mon_decimal_point)),a("td.line_tax",b).each(function(){var b=a("input.line_tax",a(this)),e=accounting.unformat(b.attr("data-total_tax"),woocommerce_admin.mon_decimal_point)/d;e>0&&b.val(parseFloat(accounting.formatNumber(e*c,woocommerce_admin_meta_boxes.rounding_precision,"")).toString().replace(".",woocommerce_admin.mon_decimal_point));var f=a("input.line_subtotal_tax",a(this)),g=accounting.unformat(f.attr("data-subtotal_tax"),woocommerce_admin.mon_decimal_point)/d;g>0&&f.val(parseFloat(accounting.formatNumber(g*c,woocommerce_admin_meta_boxes.rounding_precision,"")).toString().replace(".",woocommerce_admin.mon_decimal_point))}),a(this).trigger("quantity_changed")},add_line_item:function(){return a("div.wc-order-add-item").slideDown(),a("div.wc-order-bulk-actions").slideUp(),!1},refund_items:function(){return a("div.wc-order-refund-items").slideDown(),a("div.wc-order-bulk-actions").slideUp(),a("div.wc-order-totals-items").slideUp(),a("#woocommerce-order-items").find("div.refund").show(),a(".wc-order-edit-line-item .wc-order-edit-line-item-actions").hide(),!1},cancel:function(){return a(this).closest("div.wc-order-data-row").slideUp(),a("div.wc-order-bulk-actions").slideDown(),a("div.wc-order-totals-items").slideDown(),a("#woocommerce-order-items").find("div.refund").hide(),a(".wc-order-edit-line-item .wc-order-edit-line-item-actions").show(),"true"===a(this).attr("data-reload")&&c.reload_items(),!1},add_item:function(){return a(this).WCBackboneModal({template:"wc-modal-add-products"}),!1},add_fee:function(){c.block();var b={action:"woocommerce_add_order_fee",order_id:woocommerce_admin_meta_boxes.post_id,security:woocommerce_admin_meta_boxes.order_item_nonce};return a.post(woocommerce_admin_meta_boxes.ajax_url,b,function(b){a("table.woocommerce_order_items tbody#order_fee_line_items").append(b),c.unblock()}),!1},add_shipping:function(){c.block();var b={action:"woocommerce_add_order_shipping",order_id:woocommerce_admin_meta_boxes.post_id,security:woocommerce_admin_meta_boxes.order_item_nonce};return a.post(woocommerce_admin_meta_boxes.ajax_url,b,function(b){a("table.woocommerce_order_items tbody#order_shipping_line_items").append(b),c.unblock()}),!1},add_tax:function(){return a(this).WCBackboneModal({template:"wc-modal-add-tax"}),!1},edit_item:function(){return a(this).closest("tr").find(".view").hide(),a(this).closest("tr").find(".edit").show(),a(this).hide(),a("button.add-line-item").click(),a("button.cancel-action").attr("data-reload",!0),!1},delete_item:function(){var b=window.confirm(woocommerce_admin_meta_boxes.remove_item_notice);if(b){var d=a(this).closest("tr.item, tr.fee, tr.shipping"),e=d.attr("data-order_item_id");c.block();var f={order_item_ids:e,action:"woocommerce_remove_order_item",security:woocommerce_admin_meta_boxes.order_item_nonce};a.ajax({url:woocommerce_admin_meta_boxes.ajax_url,data:f,type:"POST",success:function(){d.remove(),c.unblock()}})}return!1},delete_tax:function(){if(window.confirm(woocommerce_admin_meta_boxes.i18n_delete_tax)){c.block();var d={action:"woocommerce_remove_order_tax",rate_id:a(this).attr("data-rate_id"),order_id:woocommerce_admin_meta_boxes.post_id,security:woocommerce_admin_meta_boxes.order_item_nonce};a.ajax({url:woocommerce_admin_meta_boxes.ajax_url,data:d,type:"POST",success:function(d){a("#woocommerce-order-items").find(".inside").empty(),a("#woocommerce-order-items").find(".inside").append(d),b.init_tiptip(),c.unblock(),c.stupidtable.init()}})}return!1},calculate_tax:function(){if(window.confirm(woocommerce_admin_meta_boxes.calc_line_taxes)){c.block();var d="",e="",f="",g="";"shipping"===woocommerce_admin_meta_boxes.tax_based_on&&(d=a("#_shipping_country").val(),e=a("#_shipping_state").val(),f=a("#_shipping_postcode").val(),g=a("#_shipping_city").val()),"billing"!==woocommerce_admin_meta_boxes.tax_based_on&&d||(d=a("#_billing_country").val(),e=a("#_billing_state").val(),f=a("#_billing_postcode").val(),g=a("#_billing_city").val());var h={action:"woocommerce_calc_line_taxes",order_id:woocommerce_admin_meta_boxes.post_id,items:a("table.woocommerce_order_items :input[name], .wc-order-totals-items :input[name]").serialize(),country:d,state:e,postcode:f,city:g,security:woocommerce_admin_meta_boxes.calc_totals_nonce};a.ajax({url:woocommerce_admin_meta_boxes.ajax_url,data:h,type:"POST",success:function(d){a("#woocommerce-order-items").find(".inside").empty(),a("#woocommerce-order-items").find(".inside").append(d),b.init_tiptip(),c.unblock(),c.stupidtable.init()}})}return!1},calculate_totals:function(){if(window.confirm(woocommerce_admin_meta_boxes.calc_totals)){c.block();var b=0,d=0,e=0;a(".woocommerce_order_items tr.shipping input.line_total").each(function(){var b=a(this).val()||"0";b=accounting.unformat(b,woocommerce_admin.mon_decimal_point),e+=parseFloat(b)}),a(".woocommerce_order_items input.line_tax").each(function(){var b=a(this).val()||"0";b=accounting.unformat(b,woocommerce_admin.mon_decimal_point),d+=parseFloat(b)}),a(".woocommerce_order_items tr.item, .woocommerce_order_items tr.fee").each(function(){var c=a(this).find("input.line_total").val()||"0";b+=accounting.unformat(c.replace(",","."))}),"yes"===woocommerce_admin_meta_boxes.round_at_subtotal&&(d=parseFloat(accounting.toFixed(d,woocommerce_admin_meta_boxes.rounding_precision))),a("#_order_total").val(accounting.formatNumber(b+d+e,woocommerce_admin_meta_boxes.currency_format_num_decimals,"",woocommerce_admin.mon_decimal_point)).change(),a("button.save-action").click()}return!1},save_line_items:function(){var d={order_id:woocommerce_admin_meta_boxes.post_id,items:a("table.woocommerce_order_items :input[name], .wc-order-totals-items :input[name]").serialize(),action:"woocommerce_save_order_items",security:woocommerce_admin_meta_boxes.order_item_nonce};return c.block(),a.ajax({url:woocommerce_admin_meta_boxes.ajax_url,data:d,type:"POST",success:function(d){a("#woocommerce-order-items").find(".inside").empty(),a("#woocommerce-order-items").find(".inside").append(d),b.init_tiptip(),c.unblock(),c.stupidtable.init()}}),a(this).trigger("items_saved"),!1},refunds:{do_refund:function(){if(c.block(),window.confirm(woocommerce_admin_meta_boxes.i18n_do_refund)){var b=a("input#refund_amount").val(),d=a("input#refund_reason").val(),e={},f={},g={};a(".refund input.refund_order_item_qty").each(function(b,c){a(c).closest("tr").data("order_item_id")&&c.value&&(e[a(c).closest("tr").data("order_item_id")]=c.value)}),a(".refund input.refund_line_total").each(function(b,c){a(c).closest("tr").data("order_item_id")&&(f[a(c).closest("tr").data("order_item_id")]=accounting.unformat(c.value,woocommerce_admin.mon_decimal_point))}),a(".refund input.refund_line_tax").each(function(b,c){if(a(c).closest("tr").data("order_item_id")){var d=a(c).data("tax_id");g[a(c).closest("tr").data("order_item_id")]||(g[a(c).closest("tr").data("order_item_id")]={}),g[a(c).closest("tr").data("order_item_id")][d]=accounting.unformat(c.value,woocommerce_admin.mon_decimal_point)}});var h={action:"woocommerce_refund_line_items",order_id:woocommerce_admin_meta_boxes.post_id,refund_amount:b,refund_reason:d,line_item_qtys:JSON.stringify(e,null,""),line_item_totals:JSON.stringify(f,null,""),line_item_tax_totals:JSON.stringify(g,null,""),api_refund:a(this).is(".do-api-refund"),restock_refunded_items:a("#restock_refunded_items:checked").size()?"true":"false",security:woocommerce_admin_meta_boxes.order_item_nonce};a.post(woocommerce_admin_meta_boxes.ajax_url,h,function(a){!0===a.success?(c.reload_items(),"fully_refunded"===a.data.status&&(window.location.href=window.location.href)):(window.alert(a.data.error),c.unblock())})}else c.unblock()},delete_refund:function(){if(window.confirm(woocommerce_admin_meta_boxes.i18n_delete_refund)){var b=a(this).closest("tr.refund"),d=b.attr("data-order_refund_id");c.block();var e={action:"woocommerce_delete_refund",refund_id:d,security:woocommerce_admin_meta_boxes.order_item_nonce};a.ajax({url:woocommerce_admin_meta_boxes.ajax_url,data:e,type:"POST",success:function(){c.reload_items()}})}return!1},input_changed:function(){var b=0,c=a(".woocommerce_order_items").find("tr.item, tr.fee, tr.shipping");c.each(function(){var c=a(this),d=c.find(".refund input:not(.refund_order_item_qty)");d.each(function(c,d){b+=parseFloat(accounting.unformat(a(d).val()||0,woocommerce_admin.mon_decimal_point))})}),a("#refund_amount").val(accounting.formatNumber(b,woocommerce_admin_meta_boxes.currency_format_num_decimals,"",woocommerce_admin.mon_decimal_point)).change()},amount_changed:function(){var b=accounting.unformat(a(this).val(),woocommerce_admin.mon_decimal_point);a("button .wc-order-refund-amount .amount").text(accounting.formatMoney(b,{symbol:woocommerce_admin_meta_boxes.currency_format_symbol,decimal:woocommerce_admin_meta_boxes.currency_format_decimal_sep,thousand:woocommerce_admin_meta_boxes.currency_format_thousand_sep,precision:woocommerce_admin_meta_boxes.currency_format_num_decimals,format:woocommerce_admin_meta_boxes.currency_format}))},refund_quantity_changed:function(){var b=a(this).closest("tr.item"),c=b.find("input.quantity").val(),d=a(this).val(),e=a("input.line_total",b),f=a("input.refund_line_total",b),g=accounting.unformat(e.attr("data-total"),woocommerce_admin.mon_decimal_point)/c;f.val(parseFloat(accounting.formatNumber(g*d,woocommerce_admin_meta_boxes.rounding_precision,"")).toString().replace(".",woocommerce_admin.mon_decimal_point)).change(),a("td.line_tax",b).each(function(){var b=a("input.line_tax",a(this)),e=a("input.refund_line_tax",a(this)),f=accounting.unformat(b.attr("data-total_tax"),woocommerce_admin.mon_decimal_point)/c;f>0?e.val(parseFloat(accounting.formatNumber(f*d,woocommerce_admin_meta_boxes.rounding_precision,"")).toString().replace(".",woocommerce_admin.mon_decimal_point)).change():e.val(0).change()}),d>0?a("#restock_refunded_items").closest("tr").show():(a("#restock_refunded_items").closest("tr").hide(),a(".woocommerce_order_items input.refund_order_item_qty").each(function(){a(this).val()>0&&a("#restock_refunded_items").closest("tr").show()})),a(this).trigger("refund_quantity_changed")}},item_meta:{add:function(){var b=a(this),d=b.closest("tr.item"),e={order_item_id:d.attr("data-order_item_id"),action:"woocommerce_add_order_item_meta",security:woocommerce_admin_meta_boxes.order_item_nonce};return c.block(),a.ajax({url:woocommerce_admin_meta_boxes.ajax_url,data:e,type:"POST",success:function(a){d.find("tbody.meta_items").append(a),c.unblock()}}),!1},remove:function(){if(window.confirm(woocommerce_admin_meta_boxes.remove_item_meta)){var b=a(this).closest("tr"),d={meta_id:b.attr("data-meta_id"),action:"woocommerce_remove_order_item_meta",security:woocommerce_admin_meta_boxes.order_item_nonce};c.block(),a.ajax({url:woocommerce_admin_meta_boxes.ajax_url,data:d,type:"POST",success:function(){b.hide(),c.unblock()}})}return!1}},bulk_actions:{check_column:function(){a(this).is(":checked")?a("#woocommerce-order-items").find(".check-column input").attr("checked","checked"):a("#woocommerce-order-items").find(".check-column input").removeAttr("checked")},do_bulk_action:function(){var b=a(this).closest(".bulk-actions").find("select").val(),d=a("#woocommerce-order-items").find(".check-column input:checked"),e=[];return a(d).each(function(){var b=a(this).closest("tr");b.attr("data-order_item_id")&&e.push(b.attr("data-order_item_id"))}),0===e.length?void window.alert(woocommerce_admin_meta_boxes.i18n_select_items):(c.bulk_actions["do_"+b]&&c.bulk_actions["do_"+b](d,e),!1)},do_delete:function(b,d){if(window.confirm(woocommerce_admin_meta_boxes.remove_item_notice)){c.block();var e={order_item_ids:d,action:"woocommerce_remove_order_item",security:woocommerce_admin_meta_boxes.order_item_nonce};a.ajax({url:woocommerce_admin_meta_boxes.ajax_url,data:e,type:"POST",success:function(){a(b).each(function(){a(this).closest("tr").remove()}),c.unblock()}})}},do_increase_stock:function(b,d){c.block();var e={};a(b).each(function(){var b=a(this).closest("tr.item, tr.fee"),c=b.find("input.quantity");e[b.attr("data-order_item_id")]=c.val()});var f={order_id:woocommerce_admin_meta_boxes.post_id,order_item_ids:d,order_item_qty:e,action:"woocommerce_increase_order_item_stock",security:woocommerce_admin_meta_boxes.order_item_nonce};a.ajax({url:woocommerce_admin_meta_boxes.ajax_url,data:f,type:"POST",success:function(a){window.alert(a),c.unblock()}})},do_reduce_stock:function(b,d){c.block();var e={};a(b).each(function(){var b=a(this).closest("tr.item, tr.fee"),c=b.find("input.quantity");e[b.attr("data-order_item_id")]=c.val()});var f={order_id:woocommerce_admin_meta_boxes.post_id,order_item_ids:d,order_item_qty:e,action:"woocommerce_reduce_order_item_stock",security:woocommerce_admin_meta_boxes.order_item_nonce};a.ajax({url:woocommerce_admin_meta_boxes.ajax_url,data:f,type:"POST",success:function(a){window.alert(a),c.unblock()}})}},backbone:{init:function(b,c){"wc-modal-add-products"===c&&a(document.body).trigger("wc-enhanced-select-init")},response:function(a,b,d){if("wc-modal-add-tax"===b){var e=d.add_order_tax,f="";d.manual_tax_rate_id&&(f=d.manual_tax_rate_id),c.backbone.add_tax(e,f)}"wc-modal-add-products"===b&&c.backbone.add_item(d.add_order_items)},add_item:function(d){if(d=d.split(",")){var e=d.length;c.block(),a.each(d,function(d,f){var g={action:"woocommerce_add_order_item",item_to_add:f,order_id:woocommerce_admin_meta_boxes.post_id,security:woocommerce_admin_meta_boxes.order_item_nonce};a.post(woocommerce_admin_meta_boxes.ajax_url,g,function(d){a("table.woocommerce_order_items tbody#order_line_items").append(d),--e||(b.init_tiptip(),c.unblock())})})}},add_tax:function(d,e){if(e&&(d=e),!d)return!1;var f=a(".order-tax-id").map(function(){return a(this).val()}).get();if(-1===a.inArray(d,f)){c.block();var g={action:"woocommerce_add_order_tax",rate_id:d,order_id:woocommerce_admin_meta_boxes.post_id,security:woocommerce_admin_meta_boxes.order_item_nonce};a.ajax({url:woocommerce_admin_meta_boxes.ajax_url,data:g,type:"POST",success:function(d){a("#woocommerce-order-items").find(".inside").empty(),a("#woocommerce-order-items").find(".inside").append(d),b.init_tiptip(),c.unblock(),c.stupidtable.init()}})}else window.alert(woocommerce_admin_meta_boxes.i18n_tax_rate_already_exists)}},stupidtable:{init:function(){a(".woocommerce_order_items").stupidtable().on("aftertablesort",this.add_arrows)},add_arrows:function(b,c){var d=a(this).find("th"),e="asc"===c.direction?"↑":"↓",f=c.column;f>1&&(f-=1),d.find(".wc-arrow").remove(),d.eq(f).append(''+e+"")}}},d={init:function(){a("#woocommerce-order-notes").on("click","a.add_note",this.add_order_note).on("click","a.delete_note",this.delete_order_note)},add_order_note:function(){if(a("textarea#add_order_note").val()){a("#woocommerce-order-notes").block({message:null,overlayCSS:{background:"#fff",opacity:.6}});var b={action:"woocommerce_add_order_note",post_id:woocommerce_admin_meta_boxes.post_id,note:a("textarea#add_order_note").val(),note_type:a("select#order_note_type").val(),security:woocommerce_admin_meta_boxes.add_order_note_nonce};return a.post(woocommerce_admin_meta_boxes.ajax_url,b,function(b){a("ul.order_notes").prepend(b),a("#woocommerce-order-notes").unblock(),a("#add_order_note").val("")}),!1}},delete_order_note:function(){var b=a(this).closest("li.note");a(b).block({message:null,overlayCSS:{background:"#fff",opacity:.6}});var c={action:"woocommerce_delete_order_note",note_id:a(b).attr("rel"),security:woocommerce_admin_meta_boxes.delete_order_note_nonce};return a.post(woocommerce_admin_meta_boxes.ajax_url,c,function(){a(b).remove()}),!1}},e={init:function(){a(".order_download_permissions").on("click","button.grant_access",this.grant_access).on("click","button.revoke_access",this.revoke_access)},grant_access:function(){var b=a("#grant_access_id").val();if(b){a(".order_download_permissions").block({message:null,overlayCSS:{background:"#fff",opacity:.6}});var c={action:"woocommerce_grant_access_to_download",product_ids:b,loop:a(".order_download_permissions .wc-metabox").size(),order_id:woocommerce_admin_meta_boxes.post_id,security:woocommerce_admin_meta_boxes.grant_access_nonce};return a.post(woocommerce_admin_meta_boxes.ajax_url,c,function(b){b?a(".order_download_permissions .wc-metaboxes").append(b):window.alert(woocommerce_admin_meta_boxes.i18n_download_permission_fail),a(document.body).trigger("wc-init-datepickers"),a("#grant_access_id").val("").change(),a(".order_download_permissions").unblock()}),!1}},revoke_access:function(){if(window.confirm(woocommerce_admin_meta_boxes.i18n_permission_revoke)){var b=a(this).parent().parent(),c=a(this).attr("rel").split(",")[0],d=a(this).attr("rel").split(",")[1];if(c>0){a(b).block({message:null,overlayCSS:{background:"#fff",opacity:.6}});var e={action:"woocommerce_revoke_access_to_download",product_id:c,download_id:d,order_id:woocommerce_admin_meta_boxes.post_id,security:woocommerce_admin_meta_boxes.revoke_access_nonce};a.post(woocommerce_admin_meta_boxes.ajax_url,e,function(){a(b).fadeOut("300",function(){a(b).remove()})})}else a(b).fadeOut("300",function(){a(b).remove()})}return!1}};b.init(),c.init(),d.init(),e.init()}); \ No newline at end of file +jQuery(function(a){var b={states:null,init:function(){"undefined"!=typeof woocommerce_admin_meta_boxes_order&&"undefined"!=typeof woocommerce_admin_meta_boxes_order.countries&&(this.states=a.parseJSON(woocommerce_admin_meta_boxes_order.countries.replace(/"/g,'"'))),a(".js_field-country").select2().change(this.change_country),a(".js_field-country").trigger("change",[!0]),a(document.body).on("change","select.js_field-state",this.change_state),a("#woocommerce-order-actions input, #woocommerce-order-actions a").click(function(){window.onbeforeunload=""}),a("a.edit_address").click(this.edit_address),a("a.billing-same-as-shipping").on("click",this.copy_billing_to_shipping),a("a.load_customer_billing").on("click",this.load_billing),a("a.load_customer_shipping").on("click",this.load_shipping),a("#customer_user").on("change",this.change_customer_user)},change_country:function(c,d){if("undefined"==typeof d&&(d=!1),null!==b.states){var e=a(this),f=e.val(),g=e.parents("div.edit_address").find(":input.js_field-state"),h=g.parent(),i=g.attr("name"),j=g.attr("id"),k=e.data("woocommerce.stickState-"+f)?e.data("woocommerce.stickState-"+f):g.val(),l=g.attr("placeholder");if(d&&e.data("woocommerce.stickState-"+f,k),h.show().find(".select2-container").remove(),a.isEmptyObject(b.states[f]))g.replaceWith('');else{var m=a(''),n=b.states[f];m.append(a('")),a.each(n,function(b){m.append(a('"))}),m.val(k),g.replaceWith(m),m.show().select2().hide().change()}a(document.body).trigger("contry-change.woocommerce",[f,a(this).closest("div")]),a(document.body).trigger("country-change.woocommerce",[f,a(this).closest("div")])}},change_state:function(){var b=a(this),c=b.val(),d=b.parents("div.edit_address").find(":input.js_field-country"),e=d.val();d.data("woocommerce.stickState-"+e,c)},init_tiptip:function(){a("#tiptip_holder").removeAttr("style"),a("#tiptip_arrow").removeAttr("style"),a(".tips").tipTip({attribute:"data-tip",fadeIn:50,fadeOut:50,delay:200})},edit_address:function(b){b.preventDefault();var c=a(this),d=c.closest(".order_data_column"),e=d.find("div.edit_address"),f=d.find("div.address"),g=e.find(".js_field-country"),h=e.find(".js_field-state");f.hide(),c.parent().find("a").toggle(),g.val()||g.val(woocommerce_admin_meta_boxes_order.default_country).change(),h.val()||h.val(woocommerce_admin_meta_boxes_order.default_state).change(),e.show()},change_customer_user:function(){a("#_billing_country").val()||(a("a.edit_address").click(),b.load_billing(!0),b.load_shipping(!0))},load_billing:function(b){if(!0===b||window.confirm(woocommerce_admin_meta_boxes.load_billing)){var c=a("#customer_user").val();if(!c)return window.alert(woocommerce_admin_meta_boxes.no_customer_selected),!1;var d={user_id:c,action:"woocommerce_get_customer_details",security:woocommerce_admin_meta_boxes.get_customer_details_nonce};a(this).closest("div.edit_address").block({message:null,overlayCSS:{background:"#fff",opacity:.6}}),a.ajax({url:woocommerce_admin_meta_boxes.ajax_url,data:d,type:"POST",success:function(b){b&&b.billing&&a.each(b.billing,function(b,c){a(":input#_billing_"+b).val(c).change()}),a("div.edit_address").unblock()}})}return!1},load_shipping:function(b){if(!0===b||window.confirm(woocommerce_admin_meta_boxes.load_shipping)){var c=a("#customer_user").val();if(!c)return window.alert(woocommerce_admin_meta_boxes.no_customer_selected),!1;var d={user_id:c,action:"woocommerce_get_customer_details",security:woocommerce_admin_meta_boxes.get_customer_details_nonce};a(this).closest("div.edit_address").block({message:null,overlayCSS:{background:"#fff",opacity:.6}}),a.ajax({url:woocommerce_admin_meta_boxes.ajax_url,data:d,type:"POST",success:function(b){b&&b.billing&&a.each(b.shipping,function(b,c){a(":input#_shipping_"+b).val(c).change()}),a("div.edit_address").unblock()}})}return!1},copy_billing_to_shipping:function(){return window.confirm(woocommerce_admin_meta_boxes.copy_billing)&&a('.order_data_column :input[name^="_billing_"]').each(function(){var b=a(this).attr("name");b=b.replace("_billing_","_shipping_"),a(":input#"+b).val(a(this).val()).change()}),!1}},c={init:function(){this.stupidtable.init(),a("#woocommerce-order-items").on("click","button.add-line-item",this.add_line_item).on("click","button.refund-items",this.refund_items).on("click",".cancel-action",this.cancel).on("click","button.add-order-item",this.add_item).on("click","button.add-order-fee",this.add_fee).on("click","button.add-order-shipping",this.add_shipping).on("click","button.add-order-tax",this.add_tax).on("click","button.save-action",this.save_line_items).on("click","a.delete-order-tax",this.delete_tax).on("click","button.calculate-action",this.recalculate).on("click","a.edit-order-item",this.edit_item).on("click","a.delete-order-item",this.delete_item).on("click","tr.item, tr.fee, tr.shipping, tr.refund",this.select_row).on("click","tr.item :input, tr.fee :input, tr.shipping :input, tr.refund :input, tr.item a, tr.fee a, tr.shipping a, tr.refund a",this.select_row_child).on("click","button.bulk-delete-items",this.bulk_actions.do_delete).on("click","button.bulk-increase-stock",this.bulk_actions.do_increase_stock).on("click","button.bulk-decrease-stock",this.bulk_actions.do_reduce_stock).on("click",".delete_refund",this.refunds.delete_refund).on("click","button.do-api-refund, button.do-manual-refund",this.refunds.do_refund).on("change",".refund input.refund_line_total, .refund input.refund_line_tax",this.refunds.input_changed).on("change keyup",".wc-order-refund-items #refund_amount",this.refunds.amount_changed).on("change","input.refund_order_item_qty",this.refunds.refund_quantity_changed).on("change","input.quantity",this.quantity_changed).on("keyup change",".split-input :input",function(){var b=a(this).parent().prev().find(":input");b&&(""===b.val()||b.is(".match-total"))&&b.val(a(this).val()).addClass("match-total")}).on("keyup",".split-input :input",function(){a(this).removeClass("match-total")}).on("click","button.add_order_item_meta",this.item_meta.add).on("click","button.remove_order_item_meta",this.item_meta.remove),a(document.body).on("wc_backbone_modal_loaded",this.backbone.init).on("wc_backbone_modal_response",this.backbone.response)},block:function(){a("#woocommerce-order-items").block({message:null,overlayCSS:{background:"#fff",opacity:.6}})},unblock:function(){a("#woocommerce-order-items").unblock()},reload_items:function(){var d={order_id:woocommerce_admin_meta_boxes.post_id,action:"woocommerce_load_order_items",security:woocommerce_admin_meta_boxes.order_item_nonce};c.block(),a.ajax({url:woocommerce_admin_meta_boxes.ajax_url,data:d,type:"POST",success:function(d){a("#woocommerce-order-items").find(".inside").empty(),a("#woocommerce-order-items").find(".inside").append(d),b.init_tiptip(),c.unblock(),c.stupidtable.init()}})},quantity_changed:function(){var b=a(this).closest("tr.item"),c=a(this).val(),d=a(this).attr("data-qty"),e=a("input.line_total",b),f=a("input.line_subtotal",b),g=accounting.unformat(e.attr("data-total"),woocommerce_admin.mon_decimal_point)/d;e.val(parseFloat(accounting.formatNumber(g*c,woocommerce_admin_meta_boxes.rounding_precision,"")).toString().replace(".",woocommerce_admin.mon_decimal_point));var h=accounting.unformat(f.attr("data-subtotal"),woocommerce_admin.mon_decimal_point)/d;f.val(parseFloat(accounting.formatNumber(h*c,woocommerce_admin_meta_boxes.rounding_precision,"")).toString().replace(".",woocommerce_admin.mon_decimal_point)),a("input.line_tax",b).each(function(){var e=a(this),f=e.data("tax_id"),g=accounting.unformat(e.attr("data-total_tax"),woocommerce_admin.mon_decimal_point)/d,h=a('input.line_subtotal_tax[data-tax_id="'+f+'"]',b),i=accounting.unformat(h.attr("data-subtotal_tax"),woocommerce_admin.mon_decimal_point)/d;00?a("#restock_refunded_items").closest("tr").show():(a("#restock_refunded_items").closest("tr").hide(),a(".woocommerce_order_items input.refund_order_item_qty").each(function(){a(this).val()>0&&a("#restock_refunded_items").closest("tr").show()})),a(this).trigger("refund_quantity_changed")}},item_meta:{add:function(){var b=a(this),c=b.closest("tr.item, tr.shipping"),d=c.find("tbody.meta_items"),e=d.find("tr").length+1,f='';return d.append(f),!1},remove:function(){if(window.confirm(woocommerce_admin_meta_boxes.remove_item_meta)){var b=a(this).closest("tr");b.find(":input").val(""),b.hide()}return!1}},select_row:function(){var b=!1;b=a(this).is("tr")?a(this):a(this).closest("tr");var c=a(this).closest("table");b.is(".selected")?b.removeClass("selected"):b.addClass("selected");var d=c.find("tr.selected");if(d.length){a("div.wc-order-item-bulk-edit").slideDown();var e=!1;d.each(function(){a(this).is("tr.item")&&(e=!0)}),e?a(".bulk-increase-stock, .bulk-decrease-stock").show():a(".bulk-increase-stock, .bulk-decrease-stock").hide()}else a("div.wc-order-item-bulk-edit").slideUp()},select_row_child:function(a){a.stopPropagation()},bulk_actions:{do_delete:function(b){b.preventDefault();var d=a("table.woocommerce_order_items"),e=d.find("tr.selected");if(e.length&&window.confirm(woocommerce_admin_meta_boxes.remove_item_notice)){c.block();var f=[],g=[],h=[];a.map(e,function(b){var c=a(b);c.is(".refund")?g.push(parseInt(a(c).data("order_refund_id"),10)):f.push(parseInt(a(c).data("order_item_id"),10))}),f.length&&h.push(a.ajax({url:woocommerce_admin_meta_boxes.ajax_url,data:{order_item_ids:f,action:"woocommerce_remove_order_item",security:woocommerce_admin_meta_boxes.order_item_nonce},type:"POST"})),g.length&&h.push(a.ajax({url:woocommerce_admin_meta_boxes.ajax_url,data:{action:"woocommerce_delete_refund",refund_id:g,security:woocommerce_admin_meta_boxes.order_item_nonce},type:"POST"})),h?a.when.apply(a,h).done(function(){c.reload_items(),c.unblock()}):c.unblock()}},do_increase_stock:function(b){b.preventDefault(),c.block();var d=a("table.woocommerce_order_items"),e=d.find("tr.selected"),f={},g=a.map(e,function(b){return parseInt(a(b).data("order_item_id"),10)});e.each(function(){a(this).find("input.quantity").length&&(f[a(this).attr("data-order_item_id")]=a(this).find("input.quantity").val())});var h={order_id:woocommerce_admin_meta_boxes.post_id,order_item_ids:g,order_item_qty:f,action:"woocommerce_increase_order_item_stock",security:woocommerce_admin_meta_boxes.order_item_nonce};a.ajax({url:woocommerce_admin_meta_boxes.ajax_url,data:h,type:"POST",success:function(a){window.alert(a),c.unblock()}})},do_reduce_stock:function(b){b.preventDefault(),c.block();var d=a("table.woocommerce_order_items"),e=d.find("tr.selected"),f={},g=a.map(e,function(b){return parseInt(a(b).data("order_item_id"),10)});e.each(function(){a(this).find("input.quantity").length&&(f[a(this).attr("data-order_item_id")]=a(this).find("input.quantity").val())});var h={order_id:woocommerce_admin_meta_boxes.post_id,order_item_ids:g,order_item_qty:f,action:"woocommerce_reduce_order_item_stock",security:woocommerce_admin_meta_boxes.order_item_nonce};a.ajax({url:woocommerce_admin_meta_boxes.ajax_url,data:h,type:"POST",success:function(a){window.alert(a),c.unblock()}})}},backbone:{init:function(b,c){"wc-modal-add-products"===c&&a(document.body).trigger("wc-enhanced-select-init")},response:function(a,b,d){if("wc-modal-add-tax"===b){var e=d.add_order_tax,f="";d.manual_tax_rate_id&&(f=d.manual_tax_rate_id),c.backbone.add_tax(e,f)}"wc-modal-add-products"===b&&c.backbone.add_item(d.add_order_items)},add_item:function(d){if(d){c.block();var e={action:"woocommerce_add_order_item",item_to_add:d,dataType:"json",order_id:woocommerce_admin_meta_boxes.post_id,security:woocommerce_admin_meta_boxes.order_item_nonce};a.post(woocommerce_admin_meta_boxes.ajax_url,e,function(d){d.success?a("table.woocommerce_order_items tbody#order_line_items").append(d.data.html):window.alert(d.data.error),b.init_tiptip(),c.unblock()})}},add_tax:function(d,e){if(e&&(d=e),!d)return!1;var f=a(".order-tax-id").map(function(){return a(this).val()}).get();if(-1===a.inArray(d,f)){c.block();var g={action:"woocommerce_add_order_tax",rate_id:d,order_id:woocommerce_admin_meta_boxes.post_id,security:woocommerce_admin_meta_boxes.order_item_nonce};a.ajax({url:woocommerce_admin_meta_boxes.ajax_url,data:g,dataType:"json",type:"POST",success:function(d){d.success?(a("#woocommerce-order-items").find(".inside").empty(),a("#woocommerce-order-items").find(".inside").append(d.data.html),b.init_tiptip(),c.stupidtable.init()):window.alert(d.data.error),c.unblock()}})}else window.alert(woocommerce_admin_meta_boxes.i18n_tax_rate_already_exists)}},stupidtable:{init:function(){a(".woocommerce_order_items").stupidtable(),a(".woocommerce_order_items").on("aftertablesort",this.add_arrows)},add_arrows:function(b,c){var d=a(this).find("th"),e="asc"===c.direction?"↑":"↓",f=c.column;d.find(".wc-arrow").remove(),d.eq(f).append(''+e+"")}}},d={init:function(){a("#woocommerce-order-notes").on("click","button.add_note",this.add_order_note).on("click","a.delete_note",this.delete_order_note)},add_order_note:function(){if(a("textarea#add_order_note").val()){a("#woocommerce-order-notes").block({message:null,overlayCSS:{background:"#fff",opacity:.6}});var b={action:"woocommerce_add_order_note",post_id:woocommerce_admin_meta_boxes.post_id,note:a("textarea#add_order_note").val(),note_type:a("select#order_note_type").val(),security:woocommerce_admin_meta_boxes.add_order_note_nonce};return a.post(woocommerce_admin_meta_boxes.ajax_url,b,function(b){a("ul.order_notes").prepend(b),a("#woocommerce-order-notes").unblock(),a("#add_order_note").val("")}),!1}},delete_order_note:function(){if(window.confirm(woocommerce_admin_meta_boxes.i18n_delete_note)){var b=a(this).closest("li.note");a(b).block({message:null,overlayCSS:{background:"#fff",opacity:.6}});var c={action:"woocommerce_delete_order_note",note_id:a(b).attr("rel"),security:woocommerce_admin_meta_boxes.delete_order_note_nonce};a.post(woocommerce_admin_meta_boxes.ajax_url,c,function(){a(b).remove()})}return!1}},e={init:function(){a(".order_download_permissions").on("click","button.grant_access",this.grant_access).on("click","button.revoke_access",this.revoke_access)},grant_access:function(){var b=a("#grant_access_id").val();if(b){a(".order_download_permissions").block({message:null,overlayCSS:{background:"#fff",opacity:.6}});var c={action:"woocommerce_grant_access_to_download",product_ids:b,loop:a(".order_download_permissions .wc-metabox").length,order_id:woocommerce_admin_meta_boxes.post_id,security:woocommerce_admin_meta_boxes.grant_access_nonce};return a.post(woocommerce_admin_meta_boxes.ajax_url,c,function(b){b?a(".order_download_permissions .wc-metaboxes").append(b):window.alert(woocommerce_admin_meta_boxes.i18n_download_permission_fail),a(document.body).trigger("wc-init-datepickers"),a("#grant_access_id").val("").change(),a(".order_download_permissions").unblock()}),!1}},revoke_access:function(){if(window.confirm(woocommerce_admin_meta_boxes.i18n_permission_revoke)){var b=a(this).parent().parent(),c=a(this).attr("rel").split(",")[0],d=a(this).attr("rel").split(",")[1],e=a(this).data("permission_id");if(c>0){a(b).block({message:null,overlayCSS:{background:"#fff",opacity:.6}});var f={action:"woocommerce_revoke_access_to_download",product_id:c,download_id:d,permission_id:e,order_id:woocommerce_admin_meta_boxes.post_id,security:woocommerce_admin_meta_boxes.revoke_access_nonce};a.post(woocommerce_admin_meta_boxes.ajax_url,f,function(){a(b).fadeOut("300",function(){a(b).remove()})})}else a(b).fadeOut("300",function(){a(b).remove()})}return!1}};b.init(),c.init(),d.init(),e.init()}); \ No newline at end of file diff --git a/assets/js/admin/meta-boxes-product-variation.js b/assets/js/admin/meta-boxes-product-variation.js index fff33f6b644..bc3e644583e 100644 --- a/assets/js/admin/meta-boxes-product-variation.js +++ b/assets/js/admin/meta-boxes-product-variation.js @@ -31,6 +31,7 @@ jQuery( function( $ ) { */ reload: function() { wc_meta_boxes_product_variations_ajax.load_variations( 1 ); + wc_meta_boxes_product_variations_pagenav.set_paginav( 0 ); }, /** @@ -117,21 +118,19 @@ jQuery( function( $ ) { }); // Datepicker fields - $( '.sale_price_dates_fields', wrapper ).each( function() { - var dates = $( this ).find( 'input' ).datepicker({ - defaultDate: '', - dateFormat: 'yy-mm-dd', - numberOfMonths: 1, - showButtonPanel: true, - onSelect: function( selectedDate ) { - var option = $( this ).is( '.sale_price_dates_from' ) ? 'minDate' : 'maxDate', - instance = $( this ).data( 'datepicker' ), - date = $.datepicker.parseDate( instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings ); + $( '.sale_price_dates_fields', wrapper ).find( 'input' ).datepicker({ + defaultDate: '', + dateFormat: 'yy-mm-dd', + numberOfMonths: 1, + showButtonPanel: true, + onSelect: function( selectedDate, instance ) { + var option = $( this ).is( '.sale_price_dates_from' ) ? 'minDate' : 'maxDate', + dates = $( this ).closest( '.sale_price_dates_fields' ).find( 'input' ), + date = $.datepicker.parseDate( instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings ); - dates.not( this ).datepicker( 'option', option, date ); - $( this ).change(); - } - }); + dates.not( this ).datepicker( 'option', option, date ); + $( this ).change(); + } }); // Allow sorting @@ -554,7 +553,7 @@ jQuery( function( $ ) { var data = { action: 'woocommerce_add_variation', post_id: woocommerce_admin_meta_boxes_variations.post_id, - loop: $( '.woocommerce_variation' ).size(), + loop: $( '.woocommerce_variation' ).length, security: woocommerce_admin_meta_boxes_variations.add_variation_nonce }; diff --git a/assets/js/admin/meta-boxes-product-variation.min.js b/assets/js/admin/meta-boxes-product-variation.min.js index 3163ebbf7aa..6b93d6296cb 100644 --- a/assets/js/admin/meta-boxes-product-variation.min.js +++ b/assets/js/admin/meta-boxes-product-variation.min.js @@ -1 +1 @@ -jQuery(function(a){var b={init:function(){a("#variable_product_options").on("change","input.variable_is_downloadable",this.variable_is_downloadable).on("change","input.variable_is_virtual",this.variable_is_virtual).on("change","input.variable_manage_stock",this.variable_manage_stock).on("click","button.notice-dismiss",this.notice_dismiss).on("click","h3 .sort",this.set_menu_order).on("reload",this.reload),a("input.variable_is_downloadable, input.variable_is_virtual, input.variable_manage_stock").change(),a("#woocommerce-product-data").on("woocommerce_variations_loaded",this.variations_loaded),a(document.body).on("woocommerce_variations_added",this.variation_added)},reload:function(){d.load_variations(1)},variable_is_downloadable:function(){a(this).closest(".woocommerce_variation").find(".show_if_variation_downloadable").hide(),a(this).is(":checked")&&a(this).closest(".woocommerce_variation").find(".show_if_variation_downloadable").show()},variable_is_virtual:function(){a(this).closest(".woocommerce_variation").find(".hide_if_variation_virtual").show(),a(this).is(":checked")&&a(this).closest(".woocommerce_variation").find(".hide_if_variation_virtual").hide()},variable_manage_stock:function(){a(this).closest(".woocommerce_variation").find(".show_if_variation_manage_stock").hide(),a(this).is(":checked")&&a(this).closest(".woocommerce_variation").find(".show_if_variation_manage_stock").show()},notice_dismiss:function(){a(this).closest("div.notice").remove()},variations_loaded:function(c,d){d=d||!1;var e=a("#woocommerce-product-data");d||(a("input.variable_is_downloadable, input.variable_is_virtual, input.variable_manage_stock",e).change(),a(".woocommerce_variation",e).each(function(b,c){var d=a(c),e=a(".sale_price_dates_from",d).val(),f=a(".sale_price_dates_to",d).val();(""!==e||""!==f)&&a("a.sale_schedule",d).click()}),a(".woocommerce_variations .variation-needs-update",e).removeClass("variation-needs-update"),a("button.cancel-variation-changes, button.save-variation-changes",e).attr("disabled","disabled")),a("#tiptip_holder").removeAttr("style"),a("#tiptip_arrow").removeAttr("style"),a(".woocommerce_variations .tips, .woocommerce_variations .help_tip, .woocommerce_variations .woocommerce-help-tip",e).tipTip({attribute:"data-tip",fadeIn:50,fadeOut:50,delay:200}),a(".sale_price_dates_fields",e).each(function(){var b=a(this).find("input").datepicker({defaultDate:"",dateFormat:"yy-mm-dd",numberOfMonths:1,showButtonPanel:!0,onSelect:function(c){var d=a(this).is(".sale_price_dates_from")?"minDate":"maxDate",e=a(this).data("datepicker"),f=a.datepicker.parseDate(e.settings.dateFormat||a.datepicker._defaults.dateFormat,c,e.settings);b.not(this).datepicker("option",d,f),a(this).change()}})}),a(".woocommerce_variations",e).sortable({items:".woocommerce_variation",cursor:"move",axis:"y",handle:".sort",scrollSensitivity:40,forcePlaceholderSize:!0,helper:"clone",opacity:.65,stop:function(){b.variation_row_indexes()}}),a(document.body).trigger("wc-enhanced-select-init")},variation_added:function(a,c){1===c&&b.variations_loaded(null,!0)},set_menu_order:function(b){b.preventDefault();var c=a(this).closest(".woocommerce_variation").find(".variation_menu_order"),e=window.prompt(woocommerce_admin_meta_boxes_variations.i18n_enter_menu_order,c.val());null!=e&&(c.val(parseInt(e,10)).change(),d.save_variations())},variation_row_indexes:function(){var b=a("#variable_product_options").find(".woocommerce_variations"),c=parseInt(b.attr("data-page"),10),d=parseInt((c-1)*woocommerce_admin_meta_boxes_variations.variations_per_page,10);a(".woocommerce_variations .woocommerce_variation").each(function(b,c){a(".variation_menu_order",c).val(parseInt(a(c).index(".woocommerce_variations .woocommerce_variation"),10)+1+d).change()})}},c={variable_image_frame:null,setting_variation_image_id:null,setting_variation_image:null,wp_media_post_id:wp.media.model.settings.post.id,init:function(){a("#variable_product_options").on("click",".upload_image_button",this.add_image),a("a.add_media").on("click",this.restore_wp_media_post_id)},add_image:function(b){var d=a(this),e=d.attr("rel"),f=d.closest(".upload_image");if(c.setting_variation_image=f,c.setting_variation_image_id=e,b.preventDefault(),d.is(".remove"))a(".upload_image_id",c.setting_variation_image).val("").change(),c.setting_variation_image.find("img").eq(0).attr("src",woocommerce_admin_meta_boxes_variations.woocommerce_placeholder_img_src),c.setting_variation_image.find(".upload_image_button").removeClass("remove");else{if(c.variable_image_frame)return c.variable_image_frame.uploader.uploader.param("post_id",c.setting_variation_image_id),void c.variable_image_frame.open();wp.media.model.settings.post.id=c.setting_variation_image_id,c.variable_image_frame=wp.media.frames.variable_image=wp.media({title:woocommerce_admin_meta_boxes_variations.i18n_choose_image,button:{text:woocommerce_admin_meta_boxes_variations.i18n_set_image},states:[new wp.media.controller.Library({title:woocommerce_admin_meta_boxes_variations.i18n_choose_image,filterable:"all"})]}),c.variable_image_frame.on("select",function(){var b=c.variable_image_frame.state().get("selection").first().toJSON(),d=b.sizes&&b.sizes.thumbnail?b.sizes.thumbnail.url:b.url;a(".upload_image_id",c.setting_variation_image).val(b.id).change(),c.setting_variation_image.find(".upload_image_button").addClass("remove"),c.setting_variation_image.find("img").eq(0).attr("src",d),wp.media.model.settings.post.id=c.wp_media_post_id}),c.variable_image_frame.open()}},restore_wp_media_post_id:function(){wp.media.model.settings.post.id=c.wp_media_post_id}},d={init:function(){a("li.variations_tab a").on("click",this.initial_load),a("#variable_product_options").on("click","button.save-variation-changes",this.save_variations).on("click","button.cancel-variation-changes",this.cancel_variations).on("click",".remove_variation",this.remove_variation),a(document.body).on("change","#variable_product_options .woocommerce_variations :input",this.input_changed).on("change",".variations-defaults select",this.defaults_changed),a("form#post").on("submit",this.save_on_submit),a(".wc-metaboxes-wrapper").on("click","a.do_variation_action",this.do_variation_action)},check_for_changes:function(){var b=a("#variable_product_options").find(".woocommerce_variations .variation-needs-update");if(00?(c.push(b),f.variation_ids=c,f.security=woocommerce_admin_meta_boxes_variations.delete_variations_nonce,a.post(woocommerce_admin_meta_boxes_variations.ajax_url,f,function(){var b=a("#variable_product_options").find(".woocommerce_variations"),c=parseInt(b.attr("data-page"),10),d=Math.ceil((parseInt(b.attr("data-total"),10)-1)/woocommerce_admin_meta_boxes_variations.variations_per_page),f=1;a("#woocommerce-product-data").trigger("woocommerce_variations_removed"),c===d||d>=c?f=c:c>d&&0!==d&&(f=d),e.go_to_page(f,-1)})):d.unblock()}return!1},link_all_variations:function(){if(d.check_for_changes(),window.confirm(woocommerce_admin_meta_boxes_variations.i18n_link_all_variations)){d.block();var b={action:"woocommerce_link_all_variations",post_id:woocommerce_admin_meta_boxes_variations.post_id,security:woocommerce_admin_meta_boxes_variations.link_variation_nonce};a.post(woocommerce_admin_meta_boxes_variations.ajax_url,b,function(b){var c=parseInt(b,10);1===c?window.alert(c+" "+woocommerce_admin_meta_boxes_variations.i18n_variation_added):0===c||c>1?window.alert(c+" "+woocommerce_admin_meta_boxes_variations.i18n_variations_added):window.alert(woocommerce_admin_meta_boxes_variations.i18n_no_variations_added),c>0?(e.go_to_page(1,c),a("#variable_product_options").trigger("woocommerce_variations_added",c)):d.unblock()})}return!1},input_changed:function(){a(this).closest(".woocommerce_variation").addClass("variation-needs-update"),a("button.cancel-variation-changes, button.save-variation-changes").removeAttr("disabled"),a("#variable_product_options").trigger("woocommerce_variations_input_changed")},defaults_changed:function(){a(this).closest("#variable_product_options").find(".woocommerce_variation:first").addClass("variation-needs-update"),a("button.cancel-variation-changes, button.save-variation-changes").removeAttr("disabled"),a("#variable_product_options").trigger("woocommerce_variations_defaults_changed")},do_variation_action:function(){var b,c=a("select.variation_actions").val(),f={},g=0;switch(c){case"add_variation":return void d.add_variation();case"link_all_variations":return void d.link_all_variations();case"delete_all":window.confirm(woocommerce_admin_meta_boxes_variations.i18n_delete_all_variations)&&window.confirm(woocommerce_admin_meta_boxes_variations.i18n_last_warning)&&(f.allowed=!0,g=-1*parseInt(a("#variable_product_options").find(".woocommerce_variations").attr("data-total"),10));break;case"variable_regular_price_increase":case"variable_regular_price_decrease":case"variable_sale_price_increase":case"variable_sale_price_decrease":b=window.prompt(woocommerce_admin_meta_boxes_variations.i18n_enter_a_value_fixed_or_percent),null!=b&&(b.indexOf("%")>=0?f.value=accounting.unformat(b.replace(/\%/,""),woocommerce_admin.mon_decimal_point)+"%":f.value=accounting.unformat(b,woocommerce_admin.mon_decimal_point));break;case"variable_regular_price":case"variable_sale_price":case"variable_stock":case"variable_weight":case"variable_length":case"variable_width":case"variable_height":case"variable_download_limit":case"variable_download_expiry":b=window.prompt(woocommerce_admin_meta_boxes_variations.i18n_enter_a_value),null!=b&&(f.value=b);break;case"variable_sale_schedule":f.date_from=window.prompt(woocommerce_admin_meta_boxes_variations.i18n_scheduled_sale_start),f.date_to=window.prompt(woocommerce_admin_meta_boxes_variations.i18n_scheduled_sale_end),null===f.date_from&&(f.date_from=!1),null===f.date_to&&(f.date_to=!1);break;default:a("select.variation_actions").trigger(c),f=a("select.variation_actions").triggerHandler(c+"_ajax_data",f)}"delete_all"===c&&f.allowed?a("#variable_product_options").find(".variation-needs-update").removeClass("variation-needs-update"):d.check_for_changes(),d.block(),a.ajax({url:woocommerce_admin_meta_boxes_variations.ajax_url,data:{action:"woocommerce_bulk_edit_variations",security:woocommerce_admin_meta_boxes_variations.bulk_edit_variations_nonce,product_id:woocommerce_admin_meta_boxes_variations.post_id,product_type:a("#product-type").val(),bulk_action:c,data:f},type:"POST",success:function(){e.go_to_page(1,g)}})}},e={init:function(){a(document.body).on("woocommerce_variations_added",this.update_single_quantity).on("change",".variations-pagenav .page-selector",this.page_selector).on("click",".variations-pagenav .first-page",this.first_page).on("click",".variations-pagenav .prev-page",this.prev_page).on("click",".variations-pagenav .next-page",this.next_page).on("click",".variations-pagenav .last-page",this.last_page)},update_variations_count:function(b){var c=a("#variable_product_options").find(".woocommerce_variations"),d=parseInt(c.attr("data-total"),10)+b,e=a(".variations-pagenav .displaying-num");return c.attr("data-total",d),1===d?e.text(woocommerce_admin_meta_boxes_variations.i18n_variation_count_single.replace("%qty%",d)):e.text(woocommerce_admin_meta_boxes_variations.i18n_variation_count_plural.replace("%qty%",d)),d},update_single_quantity:function(b,c){if(1===c){var d=a(".variations-pagenav");e.update_variations_count(c),d.is(":hidden")&&(a("option, optgroup",".variation_actions").show(),a(".variation_actions").val("add_variation"),a("#variable_product_options").find(".toolbar").show(),d.show(),a(".pagination-links",d).hide())}},set_paginav:function(b){var c=a("#variable_product_options").find(".woocommerce_variations"),d=e.update_variations_count(b),f=a("#variable_product_options").find(".toolbar"),g=a(".variation_actions"),h=a(".variations-pagenav"),i=a(".pagination-links",h),j=Math.ceil(d/woocommerce_admin_meta_boxes_variations.variations_per_page),k="";c.attr("data-total_pages",j),a(".total-pages",h).text(j);for(var l=1;j>=l;l++)k+='";a(".page-selector",h).empty().html(k),0===d?(f.not(".toolbar-top, .toolbar-buttons").hide(),h.hide(),a("option, optgroup",g).hide(),a(".variation_actions").val("add_variation"),a('option[data-global="true"]',g).show()):(f.show(),h.show(),a("option, optgroup",g).show(),a(".variation_actions").val("add_variation"),1===j?i.hide():i.show())},check_is_enabled:function(b){return!a(b).hasClass("disabled")},change_classes:function(b,c){var d=a(".variations-pagenav .first-page"),e=a(".variations-pagenav .prev-page"),f=a(".variations-pagenav .next-page"),g=a(".variations-pagenav .last-page");1===b?(d.addClass("disabled"),e.addClass("disabled")):(d.removeClass("disabled"),e.removeClass("disabled")),c===b?(f.addClass("disabled"),g.addClass("disabled")):(f.removeClass("disabled"),g.removeClass("disabled"))},set_page:function(b){a(".variations-pagenav .page-selector").val(b).first().change()},go_to_page:function(a,b){a=a||1,b=b||0,e.set_paginav(b),e.set_page(a)},page_selector:function(){var b=parseInt(a(this).val(),10),c=a("#variable_product_options").find(".woocommerce_variations");a(".variations-pagenav .page-selector").val(b),d.check_for_changes(),e.change_classes(b,parseInt(c.attr("data-total_pages"),10)),d.load_variations(b)},first_page:function(){return e.check_is_enabled(this)&&e.set_page(1),!1},prev_page:function(){if(e.check_is_enabled(this)){var b=a("#variable_product_options").find(".woocommerce_variations"),c=parseInt(b.attr("data-page"),10)-1,d=c>0?c:1;e.set_page(d)}return!1},next_page:function(){if(e.check_is_enabled(this)){var b=a("#variable_product_options").find(".woocommerce_variations"),c=parseInt(b.attr("data-total_pages"),10),d=parseInt(b.attr("data-page"),10)+1,f=c>=d?d:c;e.set_page(f)}return!1},last_page:function(){if(e.check_is_enabled(this)){var b=a("#variable_product_options").find(".woocommerce_variations").attr("data-total_pages");e.set_page(b)}return!1}};b.init(),c.init(),d.init(),e.init()}); \ No newline at end of file +jQuery(function(a){var b={init:function(){a("#variable_product_options").on("change","input.variable_is_downloadable",this.variable_is_downloadable).on("change","input.variable_is_virtual",this.variable_is_virtual).on("change","input.variable_manage_stock",this.variable_manage_stock).on("click","button.notice-dismiss",this.notice_dismiss).on("click","h3 .sort",this.set_menu_order).on("reload",this.reload),a("input.variable_is_downloadable, input.variable_is_virtual, input.variable_manage_stock").change(),a("#woocommerce-product-data").on("woocommerce_variations_loaded",this.variations_loaded),a(document.body).on("woocommerce_variations_added",this.variation_added)},reload:function(){d.load_variations(1),e.set_paginav(0)},variable_is_downloadable:function(){a(this).closest(".woocommerce_variation").find(".show_if_variation_downloadable").hide(),a(this).is(":checked")&&a(this).closest(".woocommerce_variation").find(".show_if_variation_downloadable").show()},variable_is_virtual:function(){a(this).closest(".woocommerce_variation").find(".hide_if_variation_virtual").show(),a(this).is(":checked")&&a(this).closest(".woocommerce_variation").find(".hide_if_variation_virtual").hide()},variable_manage_stock:function(){a(this).closest(".woocommerce_variation").find(".show_if_variation_manage_stock").hide(),a(this).is(":checked")&&a(this).closest(".woocommerce_variation").find(".show_if_variation_manage_stock").show()},notice_dismiss:function(){a(this).closest("div.notice").remove()},variations_loaded:function(c,d){d=d||!1;var e=a("#woocommerce-product-data");d||(a("input.variable_is_downloadable, input.variable_is_virtual, input.variable_manage_stock",e).change(),a(".woocommerce_variation",e).each(function(b,c){var d=a(c),e=a(".sale_price_dates_from",d).val(),f=a(".sale_price_dates_to",d).val();""===e&&""===f||a("a.sale_schedule",d).click()}),a(".woocommerce_variations .variation-needs-update",e).removeClass("variation-needs-update"),a("button.cancel-variation-changes, button.save-variation-changes",e).attr("disabled","disabled")),a("#tiptip_holder").removeAttr("style"),a("#tiptip_arrow").removeAttr("style"),a(".woocommerce_variations .tips, .woocommerce_variations .help_tip, .woocommerce_variations .woocommerce-help-tip",e).tipTip({attribute:"data-tip",fadeIn:50,fadeOut:50,delay:200}),a(".sale_price_dates_fields",e).find("input").datepicker({defaultDate:"",dateFormat:"yy-mm-dd",numberOfMonths:1,showButtonPanel:!0,onSelect:function(b,c){var d=a(this).is(".sale_price_dates_from")?"minDate":"maxDate",e=a(this).closest(".sale_price_dates_fields").find("input"),f=a.datepicker.parseDate(c.settings.dateFormat||a.datepicker._defaults.dateFormat,b,c.settings);e.not(this).datepicker("option",d,f),a(this).change()}}),a(".woocommerce_variations",e).sortable({items:".woocommerce_variation",cursor:"move",axis:"y",handle:".sort",scrollSensitivity:40,forcePlaceholderSize:!0,helper:"clone",opacity:.65,stop:function(){b.variation_row_indexes()}}),a(document.body).trigger("wc-enhanced-select-init")},variation_added:function(a,c){1===c&&b.variations_loaded(null,!0)},set_menu_order:function(b){b.preventDefault();var c=a(this).closest(".woocommerce_variation").find(".variation_menu_order"),e=window.prompt(woocommerce_admin_meta_boxes_variations.i18n_enter_menu_order,c.val());null!=e&&(c.val(parseInt(e,10)).change(),d.save_variations())},variation_row_indexes:function(){var b=a("#variable_product_options").find(".woocommerce_variations"),c=parseInt(b.attr("data-page"),10),d=parseInt((c-1)*woocommerce_admin_meta_boxes_variations.variations_per_page,10);a(".woocommerce_variations .woocommerce_variation").each(function(b,c){a(".variation_menu_order",c).val(parseInt(a(c).index(".woocommerce_variations .woocommerce_variation"),10)+1+d).change()})}},c={variable_image_frame:null,setting_variation_image_id:null,setting_variation_image:null,wp_media_post_id:wp.media.model.settings.post.id,init:function(){a("#variable_product_options").on("click",".upload_image_button",this.add_image),a("a.add_media").on("click",this.restore_wp_media_post_id)},add_image:function(b){var d=a(this),e=d.attr("rel"),f=d.closest(".upload_image");if(c.setting_variation_image=f,c.setting_variation_image_id=e,b.preventDefault(),d.is(".remove"))a(".upload_image_id",c.setting_variation_image).val("").change(),c.setting_variation_image.find("img").eq(0).attr("src",woocommerce_admin_meta_boxes_variations.woocommerce_placeholder_img_src),c.setting_variation_image.find(".upload_image_button").removeClass("remove");else{if(c.variable_image_frame)return c.variable_image_frame.uploader.uploader.param("post_id",c.setting_variation_image_id),void c.variable_image_frame.open();wp.media.model.settings.post.id=c.setting_variation_image_id,c.variable_image_frame=wp.media.frames.variable_image=wp.media({title:woocommerce_admin_meta_boxes_variations.i18n_choose_image,button:{text:woocommerce_admin_meta_boxes_variations.i18n_set_image},states:[new wp.media.controller.Library({title:woocommerce_admin_meta_boxes_variations.i18n_choose_image,filterable:"all"})]}),c.variable_image_frame.on("select",function(){var b=c.variable_image_frame.state().get("selection").first().toJSON(),d=b.sizes&&b.sizes.thumbnail?b.sizes.thumbnail.url:b.url;a(".upload_image_id",c.setting_variation_image).val(b.id).change(),c.setting_variation_image.find(".upload_image_button").addClass("remove"),c.setting_variation_image.find("img").eq(0).attr("src",d),wp.media.model.settings.post.id=c.wp_media_post_id}),c.variable_image_frame.open()}},restore_wp_media_post_id:function(){wp.media.model.settings.post.id=c.wp_media_post_id}},d={init:function(){a("li.variations_tab a").on("click",this.initial_load),a("#variable_product_options").on("click","button.save-variation-changes",this.save_variations).on("click","button.cancel-variation-changes",this.cancel_variations).on("click",".remove_variation",this.remove_variation),a(document.body).on("change","#variable_product_options .woocommerce_variations :input",this.input_changed).on("change",".variations-defaults select",this.defaults_changed),a("form#post").on("submit",this.save_on_submit),a(".wc-metaboxes-wrapper").on("click","a.do_variation_action",this.do_variation_action)},check_for_changes:function(){var b=a("#variable_product_options").find(".woocommerce_variations .variation-needs-update");if(0d&&0!==d&&(f=d),e.go_to_page(f,-1)})):d.unblock()}return!1},link_all_variations:function(){if(d.check_for_changes(),window.confirm(woocommerce_admin_meta_boxes_variations.i18n_link_all_variations)){d.block();var b={action:"woocommerce_link_all_variations",post_id:woocommerce_admin_meta_boxes_variations.post_id,security:woocommerce_admin_meta_boxes_variations.link_variation_nonce};a.post(woocommerce_admin_meta_boxes_variations.ajax_url,b,function(b){var c=parseInt(b,10);1===c?window.alert(c+" "+woocommerce_admin_meta_boxes_variations.i18n_variation_added):0===c||c>1?window.alert(c+" "+woocommerce_admin_meta_boxes_variations.i18n_variations_added):window.alert(woocommerce_admin_meta_boxes_variations.i18n_no_variations_added),c>0?(e.go_to_page(1,c),a("#variable_product_options").trigger("woocommerce_variations_added",c)):d.unblock()})}return!1},input_changed:function(){a(this).closest(".woocommerce_variation").addClass("variation-needs-update"),a("button.cancel-variation-changes, button.save-variation-changes").removeAttr("disabled"),a("#variable_product_options").trigger("woocommerce_variations_input_changed")},defaults_changed:function(){a(this).closest("#variable_product_options").find(".woocommerce_variation:first").addClass("variation-needs-update"),a("button.cancel-variation-changes, button.save-variation-changes").removeAttr("disabled"),a("#variable_product_options").trigger("woocommerce_variations_defaults_changed")},do_variation_action:function(){var b,c=a("select.variation_actions").val(),f={},g=0;switch(c){case"add_variation":return void d.add_variation();case"link_all_variations":return void d.link_all_variations();case"delete_all":window.confirm(woocommerce_admin_meta_boxes_variations.i18n_delete_all_variations)&&window.confirm(woocommerce_admin_meta_boxes_variations.i18n_last_warning)&&(f.allowed=!0,g=parseInt(a("#variable_product_options").find(".woocommerce_variations").attr("data-total"),10)*-1);break;case"variable_regular_price_increase":case"variable_regular_price_decrease":case"variable_sale_price_increase":case"variable_sale_price_decrease":b=window.prompt(woocommerce_admin_meta_boxes_variations.i18n_enter_a_value_fixed_or_percent),null!=b&&(b.indexOf("%")>=0?f.value=accounting.unformat(b.replace(/\%/,""),woocommerce_admin.mon_decimal_point)+"%":f.value=accounting.unformat(b,woocommerce_admin.mon_decimal_point));break;case"variable_regular_price":case"variable_sale_price":case"variable_stock":case"variable_weight":case"variable_length":case"variable_width":case"variable_height":case"variable_download_limit":case"variable_download_expiry":b=window.prompt(woocommerce_admin_meta_boxes_variations.i18n_enter_a_value),null!=b&&(f.value=b);break;case"variable_sale_schedule":f.date_from=window.prompt(woocommerce_admin_meta_boxes_variations.i18n_scheduled_sale_start),f.date_to=window.prompt(woocommerce_admin_meta_boxes_variations.i18n_scheduled_sale_end),null===f.date_from&&(f.date_from=!1),null===f.date_to&&(f.date_to=!1);break;default:a("select.variation_actions").trigger(c),f=a("select.variation_actions").triggerHandler(c+"_ajax_data",f)}"delete_all"===c&&f.allowed?a("#variable_product_options").find(".variation-needs-update").removeClass("variation-needs-update"):d.check_for_changes(),d.block(),a.ajax({url:woocommerce_admin_meta_boxes_variations.ajax_url,data:{action:"woocommerce_bulk_edit_variations",security:woocommerce_admin_meta_boxes_variations.bulk_edit_variations_nonce,product_id:woocommerce_admin_meta_boxes_variations.post_id,product_type:a("#product-type").val(),bulk_action:c,data:f},type:"POST",success:function(){e.go_to_page(1,g)}})}},e={init:function(){a(document.body).on("woocommerce_variations_added",this.update_single_quantity).on("change",".variations-pagenav .page-selector",this.page_selector).on("click",".variations-pagenav .first-page",this.first_page).on("click",".variations-pagenav .prev-page",this.prev_page).on("click",".variations-pagenav .next-page",this.next_page).on("click",".variations-pagenav .last-page",this.last_page)},update_variations_count:function(b){var c=a("#variable_product_options").find(".woocommerce_variations"),d=parseInt(c.attr("data-total"),10)+b,e=a(".variations-pagenav .displaying-num");return c.attr("data-total",d),1===d?e.text(woocommerce_admin_meta_boxes_variations.i18n_variation_count_single.replace("%qty%",d)):e.text(woocommerce_admin_meta_boxes_variations.i18n_variation_count_plural.replace("%qty%",d)),d},update_single_quantity:function(b,c){if(1===c){var d=a(".variations-pagenav");e.update_variations_count(c),d.is(":hidden")&&(a("option, optgroup",".variation_actions").show(),a(".variation_actions").val("add_variation"),a("#variable_product_options").find(".toolbar").show(),d.show(),a(".pagination-links",d).hide())}},set_paginav:function(b){var c=a("#variable_product_options").find(".woocommerce_variations"),d=e.update_variations_count(b),f=a("#variable_product_options").find(".toolbar"),g=a(".variation_actions"),h=a(".variations-pagenav"),i=a(".pagination-links",h),j=Math.ceil(d/woocommerce_admin_meta_boxes_variations.variations_per_page),k="";c.attr("data-total_pages",j),a(".total-pages",h).text(j);for(var l=1;l<=j;l++)k+='";a(".page-selector",h).empty().html(k),0===d?(f.not(".toolbar-top, .toolbar-buttons").hide(),h.hide(),a("option, optgroup",g).hide(),a(".variation_actions").val("add_variation"),a('option[data-global="true"]',g).show()):(f.show(),h.show(),a("option, optgroup",g).show(),a(".variation_actions").val("add_variation"),1===j?i.hide():i.show())},check_is_enabled:function(b){return!a(b).hasClass("disabled")},change_classes:function(b,c){var d=a(".variations-pagenav .first-page"),e=a(".variations-pagenav .prev-page"),f=a(".variations-pagenav .next-page"),g=a(".variations-pagenav .last-page");1===b?(d.addClass("disabled"),e.addClass("disabled")):(d.removeClass("disabled"),e.removeClass("disabled")),c===b?(f.addClass("disabled"),g.addClass("disabled")):(f.removeClass("disabled"),g.removeClass("disabled"))},set_page:function(b){a(".variations-pagenav .page-selector").val(b).first().change()},go_to_page:function(a,b){a=a||1,b=b||0,e.set_paginav(b),e.set_page(a)},page_selector:function(){var b=parseInt(a(this).val(),10),c=a("#variable_product_options").find(".woocommerce_variations");a(".variations-pagenav .page-selector").val(b),d.check_for_changes(),e.change_classes(b,parseInt(c.attr("data-total_pages"),10)),d.load_variations(b)},first_page:function(){return e.check_is_enabled(this)&&e.set_page(1),!1},prev_page:function(){if(e.check_is_enabled(this)){var b=a("#variable_product_options").find(".woocommerce_variations"),c=parseInt(b.attr("data-page"),10)-1,d=0=d?d:c;e.set_page(f)}return!1},last_page:function(){if(e.check_is_enabled(this)){var b=a("#variable_product_options").find(".woocommerce_variations").attr("data-total_pages");e.set_page(b)}return!1}};b.init(),c.init(),d.init(),e.init()}); \ No newline at end of file diff --git a/assets/js/admin/meta-boxes-product.js b/assets/js/admin/meta-boxes-product.js index 7bc6b6b7e2b..29d7ed41c38 100644 --- a/assets/js/admin/meta-boxes-product.js +++ b/assets/js/admin/meta-boxes-product.js @@ -18,23 +18,23 @@ jQuery( function( $ ) { }); }); - // Prevent enter submitting post form + // Prevent enter submitting post form. $( '#upsell_product_data' ).bind( 'keypress', function( e ) { if ( e.keyCode === 13 ) { return false; } }); - // Type box + // Type box. $( '.type_box' ).appendTo( '#woocommerce-product-data .hndle span' ); $( function() { - // Prevent inputs in meta box headings opening/closing contents + // Prevent inputs in meta box headings opening/closing contents. $( '#woocommerce-product-data' ).find( '.hndle' ).unbind( 'click.postboxes' ); - jQuery( '#woocommerce-product-data' ).on( 'click', '.hndle', function( event ) { + $( '#woocommerce-product-data' ).on( 'click', '.hndle', function( event ) { - // If the user clicks on some form input inside the h3 the box should not be toggled + // If the user clicks on some form input inside the h3 the box should not be toggled. if ( $( event.target ).filter( 'input, option, label, select' ).length ) { return; } @@ -43,15 +43,15 @@ jQuery( function( $ ) { }); }); - // Catalog Visibility - $( '#catalog-visibility' ).find( '.edit-catalog-visibility' ).click( function () { + // Catalog Visibility. + $( '#catalog-visibility' ).find( '.edit-catalog-visibility' ).click( function() { if ( $( '#catalog-visibility-select' ).is( ':hidden' ) ) { $( '#catalog-visibility-select' ).slideDown( 'fast' ); $( this ).hide(); } return false; }); - $( '#catalog-visibility' ).find( '.save-post-visibility' ).click( function () { + $( '#catalog-visibility' ).find( '.save-post-visibility' ).click( function() { $( '#catalog-visibility-select' ).slideUp( 'fast' ); $( '#catalog-visibility' ).find( '.edit-catalog-visibility' ).show(); @@ -65,7 +65,7 @@ jQuery( function( $ ) { $( '#catalog-visibility-display' ).text( label ); return false; }); - $( '#catalog-visibility' ).find( '.cancel-post-visibility' ).click( function () { + $( '#catalog-visibility' ).find( '.cancel-post-visibility' ).click( function() { $( '#catalog-visibility-select' ).slideUp( 'fast' ); $( '#catalog-visibility' ).find( '.edit-catalog-visibility' ).show(); @@ -88,10 +88,10 @@ jQuery( function( $ ) { return false; }); - // PRODUCT TYPE SPECIFIC OPTIONS - $( 'select#product-type' ).change( function () { + // PRODUCT TYPE SPECIFIC OPTIONS. + $( 'select#product-type' ).change( function() { - // Get value + // Get value. var select_val = $( this ).val(); if ( 'variable' === select_val ) { @@ -114,34 +114,28 @@ jQuery( function( $ ) { }).change(); - $( document.body ).on( 'woocommerce-product-type-change', function( e, select_val ) { - if ( 'variable' !== select_val && 0 < $( '#variable_product_options' ).find( 'input[name^=variable_sku]' ).length && $( document.body ).triggerHandler( 'woocommerce-display-product-type-alert', select_val ) !== false ) { - window.alert( woocommerce_admin_meta_boxes.i18n_product_type_alert ); - } - }); - $( 'input#_downloadable, input#_virtual' ).change( function() { show_and_hide_panels(); }); function show_and_hide_panels() { var product_type = $( 'select#product-type' ).val(); - var is_virtual = $( 'input#_virtual:checked' ).size(); - var is_downloadable = $( 'input#_downloadable:checked' ).size(); + var is_virtual = $( 'input#_virtual:checked' ).length; + var is_downloadable = $( 'input#_downloadable:checked' ).length; - // Hide/Show all with rules + // Hide/Show all with rules. var hide_classes = '.hide_if_downloadable, .hide_if_virtual'; - var show_classes = '.show_if_downloadable, .show_if_virtual, .show_if_external'; + var show_classes = '.show_if_downloadable, .show_if_virtual'; $.each( woocommerce_admin_meta_boxes.product_types, function( index, value ) { hide_classes = hide_classes + ', .hide_if_' + value; show_classes = show_classes + ', .show_if_' + value; - } ); + }); $( hide_classes ).show(); $( show_classes ).hide(); - // Shows rules + // Shows rules. if ( is_downloadable ) { $( '.show_if_downloadable' ).show(); } @@ -151,7 +145,7 @@ jQuery( function( $ ) { $( '.show_if_' + product_type ).show(); - // Hide rules + // Hide rules. if ( is_downloadable ) { $( '.hide_if_downloadable' ).hide(); } @@ -162,16 +156,35 @@ jQuery( function( $ ) { $( '.hide_if_' + product_type ).hide(); $( 'input#_manage_stock' ).change(); + + // Hide empty panels/tabs after display. + $( '.woocommerce_options_panel' ).each( function() { + var $children = $( this ).children( '.options_group' ); + + if ( 0 === $children.length ) { + return; + } + + var $invisble = $children.filter( function() { + return 'none' === $( this ).css( 'display' ); + }); + + // Hide panel. + if ( $invisble.length === $children.length ) { + var $id = $( this ).prop( 'id' ); + $( '.product_data_tabs' ).find( 'li a[href="#' + $id + '"]' ).parent().hide(); + } + }); } - // Sale price schedule + // Sale price schedule. $( '.sale_price_dates_fields' ).each( function() { var $these_sale_dates = $( this ); var sale_schedule_set = false; var $wrap = $these_sale_dates.closest( 'div, table' ); $these_sale_dates.find( 'input' ).each( function() { - if ( $( this ).val() !== '' ) { + if ( '' !== $( this ).val() ) { sale_schedule_set = true; } }); @@ -205,7 +218,7 @@ jQuery( function( $ ) { return false; }); - // File inputs + // File inputs. $( '#woocommerce-product-data' ).on( 'click','.downloadable_files a.insert', function() { $( this ).closest( '.downloadable_files' ).find( 'tbody' ).append( $( this ).data( 'row' ) ); return false; @@ -215,7 +228,7 @@ jQuery( function( $ ) { return false; }); - // STOCK OPTIONS + // STOCK OPTIONS. $( 'input#_manage_stock' ).change( function() { if ( $( this ).is( ':checked' ) ) { $( 'div.stock_fields' ).show(); @@ -224,7 +237,7 @@ jQuery( function( $ ) { } }).change(); - // DATE PICKER FIELDS + // DATE PICKER FIELDS. $( '.sale_price_dates_fields' ).each( function() { var dates = $( this ).find( 'input' ).datepicker({ defaultDate: '', @@ -240,18 +253,18 @@ jQuery( function( $ ) { }); }); - // ATTRIBUTE TABLES + // ATTRIBUTE TABLES. - // Initial order - var woocommerce_attribute_items = $('.product_attributes').find('.woocommerce_attribute').get(); + // Initial order. + var woocommerce_attribute_items = $( '.product_attributes' ).find( '.woocommerce_attribute' ).get(); - woocommerce_attribute_items.sort(function(a, b) { + woocommerce_attribute_items.sort( function( a, b ) { var compA = parseInt( $( a ).attr( 'rel' ), 10 ); var compB = parseInt( $( b ).attr( 'rel' ), 10 ); - return (compA < compB) ? -1 : (compA > compB) ? 1 : 0; + return ( compA < compB ) ? -1 : ( compA > compB ) ? 1 : 0; }); - $( woocommerce_attribute_items ).each( function( idx, itm ) { - $( '.product_attributes' ).append(itm); + $( woocommerce_attribute_items ).each( function( index, el ) { + $( '.product_attributes' ).append( el ); }); function attribute_row_indexes() { @@ -266,11 +279,12 @@ jQuery( function( $ ) { } }); - // Add rows + // Add rows. $( 'button.add_attribute' ).on( 'click', function() { - var size = $( '.product_attributes .woocommerce_attribute' ).size(); + var size = $( '.product_attributes .woocommerce_attribute' ).length; var attribute = $( 'select.attribute_taxonomy' ).val(); - var $wrapper = $( this ).closest( '#product_attributes' ).find( '.product_attributes' ); + var $wrapper = $( this ).closest( '#product_attributes' ); + var $attributes = $wrapper.find( '.product_attributes' ); var product_type = $( 'select#product-type' ).val(); var data = { action: 'woocommerce_add_attribute', @@ -288,10 +302,10 @@ jQuery( function( $ ) { }); $.post( woocommerce_admin_meta_boxes.ajax_url, data, function( response ) { - $wrapper.append( response ); + $attributes.append( response ); - if ( product_type !== 'variable' ) { - $wrapper.find( '.enable_variation' ).hide(); + if ( 'variable' !== product_type ) { + $attributes.find( '.enable_variation' ).hide(); } $( document.body ).trigger( 'wc-enhanced-select-init' ); @@ -321,7 +335,7 @@ jQuery( function( $ ) { $( '.product_attributes' ).on( 'click', 'button.select_no_attributes', function() { $( this ).closest( 'td' ).find( 'select option' ).removeAttr( 'selected' ); - $( this ).closest( 'td' ).find( 'select').change(); + $( this ).closest( 'td' ).find( 'select' ).change(); return false; }); @@ -330,11 +344,11 @@ jQuery( function( $ ) { var $parent = $( this ).parent().parent(); if ( $parent.is( '.taxonomy' ) ) { - $parent.find( 'select, input[type=text]' ).val(''); + $parent.find( 'select, input[type=text]' ).val( '' ); $parent.hide(); $( 'select.attribute_taxonomy' ).find( 'option[value="' + $parent.data( 'taxonomy' ) + '"]' ).removeAttr( 'disabled' ); } else { - $parent.find( 'select, input[type=text]' ).val(''); + $parent.find( 'select, input[type=text]' ).val( '' ); $parent.hide(); attribute_row_indexes(); } @@ -342,7 +356,7 @@ jQuery( function( $ ) { return false; }); - // Attribute ordering + // Attribute ordering. $( '.product_attributes' ).sortable({ items: '.woocommerce_attribute', cursor: 'move', @@ -362,10 +376,16 @@ jQuery( function( $ ) { } }); - // Add a new attribute (via ajax) + // Add a new attribute (via ajax). $( '.product_attributes' ).on( 'click', 'button.add_new_attribute', function() { - $( '.product_attributes' ).block({ message: null, overlayCSS: { background: '#fff', opacity: 0.6 } }); + $( '.product_attributes' ).block({ + message: null, + overlayCSS: { + background: '#fff', + opacity: 0.6 + } + }); var $wrapper = $( this ).closest( '.woocommerce_attribute' ); var attribute = $wrapper.data( 'taxonomy' ); @@ -383,11 +403,11 @@ jQuery( function( $ ) { $.post( woocommerce_admin_meta_boxes.ajax_url, data, function( response ) { if ( response.error ) { - // Error + // Error. window.alert( response.error ); } else if ( response.slug ) { - // Success - $wrapper.find( 'select.attribute_values' ).append( '' ); + // Success. + $wrapper.find( 'select.attribute_values' ).append( '' ); $wrapper.find( 'select.attribute_values' ).change(); } @@ -401,7 +421,7 @@ jQuery( function( $ ) { return false; }); - // Save attributes and update variations + // Save attributes and update variations. $( '.save_attributes' ).on( 'click', function() { $( '#woocommerce-product-data' ).block({ @@ -413,29 +433,30 @@ jQuery( function( $ ) { }); var data = { - post_id: woocommerce_admin_meta_boxes.post_id, - data: $( '.product_attributes' ).find( 'input, select, textarea' ).serialize(), - action: 'woocommerce_save_attributes', - security: woocommerce_admin_meta_boxes.save_attributes_nonce + post_id : woocommerce_admin_meta_boxes.post_id, + product_type: $( '#product-type' ).val(), + data : $( '.product_attributes' ).find( 'input, select, textarea' ).serialize(), + action : 'woocommerce_save_attributes', + security : woocommerce_admin_meta_boxes.save_attributes_nonce }; $.post( woocommerce_admin_meta_boxes.ajax_url, data, function() { - // Reload variations panel + // Reload variations panel. var this_page = window.location.toString(); this_page = this_page.replace( 'post-new.php?', 'post.php?post=' + woocommerce_admin_meta_boxes.post_id + '&action=edit&' ); - // Load variations panel + // Load variations panel. $( '#variable_product_options' ).load( this_page + ' #variable_product_options_inner', function() { $( '#variable_product_options' ).trigger( 'reload' ); }); }); }); - // Uploading files + // Uploading files. var downloadable_file_frame; var file_path_field; - jQuery( document.body ).on( 'click', '.upload_file_button', function( event ) { + $( document.body ).on( 'click', '.upload_file_button', function( event ) { var $el = $( this ); file_path_field = $el.closest( 'tr' ).find( 'td.file_url input' ); @@ -488,7 +509,7 @@ jQuery( function( $ ) { file_path_field.val( file_path ).change(); }); - // Set post to 0 and set our custom type + // Set post to 0 and set our custom type. downloadable_file_frame.on( 'ready', function() { downloadable_file_frame.uploader.options.uploader.params = { type: 'downloadable_product' @@ -499,8 +520,8 @@ jQuery( function( $ ) { downloadable_file_frame.open(); }); - // Download ordering - jQuery( '.downloadable_files tbody' ).sortable({ + // Download ordering. + $( '.downloadable_files tbody' ).sortable({ items: 'tr', cursor: 'move', axis: 'y', @@ -511,12 +532,12 @@ jQuery( function( $ ) { opacity: 0.65 }); - // Product gallery file uploads + // Product gallery file uploads. var product_gallery_frame; var $image_gallery_ids = $( '#product_image_gallery' ); var $product_images = $( '#product_images_container' ).find( 'ul.product_images' ); - jQuery( '.add_product_images' ).on( 'click', 'a', function( event ) { + $( '.add_product_images' ).on( 'click', 'a', function( event ) { var $el = $( this ); event.preventDefault(); @@ -566,7 +587,7 @@ jQuery( function( $ ) { product_gallery_frame.open(); }); - // Image ordering + // Image ordering. $product_images.sortable({ items: 'li.image', cursor: 'move', @@ -586,7 +607,7 @@ jQuery( function( $ ) { var attachment_ids = ''; $( '#product_images_container' ).find( 'ul li.image' ).css( 'cursor', 'default' ).each( function() { - var attachment_id = jQuery( this ).attr( 'data-attachment_id' ); + var attachment_id = $( this ).attr( 'data-attachment_id' ); attachment_ids = attachment_ids + attachment_id + ','; }); @@ -594,20 +615,20 @@ jQuery( function( $ ) { } }); - // Remove images + // Remove images. $( '#product_images_container' ).on( 'click', 'a.delete', function() { $( this ).closest( 'li.image' ).remove(); var attachment_ids = ''; $( '#product_images_container' ).find( 'ul li.image' ).css( 'cursor', 'default' ).each( function() { - var attachment_id = jQuery( this ).attr( 'data-attachment_id' ); + var attachment_id = $( this ).attr( 'data-attachment_id' ); attachment_ids = attachment_ids + attachment_id + ','; }); $image_gallery_ids.val( attachment_ids ); - // remove any lingering tooltips + // Remove any lingering tooltips. $( '#tiptip_holder' ).removeAttr( 'style' ); $( '#tiptip_arrow' ).removeAttr( 'style' ); diff --git a/assets/js/admin/meta-boxes-product.min.js b/assets/js/admin/meta-boxes-product.min.js index 550cfd1d571..283b69cee9c 100644 --- a/assets/js/admin/meta-boxes-product.min.js +++ b/assets/js/admin/meta-boxes-product.min.js @@ -1 +1 @@ -jQuery(function(a){function b(){var b=a("select#product-type").val(),c=a("input#_virtual:checked").size(),d=a("input#_downloadable:checked").size(),e=".hide_if_downloadable, .hide_if_virtual",f=".show_if_downloadable, .show_if_virtual, .show_if_external";a.each(woocommerce_admin_meta_boxes.product_types,function(a,b){e=e+", .hide_if_"+b,f=f+", .show_if_"+b}),a(e).show(),a(f).hide(),d&&a(".show_if_downloadable").show(),c&&a(".show_if_virtual").show(),a(".show_if_"+b).show(),d&&a(".hide_if_downloadable").hide(),c&&a(".hide_if_virtual").hide(),a(".hide_if_"+b).hide(),a("input#_manage_stock").change()}function c(){a(".product_attributes .woocommerce_attribute").each(function(b,c){a(".attribute_position",c).val(parseInt(a(c).index(".product_attributes .woocommerce_attribute"),10))})}a(function(){a('[id$="-all"] > ul.categorychecklist').each(function(){var b=a(this),c=b.find(":checked").first();if(c.length){var d=b.find("input").position().top,e=c.position().top;b.closest(".tabs-panel").scrollTop(e-d+5)}})}),a("#upsell_product_data").bind("keypress",function(a){return 13===a.keyCode?!1:void 0}),a(".type_box").appendTo("#woocommerce-product-data .hndle span"),a(function(){a("#woocommerce-product-data").find(".hndle").unbind("click.postboxes"),jQuery("#woocommerce-product-data").on("click",".hndle",function(b){a(b.target).filter("input, option, label, select").length||a("#woocommerce-product-data").toggleClass("closed")})}),a("#catalog-visibility").find(".edit-catalog-visibility").click(function(){return a("#catalog-visibility-select").is(":hidden")&&(a("#catalog-visibility-select").slideDown("fast"),a(this).hide()),!1}),a("#catalog-visibility").find(".save-post-visibility").click(function(){a("#catalog-visibility-select").slideUp("fast"),a("#catalog-visibility").find(".edit-catalog-visibility").show();var b=a("input[name=_visibility]:checked").attr("data-label");return a("input[name=_featured]").is(":checked")&&(b=b+", "+woocommerce_admin_meta_boxes.featured_label,a("input[name=_featured]").attr("checked","checked")),a("#catalog-visibility-display").text(b),!1}),a("#catalog-visibility").find(".cancel-post-visibility").click(function(){a("#catalog-visibility-select").slideUp("fast"),a("#catalog-visibility").find(".edit-catalog-visibility").show();var b=a("#current_visibility").val(),c=a("#current_featured").val();a("input[name=_visibility]").removeAttr("checked"),a("input[name=_visibility][value="+b+"]").attr("checked","checked");var d=a("input[name=_visibility]:checked").attr("data-label");return"yes"===c?(d=d+", "+woocommerce_admin_meta_boxes.featured_label,a("input[name=_featured]").attr("checked","checked")):a("input[name=_featured]").removeAttr("checked"),a("#catalog-visibility-display").text(d),!1}),a("select#product-type").change(function(){var c=a(this).val();"variable"===c?(a("input#_manage_stock").change(),a("input#_downloadable").prop("checked",!1),a("input#_virtual").removeAttr("checked")):"grouped"===c?(a("input#_downloadable").prop("checked",!1),a("input#_virtual").removeAttr("checked")):"external"===c&&(a("input#_downloadable").prop("checked",!1),a("input#_virtual").removeAttr("checked")),b(),a("ul.wc-tabs li:visible").eq(0).find("a").click(),a(document.body).trigger("woocommerce-product-type-change",c,a(this))}).change(),a(document.body).on("woocommerce-product-type-change",function(b,c){"variable"!==c&&0d?-1:d>e?1:0}),a(d).each(function(b,c){a(".product_attributes").append(c)}),a(".product_attributes .woocommerce_attribute").each(function(b,c){"none"!==a(c).css("display")&&a(c).is(".taxonomy")&&a("select.attribute_taxonomy").find('option[value="'+a(c).data("taxonomy")+'"]').attr("disabled","disabled")}),a("button.add_attribute").on("click",function(){var b=a(".product_attributes .woocommerce_attribute").size(),d=a("select.attribute_taxonomy").val(),e=a(this).closest("#product_attributes").find(".product_attributes"),f=a("select#product-type").val(),g={action:"woocommerce_add_attribute",taxonomy:d,i:b,security:woocommerce_admin_meta_boxes.add_attribute_nonce};return e.block({message:null,overlayCSS:{background:"#fff",opacity:.6}}),a.post(woocommerce_admin_meta_boxes.ajax_url,g,function(b){e.append(b),"variable"!==f&&e.find(".enable_variation").hide(),a(document.body).trigger("wc-enhanced-select-init"),c(),e.unblock(),a(document.body).trigger("woocommerce_added_attribute")}),d&&(a("select.attribute_taxonomy").find('option[value="'+d+'"]').attr("disabled","disabled"),a("select.attribute_taxonomy").val("")),!1}),a(".product_attributes").on("blur","input.attribute_name",function(){a(this).closest(".woocommerce_attribute").find("strong.attribute_name").text(a(this).val())}),a(".product_attributes").on("click","button.select_all_attributes",function(){return a(this).closest("td").find("select option").attr("selected","selected"),a(this).closest("td").find("select").change(),!1}),a(".product_attributes").on("click","button.select_no_attributes",function(){return a(this).closest("td").find("select option").removeAttr("selected"),a(this).closest("td").find("select").change(),!1}),a(".product_attributes").on("click",".remove_row",function(){if(window.confirm(woocommerce_admin_meta_boxes.remove_attribute)){var b=a(this).parent().parent();b.is(".taxonomy")?(b.find("select, input[type=text]").val(""),b.hide(),a("select.attribute_taxonomy").find('option[value="'+b.data("taxonomy")+'"]').removeAttr("disabled")):(b.find("select, input[type=text]").val(""),b.hide(),c())}return!1}),a(".product_attributes").sortable({items:".woocommerce_attribute",cursor:"move",axis:"y",handle:"h3",scrollSensitivity:40,forcePlaceholderSize:!0,helper:"clone",opacity:.65,placeholder:"wc-metabox-sortable-placeholder",start:function(a,b){b.item.css("background-color","#f6f6f6")},stop:function(a,b){b.item.removeAttr("style"),c()}}),a(".product_attributes").on("click","button.add_new_attribute",function(){a(".product_attributes").block({message:null,overlayCSS:{background:"#fff",opacity:.6}});var b=a(this).closest(".woocommerce_attribute"),c=b.data("taxonomy"),d=window.prompt(woocommerce_admin_meta_boxes.new_attribute_prompt);if(d){var e={action:"woocommerce_add_new_attribute",taxonomy:c,term:d,security:woocommerce_admin_meta_boxes.add_attribute_nonce};a.post(woocommerce_admin_meta_boxes.ajax_url,e,function(c){c.error?window.alert(c.error):c.slug&&(b.find("select.attribute_values").append('"),b.find("select.attribute_values").change()),a(".product_attributes").unblock()})}else a(".product_attributes").unblock();return!1}),a(".save_attributes").on("click",function(){a("#woocommerce-product-data").block({message:null,overlayCSS:{background:"#fff",opacity:.6}});var b={post_id:woocommerce_admin_meta_boxes.post_id,data:a(".product_attributes").find("input, select, textarea").serialize(),action:"woocommerce_save_attributes",security:woocommerce_admin_meta_boxes.save_attributes_nonce};a.post(woocommerce_admin_meta_boxes.ajax_url,b,function(){var b=window.location.toString();b=b.replace("post-new.php?","post.php?post="+woocommerce_admin_meta_boxes.post_id+"&action=edit&"),a("#variable_product_options").load(b+" #variable_product_options_inner",function(){a("#variable_product_options").trigger("reload")})})});var e,f;jQuery(document.body).on("click",".upload_file_button",function(b){var c=a(this);if(f=c.closest("tr").find("td.file_url input"),b.preventDefault(),e)return void e.open();var d=[new wp.media.controller.Library({library:wp.media.query(),multiple:!0,title:c.data("choose"),priority:20,filterable:"uploaded"})];e=wp.media.frames.downloadable_file=wp.media({title:c.data("choose"),library:{type:""},button:{text:c.data("update")},multiple:!0,states:d}),e.on("select",function(){var a="",b=e.state().get("selection");b.map(function(b){b=b.toJSON(),b.url&&(a=b.url)}),f.val(a).change()}),e.on("ready",function(){e.uploader.options.uploader.params={type:"downloadable_product"}}),e.open()}),jQuery(".downloadable_files tbody").sortable({items:"tr",cursor:"move",axis:"y",handle:"td.sort",scrollSensitivity:40,forcePlaceholderSize:!0,helper:"clone",opacity:.65});var g,h=a("#product_image_gallery"),i=a("#product_images_container").find("ul.product_images");jQuery(".add_product_images").on("click","a",function(b){var c=a(this);return b.preventDefault(),g?void g.open():(g=wp.media.frames.product_gallery=wp.media({title:c.data("choose"),button:{text:c.data("update")},states:[new wp.media.controller.Library({title:c.data("choose"),filterable:"all",multiple:!0})]}),g.on("select",function(){var a=g.state().get("selection"),b=h.val();a.map(function(a){if(a=a.toJSON(),a.id){b=b?b+","+a.id:a.id;var d=a.sizes&&a.sizes.thumbnail?a.sizes.thumbnail.url:a.url;i.append('
  • ")}}),h.val(b)}),void g.open())}),i.sortable({items:"li.image",cursor:"move",scrollSensitivity:40,forcePlaceholderSize:!0,forceHelperSize:!1,helper:"clone",opacity:.65,placeholder:"wc-metabox-sortable-placeholder",start:function(a,b){b.item.css("background-color","#f6f6f6")},stop:function(a,b){b.item.removeAttr("style")},update:function(){var b="";a("#product_images_container").find("ul li.image").css("cursor","default").each(function(){var a=jQuery(this).attr("data-attachment_id");b=b+a+","}),h.val(b)}}),a("#product_images_container").on("click","a.delete",function(){a(this).closest("li.image").remove();var b="";return a("#product_images_container").find("ul li.image").css("cursor","default").each(function(){var a=jQuery(this).attr("data-attachment_id");b=b+a+","}),h.val(b),a("#tiptip_holder").removeAttr("style"),a("#tiptip_arrow").removeAttr("style"),!1})}); \ No newline at end of file +jQuery(function(a){function b(){var b=a("select#product-type").val(),c=a("input#_virtual:checked").length,d=a("input#_downloadable:checked").length,e=".hide_if_downloadable, .hide_if_virtual",f=".show_if_downloadable, .show_if_virtual";a.each(woocommerce_admin_meta_boxes.product_types,function(a,b){e=e+", .hide_if_"+b,f=f+", .show_if_"+b}),a(e).show(),a(f).hide(),d&&a(".show_if_downloadable").show(),c&&a(".show_if_virtual").show(),a(".show_if_"+b).show(),d&&a(".hide_if_downloadable").hide(),c&&a(".hide_if_virtual").hide(),a(".hide_if_"+b).hide(),a("input#_manage_stock").change(),a(".woocommerce_options_panel").each(function(){var b=a(this).children(".options_group");if(0!==b.length){var c=b.filter(function(){return"none"===a(this).css("display")});if(c.length===b.length){var d=a(this).prop("id");a(".product_data_tabs").find('li a[href="#'+d+'"]').parent().hide()}}})}function c(){a(".product_attributes .woocommerce_attribute").each(function(b,c){a(".attribute_position",c).val(parseInt(a(c).index(".product_attributes .woocommerce_attribute"),10))})}a(function(){a('[id$="-all"] > ul.categorychecklist').each(function(){var b=a(this),c=b.find(":checked").first();if(c.length){var d=b.find("input").position().top,e=c.position().top;b.closest(".tabs-panel").scrollTop(e-d+5)}})}),a("#upsell_product_data").bind("keypress",function(a){if(13===a.keyCode)return!1}),a(".type_box").appendTo("#woocommerce-product-data .hndle span"),a(function(){a("#woocommerce-product-data").find(".hndle").unbind("click.postboxes"),a("#woocommerce-product-data").on("click",".hndle",function(b){a(b.target).filter("input, option, label, select").length||a("#woocommerce-product-data").toggleClass("closed")})}),a("#catalog-visibility").find(".edit-catalog-visibility").click(function(){return a("#catalog-visibility-select").is(":hidden")&&(a("#catalog-visibility-select").slideDown("fast"),a(this).hide()),!1}),a("#catalog-visibility").find(".save-post-visibility").click(function(){a("#catalog-visibility-select").slideUp("fast"),a("#catalog-visibility").find(".edit-catalog-visibility").show();var b=a("input[name=_visibility]:checked").attr("data-label");return a("input[name=_featured]").is(":checked")&&(b=b+", "+woocommerce_admin_meta_boxes.featured_label,a("input[name=_featured]").attr("checked","checked")),a("#catalog-visibility-display").text(b),!1}),a("#catalog-visibility").find(".cancel-post-visibility").click(function(){a("#catalog-visibility-select").slideUp("fast"),a("#catalog-visibility").find(".edit-catalog-visibility").show();var b=a("#current_visibility").val(),c=a("#current_featured").val();a("input[name=_visibility]").removeAttr("checked"),a("input[name=_visibility][value="+b+"]").attr("checked","checked");var d=a("input[name=_visibility]:checked").attr("data-label");return"yes"===c?(d=d+", "+woocommerce_admin_meta_boxes.featured_label,a("input[name=_featured]").attr("checked","checked")):a("input[name=_featured]").removeAttr("checked"),a("#catalog-visibility-display").text(d),!1}),a("select#product-type").change(function(){var c=a(this).val();"variable"===c?(a("input#_manage_stock").change(),a("input#_downloadable").prop("checked",!1),a("input#_virtual").removeAttr("checked")):"grouped"===c?(a("input#_downloadable").prop("checked",!1),a("input#_virtual").removeAttr("checked")):"external"===c&&(a("input#_downloadable").prop("checked",!1),a("input#_virtual").removeAttr("checked")),b(),a("ul.wc-tabs li:visible").eq(0).find("a").click(),a(document.body).trigger("woocommerce-product-type-change",c,a(this))}).change(),a("input#_downloadable, input#_virtual").change(function(){b()}),a(".sale_price_dates_fields").each(function(){var b=a(this),c=!1,d=b.closest("div, table");b.find("input").each(function(){""!==a(this).val()&&(c=!0)}),c?(d.find(".sale_schedule").hide(),d.find(".sale_price_dates_fields").show()):(d.find(".sale_schedule").show(),d.find(".sale_price_dates_fields").hide())}),a("#woocommerce-product-data").on("click",".sale_schedule",function(){var b=a(this).closest("div, table");return a(this).hide(),b.find(".cancel_sale_schedule").show(),b.find(".sale_price_dates_fields").show(),!1}),a("#woocommerce-product-data").on("click",".cancel_sale_schedule",function(){var b=a(this).closest("div, table");return a(this).hide(),b.find(".sale_schedule").show(),b.find(".sale_price_dates_fields").hide(),b.find(".sale_price_dates_fields").find("input").val(""),!1}),a("#woocommerce-product-data").on("click",".downloadable_files a.insert",function(){return a(this).closest(".downloadable_files").find("tbody").append(a(this).data("row")),!1}),a("#woocommerce-product-data").on("click",".downloadable_files a.delete",function(){return a(this).closest("tr").remove(),!1}),a("input#_manage_stock").change(function(){a(this).is(":checked")?a("div.stock_fields").show():a("div.stock_fields").hide()}).change(),a(".sale_price_dates_fields").each(function(){var b=a(this).find("input").datepicker({defaultDate:"",dateFormat:"yy-mm-dd",numberOfMonths:1,showButtonPanel:!0,onSelect:function(c){var d=a(this).is("#_sale_price_dates_from, .sale_price_dates_from")?"minDate":"maxDate",e=a(this).data("datepicker"),f=a.datepicker.parseDate(e.settings.dateFormat||a.datepicker._defaults.dateFormat,c,e.settings);b.not(this).datepicker("option",d,f)}})});var d=a(".product_attributes").find(".woocommerce_attribute").get();d.sort(function(b,c){var d=parseInt(a(b).attr("rel"),10),e=parseInt(a(c).attr("rel"),10);return de?1:0}),a(d).each(function(b,c){a(".product_attributes").append(c)}),a(".product_attributes .woocommerce_attribute").each(function(b,c){"none"!==a(c).css("display")&&a(c).is(".taxonomy")&&a("select.attribute_taxonomy").find('option[value="'+a(c).data("taxonomy")+'"]').attr("disabled","disabled")}),a("button.add_attribute").on("click",function(){var b=a(".product_attributes .woocommerce_attribute").length,d=a("select.attribute_taxonomy").val(),e=a(this).closest("#product_attributes"),f=e.find(".product_attributes"),g=a("select#product-type").val(),h={action:"woocommerce_add_attribute",taxonomy:d,i:b,security:woocommerce_admin_meta_boxes.add_attribute_nonce};return e.block({message:null,overlayCSS:{background:"#fff",opacity:.6}}),a.post(woocommerce_admin_meta_boxes.ajax_url,h,function(b){f.append(b),"variable"!==g&&f.find(".enable_variation").hide(),a(document.body).trigger("wc-enhanced-select-init"),c(),e.unblock(),a(document.body).trigger("woocommerce_added_attribute")}),d&&(a("select.attribute_taxonomy").find('option[value="'+d+'"]').attr("disabled","disabled"),a("select.attribute_taxonomy").val("")),!1}),a(".product_attributes").on("blur","input.attribute_name",function(){a(this).closest(".woocommerce_attribute").find("strong.attribute_name").text(a(this).val())}),a(".product_attributes").on("click","button.select_all_attributes",function(){return a(this).closest("td").find("select option").attr("selected","selected"),a(this).closest("td").find("select").change(),!1}),a(".product_attributes").on("click","button.select_no_attributes",function(){return a(this).closest("td").find("select option").removeAttr("selected"),a(this).closest("td").find("select").change(),!1}),a(".product_attributes").on("click",".remove_row",function(){if(window.confirm(woocommerce_admin_meta_boxes.remove_attribute)){var b=a(this).parent().parent();b.is(".taxonomy")?(b.find("select, input[type=text]").val(""),b.hide(),a("select.attribute_taxonomy").find('option[value="'+b.data("taxonomy")+'"]').removeAttr("disabled")):(b.find("select, input[type=text]").val(""),b.hide(),c())}return!1}),a(".product_attributes").sortable({items:".woocommerce_attribute",cursor:"move",axis:"y",handle:"h3",scrollSensitivity:40,forcePlaceholderSize:!0,helper:"clone",opacity:.65,placeholder:"wc-metabox-sortable-placeholder",start:function(a,b){b.item.css("background-color","#f6f6f6")},stop:function(a,b){b.item.removeAttr("style"),c()}}),a(".product_attributes").on("click","button.add_new_attribute",function(){a(".product_attributes").block({message:null,overlayCSS:{background:"#fff",opacity:.6}});var b=a(this).closest(".woocommerce_attribute"),c=b.data("taxonomy"),d=window.prompt(woocommerce_admin_meta_boxes.new_attribute_prompt);if(d){var e={action:"woocommerce_add_new_attribute",taxonomy:c,term:d,security:woocommerce_admin_meta_boxes.add_attribute_nonce};a.post(woocommerce_admin_meta_boxes.ajax_url,e,function(c){c.error?window.alert(c.error):c.slug&&(b.find("select.attribute_values").append('"),b.find("select.attribute_values").change()),a(".product_attributes").unblock()})}else a(".product_attributes").unblock();return!1}),a(".save_attributes").on("click",function(){a("#woocommerce-product-data").block({message:null,overlayCSS:{background:"#fff",opacity:.6}});var b={post_id:woocommerce_admin_meta_boxes.post_id,product_type:a("#product-type").val(),data:a(".product_attributes").find("input, select, textarea").serialize(),action:"woocommerce_save_attributes",security:woocommerce_admin_meta_boxes.save_attributes_nonce};a.post(woocommerce_admin_meta_boxes.ajax_url,b,function(){var b=window.location.toString();b=b.replace("post-new.php?","post.php?post="+woocommerce_admin_meta_boxes.post_id+"&action=edit&"),a("#variable_product_options").load(b+" #variable_product_options_inner",function(){a("#variable_product_options").trigger("reload")})})});var e,f;a(document.body).on("click",".upload_file_button",function(b){var c=a(this);if(f=c.closest("tr").find("td.file_url input"),b.preventDefault(),e)return void e.open();var d=[new wp.media.controller.Library({library:wp.media.query(),multiple:!0,title:c.data("choose"),priority:20,filterable:"uploaded"})];e=wp.media.frames.downloadable_file=wp.media({title:c.data("choose"),library:{type:""},button:{text:c.data("update")},multiple:!0,states:d}),e.on("select",function(){var a="",b=e.state().get("selection");b.map(function(b){b=b.toJSON(),b.url&&(a=b.url)}),f.val(a).change()}),e.on("ready",function(){e.uploader.options.uploader.params={type:"downloadable_product"}}),e.open()}),a(".downloadable_files tbody").sortable({items:"tr",cursor:"move",axis:"y",handle:"td.sort",scrollSensitivity:40,forcePlaceholderSize:!0,helper:"clone",opacity:.65});var g,h=a("#product_image_gallery"),i=a("#product_images_container").find("ul.product_images");a(".add_product_images").on("click","a",function(b){var c=a(this);return b.preventDefault(),g?void g.open():(g=wp.media.frames.product_gallery=wp.media({title:c.data("choose"),button:{text:c.data("update")},states:[new wp.media.controller.Library({title:c.data("choose"),filterable:"all",multiple:!0})]}),g.on("select",function(){var a=g.state().get("selection"),b=h.val();a.map(function(a){if(a=a.toJSON(),a.id){b=b?b+","+a.id:a.id;var d=a.sizes&&a.sizes.thumbnail?a.sizes.thumbnail.url:a.url;i.append('
  • ")}}),h.val(b)}),void g.open())}),i.sortable({items:"li.image",cursor:"move",scrollSensitivity:40,forcePlaceholderSize:!0,forceHelperSize:!1,helper:"clone",opacity:.65,placeholder:"wc-metabox-sortable-placeholder",start:function(a,b){b.item.css("background-color","#f6f6f6")},stop:function(a,b){b.item.removeAttr("style")},update:function(){var b="";a("#product_images_container").find("ul li.image").css("cursor","default").each(function(){var c=a(this).attr("data-attachment_id");b=b+c+","}),h.val(b)}}),a("#product_images_container").on("click","a.delete",function(){a(this).closest("li.image").remove();var b="";return a("#product_images_container").find("ul li.image").css("cursor","default").each(function(){var c=a(this).attr("data-attachment_id");b=b+c+","}),h.val(b),a("#tiptip_holder").removeAttr("style"),a("#tiptip_arrow").removeAttr("style"),!1})}); \ No newline at end of file diff --git a/assets/js/admin/meta-boxes.js b/assets/js/admin/meta-boxes.js index bb5624a5781..39c35e4da06 100644 --- a/assets/js/admin/meta-boxes.js +++ b/assets/js/admin/meta-boxes.js @@ -20,7 +20,7 @@ jQuery( function ( $ ) { var code = event.keyCode || event.which; // Tab key - if ( code === '9' && $( '#woocommerce-coupon-description' ).size() > 0 ) { + if ( code === '9' && $( '#woocommerce-coupon-description' ).length > 0 ) { event.stopPropagation(); $( '#woocommerce-coupon-description' ).focus(); return false; diff --git a/assets/js/admin/meta-boxes.min.js b/assets/js/admin/meta-boxes.min.js index cf4df08995b..69d1ef2aa6e 100644 --- a/assets/js/admin/meta-boxes.min.js +++ b/assets/js/admin/meta-boxes.min.js @@ -1 +1 @@ -jQuery(function(a){function b(){a("#tiptip_holder").removeAttr("style"),a("#tiptip_arrow").removeAttr("style"),a(".tips").tipTip({attribute:"data-tip",fadeIn:50,fadeOut:50,delay:200})}b(),a("#titlediv").find("#title").keyup(function(b){var c=b.keyCode||b.which;return"9"===c&&a("#woocommerce-coupon-description").size()>0?(b.stopPropagation(),a("#woocommerce-coupon-description").focus(),!1):void 0}),a(".wc-metaboxes-wrapper").on("click",".wc-metabox > h3",function(){a(this).parent(".wc-metabox").toggleClass("closed").toggleClass("open")}),a(document.body).on("wc-init-tabbed-panels",function(){a("ul.wc-tabs").show(),a("ul.wc-tabs a").click(function(b){b.preventDefault();var c=a(this).closest("div.panel-wrap");a("ul.wc-tabs li",c).removeClass("active"),a(this).parent().addClass("active"),a("div.panel",c).hide(),a(a(this).attr("href")).show()}),a("div.panel-wrap").each(function(){a(this).find("ul.wc-tabs li").eq(0).find("a").click()})}).trigger("wc-init-tabbed-panels"),a(document.body).on("wc-init-datepickers",function(){a(".date-picker-field, .date-picker").datepicker({dateFormat:"yy-mm-dd",numberOfMonths:1,showButtonPanel:!0})}).trigger("wc-init-datepickers"),a(".wc-metaboxes-wrapper").on("click",".wc-metabox h3",function(b){a(b.target).filter(":input, option, .sort").length||a(this).next(".wc-metabox-content").stop().slideToggle()}).on("click",".expand_all",function(){return a(this).closest(".wc-metaboxes-wrapper").find(".wc-metabox > .wc-metabox-content").show(),!1}).on("click",".close_all",function(){return a(this).closest(".wc-metaboxes-wrapper").find(".wc-metabox > .wc-metabox-content").hide(),!1}),a(".wc-metabox.closed").each(function(){a(this).find(".wc-metabox-content").hide()})}); \ No newline at end of file +jQuery(function(a){function b(){a("#tiptip_holder").removeAttr("style"),a("#tiptip_arrow").removeAttr("style"),a(".tips").tipTip({attribute:"data-tip",fadeIn:50,fadeOut:50,delay:200})}b(),a("#titlediv").find("#title").keyup(function(b){var c=b.keyCode||b.which;if("9"===c&&a("#woocommerce-coupon-description").length>0)return b.stopPropagation(),a("#woocommerce-coupon-description").focus(),!1}),a(".wc-metaboxes-wrapper").on("click",".wc-metabox > h3",function(){a(this).parent(".wc-metabox").toggleClass("closed").toggleClass("open")}),a(document.body).on("wc-init-tabbed-panels",function(){a("ul.wc-tabs").show(),a("ul.wc-tabs a").click(function(b){b.preventDefault();var c=a(this).closest("div.panel-wrap");a("ul.wc-tabs li",c).removeClass("active"),a(this).parent().addClass("active"),a("div.panel",c).hide(),a(a(this).attr("href")).show()}),a("div.panel-wrap").each(function(){a(this).find("ul.wc-tabs li").eq(0).find("a").click()})}).trigger("wc-init-tabbed-panels"),a(document.body).on("wc-init-datepickers",function(){a(".date-picker-field, .date-picker").datepicker({dateFormat:"yy-mm-dd",numberOfMonths:1,showButtonPanel:!0})}).trigger("wc-init-datepickers"),a(".wc-metaboxes-wrapper").on("click",".wc-metabox h3",function(b){a(b.target).filter(":input, option, .sort").length||a(this).next(".wc-metabox-content").stop().slideToggle()}).on("click",".expand_all",function(){return a(this).closest(".wc-metaboxes-wrapper").find(".wc-metabox > .wc-metabox-content").show(),!1}).on("click",".close_all",function(){return a(this).closest(".wc-metaboxes-wrapper").find(".wc-metabox > .wc-metabox-content").hide(),!1}),a(".wc-metabox.closed").each(function(){a(this).find(".wc-metabox-content").hide()})}); \ No newline at end of file diff --git a/assets/js/admin/order-backbone-modal.min.js b/assets/js/admin/order-backbone-modal.min.js deleted file mode 100644 index a3721ff1122..00000000000 --- a/assets/js/admin/order-backbone-modal.min.js +++ /dev/null @@ -1 +0,0 @@ -!function(a,b,c){"use strict";a.fn.WCBackboneModal=function(b){return this.each(function(){new a.WCBackboneModal(a(this),b)})},a.WCBackboneModal=function(b,c){var d=a.extend({},a.WCBackboneModal.defaultOptions,c);d.template&&new a.WCBackboneModal.View({target:d.template,string:d.variable})},a.WCBackboneModal.defaultOptions={template:"",variable:{}},a.WCBackboneModal.View=b.View.extend({tagName:"div",id:"wc-backbone-modal-dialog",_target:void 0,_string:void 0,events:{"click .modal-close":"closeButton","click #btn-ok":"addButton","touchstart #btn-ok":"addButton",keydown:"keyboardActions"},initialize:function(a){this._target=a.target,this._string=a.string,c.bindAll(this,"render"),this.render()},render:function(){var b=wp.template(this._target);this.$el.attr("tabindex","0").append(b(this._string)),a(document.body).css({overflow:"hidden"}).append(this.$el);var c=a(".wc-backbone-modal-content").find("article"),d=c.height()<90?90:c.height(),e=a(window).height()-200;e>400&&(e=400),d>e?c.css({overflow:"auto",height:e+"px"}):c.css({overflow:"visible",height:d>90?"auto":d+"px"}),a(".wc-backbone-modal-content").css({"margin-top":"-"+a(".wc-backbone-modal-content").height()/2+"px","margin-left":"-"+a(".wc-backbone-modal-content").width()/2+"px"}),a(document.body).trigger("wc_backbone_modal_loaded",this._target)},closeButton:function(b){b.preventDefault(),a(document.body).trigger("wc_backbone_modal_before_remove",this._target),this.undelegateEvents(),a(document).off("focusin"),a(document.body).css({overflow:"auto"}),this.remove(),a(document.body).trigger("wc_backbone_modal_removed",this._target)},addButton:function(b){a(document.body).trigger("wc_backbone_modal_response",[this._target,this.getFormData()]),this.closeButton(b)},getFormData:function(){var b={};return a(document.body).trigger("wc_backbone_modal_before_update",this._target),a.each(a("form",this.$el).serializeArray(),function(c,d){b.hasOwnProperty(d.name)?(b[d.name]=a.makeArray(b[d.name]),b[d.name].push(d.value)):b[d.name]=d.value}),b},keyboardActions:function(a){var b=a.keyCode||a.which;13!==b||a.target.tagName&&("input"===a.target.tagName.toLowerCase()||"textarea"===a.target.tagName.toLowerCase())||this.addButton(a),27===b&&this.closeButton(a)}})}(jQuery,Backbone,_); \ No newline at end of file diff --git a/assets/js/admin/product-ordering.js b/assets/js/admin/product-ordering.js index f855db832eb..9c2075eb5cd 100644 --- a/assets/js/admin/product-ordering.js +++ b/assets/js/admin/product-ordering.js @@ -1,7 +1,7 @@ /*global ajaxurl */ /** - * Based on Simple Page Ordering by 10up (http://wordpress.org/extend/plugins/simple-page-ordering/) + * Based on Simple Page Ordering by 10up (https://wordpress.org/plugins/simple-page-ordering/) * * Modified - products have no children (non hierarchical) */ @@ -21,17 +21,7 @@ jQuery( function( $ ) { return ui; }, start: function( event, ui ) { - ui.placeholder.children().each( function() { - var $original = ui.item.children().eq( ui.placeholder.children().index( this ) ), - $this = $( this ); - - $.each( $original[0].attributes, function( k, attr ) { - $this.attr( attr.name, attr.value ); - }); - }); - if ( ! ui.item.hasClass( 'alternate' ) ) { - ui.item.css( 'background-color', '#ffffff' ); - } + ui.item.css( 'background-color', '#ffffff' ); ui.item.children( 'td, th' ).css( 'border-bottom-width', '0' ); ui.item.css( 'outline', '1px solid #dfdfdf' ); }, diff --git a/assets/js/admin/product-ordering.min.js b/assets/js/admin/product-ordering.min.js index 4cef2c48d92..de12cba6afa 100644 --- a/assets/js/admin/product-ordering.min.js +++ b/assets/js/admin/product-ordering.min.js @@ -1 +1 @@ -jQuery(function(a){a("table.widefat tbody th, table.widefat tbody td").css("cursor","move"),a("table.widefat tbody").sortable({items:"tr:not(.inline-edit-row)",cursor:"move",axis:"y",containment:"table.widefat",scrollSensitivity:40,helper:function(b,c){return c.each(function(){a(this).width(a(this).width())}),c},start:function(b,c){c.placeholder.children().each(function(){var b=c.item.children().eq(c.placeholder.children().index(this)),d=a(this);a.each(b[0].attributes,function(a,b){d.attr(b.name,b.value)})}),c.item.hasClass("alternate")||c.item.css("background-color","#ffffff"),c.item.children("td, th").css("border-bottom-width","0"),c.item.css("outline","1px solid #dfdfdf")},stop:function(a,b){b.item.removeAttr("style"),b.item.children("td,th").css("border-bottom-width","1px")},update:function(b,c){a("table.widefat tbody th, table.widefat tbody td").css("cursor","default"),a("table.widefat tbody").sortable("disable");var d=c.item.find(".check-column input").val(),e=c.item.prev().find(".check-column input").val(),f=c.item.next().find(".check-column input").val();c.item.find(".check-column input").hide().after('processing'),a.post(ajaxurl,{action:"woocommerce_product_ordering",id:d,previd:e,nextid:f},function(b){a.each(b,function(b,c){a("#inline_"+b+" .menu_order").html(c)}),c.item.find(".check-column input").show().siblings("img").remove(),a("table.widefat tbody th, table.widefat tbody td").css("cursor","move"),a("table.widefat tbody").sortable("enable")}),a("table.widefat tbody tr").each(function(){var b=a("table.widefat tbody tr").index(this);b%2===0?a(this).addClass("alternate"):a(this).removeClass("alternate")})}})}); \ No newline at end of file +jQuery(function(a){a("table.widefat tbody th, table.widefat tbody td").css("cursor","move"),a("table.widefat tbody").sortable({items:"tr:not(.inline-edit-row)",cursor:"move",axis:"y",containment:"table.widefat",scrollSensitivity:40,helper:function(b,c){return c.each(function(){a(this).width(a(this).width())}),c},start:function(a,b){b.item.css("background-color","#ffffff"),b.item.children("td, th").css("border-bottom-width","0"),b.item.css("outline","1px solid #dfdfdf")},stop:function(a,b){b.item.removeAttr("style"),b.item.children("td,th").css("border-bottom-width","1px")},update:function(b,c){a("table.widefat tbody th, table.widefat tbody td").css("cursor","default"),a("table.widefat tbody").sortable("disable");var d=c.item.find(".check-column input").val(),e=c.item.prev().find(".check-column input").val(),f=c.item.next().find(".check-column input").val();c.item.find(".check-column input").hide().after('processing'),a.post(ajaxurl,{action:"woocommerce_product_ordering",id:d,previd:e,nextid:f},function(b){a.each(b,function(b,c){a("#inline_"+b+" .menu_order").html(c)}),c.item.find(".check-column input").show().siblings("img").remove(),a("table.widefat tbody th, table.widefat tbody td").css("cursor","move"),a("table.widefat tbody").sortable("enable")}),a("table.widefat tbody tr").each(function(){var b=a("table.widefat tbody tr").index(this);b%2===0?a(this).addClass("alternate"):a(this).removeClass("alternate")})}})}); \ No newline at end of file diff --git a/assets/js/admin/quick-edit.js b/assets/js/admin/quick-edit.js index ca1dbfaf630..21c8964ef02 100644 --- a/assets/js/admin/quick-edit.js +++ b/assets/js/admin/quick-edit.js @@ -1,4 +1,4 @@ -/*global ajaxurl, inlineEditPost, inlineEditL10n */ +/*global inlineEditPost, woocommerce_admin */ jQuery(function( $ ) { $( '#the-list' ).on( 'click', '.editinline', function() { @@ -28,9 +28,12 @@ jQuery(function( $ ) { tax_class = $wc_inline_data.find( '.tax_class' ).text(), backorders = $wc_inline_data.find( '.backorders' ).text(); + var formatted_regular_price = regular_price.replace('.', woocommerce_admin.mon_decimal_point ), + formatted_sale_price = sale_price.replace('.', woocommerce_admin.mon_decimal_point ); + $( 'input[name="_sku"]', '.inline-edit-row' ).val( sku ); - $( 'input[name="_regular_price"]', '.inline-edit-row' ).val( regular_price ); - $( 'input[name="_sale_price"]', '.inline-edit-row' ).val( sale_price ); + $( 'input[name="_regular_price"]', '.inline-edit-row' ).val( formatted_regular_price ); + $( 'input[name="_sale_price"]', '.inline-edit-row' ).val( formatted_sale_price ); $( 'input[name="_weight"]', '.inline-edit-row' ).val( weight ); $( 'input[name="_length"]', '.inline-edit-row' ).val( length ); $( 'input[name="_width"]', '.inline-edit-row' ).val( width ); @@ -101,10 +104,6 @@ jQuery(function( $ ) { $( 'input.text', '.inline-edit-row' ).val( '' ); $( '#woocommerce-fields' ).find( 'select' ).prop( 'selectedIndex', 0 ); $( '#woocommerce-fields-bulk' ).find( '.inline-edit-group .change-input' ).hide(); - - // Autosuggest product tags on bulk edit - var tax = 'product_tag'; - $( 'tr.inline-editor textarea[name="tax_input[' + tax + ']"]' ).suggest( ajaxurl + '?action=ajax-tag-search&tax=' + tax, { delay: 500, minchars: 2, multiple: true, multipleSep: inlineEditL10n.comma } ); }); $( '#wpbody' ).on( 'change', '#woocommerce-fields-bulk .inline-edit-group .change_to', function() { diff --git a/assets/js/admin/quick-edit.min.js b/assets/js/admin/quick-edit.min.js index 549395d247c..affe9fc31a9 100644 --- a/assets/js/admin/quick-edit.min.js +++ b/assets/js/admin/quick-edit.min.js @@ -1 +1 @@ -jQuery(function(a){a("#the-list").on("click",".editinline",function(){inlineEditPost.revert();var b=a(this).closest("tr").attr("id");b=b.replace("post-","");var c=a("#woocommerce_inline_"+b),d=c.find(".sku").text(),e=c.find(".regular_price").text(),f=c.find(".sale_price ").text(),g=c.find(".weight").text(),h=c.find(".length").text(),i=c.find(".width").text(),j=c.find(".height").text(),k=c.find(".shipping_class").text(),l=c.find(".visibility").text(),m=c.find(".stock_status").text(),n=c.find(".stock").text(),o=c.find(".featured").text(),p=c.find(".manage_stock").text(),q=c.find(".menu_order").text(),r=c.find(".tax_status").text(),s=c.find(".tax_class").text(),t=c.find(".backorders").text();a('input[name="_sku"]',".inline-edit-row").val(d),a('input[name="_regular_price"]',".inline-edit-row").val(e),a('input[name="_sale_price"]',".inline-edit-row").val(f),a('input[name="_weight"]',".inline-edit-row").val(g),a('input[name="_length"]',".inline-edit-row").val(h),a('input[name="_width"]',".inline-edit-row").val(i),a('input[name="_height"]',".inline-edit-row").val(j),a('select[name="_shipping_class"] option:selected',".inline-edit-row").attr("selected",!1).change(),a('select[name="_shipping_class"] option[value="'+k+'"]').attr("selected","selected").change(),a('input[name="_stock"]',".inline-edit-row").val(n),a('input[name="menu_order"]',".inline-edit-row").val(q),a('select[name="_tax_status"] option, select[name="_tax_class"] option, select[name="_visibility"] option, select[name="_stock_status"] option, select[name="_backorders"] option').removeAttr("selected"),a('select[name="_tax_status"] option[value="'+r+'"]',".inline-edit-row").attr("selected","selected"),a('select[name="_tax_class"] option[value="'+s+'"]',".inline-edit-row").attr("selected","selected"),a('select[name="_visibility"] option[value="'+l+'"]',".inline-edit-row").attr("selected","selected"),a('select[name="_stock_status"] option[value="'+m+'"]',".inline-edit-row").attr("selected","selected"),a('select[name="_backorders"] option[value="'+t+'"]',".inline-edit-row").attr("selected","selected"),"yes"===o?a('input[name="_featured"]',".inline-edit-row").attr("checked","checked"):a('input[name="_featured"]',".inline-edit-row").removeAttr("checked"),"yes"===p?(a(".stock_qty_field",".inline-edit-row").show().removeAttr("style"),a('input[name="_manage_stock"]',".inline-edit-row").attr("checked","checked")):(a(".stock_qty_field",".inline-edit-row").hide(),a('input[name="_manage_stock"]',".inline-edit-row").removeAttr("checked"));var u=c.find(".product_type").text(),v=c.find(".product_is_virtual").text();"simple"===u||"external"===u?a(".price_fields",".inline-edit-row").show().removeAttr("style"):a(".price_fields",".inline-edit-row").hide(),"yes"===v?a(".dimension_fields",".inline-edit-row").hide():a(".dimension_fields",".inline-edit-row").show().removeAttr("style"),"grouped"===u?a(".stock_fields",".inline-edit-row").hide():a(".stock_fields",".inline-edit-row").show().removeAttr("style")}),a("#the-list").on("change",'.inline-edit-row input[name="_manage_stock"]',function(){a(this).is(":checked")?a(".stock_qty_field",".inline-edit-row").show().removeAttr("style"):a(".stock_qty_field",".inline-edit-row").hide()}),a("#wpbody").on("click","#doaction, #doaction2",function(){a("input.text",".inline-edit-row").val(""),a("#woocommerce-fields").find("select").prop("selectedIndex",0),a("#woocommerce-fields-bulk").find(".inline-edit-group .change-input").hide();var b="product_tag";a('tr.inline-editor textarea[name="tax_input['+b+']"]').suggest(ajaxurl+"?action=ajax-tag-search&tax="+b,{delay:500,minchars:2,multiple:!0,multipleSep:inlineEditL10n.comma})}),a("#wpbody").on("change","#woocommerce-fields-bulk .inline-edit-group .change_to",function(){0' + contents + '' ).css( { top: y - 16, - left: x + 20 + left: x + 20 }).appendTo( 'body' ).fadeIn( 200 ); } @@ -110,6 +110,7 @@ jQuery(function( $ ) { defaultDate: '', dateFormat: 'yy-mm-dd', numberOfMonths: 1, + minDate: '-20Y', maxDate: '+0D', showButtonPanel: true, showOn: 'focus', @@ -136,26 +137,27 @@ jQuery(function( $ ) { exclude_series = exclude_series.split( ',' ); var xaxes_label = $( this ).data( 'xaxes' ); var groupby = $( this ) .data( 'groupby' ); + var index_type = $( this ).data( 'index_type' ); var export_format = $( this ).data( 'export' ); var csv_data = 'data:application/csv;charset=utf-8,'; var s, series_data, d; if ( 'table' === export_format ) { - $( this ).closest( 'div' ).find( 'thead tr,tbody tr' ).each( function() { + $( this ).offsetParent().find( 'thead tr,tbody tr' ).each( function() { $( this ).find( 'th, td' ).each( function() { var value = $( this ).text(); - value = value.replace( '[?]', '' ); + value = value.replace( '[?]', '' ).replace( '#', '' ); csv_data += '"' + value + '"' + ','; }); csv_data = csv_data.substring( 0, csv_data.length - 1 ); csv_data += '\n'; }); - $( this ).closest( 'div' ).find( 'tfoot tr' ).each( function() { + $( this ).offsetParent().find( 'tfoot tr' ).each( function() { $( this ).find( 'th, td' ).each( function() { var value = $( this ).text(); - value = value.replace( '[?]', '' ); + value = value.replace( '[?]', '' ).replace( '#', '' ); csv_data += '"' + value + '"' + ','; if ( $( this ).attr( 'colspan' ) > 0 ) { for ( i = 1; i < $(this).attr('colspan'); i++ ) { @@ -175,7 +177,7 @@ jQuery(function( $ ) { var the_series = window.main_chart.getData(); var series = []; - csv_data += xaxes_label + ','; + csv_data += '"' + xaxes_label + '",'; $.each( the_series, function( index, value ) { if ( ! exclude_series || $.inArray( index.toString(), exclude_series ) === -1 ) { @@ -185,7 +187,7 @@ jQuery(function( $ ) { // CSV Headers for ( s = 0; s < series.length; ++s ) { - csv_data += series[s].label + ','; + csv_data += '"' + series[s].label + '",'; } csv_data = csv_data.substring( 0, csv_data.length - 1 ); @@ -217,10 +219,14 @@ jQuery(function( $ ) { $.each( xaxis, function( index, value ) { var date = new Date( parseInt( index, 10 ) ); - if ( groupby === 'day' ) { - csv_data += date.getUTCFullYear() + '-' + parseInt( date.getUTCMonth() + 1, 10 ) + '-' + date.getUTCDate() + ','; + if ( 'none' === index_type ) { + csv_data += '"' + index + '",'; } else { - csv_data += date.getUTCFullYear() + '-' + parseInt( date.getUTCMonth() + 1, 10 ) + ','; + if ( groupby === 'day' ) { + csv_data += '"' + date.getUTCFullYear() + '-' + parseInt( date.getUTCMonth() + 1, 10 ) + '-' + date.getUTCDate() + '",'; + } else { + csv_data += '"' + date.getUTCFullYear() + '-' + parseInt( date.getUTCMonth() + 1, 10 ) + '",'; + } } for ( var d = 0; d < value.length; ++d ) { @@ -231,7 +237,7 @@ jQuery(function( $ ) { val = val.toFixed( 2 ); } - csv_data += val + ','; + csv_data += '"' + val + '",'; } csv_data = csv_data.substring( 0, csv_data.length - 1 ); csv_data += '\n'; diff --git a/assets/js/admin/reports.min.js b/assets/js/admin/reports.min.js index 2f0b9c2c965..9cfd34c51fc 100644 --- a/assets/js/admin/reports.min.js +++ b/assets/js/admin/reports.min.js @@ -1 +1 @@ -jQuery(function(a){function b(b,c,d){a('
    '+d+"
    ").css({top:c-16,left:b+20}).appendTo("body").fadeIn(200)}var c=null,d=null;a(".chart-placeholder").bind("plothover",function(e,f,g){if(g){if((c!==g.dataIndex||d!==g.seriesIndex)&&(c=g.dataIndex,d=g.seriesIndex,a(".chart-tooltip").remove(),g.series.points.show||g.series.enable_tooltip)){var h=g.series.data[g.dataIndex][1],i="";g.series.prepend_label&&(i=i+g.series.label+": "),g.series.prepend_tooltip&&(i+=g.series.prepend_tooltip),i+=h,g.series.append_tooltip&&(i+=g.series.append_tooltip),g.series.pie.show?b(f.pageX,f.pageY,i):b(g.pageX,g.pageY,i)}}else a(".chart-tooltip").remove(),c=null}),a(".wc_sparkline.bars").each(function(){var b=a(this).data("sparkline"),c={grid:{show:!1}},d=[{data:b,color:a(this).data("color"),bars:{fillColor:a(this).data("color"),fill:!0,show:!0,lineWidth:1,barWidth:a(this).data("barwidth"),align:"center"},shadowSize:0}];a.plot(a(this),d,c)}),a(".wc_sparkline.lines").each(function(){var b=a(this).data("sparkline"),c={grid:{show:!1}},d=[{data:b,color:a(this).data("color"),lines:{fill:!1,show:!0,lineWidth:1,align:"center"},shadowSize:0}];a.plot(a(this),d,c)});var e=a(".range_datepicker").datepicker({changeMonth:!0,changeYear:!0,defaultDate:"",dateFormat:"yy-mm-dd",numberOfMonths:1,maxDate:"+0D",showButtonPanel:!0,showOn:"focus",buttonImageOnly:!0,onSelect:function(b){var c=a(this).is(".from")?"minDate":"maxDate",d=a(this).data("datepicker"),f=a.datepicker.parseDate(d.settings.dateFormat||a.datepicker._defaults.dateFormat,b,d.settings);e.not(this).datepicker("option",c,f)}}),f=document.createElement("a");"undefined"==typeof f.download&&a(".export_csv").hide(),a(".export_csv").click(function(){var b=a(this).data("exclude_series")||"";b=b.toString(),b=b.split(",");var c,d,e,f=a(this).data("xaxes"),g=a(this).data("groupby"),h=a(this).data("export"),i="data:application/csv;charset=utf-8,";if("table"===h)a(this).closest("div").find("thead tr,tbody tr").each(function(){a(this).find("th, td").each(function(){var b=a(this).text();b=b.replace("[?]",""),i+='"'+b+'",'}),i=i.substring(0,i.length-1),i+="\n"}),a(this).closest("div").find("tfoot tr").each(function(){a(this).find("th, td").each(function(){var b=a(this).text();if(b=b.replace("[?]",""),i+='"'+b+'",',a(this).attr("colspan")>0)for(m=1;m'+d+"").css({top:c-16,left:b+20}).appendTo("body").fadeIn(200)}var c=null,d=null;a(".chart-placeholder").bind("plothover",function(e,f,g){if(g){if((c!==g.dataIndex||d!==g.seriesIndex)&&(c=g.dataIndex,d=g.seriesIndex,a(".chart-tooltip").remove(),g.series.points.show||g.series.enable_tooltip)){var h=g.series.data[g.dataIndex][1],i="";g.series.prepend_label&&(i=i+g.series.label+": "),g.series.prepend_tooltip&&(i+=g.series.prepend_tooltip),i+=h,g.series.append_tooltip&&(i+=g.series.append_tooltip),g.series.pie.show?b(f.pageX,f.pageY,i):b(g.pageX,g.pageY,i)}}else a(".chart-tooltip").remove(),c=null}),a(".wc_sparkline.bars").each(function(){var b=a(this).data("sparkline"),c={grid:{show:!1}},d=[{data:b,color:a(this).data("color"),bars:{fillColor:a(this).data("color"),fill:!0,show:!0,lineWidth:1,barWidth:a(this).data("barwidth"),align:"center"},shadowSize:0}];a.plot(a(this),d,c)}),a(".wc_sparkline.lines").each(function(){var b=a(this).data("sparkline"),c={grid:{show:!1}},d=[{data:b,color:a(this).data("color"),lines:{fill:!1,show:!0,lineWidth:1,align:"center"},shadowSize:0}];a.plot(a(this),d,c)});var e=a(".range_datepicker").datepicker({changeMonth:!0,changeYear:!0,defaultDate:"",dateFormat:"yy-mm-dd",numberOfMonths:1,minDate:"-20Y",maxDate:"+0D",showButtonPanel:!0,showOn:"focus",buttonImageOnly:!0,onSelect:function(b){var c=a(this).is(".from")?"minDate":"maxDate",d=a(this).data("datepicker"),f=a.datepicker.parseDate(d.settings.dateFormat||a.datepicker._defaults.dateFormat,b,d.settings);e.not(this).datepicker("option",c,f)}}),f=document.createElement("a");"undefined"==typeof f.download&&a(".export_csv").hide(),a(".export_csv").click(function(){var b=a(this).data("exclude_series")||"";b=b.toString(),b=b.split(",");var c,d,e,f=a(this).data("xaxes"),g=a(this).data("groupby"),h=a(this).data("index_type"),i=a(this).data("export"),j="data:application/csv;charset=utf-8,";if("table"===i)a(this).offsetParent().find("thead tr,tbody tr").each(function(){a(this).find("th, td").each(function(){var b=a(this).text();b=b.replace("[?]","").replace("#",""),j+='"'+b+'",'}),j=j.substring(0,j.length-1),j+="\n"}),a(this).offsetParent().find("tfoot tr").each(function(){a(this).find("th, td").each(function(){var b=a(this).text();if(b=b.replace("[?]","").replace("#",""),j+='"'+b+'",',a(this).attr("colspan")>0)for(n=1;n 0 ? '&' : '?' ) + 'action=woocommerce_tax_rates_save_changes', data: { current_class: data.current_class, wc_tax_nonce: data.wc_tax_nonce, @@ -95,6 +97,9 @@ WCTaxTableModelInstance.changes = {}; WCTaxTableModelInstance.trigger( 'saved:rates' ); + + // Reload view. + WCTaxTableInstance.render(); } self.unblock(); @@ -114,8 +119,7 @@ this.listenTo( this.model, 'change:rates', this.setUnloadConfirmation ); this.listenTo( this.model, 'saved:rates', this.clearUnloadConfirmation ); - $tbody.on( 'change', { view: this }, this.updateModelOnChange ); - $tbody.on( 'sortupdate', { view: this }, this.updateModelOnSort ); + $tbody.on( 'change autocompletechange', ':input', { view: this }, this.updateModelOnChange ); $search_field.on( 'keyup search', { view: this }, this.onSearchField ); $pagination.on( 'click', 'a', { view: this }, this.onPageChange ); $pagination.on( 'change', 'input', { view: this }, this.onPageChange ); @@ -173,13 +177,9 @@ current_page: this.page, qty_pages: qty_pages } ) ); - } - - // Disable sorting if there is a search term filtering the items. - if ( $search_field.val() ) { - $tbody.sortable( 'disable' ); } else { - $tbody.sortable( 'enable' ); + $pagination.empty(); + view.page = 1; } }, updateUrl: function() { @@ -243,6 +243,8 @@ return parseInt( val, 10 ); } ); + // Move the last page + view.page = view.qty_pages; } rates[ newRow.tax_rate_id ] = newRow; @@ -258,27 +260,13 @@ model = view.model, rates = _.indexBy( model.get( 'rates' ), 'tax_rate_id' ), changes = {}, - $current, current_id, current_order, rates_to_reorder, reordered_rates; + $current, current_id; event.preventDefault(); if ( $current = $tbody.children( '.current' ) ) { $current.each(function(){ current_id = $( this ).data('id'); - current_order = parseInt( rates[ current_id ].tax_rate_order, 10 ); - - rates_to_reorder = _.filter( rates, function( rate ) { - if ( parseInt( rate.tax_rate_order, 10 ) > current_order ) { - return true; - } - return false; - } ); - - reordered_rates = _.map( rates_to_reorder, function( rate ) { - rate.tax_rate_order--; - changes[ rate.tax_rate_id ] = _.extend( changes[ rate.tax_rate_id ] || {}, { tax_rate_order : rate.tax_rate_order } ); - return rate; - } ); delete rates[ current_id ]; @@ -368,55 +356,6 @@ model.setRateAttribute( id, attribute, val ); }, - updateModelOnSort: function( event, ui ) { - var view = event.data.view, - model = view.model, - $tr = ui.item, - tax_rate_id = $tr.data( 'id' ), - rates = _.indexBy( model.get( 'rates' ), 'tax_rate_id' ), - old_position = rates[ tax_rate_id ].tax_rate_order, - new_position = $tr.index() + ( ( view.page - 1 ) * view.per_page ), - which_way = ( new_position > old_position ) ? 'higher' : 'lower', - changes = {}, - rates_to_reorder, reordered_rates; - - rates_to_reorder = _.filter( rates, function( rate ) { - var order = parseInt( rate.tax_rate_order, 10 ), - limits = [ old_position, new_position ]; - - if ( parseInt( rate.tax_rate_id, 10 ) === parseInt( tax_rate_id, 10 ) ) { - return true; - } else if ( order > _.min( limits ) && order < _.max( limits ) ) { - return true; - } else if ( 'higher' === which_way && order === _.max( limits ) ) { - return true; - } else if ( 'lower' === which_way && order === _.min( limits ) ) { - return true; - } - return false; - } ); - - reordered_rates = _.map( rates_to_reorder, function( rate ) { - var order = parseInt( rate.tax_rate_order, 10 ); - - if ( parseInt( rate.tax_rate_id, 10 ) === parseInt( tax_rate_id, 10 ) ) { - rate.tax_rate_order = new_position; - } else if ( 'higher' === which_way ) { - rate.tax_rate_order = order - 1; - } else if ( 'lower' === which_way ) { - rate.tax_rate_order = order + 1; - } - - changes[ rate.tax_rate_id ] = _.extend( changes[ rate.tax_rate_id ] || {}, { tax_rate_order : rate.tax_rate_order } ); - - return rate; - } ); - - if ( reordered_rates.length ) { - model.logChanges( changes ); - view.render(); // temporary, probably should get yanked. - } - }, sanitizePage: function( page_num ) { page_num = parseInt( page_num, 10 ); if ( page_num < 1 ) { @@ -432,8 +371,6 @@ } ), WCTaxTableInstance = new WCTaxTableViewConstructor({ model: WCTaxTableModelInstance, - // page: data.page, // I'd prefer to have these two specified down here in the instance, - // per_page: data.limit, // but it doesn't seem to recognize them in render if I do. :\ el: '#rates' } ); diff --git a/assets/js/admin/settings-views-html-settings-tax.min.js b/assets/js/admin/settings-views-html-settings-tax.min.js index a3305d72181..39172b9bd62 100644 --- a/assets/js/admin/settings-views-html-settings-tax.min.js +++ b/assets/js/admin/settings-views-html-settings-tax.min.js @@ -1 +1 @@ -!function(a,b,c,d){a(function(){String.prototype.trim||(String.prototype.trim=function(){return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")});var e=c.template("wc-tax-table-row"),f=c.template("wc-tax-table-row-empty"),g=c.template("wc-tax-table-pagination"),h=a(".wc_tax_rates"),i=a("#rates"),j=a('input[name="save"]'),k=a("#rates-pagination"),l=a("#rates-search .wc-tax-rates-search-field"),m=a(".submit .button-primary[type=submit]"),n=Backbone.Model.extend({changes:{},setRateAttribute:function(a,b,c){var d=_.indexBy(this.get("rates"),"tax_rate_id"),e={};d[a][b]!==c&&(e[a]={},e[a][b]=c,d[a][b]=c),this.logChanges(e)},logChanges:function(a){var b=this.changes||{};_.each(a,function(a,c){b[c]=_.extend(b[c]||{tax_rate_id:c},a)}),this.changes=b,this.trigger("change:rates")},getFilteredRates:function(){var a=this.get("rates"),b=l.val().toLowerCase();return b.length&&(a=_.filter(a,function(a){var c=_.toArray(a).join(" ").toLowerCase();return-1!==c.indexOf(b)})),a=_.sortBy(a,function(a){return parseInt(a.tax_rate_order,10)})},block:function(){a(".wc_tax_rates").block({message:null,overlayCSS:{background:"#fff",opacity:.6}})},unblock:function(){a(".wc_tax_rates").unblock()},save:function(){var a=this;a.block(),Backbone.ajax({method:"POST",dataType:"json",url:d+"?action=woocommerce_tax_rates_save_changes",data:{current_class:b.current_class,wc_tax_nonce:b.wc_tax_nonce,changes:a.changes},success:function(b,c){"success"===c&&(p.set("rates",b.data.rates),p.trigger("change:rates"),p.changes={},p.trigger("saved:rates")),a.unblock()}})}}),o=Backbone.View.extend({rowTemplate:e,per_page:b.limit,page:b.page,initialize:function(){var c=Math.ceil(_.toArray(this.model.get("rates")).length/this.per_page);this.qty_pages=0===c?1:c,this.page=this.sanitizePage(b.page),this.listenTo(this.model,"change:rates",this.setUnloadConfirmation),this.listenTo(this.model,"saved:rates",this.clearUnloadConfirmation),i.on("change",{view:this},this.updateModelOnChange),i.on("sortupdate",{view:this},this.updateModelOnSort),l.on("keyup search",{view:this},this.onSearchField),k.on("click","a",{view:this},this.onPageChange),k.on("change","input",{view:this},this.onPageChange),a(window).on("beforeunload",{view:this},this.unloadConfirmation),m.on("click",{view:this},this.onSubmit),j.attr("disabled","disabled"),h.find(".insert").on("click",{view:this},this.onAddNewRow),h.find(".remove_tax_rates").on("click",{view:this},this.onDeleteRow),h.find(".export").on("click",{view:this},this.onExport)},render:function(){var c=this.model.getFilteredRates(),d=_.size(c),e=Math.ceil(d/this.per_page),h=0===d?0:this.per_page*(this.page-1),j=this.per_page*this.page,m=_.toArray(c).slice(h,j),n=this;this.$el.empty(),m.length?a.each(m,function(a,b){n.$el.append(n.rowTemplate(b))}):n.$el.append(f()),this.$el.find("td.country input").autocomplete({source:b.countries,minLength:2}),this.$el.find("td.state input").autocomplete({source:b.states,minLength:3}),this.$el.find("td.postcode input, td.city input").change(function(){a(this).attr("name",a(this).data("name"))}),e>1&&k.html(g({qty_rates:d,current_page:this.page,qty_pages:e})),l.val()?i.sortable("disable"):i.sortable("enable")},updateUrl:function(){if(window.history.replaceState){var a=b.base_url,c=l.val();1e?!0:!1}),g=_.map(f,function(a){return a.tax_rate_order++,l[a.tax_rate_id]=_.extend(l[a.tax_rate_id]||{},{tax_rate_order:a.tax_rate_order}),a})):n.tax_rate_order=1+_.max(_.pluck(k,"tax_rate_order"),function(a){return parseInt(a,10)}),k[n.tax_rate_id]=n,l[n.tax_rate_id]=n,j.set("rates",k),j.logChanges(l),h.render()},onDeleteRow:function(c){var d,e,f,g,h,j=c.data.view,k=j.model,l=_.indexBy(k.get("rates"),"tax_rate_id"),m={};c.preventDefault(),(d=i.children(".current"))?(d.each(function(){e=a(this).data("id"),f=parseInt(l[e].tax_rate_order,10),g=_.filter(l,function(a){return parseInt(a.tax_rate_order,10)>f?!0:!1}),h=_.map(g,function(a){return a.tax_rate_order--,m[a.tax_rate_id]=_.extend(m[a.tax_rate_id]||{},{tax_rate_order:a.tax_rate_order}),a}),delete l[e],m[e]=_.extend(m[e]||{},{deleted:"deleted"})}),k.set("rates",l),k.logChanges(m),j.render()):window.alert(b.strings.no_rows_selected)},onSearchField:function(a){a.data.view.updateUrl(),a.data.view.render()},onPageChange:function(b){var c=a(b.currentTarget);b.preventDefault(),b.data.view.page=c.data("goto")?c.data("goto"):c.val(),b.data.view.render(),b.data.view.updateUrl()},onExport:function(c){var d="data:application/csv;charset=utf-8,"+b.strings.csv_data_cols.join(",")+"\n";return a.each(c.data.view.model.getFilteredRates(),function(a,c){var e="";e+=c.tax_rate_country+",",e+=c.tax_rate_state+",",e+=(c.postcode?c.postcode.join("; "):"")+",",e+=(c.city?c.city.join("; "):"")+",",e+=c.tax_rate+",",e+=c.tax_rate_name+",",e+=c.tax_rate_priority+",",e+=c.tax_rate_compound+",",e+=c.tax_rate_shipping+",",e+=b.current_class,d+=e+"\n"}),a(this).attr("href",encodeURI(d)),!0},setUnloadConfirmation:function(){this.needsUnloadConfirm=!0,j.removeAttr("disabled")},clearUnloadConfirmation:function(){this.needsUnloadConfirm=!1,j.attr("disabled","disabled")},unloadConfirmation:function(a){return a.data.view.needsUnloadConfirm?(a.returnValue=b.strings.unload_confirmation_msg,window.event.returnValue=b.strings.unload_confirmation_msg,b.strings.unload_confirmation_msg):void 0},updateModelOnChange:function(b){var c=b.data.view.model,d=a(b.target),e=d.closest("tr").data("id"),f=d.data("attribute"),g=d.val();("city"===f||"postcode"===f)&&(g=g.split(";"),g=a.map(g,function(a){return a.trim()})),("tax_rate_compound"===f||"tax_rate_shipping"===f)&&(g=d.is(":checked")?1:0),c.setRateAttribute(e,f,g)},updateModelOnSort:function(a,b){var c,d,e=a.data.view,f=e.model,g=b.item,h=g.data("id"),i=_.indexBy(f.get("rates"),"tax_rate_id"),j=i[h].tax_rate_order,k=g.index()+(e.page-1)*e.per_page,l=k>j?"higher":"lower",m={};c=_.filter(i,function(a){var b=parseInt(a.tax_rate_order,10),c=[j,k];return parseInt(a.tax_rate_id,10)===parseInt(h,10)?!0:b>_.min(c)&&b<_.max(c)?!0:"higher"===l&&b===_.max(c)?!0:"lower"===l&&b===_.min(c)?!0:!1}),d=_.map(c,function(a){var b=parseInt(a.tax_rate_order,10);return parseInt(a.tax_rate_id,10)===parseInt(h,10)?a.tax_rate_order=k:"higher"===l?a.tax_rate_order=b-1:"lower"===l&&(a.tax_rate_order=b+1),m[a.tax_rate_id]=_.extend(m[a.tax_rate_id]||{},{tax_rate_order:a.tax_rate_order}),a}),d.length&&(f.logChanges(m),e.render())},sanitizePage:function(a){return a=parseInt(a,10),1>a?a=1:a>this.qty_pages&&(a=this.qty_pages),a}}),p=new n({rates:b.rates}),q=new o({model:p,el:"#rates"});q.render()})}(jQuery,htmlSettingsTaxLocalizeScript,wp,ajaxurl); \ No newline at end of file +!function(a,b,c,d){a(function(){String.prototype.trim||(String.prototype.trim=function(){return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")});var e=c.template("wc-tax-table-row"),f=c.template("wc-tax-table-row-empty"),g=c.template("wc-tax-table-pagination"),h=a(".wc_tax_rates"),i=a("#rates"),j=a('input[name="save"]'),k=a("#rates-pagination"),l=a("#rates-search .wc-tax-rates-search-field"),m=a(".submit .button-primary[type=submit]"),n=Backbone.Model.extend({changes:{},setRateAttribute:function(a,b,c){var d=_.indexBy(this.get("rates"),"tax_rate_id"),e={};d[a][b]!==c&&(e[a]={},e[a][b]=c,d[a][b]=c),this.logChanges(e)},logChanges:function(a){var b=this.changes||{};_.each(a,function(a,c){b[c]=_.extend(b[c]||{tax_rate_id:c},a)}),this.changes=b,this.trigger("change:rates")},getFilteredRates:function(){var a=this.get("rates"),b=l.val().toLowerCase();return b.length&&(a=_.filter(a,function(a){var c=_.toArray(a).join(" ").toLowerCase();return-1!==c.indexOf(b)})),a=_.sortBy(a,function(a){return parseInt(a.tax_rate_order,10)})},block:function(){a(".wc_tax_rates").block({message:null,overlayCSS:{background:"#fff",opacity:.6}})},unblock:function(){a(".wc_tax_rates").unblock()},save:function(){var a=this;a.block(),Backbone.ajax({method:"POST",dataType:"json",url:d+(d.indexOf("?")>0?"&":"?")+"action=woocommerce_tax_rates_save_changes",data:{current_class:b.current_class,wc_tax_nonce:b.wc_tax_nonce,changes:a.changes},success:function(b,c){"success"===c&&(p.set("rates",b.data.rates),p.trigger("change:rates"),p.changes={},p.trigger("saved:rates"),q.render()),a.unblock()}})}}),o=Backbone.View.extend({rowTemplate:e,per_page:b.limit,page:b.page,initialize:function(){var c=Math.ceil(_.toArray(this.model.get("rates")).length/this.per_page);this.qty_pages=0===c?1:c,this.page=this.sanitizePage(b.page),this.listenTo(this.model,"change:rates",this.setUnloadConfirmation),this.listenTo(this.model,"saved:rates",this.clearUnloadConfirmation),i.on("change autocompletechange",":input",{view:this},this.updateModelOnChange),l.on("keyup search",{view:this},this.onSearchField),k.on("click","a",{view:this},this.onPageChange),k.on("change","input",{view:this},this.onPageChange),a(window).on("beforeunload",{view:this},this.unloadConfirmation),m.on("click",{view:this},this.onSubmit),j.attr("disabled","disabled"),h.find(".insert").on("click",{view:this},this.onAddNewRow),h.find(".remove_tax_rates").on("click",{view:this},this.onDeleteRow),h.find(".export").on("click",{view:this},this.onExport)},render:function(){var c=this.model.getFilteredRates(),d=_.size(c),e=Math.ceil(d/this.per_page),h=0===d?0:this.per_page*(this.page-1),i=this.per_page*this.page,j=_.toArray(c).slice(h,i),l=this;this.$el.empty(),j.length?a.each(j,function(a,b){l.$el.append(l.rowTemplate(b))}):l.$el.append(f()),this.$el.find("td.country input").autocomplete({source:b.countries,minLength:2}),this.$el.find("td.state input").autocomplete({source:b.states,minLength:3}),this.$el.find("td.postcode input, td.city input").change(function(){a(this).attr("name",a(this).data("name"))}),e>1?k.html(g({qty_rates:d,current_page:this.page,qty_pages:e})):(k.empty(),l.page=1)},updateUrl:function(){if(window.history.replaceState){var a=b.base_url,c=l.val();1e}),g=_.map(f,function(a){return a.tax_rate_order++,l[a.tax_rate_id]=_.extend(l[a.tax_rate_id]||{},{tax_rate_order:a.tax_rate_order}),a})):(n.tax_rate_order=1+_.max(_.pluck(k,"tax_rate_order"),function(a){return parseInt(a,10)}),h.page=h.qty_pages),k[n.tax_rate_id]=n,l[n.tax_rate_id]=n,j.set("rates",k),j.logChanges(l),h.render()},onDeleteRow:function(c){var d,e,f=c.data.view,g=f.model,h=_.indexBy(g.get("rates"),"tax_rate_id"),j={};c.preventDefault(),(d=i.children(".current"))?(d.each(function(){e=a(this).data("id"),delete h[e],j[e]=_.extend(j[e]||{},{deleted:"deleted"})}),g.set("rates",h),g.logChanges(j),f.render()):window.alert(b.strings.no_rows_selected)},onSearchField:function(a){a.data.view.updateUrl(),a.data.view.render()},onPageChange:function(b){var c=a(b.currentTarget);b.preventDefault(),b.data.view.page=c.data("goto")?c.data("goto"):c.val(),b.data.view.render(),b.data.view.updateUrl()},onExport:function(c){var d="data:application/csv;charset=utf-8,"+b.strings.csv_data_cols.join(",")+"\n";return a.each(c.data.view.model.getFilteredRates(),function(a,c){var e="";e+=c.tax_rate_country+",",e+=c.tax_rate_state+",",e+=(c.postcode?c.postcode.join("; "):"")+",",e+=(c.city?c.city.join("; "):"")+",",e+=c.tax_rate+",",e+=c.tax_rate_name+",",e+=c.tax_rate_priority+",",e+=c.tax_rate_compound+",",e+=c.tax_rate_shipping+",",e+=b.current_class,d+=e+"\n"}),a(this).attr("href",encodeURI(d)),!0},setUnloadConfirmation:function(){this.needsUnloadConfirm=!0,j.removeAttr("disabled")},clearUnloadConfirmation:function(){this.needsUnloadConfirm=!1,j.attr("disabled","disabled")},unloadConfirmation:function(a){if(a.data.view.needsUnloadConfirm)return a.returnValue=b.strings.unload_confirmation_msg,window.event.returnValue=b.strings.unload_confirmation_msg,b.strings.unload_confirmation_msg},updateModelOnChange:function(b){var c=b.data.view.model,d=a(b.target),e=d.closest("tr").data("id"),f=d.data("attribute"),g=d.val();"city"!==f&&"postcode"!==f||(g=g.split(";"),g=a.map(g,function(a){return a.trim()})),"tax_rate_compound"!==f&&"tax_rate_shipping"!==f||(g=d.is(":checked")?1:0),c.setRateAttribute(e,f,g)},sanitizePage:function(a){return a=parseInt(a,10),a<1?a=1:a>this.qty_pages&&(a=this.qty_pages),a}}),p=new n({rates:b.rates}),q=new o({model:p,el:"#rates"});q.render()})}(jQuery,htmlSettingsTaxLocalizeScript,wp,ajaxurl); \ No newline at end of file diff --git a/assets/js/admin/settings.js b/assets/js/admin/settings.js index 46791e69801..0f722f2830f 100644 --- a/assets/js/admin/settings.js +++ b/assets/js/admin/settings.js @@ -1,44 +1,67 @@ /* global woocommerce_settings_params */ -jQuery( window ).load( function() { +( function( $ ) { - // Countries - jQuery( 'select#woocommerce_allowed_countries, select#woocommerce_ship_to_countries' ).change( function() { - if ( jQuery( this ).val() === 'specific' ) { - jQuery( this ).parent().parent().next( 'tr' ).show(); + // Sell Countries + $( 'select#woocommerce_allowed_countries' ).change( function() { + if ( 'specific' === $( this ).val() ) { + $( this ).closest('tr').next( 'tr' ).hide(); + $( this ).closest('tr').next().next( 'tr' ).show(); + } else if ( 'all_except' === $( this ).val() ) { + $( this ).closest('tr').next( 'tr' ).show(); + $( this ).closest('tr').next().next( 'tr' ).hide(); } else { - jQuery( this ).parent().parent().next( 'tr' ).hide(); + $( this ).closest('tr').next( 'tr' ).hide(); + $( this ).closest('tr').next().next( 'tr' ).hide(); + } + }).change(); + + // Ship Countries + $( 'select#woocommerce_ship_to_countries' ).change( function() { + if ( 'specific' === $( this ).val() ) { + $( this ).closest('tr').next( 'tr' ).show(); + } else { + $( this ).closest('tr').next( 'tr' ).hide(); + } + }).change(); + + // Stock management + $( 'input#woocommerce_manage_stock' ).change( function() { + if ( $( this ).is(':checked') ) { + $( this ).closest('tbody').find( '.manage_stock_field' ).closest( 'tr' ).show(); + } else { + $( this ).closest('tbody').find( '.manage_stock_field' ).closest( 'tr' ).hide(); } }).change(); // Color picker - jQuery( '.colorpick' ).iris({ + $( '.colorpick' ).iris({ change: function( event, ui ) { - jQuery( this ).parent().find( '.colorpickpreview' ).css({ backgroundColor: ui.color.toString() }); + $( this ).parent().find( '.colorpickpreview' ).css({ backgroundColor: ui.color.toString() }); }, hide: true, border: true }).click( function() { - jQuery( '.iris-picker' ).hide(); - jQuery( this ).closest( 'td' ).find( '.iris-picker' ).show(); + $( '.iris-picker' ).hide(); + $( this ).closest( 'td' ).find( '.iris-picker' ).show(); }); - jQuery( 'body' ).click( function() { - jQuery( '.iris-picker' ).hide(); + $( 'body' ).click( function() { + $( '.iris-picker' ).hide(); }); - jQuery( '.colorpick' ).click( function( event ) { + $( '.colorpick' ).click( function( event ) { event.stopPropagation(); }); // Edit prompt - jQuery( function() { + $( function() { var changed = false; - jQuery( 'input, textarea, select, checkbox' ).change( function() { + $( 'input, textarea, select, checkbox' ).change( function() { changed = true; }); - jQuery( '.woo-nav-tab-wrapper a' ).click( function() { + $( '.woo-nav-tab-wrapper a' ).click( function() { if ( changed ) { window.onbeforeunload = function() { return woocommerce_settings_params.i18n_nav_warning; @@ -48,13 +71,13 @@ jQuery( window ).load( function() { } }); - jQuery( '.submit input' ).click( function() { + $( '.submit input' ).click( function() { window.onbeforeunload = ''; }); }); // Sorting - jQuery( 'table.wc_gateways tbody, table.wc_shipping tbody' ).sortable({ + $( 'table.wc_gateways tbody, table.wc_shipping tbody' ).sortable({ items: 'tr', cursor: 'move', axis: 'y', @@ -62,7 +85,7 @@ jQuery( window ).load( function() { scrollSensitivity: 40, helper: function( event, ui ) { ui.children().each( function() { - jQuery( this ).width( jQuery( this ).width() ); + $( this ).width( $( this ).width() ); }); ui.css( 'left', '0' ); return ui; @@ -76,15 +99,15 @@ jQuery( window ).load( function() { }); // Select all/none - jQuery( '.woocommerce' ).on( 'click', '.select_all', function() { - jQuery( this ).closest( 'td' ).find( 'select option' ).attr( 'selected', 'selected' ); - jQuery( this ).closest( 'td' ).find( 'select' ).trigger( 'change' ); + $( '.woocommerce' ).on( 'click', '.select_all', function() { + $( this ).closest( 'td' ).find( 'select option' ).attr( 'selected', 'selected' ); + $( this ).closest( 'td' ).find( 'select' ).trigger( 'change' ); return false; }); - jQuery( '.woocommerce' ).on( 'click', '.select_none', function() { - jQuery( this ).closest( 'td' ).find( 'select option' ).removeAttr( 'selected' ); - jQuery( this ).closest( 'td' ).find( 'select' ).trigger( 'change' ); + $( '.woocommerce' ).on( 'click', '.select_none', function() { + $( this ).closest( 'td' ).find( 'select option' ).removeAttr( 'selected' ); + $( this ).closest( 'td' ).find( 'select' ).trigger( 'change' ); return false; }); -}); +})( jQuery ); diff --git a/assets/js/admin/settings.min.js b/assets/js/admin/settings.min.js index 1c85132b5d5..1f565fceb3d 100644 --- a/assets/js/admin/settings.min.js +++ b/assets/js/admin/settings.min.js @@ -1 +1 @@ -jQuery(window).load(function(){jQuery("select#woocommerce_allowed_countries, select#woocommerce_ship_to_countries").change(function(){"specific"===jQuery(this).val()?jQuery(this).parent().parent().next("tr").show():jQuery(this).parent().parent().next("tr").hide()}).change(),jQuery(".colorpick").iris({change:function(a,b){jQuery(this).parent().find(".colorpickpreview").css({backgroundColor:b.color.toString()})},hide:!0,border:!0}).click(function(){jQuery(".iris-picker").hide(),jQuery(this).closest("td").find(".iris-picker").show()}),jQuery("body").click(function(){jQuery(".iris-picker").hide()}),jQuery(".colorpick").click(function(a){a.stopPropagation()}),jQuery(function(){var a=!1;jQuery("input, textarea, select, checkbox").change(function(){a=!0}),jQuery(".woo-nav-tab-wrapper a").click(function(){a?window.onbeforeunload=function(){return woocommerce_settings_params.i18n_nav_warning}:window.onbeforeunload=""}),jQuery(".submit input").click(function(){window.onbeforeunload=""})}),jQuery("table.wc_gateways tbody, table.wc_shipping tbody").sortable({items:"tr",cursor:"move",axis:"y",handle:"td.sort",scrollSensitivity:40,helper:function(a,b){return b.children().each(function(){jQuery(this).width(jQuery(this).width())}),b.css("left","0"),b},start:function(a,b){b.item.css("background-color","#f6f6f6")},stop:function(a,b){b.item.removeAttr("style")}}),jQuery(".woocommerce").on("click",".select_all",function(){return jQuery(this).closest("td").find("select option").attr("selected","selected"),jQuery(this).closest("td").find("select").trigger("change"),!1}),jQuery(".woocommerce").on("click",".select_none",function(){return jQuery(this).closest("td").find("select option").removeAttr("selected"),jQuery(this).closest("td").find("select").trigger("change"),!1})}); \ No newline at end of file +!function(a){a("select#woocommerce_allowed_countries").change(function(){"specific"===a(this).val()?(a(this).closest("tr").next("tr").hide(),a(this).closest("tr").next().next("tr").show()):"all_except"===a(this).val()?(a(this).closest("tr").next("tr").show(),a(this).closest("tr").next().next("tr").hide()):(a(this).closest("tr").next("tr").hide(),a(this).closest("tr").next().next("tr").hide())}).change(),a("select#woocommerce_ship_to_countries").change(function(){"specific"===a(this).val()?a(this).closest("tr").next("tr").show():a(this).closest("tr").next("tr").hide()}).change(),a("input#woocommerce_manage_stock").change(function(){a(this).is(":checked")?a(this).closest("tbody").find(".manage_stock_field").closest("tr").show():a(this).closest("tbody").find(".manage_stock_field").closest("tr").hide()}).change(),a(".colorpick").iris({change:function(b,c){a(this).parent().find(".colorpickpreview").css({backgroundColor:c.color.toString()})},hide:!0,border:!0}).click(function(){a(".iris-picker").hide(),a(this).closest("td").find(".iris-picker").show()}),a("body").click(function(){a(".iris-picker").hide()}),a(".colorpick").click(function(a){a.stopPropagation()}),a(function(){var b=!1;a("input, textarea, select, checkbox").change(function(){b=!0}),a(".woo-nav-tab-wrapper a").click(function(){b?window.onbeforeunload=function(){return woocommerce_settings_params.i18n_nav_warning}:window.onbeforeunload=""}),a(".submit input").click(function(){window.onbeforeunload=""})}),a("table.wc_gateways tbody, table.wc_shipping tbody").sortable({items:"tr",cursor:"move",axis:"y",handle:"td.sort",scrollSensitivity:40,helper:function(b,c){return c.children().each(function(){a(this).width(a(this).width())}),c.css("left","0"),c},start:function(a,b){b.item.css("background-color","#f6f6f6")},stop:function(a,b){b.item.removeAttr("style")}}),a(".woocommerce").on("click",".select_all",function(){return a(this).closest("td").find("select option").attr("selected","selected"),a(this).closest("td").find("select").trigger("change"),!1}),a(".woocommerce").on("click",".select_none",function(){return a(this).closest("td").find("select option").removeAttr("selected"),a(this).closest("td").find("select").trigger("change"),!1})}(jQuery); \ No newline at end of file diff --git a/assets/js/admin/system-status.js b/assets/js/admin/system-status.js new file mode 100644 index 00000000000..12efd043065 --- /dev/null +++ b/assets/js/admin/system-status.js @@ -0,0 +1,121 @@ +/* global jQuery, woocommerce_admin_system_status */ +jQuery( function ( $ ) { + + /** + * Users country and state fields + */ + var wcSystemStatus = { + init: function() { + $( document.body ) + .on( 'click', 'a.help_tip, a.woocommerce-help-tip', this.preventTipTipClick ) + .on( 'click', 'a.debug-report', this.generateReport ) + .on( 'copy', '#copy-for-support', this.copyReport ) + .on( 'aftercopy', '#copy-for-support', this.afterCopyReport ); + }, + + /** + * Prevent anchor behavior when click on TipTip. + * + * @return {Bool} + */ + preventTipTipClick: function() { + return false; + }, + + /** + * Generate system status report. + * + * @return {Bool} + */ + generateReport: function() { + var report = ''; + + $( '.wc_status_table thead, .wc_status_table tbody' ).each( function() { + if ( $( this ).is( 'thead' ) ) { + var label = $( this ).find( 'th:eq(0)' ).data( 'export-label' ) || $( this ).text(); + report = report + '\n### ' + $.trim( label ) + ' ###\n\n'; + } else { + $( 'tr', $( this ) ).each( function() { + var label = $( this ).find( 'td:eq(0)' ).data( 'export-label' ) || $( this ).find( 'td:eq(0)' ).text(); + var the_name = $.trim( label ).replace( /(<([^>]+)>)/ig, '' ); // Remove HTML. + + // Find value + var $value_html = $( this ).find( 'td:eq(2)' ).clone(); + $value_html.find( '.private' ).remove(); + $value_html.find( '.dashicons-yes' ).replaceWith( '✔' ); + $value_html.find( '.dashicons-no-alt, .dashicons-warning' ).replaceWith( '❌' ); + + // Format value + var the_value = $.trim( $value_html.text() ); + var value_array = the_value.split( ', ' ); + + if ( value_array.length > 1 ) { + // If value have a list of plugins ','. + // Split to add new line. + var temp_line =''; + $.each( value_array, function( key, line ) { + temp_line = temp_line + line + '\n'; + }); + + the_value = temp_line; + } + + report = report + '' + the_name + ': ' + the_value + '\n'; + }); + } + }); + + try { + $( '#debug-report' ).slideDown(); + $( '#debug-report' ).find( 'textarea' ).val( '`' + report + '`' ).focus().select(); + $( this ).fadeOut(); + return false; + } catch ( e ) { + /* jshint devel: true */ + console.log( e ); + } + + return false; + }, + + /** + * Copy for report. + * + * @param {Object} evt Copy event. + */ + copyReport: function( evt ) { + evt.clipboardData.clearData(); + evt.clipboardData.setData( 'text/plain', $( '#debug-report' ).find( 'textarea' ).val() ); + evt.preventDefault(); + }, + + /** + * Actions after copying the report. + * Display a "Copied!" tip when success copied + * or display an error message. + * + * @param {Object} evt Copy event. + */ + afterCopyReport: function( evt ) { + if ( true === evt.success['text/plain'] ) { + $( '#copy-for-support' ).tipTip({ + 'attribute': 'data-tip', + 'activation': 'focus', + 'fadeIn': 50, + 'fadeOut': 50, + 'delay': 0 + }).focus(); + } else { + $( '.copy-error' ).removeClass( 'hidden' ); + $( '#debug-report' ).find( 'textarea' ).focus().select(); + } + } + }; + + wcSystemStatus.init(); + + $( '#log-viewer-select' ).on( 'click', 'h2 a.page-title-action', function( evt ) { + evt.stopImmediatePropagation(); + return window.confirm( woocommerce_admin_system_status.delete_log_confirmation ); + }); +}); diff --git a/assets/js/admin/system-status.min.js b/assets/js/admin/system-status.min.js new file mode 100644 index 00000000000..ee9e65ab63f --- /dev/null +++ b/assets/js/admin/system-status.min.js @@ -0,0 +1 @@ +jQuery(function(a){var b={init:function(){a(document.body).on("click","a.help_tip, a.woocommerce-help-tip",this.preventTipTipClick).on("click","a.debug-report",this.generateReport).on("copy","#copy-for-support",this.copyReport).on("aftercopy","#copy-for-support",this.afterCopyReport)},preventTipTipClick:function(){return!1},generateReport:function(){var b="";a(".wc_status_table thead, .wc_status_table tbody").each(function(){if(a(this).is("thead")){var c=a(this).find("th:eq(0)").data("export-label")||a(this).text();b=b+"\n### "+a.trim(c)+" ###\n\n"}else a("tr",a(this)).each(function(){var c=a(this).find("td:eq(0)").data("export-label")||a(this).find("td:eq(0)").text(),d=a.trim(c).replace(/(<([^>]+)>)/gi,""),e=a(this).find("td:eq(2)").clone();e.find(".private").remove(),e.find(".dashicons-yes").replaceWith("✔"),e.find(".dashicons-no-alt, .dashicons-warning").replaceWith("❌");var f=a.trim(e.text()),g=f.split(", ");if(g.length>1){var h="";a.each(g,function(a,b){h=h+b+"\n"}),f=h}b=b+""+d+": "+f+"\n"})});try{return a("#debug-report").slideDown(),a("#debug-report").find("textarea").val("`"+b+"`").focus().select(),a(this).fadeOut(),!1}catch(a){console.log(a)}return!1},copyReport:function(b){b.clipboardData.clearData(),b.clipboardData.setData("text/plain",a("#debug-report").find("textarea").val()),b.preventDefault()},afterCopyReport:function(b){!0===b.success["text/plain"]?a("#copy-for-support").tipTip({attribute:"data-tip",activation:"focus",fadeIn:50,fadeOut:50,delay:0}).focus():(a(".copy-error").removeClass("hidden"),a("#debug-report").find("textarea").focus().select())}};b.init()}); \ No newline at end of file diff --git a/assets/js/admin/wc-enhanced-select.js b/assets/js/admin/wc-enhanced-select.js index 823ec617a5e..4634ecf6645 100644 --- a/assets/js/admin/wc-enhanced-select.js +++ b/assets/js/admin/wc-enhanced-select.js @@ -2,226 +2,216 @@ jQuery( function( $ ) { function getEnhancedSelectFormatString() { - var formatString = { - formatMatches: function( matches ) { - if ( 1 === matches ) { - return wc_enhanced_select_params.i18n_matches_1; + return { + 'language': { + errorLoading: function() { + // Workaround for https://github.com/select2/select2/issues/4355 instead of i18n_ajax_error. + return wc_enhanced_select_params.i18n_searching; + }, + inputTooLong: function( args ) { + var overChars = args.input.length - args.maximum; + + if ( 1 === overChars ) { + return wc_enhanced_select_params.i18n_input_too_long_1; + } + + return wc_enhanced_select_params.i18n_input_too_long_n.replace( '%qty%', overChars ); + }, + inputTooShort: function( args ) { + var remainingChars = args.minimum - args.input.length; + + if ( 1 === remainingChars ) { + return wc_enhanced_select_params.i18n_input_too_short_1; + } + + return wc_enhanced_select_params.i18n_input_too_short_n.replace( '%qty%', remainingChars ); + }, + loadingMore: function() { + return wc_enhanced_select_params.i18n_load_more; + }, + maximumSelected: function( args ) { + if ( args.maximum === 1 ) { + return wc_enhanced_select_params.i18n_selection_too_long_1; + } + + return wc_enhanced_select_params.i18n_selection_too_long_n.replace( '%qty%', args.maximum ); + }, + noResults: function() { + return wc_enhanced_select_params.i18n_no_matches; + }, + searching: function() { + return wc_enhanced_select_params.i18n_searching; } - - return wc_enhanced_select_params.i18n_matches_n.replace( '%qty%', matches ); - }, - formatNoMatches: function() { - return wc_enhanced_select_params.i18n_no_matches; - }, - formatAjaxError: function() { - return wc_enhanced_select_params.i18n_ajax_error; - }, - formatInputTooShort: function( input, min ) { - var number = min - input.length; - - if ( 1 === number ) { - return wc_enhanced_select_params.i18n_input_too_short_1; - } - - return wc_enhanced_select_params.i18n_input_too_short_n.replace( '%qty%', number ); - }, - formatInputTooLong: function( input, max ) { - var number = input.length - max; - - if ( 1 === number ) { - return wc_enhanced_select_params.i18n_input_too_long_1; - } - - return wc_enhanced_select_params.i18n_input_too_long_n.replace( '%qty%', number ); - }, - formatSelectionTooBig: function( limit ) { - if ( 1 === limit ) { - return wc_enhanced_select_params.i18n_selection_too_long_1; - } - - return wc_enhanced_select_params.i18n_selection_too_long_n.replace( '%qty%', limit ); - }, - formatLoadMore: function() { - return wc_enhanced_select_params.i18n_load_more; - }, - formatSearching: function() { - return wc_enhanced_select_params.i18n_searching; } }; - - return formatString; } - $( document.body ) + try { + $( document.body ) - .on( 'wc-enhanced-select-init', function() { + .on( 'wc-enhanced-select-init', function() { - // Regular select boxes - $( ':input.wc-enhanced-select, :input.chosen_select' ).filter( ':not(.enhanced)' ).each( function() { - var select2_args = $.extend({ - minimumResultsForSearch: 10, - allowClear: $( this ).data( 'allow_clear' ) ? true : false, - placeholder: $( this ).data( 'placeholder' ) - }, getEnhancedSelectFormatString() ); + // Regular select boxes + $( ':input.wc-enhanced-select, :input.chosen_select' ).filter( ':not(.enhanced)' ).each( function() { + var select2_args = $.extend({ + minimumResultsForSearch: 10, + allowClear: $( this ).data( 'allow_clear' ) ? true : false, + placeholder: $( this ).data( 'placeholder' ) + }, getEnhancedSelectFormatString() ); - $( this ).select2( select2_args ).addClass( 'enhanced' ); - }); + $( this ).select2( select2_args ).addClass( 'enhanced' ); + }); - $( ':input.wc-enhanced-select-nostd, :input.chosen_select_nostd' ).filter( ':not(.enhanced)' ).each( function() { - var select2_args = $.extend({ - minimumResultsForSearch: 10, - allowClear: true, - placeholder: $( this ).data( 'placeholder' ) - }, getEnhancedSelectFormatString() ); + $( ':input.wc-enhanced-select-nostd, :input.chosen_select_nostd' ).filter( ':not(.enhanced)' ).each( function() { + var select2_args = $.extend({ + minimumResultsForSearch: 10, + allowClear: true, + placeholder: $( this ).data( 'placeholder' ) + }, getEnhancedSelectFormatString() ); - $( this ).select2( select2_args ).addClass( 'enhanced' ); - }); + $( this ).select2( select2_args ).addClass( 'enhanced' ); + }); - // Ajax product search box - $( ':input.wc-product-search' ).filter( ':not(.enhanced)' ).each( function() { - var select2_args = { - allowClear: $( this ).data( 'allow_clear' ) ? true : false, - placeholder: $( this ).data( 'placeholder' ), - minimumInputLength: $( this ).data( 'minimum_input_length' ) ? $( this ).data( 'minimum_input_length' ) : '3', - escapeMarkup: function( m ) { - return m; - }, - ajax: { - url: wc_enhanced_select_params.ajax_url, - dataType: 'json', - quietMillis: 250, - data: function( term ) { - return { - term: term, - action: $( this ).data( 'action' ) || 'woocommerce_json_search_products_and_variations', - security: wc_enhanced_select_params.search_products_nonce, - exclude: $( this ).data( 'exclude' ), - include: $( this ).data( 'include' ), - limit: $( this ).data( 'limit' ) - }; - }, - results: function( data ) { - var terms = []; - if ( data ) { - $.each( data, function( id, text ) { - terms.push( { id: id, text: text } ); - }); - } - return { - results: terms - }; - }, - cache: true - } - }; - - if ( $( this ).data( 'multiple' ) === true ) { - select2_args.multiple = true; - select2_args.initSelection = function( element, callback ) { - var data = $.parseJSON( element.attr( 'data-selected' ) ); - var selected = []; - - $( element.val().split( ',' ) ).each( function( i, val ) { - selected.push({ - id: val, - text: data[ val ] - }); - }); - return callback( selected ); - }; - select2_args.formatSelection = function( data ) { - return '
    ' + data.text + '
    '; - }; - } else { - select2_args.multiple = false; - select2_args.initSelection = function( element, callback ) { - var data = { - id: element.val(), - text: element.attr( 'data-selected' ) - }; - return callback( data ); - }; - } - - select2_args = $.extend( select2_args, getEnhancedSelectFormatString() ); - - $( this ).select2( select2_args ).addClass( 'enhanced' ); - }); - - // Ajax customer search boxes - $( ':input.wc-customer-search' ).filter( ':not(.enhanced)' ).each( function() { - var select2_args = { - allowClear: $( this ).data( 'allow_clear' ) ? true : false, - placeholder: $( this ).data( 'placeholder' ), - minimumInputLength: $( this ).data( 'minimum_input_length' ) ? $( this ).data( 'minimum_input_length' ) : '3', - escapeMarkup: function( m ) { - return m; - }, - ajax: { - url: wc_enhanced_select_params.ajax_url, - dataType: 'json', - quietMillis: 250, - data: function( term ) { - return { - term: term, - action: 'woocommerce_json_search_customers', - security: wc_enhanced_select_params.search_customers_nonce - }; - }, - results: function( data ) { - var terms = []; - if ( data ) { - $.each( data, function( id, text ) { - terms.push({ - id: id, - text: text + // Ajax product search box + $( ':input.wc-product-search' ).filter( ':not(.enhanced)' ).each( function() { + var select2_args = { + allowClear: $( this ).data( 'allow_clear' ) ? true : false, + placeholder: $( this ).data( 'placeholder' ), + minimumInputLength: $( this ).data( 'minimum_input_length' ) ? $( this ).data( 'minimum_input_length' ) : '3', + escapeMarkup: function( m ) { + return m; + }, + ajax: { + url: wc_enhanced_select_params.ajax_url, + dataType: 'json', + delay: 250, + data: function( params ) { + return { + term: params.term, + action: $( this ).data( 'action' ) || 'woocommerce_json_search_products_and_variations', + security: wc_enhanced_select_params.search_products_nonce, + exclude: $( this ).data( 'exclude' ), + include: $( this ).data( 'include' ), + limit: $( this ).data( 'limit' ) + }; + }, + processResults: function( data ) { + var terms = []; + if ( data ) { + $.each( data, function( id, text ) { + terms.push( { id: id, text: text } ); }); - }); + } + return { + results: terms + }; + }, + cache: true + } + }; + + select2_args = $.extend( select2_args, getEnhancedSelectFormatString() ); + + $( this ).select2( select2_args ).addClass( 'enhanced' ); + + if ( $( this ).data( 'sortable' ) ) { + var $select = $(this); + var $list = $( this ).next( '.select2-container' ).find( 'ul.select2-selection__rendered' ); + + $list.sortable({ + placeholder : 'ui-state-highlight select2-selection__choice', + forcePlaceholderSize: true, + items : 'li:not(.select2-search__field)', + tolerance : 'pointer', + stop: function() { + $( $list.find( '.select2-selection__choice' ).get().reverse() ).each( function() { + var id = $( this ).data( 'data' ).id; + var option = $select.find( 'option[value="' + id + '"]' )[0]; + $select.prepend( option ); + } ); } - return { results: terms }; - }, - cache: true - } - }; - if ( $( this ).data( 'multiple' ) === true ) { - select2_args.multiple = true; - select2_args.initSelection = function( element, callback ) { - var data = $.parseJSON( element.attr( 'data-selected' ) ); - var selected = []; - - $( element.val().split( ',' ) ).each( function( i, val ) { - selected.push({ - id: val, - text: data[ val ] - }); }); - return callback( selected ); + } + }); + + // Ajax customer search boxes + $( ':input.wc-customer-search' ).filter( ':not(.enhanced)' ).each( function() { + var select2_args = { + allowClear: $( this ).data( 'allow_clear' ) ? true : false, + placeholder: $( this ).data( 'placeholder' ), + minimumInputLength: $( this ).data( 'minimum_input_length' ) ? $( this ).data( 'minimum_input_length' ) : '1', + escapeMarkup: function( m ) { + return m; + }, + ajax: { + url: wc_enhanced_select_params.ajax_url, + dataType: 'json', + delay: 250, + data: function( params ) { + return { + term: params.term, + action: 'woocommerce_json_search_customers', + security: wc_enhanced_select_params.search_customers_nonce, + exclude: $( this ).data( 'exclude' ) + }; + }, + processResults: function( data ) { + var terms = []; + if ( data ) { + $.each( data, function( id, text ) { + terms.push({ + id: id, + text: text + }); + }); + } + return { + results: terms + }; + }, + cache: true + } }; - select2_args.formatSelection = function( data ) { - return '
    ' + data.text + '
    '; - }; - } else { - select2_args.multiple = false; - select2_args.initSelection = function( element, callback ) { - var data = { - id: element.val(), - text: element.attr( 'data-selected' ) - }; - return callback( data ); - }; - } - select2_args = $.extend( select2_args, getEnhancedSelectFormatString() ); + select2_args = $.extend( select2_args, getEnhancedSelectFormatString() ); - $( this ).select2( select2_args ).addClass( 'enhanced' ); - }); - }) + $( this ).select2( select2_args ).addClass( 'enhanced' ); - // WooCommerce Backbone Modal - .on( 'wc_backbone_modal_before_remove', function() { - $( ':input.wc-enhanced-select, :input.wc-product-search, :input.wc-customer-search' ).select2( 'close' ); - }) + if ( $( this ).data( 'sortable' ) ) { + var $select = $(this); + var $list = $( this ).next( '.select2-container' ).find( 'ul.select2-selection__rendered' ); - .trigger( 'wc-enhanced-select-init' ); + $list.sortable({ + placeholder : 'ui-state-highlight select2-selection__choice', + forcePlaceholderSize: true, + items : 'li:not(.select2-search__field)', + tolerance : 'pointer', + stop: function() { + $( $list.find( '.select2-selection__choice' ).get().reverse() ).each( function() { + var id = $( this ).data( 'data' ).id; + var option = $select.find( 'option[value="' + id + '"]' )[0]; + $select.prepend( option ); + } ); + } + }); + } + }); + }) + // WooCommerce Backbone Modal + .on( 'wc_backbone_modal_before_remove', function() { + $( '.wc-enhanced-select, :input.wc-product-search, :input.wc-customer-search' ).filter( '.select2-hidden-accessible' ).select2( 'close' ); + }) + + .trigger( 'wc-enhanced-select-init' ); + + $( 'html' ).on( 'click', function( event ) { + if ( this === event.target ) { + $( '.wc-enhanced-select, :input.wc-product-search, :input.wc-customer-search' ).filter( '.select2-hidden-accessible' ).select2( 'close' ); + } + } ); + } catch( err ) { + // If select2 failed (conflict?) log the error but don't stop other scripts breaking. + window.console.log( err ); + } }); diff --git a/assets/js/admin/wc-enhanced-select.min.js b/assets/js/admin/wc-enhanced-select.min.js index ea1d5c0c201..6ea19077f26 100644 --- a/assets/js/admin/wc-enhanced-select.min.js +++ b/assets/js/admin/wc-enhanced-select.min.js @@ -1 +1 @@ -jQuery(function(a){function b(){var a={formatMatches:function(a){return 1===a?wc_enhanced_select_params.i18n_matches_1:wc_enhanced_select_params.i18n_matches_n.replace("%qty%",a)},formatNoMatches:function(){return wc_enhanced_select_params.i18n_no_matches},formatAjaxError:function(){return wc_enhanced_select_params.i18n_ajax_error},formatInputTooShort:function(a,b){var c=b-a.length;return 1===c?wc_enhanced_select_params.i18n_input_too_short_1:wc_enhanced_select_params.i18n_input_too_short_n.replace("%qty%",c)},formatInputTooLong:function(a,b){var c=a.length-b;return 1===c?wc_enhanced_select_params.i18n_input_too_long_1:wc_enhanced_select_params.i18n_input_too_long_n.replace("%qty%",c)},formatSelectionTooBig:function(a){return 1===a?wc_enhanced_select_params.i18n_selection_too_long_1:wc_enhanced_select_params.i18n_selection_too_long_n.replace("%qty%",a)},formatLoadMore:function(){return wc_enhanced_select_params.i18n_load_more},formatSearching:function(){return wc_enhanced_select_params.i18n_searching}};return a}a(document.body).on("wc-enhanced-select-init",function(){a(":input.wc-enhanced-select, :input.chosen_select").filter(":not(.enhanced)").each(function(){var c=a.extend({minimumResultsForSearch:10,allowClear:a(this).data("allow_clear")?!0:!1,placeholder:a(this).data("placeholder")},b());a(this).select2(c).addClass("enhanced")}),a(":input.wc-enhanced-select-nostd, :input.chosen_select_nostd").filter(":not(.enhanced)").each(function(){var c=a.extend({minimumResultsForSearch:10,allowClear:!0,placeholder:a(this).data("placeholder")},b());a(this).select2(c).addClass("enhanced")}),a(":input.wc-product-search").filter(":not(.enhanced)").each(function(){var c={allowClear:a(this).data("allow_clear")?!0:!1,placeholder:a(this).data("placeholder"),minimumInputLength:a(this).data("minimum_input_length")?a(this).data("minimum_input_length"):"3",escapeMarkup:function(a){return a},ajax:{url:wc_enhanced_select_params.ajax_url,dataType:"json",quietMillis:250,data:function(b){return{term:b,action:a(this).data("action")||"woocommerce_json_search_products_and_variations",security:wc_enhanced_select_params.search_products_nonce,exclude:a(this).data("exclude"),include:a(this).data("include"),limit:a(this).data("limit")}},results:function(b){var c=[];return b&&a.each(b,function(a,b){c.push({id:a,text:b})}),{results:c}},cache:!0}};a(this).data("multiple")===!0?(c.multiple=!0,c.initSelection=function(b,c){var d=a.parseJSON(b.attr("data-selected")),e=[];return a(b.val().split(",")).each(function(a,b){e.push({id:b,text:d[b]})}),c(e)},c.formatSelection=function(a){return'
    '+a.text+"
    "}):(c.multiple=!1,c.initSelection=function(a,b){var c={id:a.val(),text:a.attr("data-selected")};return b(c)}),c=a.extend(c,b()),a(this).select2(c).addClass("enhanced")}),a(":input.wc-customer-search").filter(":not(.enhanced)").each(function(){var c={allowClear:a(this).data("allow_clear")?!0:!1,placeholder:a(this).data("placeholder"),minimumInputLength:a(this).data("minimum_input_length")?a(this).data("minimum_input_length"):"3",escapeMarkup:function(a){return a},ajax:{url:wc_enhanced_select_params.ajax_url,dataType:"json",quietMillis:250,data:function(a){return{term:a,action:"woocommerce_json_search_customers",security:wc_enhanced_select_params.search_customers_nonce}},results:function(b){var c=[];return b&&a.each(b,function(a,b){c.push({id:a,text:b})}),{results:c}},cache:!0}};a(this).data("multiple")===!0?(c.multiple=!0,c.initSelection=function(b,c){var d=a.parseJSON(b.attr("data-selected")),e=[];return a(b.val().split(",")).each(function(a,b){e.push({id:b,text:d[b]})}),c(e)},c.formatSelection=function(a){return'
    '+a.text+"
    "}):(c.multiple=!1,c.initSelection=function(a,b){var c={id:a.val(),text:a.attr("data-selected")};return b(c)}),c=a.extend(c,b()),a(this).select2(c).addClass("enhanced")})}).on("wc_backbone_modal_before_remove",function(){a(":input.wc-enhanced-select, :input.wc-product-search, :input.wc-customer-search").select2("close")}).trigger("wc-enhanced-select-init")}); \ No newline at end of file +jQuery(function(a){function b(){return{language:{errorLoading:function(){return wc_enhanced_select_params.i18n_searching},inputTooLong:function(a){var b=a.input.length-a.maximum;return 1===b?wc_enhanced_select_params.i18n_input_too_long_1:wc_enhanced_select_params.i18n_input_too_long_n.replace("%qty%",b)},inputTooShort:function(a){var b=a.minimum-a.input.length;return 1===b?wc_enhanced_select_params.i18n_input_too_short_1:wc_enhanced_select_params.i18n_input_too_short_n.replace("%qty%",b)},loadingMore:function(){return wc_enhanced_select_params.i18n_load_more},maximumSelected:function(a){return 1===a.maximum?wc_enhanced_select_params.i18n_selection_too_long_1:wc_enhanced_select_params.i18n_selection_too_long_n.replace("%qty%",a.maximum)},noResults:function(){return wc_enhanced_select_params.i18n_no_matches},searching:function(){return wc_enhanced_select_params.i18n_searching}}}}try{a(document.body).on("wc-enhanced-select-init",function(){a(":input.wc-enhanced-select, :input.chosen_select").filter(":not(.enhanced)").each(function(){var c=a.extend({minimumResultsForSearch:10,allowClear:!!a(this).data("allow_clear"),placeholder:a(this).data("placeholder")},b());a(this).select2(c).addClass("enhanced")}),a(":input.wc-enhanced-select-nostd, :input.chosen_select_nostd").filter(":not(.enhanced)").each(function(){var c=a.extend({minimumResultsForSearch:10,allowClear:!0,placeholder:a(this).data("placeholder")},b());a(this).select2(c).addClass("enhanced")}),a(":input.wc-product-search").filter(":not(.enhanced)").each(function(){var c={allowClear:!!a(this).data("allow_clear"),placeholder:a(this).data("placeholder"),minimumInputLength:a(this).data("minimum_input_length")?a(this).data("minimum_input_length"):"3",escapeMarkup:function(a){return a},ajax:{url:wc_enhanced_select_params.ajax_url,dataType:"json",delay:250,data:function(b){return{term:b.term,action:a(this).data("action")||"woocommerce_json_search_products_and_variations",security:wc_enhanced_select_params.search_products_nonce,exclude:a(this).data("exclude"),include:a(this).data("include"),limit:a(this).data("limit")}},processResults:function(b){var c=[];return b&&a.each(b,function(a,b){c.push({id:a,text:b})}),{results:c}},cache:!0}};if(c=a.extend(c,b()),a(this).select2(c).addClass("enhanced"),a(this).data("sortable")){var d=a(this),e=a(this).next(".select2-container").find("ul.select2-selection__rendered");e.sortable({placeholder:"ui-state-highlight select2-selection__choice",forcePlaceholderSize:!0,items:"li:not(.select2-search__field)",tolerance:"pointer",stop:function(){a(e.find(".select2-selection__choice").get().reverse()).each(function(){var b=a(this).data("data").id,c=d.find('option[value="'+b+'"]')[0];d.prepend(c)})}})}}),a(":input.wc-customer-search").filter(":not(.enhanced)").each(function(){var c={allowClear:!!a(this).data("allow_clear"),placeholder:a(this).data("placeholder"),minimumInputLength:a(this).data("minimum_input_length")?a(this).data("minimum_input_length"):"1",escapeMarkup:function(a){return a},ajax:{url:wc_enhanced_select_params.ajax_url,dataType:"json",delay:250,data:function(b){return{term:b.term,action:"woocommerce_json_search_customers",security:wc_enhanced_select_params.search_customers_nonce,exclude:a(this).data("exclude")}},processResults:function(b){var c=[];return b&&a.each(b,function(a,b){c.push({id:a,text:b})}),{results:c}},cache:!0}};if(c=a.extend(c,b()),a(this).select2(c).addClass("enhanced"),a(this).data("sortable")){var d=a(this),e=a(this).next(".select2-container").find("ul.select2-selection__rendered");e.sortable({placeholder:"ui-state-highlight select2-selection__choice",forcePlaceholderSize:!0,items:"li:not(.select2-search__field)",tolerance:"pointer",stop:function(){a(e.find(".select2-selection__choice").get().reverse()).each(function(){var b=a(this).data("data").id,c=d.find('option[value="'+b+'"]')[0];d.prepend(c)})}})}})}).on("wc_backbone_modal_before_remove",function(){a(".wc-enhanced-select, :input.wc-product-search, :input.wc-customer-search").filter(".select2-hidden-accessible").select2("close")}).trigger("wc-enhanced-select-init"),a("html").on("click",function(b){this===b.target&&a(".wc-enhanced-select, :input.wc-product-search, :input.wc-customer-search").filter(".select2-hidden-accessible").select2("close")})}catch(a){window.console.log(a)}}); \ No newline at end of file diff --git a/assets/js/admin/wc-setup.js b/assets/js/admin/wc-setup.js index 6a88f418d41..96145eaac7f 100644 --- a/assets/js/admin/wc-setup.js +++ b/assets/js/admin/wc-setup.js @@ -1,9 +1,9 @@ /*global wc_setup_params */ -jQuery(function( $ ) { +jQuery( function( $ ) { var locale_info = $.parseJSON( wc_setup_params.locale_info ); - $('select[name="store_location"]').change(function(){ + $( 'select[name="store_location"]' ).change( function() { var country_option = $(this).val(); var country = country_option.split( ':' )[0]; var country_locale_info = locale_info[ country ]; @@ -23,19 +23,9 @@ jQuery(function( $ ) { $(':input[name="decimal_sep"]').closest('tr').show(); $(':input[name="num_decimals"]').closest('tr').show(); } - }).change(); + } ).change(); - $('input[name="woocommerce_calc_shipping"]').change(function(){ - if ( $(this).is( ':checked' ) ) { - $(':input[name="shipping_cost_domestic"]').closest('tr').show(); - $(':input[name="shipping_cost_international"]').closest('tr').show(); - } else { - $(':input[name="shipping_cost_domestic"]').closest('tr').hide(); - $(':input[name="shipping_cost_international"]').closest('tr').hide(); - } - }).change(); - - $('input[name="woocommerce_calc_taxes"]').change(function(){ + $( 'input[name="woocommerce_calc_taxes"]' ).change( function() { if ( $(this).is( ':checked' ) ) { $(':input[name="woocommerce_prices_include_tax"], :input[name="woocommerce_import_tax_rates"]').closest('tr').show(); $('tr.tax-rates').show(); @@ -43,17 +33,9 @@ jQuery(function( $ ) { $(':input[name="woocommerce_prices_include_tax"], :input[name="woocommerce_import_tax_rates"]').closest('tr').hide(); $('tr.tax-rates').hide(); } - }).change(); + } ).change(); - $('input[name="woocommerce_import_tax_rates"]').change(function(){ - if ( $(this).is( ':checked' ) ) { - $('.importing-tax-rates').show(); - } else { - $('.importing-tax-rates').hide(); - } - }).change(); - - $('.button-next').on( 'click', function() { + $( '.button-next' ).on( 'click', function() { $('.wc-setup-content').block({ message: null, overlayCSS: { @@ -62,6 +44,23 @@ jQuery(function( $ ) { } }); return true; - }); + } ); -}); + $( '.wc-wizard-payment-gateways' ).on( 'change', '.wc-wizard-gateway-enable input', function() { + if ( $( this ).is( ':checked' ) ) { + $( this ).closest( 'li' ).addClass( 'checked' ); + } else { + $( this ).closest( 'li' ).removeClass( 'checked' ); + } + } ); + + $( '.wc-wizard-payment-gateways' ).on( 'click', 'li.wc-wizard-gateway', function() { + var $enabled = $( this ).find( '.wc-wizard-gateway-enable input' ); + + $enabled.prop( 'checked', ! $enabled.prop( 'checked' ) ).change(); + } ); + + $( '.wc-wizard-payment-gateways' ).on( 'click', 'li.wc-wizard-gateway table, li.wc-wizard-gateway a', function( e ) { + e.stopPropagation(); + } ); +} ); diff --git a/assets/js/admin/wc-setup.min.js b/assets/js/admin/wc-setup.min.js index 72efc694a0f..5dcaf11b467 100644 --- a/assets/js/admin/wc-setup.min.js +++ b/assets/js/admin/wc-setup.min.js @@ -1 +1 @@ -jQuery(function(a){var b=a.parseJSON(wc_setup_params.locale_info);a('select[name="store_location"]').change(function(){var c=a(this).val(),d=c.split(":")[0],e=b[d],f=["thousand_sep","decimal_sep","num_decimals","currency_pos"];e?a.each(e,function(b,c){a(':input[name="'+b+'"]').val(c).change(),-1!==a.inArray(b,f)&&a(':input[name="'+b+'"]').closest("tr").hide()}):(a(':input[name="currency_pos"]').closest("tr").show(),a(':input[name="thousand_sep"]').closest("tr").show(),a(':input[name="decimal_sep"]').closest("tr").show(),a(':input[name="num_decimals"]').closest("tr").show())}).change(),a('input[name="woocommerce_calc_shipping"]').change(function(){a(this).is(":checked")?(a(':input[name="shipping_cost_domestic"]').closest("tr").show(),a(':input[name="shipping_cost_international"]').closest("tr").show()):(a(':input[name="shipping_cost_domestic"]').closest("tr").hide(),a(':input[name="shipping_cost_international"]').closest("tr").hide())}).change(),a('input[name="woocommerce_calc_taxes"]').change(function(){a(this).is(":checked")?(a(':input[name="woocommerce_prices_include_tax"], :input[name="woocommerce_import_tax_rates"]').closest("tr").show(),a("tr.tax-rates").show()):(a(':input[name="woocommerce_prices_include_tax"], :input[name="woocommerce_import_tax_rates"]').closest("tr").hide(),a("tr.tax-rates").hide())}).change(),a('input[name="woocommerce_import_tax_rates"]').change(function(){a(this).is(":checked")?a(".importing-tax-rates").show():a(".importing-tax-rates").hide()}).change(),a(".button-next").on("click",function(){return a(".wc-setup-content").block({message:null,overlayCSS:{background:"#fff",opacity:.6}}),!0})}); \ No newline at end of file +jQuery(function(a){var b=a.parseJSON(wc_setup_params.locale_info);a('select[name="store_location"]').change(function(){var c=a(this).val(),d=c.split(":")[0],e=b[d],f=["thousand_sep","decimal_sep","num_decimals","currency_pos"];e?a.each(e,function(b,c){a(':input[name="'+b+'"]').val(c).change(),-1!==a.inArray(b,f)&&a(':input[name="'+b+'"]').closest("tr").hide()}):(a(':input[name="currency_pos"]').closest("tr").show(),a(':input[name="thousand_sep"]').closest("tr").show(),a(':input[name="decimal_sep"]').closest("tr").show(),a(':input[name="num_decimals"]').closest("tr").show())}).change(),a('input[name="woocommerce_calc_taxes"]').change(function(){a(this).is(":checked")?(a(':input[name="woocommerce_prices_include_tax"], :input[name="woocommerce_import_tax_rates"]').closest("tr").show(),a("tr.tax-rates").show()):(a(':input[name="woocommerce_prices_include_tax"], :input[name="woocommerce_import_tax_rates"]').closest("tr").hide(),a("tr.tax-rates").hide())}).change(),a(".button-next").on("click",function(){return a(".wc-setup-content").block({message:null,overlayCSS:{background:"#fff",opacity:.6}}),!0}),a(".wc-wizard-payment-gateways").on("change",".wc-wizard-gateway-enable input",function(){a(this).is(":checked")?a(this).closest("li").addClass("checked"):a(this).closest("li").removeClass("checked")}),a(".wc-wizard-payment-gateways").on("click","li.wc-wizard-gateway",function(){var b=a(this).find(".wc-wizard-gateway-enable input");b.prop("checked",!b.prop("checked")).change()}),a(".wc-wizard-payment-gateways").on("click","li.wc-wizard-gateway table, li.wc-wizard-gateway a",function(a){a.stopPropagation()})}); \ No newline at end of file diff --git a/assets/js/admin/wc-shipping-classes.js b/assets/js/admin/wc-shipping-classes.js new file mode 100644 index 00000000000..eefd8374b89 --- /dev/null +++ b/assets/js/admin/wc-shipping-classes.js @@ -0,0 +1,245 @@ +/* global shippingClassesLocalizeScript, ajaxurl */ +( function( $, data, wp, ajaxurl ) { + $( function() { + var $tbody = $( '.wc-shipping-class-rows' ), + $save_button = $( '.wc-shipping-class-save' ), + $row_template = wp.template( 'wc-shipping-class-row' ), + $blank_template = wp.template( 'wc-shipping-class-row-blank' ), + + // Backbone model + ShippingClass = Backbone.Model.extend({ + changes: {}, + logChanges: function( changedRows ) { + var changes = this.changes || {}; + + _.each( changedRows, function( row, id ) { + changes[ id ] = _.extend( changes[ id ] || { term_id : id }, row ); + } ); + + this.changes = changes; + this.trigger( 'change:classes' ); + }, + save: function() { + if ( _.size( this.changes ) ) { + $.post( ajaxurl + ( ajaxurl.indexOf( '?' ) > 0 ? '&' : '?' ) + 'action=woocommerce_shipping_classes_save_changes', { + wc_shipping_classes_nonce : data.wc_shipping_classes_nonce, + changes : this.changes + }, this.onSaveResponse, 'json' ); + } else { + shippingClass.trigger( 'saved:classes' ); + } + }, + discardChanges: function( id ) { + var changes = this.changes || {}; + + // Delete all changes + delete changes[ id ]; + + // No changes? Disable save button. + if ( 0 === _.size( this.changes ) ) { + shippingClassView.clearUnloadConfirmation(); + } + }, + onSaveResponse: function( response, textStatus ) { + if ( 'success' === textStatus ) { + if ( response.success ) { + shippingClass.set( 'classes', response.data.shipping_classes ); + shippingClass.trigger( 'change:classes' ); + shippingClass.changes = {}; + shippingClass.trigger( 'saved:classes' ); + } else if ( response.data ) { + window.alert( response.data ); + } else { + window.alert( data.strings.save_failed ); + } + } + shippingClassView.unblock(); + } + } ), + + // Backbone view + ShippingClassView = Backbone.View.extend({ + rowTemplate: $row_template, + initialize: function() { + this.listenTo( this.model, 'change:classes', this.setUnloadConfirmation ); + this.listenTo( this.model, 'saved:classes', this.clearUnloadConfirmation ); + this.listenTo( this.model, 'saved:classes', this.render ); + $tbody.on( 'change', { view: this }, this.updateModelOnChange ); + $( window ).on( 'beforeunload', { view: this }, this.unloadConfirmation ); + $save_button.on( 'click', { view: this }, this.onSubmit ); + $( document.body ).on( 'click', '.wc-shipping-class-add', { view: this }, this.onAddNewRow ); + $( document.body ).on( 'click', '.wc-shipping-class-save-changes', { view: this }, this.onSubmit ); + }, + block: function() { + $( this.el ).block({ + message: null, + overlayCSS: { + background: '#fff', + opacity: 0.6 + } + }); + }, + unblock: function() { + $( this.el ).unblock(); + }, + render: function() { + var classes = _.indexBy( this.model.get( 'classes' ), 'term_id' ), + view = this; + + this.$el.empty(); + this.unblock(); + + if ( _.size( classes ) ) { + // Sort classes + classes = _.sortBy( classes, function( shipping_class ) { + return shipping_class.name; + } ); + + // Populate $tbody with the current classes + $.each( classes, function( id, rowData ) { + view.renderRow( rowData ); + } ); + } else { + view.$el.append( $blank_template ); + } + }, + renderRow: function( rowData ) { + var view = this; + view.$el.append( view.rowTemplate( rowData ) ); + view.initRow( rowData ); + }, + initRow: function( rowData ) { + var view = this; + var $tr = view.$el.find( 'tr[data-id="' + rowData.term_id + '"]'); + + // Support select boxes + $tr.find( 'select' ).each( function() { + var attribute = $( this ).data( 'attribute' ); + $( this ).find( 'option[value="' + rowData[ attribute ] + '"]' ).prop( 'selected', true ); + } ); + + // Make the rows function + $tr.find( '.view' ).show(); + $tr.find( '.edit' ).hide(); + $tr.find( '.wc-shipping-class-edit' ).on( 'click', { view: this }, this.onEditRow ); + $tr.find( '.wc-shipping-class-delete' ).on( 'click', { view: this }, this.onDeleteRow ); + $tr.find( '.editing .wc-shipping-class-edit' ).trigger('click'); + $tr.find( '.wc-shipping-class-cancel-edit' ).on( 'click', { view: this }, this.onCancelEditRow ); + + // Editing? + if ( true === rowData.editing ) { + $tr.addClass( 'editing' ); + $tr.find( '.wc-shipping-class-edit' ).trigger( 'click' ); + } + }, + onSubmit: function( event ) { + event.data.view.block(); + event.data.view.model.save(); + event.preventDefault(); + }, + onAddNewRow: function( event ) { + event.preventDefault(); + + var view = event.data.view, + model = view.model, + classes = _.indexBy( model.get( 'classes' ), 'term_id' ), + changes = {}, + size = _.size( classes ), + newRow = _.extend( {}, data.default_class, { + term_id: 'new-' + size + '-' + Date.now(), + editing: true, + newRow : true + } ); + + changes[ newRow.term_id ] = newRow; + + model.logChanges( changes ); + view.renderRow( newRow ); + $( '.wc-shipping-classes-blank-state' ).remove(); + }, + onEditRow: function( event ) { + event.preventDefault(); + $( this ).closest('tr').addClass('editing'); + $( this ).closest('tr').find('.view').hide(); + $( this ).closest('tr').find('.edit').show(); + event.data.view.model.trigger( 'change:classes' ); + }, + onDeleteRow: function( event ) { + var view = event.data.view, + model = view.model, + classes = _.indexBy( model.get( 'classes' ), 'term_id' ), + changes = {}, + term_id = $( this ).closest('tr').data('id'); + + event.preventDefault(); + + if ( classes[ term_id ] ) { + delete classes[ term_id ]; + changes[ term_id ] = _.extend( changes[ term_id ] || {}, { deleted : 'deleted' } ); + model.set( 'classes', classes ); + model.logChanges( changes ); + } + + view.render(); + }, + onCancelEditRow: function( event ) { + var view = event.data.view, + model = view.model, + row = $( this ).closest('tr'), + term_id = $( this ).closest('tr').data('id'), + classes = _.indexBy( model.get( 'classes' ), 'term_id' ); + + event.preventDefault(); + model.discardChanges( term_id ); + + if ( classes[ term_id ] ) { + classes[ term_id ].editing = false; + row.after( view.rowTemplate( classes[ term_id ] ) ); + view.initRow( classes[ term_id ] ); + } + + row.remove(); + }, + setUnloadConfirmation: function() { + this.needsUnloadConfirm = true; + $save_button.removeAttr( 'disabled' ); + }, + clearUnloadConfirmation: function() { + this.needsUnloadConfirm = false; + $save_button.attr( 'disabled', 'disabled' ); + }, + unloadConfirmation: function( event ) { + if ( event.data.view.needsUnloadConfirm ) { + event.returnValue = data.strings.unload_confirmation_msg; + window.event.returnValue = data.strings.unload_confirmation_msg; + return data.strings.unload_confirmation_msg; + } + }, + updateModelOnChange: function( event ) { + var model = event.data.view.model, + $target = $( event.target ), + term_id = $target.closest( 'tr' ).data( 'id' ), + attribute = $target.data( 'attribute' ), + value = $target.val(), + classes = _.indexBy( model.get( 'classes' ), 'term_id' ), + changes = {}; + + if ( ! classes[ term_id ] || classes[ term_id ][ attribute ] !== value ) { + changes[ term_id ] = {}; + changes[ term_id ][ attribute ] = value; + } + + model.logChanges( changes ); + } + } ), + shippingClass = new ShippingClass({ + classes: data.classes + } ), + shippingClassView = new ShippingClassView({ + model: shippingClass, + el: $tbody + } ); + + shippingClassView.render(); + }); +})( jQuery, shippingClassesLocalizeScript, wp, ajaxurl ); diff --git a/assets/js/admin/wc-shipping-classes.min.js b/assets/js/admin/wc-shipping-classes.min.js new file mode 100644 index 00000000000..d083a48efc5 --- /dev/null +++ b/assets/js/admin/wc-shipping-classes.min.js @@ -0,0 +1 @@ +!function(a,b,c,d){a(function(){var e=a(".wc-shipping-class-rows"),f=a(".wc-shipping-class-save"),g=c.template("wc-shipping-class-row"),h=c.template("wc-shipping-class-row-blank"),i=Backbone.Model.extend({changes:{},logChanges:function(a){var b=this.changes||{};_.each(a,function(a,c){b[c]=_.extend(b[c]||{term_id:c},a)}),this.changes=b,this.trigger("change:classes")},save:function(){_.size(this.changes)?a.post(d+(d.indexOf("?")>0?"&":"?")+"action=woocommerce_shipping_classes_save_changes",{wc_shipping_classes_nonce:b.wc_shipping_classes_nonce,changes:this.changes},this.onSaveResponse,"json"):k.trigger("saved:classes")},discardChanges:function(a){var b=this.changes||{};delete b[a],0===_.size(this.changes)&&l.clearUnloadConfirmation()},onSaveResponse:function(a,c){"success"===c&&(a.success?(k.set("classes",a.data.shipping_classes),k.trigger("change:classes"),k.changes={},k.trigger("saved:classes")):a.data?window.alert(a.data):window.alert(b.strings.save_failed)),l.unblock()}}),j=Backbone.View.extend({rowTemplate:g,initialize:function(){this.listenTo(this.model,"change:classes",this.setUnloadConfirmation),this.listenTo(this.model,"saved:classes",this.clearUnloadConfirmation),this.listenTo(this.model,"saved:classes",this.render),e.on("change",{view:this},this.updateModelOnChange),a(window).on("beforeunload",{view:this},this.unloadConfirmation),f.on("click",{view:this},this.onSubmit),a(document.body).on("click",".wc-shipping-class-add",{view:this},this.onAddNewRow),a(document.body).on("click",".wc-shipping-class-save-changes",{view:this},this.onSubmit)},block:function(){a(this.el).block({message:null,overlayCSS:{background:"#fff",opacity:.6}})},unblock:function(){a(this.el).unblock()},render:function(){var b=_.indexBy(this.model.get("classes"),"term_id"),c=this;this.$el.empty(),this.unblock(),_.size(b)?(b=_.sortBy(b,function(a){return a.name}),a.each(b,function(a,b){c.renderRow(b)})):c.$el.append(h)},renderRow:function(a){var b=this;b.$el.append(b.rowTemplate(a)),b.initRow(a)},initRow:function(b){var c=this,d=c.$el.find('tr[data-id="'+b.term_id+'"]');d.find("select").each(function(){var c=a(this).data("attribute");a(this).find('option[value="'+b[c]+'"]').prop("selected",!0)}),d.find(".view").show(),d.find(".edit").hide(),d.find(".wc-shipping-class-edit").on("click",{view:this},this.onEditRow),d.find(".wc-shipping-class-delete").on("click",{view:this},this.onDeleteRow),d.find(".editing .wc-shipping-class-edit").trigger("click"),d.find(".wc-shipping-class-cancel-edit").on("click",{view:this},this.onCancelEditRow),!0===b.editing&&(d.addClass("editing"),d.find(".wc-shipping-class-edit").trigger("click"))},onSubmit:function(a){a.data.view.block(),a.data.view.model.save(),a.preventDefault()},onAddNewRow:function(c){c.preventDefault();var d=c.data.view,e=d.model,f=_.indexBy(e.get("classes"),"term_id"),g={},h=_.size(f),i=_.extend({},b.default_class,{term_id:"new-"+h+"-"+Date.now(),editing:!0,newRow:!0});g[i.term_id]=i,e.logChanges(g),d.renderRow(i),a(".wc-shipping-classes-blank-state").remove()},onEditRow:function(b){b.preventDefault(),a(this).closest("tr").addClass("editing"),a(this).closest("tr").find(".view").hide(),a(this).closest("tr").find(".edit").show(),b.data.view.model.trigger("change:classes")},onDeleteRow:function(b){var c=b.data.view,d=c.model,e=_.indexBy(d.get("classes"),"term_id"),f={},g=a(this).closest("tr").data("id");b.preventDefault(),e[g]&&(delete e[g],f[g]=_.extend(f[g]||{},{deleted:"deleted"}),d.set("classes",e),d.logChanges(f)),c.render()},onCancelEditRow:function(b){var c=b.data.view,d=c.model,e=a(this).closest("tr"),f=a(this).closest("tr").data("id"),g=_.indexBy(d.get("classes"),"term_id");b.preventDefault(),d.discardChanges(f),g[f]&&(g[f].editing=!1,e.after(c.rowTemplate(g[f])),c.initRow(g[f])),e.remove()},setUnloadConfirmation:function(){this.needsUnloadConfirm=!0,f.removeAttr("disabled")},clearUnloadConfirmation:function(){this.needsUnloadConfirm=!1,f.attr("disabled","disabled")},unloadConfirmation:function(a){if(a.data.view.needsUnloadConfirm)return a.returnValue=b.strings.unload_confirmation_msg,window.event.returnValue=b.strings.unload_confirmation_msg,b.strings.unload_confirmation_msg},updateModelOnChange:function(b){var c=b.data.view.model,d=a(b.target),e=d.closest("tr").data("id"),f=d.data("attribute"),g=d.val(),h=_.indexBy(c.get("classes"),"term_id"),i={};h[e]&&h[e][f]===g||(i[e]={},i[e][f]=g),c.logChanges(i)}}),k=new i({classes:b.classes}),l=new j({model:k,el:e});l.render()})}(jQuery,shippingClassesLocalizeScript,wp,ajaxurl); \ No newline at end of file diff --git a/assets/js/admin/wc-shipping-zone-methods.js b/assets/js/admin/wc-shipping-zone-methods.js new file mode 100644 index 00000000000..c3ec5efc753 --- /dev/null +++ b/assets/js/admin/wc-shipping-zone-methods.js @@ -0,0 +1,394 @@ +/* global shippingZoneMethodsLocalizeScript, ajaxurl */ +( function( $, data, wp, ajaxurl ) { + $( function() { + var $table = $( '.wc-shipping-zone-methods' ), + $tbody = $( '.wc-shipping-zone-method-rows' ), + $save_button = $( '.wc-shipping-zone-method-save' ), + $row_template = wp.template( 'wc-shipping-zone-method-row' ), + $blank_template = wp.template( 'wc-shipping-zone-method-row-blank' ), + + // Backbone model + ShippingMethod = Backbone.Model.extend({ + changes: {}, + logChanges: function( changedRows ) { + var changes = this.changes || {}; + + _.each( changedRows.methods, function( row, id ) { + changes.methods = changes.methods || { methods : {} }; + changes.methods[ id ] = _.extend( changes.methods[ id ] || { instance_id : id }, row ); + } ); + + if ( typeof changedRows.zone_name !== 'undefined' ) { + changes.zone_name = changedRows.zone_name; + } + + if ( typeof changedRows.zone_locations !== 'undefined' ) { + changes.zone_locations = changedRows.zone_locations; + } + + if ( typeof changedRows.zone_postcodes !== 'undefined' ) { + changes.zone_postcodes = changedRows.zone_postcodes; + } + + this.changes = changes; + this.trigger( 'change:methods' ); + }, + save: function() { + $.post( ajaxurl + ( ajaxurl.indexOf( '?' ) > 0 ? '&' : '?' ) + 'action=woocommerce_shipping_zone_methods_save_changes', { + wc_shipping_zones_nonce : data.wc_shipping_zones_nonce, + changes : this.changes, + zone_id : data.zone_id + }, this.onSaveResponse, 'json' ); + }, + onSaveResponse: function( response, textStatus ) { + if ( 'success' === textStatus ) { + if ( response.success ) { + if ( response.data.zone_id !== data.zone_id ) { + data.zone_id = response.data.zone_id; + if ( window.history.pushState ) { + window.history.pushState({}, '', 'admin.php?page=wc-settings&tab=shipping&zone_id=' + response.data.zone_id ); + } + } + shippingMethod.set( 'methods', response.data.methods ); + shippingMethod.trigger( 'change:methods' ); + shippingMethod.changes = {}; + shippingMethod.trigger( 'saved:methods' ); + } else { + window.alert( data.strings.save_failed ); + } + } + } + } ), + + // Backbone view + ShippingMethodView = Backbone.View.extend({ + rowTemplate: $row_template, + initialize: function() { + this.listenTo( this.model, 'change:methods', this.setUnloadConfirmation ); + this.listenTo( this.model, 'saved:methods', this.clearUnloadConfirmation ); + this.listenTo( this.model, 'saved:methods', this.render ); + $tbody.on( 'change', { view: this }, this.updateModelOnChange ); + $tbody.on( 'sortupdate', { view: this }, this.updateModelOnSort ); + $( window ).on( 'beforeunload', { view: this }, this.unloadConfirmation ); + $save_button.on( 'click', { view: this }, this.onSubmit ); + + $( document.body ).on( 'input change', '#zone_name, #zone_locations, #zone_postcodes', { view: this }, this.onUpdateZone ); + $( document.body ).on( 'click', '.wc-shipping-zone-method-settings', { view: this }, this.onConfigureShippingMethod ); + $( document.body ).on( 'click', '.wc-shipping-zone-add-method', { view: this }, this.onAddShippingMethod ); + $( document.body ).on( 'wc_backbone_modal_response', this.onConfigureShippingMethodSubmitted ); + $( document.body ).on( 'wc_backbone_modal_response', this.onAddShippingMethodSubmitted ); + $( document.body ).on( 'change', '.wc-shipping-zone-method-selector select', this.onChangeShippingMethodSelector ); + $( document.body ).on( 'click', '.wc-shipping-zone-postcodes-toggle', this.onTogglePostcodes ); + }, + onUpdateZone: function( event ) { + var view = event.data.view, + model = view.model, + value = $( this ).val(), + $target = $( event.target ), + attribute = $target.data( 'attribute' ), + changes = {}; + + event.preventDefault(); + + changes[ attribute ] = value; + model.set( attribute, value ); + model.logChanges( changes ); + view.render(); + }, + block: function() { + $( this.el ).block({ + message: null, + overlayCSS: { + background: '#fff', + opacity: 0.6 + } + }); + }, + unblock: function() { + $( this.el ).unblock(); + }, + render: function() { + var methods = _.indexBy( this.model.get( 'methods' ), 'instance_id' ), + zone_name = this.model.get( 'zone_name' ), + view = this; + + // Set name. + $('.wc-shipping-zone-name').text( zone_name ? zone_name : data.strings.default_zone_name ); + + // Blank out the contents. + this.$el.empty(); + this.unblock(); + + if ( _.size( methods ) ) { + // Sort methods + methods = _.sortBy( methods, function( method ) { + return parseInt( method.method_order, 10 ); + } ); + + // Populate $tbody with the current methods + $.each( methods, function( id, rowData ) { + if ( 'yes' === rowData.enabled ) { + rowData.enabled_icon = '' + data.strings.yes + ''; + } else { + rowData.enabled_icon = '' + data.strings.no + ''; + } + + view.$el.append( view.rowTemplate( rowData ) ); + + var $tr = view.$el.find( 'tr[data-id="' + rowData.instance_id + '"]'); + + if ( ! rowData.has_settings ) { + $tr.find( '.wc-shipping-zone-method-title a').replaceWith( $tr.find( '.wc-shipping-zone-method-title' ).text() ); + $tr.find( '.wc-shipping-zone-method-settings' ).remove(); + } + } ); + + // Make the rows function + this.$el.find( '.wc-shipping-zone-method-delete' ).on( 'click', { view: this }, this.onDeleteRow ); + this.$el.find( '.wc-shipping-zone-method-enabled a').on( 'click', { view: this }, this.onToggleEnabled ); + } else { + view.$el.append( $blank_template ); + } + + this.initTooltips(); + }, + initTooltips: function() { + $( '#tiptip_holder' ).removeAttr( 'style' ); + $( '#tiptip_arrow' ).removeAttr( 'style' ); + $( '.tips' ).tipTip({ 'attribute': 'data-tip', 'fadeIn': 50, 'fadeOut': 50, 'delay': 50 }); + }, + onSubmit: function( event ) { + event.data.view.block(); + event.data.view.model.save(); + event.preventDefault(); + }, + onDeleteRow: function( event ) { + var view = event.data.view, + model = view.model, + methods = _.indexBy( model.get( 'methods' ), 'instance_id' ), + changes = {}, + instance_id = $( this ).closest('tr').data('id'); + + event.preventDefault(); + + delete methods[ instance_id ]; + changes.methods = changes.methods || { methods : {} }; + changes.methods[ instance_id ] = _.extend( changes.methods[ instance_id ] || {}, { deleted : 'deleted' } ); + model.set( 'methods', methods ); + model.logChanges( changes ); + view.render(); + }, + onToggleEnabled: function( event ) { + var view = event.data.view, + $target = $( event.target ), + model = view.model, + methods = _.indexBy( model.get( 'methods' ), 'instance_id' ), + instance_id = $target.closest( 'tr' ).data( 'id' ), + enabled = $target.closest( 'tr' ).data( 'enabled' ) === 'yes' ? 'no' : 'yes', + changes = {}; + + event.preventDefault(); + methods[ instance_id ].enabled = enabled; + changes.methods = changes.methods || { methods : {} }; + changes.methods[ instance_id ] = _.extend( changes.methods[ instance_id ] || {}, { enabled : enabled } ); + model.set( 'methods', methods ); + model.logChanges( changes ); + view.render(); + }, + setUnloadConfirmation: function() { + this.needsUnloadConfirm = true; + $save_button.removeAttr( 'disabled' ); + }, + clearUnloadConfirmation: function() { + this.needsUnloadConfirm = false; + $save_button.attr( 'disabled', 'disabled' ); + }, + unloadConfirmation: function( event ) { + if ( event.data.view.needsUnloadConfirm ) { + event.returnValue = data.strings.unload_confirmation_msg; + window.event.returnValue = data.strings.unload_confirmation_msg; + return data.strings.unload_confirmation_msg; + } + }, + updateModelOnChange: function( event ) { + var model = event.data.view.model, + $target = $( event.target ), + instance_id = $target.closest( 'tr' ).data( 'id' ), + attribute = $target.data( 'attribute' ), + value = $target.val(), + methods = _.indexBy( model.get( 'methods' ), 'instance_id' ), + changes = {}; + + if ( methods[ instance_id ][ attribute ] !== value ) { + changes.methods[ instance_id ] = {}; + changes.methods[ instance_id ][ attribute ] = value; + methods[ instance_id ][ attribute ] = value; + } + + model.logChanges( changes ); + }, + updateModelOnSort: function( event ) { + var view = event.data.view, + model = view.model, + methods = _.indexBy( model.get( 'methods' ), 'instance_id' ), + changes = {}; + + _.each( methods, function( method ) { + var old_position = parseInt( method.method_order, 10 ); + var new_position = parseInt( $table.find( 'tr[data-id="' + method.instance_id + '"]').index() + 1, 10 ); + + if ( old_position !== new_position ) { + methods[ method.instance_id ].method_order = new_position; + changes.methods = changes.methods || { methods : {} }; + changes.methods[ method.instance_id ] = _.extend( changes.methods[ method.instance_id ] || {}, { method_order : new_position } ); + } + } ); + + if ( _.size( changes ) ) { + model.logChanges( changes ); + } + }, + onConfigureShippingMethod: function( event ) { + var instance_id = $( this ).closest( 'tr' ).data( 'id' ), + model = event.data.view.model, + methods = _.indexBy( model.get( 'methods' ), 'instance_id' ), + method = methods[ instance_id ]; + + // Only load modal if supported + if ( ! method.settings_html ) { + return true; + } + + event.preventDefault(); + + $( this ).WCBackboneModal({ + template : 'wc-modal-shipping-method-settings', + variable : { + instance_id : instance_id, + method : method + }, + data : { + instance_id : instance_id, + method : method + } + }); + + $( document.body ).trigger( 'init_tooltips' ); + }, + onConfigureShippingMethodSubmitted: function( event, target, posted_data ) { + if ( 'wc-modal-shipping-method-settings' === target ) { + shippingMethodView.block(); + + // Save method settings via ajax call + $.post( ajaxurl + ( ajaxurl.indexOf( '?' ) > 0 ? '&' : '?' ) + 'action=woocommerce_shipping_zone_methods_save_settings', { + wc_shipping_zones_nonce : data.wc_shipping_zones_nonce, + instance_id : posted_data.instance_id, + data : posted_data + }, function( response, textStatus ) { + if ( 'success' === textStatus && response.success ) { + $( 'table.wc-shipping-zone-methods' ).parent().find( '#woocommerce_errors' ).remove(); + + // If there were errors, prepend the form. + if ( response.data.errors.length > 0 ) { + this.showErrors( response.data.errors ); + } + + // Method was saved. Re-render. + if ( _.size( shippingMethodView.model.changes ) ) { + shippingMethodView.model.save(); + } else { + shippingMethodView.model.onSaveResponse( response, textStatus ); + } + } else { + window.alert( data.strings.save_failed ); + shippingMethodView.unblock(); + } + }, 'json' ); + } + }, + showErrors: function( errors ) { + var error_html = '
    '; + + $( errors ).each( function( index, value ) { + error_html = error_html + '

    ' + value + '

    '; + } ); + error_html = error_html + '
    '; + + $( 'table.wc-shipping-zone-methods' ).before( error_html ); + }, + onAddShippingMethod: function( event ) { + event.preventDefault(); + + $( this ).WCBackboneModal({ + template : 'wc-modal-add-shipping-method', + variable : { + zone_id : data.zone_id + } + }); + + $( '.wc-shipping-zone-method-selector select' ).change(); + }, + onAddShippingMethodSubmitted: function( event, target, posted_data ) { + if ( 'wc-modal-add-shipping-method' === target ) { + shippingMethodView.block(); + + // Add method to zone via ajax call + $.post( ajaxurl + ( ajaxurl.indexOf( '?' ) > 0 ? '&' : '?' ) + 'action=woocommerce_shipping_zone_add_method', { + wc_shipping_zones_nonce : data.wc_shipping_zones_nonce, + method_id : posted_data.add_method_id, + zone_id : data.zone_id + }, function( response, textStatus ) { + if ( 'success' === textStatus && response.success ) { + if ( response.data.zone_id !== data.zone_id ) { + data.zone_id = response.data.zone_id; + if ( window.history.pushState ) { + window.history.pushState({}, '', 'admin.php?page=wc-settings&tab=shipping&zone_id=' + response.data.zone_id ); + } + } + // Trigger save if there are changes, or just re-render + if ( _.size( shippingMethodView.model.changes ) ) { + shippingMethodView.model.save(); + } else { + shippingMethodView.model.set( 'methods', response.data.methods ); + shippingMethodView.model.trigger( 'change:methods' ); + shippingMethodView.model.changes = {}; + shippingMethodView.model.trigger( 'saved:methods' ); + } + } + shippingMethodView.unblock(); + }, 'json' ); + } + }, + onChangeShippingMethodSelector: function() { + var description = $( this ).find( 'option:selected' ).data( 'description' ); + $( this ).parent().find( '.wc-shipping-zone-method-description' ).remove(); + $( this ).after( '
    ' + description + '
    ' ); + $( this ).closest( 'article' ).height( $( this ).parent().height() ); + }, + onTogglePostcodes: function( event ) { + event.preventDefault(); + var $tr = $( this ).closest( 'tr'); + $tr.find( '.wc-shipping-zone-postcodes' ).show(); + $tr.find( '.wc-shipping-zone-postcodes-toggle' ).hide(); + } + } ), + shippingMethod = new ShippingMethod({ + methods: data.methods, + zone_name: data.zone_name + } ), + shippingMethodView = new ShippingMethodView({ + model: shippingMethod, + el: $tbody + } ); + + shippingMethodView.render(); + + $tbody.sortable({ + items: 'tr', + cursor: 'move', + axis: 'y', + handle: 'td.wc-shipping-zone-method-sort', + scrollSensitivity: 40 + }); + }); +})( jQuery, shippingZoneMethodsLocalizeScript, wp, ajaxurl ); diff --git a/assets/js/admin/wc-shipping-zone-methods.min.js b/assets/js/admin/wc-shipping-zone-methods.min.js new file mode 100644 index 00000000000..375e7d8f870 --- /dev/null +++ b/assets/js/admin/wc-shipping-zone-methods.min.js @@ -0,0 +1 @@ +!function(a,b,c,d){a(function(){var e=a(".wc-shipping-zone-methods"),f=a(".wc-shipping-zone-method-rows"),g=a(".wc-shipping-zone-method-save"),h=c.template("wc-shipping-zone-method-row"),i=c.template("wc-shipping-zone-method-row-blank"),j=Backbone.Model.extend({changes:{},logChanges:function(a){var b=this.changes||{};_.each(a.methods,function(a,c){b.methods=b.methods||{methods:{}},b.methods[c]=_.extend(b.methods[c]||{instance_id:c},a)}),"undefined"!=typeof a.zone_name&&(b.zone_name=a.zone_name),"undefined"!=typeof a.zone_locations&&(b.zone_locations=a.zone_locations),"undefined"!=typeof a.zone_postcodes&&(b.zone_postcodes=a.zone_postcodes),this.changes=b,this.trigger("change:methods")},save:function(){a.post(d+(d.indexOf("?")>0?"&":"?")+"action=woocommerce_shipping_zone_methods_save_changes",{wc_shipping_zones_nonce:b.wc_shipping_zones_nonce,changes:this.changes,zone_id:b.zone_id},this.onSaveResponse,"json")},onSaveResponse:function(a,c){"success"===c&&(a.success?(a.data.zone_id!==b.zone_id&&(b.zone_id=a.data.zone_id,window.history.pushState&&window.history.pushState({},"","admin.php?page=wc-settings&tab=shipping&zone_id="+a.data.zone_id)),l.set("methods",a.data.methods),l.trigger("change:methods"),l.changes={},l.trigger("saved:methods")):window.alert(b.strings.save_failed))}}),k=Backbone.View.extend({rowTemplate:h,initialize:function(){this.listenTo(this.model,"change:methods",this.setUnloadConfirmation),this.listenTo(this.model,"saved:methods",this.clearUnloadConfirmation),this.listenTo(this.model,"saved:methods",this.render),f.on("change",{view:this},this.updateModelOnChange),f.on("sortupdate",{view:this},this.updateModelOnSort),a(window).on("beforeunload",{view:this},this.unloadConfirmation),g.on("click",{view:this},this.onSubmit),a(document.body).on("input change","#zone_name, #zone_locations, #zone_postcodes",{view:this},this.onUpdateZone),a(document.body).on("click",".wc-shipping-zone-method-settings",{view:this},this.onConfigureShippingMethod),a(document.body).on("click",".wc-shipping-zone-add-method",{view:this},this.onAddShippingMethod),a(document.body).on("wc_backbone_modal_response",this.onConfigureShippingMethodSubmitted),a(document.body).on("wc_backbone_modal_response",this.onAddShippingMethodSubmitted),a(document.body).on("change",".wc-shipping-zone-method-selector select",this.onChangeShippingMethodSelector),a(document.body).on("click",".wc-shipping-zone-postcodes-toggle",this.onTogglePostcodes)},onUpdateZone:function(b){var c=b.data.view,d=c.model,e=a(this).val(),f=a(b.target),g=f.data("attribute"),h={};b.preventDefault(),h[g]=e,d.set(g,e),d.logChanges(h),c.render()},block:function(){a(this.el).block({message:null,overlayCSS:{background:"#fff",opacity:.6}})},unblock:function(){a(this.el).unblock()},render:function(){var c=_.indexBy(this.model.get("methods"),"instance_id"),d=this.model.get("zone_name"),e=this;a(".wc-shipping-zone-name").text(d?d:b.strings.default_zone_name),this.$el.empty(),this.unblock(),_.size(c)?(c=_.sortBy(c,function(a){return parseInt(a.method_order,10)}),a.each(c,function(a,c){"yes"===c.enabled?c.enabled_icon=''+b.strings.yes+"":c.enabled_icon=''+b.strings.no+"",e.$el.append(e.rowTemplate(c));var d=e.$el.find('tr[data-id="'+c.instance_id+'"]');c.has_settings||(d.find(".wc-shipping-zone-method-title a").replaceWith(d.find(".wc-shipping-zone-method-title").text()),d.find(".wc-shipping-zone-method-settings").remove())}),this.$el.find(".wc-shipping-zone-method-delete").on("click",{view:this},this.onDeleteRow),this.$el.find(".wc-shipping-zone-method-enabled a").on("click",{view:this},this.onToggleEnabled)):e.$el.append(i),this.initTooltips()},initTooltips:function(){a("#tiptip_holder").removeAttr("style"),a("#tiptip_arrow").removeAttr("style"),a(".tips").tipTip({attribute:"data-tip",fadeIn:50,fadeOut:50,delay:50})},onSubmit:function(a){a.data.view.block(),a.data.view.model.save(),a.preventDefault()},onDeleteRow:function(b){var c=b.data.view,d=c.model,e=_.indexBy(d.get("methods"),"instance_id"),f={},g=a(this).closest("tr").data("id");b.preventDefault(),delete e[g],f.methods=f.methods||{methods:{}},f.methods[g]=_.extend(f.methods[g]||{},{deleted:"deleted"}),d.set("methods",e),d.logChanges(f),c.render()},onToggleEnabled:function(b){var c=b.data.view,d=a(b.target),e=c.model,f=_.indexBy(e.get("methods"),"instance_id"),g=d.closest("tr").data("id"),h="yes"===d.closest("tr").data("enabled")?"no":"yes",i={};b.preventDefault(),f[g].enabled=h,i.methods=i.methods||{methods:{}},i.methods[g]=_.extend(i.methods[g]||{},{enabled:h}),e.set("methods",f),e.logChanges(i),c.render()},setUnloadConfirmation:function(){this.needsUnloadConfirm=!0,g.removeAttr("disabled")},clearUnloadConfirmation:function(){this.needsUnloadConfirm=!1,g.attr("disabled","disabled")},unloadConfirmation:function(a){if(a.data.view.needsUnloadConfirm)return a.returnValue=b.strings.unload_confirmation_msg,window.event.returnValue=b.strings.unload_confirmation_msg,b.strings.unload_confirmation_msg},updateModelOnChange:function(b){var c=b.data.view.model,d=a(b.target),e=d.closest("tr").data("id"),f=d.data("attribute"),g=d.val(),h=_.indexBy(c.get("methods"),"instance_id"),i={};h[e][f]!==g&&(i.methods[e]={},i.methods[e][f]=g,h[e][f]=g),c.logChanges(i)},updateModelOnSort:function(a){var b=a.data.view,c=b.model,d=_.indexBy(c.get("methods"),"instance_id"),f={};_.each(d,function(a){var b=parseInt(a.method_order,10),c=parseInt(e.find('tr[data-id="'+a.instance_id+'"]').index()+1,10);b!==c&&(d[a.instance_id].method_order=c,f.methods=f.methods||{methods:{}},f.methods[a.instance_id]=_.extend(f.methods[a.instance_id]||{},{method_order:c}))}),_.size(f)&&c.logChanges(f)},onConfigureShippingMethod:function(b){var c=a(this).closest("tr").data("id"),d=b.data.view.model,e=_.indexBy(d.get("methods"),"instance_id"),f=e[c];return!f.settings_html||(b.preventDefault(),a(this).WCBackboneModal({template:"wc-modal-shipping-method-settings",variable:{instance_id:c,method:f},data:{instance_id:c,method:f}}),void a(document.body).trigger("init_tooltips"))},onConfigureShippingMethodSubmitted:function(c,e,f){"wc-modal-shipping-method-settings"===e&&(m.block(),a.post(d+(d.indexOf("?")>0?"&":"?")+"action=woocommerce_shipping_zone_methods_save_settings",{wc_shipping_zones_nonce:b.wc_shipping_zones_nonce,instance_id:f.instance_id,data:f},function(c,d){"success"===d&&c.success?(a("table.wc-shipping-zone-methods").parent().find("#woocommerce_errors").remove(),c.data.errors.length>0&&this.showErrors(c.data.errors),_.size(m.model.changes)?m.model.save():m.model.onSaveResponse(c,d)):(window.alert(b.strings.save_failed),m.unblock())},"json"))},showErrors:function(b){var c='
    ';a(b).each(function(a,b){c=c+"

    "+b+"

    "}),c+="
    ",a("table.wc-shipping-zone-methods").before(c)},onAddShippingMethod:function(c){c.preventDefault(),a(this).WCBackboneModal({template:"wc-modal-add-shipping-method",variable:{zone_id:b.zone_id}}),a(".wc-shipping-zone-method-selector select").change()},onAddShippingMethodSubmitted:function(c,e,f){"wc-modal-add-shipping-method"===e&&(m.block(),a.post(d+(d.indexOf("?")>0?"&":"?")+"action=woocommerce_shipping_zone_add_method",{wc_shipping_zones_nonce:b.wc_shipping_zones_nonce,method_id:f.add_method_id,zone_id:b.zone_id},function(a,c){"success"===c&&a.success&&(a.data.zone_id!==b.zone_id&&(b.zone_id=a.data.zone_id,window.history.pushState&&window.history.pushState({},"","admin.php?page=wc-settings&tab=shipping&zone_id="+a.data.zone_id)),_.size(m.model.changes)?m.model.save():(m.model.set("methods",a.data.methods),m.model.trigger("change:methods"),m.model.changes={},m.model.trigger("saved:methods"))),m.unblock()},"json"))},onChangeShippingMethodSelector:function(){var b=a(this).find("option:selected").data("description");a(this).parent().find(".wc-shipping-zone-method-description").remove(),a(this).after('
    '+b+"
    "),a(this).closest("article").height(a(this).parent().height())},onTogglePostcodes:function(b){b.preventDefault();var c=a(this).closest("tr");c.find(".wc-shipping-zone-postcodes").show(),c.find(".wc-shipping-zone-postcodes-toggle").hide()}}),l=new j({methods:b.methods,zone_name:b.zone_name}),m=new k({model:l,el:f});m.render(),f.sortable({items:"tr",cursor:"move",axis:"y",handle:"td.wc-shipping-zone-method-sort",scrollSensitivity:40})})}(jQuery,shippingZoneMethodsLocalizeScript,wp,ajaxurl); \ No newline at end of file diff --git a/assets/js/admin/wc-shipping-zones.js b/assets/js/admin/wc-shipping-zones.js new file mode 100644 index 00000000000..c4eaeea9e85 --- /dev/null +++ b/assets/js/admin/wc-shipping-zones.js @@ -0,0 +1,267 @@ +/* global shippingZonesLocalizeScript, ajaxurl */ +( function( $, data, wp, ajaxurl ) { + $( function() { + var $table = $( '.wc-shipping-zones' ), + $tbody = $( '.wc-shipping-zone-rows' ), + $save_button = $( '.wc-shipping-zone-save' ), + $row_template = wp.template( 'wc-shipping-zone-row' ), + $blank_template = wp.template( 'wc-shipping-zone-row-blank' ), + + // Backbone model + ShippingZone = Backbone.Model.extend({ + changes: {}, + logChanges: function( changedRows ) { + var changes = this.changes || {}; + + _.each( changedRows, function( row, id ) { + changes[ id ] = _.extend( changes[ id ] || { zone_id : id }, row ); + } ); + + this.changes = changes; + this.trigger( 'change:zones' ); + }, + discardChanges: function( id ) { + var changes = this.changes || {}, + set_position = null, + zones = _.indexBy( this.get( 'zones' ), 'zone_id' ); + + // Find current set position if it has moved since last save + if ( changes[ id ] && changes[ id ].zone_order !== undefined ) { + set_position = changes[ id ].zone_order; + } + + // Delete all changes + delete changes[ id ]; + + // If the position was set, and this zone does exist in DB, set the position again so the changes are not lost. + if ( set_position !== null && zones[ id ] && zones[ id ].zone_order !== set_position ) { + changes[ id ] = _.extend( changes[ id ] || {}, { zone_id : id, zone_order : set_position } ); + } + + this.changes = changes; + + // No changes? Disable save button. + if ( 0 === _.size( this.changes ) ) { + shippingZoneView.clearUnloadConfirmation(); + } + }, + save: function() { + if ( _.size( this.changes ) ) { + $.post( ajaxurl + ( ajaxurl.indexOf( '?' ) > 0 ? '&' : '?' ) + 'action=woocommerce_shipping_zones_save_changes', { + wc_shipping_zones_nonce : data.wc_shipping_zones_nonce, + changes : this.changes + }, this.onSaveResponse, 'json' ); + } else { + shippingZone.trigger( 'saved:zones' ); + } + }, + onSaveResponse: function( response, textStatus ) { + if ( 'success' === textStatus ) { + if ( response.success ) { + shippingZone.set( 'zones', response.data.zones ); + shippingZone.trigger( 'change:zones' ); + shippingZone.changes = {}; + shippingZone.trigger( 'saved:zones' ); + } else { + window.alert( data.strings.save_failed ); + } + } + } + } ), + + // Backbone view + ShippingZoneView = Backbone.View.extend({ + rowTemplate: $row_template, + initialize: function() { + this.listenTo( this.model, 'change:zones', this.setUnloadConfirmation ); + this.listenTo( this.model, 'saved:zones', this.clearUnloadConfirmation ); + this.listenTo( this.model, 'saved:zones', this.render ); + $tbody.on( 'change', { view: this }, this.updateModelOnChange ); + $tbody.on( 'sortupdate', { view: this }, this.updateModelOnSort ); + $( window ).on( 'beforeunload', { view: this }, this.unloadConfirmation ); + $( document.body ).on( 'click', '.wc-shipping-zone-add', { view: this }, this.onAddNewRow ); + }, + block: function() { + $( this.el ).block({ + message: null, + overlayCSS: { + background: '#fff', + opacity: 0.6 + } + }); + }, + unblock: function() { + $( this.el ).unblock(); + }, + render: function() { + var zones = _.indexBy( this.model.get( 'zones' ), 'zone_id' ), + view = this; + + view.$el.empty(); + view.unblock(); + + if ( _.size( zones ) ) { + // Sort zones + zones = _.sortBy( zones, function( zone ) { + return parseInt( zone.zone_order, 10 ); + } ); + + // Populate $tbody with the current zones + $.each( zones, function( id, rowData ) { + view.renderRow( rowData ); + } ); + } else { + view.$el.append( $blank_template ); + } + + view.initRows(); + }, + renderRow: function( rowData ) { + var view = this; + view.$el.append( view.rowTemplate( rowData ) ); + view.initRow( rowData ); + }, + initRow: function( rowData ) { + var view = this; + var $tr = view.$el.find( 'tr[data-id="' + rowData.zone_id + '"]'); + + // List shipping methods + view.renderShippingMethods( rowData.zone_id, rowData.shipping_methods ); + $tr.find( '.wc-shipping-zone-delete' ).on( 'click', { view: this }, this.onDeleteRow ); + }, + initRows: function() { + // Stripe + if ( 0 === ( $( 'tbody.wc-shipping-zone-rows tr' ).length % 2 ) ) { + $table.find( 'tbody.wc-shipping-zone-rows' ).next( 'tbody' ).find( 'tr' ).addClass( 'odd' ); + } else { + $table.find( 'tbody.wc-shipping-zone-rows' ).next( 'tbody' ).find( 'tr' ).removeClass( 'odd' ); + } + // Tooltips + $( '#tiptip_holder' ).removeAttr( 'style' ); + $( '#tiptip_arrow' ).removeAttr( 'style' ); + $( '.tips' ).tipTip({ 'attribute': 'data-tip', 'fadeIn': 50, 'fadeOut': 50, 'delay': 50 }); + }, + renderShippingMethods: function( zone_id, shipping_methods ) { + var $tr = $( '.wc-shipping-zones tr[data-id="' + zone_id + '"]'); + var $method_list = $tr.find('.wc-shipping-zone-methods ul'); + + $method_list.find( '.wc-shipping-zone-method' ).remove(); + + if ( _.size( shipping_methods ) ) { + shipping_methods = _.sortBy( shipping_methods, function( method ) { + return parseInt( method.method_order, 10 ); + } ); + + _.each( shipping_methods, function( shipping_method ) { + var class_name = 'method_disabled'; + + if ( 'yes' === shipping_method.enabled ) { + class_name = 'method_enabled'; + } + + $method_list.append( '
  • ' + shipping_method.title + '
  • ' ); + } ); + } else { + $method_list.append( '
  • ' + data.strings.no_shipping_methods_offered + '
  • ' ); + } + }, + onDeleteRow: function( event ) { + var view = event.data.view, + model = view.model, + zones = _.indexBy( model.get( 'zones' ), 'zone_id' ), + changes = {}, + row = $( this ).closest('tr'), + zone_id = row.data('id'); + + event.preventDefault(); + + if ( window.confirm( data.strings.delete_confirmation_msg ) ) { + if ( zones[ zone_id ] ) { + delete zones[ zone_id ]; + changes[ zone_id ] = _.extend( changes[ zone_id ] || {}, { deleted : 'deleted' } ); + model.set( 'zones', zones ); + model.logChanges( changes ); + event.data.view.block(); + event.data.view.model.save(); + } + } + }, + setUnloadConfirmation: function() { + this.needsUnloadConfirm = true; + $save_button.prop( 'disabled', false ); + }, + clearUnloadConfirmation: function() { + this.needsUnloadConfirm = false; + $save_button.prop( 'disabled', true ); + }, + unloadConfirmation: function( event ) { + if ( event.data.view.needsUnloadConfirm ) { + event.returnValue = data.strings.unload_confirmation_msg; + window.event.returnValue = data.strings.unload_confirmation_msg; + return data.strings.unload_confirmation_msg; + } + }, + updateModelOnChange: function( event ) { + var model = event.data.view.model, + $target = $( event.target ), + zone_id = $target.closest( 'tr' ).data( 'id' ), + attribute = $target.data( 'attribute' ), + value = $target.val(), + zones = _.indexBy( model.get( 'zones' ), 'zone_id' ), + changes = {}; + + if ( ! zones[ zone_id ] || zones[ zone_id ][ attribute ] !== value ) { + changes[ zone_id ] = {}; + changes[ zone_id ][ attribute ] = value; + } + + model.logChanges( changes ); + }, + updateModelOnSort: function( event ) { + var view = event.data.view, + model = view.model, + zones = _.indexBy( model.get( 'zones' ), 'zone_id' ), + rows = $( 'tbody.wc-shipping-zone-rows tr' ), + changes = {}; + + // Update sorted row position + _.each( rows, function( row ) { + var zone_id = $( row ).data( 'id' ), + old_position = null, + new_position = parseInt( $( row ).index(), 10 ); + + if ( zones[ zone_id ] ) { + old_position = parseInt( zones[ zone_id ].zone_order, 10 ); + } + + if ( old_position !== new_position ) { + changes[ zone_id ] = _.extend( changes[ zone_id ] || {}, { zone_order : new_position } ); + } + } ); + + if ( _.size( changes ) ) { + model.logChanges( changes ); + event.data.view.block(); + event.data.view.model.save(); + } + } + } ), + shippingZone = new ShippingZone({ + zones: data.zones + } ), + shippingZoneView = new ShippingZoneView({ + model: shippingZone, + el: $tbody + } ); + + shippingZoneView.render(); + + $tbody.sortable({ + items: 'tr', + cursor: 'move', + axis: 'y', + handle: 'td.wc-shipping-zone-sort', + scrollSensitivity: 40 + }); + }); +})( jQuery, shippingZonesLocalizeScript, wp, ajaxurl ); diff --git a/assets/js/admin/wc-shipping-zones.min.js b/assets/js/admin/wc-shipping-zones.min.js new file mode 100644 index 00000000000..3bfee69d1fd --- /dev/null +++ b/assets/js/admin/wc-shipping-zones.min.js @@ -0,0 +1 @@ +!function(a,b,c,d){a(function(){var e=a(".wc-shipping-zones"),f=a(".wc-shipping-zone-rows"),g=a(".wc-shipping-zone-save"),h=c.template("wc-shipping-zone-row"),i=c.template("wc-shipping-zone-row-blank"),j=Backbone.Model.extend({changes:{},logChanges:function(a){var b=this.changes||{};_.each(a,function(a,c){b[c]=_.extend(b[c]||{zone_id:c},a)}),this.changes=b,this.trigger("change:zones")},discardChanges:function(a){var b=this.changes||{},c=null,d=_.indexBy(this.get("zones"),"zone_id");b[a]&&void 0!==b[a].zone_order&&(c=b[a].zone_order),delete b[a],null!==c&&d[a]&&d[a].zone_order!==c&&(b[a]=_.extend(b[a]||{},{zone_id:a,zone_order:c})),this.changes=b,0===_.size(this.changes)&&m.clearUnloadConfirmation()},save:function(){_.size(this.changes)?a.post(d+(d.indexOf("?")>0?"&":"?")+"action=woocommerce_shipping_zones_save_changes",{wc_shipping_zones_nonce:b.wc_shipping_zones_nonce,changes:this.changes},this.onSaveResponse,"json"):l.trigger("saved:zones")},onSaveResponse:function(a,c){"success"===c&&(a.success?(l.set("zones",a.data.zones),l.trigger("change:zones"),l.changes={},l.trigger("saved:zones")):window.alert(b.strings.save_failed))}}),k=Backbone.View.extend({rowTemplate:h,initialize:function(){this.listenTo(this.model,"change:zones",this.setUnloadConfirmation),this.listenTo(this.model,"saved:zones",this.clearUnloadConfirmation),this.listenTo(this.model,"saved:zones",this.render),f.on("change",{view:this},this.updateModelOnChange),f.on("sortupdate",{view:this},this.updateModelOnSort),a(window).on("beforeunload",{view:this},this.unloadConfirmation),a(document.body).on("click",".wc-shipping-zone-add",{view:this},this.onAddNewRow)},block:function(){a(this.el).block({message:null,overlayCSS:{background:"#fff",opacity:.6}})},unblock:function(){a(this.el).unblock()},render:function(){var b=_.indexBy(this.model.get("zones"),"zone_id"),c=this;c.$el.empty(),c.unblock(),_.size(b)?(b=_.sortBy(b,function(a){return parseInt(a.zone_order,10)}),a.each(b,function(a,b){c.renderRow(b)})):c.$el.append(i),c.initRows()},renderRow:function(a){var b=this;b.$el.append(b.rowTemplate(a)),b.initRow(a)},initRow:function(a){var b=this,c=b.$el.find('tr[data-id="'+a.zone_id+'"]');b.renderShippingMethods(a.zone_id,a.shipping_methods),c.find(".wc-shipping-zone-delete").on("click",{view:this},this.onDeleteRow)},initRows:function(){0===a("tbody.wc-shipping-zone-rows tr").length%2?e.find("tbody.wc-shipping-zone-rows").next("tbody").find("tr").addClass("odd"):e.find("tbody.wc-shipping-zone-rows").next("tbody").find("tr").removeClass("odd"),a("#tiptip_holder").removeAttr("style"),a("#tiptip_arrow").removeAttr("style"),a(".tips").tipTip({attribute:"data-tip",fadeIn:50,fadeOut:50,delay:50})},renderShippingMethods:function(c,d){var e=a('.wc-shipping-zones tr[data-id="'+c+'"]'),f=e.find(".wc-shipping-zone-methods ul");f.find(".wc-shipping-zone-method").remove(),_.size(d)?(d=_.sortBy(d,function(a){return parseInt(a.method_order,10)}),_.each(d,function(a){var b="method_disabled";"yes"===a.enabled&&(b="method_enabled"),f.append('
  • '+a.title+"
  • ")})):f.append('
  • '+b.strings.no_shipping_methods_offered+"
  • ")},onDeleteRow:function(c){var d=c.data.view,e=d.model,f=_.indexBy(e.get("zones"),"zone_id"),g={},h=a(this).closest("tr"),i=h.data("id");c.preventDefault(),window.confirm(b.strings.delete_confirmation_msg)&&f[i]&&(delete f[i],g[i]=_.extend(g[i]||{},{deleted:"deleted"}),e.set("zones",f),e.logChanges(g),c.data.view.block(),c.data.view.model.save())},setUnloadConfirmation:function(){this.needsUnloadConfirm=!0,g.prop("disabled",!1)},clearUnloadConfirmation:function(){this.needsUnloadConfirm=!1,g.prop("disabled",!0)},unloadConfirmation:function(a){if(a.data.view.needsUnloadConfirm)return a.returnValue=b.strings.unload_confirmation_msg,window.event.returnValue=b.strings.unload_confirmation_msg,b.strings.unload_confirmation_msg},updateModelOnChange:function(b){var c=b.data.view.model,d=a(b.target),e=d.closest("tr").data("id"),f=d.data("attribute"),g=d.val(),h=_.indexBy(c.get("zones"),"zone_id"),i={};h[e]&&h[e][f]===g||(i[e]={},i[e][f]=g),c.logChanges(i)},updateModelOnSort:function(b){var c=b.data.view,d=c.model,e=_.indexBy(d.get("zones"),"zone_id"),f=a("tbody.wc-shipping-zone-rows tr"),g={};_.each(f,function(b){var c=a(b).data("id"),d=null,f=parseInt(a(b).index(),10);e[c]&&(d=parseInt(e[c].zone_order,10)),d!==f&&(g[c]=_.extend(g[c]||{},{zone_order:f}))}),_.size(g)&&(d.logChanges(g),b.data.view.block(),b.data.view.model.save())}}),l=new j({zones:b.zones}),m=new k({model:l,el:f});m.render(),f.sortable({items:"tr",cursor:"move",axis:"y",handle:"td.wc-shipping-zone-sort",scrollSensitivity:40})})}(jQuery,shippingZonesLocalizeScript,wp,ajaxurl); \ No newline at end of file diff --git a/assets/js/admin/woocommerce_admin.js b/assets/js/admin/woocommerce_admin.js index be14474be02..e36b7e6b846 100644 --- a/assets/js/admin/woocommerce_admin.js +++ b/assets/js/admin/woocommerce_admin.js @@ -7,10 +7,11 @@ jQuery( function ( $ ) { // Field validation error tips $( document.body ) + .on( 'wc_add_error_tip', function( e, element, error_type ) { var offset = element.position(); - if ( element.parent().find( '.wc_error_tip' ).size() === 0 ) { + if ( element.parent().find( '.wc_error_tip' ).length === 0 ) { element.after( '
    ' + woocommerce_admin[error_type] + '
    ' ); element.parent().find( '.wc_error_tip' ) .css( 'left', offset.left + element.width() - ( element.width() / 2 ) - ( $( '.wc_error_tip' ).width() / 2 ) ) @@ -18,51 +19,78 @@ jQuery( function ( $ ) { .fadeIn( '100' ); } }) + .on( 'wc_remove_error_tip', function( e, element, error_type ) { - element.parent().find( '.wc_error_tip.' + error_type ).remove(); + element.parent().find( '.wc_error_tip.' + error_type ).fadeOut( '100', function() { $( this ).remove(); } ); }) + .on( 'click', function() { $( '.wc_error_tip' ).fadeOut( '100', function() { $( this ).remove(); } ); }) + .on( 'blur', '.wc_input_decimal[type=text], .wc_input_price[type=text], .wc_input_country_iso[type=text]', function() { $( '.wc_error_tip' ).fadeOut( '100', function() { $( this ).remove(); } ); }) - .on( 'keyup change', '.wc_input_price[type=text]', function() { + + .on( 'change', '.wc_input_price[type=text], .wc_input_decimal[type=text], .wc-order-totals #refund_amount[type=text]', function() { + var regex; + + if ( $( this ).is( '.wc_input_price' ) || $( this ).is( '#refund_amount' ) ) { + regex = new RegExp( '[^\-0-9\%\\' + woocommerce_admin.mon_decimal_point + ']+', 'gi' ); + } else { + regex = new RegExp( '[^\-0-9\%\\' + woocommerce_admin.decimal_point + ']+', 'gi' ); + } + var value = $( this ).val(); - var regex = new RegExp( '[^\-0-9\%\\' + woocommerce_admin.mon_decimal_point + ']+', 'gi' ); var newvalue = value.replace( regex, '' ); if ( value !== newvalue ) { $( this ).val( newvalue ); - $( document.body ).triggerHandler( 'wc_add_error_tip', [ $( this ), 'i18n_mon_decimal_error' ] ); - } else { - $( document.body ).triggerHandler( 'wc_remove_error_tip', [ $( this ), 'i18n_mon_decimal_error' ] ); } }) - .on( 'keyup change', '.wc_input_decimal[type=text]', function() { + + .on( 'keyup', '.wc_input_price[type=text], .wc_input_decimal[type=text], .wc_input_country_iso[type=text], .wc-order-totals #refund_amount[type=text]', function() { + var regex, error; + + if ( $( this ).is( '.wc_input_price' ) || $( this ).is( '#refund_amount' ) ) { + regex = new RegExp( '[^\-0-9\%\\' + woocommerce_admin.mon_decimal_point + ']+', 'gi' ); + error = 'i18n_mon_decimal_error'; + } else if ( $( this ).is( '.wc_input_country_iso' ) ) { + regex = new RegExp( '([^A-Z])+|(.){3,}', 'im' ); + error = 'i18n_country_iso_error'; + } else { + regex = new RegExp( '[^\-0-9\%\\' + woocommerce_admin.decimal_point + ']+', 'gi' ); + error = 'i18n_decimal_error'; + } + var value = $( this ).val(); - var regex = new RegExp( '[^\-0-9\%\\' + woocommerce_admin.decimal_point + ']+', 'gi' ); var newvalue = value.replace( regex, '' ); if ( value !== newvalue ) { - $( this ).val( newvalue ); - $( document.body ).triggerHandler( 'wc_add_error_tip', [ $( this ), 'i18n_decimal_error' ] ); + $( document.body ).triggerHandler( 'wc_add_error_tip', [ $( this ), error ] ); } else { - $( document.body ).triggerHandler( 'wc_remove_error_tip', [ $( this ), 'i18n_decimal_error' ] ); + $( document.body ).triggerHandler( 'wc_remove_error_tip', [ $( this ), error ] ); } }) - .on( 'keyup change', '.wc_input_country_iso[type=text]', function() { - var value = $( this ).val(); - var regex = new RegExp( '^([A-Z])?([A-Z])$' ); - if ( ! regex.test( value ) ) { + .on( 'change', '#_sale_price.wc_input_price[type=text], .wc_input_price[name^=variable_sale_price]', function() { + var sale_price_field = $( this ), regular_price_field; + + if( sale_price_field.attr( 'name' ).indexOf( 'variable' ) !== -1 ) { + regular_price_field = sale_price_field.parents( '.variable_pricing' ).find( '.wc_input_price[name^=variable_regular_price]' ); + } else { + regular_price_field = $( '#_regular_price' ); + } + + var sale_price = parseFloat( window.accounting.unformat( sale_price_field.val(), woocommerce_admin.mon_decimal_point ) ); + var regular_price = parseFloat( window.accounting.unformat( regular_price_field.val(), woocommerce_admin.mon_decimal_point ) ); + + if ( sale_price >= regular_price ) { $( this ).val( '' ); - $( document.body ).triggerHandler( 'wc_add_error_tip', [ $( this ), 'i18n_country_iso_error' ] ); - } else { - $( document.body ).triggerHandler( 'wc_remove_error_tip', [ $( this ), 'i18n_country_iso_error' ] ); } }) - .on( 'keyup change', '#_sale_price.wc_input_price[type=text], .wc_input_price[name^=variable_sale_price]', function() { + + .on( 'keyup', '#_sale_price.wc_input_price[type=text], .wc_input_price[name^=variable_sale_price]', function() { var sale_price_field = $( this ), regular_price_field; if( sale_price_field.attr( 'name' ).indexOf( 'variable' ) !== -1 ) { @@ -79,21 +107,26 @@ jQuery( function ( $ ) { } else { $( document.body ).triggerHandler( 'wc_remove_error_tip', [ $(this), 'i18_sale_less_than_regular_error' ] ); } + }) + + .on( 'init_tooltips', function() { + var tiptip_args = { + 'attribute': 'data-tip', + 'fadeIn': 50, + 'fadeOut': 50, + 'delay': 200 + }; + + $( '.tips, .help_tip, .woocommerce-help-tip' ).tipTip( tiptip_args ); + + // Add tiptip to parent element for widefat tables + $( '.parent-tips' ).each( function() { + $( this ).closest( 'a, th' ).attr( 'data-tip', $( this ).data( 'tip' ) ).tipTip( tiptip_args ).css( 'cursor', 'help' ); + }); }); // Tooltips - var tiptip_args = { - 'attribute': 'data-tip', - 'fadeIn': 50, - 'fadeOut': 50, - 'delay': 200 - }; - $( '.tips, .help_tip, .woocommerce-help-tip' ).tipTip( tiptip_args ); - - // Add tiptip to parent element for widefat tables - $( '.parent-tips' ).each( function() { - $( this ).closest( 'a, th' ).attr( 'data-tip', $( this ).data( 'tip' ) ).tipTip( tiptip_args ).css( 'cursor', 'help' ); - }); + $( document.body ).trigger( 'init_tooltips' ); // wc_input_table tables $( '.wc_input_table.sortable tbody' ).sortable({ @@ -115,7 +148,7 @@ jQuery( function ( $ ) { $( '.wc_input_table .remove_rows' ).click( function() { var $tbody = $( this ).closest( '.wc_input_table' ).find( 'tbody' ); - if ( $tbody.find( 'tr.current' ).size() > 0 ) { + if ( $tbody.find( 'tr.current' ).length > 0 ) { var $current = $tbody.find( 'tr.current' ); $current.each( function() { $( this ).remove(); @@ -125,15 +158,16 @@ jQuery( function ( $ ) { }); var controlled = false; - var shifted = false; - var hasFocus = false; + var shifted = false; + var hasFocus = false; $( document.body ).bind( 'keyup keydown', function( e ) { - shifted = e.shiftKey; controlled = e.ctrlKey || e.metaKey; + shifted = e.shiftKey; + controlled = e.ctrlKey || e.metaKey; }); $( '.wc_input_table' ).on( 'focus click', 'input', function( e ) { - var $this_table = $( this ).closest( 'table' ); + var $this_table = $( this ).closest( 'table, tbody' ); var $this_row = $( this ).closest( 'tr' ); if ( ( e.type === 'focus' && hasFocus !== $this_row.index() ) || ( e.type === 'click' && $( this ).is( ':focus' ) ) ) { @@ -146,7 +180,7 @@ jQuery( function ( $ ) { $( 'tr', $this_table ).removeClass( 'current' ); $this_row.addClass( 'selected_now' ).addClass( 'current' ); - if ( $( 'tr.last_selected', $this_table ).size() > 0 ) { + if ( $( 'tr.last_selected', $this_table ).length > 0 ) { if ( $this_row.index() > $( 'tr.last_selected', $this_table ).index() ) { $( 'tr', $this_table ).slice( $( 'tr.last_selected', $this_table ).index(), $this_row.index() ).addClass( 'current' ); } else { @@ -221,4 +255,11 @@ jQuery( function ( $ ) { // Attribute term table $( 'table.attributes-table tbody tr:nth-child(odd)' ).addClass( 'alternate' ); + + // Load videos when help button is clicked. + $( '#contextual-help-link' ).on( 'click', function() { + var frame = $( '#tab-panel-woocommerce_guided_tour_tab iframe' ); + + frame.attr( 'src', frame.data( 'src' ) ); + }); }); diff --git a/assets/js/admin/woocommerce_admin.min.js b/assets/js/admin/woocommerce_admin.min.js index 73564cbb26c..fc6d848b306 100644 --- a/assets/js/admin/woocommerce_admin.min.js +++ b/assets/js/admin/woocommerce_admin.min.js @@ -1 +1 @@ -jQuery(function(a){a(document.body).on("wc_add_error_tip",function(b,c,d){var e=c.position();0===c.parent().find(".wc_error_tip").size()&&(c.after('
    '+woocommerce_admin[d]+"
    "),c.parent().find(".wc_error_tip").css("left",e.left+c.width()-c.width()/2-a(".wc_error_tip").width()/2).css("top",e.top+c.height()).fadeIn("100"))}).on("wc_remove_error_tip",function(a,b,c){b.parent().find(".wc_error_tip."+c).remove()}).on("click",function(){a(".wc_error_tip").fadeOut("100",function(){a(this).remove()})}).on("blur",".wc_input_decimal[type=text], .wc_input_price[type=text], .wc_input_country_iso[type=text]",function(){a(".wc_error_tip").fadeOut("100",function(){a(this).remove()})}).on("keyup change",".wc_input_price[type=text]",function(){var b=a(this).val(),c=new RegExp("[^-0-9%\\"+woocommerce_admin.mon_decimal_point+"]+","gi"),d=b.replace(c,"");b!==d?(a(this).val(d),a(document.body).triggerHandler("wc_add_error_tip",[a(this),"i18n_mon_decimal_error"])):a(document.body).triggerHandler("wc_remove_error_tip",[a(this),"i18n_mon_decimal_error"])}).on("keyup change",".wc_input_decimal[type=text]",function(){var b=a(this).val(),c=new RegExp("[^-0-9%\\"+woocommerce_admin.decimal_point+"]+","gi"),d=b.replace(c,"");b!==d?(a(this).val(d),a(document.body).triggerHandler("wc_add_error_tip",[a(this),"i18n_decimal_error"])):a(document.body).triggerHandler("wc_remove_error_tip",[a(this),"i18n_decimal_error"])}).on("keyup change",".wc_input_country_iso[type=text]",function(){var b=a(this).val(),c=new RegExp("^([A-Z])?([A-Z])$");c.test(b)?a(document.body).triggerHandler("wc_remove_error_tip",[a(this),"i18n_country_iso_error"]):(a(this).val(""),a(document.body).triggerHandler("wc_add_error_tip",[a(this),"i18n_country_iso_error"]))}).on("keyup change","#_sale_price.wc_input_price[type=text], .wc_input_price[name^=variable_sale_price]",function(){var b,c=a(this);b=-1!==c.attr("name").indexOf("variable")?c.parents(".variable_pricing").find(".wc_input_price[name^=variable_regular_price]"):a("#_regular_price");var d=parseFloat(window.accounting.unformat(c.val(),woocommerce_admin.mon_decimal_point)),e=parseFloat(window.accounting.unformat(b.val(),woocommerce_admin.mon_decimal_point));d>=e?a(document.body).triggerHandler("wc_add_error_tip",[a(this),"i18_sale_less_than_regular_error"]):a(document.body).triggerHandler("wc_remove_error_tip",[a(this),"i18_sale_less_than_regular_error"])});var b={attribute:"data-tip",fadeIn:50,fadeOut:50,delay:200};a(".tips, .help_tip, .woocommerce-help-tip").tipTip(b),a(".parent-tips").each(function(){a(this).closest("a, th").attr("data-tip",a(this).data("tip")).tipTip(b).css("cursor","help")}),a(".wc_input_table.sortable tbody").sortable({items:"tr",cursor:"move",axis:"y",scrollSensitivity:40,forcePlaceholderSize:!0,helper:"clone",opacity:.65,placeholder:"wc-metabox-sortable-placeholder",start:function(a,b){b.item.css("background-color","#f6f6f6")},stop:function(a,b){b.item.removeAttr("style")}}),a(".wc_input_table .remove_rows").click(function(){var b=a(this).closest(".wc_input_table").find("tbody");if(b.find("tr.current").size()>0){var c=b.find("tr.current");c.each(function(){a(this).remove()})}return!1});var c=!1,d=!1,e=!1;a(document.body).bind("keyup keydown",function(a){d=a.shiftKey,c=a.ctrlKey||a.metaKey}),a(".wc_input_table").on("focus click","input",function(b){var f=a(this).closest("table"),g=a(this).closest("tr");("focus"===b.type&&e!==g.index()||"click"===b.type&&a(this).is(":focus"))&&(e=g.index(),d||c?d?(a("tr",f).removeClass("current"),g.addClass("selected_now").addClass("current"),a("tr.last_selected",f).size()>0&&(g.index()>a("tr.last_selected",f).index()?a("tr",f).slice(a("tr.last_selected",f).index(),g.index()).addClass("current"):a("tr",f).slice(g.index(),a("tr.last_selected",f).index()+1).addClass("current")),a("tr",f).removeClass("last_selected"),g.addClass("last_selected")):(a("tr",f).removeClass("last_selected"),c&&a(this).closest("tr").is(".current")?g.removeClass("current"):g.addClass("current").addClass("last_selected")):(a("tr",f).removeClass("current").removeClass("last_selected"),g.addClass("current").addClass("last_selected")),a("tr",f).removeClass("selected_now"))}).on("blur","input",function(){e=!1}),a(".woocommerce_page_wc-settings .shippingrows tbody tr:even, table.attributes-table tbody tr:nth-child(odd)").addClass("alternate"),a(document.body).on("click",".show_order_items",function(){return a(this).closest("td").find("table").toggle(),!1}),a("select.availability").change(function(){"all"===a(this).val()?a(this).closest("tr").next("tr").hide():a(this).closest("tr").next("tr").show()}).change(),a(".hide_options_if_checked").each(function(){a(this).find("input:eq(0)").change(function(){a(this).is(":checked")?a(this).closest("fieldset, tr").nextUntil(".hide_options_if_checked, .show_options_if_checked",".hidden_option").hide():a(this).closest("fieldset, tr").nextUntil(".hide_options_if_checked, .show_options_if_checked",".hidden_option").show()}).change()}),a(".show_options_if_checked").each(function(){a(this).find("input:eq(0)").change(function(){a(this).is(":checked")?a(this).closest("fieldset, tr").nextUntil(".hide_options_if_checked, .show_options_if_checked",".hidden_option").show():a(this).closest("fieldset, tr").nextUntil(".hide_options_if_checked, .show_options_if_checked",".hidden_option").hide()}).change()}),a("input#woocommerce_demo_store").change(function(){a(this).is(":checked")?a("#woocommerce_demo_store_notice").closest("tr").show():a("#woocommerce_demo_store_notice").closest("tr").hide()}).change(),a("table.attributes-table tbody tr:nth-child(odd)").addClass("alternate")}); \ No newline at end of file +jQuery(function(a){a(document.body).on("wc_add_error_tip",function(b,c,d){var e=c.position();0===c.parent().find(".wc_error_tip").length&&(c.after('
    '+woocommerce_admin[d]+"
    "),c.parent().find(".wc_error_tip").css("left",e.left+c.width()-c.width()/2-a(".wc_error_tip").width()/2).css("top",e.top+c.height()).fadeIn("100"))}).on("wc_remove_error_tip",function(b,c,d){c.parent().find(".wc_error_tip."+d).fadeOut("100",function(){a(this).remove()})}).on("click",function(){a(".wc_error_tip").fadeOut("100",function(){a(this).remove()})}).on("blur",".wc_input_decimal[type=text], .wc_input_price[type=text], .wc_input_country_iso[type=text]",function(){a(".wc_error_tip").fadeOut("100",function(){a(this).remove()})}).on("change",".wc_input_price[type=text], .wc_input_decimal[type=text], .wc-order-totals #refund_amount[type=text]",function(){var b;b=a(this).is(".wc_input_price")||a(this).is("#refund_amount")?new RegExp("[^-0-9%\\"+woocommerce_admin.mon_decimal_point+"]+","gi"):new RegExp("[^-0-9%\\"+woocommerce_admin.decimal_point+"]+","gi");var c=a(this).val(),d=c.replace(b,"");c!==d&&a(this).val(d)}).on("keyup",".wc_input_price[type=text], .wc_input_decimal[type=text], .wc_input_country_iso[type=text], .wc-order-totals #refund_amount[type=text]",function(){var b,c;a(this).is(".wc_input_price")||a(this).is("#refund_amount")?(b=new RegExp("[^-0-9%\\"+woocommerce_admin.mon_decimal_point+"]+","gi"),c="i18n_mon_decimal_error"):a(this).is(".wc_input_country_iso")?(b=new RegExp("([^A-Z])+|(.){3,}","im"),c="i18n_country_iso_error"):(b=new RegExp("[^-0-9%\\"+woocommerce_admin.decimal_point+"]+","gi"),c="i18n_decimal_error");var d=a(this).val(),e=d.replace(b,"");d!==e?a(document.body).triggerHandler("wc_add_error_tip",[a(this),c]):a(document.body).triggerHandler("wc_remove_error_tip",[a(this),c])}).on("change","#_sale_price.wc_input_price[type=text], .wc_input_price[name^=variable_sale_price]",function(){var b,c=a(this);b=c.attr("name").indexOf("variable")!==-1?c.parents(".variable_pricing").find(".wc_input_price[name^=variable_regular_price]"):a("#_regular_price");var d=parseFloat(window.accounting.unformat(c.val(),woocommerce_admin.mon_decimal_point)),e=parseFloat(window.accounting.unformat(b.val(),woocommerce_admin.mon_decimal_point));d>=e&&a(this).val("")}).on("keyup","#_sale_price.wc_input_price[type=text], .wc_input_price[name^=variable_sale_price]",function(){var b,c=a(this);b=c.attr("name").indexOf("variable")!==-1?c.parents(".variable_pricing").find(".wc_input_price[name^=variable_regular_price]"):a("#_regular_price");var d=parseFloat(window.accounting.unformat(c.val(),woocommerce_admin.mon_decimal_point)),e=parseFloat(window.accounting.unformat(b.val(),woocommerce_admin.mon_decimal_point));d>=e?a(document.body).triggerHandler("wc_add_error_tip",[a(this),"i18_sale_less_than_regular_error"]):a(document.body).triggerHandler("wc_remove_error_tip",[a(this),"i18_sale_less_than_regular_error"])}).on("init_tooltips",function(){var b={attribute:"data-tip",fadeIn:50,fadeOut:50,delay:200};a(".tips, .help_tip, .woocommerce-help-tip").tipTip(b),a(".parent-tips").each(function(){a(this).closest("a, th").attr("data-tip",a(this).data("tip")).tipTip(b).css("cursor","help")})}),a(document.body).trigger("init_tooltips"),a(".wc_input_table.sortable tbody").sortable({items:"tr",cursor:"move",axis:"y",scrollSensitivity:40,forcePlaceholderSize:!0,helper:"clone",opacity:.65,placeholder:"wc-metabox-sortable-placeholder",start:function(a,b){b.item.css("background-color","#f6f6f6")},stop:function(a,b){b.item.removeAttr("style")}}),a(".wc_input_table .remove_rows").click(function(){var b=a(this).closest(".wc_input_table").find("tbody");if(b.find("tr.current").length>0){var c=b.find("tr.current");c.each(function(){a(this).remove()})}return!1});var b=!1,c=!1,d=!1;a(document.body).bind("keyup keydown",function(a){c=a.shiftKey,b=a.ctrlKey||a.metaKey}),a(".wc_input_table").on("focus click","input",function(e){var f=a(this).closest("table, tbody"),g=a(this).closest("tr");("focus"===e.type&&d!==g.index()||"click"===e.type&&a(this).is(":focus"))&&(d=g.index(),c||b?c?(a("tr",f).removeClass("current"),g.addClass("selected_now").addClass("current"),a("tr.last_selected",f).length>0&&(g.index()>a("tr.last_selected",f).index()?a("tr",f).slice(a("tr.last_selected",f).index(),g.index()).addClass("current"):a("tr",f).slice(g.index(),a("tr.last_selected",f).index()+1).addClass("current")),a("tr",f).removeClass("last_selected"),g.addClass("last_selected")):(a("tr",f).removeClass("last_selected"),b&&a(this).closest("tr").is(".current")?g.removeClass("current"):g.addClass("current").addClass("last_selected")):(a("tr",f).removeClass("current").removeClass("last_selected"),g.addClass("current").addClass("last_selected")),a("tr",f).removeClass("selected_now"))}).on("blur","input",function(){d=!1}),a(".woocommerce_page_wc-settings .shippingrows tbody tr:even, table.attributes-table tbody tr:nth-child(odd)").addClass("alternate"),a(document.body).on("click",".show_order_items",function(){return a(this).closest("td").find("table").toggle(),!1}),a("select.availability").change(function(){"all"===a(this).val()?a(this).closest("tr").next("tr").hide():a(this).closest("tr").next("tr").show()}).change(),a(".hide_options_if_checked").each(function(){a(this).find("input:eq(0)").change(function(){a(this).is(":checked")?a(this).closest("fieldset, tr").nextUntil(".hide_options_if_checked, .show_options_if_checked",".hidden_option").hide():a(this).closest("fieldset, tr").nextUntil(".hide_options_if_checked, .show_options_if_checked",".hidden_option").show()}).change()}),a(".show_options_if_checked").each(function(){a(this).find("input:eq(0)").change(function(){a(this).is(":checked")?a(this).closest("fieldset, tr").nextUntil(".hide_options_if_checked, .show_options_if_checked",".hidden_option").show():a(this).closest("fieldset, tr").nextUntil(".hide_options_if_checked, .show_options_if_checked",".hidden_option").hide()}).change()}),a("input#woocommerce_demo_store").change(function(){a(this).is(":checked")?a("#woocommerce_demo_store_notice").closest("tr").show():a("#woocommerce_demo_store_notice").closest("tr").hide()}).change(),a("table.attributes-table tbody tr:nth-child(odd)").addClass("alternate"),a("#contextual-help-link").on("click",function(){var b=a("#tab-panel-woocommerce_guided_tour_tab iframe");b.attr("src",b.data("src"))})}); \ No newline at end of file diff --git a/assets/js/chosen/ajax-chosen.jquery.js b/assets/js/chosen/ajax-chosen.jquery.js deleted file mode 100644 index f823a9b103d..00000000000 --- a/assets/js/chosen/ajax-chosen.jquery.js +++ /dev/null @@ -1,81 +0,0 @@ -// Generated by CoffeeScript 1.3.1 - -(function($) { - return $.fn.ajaxChosen = function(settings, callback) { - var chosenXhr, defaultOptions, options, select; - if (settings == null) { - settings = {}; - } - if (callback == null) { - callback = function() {}; - } - defaultOptions = { - minTermLength: 3, - afterTypeDelay: 500, - jsonTermKey: "term" - }; - select = this; - chosenXhr = null; - options = $.extend({}, defaultOptions, settings); - this.chosen(); - return this.each(function() { - return $(this).next('.chosen-container').find(".search-field > input, .chosen-search > input").bind('keyup', function() { - var field, msg, success, val; - val = $.trim($(this).attr('value')); - msg = val.length < options.minTermLength ? "Keep typing..." : "Looking for '" + val + "'"; - select.next('.chosen-container').find('.no-results').text(msg); - if (val === $(this).data('prevVal')) { - return false; - } - $(this).data('prevVal', val); - if (this.timer) { - clearTimeout(this.timer); - } - if (val.length < options.minTermLength) { - return false; - } - field = $(this); - if (!(options.data != null)) { - options.data = {}; - } - options.data[options.jsonTermKey] = val; - if (options.dataCallback != null) { - options.data = options.dataCallback(options.data); - } - success = options.success; - options.success = function(data) { - var items, selected_values; - if (!(data != null)) { - return; - } - selected_values = []; - select.find('option').each(function() { - if (!$(this).is(":selected")) { - return $(this).remove(); - } else { - return selected_values.push($(this).val() + "-" + $(this).text()); - } - }); - items = callback(data); - $.each(items, function(value, text) { - if ($.inArray(value + "-" + text, selected_values) === -1) { - return $("