Commit Graph

559 Commits

Author SHA1 Message Date
Saad Tarhi f8c5e910d2 Shopper → Cart → Can update product quantity (https://github.com/woocommerce/woocommerce-blocks/pull/6025)
* Add XPath expressions

* Add "setCartQuantity" utility function

* Add "productIsInCart" utility function

* Add "update product qty" e2e test

* Clean up test file

* Fix test on headless mode

* Add Increase/Decrease qty test cases

* Decrease the query chain for better maintainability

* Rename expression functions/file for more clarity

* Resolve conflict with trunk

Co-authored-by: Saad Tarhi <saad.tarhi@automattic.com>
2022-03-23 13:51:56 +01:00
Niels Lange 9346e723f3 Shopper can place an order as logged in user (https://github.com/woocommerce/woocommerce-blocks/pull/6037)
* Shopper can place an order as logged in user

* Fill billing address for logged in user

Co-authored-by: Saad Tarhi <saad.trh@gmail.com>
2022-03-23 13:23:22 +01:00
Tarun Vijwani 532952dd31 Critical flows: Shopper → Checkout → Can view empty checkout message (https://github.com/woocommerce/woocommerce-blocks/pull/6042)
* Added new test case for Critical flows: Shopper → Checkout → Can view empty checkout message
2022-03-23 15:17:48 +04:00
Niels Lange 512ae84b09 Shopper → Checkout → Can choose payment option (https://github.com/woocommerce/woocommerce-blocks/pull/5839)
* Shopper can choose payment option

* Empty cart before and after each test

Co-authored-by: Saad Tarhi <saad.trh@gmail.com>
2022-03-23 12:01:33 +01:00
Alba Rincón 13311e7bee Rename Legacy Template block to Classic Template block (https://github.com/woocommerce/woocommerce-blocks/pull/6021)
The internal ID has been kept after a comment by @tjcafferkey. This causes a
bit of inconsistency in the internal code, but it was deemed that it would have
been better as users who have customized templates using this
blocks ID will have saved this in their database, and it would result
in a corrupt block when loaded, and we didn't want to support both IDs at the
moment.

Otherwise, most other references to the legacy template, are now using the word
“classic”.

Co-authored-by: Alba Rincón <alba@albasauatticmbp.home>
2022-03-22 23:34:43 +01:00
Tung Du 64ae9330a2 Shopper → Mini Cart → Can see correct tax (https://github.com/woocommerce/woocommerce-blocks/pull/5979)
Co-authored-by: Lucio Giannotta <lucio.giannotta@a8c.com>
2022-03-22 08:54:06 +07:00
Mike Jolley 8e057a03f5 Remove X- Prefixes from custom headers (https://github.com/woocommerce/woocommerce-blocks/pull/6020)
* Remove X- Prefixes from custom headers

* Fix docs

* Handle deprecated X-WC-Store-API-Nonce header if received

* Send old nonce until future version removes this

* Add todo and cut off date

* wc_deprecated_argument

* Update todo name

* typo

* Back compat in batch

* Flip Nonce logic to make it easier to support both in client bw compat logic
2022-03-11 12:07:08 +00:00
Tarun Vijwani 349c668f01 Critical flows: Shopper → Cart → Can view empty cart message (https://github.com/woocommerce/woocommerce-blocks/pull/6024)
* Added test case for Critical flows: Shopper → Cart → Can view empty cart message
2022-03-10 15:50:07 +04:00
Tarun Vijwani 0530048f4c Critical flows: Shopper → Cart → Can remove product (https://github.com/woocommerce/woocommerce-blocks/pull/6015)
* Added test case for Critical flows: Shopper → Cart → Can remove product
2022-03-10 15:47:53 +04:00
Tomasz Tunik f15d628610 Fix 404 and 500 errors in E2E test logs, editor and front-end. (https://github.com/woocommerce/woocommerce-blocks/pull/5989)
* Change atomic blocks to not use custom webpack build paths

we want to always load lazy loaded components from their default paths
to avoid having to handle importing components in different ways for
regular and atomic component packages

* Add footer parts to test themes

The Site Editor is expecting the footer parts to be there or it will try to
load them anyways and throw a 404. It's not breaking, but it's polluting
the console.

* Use REST API to tear down the templates

Previously, we used a util called `trashAllPosts` which navigated to the post UI
and deleted all the posts to tear down any side-effects of template editing tests.

However, with a [recent change](14e20f72b5),
WP Core removed the UI for those and that made our tests meet a 500 error.

Using the REST API should also make everything faster.

* Remove deprecated pupeteer waitFor usage

was still present in attribute-filter.test.js

* Update package-lock.json

* pin package versions

* Unify all atomic blocks to register on php side

* Remove Atomic Blcoks chunk_translation handling from AllBlocks

Before it was responsible for enabling translations for all the atomic blocks

* Add per atomic block chunk_translation registration

* update @wordpress/e2e-test-utils to 6.0.2

* add optional puppeteer

* pin workflows node version to 16.13.2

* upgrade package-lock

* upgrade package-lock

* set react and react-dom as peerDeps

* remove atomic block registration

Co-authored-by: Lucio Giannotta <lucio.giannotta@a8c.com>
Co-authored-by: Luigi <gigitux@gmail.com>
2022-03-10 11:00:23 +01:00
Niels Lange d9dd7a0df6 Shopper can choose shipping option (https://github.com/woocommerce/woocommerce-blocks/pull/5844) 2022-03-09 13:23:52 +01:00
Alex Florisca fcadeaa2e1 E2E test improvements and consolidatng (https://github.com/woocommerce/woocommerce-blocks/pull/6013)
* Refactor e2e tests slightly for better efficiency

* Add "proceedToCheckout" shopper method & refactor code

* Use "beforeEach" in case we add more test cases

I've kept the "afterAll" function to reset any side effects at the end
of this file's tests

* Use "beforeEach" in "checkout-place-order-as-guest" file

* Use BASE_URL in shopper.block.goToBlockPage

Co-authored-by: Saad Tarhi <saad.tarhi@automattic.com>
2022-03-09 10:16:24 +00:00
Alex Florisca 2e674dd6c0 Critical flow: Can see correct tax (https://github.com/woocommerce/woocommerce-blocks/pull/5900)
* Tax is displayed correctly e2e test

* Add extra utils to shopper

* add single e2e test script oin package.json

* Feedback changes from Niels

* Test tax is correct on summary page

* Check if CI test passes

* Longer timeout for tax test

* change timeout in jest config

* increate jest timeout

* Test

* Test

* Test

* setTimeout outside of tests to 120000

* Address raluca's feedback and timeout everywheregaa

* Increase timeout on  for search box

* set jest timeout to 120000

* Raluca's suggestions

* Debug

* Increase search timeout to 5000

* Only run Tax e2e tests in CI for quicker debug - REMOVE THIS

* use waitforSelector

* 30s delay for toMatchElement

* Let'shope this works

* Remove toMatchElement

* waitForSelector

* Run debug test only

* Debug tax test

* debug taxes

* shopper using toMatchElement again

* Remove the 30000 timeout delay from toMatchElement

* Run all tests but only once

* Remove tax test

* Revert "Remove tax test"

This reverts commit 7db34120e1e91f4fd26514fdb9525cac2a6066bb.

* Delete the minicart test

* Revert "Revert "Remove tax test""

This reverts commit 31dd654e52f37fcd02ccd25336958248bef495c6.

* Revert "Delete the minicart test"

This reverts commit 5595f0834a975d097a300bc0c7cbf643caa8b764.

* tax test

* block addToCart

* Put back block functions

* Refactor block.addToCart

* mini-cart e2e test uses shopper.block.emptyCart()

* only run shopper tests in CI

* Run frontend and shopper tests and change waitFor -> waitForTimeout

* Run frontend tests in CI

* Run CI e2e tests again

* Skip legacy template blocks

* Skip legacy template test but run all others

* Switch to storefront instead of twentytwentyone after legacy-template-blocks tests finish

* Tidy up

* fix typo

* Fix ESLint issue

Co-authored-by: Saad Tarhi <saad.trh@gmail.com>
Co-authored-by: Saad Tarhi <saad.tarhi@automattic.com>
2022-03-08 14:50:16 +00:00
Saad Tarhi 1e15672b7b Shopper → Checkout → Can place an order as guest (https://github.com/woocommerce/woocommerce-blocks/pull/6009)
* Add "goToCheckout" method in "shopper.block"

Instead of using "shopper.goToCheckoutBlock" method, it will much easier
to maintain the following structure "shopper.block.goToCheckout"

* Create a constant for billing details

* Create "fillBillingDetails" shopper method

* Add "placeOrder" method to "shopper"

* Enable "Cash on delivery" payment method for our test

* Update "@woocommerce/e2e-utils" package

Some new useful e2e utility functions weren't avaiable in the previous version

* Add E2E test for "Can place an order as guest"

* Fix mini-cart failing E2E tests

In case this fix woocommerce/woocommerce-blocks#6006 isn't merged yet, this commit can be used to pass all
E2E tests

Co-authored-by: Saad Tarhi <saad.tarhi@automattic.com>
2022-03-08 14:52:40 +01:00
Tung Du 75b5181e0e Shopper → Mini Cart → Can view empty cart message and start shopping button (https://github.com/woocommerce/woocommerce-blocks/pull/5918) 2022-03-08 17:01:27 +07:00
Saad Tarhi c0aec1e85b Fix mini cart failling tests (https://github.com/woocommerce/woocommerce-blocks/pull/6006)
Set the correct "emptyCart" utility function

Co-authored-by: Saad Tarhi <saad.tarhi@automattic.com>
2022-03-08 00:09:20 +01:00
Saad Tarhi dee5032d41 Shopper → Cart → Can proceed to checkout (https://github.com/woocommerce/woocommerce-blocks/pull/5901)
* Shopper → Cart → Can proceed to checkout

* Refactor the code for E2E testing

Introduce some discussed solution to structure and optimize the code

* Resolve some conflicts with the trunk branch

* Remove method overriding and refactor code

We are trying to avoid overriding exiting E2E Woo's utility functions

Instead we can use our own "shopper.block"

* Use a consistent constant naming convention

Co-authored-by: Saad Tarhi <saad.tarhi@automattic.com>
2022-03-07 16:23:31 +01:00
Mike Jolley eae1d75c86 Store API: Consistent error code and hook naming (https://github.com/woocommerce/woocommerce-blocks/pull/5992)
* Update error codes with `woocommerce_rest_` prefixes.

* Update action and filter hooks with woocommerce_store_api_ prefix

* Update hook docs

* Update error code mismatches

* Update hook name in tests

* update hook name in tests

* phpcs
2022-03-07 13:51:07 +00:00
Mike Jolley fd03b79995 StoreAPI: Rename namespace to remove `\Blocks` (https://github.com/woocommerce/woocommerce-blocks/pull/5982)
* Composer config

* Update namespace in deprecated.php

* Bulk update namespace

* Revert rename in deprecated class

* bw compat

* Store API: Add dedicated container and make Store API code self-contained (https://github.com/woocommerce/woocommerce-blocks/pull/5986)

* Move ArrayUtils to StoreApi

* Move PaymentContext/PaymentResult

* Move create account functionality to checkout endpoint. Update tests.

* Move get_routes_from_namespace to blocks

* Move RestApi logic within StoreApi namespace/directory

* StoreAPI Container

* Update functions

* Update extend docs

* Run Doc build script

* Missing container calls for 3rd party extensions

* Fix doc toc
2022-03-04 13:28:37 +00:00
Tung Du 892d7c268d Shopper → Mini Cart → Can update product quantity (https://github.com/woocommerce/woocommerce-blocks/pull/5963) 2022-03-04 17:40:13 +07:00
Tung Du 43529e5735 Shopper → Mini Cart → Can go to Cart page (https://github.com/woocommerce/woocommerce-blocks/pull/5977) 2022-03-04 16:57:34 +07:00
Tung Du 33ac2d5f4b Shopper → Mini Cart → Can proceed to checkout (https://github.com/woocommerce/woocommerce-blocks/pull/5978) 2022-03-03 08:24:30 +07:00
Lucio Giannotta 08a99165ca Add mock theme with Woo Templates for E2E tests (https://github.com/woocommerce/woocommerce-blocks/pull/5920)
This PR adds a block-enabled theme with templates for WooCommerce
which is intended to be used when testing the more complex scenarios
such as template fallbacks.

Additionally, since theme-dependent logic seems to be becoming more
and more useful (see woocommerce/woocommerce-blocks#5913), this PR also adds a utility function used to
explicitly declare theme dependencies of a test (`useTheme`).

Said function will activate the theme before running a given suite and then
reactivate the previous theme, as to make sure to not have any side-effects
(such as the ones described in woocommerce/woocommerce-blocks#5913 above).

Closes woocommerce/woocommerce-blocks#5660
2022-03-02 15:49:00 +01:00
Christos Lilitsas c35bf8ee67 Store API: Refactored validation handling and introduced `woocommerce_store_api_cart_errors` hook (https://github.com/woocommerce/woocommerce-blocks/pull/5904)
* Introduce 'wooocommerce_store_api_validate_cart' action

This action can be used by third party developers to add extra 'errors' in cart route responses. This is meant to function as a replacement of the legacy 'woocommerce_check_cart_items' hook.

* Introduce a new 'wooocommerce_blocks_draft_order_updated' action

The new action can be used to modify the finalized draft order object.
Additionally, developers can use it to throw a RouteException in order to prevent access to the checkout block.

The PR also shuffles some existing code that checks the order instance and sets the draft order ID before the 'woocommerce_blocks_checkout_update_order_meta' gets fired.

* Fix PHPCS

* Revert changes to Checkout route

* Add some extra content to the 'woocommerce_blocks_checkout_update_order_meta' docblock on the effect of exceptions thrown from callbacks

* Add __experimental prefix to 'wooocommerce_store_api_validate_cart' action

* Remove long ooo

* Add example

* Refactor cart error getters as wrappers to the validate functions

* Refactor stock_exceptions_to_wp_errors to return a single wp error.

* Add type hint in custom exception

* Fix namespace versioning and some minor improvements

* Move InvalidCartException catcher from AbstractCartRoute to AbstractRoute

* Introduce the __experimental_woocommerce_store_api_cart_errors filter

* Handle all notices and group them into a single WP_Error instance

* Cleanup doc and update example

* Cleanup NoticeHandler

* Fix doc

* Fix WP_Error namespace

* Update NoticeHandler unit tests

* Fix Unit tests typo

* Add docs to tests to bypass precommit scripts

* Refactor wp error grouping with merge_from

* Remove previous cart getters and refactor the get_cart_errors

* Fix CartSchema error getter and minor fixes

* Revert NoticeHandler exception namespace

* Unit test fix for get_cart_errors

* Switch back to do_action

* Update the example doc

* Duplicate use statement

* Update docblock in validate_cart() method for validation hooks

* Update action docs

* Remove __experimental prefix

Co-authored-by: Manos Psychogyiopoulos <psyx@somewherewarm.com>
Co-authored-by: Mike Jolley <mike.jolley@me.com>
2022-03-02 12:21:31 +00:00
Tung Du 22eccc8614 Shopper → Mini Cart → Can view filled mini cart contents block (https://github.com/woocommerce/woocommerce-blocks/pull/5923) 2022-03-01 18:25:13 +07:00
Mike Jolley 49b65c7bcf Refactor ExtendRestApi as ExtendSchema and expose `register_endpoint_data` as a public function (https://github.com/woocommerce/woocommerce-blocks/pull/5941)
* Create Extend class under schema namespace

* ExtendRestApi -> ExtendSchema

* ExtendSchema helper functions

* Move tests

* Fix tests

* Fix docs

* Typos

* Remove invalid param

* phpcs formatting

* Update docs/contributors/documentation-guidelines.md

Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com>

* Update docs/extensibility/filtering-payment-methods.md

Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com>

* Update docs/extensibility/README.md

Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com>

* Update docs/extensibility/available-slot-fills.md

Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com>

* Asserttrue comment

Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com>
2022-03-01 10:34:05 +00:00
Lucio Giannotta 8ad1dff1f4 Rename templates to more e-commerce friendly names (https://github.com/woocommerce/woocommerce-blocks/pull/5935) 2022-02-28 08:00:01 +01:00
Thomas Roberts 7915a793fa Await expectations in checkout frontend test (https://github.com/woocommerce/woocommerce-blocks/pull/5942) 2022-02-25 18:21:10 +00:00
Raluca Stan e01592e736 Add constants for C & C pages in our E2E tests (https://github.com/woocommerce/woocommerce-blocks/pull/5938)
* Add constants for C & C pages in our E2E tests

Inspired by WC E2E this will avoid going to admin to find out the links for these pages.

* Select C & C pages by using the main navigation links

* Fix function calls

* Revert back to using constants for C & C block pages' URLs

reverts 9587a0bd5efa5d97b484cd8d1bf927ff50f8e014 and bd7e2f996792d887756c0a0f4a10e6886574e77b
2022-02-25 10:44:16 +01:00
Tung Du 49c5659eb9 Shopper → Mini Cart → Can open/close the drawer (https://github.com/woocommerce/woocommerce-blocks/pull/5894) 2022-02-24 21:02:24 +07:00
Thomas Roberts bbe68f395e Change tests that use the incorrect `waitForSelector` API (https://github.com/woocommerce/woocommerce-blocks/pull/5932)
* Change tests that use the incorrect waitForSelector API

* Use .toMatchElement instead of just .toMatch

* Use sentence case for page title check
2022-02-24 11:31:26 +00:00
Thomas Roberts 918de7bc75 Ensure screenshots can be attached in jest html report (https://github.com/woocommerce/woocommerce-blocks/pull/5919)
* Ensure screenshots can be attached in jest html report

* Force tests to fail in ci

* Console log for testing

* Console log for testing

* Check on hook failure as well as test failure

* Revert "Force tests to fail in ci"

This reverts commit 6efebd63bba4792214f5b24824fb405cf38b1367.

* Take full page screenshot only when error type is not hook_failure

* Remove console log
2022-02-24 09:06:24 +00:00
Mike Jolley a58b2d0ac4 Store API: Introduce API Versioning System (https://github.com/woocommerce/woocommerce-blocks/pull/5911)
* Fix missing dependency

* Min version exceeds required 5.6

* Move exceptions

* Move schemas under V1 namespace

* Move routes to v1

* Move RouteException

* Route versioning

* Update route and schema identifiers/init

* Rework route init to support multiple versions and multiple schema

* Tests for cart routes

* Cart coupons tests

* Batch

* extensions

* Update docs

* Update remaining tests

* woocommerce_store_api_route_version was unused

* Revert unrelated change

* Fix phpcs

* Update src/StoreApi/docs/guiding-principles.md

Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com>

* Update src/StoreApi/docs/cart-items.md

Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com>

* Update src/StoreApi/RoutesController.php

Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com>

* Note about v1 unversioned endpoints

* Remove unused get_route_version

* 409 comment in tests

* Remove copy pasted comments

* Update all usage to v1

* Correct namespace

* More v1 namespaces

* More missing v1

* fix mocks

Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com>
2022-02-23 12:00:45 +00:00
Tung Du 399a204138 Fix: Ensure `shopper.goToBlockPage` works with any theme (https://github.com/woocommerce/woocommerce-blocks/pull/5914) 2022-02-22 11:34:51 +07:00
Tung Du 47f8993a8d Shopper → Mini Cart → Can see the icon with a badge (https://github.com/woocommerce/woocommerce-blocks/pull/5877) 2022-02-22 09:50:59 +07:00
Lucio Giannotta 341a742916 E2E tests for Product Tag Template and Legacy Block (https://github.com/woocommerce/woocommerce-blocks/pull/5888)
Also: 

* Add fixtures for tags
* Teardown both categories and tags when tests are done
2022-02-21 13:26:22 +01:00
Lucio Giannotta d64ebc72dc E2E tests for Product Category Template and Legacy Block (https://github.com/woocommerce/woocommerce-blocks/pull/5820) 2022-02-21 12:38:36 +01:00
Lucio Giannotta 5de9fec527 E2E tests for Product Archive Template and Legacy Block (https://github.com/woocommerce/woocommerce-blocks/pull/5748)
Also:
* Refactors the function to add a custom paragraph
* Add front-end test for archive template
* Use WordPress data to guarantee block presence
* Use WordPress data instead of selectors to match blocks
2022-02-21 12:01:56 +01:00
Lucio Giannotta 497820dcb9 E2E tests for Single Product Template (https://github.com/woocommerce/woocommerce-blocks/pull/5722)
* Add empty block theme to mock E2E tests
* Install empty theme in the test WP instance
2022-02-21 11:01:42 +01:00
Niels Lange 6946a0c189 Remove obsolete * in comment 2022-02-14 17:55:28 +07:00
Alex Florisca 16d5e773bc Reformatted prettier files (https://github.com/woocommerce/woocommerce-blocks/pull/5735) 2022-02-07 16:59:44 +00:00
Tung Du 4dab187dbe Fix: only allow Mini Cart block in Widgets and Site Editor (https://github.com/woocommerce/woocommerce-blocks/pull/5653)
* fix: exclude Mini Cart from the blocks editor

* fix: explicitly register Mini Cart blocks for Site Editor and Widgets

* add check to loading the block on frontend

* add e2e tests for widget area

* improve test title

Co-authored-by: Luigi <gigitux@gmail.com>
2022-02-07 11:29:22 +01:00
Thomas Roberts 426eb51830 Update Checkout block E2E fixture and increase node version in GH actions (https://github.com/woocommerce/woocommerce-blocks/pull/5678)
* Remove unnecessary setup step and use node v16 in E2E action

* Ensure storefront is active

* Use new checkout fixture

* Try with only checkout test

* Update package.json

* Run all tests, not just checkout
2022-02-01 11:14:16 +00:00
Thomas Roberts afd9d42805 Add Checkout Order Summary inner block tests (https://github.com/woocommerce/woocommerce-blocks/pull/5675)
* Add fake items fixture

* Add test for rendering items in sidebar

* Add test for items with addons

* Add textContentMatcherAccrossSiblings helper

This is needed to match text when it's spread over a few elements

* Add test to ensure subtotal renders correctly

* Add test to ensure discounts are rendered correctly

* Add test to ensure fees are shown correctly

* Add test to check coupon entry form isn't present when coupons disabled

* Add more mock data to useStoreCart

* Mock useShippingDataContext

* Rename useStoreCartValue to useStoreCartReturnValue

* Remove unnecessary coupon button test

This should be tested within the TotalsCoupon component

* Add tests for shipping presence

* Add test for coupons

* Remove cart items fixtures

These are no longer needed

* Move the findByText utils to the utils folder

* Move inner blocks test to correct directory
2022-01-31 10:53:08 +00:00
Mike Jolley 7f2af8c1a6 Validate available payment methods before attempting payment or updating order statuses (https://github.com/woocommerce/woocommerce-blocks/pull/5440)
* Make payment method required

* removed unused imports

* Remove PUT method

* Validate available method when updating order

* Enable bacs for tests
2022-01-04 18:04:08 +00:00
Thomas Roberts 5036c69638 Add E2E tests for Filter blocks (Price, Attribute, and Active Filters) (https://github.com/woocommerce/woocommerce-blocks/pull/4562)
* Add clear and fill input test util

* Add tests for Filter Products by Price

* Add class name to filter products by price block in editor

* Update wp-env

* Fix formatting

* Update lock

* Revert "Update lock"

This reverts commit f4e809e000430eea3972c94fd2aea0a19ba6961b.

* Create product attributes during setup

* Remove product attributes during teardown

* Add attributes in fixture-data

* Add two new products, for attribute testing

* Load attributes into store and apply them to products

* Add class to Filter by Attribute when editing

This is so it can be targeted in E2E tests more easily.

* Add tests for Filter Product by Attribute

* Fix formatting in attribute-filter.test.js

* Add tests for active filters block

* Add doc block for ensuteCleanAttributes

* Update wording of title test in all filter block E2E

* Update test wording to read better

* Update snapshots

* Use pptr-testing-library selectors to click elements

This makes the tests easier to reason with, and lets us take a step back from the implementation details (classnames etc.)

* Add saveOrPublish test util

* Use pptr-testing-library selectors to click elements in attribute filter

* Use pptr-testing-library selectors to click elements in price filter

* Add `puppeteer-testing-library`

* Use puppeteer-testing-library API to look for H6 button

* Use correct argument in jest-puppeteer.dev.config

* Update package.json & package-lock.json

* remove tests for 5.3

* remove snapshots

* Remove ensureCleanAttributes

* Remove puppeteer-testing-library, install missing expect-puppeteer package and update tests

The puppeteer-testing-library, although added by gutenberg is not actively used.
I have removed it and realised that the added functionality can be easily replaced by expect-puppeteer.
This is a package that we specify in the jest configuration but it was not part of our package.json.
The selectors from puppeteer-testing-library have been replaced with .toClick and the utility clearAndFillInput with .toFill

The Filter by Attribute block has been skiped until tests are fixed.

* Add back setupPageSettings to jest setup

* Fix filter by attribute block test

* Fix linting error

Co-authored-by: Raluca Stan <ralucastn@gmail.com>
2021-12-23 17:26:10 +01:00
Mike Jolley ecc80e5cff Sync order data with cart data when cart is updated from any route (https://github.com/woocommerce/woocommerce-blocks/pull/5379)
* Link order controller to cart routes

* Remove order controller from checkout route

* Fix PHP warnings in abstract schema

* Fix PHP warnings in abstract route

* Update shipping phone handling

* Includes are handled in core now

* Remove maybe_update_order_from_customer

* Add cart_updated routine to all cart routes

* Remove abstract method

* Remove test for woocommerce_blocks_cart_update_order_from_customer_request

* Remove do_order_callback
2021-12-21 13:11:51 +00:00
Mike Jolley 59c8c88438 Introduce 2 new hooks in Customer Update Route (https://github.com/woocommerce/woocommerce-blocks/pull/5345)
* Introduce woocommerce_blocks_cart_update_customer_from_request hook

* Introduce woocommerce_blocks_cart_update_order_from_customer_request

* Test actions fire

* Update hook docs
2021-12-13 13:57:45 +00:00
Luigi Teschio 13deb1b09e Mini Cart Block: render the empty state set on template parts (https://github.com/woocommerce/woocommerce-blocks/pull/5338)
* add view switcher for mini cart contents block

* editor view switcher

* update mini cart template file

* render the empty state template parts for the Mini Cart Block woocommerce/woocommerce-blocks#4674

render the empty state template parts for the Mini Cart Block woocommerce/woocommerce-blocks#4674

* update selector

* allow empty mini cart block to add all blocks

* fix tests; improve code style

* install @wordpress/block-editor package

* fix warning on frontend side

* block-editor package is not necessary

* merge attributes object

Co-authored-by: Tung Du <dinhtungdu@gmail.com>
2021-12-10 12:11:59 +01:00
Mike Jolley 70f0c06bf9 Fix e2e tests welcome guide/m1 mac support (https://github.com/woocommerce/woocommerce-blocks/pull/5096)
* Bump dependencies to fix e2e on m1 macs

* Disable welcome guide more reliably - see 3da717b8d0/packages/e2e-test-utils/src/create-new-post.js

* Update selectors and fixture data for cart block

* unused dep

* Remove duplicate block wrapper

* Remove unused jest configuration files

* More robust click in view switcher test

* Revert fixture data change
2021-11-09 13:18:55 +00:00
Seghir Nadir ea1e17fc81 Fix sanitization callback (https://github.com/woocommerce/woocommerce-blocks/pull/5060)
* Fix sanitization callback

* Add test case to confirm sanitization callbacks work for nested properties

Co-authored-by: Mike Jolley <mike.jolley@me.com>
2021-11-05 15:39:08 +00:00
Mike Jolley 72cf5eade8 Remove hydration hocs in favour of apiFetch Middlewares (https://github.com/woocommerce/woocommerce-blocks/pull/5022)
* Remove withRestApiHydration

* Preload checkout data via setting - server data is required for this block

* Handle cart hydration using createPreloadingMiddleware which removes the need for HOCs

* Rename variable

* Remove withStoreCartApiHydration and timestamp checking

* Empty test file
2021-11-04 11:05:58 +00:00
Seghir Nadir 2408e34faa Migrate Cart i1 to Cart i2 (https://github.com/woocommerce/woocommerce-blocks/pull/4973)
* move empty cart

* remove Cart and rename Cart i2 to Cart

* graduate blocks

* setup template migration from Cart i1 to Cart i2

* back to js so we have a good diff

* add migration

* fix bug in empty cart template

* add useForceLayout hook to edit

* migrate from old block to new block

* migrate styles

* respect align

* add tests

* Include latest cart line item improvements from cart-i1

* Missing changes from cart-i1

* Line items table should be disabled

* Fix e2e tests for cart i2

* update tests to adapt for inner blocks

* update select to resolveSelect to remove warning checker

* rename test/block to test/index

* move blocks to their own file

* undo rename to keep diff clean

* remove .tsx and update jest config

* Revert "update select to resolveSelect to remove warning checker"

This reverts commit 79d55de30edcfe36bbdfe7506df7a09460824f03.

* revert resolveControl

* Fix empty cart editor E2E test by scrolling to the view switch

* parse attributes for order summary block

* migrate attributes when resaving

* Update documentation

Automatic update after running npm run build:docs

* add align options to filled cart and empty cart

* append instead of replcae

* import style.scss in frontend

Co-authored-by: Mike Jolley <mike.jolley@me.com>
Co-authored-by: Raluca Stan <ralucastn@gmail.com>
2021-10-25 15:46:34 +01:00
Tung Du 7dc9b16f4a Add basic E2E tests for products grid blocks (https://github.com/woocommerce/woocommerce-blocks/pull/4872)
* wip: add product on sale test

* test: add fixture for product on sale test

* try: permission

* Revert "try: permission"

This reverts commit f8eb09c0152a567383e93c18f61e91fdadd13c40.

* test: basic e2e test for products by category block

* test: basic e2e test for products by tag block

* add basic test for products by attribute block

* trigger build

* fix: slug
2021-10-21 10:23:15 +01:00
Tung Du bd3e7126f8 Mini Cart block: display a compatibility notice when the user first adds the block in the editor (https://github.com/woocommerce/woocommerce-blocks/pull/4945) 2021-10-21 16:07:20 +07:00
Mike Jolley 4385619be5 Fix notice in e2e test suite from potentially undefined id 2021-10-20 10:11:20 +01:00
Mike Jolley 2e0d0faa84 Enforce valid states from the API (https://github.com/woocommerce/woocommerce-blocks/pull/4844)
* Enforce valid states from the API

* Remove paypal from test
2021-10-19 14:30:02 +01:00
Mike Jolley dc19412a54 Update dependency @woocommerce/e2e-utils to v0.1.6 (https://github.com/woocommerce/woocommerce-blocks/pull/4957)
* Update @woocommerce/e2e-utils

* Define grouped
2021-10-18 20:01:10 +01:00
Niels Lange 40e43b5328 Add e2e tests for Hand-picked Products (https://github.com/woocommerce/woocommerce-blocks/pull/4788) 2021-10-18 15:07:24 +01:00
Niels Lange 3f530ac755 Add e2e tests for Best Selling Products (https://github.com/woocommerce/woocommerce-blocks/pull/4785) 2021-10-18 15:06:48 +01:00
Albert Juhé Lluveras c3152aec96 Add e2e tests to verify disabled blocks can't be inserted into widget areas (https://github.com/woocommerce/woocommerce-blocks/pull/4910) 2021-10-18 08:48:03 +02:00
Niels Lange 8475bc7bad Add e2e tests for Top Rated Products (https://github.com/woocommerce/woocommerce-blocks/pull/4786) 2021-10-11 17:05:50 +01:00
Niels Lange ff78f58556 Add e2e tests for Product Categories List (https://github.com/woocommerce/woocommerce-blocks/pull/4915) 2021-10-11 18:59:45 +07:00
Niels Lange 6286f7fbd6 Add e2e tests for Newest Products (https://github.com/woocommerce/woocommerce-blocks/pull/4789) 2021-10-11 18:55:38 +07:00
Thomas Roberts 255a74b328 Add screenshots on E2E test failures (https://github.com/woocommerce/woocommerce-blocks/pull/4898)
* Add test environment to catch errors

* Add jest-circus and jest-html-reporters

This is so we can log the screenshots and errors that happen during E2E tests.

* Use the jest reporters and jest-circus to run the E2E tests

* Force cart test to break

Revert this!

* Upload jest report artifact when tests fail

* Run artifact upload on failure

* Upload entire report directory to artifact

* Revert "Force cart test to break"

This reverts commit c57f2c5ab1d7b60d8824d854c1cb9a8281a71c4b.

* Update .gitignore and jest.config

* Force cart test to break

* Force cart test to break

* Remove <rootDir> from jest-html-reporter path

This was causing the artefact not to upload.

* Revert "Force cart test to break"

Co-authored-by: Niels Lange <info@nielslange.de>
2021-10-08 11:58:44 +01:00
Tom Cafferkey 445f8175a1 Throw an exception if there is no selected shipping method on an item… (https://github.com/woocommerce/woocommerce-blocks/pull/4784)
* Throw an exception if there is no selected shipping method on an item that needs shipping

* Update src/StoreApi/Utilities/OrderController.php for ensure error message ends with a period.

Co-authored-by: Albert Juhé Lluveras <contact@albertjuhe.com>

Co-authored-by: Albert Juhé Lluveras <contact@albertjuhe.com>
2021-09-21 10:31:52 +01:00
Niels Lange 6dc54c1268 Add e2e tests for Featured Category (https://github.com/woocommerce/woocommerce-blocks/pull/4773) 2021-09-20 18:34:06 +07:00
Niels Lange 37920b118d Add E2E tests for Featured Products (https://github.com/woocommerce/woocommerce-blocks/pull/4771) 2021-09-17 14:07:26 +02:00
Mike Jolley 5c08c75612 Update Checkout to Checkout i2 (https://github.com/woocommerce/woocommerce-blocks/pull/4745)
* Remove i2 from build

* Remove i2 php registration

* Rename old checkout dir

* Rename i2 dir

* Migrate i1 to i2 code

* Register block metadata to fix frontend rendering when migrating to i2

* Register in correct order

* Missing styles

* add register-components to side effectful list

* wrong block class in e2e test

* wp prefix missing on selector

* Fix top level block test

* Reselect labels to work around rerendering

* missing empty cart styles

* Consolodate duplicate styles

* remove init code

* update selectBlockByName

Co-authored-by: Nadir Seghir <nadir.seghir@gmail.com>
2021-09-16 13:16:21 +01:00
Thomas Roberts a2772a1cad Add E2E and Unit (PHP and JS) tests for Filter by Stock block. (https://github.com/woocommerce/woocommerce-blocks/pull/4682)
* Add back end E2E tests for Filter by Stock

* Add unit/snapshot tests for Filter by stock block

* Refactor Filter by Stock block to load stock statuses in the block body

This is required to make the code easier to test, since the mocked settings were being applied immediately after the block was imported, which didn't give time to let the `allSettings` override take place in the unit tests.

* Add PHP Unit tests for test_custom_stock_counts of ProductQueryFilters

* Remove useMemo from stock filter block

This felt like an overoptimisation, it's very inexpensive to run this every render. The result is less complex code, so it's better this way imo.

* Move initial stock options and the values they are derived from into useState

* Add class name to block in editor
2021-09-15 09:20:31 +01:00
Albert Juhé Lluveras ebdacd62d7 Add initial e2e tests to Mini Cart block (https://github.com/woocommerce/woocommerce-blocks/pull/4677) 2021-09-08 10:14:53 +02:00
Mike Jolley 1d79bb6365 PHPUnit Tests running on wp-env (https://github.com/woocommerce/woocommerce-blocks/pull/4567)
* Tidy up bootstap so it uses autoloaders and works with the known plugin paths

* eslint ignore woocommerce bin

* Use WC from bin in wp-env

* Git ignore woocommerce in bin

* Remove reliance on core framework across phpunit tests

* Simplify bootstrap - since test framework is no longer required, there is no need to pull in woo from github

* Remove unused configs

* Update CI

* Implement PHPunit Polyfill

* Abstract the test case

* Update lock

* remove chown

* experiment: try sudo

* move phpversion to first run

* Remove 7.0 tests :(

* test plugin override for 5.5 test

* Use dev version

* Fix formatting

Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com>
2021-08-20 14:58:32 +01:00
Mike Jolley a7d7ea32bb Fix unfiltered html usage of blocks (https://github.com/woocommerce/woocommerce-blocks/pull/4551)
* SSR search

* deprecation handling for search

* Update snaps

* Fix duplicate class and align class property
2021-08-12 17:39:38 +01:00
Darren Ethier 5ebbd41220 Update relevant files due to L2->L0 policy change for minimum required versions. (https://github.com/woocommerce/woocommerce-blocks/pull/4484)
* update README files with version requirements

* update phpcs config

* update default environment for tests locally

* update workflows to only test against versions matching new policy

* update plugin header for new version policy

* restore older WP version support in E2E tests and PHPCS

I realized that we might still want to test against L2 WP versions in our E2E tests until those tests can be moved to WC core. While the feature plugin is L0, we still need to support L2 for existing features that are already surfaced in the WooCommerce plugin package.

Also with PHPCS if there are fixes to older things in the codebase, we will need to preserve the usage of L2 friendly (back-compat) code.

* add detection of Woo Core version to bootstrap

* update version used in phpunit tests

* add links to version policy update post

* restore 5.5.1 for Woo Core version

Getting errors with 5.5.2 - not sure what's going on but might be the tag isn't available as expected for 5.5.2 maybe?

* switch to hardcoded version header reference

PHPUNIT was tripping on this for some reason.

* remove older WP version e2e test workflows

* fix phpunit tests for new woo test suite

Woo Core now uses a container and has some mocks that are used in some legacy test helpers.

* remove explicit set WOO_VERSION for phpunit tests.

This should default to latest for the GH workflow runs.

* Update release PR template.

Add some explicit instructions around updating required WP and WC versions at time of release.

* use latest WOO_VERSION in .env

* some improvements to reduce the things needing updated

* remove extraneous code

* Add some more checklist items to release PR templates

* remove unnecessary conditional

* remove is-dismissible css classes

* Improve clarity of error messaging

* Update README.md

Co-authored-by: Albert Juhé Lluveras <contact@albertjuhe.com>

* remove checklist items about versions for patch releases

Co-authored-by: Albert Juhé Lluveras <contact@albertjuhe.com>
2021-07-29 10:52:34 -04:00
Mike Jolley 7ff3dac568 Fix e2e tests: Remove paypal from fixture data (https://github.com/woocommerce/woocommerce-blocks/pull/4507)
* Remove paypal from fixture data

* Fix scroll hoc tests

* Missing return type in cart causing TS error

* update e2e utils

* Replace searchForBlock method in e2e utils

* Single block update insert block

* Use insertBlockDontWaitForInsertClose
2021-07-26 15:05:09 +01:00
Mike Jolley 844975fcd0 Fix SKU search in the Store API (https://github.com/woocommerce/woocommerce-blocks/pull/4469)
* Fix Product Search (by SKU) functionality. This was not being executed.

* Add unit test to confirm searching by SKU is functional
2021-07-20 16:31:18 +01:00
Thomas Roberts a20f3425b1 Add cart/extensions endpoint to allow third party extensions to process server-side and get a new cart (https://github.com/woocommerce/woocommerce-blocks/pull/4298)
* Move text-input to checkout package

* Add support to TextInput for inputs with type number

* Add ExperimentalDiscountsMeta.Slot to Cart sidebar

* Add extra styles for Button and Panel components

* Add updateCartFromApi util to @woocommerce/blocks-checkout

* Change updateCartFromApi to TypeScript

* Stop passing contexts through the discounts slot fill

* Add CartExtensionsSchema class

* Add CartExtensions Route

* Add register_update_callback and get_update_callback fns

* Add extensionCartUpdate function

* Add applyExtensionCartUpdate action

* Make extensionCartUpdate use batching

* Add ExtensionCartUpdateArgs type definition

* Execute a success/error function after request in extensionCartUpdate

* Remove success and error functions

* Avoid including all schemas in CartExtensionsSchema instantiation

This is achieved by inheriting AbstractSchema and slightly modifying the way in which the latest cart data is returned from this endpoint.

* Update docs for extensionCartUpdate

* Handle errors from extension callbacks

* Throw better errors when incorrect namespace/functions are used

* Add tests for CartExtensions route,  ExtendRestApi update callback registration

* Add dummy get_properties method to CartExtensionsSchema
2021-06-07 12:16:47 +03:00
Darren Ethier c391899258 Fix broken phpunit tests (https://github.com/woocommerce/woocommerce-blocks/pull/4305)
* allow for WOO_VERSION config in tests setup

* pass through WOO_VERSION environment var to container

* force specific WOO_VERSION value for phpunit test run

* try passing through environment variable via docker arg

Also set .env for controlling local runs of phpunit
2021-06-03 09:35:52 +02:00
Mike Jolley cf8ab9fa93 Add key to each `CartTotalItem` (https://github.com/woocommerce/woocommerce-blocks/pull/4240)
* Move type defs

* Move type guards

* Fix imports

* Extract prepareTotalItems to TS file

* usePaymentMethodInterface as TS file

* Fix TS props

* Fix currency type defs

* Add return type to usePaymentMethodInterface

* Add key prop to CartTotalItem

* Fixed up js tests

* Move SymbolPosition into type-defs package

Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com>
2021-05-25 12:49:13 +01:00
Raluca Stan 092a28848c Fix e2e checkout tests and adjust jest setup (https://github.com/woocommerce/woocommerce-blocks/pull/4216)
* Fix checkout test
- make tests independent & test also for empty cart case
- make sure the Order summary is expanded with a better selector
* Remove unnecessary localStorage operations from tests
* Go to cart page before removing an item from cart
* Remove logging observing before tests
This removes unnecessary console.log interception. A big part of the logic was done for Puppeteer 1.6.1, but since 3.0.0 message.text() returns string. We allow console.error messages to surface in our tests. Although they don't cause the test to fail it might be a good addition for debugging purposes.
2021-05-18 15:09:30 +02:00
Raluca Stan 7deea0eee8 Fix cart and checkout frontend e2e tests (https://github.com/woocommerce/woocommerce-blocks/pull/4199)
* Wip: fix e2e fe tests

* Test that navigation ends

* Fix waitForNavigation

* comment out failing php test

* click the dom element

* Ensure navigation happens by waiting for it. Test page title.

* remove skip and update docs

* Revert "comment out failing php test"

This reverts commit 7c40e8caf3aa32e35e3b70eb32051251b06e0613.

* Fix USD from merge conflict

* Add missing check for page title

* Try page.waitForFunction for text search

* test to see checkout page title is correct

* test checkout page url on CI

* unde jest config change

* Fix assertion for checkout page

* remove extra localStorage item remove call

Co-authored-by: Mike Jolley <mike.jolley@me.com>
Co-authored-by: Nadir Seghir <nadir.seghir@gmail.com>
2021-05-16 18:41:34 +01:00
Albert Juhé Lluveras 792f0671af Set default store currency to USD in tests (https://github.com/woocommerce/woocommerce-blocks/pull/4203) 2021-05-13 12:14:15 +02:00
Raluca Stan b9db5d4c51 Fix/cart backend test (https://github.com/woocommerce/woocommerce-blocks/pull/4153)
* Fix backend cart e2e test

* Adjust test structure

* Fix e2e checkout backend test.

Make sure the confirmation window is closed
2021-05-05 12:52:27 +01:00
Thomas Roberts e6c7f2b6c0 Check for element before trying to click it in cart backend test (https://github.com/woocommerce/woocommerce-blocks/pull/4087) 2021-04-27 09:39:31 +01:00
Thomas Roberts 583113e373 Remove woocommerce as a dependency and install @woocommerce/e2e-utils (https://github.com/woocommerce/woocommerce-blocks/pull/4078)
* Remove woocommerce as a dependency and install @woocommerce/e2e-utils

* Remove reference to woocommerce package from tsconfig and jest config
2021-04-26 16:31:30 +01:00
Mike Jolley a4cd850384 Deprecate the woocommerce_shared_settings hook (https://github.com/woocommerce/woocommerce-blocks/pull/4092)
* Deprecate the filter

* Prevent test from failing due to notices
2021-04-26 10:36:50 +01:00
Mike Jolley dbbb99d55e Move Block Type Settings into Block Type Classes (https://github.com/woocommerce/woocommerce-blocks/pull/4059)
* BLOCK SETTINGS: Remove unused constants/settings

* AssetDataRegistry: Helpers to check for settings that exist, and registering page ID/permalinks

* Move checkout and cart block settings to checkout and cart blocktypes

* Move isShippingCalculatorEnabled to cart block

* Remove HAS_DARK_EDITOR_STYLE_SUPPORT and IS_SHIPPING_CALCULATOR_ENABLED in favour of getSetting

* Move displayCartPricesIncludingTax to blocktypes, and implement getSetting

* Move block settings to core settings and blocktypes

* Fix namespace usage

* Move review settings

* move tag settings

* Keep productCount in core data

* Move min and default height

* Improve storePages code

* Move attributes to attribute filter block type

* Move $word_count_type outside of settings array

* Remove unneeded setting in preview data (shippingCostRequiresAddress)

* Move min/max settings dependency from GridLayoutControl to Blocks themselves and use getSettings

* DEFAULT_COLUMNS and ROWS to settings

* Move product columns/rows to block types

* Add grid settings to AllProducts block

* Correct default rows

* correct min rows default

* Move hasDarkEditorStyleSupport

* Move hideOutOfStockItems to block type settings

* Move build settings to inline script dependency

* Pass data through asset api and move restApiRoutes

* Export all core settings as constants

* Remove WORD_COUNT_TYPE from core settings

* Move some other core settings to assets

* Update constants

* Make settings use TypeScript

* Update CURRENT_USER_IS_ADMIN usage

* WORD_COUNT_TYPE

* REST_API_ROUTES

* REVIEW_RATINGS_ENABLED and SHOW_AVATARS

* Remove REVIEW_RATINGS_ENABLED and SHOW_AVATARS constants

* Remove MIN_HEIGHT

* Remove DEFAULT_HEIGHT

* PLACEHOLDER_IMG_SRC

* LIMIT_TAGS

* HAS_PRODUCTS

* HOME_URL

* HAS_TAGS

* COUPONS_ENABLED

* SHIPPING_ENABLED

* TAXES_ENABLED

* DISPLAY_ITEMIZED_TAXES

* SHIPPING_COST_REQUIRES_ADDRESS

* SHIPPING_STATES and SHIPPING_COUNTRIES

* STORE_PAGES

* ALLOWED_COUNTRIES

* ALLOWED_STATES

* SHIPPING_METHODS_EXIST

* PAYMENT_GATEWAY_SORT_ORDER

* CHECKOUT_SHOW_LOGIN_REMINDER

* CHECKOUT_ALLOWS_GUEST and CHECKOUT_ALLOWS_SIGNUP

* ATTRIBUTES

* DISPLAY_CART_PRICES_INCLUDING_TAX

* DISPLAY_CART_PRICES_INCLUDING_TAX

* update build for TS files

* fix build dir

* Move blocks build config params

* Move placeholderImgSrc to core settings

* Move rest api hydration hoc to shared hocs and provide it restApiRoutes directly to avoid asset data registration

* Move wordCountType to abstract block

* Remove WORD_COUNT_TYPE in favour of getSetting

* Move IS_LARGE_CATALOG and PRODUCT_COUNT to abstract block type and use getSetting inline

* Add wcBlocksConfig

* fix tests

* Remove unused $asset_data_registry

* remove console.log

* Move build settings to abstract block

* Trigger build again

* Move hydration back to regular hocs for compatibility with trunk (merge conflict)

* Removed wcSharedHocsConfig

* esc home url

* Update search fixture

* Update search snap

* 40000 timeout

* hasProducts -> productCount

* Product Count is part of blocks config

* update mocks

* Use version comparison to determine if batching is enabled

* Change isWpVersion

* scrollTo button
2021-04-22 12:37:27 +01:00
Thomas Roberts f6220c434c Make error messages in front-end cart E2E tests better (https://github.com/woocommerce/woocommerce-blocks/pull/4077)
* Wrap waitForFunction calls in try catch to better explain why test fails

* Change to .catch and make error message better

* Remove jest.setTimeout
2021-04-21 11:51:10 +01:00
Mike Jolley 171642b8a5 Rest API batching support (2) (https://github.com/woocommerce/woocommerce-blocks/pull/4075)
* Add batch route

* Register batch route

* Allow batching on writable endpoints

* Batch in client

* Batch non-GET requests

* Batching support with typescript defs

* Remove unused hook

* Prevent multiple fragment updates

* Only use batch route if detected

* Correct var name

* Move nonce check to validate_callback so it runs before requests are completed

* remove unused imports

* updateCartFragments function as const

* Add phpunit tests for batching functionality

* Reduce batch delay

* increase timeout

* Update isCartUpdatePostRequest for batch support

* Update Endpoint used in test

* Move nonce check back inline - custom headers are not returned otherwise

* Fix error handling

* Back to 30s

* Update assets/js/middleware/cart-update.ts

Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com>

* whitespace

Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com>
2021-04-20 16:44:49 +01:00
Darren Ethier 309b3614c5 Revert "Rest API batching support (https://github.com/woocommerce/woocommerce-blocks/pull/3899)"
This reverts commit 5b65a02297.

This commit broke cart updates for the cart block (surfaced with changing quantity)

There were also legit e2e test fails for the cart-update middleware behaviour that weren’t addressed.
2021-04-18 11:58:51 -04:00
Mike Jolley 5b65a02297 Rest API batching support (https://github.com/woocommerce/woocommerce-blocks/pull/3899)
* Add batch route

* Register batch route

* Allow batching on writable endpoints

* Batch in client

* Batch non-GET requests

* Batching support with typescript defs

* Remove unused hook

* Prevent multiple fragment updates

* Only use batch route if detected

* Correct var name

* Move nonce check to validate_callback so it runs before requests are completed

* remove unused imports

* updateCartFragments function as const

* Add phpunit tests for batching functionality

* Reduce batch delay

* increase timeout
2021-04-16 13:45:56 +01:00
Thomas Roberts d057618b24 Fix failing e2e tests (https://github.com/woocommerce/woocommerce-blocks/pull/4068)
* Remove unused fixtures

* Update package-lock.json

* Update product-search fixture and snapshot

* Ensure the product is selected before continuing with the test.

This clicks the test at least once, or at most thrice to ensure it is checked before trying to evaluate the rest of the test.

* Revert "Remove unused fixtures"

This reverts commit e4a4e11b72c6723341d60391bd9cb9cc4197efaf.

* Look for button with aria-label: 'Toggle block inserter'

* Revert "Look for button with aria-label: 'Toggle block inserter'"

This reverts commit a25ea8d9abafead372ef24b2feb92ff58bd95cea.

* Update @wordpress/e2e-test-utils to 5.1.2

* Check for existence of add block button
2021-04-16 11:48:27 +01:00
Albert Juhé Lluveras 5e0c4cf0ce Add initial e2e tests to Checkout block frontend (https://github.com/woocommerce/woocommerce-blocks/pull/4004)
* Add initial e2e tests to Checkout block frontend

* Fix comment format

* Scroll to payment methods before checking if they are clickable

* Typos

* Implement caching in getBlockPagePermalink to improve e2e test performance

* Revert "Typos"

This reverts commit 1b544276056084f73d5bcdfa391d5438590e4782.

* Simplify product price definitions

* Move scrollTo function to utils
2021-04-14 15:50:27 +01:00
Thomas Roberts 00b20bdac7 Strip tags from exceptions that are converted from notices (https://github.com/woocommerce/woocommerce-blocks/pull/4005)
* Strip tags that are added to notices

* Add test to ensure HTML is stripped by convert_notices_to_exceptions

* Test function directly, rather than through validate_cart_items

* Apply correct formatting to tests/php/StoreApi/Utilities/NoticeHandler.php

Co-authored-by: Albert Juhé Lluveras <contact@albertjuhe.com>

Co-authored-by: Albert Juhé Lluveras <contact@albertjuhe.com>
2021-03-29 10:51:12 +01:00
Thomas Roberts 1a0b432669 Ensure cart changes remain after using back button to get back to the cart (https://github.com/woocommerce/woocommerce-blocks/pull/3960)
* Add cartUpdate middleware

* Include timestamp for when cart data was generated

* Add getCartFromApi action

* Check whether cart can be hydrated or needs to be fetched from API

* Add cartDataIsStale action and remove getCartFromApi action

* Add isCartDataStale selector

* Don't load cart until staleness check is complete

* Add comment to ease worry about locaStorage execution

* Correct doc block and fix typographical error

* Cater for lastCartUpdate or the timestamp being undefined

* Include @woocommerce/api and @woocommerce/e2e-utils

* Add getNormalPagePermalink test utility

This will allow us to get the permalink of a "normal" page, i.e. one that is not using the block editor.

* Add getBlockPagePermalink test utility

This will get the permalink for a page using the Block editor.

* Emit action to update cart staleness in all execution paths

* Add visitPostOfType function

This will allow us to visit the editor page for a post based on its name and post type.

* Add functions to get permalinks from editor pages

* Add front-end tests for cart

* Update package-lock.json

* Create local function to ensure the page permalink is visible

* Change functions for getting permalinks
They were often failing for unknown reasons, these _somehow_ make them more stable.

* Add logging for GitHub actions

* Add more logging for tests

* Add more logging for tests

* Add more logging for tests

* Wait for networkidle on back

* Remove logging except timestamp

* Wait for timestamp to be added to localStorage

* Split tests to make runs slightly shorter

* Wait for add to cart request before continuing test

* Fix formatting in cart.test.js

* Rename cartDataStale to setIsCartDataStale

* Create constant for localStorage timestamp name

* Rename cartDataIsStale to isCartDataStale

This is for consistency, the action to change this is called setIsCartDataStale - I think this reads better.

* Use cleaner logic when determining if the cart should render or fetch

* Change docblock for isCartDataStale selector

* Remove boolean cast from SET_IS_CART_DATA_STALE reducer

* Set longer timeouts for frontend cart tests

* Enclose cart staleness checks in condition/prevent unnecessary execution

* Remove unnecessary boolean cast from selector

* Use constant for local storage key in tests

* Use new localstorage key in tests. cant access constants in page context
2021-03-24 13:28:11 +00:00
Albert Juhé Lluveras c7bec5bcd2 Remove checks for WP 5.4 from e2e tests (https://github.com/woocommerce/woocommerce-blocks/pull/3993)
* Remove checks for WP 5.4 from e2e tests

* Update e2e local environment set up docs
2021-03-23 15:09:04 +01:00
Albert Juhé Lluveras b6403bd66c Show compatibility notice when adding the Cart and Checkouts blocks in the editor (https://github.com/woocommerce/woocommerce-blocks/pull/3937)
* add guide

* Add missing translation strings

* Use localStorageState so dismissing the compatibility notice is persisted

* Add types

* Split notice text in two paragraphs

* Update notice texts

* Remove unnecessary empty line

* Cleanup

* Prevent Gutenberg stealing focus (and closing) guide modal

* Add tests

* Don't show compatibility notice in WP <= 5.4

* Don't have tests inside if clauses

* Fix test breaking in latest Gutenberg version

* Remove unnecessary openDocumentSettingsSidebar

* Rename CompatibilityNotice to CartCheckoutCompatibilityNotice

* Add try/catch blocks around JSON operations in useLocalStorageState

* Create useCompatibilityNotice hook

Co-authored-by: Seghir Nadir <nadir.seghir@gmail.com>
2021-03-19 11:05:42 +01:00
Mike Jolley f856756ace Update Single Product Test (https://github.com/woocommerce/woocommerce-blocks/pull/3924)
* Update Single Product Test

* duplicate test

* Try adding npm install @wordpress/e2e-tests@1.9.1

* @wordpress/e2e-test-utils@4.5.0
2021-03-05 13:33:58 +00:00
Thomas Roberts e49a7eaffd Update Label component to TSX (https://github.com/woocommerce/woocommerce-blocks/pull/3889)
* Add tsconfig to components directory and include it as project

* Add @types/classnames package

* Migrate Label component to TSX

* Remove unused imports from Label component

* fix package-lock.json

It was generated with npm 7 and we don’t support that yet (and that update should be done in a separate pull)

* Add interface for LabelProps and implement.

Also:
- import `Fragment` from @wordpress/element.
- import `HTMLAttributes` explicitly as a type from react (@types/wordpress__element doesn’t export this interface).

* fix jest configuration

Co-authored-by: Darren Ethier <darren@roughsmootheng.in>
2021-02-26 11:57:49 +00:00
Seghir Nadir 30c2079af4 Enhance checkout filter system. (https://github.com/woocommerce/woocommerce-blocks/pull/3835)
* Add filter to extend product price

* Remove code targeting WC Subscriptions

* Rename filter

* Use extendibility API instead of filters

* Remove __EXPERIMENTAL_CART_ITEM_PRICE_FILTER from docs

* throw errors on validation

* Don't catch filter errors for admins

* Add tests

* wrap filter calls in memo

* pass extensions as top level prop

* abstract errors

* add jsdoc

* update tests

* review

* turn __experimentalApplyCheckoutFilter into a hook and move useMemo inside it

* revert name

* wrap getCheckoutFilters in useMemo

* refactor filter function so memozation is done inside components

* unify true instance

* fix rebase

Co-authored-by: Albert Juhé Lluveras <contact@albertjuhe.com>
2021-02-17 14:01:20 +01:00
Thomas Roberts edf79c699a Catch errors during cart validation (https://github.com/woocommerce/woocommerce-blocks/pull/3703)
* Add new exceptions for out of stock scenarios

These are needed to differentiate between the different stock validation errors, and so we can create the correct error message.

* Catch new out of stock exceptions when checking the cart for errors

This is so we can get the cart sent back to the client, if we don't catch these, then the route will just return a 500 error and crash.

* Add ArrayUtils class

This will contain methods used to operate on arrays that don't fit anywhere else.

* Handle the case in Checkout where the error is already a WP_Error

This will happen when the cart fails validation.

* Handle StockAvailabilityException in AbstractRoute

This will happen when an item or number of items in the cart are out of stock/insufficient stock.

* Throw exceptions for each type of invalid stock in validate_cart_items

This will allow us to create an error message for each type of violation to display to the user.

* Display additional error notices returned by the API

* Fix wording when throwing exceptions relating to stock

* Handle TooManyInCartException in CartController

* Abstract the merging of cart, status, and additional data into new fn

This allows us to simplify the way errors are returned from the API. The reason we have to add all of the data at once is because of how WP_Error works with the additional data, if there is already existing data in a WP_Error object, it gets moved into additional_data. By adding all of the data in one place, we stop this from happening. Also since we're only adding status and/or cart explicitly, it makes sense to just do it in one place.

* Add get_route_error_response_from_object method

This is so we can differentiate between a string and WP_Error object.

* Remove unnecessary slashes from WP_Error instantiation

* Add option to enclose each item in quotes in natural_language_join

* Abstract adding error messages to error object into single function

A lot of code was repeated, so doing this cuts down on that and ensures any changes only need to be made in one place.

* Create new parent exception for each type of out of stock exception

This is so we don't have to repeat code inside each different exception and we can simply inherit StockAvailabilityException.

* Catch the generic StockAvailabilityException in get_cart_item_errors

* No longer recalculate totals in validate function

It is not needed, the totals are recalculated elsewhere. This call was superfluous.

* Reduce nesting, and only throw exception if error object has errors

* Improve comment on get_route_error_response_from_object method

* Fix nesting when throwing the InvalidStockLevelsInCartException

* Catch errors during cart validation

* Add get_error_message_for_stock_exception_type function

This will be used to get an error message depending on the type of extension, and whether the plural form, or singular form is needed. This abstraction is better because the code is used in more than one place in the API.

* Use error message generation function instead of creating errors individually

* Use specific error codes for each type of error & fix PHPDoc

Now the stock_exceptions_to_wp_errors function will return an array of WP_Errors this is better as the client needs a distinct error code to display and replace notices.

* No longer remove items from cart or modify quantity if there is an error

* Return the WP_Error from RouteException or all Stock WP_Errors

* Fix error in PHPDoc

* No longer necessary to add get_cart_item_errors into an array

This is because the method always returns an array now.

* Rename variables in get_cart_item_errors to be more descriptive

* Improve PHPDoc on get_cart_item_errors

* Replace underscores with hyphens in error code

* Only return WP_Errors that have an actual error in them

* Add unit test for ensure the cart errors relating to stock are handled

* Fix typo in comment

* Use optional chaining to add errors to cart
2021-02-15 14:03:04 +00:00
Mike Jolley 7772d41007 Extensibility for Block Checkout Address Fields (https://github.com/woocommerce/woocommerce-blocks/pull/3662)
* Pass get_country_locale via assets

* Create helper to prepare and merge address fields

* Use new helper in address form

* Only pass field overrides now that fields are merged

* Fixc configs and remove lodash usage

* Prevent formatting of empty postcodes to suppress api error

* prevent memo on rerender

* Conitonal enqueue of locale data

* define index in increments of 10

* remove address-form

* circ deps changes

* Workaround for core data issue

* fix test

* remove prepareAddressFields export

* Remove old comment

* object from.entries polyfil

* Revert "object from.entries polyfil"

This reverts commit ba343adcf5fd2f843b225aebe340cce9b664c851.

* replace fromentries

* fix final fromentries
2021-02-11 16:49:27 +00:00
Seghir Nadir 99b78a1c9a add price package (https://github.com/woocommerce/woocommerce-blocks/pull/3790) 2021-02-04 15:30:28 +00:00
Mike Jolley 7ae87ca367 Subscriptions Shipping Packages Integration Points (https://github.com/woocommerce/woocommerce-blocks/pull/3687)
* Expose schemas

* Accept strings for select shipping rate

* strings are allowed

* Refactor shipping package to hold it's own state

* Add extension data to cart hook

* Progress but state is broken

* Move state back to hook

* Progress but state is broken

* use shipping hook updates

* Fix re-render issue

* hide x1

* Shipping slot fill

* Working slot fills

* Do not export package

* Update extend usage in unit tests

* update mock test data

* Package per slotfill

* Resolved merge conflicts

* Update assets/js/blocks/cart-checkout/subscriptions-integration.js

Co-authored-by: Seghir Nadir <nadir.seghir@gmail.com>

* rename slot

* deriveSelectedRates return doc

* useCallback in throwError

* final class ExtendRestApi

* spacing

* Move shipping rate selection to package level

* remove const for counts

* Remove schemas from extend

* unused use

* move to a single fill for packages

* add todos

* move subs code

* fix extra extensions

Co-authored-by: Seghir Nadir <nadir.seghir@gmail.com>
2021-01-28 15:24:01 +01:00
Darren Ethier dd1415c73b Fix broken PHPunit tests (https://github.com/woocommerce/woocommerce-blocks/pull/3690)
* Ensure phpunit tests are running against the blocks code and not what is included in WooCommerce core.

* cast to object to correct response expectations.

The change in https://github.com/woocommerce/woocommerce-gutenberg-products-block/pull/3679/files#diff-5d8cf88af3d9be56abf0b110a7500b3711552009533d894e07f0e891b4af266eL317 resulted in a change in shape for the response.
2021-01-16 08:48:46 +01:00
Vedanshu Jain 6d8aa16d4c Add protection around mock queries in unit tests. (https://github.com/woocommerce/woocommerce-blocks/pull/3602)
* Add protection around mock queries in unit tests.

This adds additional checks before mocking wc_get_orders query results to prevent overriding refunds query. This is needed with WC core 4.9 since it does an addtional wc_get_orders query to preload and hydrate cache for refunds in order to improve performance.

* update jetpack autoloader to 2.7.1

Co-authored-by: Seghir Nadir <nadir.seghir@gmail.com>
2021-01-14 15:48:57 +01:00
Albert Juhé Lluveras 2c8d85d18d Cart & Checkout blocks: print all item data and update variation designs (https://github.com/woocommerce/woocommerce-blocks/pull/3665)
* Cart and Checkout blocks: show all item data and update variations design

* Add class with detail name to product details
2021-01-12 11:04:53 +01:00
Albert Juhé Lluveras b4a37aebd6 Create @woocommerce/checkout to export components to a global (https://github.com/woocommerce/woocommerce-blocks/pull/3654)
* add plugin area

* add invisible errorBoundary

* introduce slot

* change name to OrderMeta

* fix rebase

* wip

* create checkout file

* Import ExperimentalOrderMeta from @woocommerce/checkout

* Rename wc-checkout-packages handle to wc-blocks-checkout

* Only import wc-blocks-checkout in the feature plugin

* Move checkout package to packages folder

* Add @woocommerce/blocks-checkout to tsconfig

* Move TotalsItem to @woocommerce/checkout

* Use Fragment short syntax

* Remove example code

* Honor renderError prop in BlockErrorBoundary

* Rename error boundary

* Add example code

This reverts commit 9b6af7178cbef05589779ef7f5a750d53e7fc8cf.

* Revert "Add example code"

This reverts commit 2f50349692f53c5bb143516365eee7a98d580dfd.

* Add @woocommerce/blocks-checkout to jest config

Co-authored-by: Seghir Nadir <nadir.seghir@gmail.com>
2021-01-07 13:02:21 +01:00
Albert Juhé Lluveras fb5c0f3af2 Add tests to AddressForm (https://github.com/woocommerce/woocommerce-blocks/pull/3621)
* Remove unnecessary async key in read more tests

* Add tests to AddressForm component
2021-01-06 10:22:51 +01:00
Thomas Roberts 9a537fdab5 Create GitHub actions for automated tests (https://github.com/woocommerce/woocommerce-blocks/pull/3544)
* Create end-to-end-tests.yml for E2E testing action

* Change actions to run on push instead of PR

* Install libstdc++-4.9-dev on E2E tests action

* Add correct apt repository for libstc++

* Reconfigure apt-get commands for installing libstdc++

* Remove accidental inclusion of Travis config from E2E tests action

* Install libkrb5-dev as part of e2e test action

* Run apt commands as sudo

* Install gutenberg plugin and e2e testutils

* Add environment variables to E2E tests

* Rename action and add further config for composer and wp-env

* Rename workflow

* Add jobs for WP 5.6, 5.5, and 5.4

* Fix YML indentation

* Apply 767 permissions to wp-env directory

* Run chmod as sudo

* Comment 5.6 and 5.6 with GB out to test 5.4 more easily

* Remove WP install job, since it should run on each step

* Change order of wp-env start and chmod

* Reorder commands for 5.4 job

* Try running 5.4 tests in isolation

* Reenable tests for all WP versions

* Move commands out of bash script into a series of commands

* Fix indentation on 5.5 job

* Re-enable libkrb5-dev install

* Clean wp-env before each run & upgrade wp-env to 3.0.0

* Update lock file for wp-env@3.0.0

* Reorder wp-env start and clean commands

* Reorder wp-env permissions commands

* Reorder wp-env permissions setup for all jobs

* Reorder wp-env permissions setup for 5.5 and 5.4

* Ensure correct order for env setup and flush permalinks twice

* Update jest snapshots

* Remove rewrite flush command from yml

* Remove npm build from every step and try it just at the start

* Set correct e2e build script

* Add jobs for PHP 8

* Specify PHP 8 minor version

* Run PHP 8 jobs first

* Remove PHP 8 jobs

* Add JS Unit tests job

* Remove js-unit-tests.js workflow

* Remove composer install from every step, add it to its own step

* Cache composer files

* Bust npm cache to test nodegit

* Rename npm cache

* Renove npm cache entirely

* Revert "Renove npm cache entirely"

This reverts commit d6fac6a6ebd9162e48f64daaa8c971320756579e.

* Rename npm cache back to how it was

* Fix yml indentation

* Remove echo from composer cache step

* Revert back to composer example

* Add PHP Unit tests to workflow

* Add PHP Unit tests to workflow

* Rename E2E tests workflow and file

* deliberately break e2e and unit tests to test workflow 👺

* fix php test, should see e2e fail

* revert broken e2e test

* Change steps into jobs, rename workflow

* Remove Travis workflow file

* Add all necessary setup steps to each job

* Rename Setup job and remove dependency

* Add individual jobs for each E2E test environment

* Add npm install and build to setup job

* YML syntax fix

* Remove error-causing chmod

* Rename blocks.ini setup step

Fixes a typographical error.

* Get the latest stable version of WooCommerce for PHPUnit testing

* Add PHP8.0 and PHP5.6 Unit tests

* Run composer update for PHP 5.6 and PHP 8.0

* Revert "Run composer update for PHP 5.6 and PHP 8.0"

This reverts commit 4f90522d0b52b7a8b9e896e9c783795be9dc5399.

* Revert "Add PHP8.0 and PHP5.6 Unit tests"

This reverts commit 66e317dec4af6e3a2ac6f78b6efd050e7fc5aa8e.

Co-authored-by: Rua Haszard <rua.haszard@automattic.com>
2021-01-05 09:27:22 +00:00
Thomas Roberts 84f83f840c Get the latest stable version of WooCommerce for PHPUnit testing (https://github.com/woocommerce/woocommerce-blocks/pull/3594) 2020-12-23 16:10:25 +01:00
Rua Haszard 0783108d19 use consistent product name `WooCommerce Blocks` (https://github.com/woocommerce/woocommerce-blocks/pull/3567)
* use consistent product name `WooCommerce Blocks:
- readme.md title
  + update product vision paragraph
- update references in readme.txt preamble
- update in tests bootstrap message

* add WCCOM/docs links front & centre in readme for convenience
2020-12-23 08:49:45 +13:00
Mike Jolley 55f0bc73a6 Fix Address Validation in the Store API and client (https://github.com/woocommerce/woocommerce-blocks/pull/3552)
* Trim input values before validation on Checkout

* Fixes required field checking at schema level

* Require country during checkout and ensure values are formatted

* Add handling for rest_invalid_param messages

* Remove prepare_address_fields - handled by schema

* Add address validation to OrderController

* Implement address validation

* Error errors from all endpoints more gracefully

* update non-true description

* required prop

* Update tests

* Fix equalityFn so updates are triggered when address changes

* Remove debounce so fields update if context changes

* Update src/StoreApi/Schemas/AbstractAddressSchema.php

Co-authored-by: Albert Juhé Lluveras <contact@albertjuhe.com>

* Add missing wp_unslash

* Validate allowed countries should block checkout if no countries are allowed

* Type in locale variable

* Update assets/js/base/utils/errors.js

Co-authored-by: Darren Ethier <darren@roughsmootheng.in>

* Fix validator calls

* Remove refererence

* Restore onChange order

* eslint fix

Co-authored-by: Albert Juhé Lluveras <contact@albertjuhe.com>
Co-authored-by: Darren Ethier <darren@roughsmootheng.in>
2020-12-17 14:52:44 +00:00
Albert Juhé Lluveras 01c1ce8ffb Update WP versions used in Travis e2e tests (https://github.com/woocommerce/woocommerce-blocks/pull/3535)
* Update WP versions used in Travis e2e tests

* Remove WP 5.3 tests

* Remove legacy WP version checks in e2e tests
2020-12-09 17:09:45 +01:00
Mike Jolley 6825dc909f Add Formatter Classes to the Store API for Extensions to Consume (https://github.com/woocommerce/woocommerce-blocks/pull/3503)
* Create and register formatter classes

* Update Schema to use formatter classes

* Update tests

* Currency formatter

* Fix tests

* Use wc_get_price_decimals() as default

* Exception on non existing formatter call

* Feedback

* remove setter
2020-12-03 19:17:03 +01:00
Mike Jolley ea52a2a2d5 Drop stock reservation when removing item from cart via the Store API (https://github.com/woocommerce/woocommerce-blocks/pull/3468)
* Remove Blocks version of ReserveStock Class

* When a cart item is removed, remove holds on stock

* Move maybe_release_stock to abstract

* Update ReserveStockException usage
2020-12-02 16:03:24 +00:00
opr fcfe5ee7dc Stop hidden products from being linked in cart and checkout blocks (https://github.com/woocommerce/woocommerce-blocks/pull/3415)
* Add catalog_visibility to CartItemSchema.php

This is used to get whether the product is visible in the catalogue, visible in the shop only, visible in search results only, or visible everywhere. We need to know this so we can pass it to the ProductImage and ProductName components.

* Remove links from CartLineItemRow if not visible in catalogue

Added catalog_visibility to lineItems prop, and when the product is not visible in the catalogue do not wrap product image in a link. Also pass down the hasLink prop to ProductName.

* Add hasLink prop to ProductName

When this prop is false we should not output the link around the product name. This is for when the product is hidden from the catalogue but we still want to show its name somewhere.

* Add tests and storybook for ProductName

* Add catalog_visibility check to OrderSummaryItem

When the catalogue visibility of a product is set to hidden or search, then the product name in the checkout sidebar should not be hyperlinked.

* Reverse logic for hiding link on product image & disabling link on name

Following a point from @budzanowski we do not need the hasLink prop, making use of disabled is probably a better idea.

* Remove tabindex from a in ProductName & output span if name is disabled

This change removes the need to pass a tabindex to the a in ProductName. This is because a disabled ProductName will now never output an a tag. When the ProductName is disabled a span is output instead, which has no tabindex by default.

This change also reverses the logic to decide whether the a or span should be output so as to make the code more readable and flow better.

* Update storybook and tests/snapshots for ProductName
2020-11-23 13:03:08 +00:00
Mike Jolley 849e351a0e Sync shipping address with billing address when shipping address fields are disabled (https://github.com/woocommerce/woocommerce-blocks/pull/3358)
* Correct docblock description

* Sync shipping address changes with billing data

* Update inline documentation

* Revert address sync because it fails when shipping is disabled explicitely

* Avoid loading shipping address from customer is shipping is disabled

* Rather than update order from the wc/store/checkout request, update the customer object

This is turn is synced to order, but also allows the cart calcultions to use the posted data. This means that taxes will be updated based on address data even if not displayed on the checkout.

* Add action that combines billing and shipping updates

* Add route for updating billing and shipping address

* Sync billing data to server on change

* Shared constants for billing data

* Skip address update if missing country

* Allow null values to skip formatting

* Add billing to cart schema

* Removed unwanted hooks from previous commit

* Decoding is handled in useStoreCart

* Remove hook

* Make shipping context hold state

* Make billing context hold state

* Add address processors

* Cart does not have billing

* Update tests, remove some unrelated changes affecting the diff

* Revert "Update inline documentation"

This reverts commit 0393f49316de3152c6dcf6fda1192c06a74f1b55.

* Make shippingRatesAreResolving conditonal based on API request

* Shared address processor in cart and checkout

* Rename REST endpoint

* CustomerDataProvider and hook

* Update shipping address type defs

* Rename customer address endpoint, and remove update-shipping

* Update tests

* Fix tests by restoring country validation

* typo

* Update assets/js/base/hooks/cart/use-store-cart.js

Co-authored-by: Darren Ethier <darren@roughsmootheng.in>

* Simplify debounce and request handling

* Remove state from address sync

This will mean billing is "forgotten" if using the checbox, but this greatly simplifies logic.

* Rename shipping rates loading to customer data loading

* Sync based on useStoreCart data

* Made cart API less strict on addresses

* Fix useCheckoutAddress sync

* Add note on currentShippingAsBilling

* Use incoming isCart

* Add more detailed inline comment for shippingAsBilling toggle event

* Combine customer billing and shipping ref

* Update address docblock

* Error handling in pluckAddress

* Fix cart response after rebase

* Update customer tests

* Update src/StoreApi/Routes/CartUpdateCustomer.php

Co-authored-by: Darren Ethier <darren@roughsmootheng.in>

Co-authored-by: Darren Ethier <darren@roughsmootheng.in>
2020-11-20 15:13:35 +00:00
Albert Juhé Lluveras e3163dc00d Add FeatureGating parameter to Package in tests (https://github.com/woocommerce/woocommerce-blocks/pull/3413) 2020-11-17 12:25:38 +00:00
Mike Jolley ec22a5c6c4 Cart and checkout should respect the global "Hide shipping costs until an address is entered" setting (https://github.com/woocommerce/woocommerce-blocks/pull/3383)
* Remove custom fieldconfig for shipping calculator so required fields for shipping are collected

* If the store config requires an address before shipping, do not return rates or totals

Totals, calculated by the cart, would be set to 0 in this scenario which could lead to customer confusion (why is the rate $10 but shipping shown as $0?)

* The shipping total row is missing a border

* Revert "If the store config requires an address before shipping, do not return rates or totals"

This reverts commit f3a4f24f5785392eb43bfc69a5548d398c47d8bb.

* Add hasCalculatedShipping to schema and hooks

* Show shipping notices with updated wording based on if shipping has calculated yet or not

* Refactor shipping row display to use new API props

* Remove block level isShippingCostHidden

* fix test

* Correct the math in the shipping preview in cart

* Document null

* Remove test—this option no longer exists

* Remove unused settings/constants
2020-11-17 11:58:38 +00:00
Albert Juhé Lluveras 6753023e08 Move feature flag PHP logic to a service class (https://github.com/woocommerce/woocommerce-blocks/pull/3343)
* Move feature flag PHP logic to a service class

* Add legacy methods

* Inject a FeatureGating class instance into Package

* Make is_experimental_build and is_feature_plugin_build methods non static
2020-11-17 08:46:12 +01:00
Seghir Nadir a576ba8d67 Introduce ExtendRestApi (https://github.com/woocommerce/woocommerce-blocks/pull/3356)
* initial prototype for ExtendRestApi

* return before assign

* fix phplint errors

* declare Throwable

* remove empty init

* return initial data if shape is not correct

* Add IDENTIFIER to schema classes

* refactor ExtendRestApi to not use filters

* remove extra check

* implement ExtendRestAPI injected into StoreAPI schemas

* use $extend instead of $extend_schema

* fix phpcs issues

* update schema

* fix data type

* address review

* fix object cast

Co-authored-by: Darren Ethier <darren@roughsmootheng.in>
2020-11-16 13:31:27 +01:00
Darren Ethier f3fdbd7b59 Fix account creation bugs (https://github.com/woocommerce/woocommerce-blocks/pull/3371)
* account for registration enabled setting when creating accounts

* default to false instead of global setting for initial allowCreateAccount attribute

* consider global allows signup value for whether account creation checkbox shows

* include existing hook when determining if checkout signup is available:
- woocommerce_checkout_registration_enabled hook

* use public api for registration settings (via WC_Checkout)

* initial round of test fixes

* fix logic flaw exposed by tests and align tests with actual values in real use

* return early if WC_Checkout is not available

* remove temporary test group and uncomment new test.

* improve test method name

* fix comment to match new routine name

* ensure block shows login prompt when store disables checkout signup

* fix incorrect conditional order and cover with tests

Co-authored-by: Rua Haszard <rua.haszard@automattic.com>
2020-11-05 15:22:43 +13:00
Seghir Nadir 2482e307e0 Save order after creating an account (https://github.com/woocommerce/woocommerce-blocks/pull/3260)
* Save order after creating an account

* create account before saving

* fix tests

* remove order from createOrder

* rename variable

* fix tests
2020-10-28 15:18:22 +01:00
Bartosz Budzanowski 58734be009 Fix Gutenberg e2e tests failures. (https://github.com/woocommerce/woocommerce-blocks/pull/3324)
* Add e2e utils file.

* Update tests to use new utils.

* Remove allow failures.
2020-10-27 13:24:53 +01:00
Remi Corson 181797906a E2E WC Core Terms Consistency (https://github.com/woocommerce/woocommerce-blocks/pull/3310)
* E2E WC Core Terms Consistency

fixes 3309

* fix test text

Co-authored-by: Seghir Nadir <nadir.seghir@gmail.com>
2020-10-22 09:49:55 -04:00
Rua Haszard f000fb4f7a Support "create account" option in checkout block (https://github.com/woocommerce/woocommerce-blocks/pull/2851)
* prototype 'create account' checkbox in checkout block

* expose store config for generating password/username  to blocks:
+ use FILTER_VALIDATE_BOOLEAN instead of hard-coded `yes`

* stub out signup form in checkout block

* context / provider to store checkout signup form data

* revert signup form - checkout block will always generate username etc

* persist signup checkbox in checkout state & pass to checkout API

* add `create_account` param to order API, fix name in client POST

* handle creating user account as part of order (first cut)

* ensure the order is associated with the new customer

* only show 'create account' checkbox when appropriate (guest checkout)

* remove unnecessary username/password variables

* refactor account-creation logic into functions:
- clarify inputs and outputs
- use RouteException for error handling
- use woo options directly, avoid dependency on WC_Checkout

* update "email exists" error message to use existing error message text

* handle all known errors from wc_create_new_customer + use core message

* only show "create account" checkbox to shopper when necessary:
- if guest checkout is disabled, user must create account - not optional

* only show "create account" if account creation is optional:
- fixes incorrect logic in previous commit
- add some comments to clarify

* fix create account logic in API when checkout requires account:
- use correct woo setting option name
- reverse logic to match option = allow guest false means registration required

* strip html tags from create account error messages

* temporarily force enable autogenerate user/pass in new account API

* fix rebase errors

* add new allowCreateAccount attribute in checkout block

* show/hide `Create account` checkbox dependent on block attribute:
- previously was dependent on store setting

* new create user API, with set initial password email (first cut):
- use core register_new_user for creating the user
  - this triggers core "set new password" email
- generate username using logic lifted from WC core
- rough cut, lots to tidy/polish here

* remove alternative/unused create account function

* set `Customer` role for signups during checkout

* eslint fix - switch case break

* remove comments that mirror code & might go stale

* tidy func comment

* remove unused function

* use store setting `allow signup` for default value of new block option

* refactor order signup logic to service class first cut:
- new CreateAccount service
- hook up via custom action (for now at least)
- paste over existing create account logic (temporary - will be replaced)

* adapt wc_create_new_customer logic in CreateAccount service (WIP)

* set default_password_nag on new account + throw instead of WP_Error

* rename `createAccount` => `shouldCreateAccount` to clarify meaning

* fix checkout block - renamed `shouldCreateAccount` (missed in prev commit)

* prototype sending alternative email template for checkout signup

* add magic link to set password to blocks new account html email

* tidy up new account email templates - set password link, subject/heading

* use same id so merchant setting tweaks apply to our new improved email

* remove logging

* code tidies in CreateAccount service:
- remove unnecessary constructor
- type-hint in should_create_customer_account
- streamline logic in should_create_customer_account - remove
unnecessary `empty` check
- add comments to illuminate different use-cases handled by should_create_customer_account

* don't provide password to new account email templates (no longer used)

* declare dependencies in root namespace

* code tidies on new account email class:
- correct namespace and camelcase name
- declare class in file, don't instantiate; instantiate in client code
(CreateAccount service) when used
- no require/file import, use `use`

* move CustomerNewEmail to folder matching namespace

* use Package->get_path for email template paths:
- CreateAccount service now depends on Package
- CreateAccount passes Package to email class so it can use `get_path`
- note: CustomerNewAccount is not registered with DI container as it
needs to be instantiated after Woo init (for `WC_Email`)
- shift email templates to {plugin}/templates, consistent with WP
convention

* call CreateAccount::from_order_request directly, no custom hook:
- custom hook is not appropriate as we may not want to allow
extensibility in this way - TBD

* add appropriate margin above create account checkbox

* remove unnecessary direct-access protection

* generalise name of error-handling method

* simplify CustomerNewAccount - instantiate directly, when needed

* remove unused new_account_email member - now instantiated on demand

* numerous fixes and updates due to rebase changes

* fix typo in name of CustomerNewAccount php file (missing `n`)

* experiment - link to lost-password form in my-account (prototype branded screen)

* Revert "experiment - link to lost-password form in my-account (prototype branded screen)"

This reverts commit e1dc6dd5e9f0218ede81da92188d813c2d0856d9.

* feature gate CreateAccount service init to dev build only +
+ remove stale comment

* feature gate front end "Create account" checkbox to feature plugin only

* feature gate editor "allow signup" option to dev build only

* feature gate checkout api create account - dev build only

* tweak feature gating PHP logic so it's robust:
- all PHP feature gating is in the service class
- all publicly-available methods return early if feature gate off
- Checkout rest API transparently calls service - no explicit feature
gate at API level

* ensure frontend/editor features are feature gated (isExperimentalBuild is a function)

* feature gate value of checkoutAllowsSignup - can only be true in feature plugin

* fix a / an typo in comment

Co-authored-by: Albert Juhé Lluveras <contact@albertjuhe.com>

* remove commented code

* hello world unit test (doesn't test anything yet)

* add a command for running unit tests when container already up:
- this should probably move to another PR/branch

* basic tests of core logic in CreateAccount service

* import isExperimentalBuild direct:
- import from alias package was causing an issue, likely a dependency cycle

* refactor from_order_request to return new user ID so it's easier to test

* test creating a customer from an order + rest request:
- i.e. a full end-to-end integration test

* delete redundant test and tidy comments

* generalise test to provider format

* refactor create-dup-user err test to use same approach as success test

* add test for when user should not be created

* don't hard-code options in "create" test, remove redundant provider in no-account-requested test

* de-generalise "user already signed up" test

* add test for malformed email

* flesh out & comment successful signup tests

* flesh out "invalid email" tests

* clarify no account requested test comment

* remove phpunit:quick - I don't think it's needed

* add comment explaining this is an integration test

* experiment – disable feature flag, is this why the tests are failing?

* revert test commit - restore feature gate (experimental flag)

* skip all tests if CreateAccount is disabled due to feature flag

* d'oh - expose CreateAccount:is_feature_enabled so can be used in tests

* add jsdoc for checkout-state shouldCreateAccount field

* remove unnecessary comment + fix whitespace/indentation

* simulate logged-out user for createaccount signup tests

* use a single, compound if statement for early return (review nitpick)

* don't hide `checkoutAllowsSignup` store setting behind feature flag:
- the feature flag should be used to enable/disable behaviour
- it's dangerous to adjust store settings/options based on feature flag

* rejig tests so they require woocommerce_blocks_phase==3:
- make feature gate method private to avoid exposing
- remove feature flag check & test skip for other builds
- set blocks phase in travis config

* remove redundant user-logout in test setup - cleaner to just require this

* use WP function bracket style (same line)

Co-authored-by: Darren Ethier <darren@roughsmootheng.in>
Co-authored-by: Albert Juhé Lluveras <contact@albertjuhe.com>
2020-10-01 15:07:16 +13:00
Darren Ethier 9115160c2f Enable and fix all jsdoc rule violations (https://github.com/woocommerce/woocommerce-blocks/pull/3168)
* add param jsdocs to satisfy jsdoc require-param rule

* Fix jsdoc-checktypes rule violations

* fix jsdoc/require-param-type rule violations

* fix jsdoc/check-param-names violations

* fix jsdoc/require-property-description rule violations

* fix rule violations for jsdoc/valid-types rule

* fix rule violations for jsdoc/require-property rule

* fix jsdoc/no-undefined-types rule violations

* fix jsdoc/check-types rule violations

* fix jsdoc/require-returns-description rule violation

* enable jsdoc/require-returns-type rule

* fix jsdoc/newline-after-description rule violations
2020-09-20 19:54:08 -04:00
Albert Juhé Lluveras 727935f04c Add several tests to Checkout block in the editor (https://github.com/woocommerce/woocommerce-blocks/pull/3058)
* Add several tests to Checkout block in the editor

* Avoid 'visibility' word for toToggleElement rule

* Refactor matchers so they receives the label instead of the text

* Make initial 'isRequired' optional

* Refactor code that produces two clicks to DRY

* Unify error messages
2020-09-14 09:46:58 +02:00
Claudio Sanches 71c2b5ba21 Remove "package" tag from files inside "src" and "tests/php" (https://github.com/woocommerce/woocommerce-blocks/pull/2972)
* Don't require package tag or file comment inside src

* Removed package from file headers

* Fixed coding standards

* fix doc blocks for REST API

* update root classes

* update phpdoc blocks for Assets and Block classes

* Domain classes

* update phpdocs for payment classes

* update phpdocs for registry classes

* update utils classes phpdocs

* missed saving one file

Co-authored-by: Darren Ethier <darren@roughsmootheng.in>
2020-09-07 14:01:07 -04:00
Darren Ethier 69ba8161b6 Add @woocommerce/eslint-plugin dependency (https://github.com/woocommerce/woocommerce-blocks/pull/3115)
* convert eslint config to use @woocommerce/eslint-plugin

- removes unnecessary dependencies
- adds e2e-tests/specs to eslint ignore (they are automatically generated)
- turns off rules that will be handled in subsequent pulls (to avoid a mammoth changeset for review).
- NOTE: prettier config needs left in because of a bug with the existing version of `@wordpress/eslint-plugin` pulled in (fixed in https://github.com/WordPress/gutenberg/pull/25068) so I left the file for now.

* prettier fixes.

* remove obsolete plugin and fixes for eslint update

This branch brings an update to eslint which also changes some syntax with plugins. So this commit:

- fixes featuer-flag plugin syntax.
- removed obsolete dependency-group plugin (which is now in the `@woocommerce/eslint-plugin` configuration.

* add to-do comment

* fixes for test runs

- this also converts our e2e test scripts to use `wp-script test:e2e`, an advantage of this is it will load CHROMIUM on demand for the e2e test run.

* fixes for test runs

- this also converts our e2e test scripts to use `wp-script test:e2e`, an advantage of this is it will load CHROMIUM on demand for the e2e test run.

* include prettier alias as a dependency

This has to be done because prettier is installed with storybook and thus the alias setup in `@wordpress/scripts` is over-ridden by the storybook import.

* another attempt at e2e-test-fix

* add some debugging and temporarily just add one e2e config test for travis

* more debugging

* try installing full puppeteer and see if fixes

* fix package-lock?

* setupSettings separately from other fixture loading

* add debugging of files

* add another console.log (hopefully trigger travis)

* split out blockPage creation to it’s own as well

* fixed! remove debugging and re-enable travis configs for entire test suite

* fix config and rename e2e-tests to e2e

- fixes the failing product-search test
- tests/e2e-tests was redundant, I changed to `tests/e2e` (this follows a file pattern change made in woocommerce core as well).

* add todo for some eslint properties

* remove unnecessary early function execution

* revert earlier commit and remove duplicate call to createBlockPages
2020-09-07 13:31:10 -04:00
Rua Haszard 5c7447f434 Rename js/components to js/editor-components (https://github.com/woocommerce/woocommerce-blocks/pull/3069)
* mass-rename js/components => js/editor-components & update webpack

* mass-change import '@woocommerce/editor-components' +
+ jsprettier quotes fix

* more mass-rename @woocommerce/editor-components

* fix up references to js/editor-components in various places:
- docs/readmes
- jest config
- typescritp config

* fix story path to match new folder/alias 'editor-components'

* fix jest tests: use new alias for editor-components

* include renamed `editor-components` in editor stylesheet cache group
2020-09-02 10:21:46 +02:00
Albert Juhé Lluveras 7ba25d63c1 Fix CartItems unit tests (https://github.com/woocommerce/woocommerce-blocks/pull/3044) 2020-08-25 10:33:41 +02:00
Albert Juhé Lluveras 8bb217cec6 Show express payment methods in the Cart block (https://github.com/woocommerce/woocommerce-blocks/pull/3004)
* Shown express payment methods in Cart block

* Fixes

* Create usePositionRelativeToViewport hook

* Typo

* Style fixes

* Remove footer push div

* Styling fixes

* Improve code clarity

* Split ExpressCheckoutFormControl into two components

* Rename visibilityObserver to referenceElement

* Replace 'useEffect' with 'useLayoutEffect'

* Add tests for usePositionRelativeToViewport

* Self-closing div

* Add explanatory comment

* Create a shim for IntersectionObserver

* Update express payment components class names

* Add todo comment to remove IntersectionObserver shim when we drop IE11 support
2020-08-20 16:14:12 +02:00
Seghir Nadir 69ff731b4e use TextControl instead of PlainText (https://github.com/woocommerce/woocommerce-blocks/pull/3014)
* use TextControl instead of PlainText

* update e2e test

* revert changes for label

* update test
2020-08-18 12:25:48 +01:00
Darren Ethier 3078b97534 Fix phpunit test config (https://github.com/woocommerce/woocommerce-blocks/pull/3001)
* set path for WP install on unit tests to ensure latest is always installed.

* fix tests using deprecated method
2020-08-12 10:54:02 -04:00
Darren Ethier dcdc5c48ce Improve behaviour of draft order cleanup to account for clobbered custom shop order status. (https://github.com/woocommerce/woocommerce-blocks/pull/2912)
* improve behaviour of draft order cleanup with tests

* hide error logging output from tests

* fix doc

* fix status check and test setup/teardown
2020-08-07 15:36:55 -04:00
Albert Juhé Lluveras b29f5d4e86 Fix WP_CONTENT_DIR path in PHP unit tests (https://github.com/woocommerce/woocommerce-blocks/pull/2935) 2020-07-30 10:41:13 +02:00
Albert Juhé Lluveras 8ace5dbcf8 Add attributes and view toggle tests to the Cart block (https://github.com/woocommerce/woocommerce-blocks/pull/2883)
* Add more tests to the Cart block

* Add page settings

* Cleanup
2020-07-29 14:39:15 +01:00
Darren Ethier a0b28f2a06 Fix typo in state property for idle status in checkout state reducer (https://github.com/woocommerce/woocommerce-blocks/pull/2925)
* fix typo in state property for idle status in checkout state reducer

* remove arg causing failure in phpunit tests on travis
2020-07-29 13:00:26 +02:00
Mike Jolley cd9f7e0ccb ⚛️ Introduce Product Element Blocks (https://github.com/woocommerce/woocommerce-blocks/pull/2871)
* Product selection when out of context for price and title blocks

* Move product element name/description/icons to constant files

* Add attributes and hocs to all elements

* Standalone block rendering

* Add a placeholder if title has no content

* Revert "Add a placeholder if title has no content"

This reverts commit 29115154b33eedc661ccd3cc758acdbc5041ffbc.

* parentClassName is not always present

* Loading state

* Wrap description in P

* Fixed loading styles when nested

* Maintain product shape in useProductData

* feature gate elements from showing in inserter

* fix feature flag

* include price PR

* edit withProductSelector to be a hoc

* fix lint issue

Co-authored-by: Seghir Nadir <nadir.seghir@gmail.com>
2020-07-22 13:20:54 +01:00
Darren Ethier 60b1422cf6 Move Draft order logic behind feature flag. (https://github.com/woocommerce/woocommerce-blocks/pull/2874)
* refactor all draft order functionality to be in it’s own class and feature gate it.

* move and fix tests for draft order deletes

* add test to ensure only draft orders are deleted

* implement review feedback and assert valid results before deleting

* update tests

* doh method can’t be protected

* fix conditional for removing scheduled action

* switch to use Woo Core function for catching the exception

* add tests for error handling.

* use `$wpdb->prepare` and remove temp group on test
2020-07-16 12:19:31 -04:00
Albert Juhé Lluveras 8bfb95c808 Deregister core cart/checkout scripts and styles when rendering the blocks (https://github.com/woocommerce/woocommerce-blocks/pull/2842)
* Deregister core cart/checkout scripts and styles when rendering the blocks

* Fix regression: redirect to full cart when adding a product from empty cart

* Make it so it scrolls to the top

* Update assets/js/base/utils/legacy-events.js

Co-authored-by: Darren Ethier <darren@roughsmootheng.in>

* Add check for jQuery availability

* Listen to removed from cart event too

* Remove unnecessary useEffect dependency

* Remove jQuery event subscriptions on component unmount

* Fix tests

Co-authored-by: Darren Ethier <darren@roughsmootheng.in>
2020-07-14 15:46:44 -04:00
Albert Juhé Lluveras d894fed1df Cart block: show products on backorder (https://github.com/woocommerce/woocommerce-blocks/pull/2833)
* Show backorder notice in the Cart block

* Don't render variation <div> if empty

* Create ProductBackorderNotification component

* Add product backorder notification to the checkout block

* Fix classname and comment

* Rename notification->badge and don't show low stock badge if backorder is shown

* Use ternary to dispaly backorder/low stock badge
2020-07-14 17:25:53 +02:00
Mike Jolley 8cd96950e8 Reviews by product/category e2e tests (https://github.com/woocommerce/woocommerce-blocks/pull/2808)
* Tests for reviews by product

* reviews by category
2020-07-06 14:48:39 -04:00
Rua Haszard 29e7aa9bdf basic e2e test for instantiating All Reviews block (https://github.com/woocommerce/woocommerce-blocks/pull/2799)
* add e2e test for instantiating All Reviews block:
- adapted code from @senadir in-progress PR
https://github.com/woocommerce/woocommerce-gutenberg-products-block/pull/2756

* remove pptr-testing-library - not needed for this test

* Don't skip tests for the review block on < 5.3

Co-authored-by: Mike Jolley <mike.jolley@me.com>
2020-07-02 11:32:42 +01:00
Seghir Nadir 73adef6c85 Add custom matcher (https://github.com/woocommerce/woocommerce-blocks/pull/2780) 2020-06-25 14:00:27 +01:00
Darren Ethier 19ab667672 implement `page.waitForNavigation` for handling the page load after clicking the search submit (https://github.com/woocommerce/woocommerce-blocks/pull/2769) 2020-06-23 10:38:48 -04:00
Darren Ethier 1953d4f96a remove unnecessary await (https://github.com/woocommerce/woocommerce-blocks/pull/2764) 2020-06-23 09:22:18 -04:00
Mike Jolley 98d240d5e6 Introduce Variation Picker Component (https://github.com/woocommerce/woocommerce-blocks/pull/2497)
* Add attributes to API

* Add component

* API updates to return variation data

* Update to handle updated api responses

* Working picker

* Update tests

* update test

* Use SelectControl

* Add Picker to Form Block

* Code cleanup and splitting

* Inline todos

* Update todos

* Update assets/js/atomic/blocks/product/add-to-cart/product-types/variable/variation-attributes/index.js

Co-authored-by: Albert Juhé Lluveras <contact@albertjuhe.com>

* change classname and move styles within component

* Correct conditional

* Avoid nesting filters

* Remove exclude from getVariationsMatchingSelectedAttributes

* basic select styles

* remove custom select styles

Co-authored-by: Albert Juhé Lluveras <contact@albertjuhe.com>
2020-06-19 15:51:09 +01:00
Darren Ethier 1026ff8fd4 Switch to use `wp-env` as the development/test environment (https://github.com/woocommerce/woocommerce-blocks/pull/2730)
* Switch to use wp-env

* fix travis config

* fix spacing?

* doh need to install packages before starting environment!

* more fixes for errors in travis environment

* hmm still have node-git issues

* nope must use dash

* maybe it’s a caching issue (we’re caching node_modules?)

* remove configs

* add wp-env override json to gitignore

* remove obsolete scripts

* fix config in travis

* restore default env (for phpunit)

* for e2e manually set WORDPRESS_BASE_URL

* doh fix variable for wp version

* run phpunit via docker and fix WordPress version used for tests

* find out what’s going on with this thing

* don’t escape?

* doh phpunit needs dev installed from composer!

* fix versions

* looks liek we have to make sure wp db is up to date?!?

- also moves pre-configuration stuff all into one file for easier maintenance.

* see if I can get insight into what the siteurl is in the wp environment on travis

* try env setup (known that will break phpunit but possible it might fix e2e?)

* output plugin list to see what is active in travis

* try flushing rules

* do a hard fulsh

* fix argument syntax

* move things around and add pre-configuration as files so all wp commands run at once

* revert back to running each container command separately

Not sure, but this might affect permissions issues?

* maybe re-ordering before the file sync will help?

also try some configuration changes

* another attempt at travis config

In this attempt:
- map .htaccess to the server on the environment start
- try changing permissions of wp-content and wp-content/plugins as a part of the e2e test bootup

* use default wp version for gute build

* refactor to run all wp commands in one go

* don’t return promise from setup function

- this might fix the sporadic fails related to the fixtures being setup (and potential race conditions there).

* make sure we activate gutenberg plugin (previously we were just installing)

The syntax of the command was incorrect.

* try alternative syntax for installing and activating plugin
2020-06-17 16:28:11 -04:00
Seghir Nadir de10d09afd Expand travis matrix (https://github.com/woocommerce/woocommerce-blocks/pull/2686)
* Expand travis matrix to cover diffrent WP versions

* skip tests on older wp versions

* duplicate tests

* add wp version to phpunit tests

* skip all products in 5.2

* fix tests

* tweak command to account for e2e-util version

* tag snapshots

* Revert "tag snapshots"

This reverts commit b55ba2e522c5a248590039a3bb224f81da2653c5.

* use hook instead of HOC

* add todo to code

* fix borked conflict

* remove dubplicate single product test

* revert assets/js/blocks/product-search/edit.js to master
2020-06-16 13:18:34 +01:00
Seghir Nadir dbd3c7ef16 Generate block pages for tests. (https://github.com/woocommerce/woocommerce-blocks/pull/2707)
* add util folder and add util to generate pages

* add loader to insert and remove pages

* update tests to use the new page creator

* refactor tests to not create pages

* remove fullscreen check

* update single product test.

The test kept failing for me locally (it wasn’t deleting the block), when I manually tested following the same manual steps would not delete the block.

* add `quiet-pull` flag to docker command to hopefully reduce noice on builds

* adjust page loader to simplfy the loop

* remove extra comment

* add docs

* move promise inside map

Co-authored-by: Darren Ethier <darren@roughsmootheng.in>
2020-06-15 15:59:18 +01:00
Darren Ethier 41ca430ffe Add initial cart flow tests (https://github.com/woocommerce/woocommerce-blocks/pull/2678)
* more setup configuration for rtl

* move default state for cart out of reducer

This also creates a file for default store states, it should make it easier to execute tests in various environments.

* Make sure there’s a default object for cart line item row

* set defaults for cartData

* add fetchMock as a global in eslint config

* add initial cart flow tests

This is just to get the ball rolling, the cart block needs more tests

* fix missing @wordpress/jest-console configs (because I overwrote the original configuration)

* update test because of change in branch

* switch import order

* add globals.d.ts file to declare globals we use.

This is a quick solution to prevent typescript linting warning about `fetchMock`. At some point we could also create a proper interface for it or import the types (if they exist) for the `jest-mock` package.

The new `globals.d.ts` file is excluded from published builds.
2020-06-10 14:21:34 -04:00
Seghir Nadir baefb8d6e9 Add fixtures data for all entities. (https://github.com/woocommerce/woocommerce-blocks/pull/2548)
* change entrypoint setup and install wc-rest-api

* enable pretty links in docker

* create fixtures functions

* create and load global setup and teardown files

* support multiple shipping zones

* use env values

* refactor command

* fix typo in command

* more to import instead of require

* add docs

* refactor test data to its own file and refactor shipping methods

* revert to commonJS require

* rename function name

* rename global variable

* update fixture functions to accept fixture as param

* document fixture data

* pin wc rest api

* update package-lock

* remove forgetten test line
2020-06-05 17:49:07 +01:00
Seghir Nadir 177b30f940 Refactor E2E setup routine (https://github.com/woocommerce/woocommerce-blocks/pull/2544)
* skip test and delete unneeded ones

* update comment
2020-06-05 15:50:17 +01:00
Mike Jolley a5b09b7a43 Update atomic block structure (https://github.com/woocommerce/woocommerce-blocks/pull/2587)
* Move components to blocks dir

* Update import

* Create edit.js for each block

* Remove components/fix title

* Update imports

* Pass corect attributes on edit

* Import

* remove lightBlockWrapper
2020-05-29 14:49:56 +01:00
Mike Jolley 18480b0d68 Add layour editor to the single product block (https://github.com/woocommerce/woocommerce-blocks/pull/2586) 2020-05-29 12:28:04 +01:00
Mike Jolley 2dc0e8112a Create shared contexts handle for inner blocks (https://github.com/woocommerce/woocommerce-blocks/pull/2568)
* Create shared contexts

* At to jest config
2020-05-28 11:02:10 +01:00
Mike Jolley a06aa1eb39 Create single product block placeholder (https://github.com/woocommerce/woocommerce-blocks/pull/2569)
* Create single product block placeholder

* test

* Placeholder frontend js

* Update imports

* Update src/BlockTypes/SingleProduct.php

Co-authored-by: Albert Juhé Lluveras <contact@albertjuhe.com>

* Update src/BlockTypes/SingleProduct.php

Co-authored-by: Albert Juhé Lluveras <contact@albertjuhe.com>

Co-authored-by: Albert Juhé Lluveras <contact@albertjuhe.com>
2020-05-27 15:45:18 +01:00
Seghir Nadir 6862938653 Add React Testing Library (https://github.com/woocommerce/woocommerce-blocks/pull/2528)
* refactor sidebar to its own component

* install RTL

* wrap component in EditorPreview

* remove example test
2020-05-20 20:33:16 +01:00
Mike Jolley 74a4e55075 Remove API summaries in favour of client side code (https://github.com/woocommerce/woocommerce-blocks/pull/2387)
* Remove summary from API

* Add wordCountType to assets

* Update packages

* Remove summary from test data

* Featured product uses short desc

* Pass description instead of summary

* Use new Summary Component

* Component and tests

* Increased versititilty of methods

* Update assets/js/base/components/cart-checkout/product-summary/index.js

Co-authored-by: Darren Ethier <darren@roughsmootheng.in>

* Extra tests for html tags

Co-authored-by: Darren Ethier <darren@roughsmootheng.in>
2020-05-06 11:30:15 +01:00
Mike Jolley a640a230ca Assets/Block settings: Only lookup page if ID > 0 (https://github.com/woocommerce/woocommerce-blocks/pull/2369)
* Only lookup page if ID > 0

* Check for valid post

* Maybe fix test path
2020-05-01 11:02:20 +01:00
Mike Jolley 8424934149 Update API status codes (https://github.com/woocommerce/woocommerce-blocks/pull/2353)
* Update HTTP status codes

* Catch JSON parsing errors.
2020-04-29 15:47:05 +01:00
Mike Jolley 95809b30bb Update payment method config to include icons (https://github.com/woocommerce/woocommerce-blocks/pull/2267)
* Remove strong and cleanup existing configs

* Fix TS validation for blocks-registry

* Allow label to be string

* Split up button and icons for cart

* Make icons and payment methods available on cart page

* Fix payment method enqueuing

* Icon normalization and Stripe implementation

* PayPal Icon

* adjust spacing

* Fix string handling

* Remove paypal icon config

* Check for an object before creating icon

* Add payment icons to Stripe label

* Update common-icons.js

* Update Cart.php

* Update jest.config.json
2020-04-29 11:57:58 +01:00
Mike Jolley a58420a60e Table creation validation for install routine (https://github.com/woocommerce/woocommerce-blocks/pull/2287)
* Bump package version for testing

* New install routine and db version

* Revert "Bump package version for testing"

This reverts commit c3fee55a34e75429b731cd7a2cc07e841010df6d.

* Update bootstrap to ensure blocks is installed properly before tests are ran

* Restore errors after install

* Use enabled method instead of comparing db version

* Moved installer code to admin_init

* Tweak test bootstrap
2020-04-28 16:36:37 +01:00
Mike Jolley e85b6fe9a9 Inject block attributes rather than save them (https://github.com/woocommerce/woocommerce-blocks/pull/2273)
* Inject attributes rather than saving them

* Update snaps
2020-04-27 12:06:58 -04:00
Mike Jolley 7f85c1bcc0 Migrate REST API usage to the Store API (https://github.com/woocommerce/woocommerce-blocks/pull/2282)
* Remove unused wc/blocks/cart endpoint

* remove unused withProducts hoc

* Remove getProducts util

* Use store API products endpoint in product blocks

* Remove product endpoint tests

* Remove controller

* Switch attributes endpoint to store api

* Refactor withAttributes to use store API

* Migrate tags and cats to store API

* MIgrate variations to store api

* Migrate reviews to store API

* Drop dedicated variation endpoint

* Move tests

* Move cart init

* Fix reviews

* Comment out broken tests

* Remove old class based with-attributes test
2020-04-24 14:36:47 +01:00
Mike Jolley 953712941b Update StoreApi namespaces/move files (https://github.com/woocommerce/woocommerce-blocks/pull/2277)
* `use` is never relative - absolute is always used so backslash is not needed

* Move process_legacy_payment code to rest api class

* Move storeapi directory

* Updated namespaces and moved tests
2020-04-22 15:39:19 +01:00
Mike Jolley d0d0cfc565 Checkout: Rename address2 attribute (https://github.com/woocommerce/woocommerce-blocks/pull/2264)
* Rename address2 attribute

* Update snap
2020-04-21 11:51:11 +01:00
Albert Juhé Lluveras 93764f9f89 Check if cart needs payment before showing payment methods (https://github.com/woocommerce/woocommerce-blocks/pull/2177)
* Check if cart needs payment before showing payment methods

* Fix tests
2020-04-09 16:01:11 +02:00
Mike Jolley c02a7cb115 Update cart after conflicts (https://github.com/woocommerce/woocommerce-blocks/pull/2175)
* Return updated cart if there is a conflict (409 response) e.g. item no longer exists

* Receive updated carts

* Update tests and coupon handling

* Further rewording
2020-04-09 13:52:31 +01:00
Mike Jolley d637c28d62 Update add to cart to useStoreCart hook (https://github.com/woocommerce/woocommerce-blocks/pull/2103)
* Switch add to cart events to useStoreCart hook

* Add to cart endpoint

* Inject dependenct schemas

* Feedback, cart items are based on product schema

* Variable typo

* Move hook to base

* Update totals correcrly

* Update tests to use schema/routes class

* Update tests to correctly use schema

* Remove type hint to prevent strict standards error
2020-04-06 11:36:28 +01:00
Mike Jolley bf8715707d [Experiment] Add container to run php unit tests in docker (https://github.com/woocommerce/woocommerce-blocks/pull/2004)
* Add container to run php unit tests in docker

* Improvemnets to entrypoints

* Simplfiy dockerfile
2020-03-31 11:47:40 +01:00
Mike Jolley 2bca9840c6 Checkout processing and order creation APIs (https://github.com/woocommerce/woocommerce-blocks/pull/2044)
* CheckoutProcessing work

add missing memoization and implement useRef strategically

This prevents effects from firing unnecessarily.

Tweak assets registration

Order hydration and checkout/ endpoint updates

Fix error handling

Error handling

* Missing isset in stripe

* Fedeback

* rename draft order ID action

* Todos
2020-03-30 15:32:23 +01:00
Albert Juhé Lluveras b67e5a5f10 Fix 'Show Sorting Dropdown' attribute ignored in All Products block (https://github.com/woocommerce/woocommerce-blocks/pull/2019)
* Fix 'Show Sorting Dropdown' attribute ignored in All Products block

* Update snapshot
2020-03-25 12:19:24 +01:00
Seghir Nadir 2ba75fdc25 Refactor useBillingData to useCheckoutContext and hooking it up to form (https://github.com/woocommerce/woocommerce-blocks/pull/2002)
* Add line pricing for cart items in the API (https://github.com/woocommerce/woocommerce-blocks/pull/1979)

* Add line pricing for cart items

* Update checkout linePrice

* Fix tests

* Update schema - add dinero

* Implement dinero in cart totals

* Update preview and remove line totals

* Update package lock

* Update checkout review

* Fix preview and default data shapes

* return first and last name in shipping address

* remove shippingAsBilling option from editor settings

* remove billing data from store

* move to context

* hook billing to hook and sync with shipping

* add email to billingData

* hydrate billing data

* some refactors

* move hydrated billing data to reducer initial state and fix stale dependencies

* fix stale useCallback

* better checks in php types

* get isEditor from context

* update typedefs

* skip state update if nothing changed

* fix rebase

* update snapshots

* rebase package

* wrap setEmail in useCallback

* remove ValidationContextProvider

* fix docs

Co-authored-by: Mike Jolley <mike.jolley@me.com>
2020-03-23 21:13:41 +01:00
Mike Jolley 2ff854e212 Add nonces to Store API endpoints (https://github.com/woocommerce/woocommerce-blocks/pull/1992)
* Disable authentication for the Store API completely.

This may also resolve woocommerce/woocommerce-blocks#1991

* Add nonce handling to the abstract route

* Default state

* Add shared controls including nonce api fetch

* Use shared controls

* Hydrate inital nonce

* Update data stores

* Update nonce validation

* Fix tests by setting nonces

* Remove print_r debug

* Revert useStoreCart change

* Add nonce middleware

Co-Authored-By: Darren Ethier <darren@roughsmootheng.in>

* Switch back to apiFetchWithHeaders

* Docs

Co-authored-by: Darren Ethier <darren@roughsmootheng.in>
2020-03-19 11:50:51 +00:00
Mike Jolley cba3b9712f Add checkout skeleton whilst loading (https://github.com/woocommerce/woocommerce-blocks/pull/1995)
* Add checkout skeleton as loading state and remove placeholder text from save method

* Hide skeleton when not loading

* add loading class

* Update snap
2020-03-19 10:39:04 +00:00
Mike Jolley bd6c7f657c Configure link for the proceed to checkout button (https://github.com/woocommerce/woocommerce-blocks/pull/1981)
* Add link for proceed to checkout button

* Fixes to indenting/types

* Update snaps

* Update notice
2020-03-17 10:30:52 +00:00
Mike Jolley 01602f90bf Implement "return to cart" and "place order" buttons on checkout (https://github.com/woocommerce/woocommerce-blocks/pull/1926)
* Add back icon

* Add cart URL constant

* Add button components

* Implement button components into checkout

* Update checkout styles to match mockup incl updates to margins and padding

* Add options to control return to cart link

* Use checkout context

* Update snapshot

* Update context

* href

* Color/arrow styling

* Implement select instead of open URL field

* Add notice and updated settings control

* Show notice conditonally

* Store permalinks to avoid extra API requests, and get pages via API

* Update snapshots

* Fix double layout conflict

* Switch back to ID and add permalink via block setting

* snaps

* Fix snapshot; add default shape for pages

* Feedback

* Better undefined handling

* Update assets/js/blocks/cart-checkout/checkout/block.js

Co-Authored-By: Darren Ethier <darren@roughsmootheng.in>

Co-authored-by: Darren Ethier <darren@roughsmootheng.in>
2020-03-16 16:38:24 +00:00
Mike Jolley 8d76bcb33e Update Cart Order and Checkout Routes (https://github.com/woocommerce/woocommerce-blocks/pull/1958)
* Remove CartShippingRates endpoint

This was moved to the /cart endpoint

* Unused customer endpoint

* Split controllers into routes

* Update/fix tests

* Add draft order ID property to the Cart schema.

* Fix status check

* cart/order-create endpoint

* Placeholder for checkout endpoint

* Resolve merge conflict

* Update classes to match master

* Use correct schema
2020-03-16 12:44:00 +00:00
Mike Jolley 128ac6d63d Refactor cart shipping settings and shipping calculator (https://github.com/woocommerce/woocommerce-blocks/pull/1943)
* Move cart attributes to attributes file

* Stop feedback prompt jumping around; consolodate strings

* Update option labels and descriptions

* Match checkout save function

* hasShippingRate helper

* Refactor full cart/frontend views for shipping calc

* Add hasShippingAddress to useShippingRates hook

* Initial shipping calculator in totals row implementation

* Create cart context

* Update preview data to match API response

* Use context provider for cart

* Provide default cart item for placeholder with correct shape

* Remove outdated shape validation from cartlineitemrow

* Use preview data in editor context

* Tidy up components

* Tests/lint

* Update assets/js/base/components/totals/totals-shipping-item/has-shipping-rate.js

Co-Authored-By: Seghir Nadir <nadir.seghir@gmail.com>

* No need to camel case previewdata

* Use isValidElement

* Implement EditorContext

* Use select if no post is given

Co-authored-by: Seghir Nadir <nadir.seghir@gmail.com>
2020-03-13 13:41:59 +00:00
Mike Jolley c20f1bd7bf Break down Store API controllers into specific routes (https://github.com/woocommerce/woocommerce-blocks/pull/1957)
* Remove CartShippingRates endpoint

This was moved to the /cart endpoint

* Unused customer endpoint

* Split controllers into routes

* Update/fix tests

* Create RouteException and single handler per route

* Move exception to cart controller
2020-03-13 12:41:01 +00:00
Darren Ethier 74fe220f89 Add new hooks related to payment methods and checkout and remove obsolete. (https://github.com/woocommerce/woocommerce-blocks/pull/1929)
* add various hooks and improve hooks folder structure

- Also restructures hooks directory to make things a bit more organized
- Add useStoreOrder placeholder (followed up in future pull)
- Add useBillingData hook.

* implement usePaymentMethodInterface hook in payment method components

* remove obsolete hooks and implement new checkout context hooks

- add useCheckoutSubmit which exposes checkout submit button interface
- add useCheckoutRedirectUrl which exposes checkout redirect url interface

* add alias for `@woocommerce/base-utils` to jest config

* use consistent variable names for payment method id
2020-03-11 06:50:12 -04:00
Darren Ethier 0cacf5e0da Disallow selecting quantity of stock past what's available. (https://github.com/woocommerce/woocommerce-blocks/pull/1905)
- `useStoreCartItemQuantity` now receives the cartItem instead of the `cartItemKey` as an argument. I didn't notice in previous reviews how it's used in the context where we already have a cartItem so implementing this reduces complexity and makes the hook more precise for it's purpose.
- Add `backorders_allowed` to the CartItem schema for the API. This allows for client to have correct logic for maximum quantity when this value is true.
- Implement the above in the `CartLineItemRow` so that quantity picker is limited by the amount of stock remaining if that is available (`lowStockRemaining`) and the `backorders_allowed` is false.
- maximum quantity is currently hardcoded to a (filtered) value of `99` when other conditions don't apply (see related issue in woocommerce/woocommerce-blocks#1913)
2020-03-10 07:43:57 -04:00
Albert Juhé Lluveras f14fc54faf Refactor 'Hide shipping costs' Cart attribute logic (https://github.com/woocommerce/woocommerce-blocks/pull/1909)
* Use kebab-case for Cart block attributes

* Simplify Cart edit function

* Refactor showShippingCosts logic

* Update snapshots
2020-03-10 10:09:34 +01:00
Mike Jolley 1942491822 Checkout Block: Add Legal links (https://github.com/woocommerce/woocommerce-blocks/pull/1881)
* Create policy component

* Create page constants

* Add toggle options

* Update assets/js/base/components/checkout/policies/style.scss

Co-Authored-By: Albert Juhé Lluveras <aljullu@gmail.com>

* Update assets/css/editor.scss

Co-Authored-By: Albert Juhé Lluveras <aljullu@gmail.com>

* Feedback

* update snapshot

Co-authored-by: Albert Juhé Lluveras <aljullu@gmail.com>
2020-03-06 12:20:17 +00:00
Mike Jolley 000858d8f1 Update `reserved stock` class to handle concurrent requests (https://github.com/woocommerce/woocommerce-blocks/pull/1778)
* Add expires column to table

* Use core class if it exists.

* Add Exception class

* Update for currcurrency

* Update tests to handle exception

* Add back legacy stock handling

* Update comments
2020-03-06 11:44:20 +00:00
Seghir Nadir 2c8388f0a8 Update and select shipping rates dynamically (https://github.com/woocommerce/woocommerce-blocks/pull/1794)
* add select shipping endpoint to router

* add select shipping method

* add selected rates to cart

* better select rates

* move schema function to seperate function

* move validation to Cart Controller

* fix wrong session key

* Update shipping/cart endpoints (https://github.com/woocommerce/woocommerce-blocks/pull/1833)

* Items should not have keys in API response

* Include package ID in response (this is just a basic index)

* /cart/select-shipping-rate/package_id

* Add package_id to package array

* Update responses and add shipping-rates to main cart endpoint

* update-shipping endpoint

* Add querying selected shipping rate to the store (https://github.com/woocommerce/woocommerce-blocks/pull/1829)

* add selecting shipping to store

* directly call useSelectShippingRate

* refactor cart keys transformation to reducer

* remove selecting first result and accept selecting

* move update shipping to new endpoint

* pass selected rates down

* select shipping right directly and fix editor issues

* fix some broken prop types

* key -> package id

* Update and fix cart/shipping-rate tests

* fix case for when rates are set

* Update useShippingRates test

* add args to rest endpoint

* move selecting shipping rate logic to hook

* fix some naming issues

* update propTypes

* update action call

* fully watch cart state

* address review issues

* fix prop type issues

* fix issue with rates not loading in checkout

* remove extra package for shipping

* move ShippingCalculatorOptions to outside

Co-authored-by: Mike Jolley <mike.jolley@me.com>
Co-authored-by: Albert Juhé Lluveras <aljullu@gmail.com>
2020-03-05 20:54:05 +01:00
Rua Haszard 5a26d2708e ensure cart totals update when items are removed or quantity changed (https://github.com/woocommerce/woocommerce-blocks/pull/1840)
* ensure cart totals update when items are removed (prototype):
- return complete cart object from DELETE cart/items/:key
- use receiveCart on client to update whole cart including total

* move API endpoint for removing cart items to cart controller:
- returns full cart schema so should be part of cart controller
- is now a POST request with param - not strict REST
- fix up client action to use new API

* move API test for removing cart items (API has moved)

* use correct path for remove API in tests (doh!)

* add extra API test for remove_cart_item with bad key => 404 (experiment)

* experiment: delete test_remove_cart_item, does test_remove_bad_cart_item work?

* reinstate test_remove_cart_item with single valid request

* remove unnecessary newline

* tidy comments in PHP api tests, rerun travis?

* remove test_remove_cart_item which may be causing problems

* reinstate troublesome remove cart item api test (experiment):
- see if this works now travis issue is resolved

* whitespace

* show correct total when changing cart item quantity:
- move update cart item quantity API to cart controller
  - & return full cart response
- update js action to new API route & receive full cart response

* simplify test_remove_cart_item API test - now just tests a valid remove succeeds

* remove test_update_item (API has moved) +
+ experimentally remove test_remove_bad_cart_item
  - testing if cart remove tests interact with each other

* fix tests (🤞) - pass params in body, not as query params

* reinstate test for re-deleting same item

* update API docs - update/delete cart item have moved to /cart

* add response data checks to new cart API tests:
- extra protection against expected 404 "false positives"

* reinstate API test for changing cart item quantity

* fix remove cart item body tests - MIA items return error code, not cart

* fix test - quantity param is int not string

* attempt fix 404ing test_update_item:
- only allow POST, remove trailing `/`
- align array equals for good measure :)

* fix action for update-item - method=POST, now takes body params

* fix response body asserts in test_update_item

* reinstate update_item and delete_item on CartItems controller

* typos + examples in new cart items API docs

* reorder previous cart item docs to minimise diff/churn

* reinstate tabs in docs response example
2020-03-06 08:11:39 +13:00
Mike Jolley dd54ce1136 Checkout form options to control field visibility (https://github.com/woocommerce/woocommerce-blocks/pull/1868)
* Fix background overlap of feedback box

* TS notices

* Add company name toggle

* Implement new attributes and toggles in editor

* Handle field config in address component

* Remove other hoc rule from tsconfig

* map -> forEach

* Remove return from forEach

* Export and extend field config

* Fix optional text for all field types

* unit text

* Update snapshot
2020-03-05 13:06:47 +00:00
Seghir Nadir f872a3b605 Fix broken e2e test for Checkout block (https://github.com/woocommerce/woocommerce-blocks/pull/1869)
* fix broken e2e test - update snapshot for checkout block:
- new `use-shipping-as-billing` data attr

* add package.json script for updating e2e test snapshots
2020-03-05 10:00:39 +01:00
Rua Haszard 1b69ff666e Add basic tests for Cart & Checkout blocks - snapshot, can only add one instance (https://github.com/woocommerce/woocommerce-blocks/pull/1809)
* basic e2e tests for cart block:
- can add block, confirm editor markup matches snapshot
- can only insert one cart block

* add basic tests for checkout block:
- can add & matches snapshot
- can only add one block

* confirm single-cart test works, by allowing multiple cart blocks :)

* Revert "confirm single-cart test works, by allowing multiple cart blocks :)"

This reverts commit aae10046f37bc53bf11d8d2e1deb626d53654f71.
2020-03-04 14:32:31 +00:00
Mike Jolley 25a2367338 Cleanup draft orders (https://github.com/woocommerce/woocommerce-blocks/pull/1855)
* On init, create cron events

* Cleanup query + unit test

* Replace cron with AS
2020-03-04 11:08:23 +00:00
Darren Ethier 12a28556db Switch lint:js command to use wp-scripts and address errors. (https://github.com/woocommerce/woocommerce-blocks/pull/1837)
* switch js lint command to use wp-scripts.

* fix lint warning for improper jsdoc syntax

* fix linting errors
2020-02-28 16:54:07 -05:00
Albert Juhé Lluveras 185149f2bd Persist previous shipping rates while loading and show its package name (https://github.com/woocommerce/woocommerce-blocks/pull/1806)
* Persist previous shipping rates while loading

* Refactor ShippingRatesControl LoadingMask

* Show package name

* Simplify CSS to avoid using the adjacent selector

* Add comment to explain why 'selected' is hardcoded in the editor

* Rename package 'index' to 'key'
2020-02-27 19:28:36 +01:00
Mike Jolley 740a636c88 Updated `store/cart` endpoint coupon formatting and handling (https://github.com/woocommerce/woocommerce-blocks/pull/1808)
* Move coupon code for API requests to body - fixes issues with coupon codes containing special characters

* Use wc_format_coupon_code when applying/removing coupons via the cart endpoint

* Add tests
2020-02-26 11:46:58 +00:00
Mike Jolley 6d7fdf50e0 Allow coupons to be applied and removed from the cart (https://github.com/woocommerce/woocommerce-blocks/pull/1790)
* useStoreCartCoupons hook

* Apply coupon w/ basic error handling for the fetch

* Basic store specifically for cart data

* Working on error states

* Show error on coupon fail

* removeCoupon action

* Added extra endpoints for more efficient cart queries

* Apply/remove coupons working

* Track applying/removing state

* StoreCartCoupon typedef

* Use coupon code on index

* Remove custom controls definition

* Adjust storecartcoupons mapper and remove ref

* Move cartData defaults and remove ref

* Call API directly, avoid schema lookup

* Improved selectors

* StoreCart typedef

* Split up cart state data and add more typedefs

* Add API tests for apply/remove coupon

* Jest tests

* Move default cart data to constant

* Comment indentation
2020-02-25 11:36:53 +00:00
Albert Juhé Lluveras 9debaf8daf Cart & Checkout: conditionally register country and state settings (https://github.com/woocommerce/woocommerce-blocks/pull/1782)
* Conditionally register wcSettings in the Cart and Checkout blocks

* Add tests
2020-02-20 16:16:32 +01:00
Albert Juhé Lluveras a30615e2cb Hook up shipping methods to API (https://github.com/woocommerce/woocommerce-blocks/pull/1468)
* Create ShippingMethodsControl component

* Hook up shipping methods to API

* Add support for several packages

* Add tests to useShippingRates

* Fix shipping_rates property name

* Only show the products list if there are several packages

* Use <FormattedMonetaryAmount> to display shipping rate prices

* Make 'country' optional in CartShippingRates

* Make CartShippingRate API return currency info

* Minor improvements

* Fix shipping fields hidden in editor

* Fix missing currency in Checkout shipping rates selector

* Add links to issues in @todo comments

* Improve ShippingRatesControl useEffect

* Remove unnecessary tab

* Remove unnecessary id in RadioControl

* API: Add error when country is invalid

* Debounce shipping rates API requests

* 'Country key' -> 'Country code'

* Don't display radio input when there is only one option

* Add message when there are no results

* Minor enhacements

* Remove unnecessary Fragment

* Simplify RadioControlOption export

* Refactor 'renderOptions' and split it into several components

* Prevent Card sidebar from taking too much width

* Move country request check outside of the loop

* Fix failing test
2020-02-14 04:43:13 +01:00
Mike Jolley 5684d4ae8a Update testPathIgnorePatterns (https://github.com/woocommerce/woocommerce-blocks/pull/1731) 2020-02-13 12:53:15 -05:00
Mike Jolley 60d05aed19 Product search block e2e test (https://github.com/woocommerce/woocommerce-blocks/pull/1712)
* add docker files

* get tests to work

* remove irrelevant files

* add woocommerce as a dep

* remove eslintignore for tests

* undo travis chages till another PR

* remove local utils and call them directly from woocommerce

* remove travis db

* Block snapshot

* Test than the block can be inserted and interacted with

* Add snapshop

* Update snapshot

* rebase on master

* add a build script for just doing npm build on e2e tests

* just run build for e2e test job

Co-authored-by: Seghir Nadir <nadir.seghir@gmail.com>
Co-authored-by: Darren Ethier <darren@roughsmootheng.in>
2020-02-11 12:23:23 -05:00
Darren Ethier a7cd7d6b22 Fix wp-cli container permissions issues for e2e docker test environment (https://github.com/woocommerce/woocommerce-blocks/pull/1716)
* add docker files

* get tests to work

* remove irrelevant files

* change userAgent to chrome

* add woocommerce as a dep

* add jest to eslint

* remove eslintignore for tests

* undo travis chages till another PR

* remove local utils and call them directly from woocommerce

* update deps

* add setup files to run tests

* export default wp link

* wait for select before selecting

* remove travis db

* ignore e2e tests in unit testing

* add tests

* add docker commands

* always run composer

* Make it possible to import directly from '@woocommerce/e2e-tests/utils'

* remove installing woocommerce via composer.

* add more docker npm scripts

* add custom docker config for wp-cli

* add changes to docker-composer.yml

Includes reading environment variables from `.env`

* revert customizations to .travis.yml

* move main docker file for the wordpress container to bin

* fix travis config

* rename wp install for travis builds back to original name

* use a version of docker-compose that travis supports

* add minor change to try and force travis test run

* fix incorrect command

* copy composer lock from master

* only run phpcs on /src directory

* give time for host to spin up for e2e tests

* increase sleep for waiting on container

* make sure plugin is built before running tests

* sigh fix improper command usage

Co-authored-by: Seghir Nadir <nadir.seghir@gmail.com>
Co-authored-by: Albert Juhé Lluveras <aljullu@gmail.com>
2020-02-11 11:13:20 -05:00
Mike Jolley 29600c501f Summary/description consistency update (https://github.com/woocommerce/woocommerce-blocks/pull/1639)
* Audit atomic block labels

* Add summary, descrtiption, and short description to API and use for summary block

* Add summary to cart item api

* Respect short description

* Tweak label of summary block

* Revert product rating label

* One description vs 3

* Update sample content with more appropriate values, and match in cart items sample

* Move summary generation to class

* Tests

* Prevent extending `ProductSummary`

* Tweak $paragraph handling

* More accurate word counting

* add tear down for filter
2020-01-29 10:59:33 +00:00
Mike Jolley 9842986cd8 Add `low_stock_remaining` field to cart items API (https://github.com/woocommerce/woocommerce-blocks/pull/1583)
* add low_stock_remaining field

* Update tests
2020-01-17 11:46:17 +00:00
Mike Jolley 253a0160f1 Validate store API schema in unit tests (https://github.com/woocommerce/woocommerce-blocks/pull/1553)
* Add schema validation helper

* Add tests for cart item schema

* Fix schema errors found by tests

* Add tests and fix validation for remaining store API endpoints

* Tweak response for nested diffs

* Array syntax

* Improved nesting and type validation for schema

* Implement and fix type checking across test suite

* Type validation fixes

* Fix null comparison

* Fix array handling

* Switch to number type and support in validation

* Test the tests

* Update tests to use objects which match schema, avoiding JSON encode/decode
2020-01-17 11:34:15 +00:00
Mike Jolley 0150681c4b REST API - Cart Order API (https://github.com/woocommerce/woocommerce-blocks/pull/1425)
* Checkout/order WIP schema

* Add _address suffix for billing/shipping

* Rename schema, update endpoints, create tests

* Fix POST in test

* Fix test response checks

* Stock reservation and draft order status

* Add todo for shipping lines

* Readme

* Rename address fields in readme

* 10 min timeout of stock

* Fix broken test

* Update src/RestApi/StoreApi/Controllers/CartOrder.php

Co-Authored-By: Darren Ethier <darren@roughsmootheng.in>

* Add typehinting where possible

* Remove explicit pass by reference

* Further typehinting

* Clarify todo comment

* Validate product instances

* Specific phpcs exclusion rule

* Exclusion rule

* Move ReserveStock code to class

* Correct shipping-rates schema to shipping_rates

* Save shipping rates and lines if included with request

* Insert todo for shipping rate code

* Calculate shipping and selected shipping from order properties, not global cart properties

* Prevent error when shipping is not needed

* Update API readme

* Added tests for stock reserve class

* Fixes conflicts with draft statuses

Co-authored-by: Darren Ethier <darren@roughsmootheng.in>
2020-01-10 13:53:16 +00:00
Darren Ethier 8627b81c16 Add payment method api and components to checkout steps (https://github.com/woocommerce/woocommerce-blocks/pull/1349)
This adds a payment methods api to the checkout block that allows for extension to register payment methods with the block.
2020-01-06 17:28:09 -05:00
Mike Jolley 9b51a824d2 Store API: Add customer endpoints (https://github.com/woocommerce/woocommerce-blocks/pull/1417)
* Add schema/GET endpoint

* Customer data updates + create tests

* Update docs

* Unused method

* Use ID from the customer object, rather than checking logged in user

* PHP 5.6 incompatibility
2019-12-20 16:07:53 +00:00
Mike Jolley 15dbc627c1 Store API: Add cart coupon endpoints (https://github.com/woocommerce/woocommerce-blocks/pull/1378)
* Correct docblock

* Implement coupons endpoint with add/delete/get functionality

* Add totals

* Use money formatting

* Added tests for new endpoints

* Add coupons to main cart endpoint and update docs to match

* Fix indenting in readme

* is_a to instanceof

* Update coupon_exists logic

* Documentation/tidy class

* Update currency responses for coupon totals w/ tests
2019-12-19 12:41:34 +00:00
Mike Jolley 6a47b2232a More API price formatting and currency handling (https://github.com/woocommerce/woocommerce-blocks/pull/1394)
* Consistent currency data and formatting for product prices

* Consistent get_store_currency_properties usage

* Update tests with schema changes

* min_price and max_price to subunit format

* Product query of min and max prices using subunit

* Cart item totals

* Collection data schema object and currency data inclusion

* Handle subunits and new API in product prices

* Update price slider to format numbers using library and new API responses for subunits

* Product query of min and max prices using subunit

* Fix indents in readme

* Add todo for currency formatting

* Handle step for subunits, fixes min/max constraints

* Handle subunit conversion on display, using consistent currency object and wrapped NumberFormat component.

* Prettier ran

* Update usePriceConstraints tests so rounding doesn't make all values be 0

* Rename to minorUnitValue

* Move currencyToNumberFormat to index file

* siteCurrencySettings to constant rather than function

* remove cents term

* cents->minor unit

* typo in todo note

* Switch to FormattedMonetaryAmount

* Formatting

* wrong case
2019-12-18 11:29:20 +00:00
Albert Juhé Lluveras af5af78266 Price filter: preserve previous constraints while loading (https://github.com/woocommerce/woocommerce-blocks/pull/1386)
* Typo

* Save previous constraint while loading

* Add tests for formatPrice

* Small code refactor

* Refactor usePriceConstraints to DRY and add tests

* Add base-hooks to jest config
2019-12-16 17:48:02 +01:00
Mike Jolley 901e996cc5 Add money formatting to API responses (https://github.com/woocommerce/woocommerce-blocks/pull/1367)
* Implement basic version of MoneyValue with decimal conversion

* Implement MoneyValue in cart classes

* Add minor unit to schema

* Update tests

* Add tests

* Tweak minor unit description

* Replace pow

* Dump rounding mode and use constant values

* Only return strings

* prepare_money_response method

* Update types back to string

* Remove unnecessary parentheses

* Feedback; force integer rounding mode to prevent notices
2019-12-13 15:37:11 +00:00
Rua Haszard e5bc742853 add pricing discount info to cart line items api (https://github.com/woocommerce/woocommerce-blocks/pull/1325)
* add more pricing detail to cart line items api:
- total line price, before any coupon/discount
- saving, aka discount amount (if any)
- boolean if saving > 0

* add new cart price info properties to schema

* tidy field naming – line subtotal=pre discounts, line total=discounted

* remove saving / discount fields from API – could be calculated on client

* return numbers (not string) for price fields

* rename API field "price" to product price for clarity

* fix schema type for total fields (now float)

* Total descriptions in schema

* Format all costs as strings to follow core rest api

* Add totals to cart schema

* Update tests

* tax_lines
2019-12-12 10:31:25 +00:00
Mike Jolley a753cbb25c Store API: Add shipping rate api (https://github.com/woocommerce/woocommerce-blocks/pull/1344)
* Add basic controllers

* Schema

* Collections

* Updated schema

* Remove package ID

* Destination handling

* Destination validation

* Rename method for extra clarity

* Tests

* RestContoller type

* typos

* Fix object/array definitions

* Fix shipping-rate definition

* Fix tests

* Add docs

* Tweak description
2019-12-10 13:54:18 +00:00
Mike Jolley 2f91921214 Fix package init for WooCommerce 3.9 (https://github.com/woocommerce/woocommerce-blocks/pull/1335)
* Update Domain/Package so plugin file is not required, only a path.

* remove WC_BLOCKS_PLUGIN_FILE constant and add more inline docs

* Update tests

* Remove WC_BLOCKS_PLUGIN_FILE constant
2019-12-09 16:44:28 +00:00
Darren Ethier be199a6d48 Restore back-compat loading of assets registry switch which ensures wcSettings is only loaded when necessary (https://github.com/woocommerce/woocommerce-blocks/pull/1292)
* restore back-compat switch

* update woocommerce/components dependency to latest version

* fix bug in AssetDataRegistry and add tests to guard against regressions
2019-12-02 14:53:36 -05:00
Mike Jolley c55a387657 Prevent multiple collection data requests using debounce (https://github.com/woocommerce/woocommerce-blocks/pull/1233)
* Add context for collection data query

* Introduce useCollectionData hook

* Implement hook in filter blocks

* Update API to handle nuances of counts instead of client side

* Clone requests so original is untouched

* Prevent dupe requests is working

* Cleanup

* Update assets/js/base/hooks/use-collection-data.js

Co-Authored-By: Albert Juhé Lluveras <aljullu@gmail.com>

* Update assets/js/base/hooks/use-collection-data.js

Co-Authored-By: Albert Juhé Lluveras <aljullu@gmail.com>

* Feedback

* Remove context
2019-11-23 17:04:30 +00:00
Seghir Nadir 1d67ec5ce9 Add on_sale to Store API for it to work. (https://github.com/woocommerce/woocommerce-blocks/pull/1185)
* add on sale to store api

* fix onsale to on_sale

* update preview to use on_sale

* update tests to use on_sale
2019-11-15 19:11:03 +01:00
Darren Ethier 5f7dfe0ac8 Fix Package::init breakage for including plugin in WC core (https://github.com/woocommerce/woocommerce-blocks/pull/1175)
* fix broken Package init process

* add missing @since tag

* update version bump file to account for file location for version change
2019-11-14 12:19:22 -05:00
Darren Ethier 534d8f6fdd Add context for query state context string. (https://github.com/woocommerce/woocommerce-blocks/pull/1172)
* ensure useProductLayoutContext actually returns the context!

* add query state context and export provider and hook.

* implement useQueryStateContext in existing querySTate hooks and refactor other implementations

* add back in documentation removed in rebase

* default layout context to empty string (no need to add additional classes by default

* fix jsdoc
2019-11-14 12:16:27 -05:00
Mike Jolley c412dde269 Store API - Add tests for product attributes endpoints (https://github.com/woocommerce/woocommerce-blocks/pull/1151)
* Add product attribute unit tests

* Add missing description param

* Allow returning empty terms

* Attribute terms tests

* Update tests/php/RestApi/StoreApi/Controllers/ProductAttributes.php

Co-Authored-By: Albert Juhé Lluveras <aljullu@gmail.com>

* Update tests/php/RestApi/StoreApi/Controllers/ProductAttributeTerms.php

Co-Authored-By: Albert Juhé Lluveras <aljullu@gmail.com>
2019-11-12 12:04:19 +00:00
Mike Jolley c038a7fed4 Filter all products block by attribute (https://github.com/woocommerce/woocommerce-blocks/pull/1127)
* Block setup

* Working filtering and intersection of arrays

* Implement block settings and no attribute placeholder

* Correctly toggle counts

* Implement filtering

* Fix price slider constraints

* Fix price slider constraints

* Edit mode

* Rename ProductAttributeControl to ProductAttributeTermControl

* Attribute ID saving

* fix incorrect test fixtures

* fix incorrect regex for parsing model (or resource names) from the route.

* Fix query classes for some endpoints

* Style improvements

* Update inline comments

* use previous tests

* Show attribute control in sidebar

* Remove displayStyle option

* Sort attributes by name

* Show more/less toggle

* Use renderFrontend

* Only sort when adding values

* Rename memo placeholder

* More specific CSS for pointer

* Update assets/js/base/hooks/use-query-state.js

Co-Authored-By: Albert Juhé Lluveras <aljullu@gmail.com>

* Remove always true taxonomy check

* Update assets/js/blocks/attribute-filter/block.js

Co-Authored-By: Albert Juhé Lluveras <aljullu@gmail.com>

* Remove lodash join

* native js for string casting

* Move internal deps

* hyphenate attributes

* Correct data set names

* Remove unwanted dependency

* Moving imports

* Missing deps

* replace yoda conditonal

* Missing deps

* Missing deps

* Check value exists

* Remove undefined filter

* renderedOptions usememo

* Set defaults in checkbox list

* Show more/less refactor

* Use getAdminLink

* Fix object length check

* Correct AND query handling for counts

* useQueryStateByContext

* Add store rest endpoints

* Update assets/js/base/components/checkbox-list/index.js

Co-Authored-By: Albert Juhé Lluveras <aljullu@gmail.com>

* Update assets/js/base/components/checkbox-list/index.js

Co-Authored-By: Albert Juhé Lluveras <aljullu@gmail.com>

* Update assets/js/base/components/checkbox-list/index.js

Co-Authored-By: Albert Juhé Lluveras <aljullu@gmail.com>

* Update assets/js/blocks/attribute-filter/block.js

Co-Authored-By: Albert Juhé Lluveras <aljullu@gmail.com>

* Feedback

* feedback

* API readme

* Fix API relation queries for multiple attributes

* Prevent all options flashing visible during loads

* null check

* Improve loading state

* Remove null options change - it's no longer needed
2019-11-11 10:32:56 +00:00
Mike Jolley 524de4555e Move "prices" data from rest API to store API (https://github.com/woocommerce/woocommerce-blocks/pull/1128) 2019-11-05 16:47:32 +00:00
Darren Ethier dafd1c22c0 add additional data to new products store endpoint (https://github.com/woocommerce/woocommerce-blocks/pull/1116) 2019-11-01 13:50:01 +00:00
Mike Jolley f851a6ef9b All Products with Inner Blocks (https://github.com/woocommerce/woocommerce-blocks/pull/1032)
* Inital block creation

* Update labels

* Columns, rows, sample data json

* Output data from API

* thumbnail_html

* Split into smaller components of grid

* Price handling

* Image handling

* Remove !

* frontend

* Work on cart api

* Cart error handling and product type conditions

* innerblock progress

* Implement layoutConfig as set from innerblocks shape.

Note:

- this is just a poc
- where things are configured likely needs changed
- will still need to work out how this gets persisted for the frontend and how things get displayed there (but likely will work fairly similar in terms of mapping to components).

* use correct prop name

* Working edit button

* Clean up block controls and edit view

* Add link with innerblocks

* update link description

* correctly handle components with inner blocks as children

* Re-organise atomic components and blocks into own directories

* Unique keys for components

* Fix default layout when inserting block for first time

* Working layoutconfig save

* Save attributes

* Move sale badge to image component

* Add disabled to render preview and blocks

* icons

* Editor view styling

* Update withComponetId to stop component ID incrementing too many times

Co-Authored-By: Darren Ethier <darren@roughsmootheng.in>

* Improve key generation

* done/cancel buttons on edit

* Create withProducts HOC for All Products block (https://github.com/woocommerce/woocommerce-blocks/pull/994)

* Create withProducts HOC for All Products block

* Add order select and pagination to All Products block

* Go to first page when changing order

* Add HOC test

* Make sure block is updated whem columns/rows change in the editor

* Fix 'SALE' badge positioning

* Remove unnecessary key

* Honor 'perPage' value when generating placeholders

* Make placeholder sizes match rendered block item

* Several CSS improvements

* Remove unused CSS properties

* Move getProducts to hocs utils

* Remove All Products sample-data.json

* Fix order select wrong margin in the editor

* Refactor how loading image gets its size

* Clear products when loadProducts start

* Enhance pagination logic

* Fix placeholder width

* Fix regular_price check

* Set product link max-width

* Implement querystrings for the All Products block (https://github.com/woocommerce/woocommerce-blocks/pull/997)

* Implement querystrings for the All Products block

* Create withWindow HOC

* Add with-window tests

* Use renderFrontend util in All Products block (https://github.com/woocommerce/woocommerce-blocks/pull/1003)

* Add with-window tests

* Use renderFrontend util in All Products block

* Rename properties and components from 'order' to 'sort' (https://github.com/woocommerce/woocommerce-blocks/pull/1012)

* Rename properties and components from 'order' to 'sort'

* Rename onOrderChange to onSortChange

* Remove unnecessary stylint-disable-line (https://github.com/woocommerce/woocommerce-blocks/pull/1016)

* Create withBrowserLocation and withBrowserHistory HOC (https://github.com/woocommerce/woocommerce-blocks/pull/1022)

* Create withBrowserWindowProp HOC

* Remove unnecessary expect's

* Always pass window prop to propMap if it exists

* Scroll to top when switching pages in All Products block (https://github.com/woocommerce/woocommerce-blocks/pull/1011)

* Scroll to top when switching pages in All Pages block

* Improve keyboard navigation in the All Products block

* Create withScrollToTop HOC

* Fix variable name typo

* Update paths with aliases

* Avoid first and last page being included in pagination 'pagesToDisplay' (https://github.com/woocommerce/woocommerce-blocks/pull/1015)

* Update lock

* constants

* linting

* Clean up styling

* Prettier

* Block options for title/image

* Prettier

* Remove shared content controls

* Update atomic block descriptions

* Summary block

* Prettier

* Impoved template edit appearance and added inline tips

* Apply prettier

* Reset and cancel buttons

* Improved keys

* Tweak tip placement

* Remove incorrect comments

* Remove disabled ofr non interactive elements

* Fragment not needed

* Update assets/js/atomic/components/product-list/title/index.js

Co-Authored-By: Albert Juhé Lluveras <contact@albertjuhe.com>

* Move componentId hoc

* Comment

* Implement onImageLoaded

* Pagination: disable first/last page if they are active (https://github.com/woocommerce/woocommerce-blocks/pull/1041)

* Update assets/js/atomic/components/product-list/rating/index.js

Co-Authored-By: Albert Juhé Lluveras <contact@albertjuhe.com>

* Sale badges refactoring

Adds sale badges blocks and improves how the default blocks are defined.

* revert changes in withComponentId

* fix flexbox alignment

* Create withQueryStringValues HOC and use it in ProductGrid component (https://github.com/woocommerce/woocommerce-blocks/pull/1040)

* Create withQueryStringValues HOC and use it in ProductGrid component

* Add tests

* Add comment explaining urlParameterSuffix

* Don't destructure props if only used once

* Move dependencies check outside the HOC

* Update test description

* Remove HOCs no longer used

* Update assets/js/atomic/blocks/product-list/image/index.js

Co-Authored-By: Albert Juhé Lluveras <contact@albertjuhe.com>

* Update assets/js/atomic/components/product-list/sale-badge/index.js

Co-Authored-By: Albert Juhé Lluveras <contact@albertjuhe.com>

* Update assets/js/atomic/utils/index.js

Co-Authored-By: Albert Juhé Lluveras <contact@albertjuhe.com>

* Update assets/js/atomic/utils/index.js

Co-Authored-By: Albert Juhé Lluveras <contact@albertjuhe.com>

* Feedback

* Grid to List

* Improved badge handling

* update package-lock after merge from master

* Add wp.data store for schema and lists. (https://github.com/woocommerce/woocommerce-blocks/pull/1008)

* install @wordpress/data-controls and deepFreeze

* add schema store

* add query-state store

* add collections store

* add bundle entry point (and export store keys and constants)

* add master README.md for new stores

* add bundle configuration and register asset php side

* Add missing param name

Co-Authored-By: Albert Juhé Lluveras <aljullu@gmail.com>

* code style fixes

* remove unnecessary period from test description

* Simplify conditional

* reorder imports (code style)

* reorder imports and codestyle

* refactor using lodash for state utils

* reorder imports

* reorder imports

* reorder dependencies

* reorder dependnecies an remove duplication block

* remove errant tab

* reorder dependencies

* Modify collections store to add headers to the store state. (https://github.com/woocommerce/woocommerce-blocks/pull/1073)

* add control for getting unparsed response from apiFetch

* Modify action so it recieves a response object.

* modify reducer to handle response object

* improve selectors to make headers accessible

- modifys existing `getCollection` to retrieve items from state.
- adds `getCollectionHeader` selector

* update resolvers to handle full response from request

- also adds resolver for `getCollectionHeader`

* update docs for changes

* Improve spacing in doc

Co-Authored-By: Albert Juhé Lluveras <aljullu@gmail.com>

* Fix spacing in inline docs

Co-Authored-By: Albert Juhé Lluveras <aljullu@gmail.com>

* change `getFromState` to receive an object instead of arguments list.

* Prepare All Products block to accept extension inner blocks (https://github.com/woocommerce/woocommerce-blocks/pull/1047)

* Simplify BLOCK_MAP

* Prepare All Products block to accept extension inner blocks

* Change filter name

* Update filter name

* Add check that block exists in BLOCK_MAP

* Create REVERSED_BLOCK_MAP instead of searching blocks each time

* Change how child blocks are registered for All Products block

* Refactor All Products block so reverse map isn't needed

* Remove getDefaultBlocks

* Make sure getRegisteredInnerBlocks always returns an object and add checks to registerInnerBlock

* Add missing blockName arg

* Add inline docs to block registry

* Move 'blockName' prop to context

* Typos

* Improve registerInnerBlock error messages and create a validation function

* Refactor context

* Rename validateOption to assertOption

* refactor where new context lives and add alias for base-context

* fix doc block

* remove todo block (there’s an issue for it)

* rename context

* Update assets/js/atomic/components/product-list/sale-badge/index.js

Co-Authored-By: Albert Juhé Lluveras <aljullu@gmail.com>

* HeadingToolbar comment

* Tweak bool comparison

* Improve how default layouts are set so all blocks can be removed and the no-content message is correct

* Sale centering

* Fix default template

* Product example switch to preview

* Update preview schema and image data to match latest schema

* Add @woocommerce/atomic-components alias

* Alias for previews to prevent need for relative paths

* Drop `align` for sale block

Align disrupts other blocks in unexpected and unavoidable ways. Drop support so the sale block is a block level item.

* Rename atomic components and blocks (and create ProductLayoutContext) (https://github.com/woocommerce/woocommerce-blocks/pull/1089)

* rename atomic blocks and components to be more generic (drop list)

* create new context for productlayout and implement provider

* Rename ProductSalesBadge to ProductSaleBadge

* Add php5.3 restriction for All Products block (https://github.com/woocommerce/woocommerce-blocks/pull/1090)

* enable legacy builds and add handling for AllProducts to be wp5.3 only

* fix legacy builds

* Prevent filemtime notice

* Implement new data stores with All Products block (https://github.com/woocommerce/woocommerce-blocks/pull/1067)

* add new hooks and tests and alias for hooks

* various fixes for stores after implementation tests

* implement new stores for ProductList component

* add doc blocks for useStoreProducts hooks

* fix typo in property on returned object
2019-10-28 09:53:09 -04:00
Mike Jolley 9d79403db2 REST API - Store API - Product filtering data, products endpoint, and cart refinements (https://github.com/woocommerce/woocommerce-blocks/pull/1055)
* Cart add endpoint and schema

* Empty card DELETE method

* Merge into single controller

* Revise verb usage

* PUT/update requests

* Move under rest api namespace

* Basic test coverage

* Invalid tests with status check

* Variation handling

* Update src/RestApi/StoreApi/Schemas/CartItemSchema.php

Co-Authored-By: Albert Juhé Lluveras <contact@albertjuhe.com>

* Remove key arg for delete endpoint

* code comment for creation

* rename param to product_id

* Renaming methods from _item to _cart_item

* Prepare storeAPI products endpoint for public use

* Price filter headers

* Attribute counts

* Add Rating filter

* Rating counts

* Fix counts

* Moved utilities

* API docs

* Use correct response for cart item

* Attributes filtering

* Stats

* Products/Stats unit tests

* Rename stats to collection data

* Remove `embed` from schema

* Add since $VID:$ tags

* Improve operator logic and add isset checks

* Force cart schema to be readonly
2019-10-25 10:43:52 +01:00
Mike Jolley b0b5cc51a3 Introduce a Cart API on top of the REST API (https://github.com/woocommerce/woocommerce-blocks/pull/1046)
* Cart add endpoint and schema

* Empty card DELETE method

* Merge into single controller

* Revise verb usage

* PUT/update requests

* Move under rest api namespace

* Basic test coverage

* Invalid tests with status check

* Variation handling

* Update src/RestApi/StoreApi/Schemas/CartItemSchema.php

Co-Authored-By: Albert Juhé Lluveras <contact@albertjuhe.com>

* Remove key arg for delete endpoint

* code comment for creation

* rename param to product_id

* Renaming methods from _item to _cart_item
2019-10-21 12:11:52 +01:00
Darren Ethier f3bd3e6a09 Introduce legacy build system and new aliases (https://github.com/woocommerce/woocommerce-blocks/pull/1018)
* install directory-named-webpack-plugin

* create new plugin for fallback legacy imports

* implement webpack configuration for fallback legacy imports and legacy builds

Note: legacy builds are currently disabled, we can enable by just commenting out when we need them.

* removed unused webpack plugin experimented with in earlier iteration

* prettier fixes

* add legacy folder with readme for explanation

* add some info on legacy builds to `CONTRIBUTING.md`

* refactor imports to use new aliases

* fix link in doc

* update jest test config for new aliases

* use native string.startsWith instead of custom function

* reformat file for spacing/code style

* add slash to alias

* clean up webpack config and make things more dry

* update indent style for json files to be tab not spaces

- adjusts editorconfig rules
- reformat jest.config.json

* simplify conditional
2019-10-06 08:36:15 -04:00
Darren Ethier 57fdb8fe9c Implement PHP DI container and refactor. Also implements new Asset data interface for extendable settings passed to js. (https://github.com/woocommerce/woocommerce-blocks/pull/956)
* Add dependency injection container for blocks

* Add new Pacakge and Bootstrap classes.

- Bootstrap for bootstrapping the plugin.
- Package will replace `src/Package` and added as a dependency for any classes needing package info.

* Introduce AssetsDataRegistry for managing asset data

* refactor existing classes to use new DIC and Asset Data Registry

- this is the bare minimum needed to make this pull viable.
- further refactors will be done in more atomic smaller pulls for easier review.

* add new settings handling and export `@woocommerce/settings` as an alias to wc.wcSettings

- the export is exposed php side on the `wc-settings` handle.

* Remove unnecessary concatenation

* Fix typos and improve doc blocks

* fix php linting issue

* Use better escaping function.

* improve jsdoc spacing

* improve test assertion

* use fully qualified class names in bootstrap

* improve comment block to account for dynamic version string replace on build

* handle exceptions a bit differently

* correct dependency reference in webpack config

* remove blank lines

* fix doc block comment alignment

* Various doc/grammar/spacing fixes from code review.

Co-Authored-By: Albert Juhé Lluveras <contact@albertjuhe.com>

* improve naming, documentation and logic of filter callbacks

While this is intended for sanitization/validation, the callback ultimately provides flexibility for filtering the value before returning or setting in state so `filter` is a better name for this.
2019-09-23 14:07:13 -04:00
Albert Juhé Lluveras 6ab7834f59 Install prettier and reformat files (https://github.com/woocommerce/woocommerce-blocks/pull/945)
* Install prettier

* Reformat all files

* Add prettier to precommit hook

* Update prettier settings to match Gutenberg code standards

* Reformat files with new settings

* Improve legibility in some line breaks
2019-09-05 17:09:31 +02:00
Mike Jolley ea0ce0e915 Fix wcSettings conflicts with wc-admin (https://github.com/woocommerce/woocommerce-blocks/pull/916)
* Add inline settings script later than init

* Rename to shared-settings for clarity - other extensions filter these

* Implement block settings

* tweak used hooks

* update comment

* Shared settings should be dependency

* Make Webpack output shared and block settings (https://github.com/woocommerce/woocommerce-blocks/pull/918)
2019-08-27 16:25:32 +01:00
Darren Ethier 72f0ed470f Refactor: Introduce `wc-block-settings` bundle serving as `@woocommerce/settings` external. (https://github.com/woocommerce/woocommerce-blocks/pull/903)
* export new @woocommerce/settings external on `wc.blockSettings` global

- This handles reading data from the dom and assigning it to the global used in all packages dependent on `@woocommerce/settings` which is registered as an external pointing to the global.
- ensures that server data is only loaded on a route if needed.

* switch all direct imports of constants to use new `@woocommerce/settings` external

* enqueu new `wc-block-settings` script and attach inline data to it.

* fix test configuration and adjust test to use new external

* fix bad merge resolution after rebase

* switch constants import to `@woocommerce/settings` external after rebase

* reorder imports for convention

* improve method name
2019-08-22 16:56:47 -04:00
Darren Ethier 0b9559e2db Install @babel/plugin-proposal-class-properties. (https://github.com/woocommerce/woocommerce-blocks/pull/856)
* add @babel/plugin-proposal-class-properties plugin

* refactor ProductByCategoryBlock to use class properties
2019-08-21 09:05:17 -04:00
Albert Juhé Lluveras a6a131f8fd Move wc_product_block_data variables to constants file (https://github.com/woocommerce/woocommerce-blocks/pull/870) 2019-08-17 11:14:11 +02:00
Darren Ethier e5bf616dca Add bundlesize package and tweak travis config (https://github.com/woocommerce/woocommerce-blocks/pull/822)
- adds bundlesize package and travis config to run it on pulls (reports size as a check on pulls)
- reconfigure travis configuration so that jobs are split by task for easier review/reporting
- Fix failing phpunit tests exposed as a result of the travis reconfiguration
- Fix legit fail exposed by failing phpunit test in products REST endpoint (permissions related)
- Don't abort plugin initialization when detecting no build asset file but still throw notice (necessary to ensure php tests run in travis because we don't build js/css assets unnecessarily for those tests)
2019-08-09 14:08:31 -04:00
Albert Juhé Lluveras 3b39d6cc61 Fix Jest missing webpack config (https://github.com/woocommerce/woocommerce-blocks/pull/781) 2019-07-31 10:25:16 +02:00
Mike Jolley 3678beab97 Move main controllers from assets/php to src (https://github.com/woocommerce/woocommerce-blocks/pull/655)
* Create Package class and use in main plugin file

* Move and refactor library class - split asset methods into new Assets class.

* Add jetpack autoloader dependency

* fix tests

* Update from master

* Update testing framework

* Update package name

* Classname changes from master

* Indent
2019-07-01 13:52:44 +01:00
Mike Jolley 51ece61df6 Update namespaces to include Automattic prefix (https://github.com/woocommerce/woocommerce-blocks/pull/653)
* Update namespaces with Automattic prefix.

* Use static methods for stateless class
2019-06-27 11:28:52 +01:00
Mike Jolley 8bc02c3b0c Include blocks api in feature plugin (https://github.com/woocommerce/woocommerce-blocks/pull/628)
* Progress moving endpoints

* Handle rest api registration

* Add tag_operator to blocks API

From https://github.com/woocommerce/woocommerce-gutenberg-products-block/pull/555

* Unit tests

* update travis

* Composer before install

* Travis config

* switch dir running composer

* nodev mode
2019-06-27 11:03:21 +01:00
Kelly Dwan d2f1aa6c44 Update grid blocks preview to match width of products on the frontend (https://github.com/woocommerce/woocommerce-blocks/pull/489)
* Update grid blocks preview to match width of products on the front end

* Remove max-width from CSS, set it on the preview itself so we can use the dynamic theme width

* Override block thumbnail width for multiple column layouts

Previously larger thumbnails would cause multiple column layouts to break and wrap early. This enforces the column width for those cases

* Add the thumbnail size to images, to prevent larger images in multiple col layouts

* Update snapshot to new preview markup
2019-03-15 12:48:46 -04:00
Kelly Dwan 1712f8dbcf Remove blocks API endpoints (https://github.com/woocommerce/woocommerce-blocks/pull/477)
* Remove blocks API endpoints

* Remove API tests
2019-03-06 16:06:02 -05:00
Timmy Crawford db79f75376 Update/wc blocks/v1/products (https://github.com/woocommerce/woocommerce-blocks/pull/459)
* Update products endpoint to match core.

* Update usage of cat_operator and attr_operator

* Fix phpcs issue

* Update parameter in tests
2019-02-28 10:07:38 -08:00
Timmy Crawford 57155e685f REST API: Change namespeace to reflect what will exist in Woo core. (https://github.com/woocommerce/woocommerce-blocks/pull/451) 2019-02-25 12:23:29 -08:00
Kevin Killingsworth ecb0f7741b Add catalog_visibility param to products api (https://github.com/woocommerce/woocommerce-blocks/pull/406)
* Add catalog_visibility param to products api

This adds a catalog_visibility=visible option to the product api which
will filter out any products that are excluded from the catalog.

* Add product_visibility phpunit test

* Add catalog_visibility for catalog, search, hidden

* Fix util js test

The util js test checks for query parameters, so this adds the
category_visibility = 'visible' param.

* Updated for comments

1. Added collection params
2. moved catalog_visibility default with others
2019-02-19 10:09:16 -06:00
renovate[bot] dfb4acf882 chore(deps): update wordpress monorepo (major) (https://github.com/woocommerce/woocommerce-blocks/pull/343)
* chore(deps): update wordpress monorepo

* Fix tests: `transformIgnorePatterns` requires the babel config to be a JS export, rather than a JSON file
2019-02-13 15:18:43 -05:00
Kelly Dwan daa106ebbe Remove Gutenberg requirement from phpunit tests (https://github.com/woocommerce/woocommerce-blocks/pull/414)
* Remove Gutenberg requirement from phpunit tests

* Remove gutenberg from the install script
2019-02-08 14:23:31 -05:00
Kelly Dwan 8da93d36f1 API: Remove custom `attributes` handling from API (https://github.com/woocommerce/woocommerce-blocks/pull/401) 2019-02-06 17:59:34 -05:00
Kevin Killingsworth dc2b4485f4 Add placeholder image for product preview (https://github.com/woocommerce/woocommerce-blocks/pull/382)
* Add placeholder image for product preview

This adds the designated placeholder image url from settings into the
wcSettings global for the blocks to use. Then uses the placeholder url
when a product doesn't have any images.

* Updated based on review notes

Using `$block_settings` instead of `$settings`
Using '' alt tag
Updated snapshot

* Add the placeholder global to test that it passes through to the preview
2019-02-01 10:45:53 -05:00
Kelly Dwan 284d98643d REST API: Add new parameter for relationship between multiple taxonomies (https://github.com/woocommerce/woocommerce-blocks/pull/377)
* Add new API parameter `tax_relation`, to handle relationship between multiple taxonomies

* Minor change to trigger a travis build
2019-01-30 16:08:21 -05:00
Kelly Dwan 1977e1586b REST API: Update products endpoint to get products across different attributes (https://github.com/woocommerce/woocommerce-blocks/pull/299)
* Add products by attributes tests

* Add new properties to Products endpoint args

Allows for requesting a combination of attribute terms across different attributes.

* Unskip working tests
2019-01-09 10:21:23 -05:00
Kelly Dwan 134976e5d5 Fix "products by all categories" not finding products in parent-categories (https://github.com/woocommerce/woocommerce-blocks/pull/272)
* Fix issue with product categories when one category is a parent

* Add tests for product by categories intersections
2018-12-20 10:24:11 -05:00
renovate[bot] d3c8998430 Update dependency @woocommerce/components to v1.3.0 (https://github.com/woocommerce/woocommerce-blocks/pull/267)
* Update dependency @woocommerce/components to v1.3.0

* Set up new globals used by @woocommerce/components
2018-12-19 10:55:16 -05:00
Kelly Dwan c6d071cebf Fix PHP CodeSniffer issues (https://github.com/woocommerce/woocommerce-blocks/pull/215) 2018-12-11 11:14:02 -06:00
Kelly Dwan dc1c1f7370 Add tests for SearchListControl (https://github.com/woocommerce/woocommerce-blocks/pull/174) 2018-11-30 15:39:16 -05:00
Claudio Sanches 81605bae30 New custom endpoints (https://github.com/woocommerce/woocommerce-blocks/pull/162)
* Included PHPCS and git hooks

* Fixed coding standards

* New Products endpoint

* Fixed product controller schema

* Improved products controller schema and response

* New product categories controller

* Updated REST API base to match WooCommerce authentication

* Fixed products/categories endpoint

* Better docblock

* Product attributes controller

* Product attribute terms controller

* Update REST API urls

* Reverted PHPCS changes

* Check permission only once while fetching posts

* Included raw price

* Included sku to products endpoint response

* Fixed endpoints in unit test

* Fixed routes in unit tests

* Check and use subscriber, contributor and author rules in unit tests
2018-11-30 14:12:56 -05:00
Kelly Dwan 6a50ebde8b Adds continuous integration testing with travis (https://github.com/woocommerce/woocommerce-blocks/pull/156)
* Add travis to run JS & CSS linting, JS tests, and PHPUnit tests

* Move API initiation out of the gutenberg/files check

So that php tests run without having to build the JS files

* Add very basic product endpoint tests

* Fix stylelint issues in CSS

* Remove e2e setup, replace with dependency setup

* Add missing install step

* Remove cache for now

* Add specific `har-validator` dependency because v 5.1.2 has disappeared

* Only run npm install for the JS test job

* Check for installed plugins

* Update install location

* Fix typo in plugin name

* Check the BRANCH variable, rather than TRAVIS_PULL_REQUEST_BRANCH, which is only set on PR runs

* Remove debug command

* A change to trigger CI

* Set the expected node & npm versions

* Remove copy-pasted command, does not apply
2018-11-27 12:12:48 -05:00
Kelly Dwan 882cd4c7bb Set up Jest for JS testing (https://github.com/woocommerce/woocommerce-blocks/pull/130)
* Set up Jest testing

* Add a snapshot test for the product preview component
2018-11-16 10:43:51 -05:00