* Add StoreNoticesWithSnackbarProvider component
* Remove snackbar from regular StoreNoticesProvider
* Create useStoreNoticesWithSnackbar hook
* Remove anything snackbar related from StoreNoticesContext
* Remove snackbar styles from store-notices
* Make checkout use store notices with snackbar context
* Move snackbar notices container to new directory
* Make useStoreCartCoupons use the notices with snackbar context
* Update tests
* Rename path and remove addSnackbarNotice
* Use StoreSnackbarNoticesProvider in Cart and Checkout blocks
* Update snackbar tests
* Update paths
* Update tests
* Create store notice provider for snackbar notices only
* Update context functions to include the word snackbar
* Change nesting in checkout
* Remove unused file
* Rework coupon filters to not be applied individually
* Add a `text` property to the coupons in the cart
This is needed to allow extensions to change the text without affecting the code.
* Output coupon text instead of code
* Add coupons filter documentation
* Add deprecation warning when extension uses couponName filter
* Change couponName filter to coupons
* Add label to Cart item definition
* Change coupon.text to coupon.label
* Update coupon.label in coupon aria-label
* Update image and coupon.text in docs
* Add filter registration example
* Separate button spinner to separate component for reuse
* Use block checkout spinner in loading mask
* Block pointer events within loading mask
* Give the useRef within useShallowEqual a default value
This prevents the potential of having an undefined value returned.
* State setter and dispatch are stable
These do not need to be used as dependencies.
* Prevent re-renders of children when using loading mask.
This prevents children being rerendered and losing state. Loading styles are applied instead using a classname, but leaving the divs in place.
* Use memoization to to prevent excessive express payment rerenders
* Wrap express payment in loading mask
* Show loading state after submission
* remove eslint exclusion
* Move spinner to base components so it's available outside of the checkout package
* Avoid extra is-loading classname
* Update snaps/fix tests
* Remove memorization of payment method content due to stale data
* Express payment error handling
* Split up payment method context to make it more manageable
* Add blocking logic to cart
* Update snap
* Restore useRef
* Fix missing function removed by accident
* Fix setActivePaymentMethod and started status (so saved methods still allow express to be initialized)
* Loading Mask Todo
* Remove boolean shallow equals
* Missing dep
* Memoize typo
* Document changes in useStoreEvents
* Replace expressPaymentMethodActive
* setExpressPaymentError deprecation
* Only change status if an error is passed
* Track disabled state via useCheckoutSubmit
* useCallback on error message functions
* Fix mocks in test
* 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
* 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>
* Change index file from base/context to .ts
This is to stop TS complaining when importing things from here.
* Convert ValidatedTextInput to TypeScript
* Convert TextInput to TypeScript
* Ensure Label accepts correct HTML Attributes Props
* Remove PropTypes from TextInput and ValidatedTextInput
No longer needed because of TypeScript
* Use correct error id to show validation message
* Use HTMLElement instead of a specific element type for LabelProps
* Update assets/js/base/components/text-input/validated-text-input.tsx
Co-authored-by: Albert Juhé Lluveras <contact@albertjuhe.com>
* Update assets/js/base/components/text-input/validated-text-input.tsx
* Use correct formatting in ValidatedTextInput
Co-authored-by: Albert Juhé Lluveras <contact@albertjuhe.com>
* git move to ts files
* Type the checkout state provider
* Restore for loop for error handling
* Types not needed
* Consolodate response handling
* Unused import
* Fix defaults for onCheckoutAfterProcessingWithSuccess etc
* Type useEmitResponse and remove isObject checks
* useEmitResponse as const
* Check that redirectUrl is string
* Define actions as const
* data.redirectUrl should be truthy
* Add redirectURL todo item as followup
* remove null fallback
* Add type defs for customer
Taken from 194ecccf78/assets/js/type-defs/customer.ts
* Convert ShippingCalculatorAddress to TypeScript
* Convert ShippingCalculator to TypeScript
* Convert ShippingLocation to TypeScript
* Allow packageId to be a number or string in useSelectShippingRate(s)
* Convert ShippingRatesControl to TypeScript
* Convert ShippingOptionsStep to TypeScript
* Allow package_id to be a string or number
This is because of Subscriptions using strings for package IDs
* Change to use CartShippingRateItemShippingRate instead of Rate
* Add extra props to PackageProps type
* Make ShippingAddress have the correct type
* Use CartShippingRateItemShippingRate instead of Rate
* Remove Rate type
* Set return types to JSX.Element
* Change type of props.renderOption in ShippingRatesControl
* Remove customer type defs and relocate aliases to default-address-fields
* Add EnteredAddress type
* Import EnteredAddress from new location
* Remove unnecessary eslint ignore
* Remove unused variable
* Remove confusing use of word Item in Shipping types
* Remove confusing use of word Item in Shipping types
* modify emitEventWithAbort to change return value
`emitEventWithAbort` now returns an array of responses up to the first response that triggered an error or fail response instead of aborting on success responses too.
* update add to cart form context provider
* update checkout state context provider
* update payment method data context provider
* update tests and fix thrown error handling.
* Add emptyHiddenAddressFields function
* Add tests for emptyHiddenAddressFields
* Remove address fields that should be hidden before processing checkout
* Empty hidden address fields before displaying in shipping calculator
* Refactor emptyHiddenAddressFields so we only iterate once
* Fix test for emptyHiddenAddressFields
* Import default address fields from @woocommerce/settings
* Import emptyHiddenAddressFields
* Copy address first before emptying fields
* Modify address directly instead of copying it
* Copy address variable instead of mutating it directly
* Add files to TS project
* Return the new address rather than the parameter
* Don't clean address fields in the presentation layer
* Clean address in useStoreCart before it gets sent to components
* Convert CartLineItemsTitle to TypeScript
* Add type guards
* Change CartLineItemRow extension to .tsx
* Remove parseInt from price precision
This is because the API sends it as a number, so it will never be a string, so no need to parse it.
* Add dinero.js types
* Type QuantitySelector and add types for @wordpress/keycodes
* Make __experimentalApplyCheckoutFilter use generic types
* Add catalog_visibility type & change types of CartItem
* Add isNumber and isString to type guards
* Type ProductLowStockBadge
* Ensure type returned by a filter function is the same it received
* Include type guards and hooks in tsconfig
* Add more type safety to useStoreCartItemQuantity
* Make className optional on QuantitySelector
* Type CartLineItemRow
* Type CartLineItemsTable
* Type Cart
* Add extra keys to CartResponseItem
* Clean aria-hidden logic
* Export type-guards from module
* Use aliases to import types in CartLineItemRow
* Remove unused prop types and specify return type of function
* Specify return type of component
* Use JSX.Element instead of ReactNode
* Remove unused variables & set return type of components
* Remove PropTypes
* 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
* 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>
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.
* 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
* Fix circular dependencies in Icons package
* CircularDependencyPlugin
* Fix deriveSelectedShippingRates CD
* Move useStoreNotices to context/hooks
* Move useStoreCart to base/context/hooks
* Move useStoreEvents to base/context/hooks
* Move collection/product hooks
* Move useStoreAddToCart
* Move useCustomerData
* move shipping hooks
* Move checkout and payment hooks
* Context should import hooks with relative paths
* Prevent circular dependency in store notices container components
* Move address fields to settings so they are shared
* Import PaymentMethod components direct
* relative import
* Fix select CD
* Move ValidationInputError
* Move components consumed by context
* Fix up internal imports in context
* fix CD in checkout package
* Separate providers
* Fixing context exports
* Fix base context hook import
* fix mocks
* Pass hooks to Slot Fills as Fill Props to avoid imports from base-context
* Export components, not hooks
* Pass props to ExperimentalOrderMeta
* Run CD plugin when using `npm start` only
* Rename CIRCULAR_DEPS to CHECK_CIRCULAR_DEPS
* Remove duplicate key from rebase
* Move packages component back to main file
* Remove dashicon module replacement
* Restore SVG import from package not external
* Move core locale handling to avoid impact settings package size
* Remove deleted file from rebase
* Implement `started` action creator.
Also for TS typing I changed `paymentMethodData` to be optional for both the `success` and `started` action creators.
This is because the behaviour allows for paymentMethodData to be retained in the state if it is not explicitly provided on dispatch.
* Implement started action creator on the exposed payment status dispatcher.
The implementation now allows for receiving payment method data when the `start` status is dispatched.
* Don’t overwrite payment method data when `success` status is set.
It is intended that if paymentMethodData is undefined, that is simply passed through to the dispatched action. This signals the reducer to retain the existing paymentMethodData in state (when undefined).
The correct way to clear the paymentMethodData is to either explictly provide an empty object, or set the status to pristine.
* Fix types for incoming paymentMethodData
* Implement receiving paymentMethodData in reducer.
This changeset also configures the reducer to retain the existing paymentMethodData in state (and related correlated information0 when the provided paymentMethodData property is undefined.
The only time paymentMethodData should be reset in state is when it is explicitly provided or the status is set to PRISTINE.
* Fix types for started action dispatcher.
* Explicitly clear paymentMethodData state when express payment started.
Also restores previous paymentMethodData when express payment cancelled.
* Switch saved tokens to utilize the payment method status started dispatched action instead of success.
This change ensures that savedToken handlers registered by payment methods have access to the `onPaymentProcessing` checkout event.
* fix typedef
Really just need to ensure types are used anywhere, this is a temporary change due to the time sensitive needs for this PR.
* Update assets/js/base/context/cart-checkout/payment-methods/reducer.ts
Co-authored-by: Albert Juhé Lluveras <contact@albertjuhe.com>
Co-authored-by: Albert Juhé Lluveras <contact@albertjuhe.com>
* type hooks
* type useStoreCart
* type the rest
* Remove old typedefs
* Specify that the return value from useDispatch is a Promise< void >
* Change return type of removeItem
* If ref.current is undefined then return value without checking shallowEq
* Revert "Specify that the return value from useDispatch is a Promise< void >"
This reverts commit 97863bd584d38024398913a79ce63fa6b964846a.
* Remove type parameter from removeItem and changeCartItemQuantity
* Change action return type to cater for generator functions
* Remove type parameter from addItemToCart
* Add mapped types file to help with actions that are generator functions
* Include addItemToCart in return types of cart actions
* Use custom DispatchFromMap
* Add todos for why we've redefined functionality that exists in Calypso
* update types
* remove fromEntries and use polyfill
* address review
* ignore ts no shadow
* fix test errors
Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com>
* add typescript support
* Add type declarations for Cart and CartResponse interfaces
* make sure we’re resolving .ts files as well as .js files on imports
* add more types
* type the cart data store
* Apply suggestions from code review (implement .tsx in configs)
Co-authored-by: Jon Surrell <jon.surrell@automattic.com>
* remove global fetchMock declaration and directly import where used.
* rename type
* remove named action types and just infer by returning action creator values as const
* use interface instead of type
* rename
* renames
* create CartAction type as union of action creator returned types and implement in reducer
* remove unused imports
* refresh package-lock after rebase
* Add base TS config that projects will inherit from
* Add tsconfig for assets/js/data project
* Ignore TS error on cart store registration
We will address this in cooldown when we have time to investigate further
* Add tsc to build step to catch TypeScript errors
* add a separate command for tsc and tweak build command to use
* restore checkJs and allowJs values in config and remove ts check from build command
* Add ts:check-all command
* Add TypeScript checking workflows
* Change triggers for TypeScript workflow
* Use npm ci instead of npm install
* Remove ts:check-all from TypeScript workflow
* Remove TS Check GitHub workflow
* Remove type-defs dir from TS include, and remove ts:check-all script
We no longer need the ts:check-all script because ts:check will do this for us, the old ts:check did nothing and did not work.
* fix coupon loading issues
* include .ts files only from type-defs folder
Co-authored-by: Jon Surrell <jon.surrell@automattic.com>
Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com>
* 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
* Add left vertical bar to payments methods step.
* Remove horizontal borders around order notes.
* Add class to order notes component.
We need it to traget that element with CSS.
* Update padding on order notes checkbox to match desing.
* Remove full stop to match the design.
* Add label for not saved payment methods option.
* Remove use new payment radio.
* Always show new ayment methods selector
* Remove editor context for now.
* Add accordion component skeleton.
* Small component refactor.
* Use accordion for new payment options.
* Fix jsdoc.
* Add styling.
* Add input styling.
* Hide label if we don't have saved methods.
* Cleanup.
* Cleanup and styling.
* Add target class to aid with alignment.
* Update use new payments label styling.
* Update Place Order button location.
* add full stop to payment method copy
* ensure that there is always a (default) selected payment method:
- using `activePaymentMethod` from context
- this ensures there is a default selected on initial render
- and handles any dynamic changes to available payment methods
- e.g. COD disappearing when change shipping option
- remove unused / redundant selectedMethod prop - context is best
* use tab-based payment UI for 2 or fewer payment methods:
- move saved payment state to payment context; it's shared state needed
by both PaymentMethodOptions and SavedPaymentMethodOptions
- show previous tabs UI if:
- customer has no saved payment methods (cards)
- store has 2 or fewer payment methods available
- when initialising SavedPaymentMethodOptions, only select one if the
user hasn't selected a real payment method - this ensures radio
buttons switch correctly between saved card => `Use another`
- remove various props and local state that is no longer required (🤞🏻)
* experimental - styling tweaks for single payment tab (remove "tab" UI)
* Revert "experimental - styling tweaks for single payment tab (remove "tab" UI)"
This reverts commit e09dd4862b97d989d950a9d67672d83e7b8992e4.
* Add single payment method UI.
* Adjust single method styling.
* Add outline and margin to two methods version.
* Fix gap for order notes on/off option.
* Update Order button spacing CSS.
* Reuse computed values.
* Remove tabs and single payment option.
* We no longer need this test as the UI was changed.
* Fix payment methods labels height.
* Simplify.
* Remove not needed import.
* Typecheck an option.
* Refactor code.
* Rename.
* Rename.
* Update typdefs.
* Remove border for add order notes.
* Correct spacing for radio-button and label.
* Add simple test. Switch to payment method.
* Update style.
Co-authored-by: Rua Haszard <rua.haszard@automattic.com>
Co-authored-by: Darren Ethier <darren@roughsmootheng.in>
* Add supports data to payment methods abstractions. Implement in Stripe.
* Add capabilities to the payment gateway.
* Payment requirements in cart schema.
* Supported features format update.
* Formatting.
* Check required payment features.
* Refactor capabilieties check.
* No need for the cart parameter.
* Allow external modifiacation of features capability.
* Use ExtendRestApi to inject payment requirements into cart endpoint.
* Simplify the code.
* Enable more integrations.
* Enable Stripe payment request.
* Move the filter to a more correc location.
* Add features check.
* Update typedefs and documentation.
* Update tests with new functionality.
* Style fixes.
* 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>
* Remove savePaymentInfo check when displaying payment methods
This is because the savePaymentInfo is derived from whether the save payment method checkbox shows. This check doesn't make sense to do because it's not a good indicator of whether the payment method is enabled. Subscriptions for example hides the checkbox because it is implied that the method will be saved. We should instead rely on the server-side to only send permitted saved payment methods.
* Add safely_get_request_payment_method
This will allow us to try to get the payment method if it was passed in the request, but will default to an empty string if not. This is different to get_request_payment_method because it doesn't throw any errors. We need it to be different because get_request_payment_method is used when the order definitely needs payment (so a normal checkout scenario, vs. a £0 subscription checkout)
* Add action to update order meta when checking out
This is needed because some extensions rely on this action to add their information to the metadata of order items.
* Remove safely_get_request_payment_method
This is no longer needed.
* Remove @since from experimental hook
* Add PHPDoc for new update_order_meta hook
* Document use of experimental hook
* Reinstate the check for allowing saved cards
* Add method to Stripe integration to determine if saved_cards is enabled
* Add new field to get_payment_method_data
This adds displaySavePaymentMethodCheckbox which will be used to determine if the checkbox to save payment methods should display.
* Add displaySavePaymentMethodCheckbox option to client
This will determine whether the "Save payment information" checkbox will be displayed.
* Add requiresSaving option to Stripe payment method data
This is informed by the saved_cards option and the result of the wc_stripe_display_save_payment_method_checkbox filter.
* Rename displaySavePaymentMethodCheckbox to requiresSaving & fix logic
* Revert negation on display_save_payment method_checkbox filter & rename
We are going to rename the properties we use to determine whether saved cards are shown, or whether the save payment method checkbox is shown, so that their names are more descriptive of what they are for.
* Rename allowSavedCards and requiresSaving in Stripe integration
* Rename savePaymentInfo&requiresSaving to showSavedCards & showSaveOption
This is so we can hide the checkbox independently of hiding the saved payment methods.
* Show deprecated message if payment methods use savePaymentInfo
This is because we are leaving it in to enable backward compatibility but payment methods registering using this should be informed of the change in case it gets removed.
* Update Stripe typedefs and keys of supports object
* Show customer payment methods if showSavedCards is true on the method
* Make PaymentMethodTab accept showSaveOption prop
This will allow us to show the save checkbox only if the payment method says it should be shown.
* Update tests to use new keys in supports when reg'ing payment methods
* Add optional chaining when validating payment method config
This makes the code a little tidier :)
* Update assets/js/blocks-registry/payment-methods/payment-method-config.js
Co-authored-by: Seghir Nadir <nadir.seghir@gmail.com>
* Add more information to deprecated call in payment method config
* Fix lint error
* Fix prop types for PaymentMethodTab
* Add information about supports on payment methods to docs
Co-authored-by: Seghir Nadir <nadir.seghir@gmail.com>
* generating changeset for pull request
* generating changeset for pull request
* Update changelog.txt for 4.3.0 release.
* Update testing instructions for 4.3.0 releae.
* Update testing instruction for review.
* Revert "Improve error displayed to customers when an item's stock status changes during checkout. (https://github.com/woocommerce/woocommerce-blocks/pull/3656)"
This reverts commit a30179f165.
* Revert 3656 documentation changes.
* Update test zip link.
* Update release date for 4.2.0.
* Bumping version strings to new version.
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: budzanowski <bartosz.budzanowski@gmail.com>
* fix circular dependency in text-input
* fix circular dependency in chip component
* fix circular dependencies in AddressForm component
* fix circular dependencies in product-list
* fix circular dependencies in hooks
* fix circular dependencies in context
* Fix circular dependencies in components/cart-checkout
* fix use-checkout-submit test
- can’t mock the hook alias anymore
- account for undefined object returned from `usePaymentMethods`
* 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
* 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>
* add you don’t need lodash eslint plugin
* handle lodash.omit eslint errors
- storybook and webpack config implementations were just ignored.
- shared/validation/index.js was converted to use ES6 destructuring to eliminate usage.
* remove lodash assign usage
* convert lodash isNan to Number.isNan
* ignore lodash.flatten lint error for now
* remove usage of lodash.isNil
* add exclusions for lodash rules in main eslintrc file rather than per file.
* For gateways with disabled saved payment metods, don't show saved items in context.
* Fix style.
* Update name.
* Simplify and fix.
* Whitespace.
* Revert for another PR.
* Formatting fix.
* 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>
* generating changeset for pull request
* generating changeset for pull request
* Update readme changelog
* Update requirements
* Testing instructions
* Update zip file
* Update nonce outside of json parse
* Set logged in cookie on store api requests
* Update zip
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: Mike Jolley <mike.jolley@me.com>
* refactor and reorder checkout processing
* improve handling of checkout POST with mixed success:
- return coupon errors in a property
- don't throw from coupon validation:
- return info about errors to route handler
- tweak logic in route handler to prevent subsequent processing
- default payment result to fail to avoid accidental successful checkout
- in client, catch errors and new customer id:
- render any errors as notices - i.e. coupon error
- if a customer ID is included, push into store (so UI updates)
* fix linter whitespace issue from rebase merge
* fix MIA order validation/errors (due to rebase):
- reinstate thrown exception when validating order
- return exception was an experiment, now solved in woocommerce/woocommerce-blocks#3454
* hide "Create account" checkbox if account is created during an error response:
- update store with new user id
- remove stale response.errors handling;
- current approach (https://github.com/woocommerce/woocommerce-blocks/pull/3454) is to add data to error response
* show a notice informing user that they have signed up
* white space
* Handle header and update typedef
* Remove "errors" schema
* remove errors
Co-authored-by: Mike Jolley <mike.jolley@me.com>
* refactor and reorder checkout processing
* move experimental order_processed hook as last step before payment:
+ flesh out docs - intention/purpose, introduced version, link to PR,
relationship to legacy hook
* return current user_id with checkout error responses, so UI can update
* clarify user id comment
* Add store API nonce to all responses
* catch new nonce & update store for POST /checkout errors
* ensure $order hook param and database are in sync
* fetchResponse->errorResponse
* Move payment method ID validation to schema
* Add the nonce inline
* Simplify error method
* Add todo for injection
* Hook docs
* Return user ID as a header instead of in error response
* Default to private methods
* Tidied processing logic/order save placement
* White space removal
* Remove duplicate comment
* Remove root slash
* Remove unused created variable
* Remove woocommerce_registration_error_email_exists filter in error message from API
* Move payment validation
* Moved comments
Co-authored-by: Mike Jolley <mike.jolley@me.com>
* 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>
* Check price >= 30
* Force payment methods to react to order totals change
* Fix express payments reducer so it overwrites
* Fallback to 0 if undefined
* handle plain options passed to registerPaymentMethod:
- no need for a callback dance
- support the previous API: if a function is passed, call it as before
* update Stripe for new registerPaymentMethod interface
* update docs & all built-in payment methods to simpler API
* handle plain options arg to registerExpressPaymentMethod:
- add legacy fallback if passed a function
- update stripe express payment method
- update docs
- remove unused `assertValidPaymentMethodCreator` util
* use correct case for `JavaScript`
Co-authored-by: Darren Ethier <darren@roughsmootheng.in>
* typedefs for payment registration options + tidies for regular methods
* typedef express payment options arg & tidy stripe/payment-request:
- use camelCase for config instance (not a constructor/type)
* mention typedefs in payment method dev docs
* use @wordpress/deprecated to warn if callback passed to payment register
* update unit tests for new payment method API
Co-authored-by: Darren Ethier <darren@roughsmootheng.in>
* 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
* Strip tags from stripe error notices
* Revise abortPayment - this does not need to provide or handle responses
* Decode entities in responseData
* Correctly handle checkoutResponse props
* Show one error at a time from express methods
* Set ID to context to avoid need to manually define it
* Add missing context docs for shouldCreateAccount
* shouldCreateAccount context docs
* No need to handle showOrderNotes in component—just don't render it
* Only render notes if needed
* Create PhoneNumber component to insert when needed
* Add errors to UI in onCheckoutAfterProcessingWithError
* Fix missing useEffect dependency
* Typo
* Reset source id if Stripe intent fails
* Remove default error on onCheckoutAfterProcessingWithError
* Add missing useEffect dependency
* Only add default error message if there is no errors in any other context
* Fix useEffect running too many times
* Add type-defs and minor improvements
* Only count error notices
* 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>
* add experimental api for deregistering payment methods
Not going to promote this api just yet.
* fix for express payment method bug
Removes incorrect condition for the purpose of this effect. The Effect is expressly for setting a default active payment method if none is set. Since active payment methods might be either a registered express payment method or a registered payment method, the check for whether the payment method is included or not is breaking express payment method behaviour.
* add test for express active state and deactive state transition
* account for possibilitiy active payment method might not be currently registered.
* Show all payment methods when it's an admin and let the error boundary handle errors
* Use StoreNoticesContainer in Payment method error boundary so notices have styling
* Filter out saved payment methods for admin users if they don't accept payments
* Simplify update options logic
* For admins, only show payment methods that errored but canPay was not false
* Simplify how new payment method option is appended
* Wrap canMakePayment in a try catch block to handle payment methods that throw an error
* Add an id to payment method error boundary errors
* Add an error boundary to express payment methods
* Hardcode failing content and savePaymentInfo to false if the payment method failed
* Add some new comments
* Add a notice instead of registering the payment method if it fails and user is admin
* Throw error early if stripe failed to load
* Split express and standard payment method error notices
* Don't add payment methods in the editor and instead add a notice
* Fix error id
* Use noticeContext constant
* Add missing JSdoc param
* Remove unnecessary removeNotice
* bail out of setting a default payment method if shopper has saved card
* ensure default payment method is only set as active if necessary:
- use functional form of setState; previous state (current payment
method) is not potentially stale value
- so the default is only set if there really is no active payment method
* remove unnecessary remnant hook dependency 🧟♀️
* 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
* Hide saved payment methods if their gateway is disabled
* Fix wrong type-def
* Remove extra blank line
* Rename var
* Use FILTER_VALIDATE_BOOLEAN instead of comparing to 'yes'
* Use data from Payment Method context instead of reading setting from the server
* Use data from Payment Method context instead of reading setting from the server
* enqueue order of payment gateways as script data
* use configured gateway order for payment method tabs
* clarify name of payment gateway sort order setting
* fix formatting
Co-authored-by: Darren Ethier <darren@roughsmootheng.in>
* fix bug - express payment methods not working due to ordering logic:
- move ordering code to payment methods in usePaymentMethods hook;
- this only applies to standard (non express) payment methods
- also any code that uses payment methods will get them in correct order
* why did this formatting not happen pre-commit?
* move method ordering into refreshPaymentMethods to avoid infinite loop:
- pass keys of express payment methods so they work correctly (show up)
- refreshPaymentMethods dispatches availablePaymentMethods to redux
store; I suspect this was causing infinite loop as the callback
depends on registeredPaymentMethods
- handle case when a payment method is not in PAYMENT_GATEWAY_SORT_ORDER
- this happens with COD when dependent on shipping
* fix formatting
* use shallow equal to prevent refreshCanMakePayments infinite loop
* use native Set instead of lodash.union for unique gateway names
* code formatting
* check to ensure we register paymentGatewaySortOrder asset once only
* fix COD tab showing out of order if not available at page load:
- return ALL gateways in sort order array
- note this includes gateways that are not enabled by merchant
* reinstate return bool from usePaymentMethods hook (broken in refactor)
* add basic typedefs for payment methods hooks
Co-authored-by: Darren Ethier <darren@roughsmootheng.in>
* Add Checkout Order notes (UI)
* Add Checkout Order notes (context)
* Add missing useEffect dependencies
* Remove duplicate toggle in editor
* Minor fixes
* Check whether orderNotes have changed before creating a new state object
* Rename showCounter to showStepNumber
* Rename 'onChange' with 'onTextChange'
* Add comment and tests to FormStep component
* Rename 'with-counter' to 'with-step-number'
* Fix wrong prop
* Make it so order notes are persisted when toggling the checkbox
* Update type-defs
* Set showStepNumber default value to true
* Provider progress
* Revert nonce change for debugging
* Working emitters
* Fix dismiss link alignment in notices
* Fix button state and double adds
* Remove old context file
* Add type defs
* Fix context name
* Leftovers from merge
* Hooks up the variation picker to cart context
* Group event emitters in context
* Fix external product display
* Pass product through to VariationAttributes
* Pass around dispatchers
* Update assets/js/base/context/add-to-cart-form/form-state/reducer.js
Co-authored-by: Darren Ethier <darren@roughsmootheng.in>
* Update assets/js/atomic/blocks/product-elements/add-to-cart/product-types/variable/variation-attributes/attribute-select-control.js
Co-authored-by: Darren Ethier <darren@roughsmootheng.in>
* Update assets/js/base/context/add-to-cart-form/form-state/reducer.js
Co-authored-by: Darren Ethier <darren@roughsmootheng.in>
* remove placeholder comment
* content->container
* Clarify variation method comment
* update comment
* Switch nesting of providers
* Variation attribute utils test coverage
* If nothing is selected yet, just return all variations.
* Comments to explain loops
* Use refs to avoid recalculation of attributes on every render
* Update memo usage
* typo
* move mock data to test file
* Switch to useShallowEqual
* trigger cart fragment refresh after add to cart
* Decode option entities
Co-authored-by: Darren Ethier <darren@roughsmootheng.in>
* 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>
* stub out COD payment method for checkout block
* consistently use sentence case for (default) payment tab labels
* expose COD `enable_for_virtual` option to client
* correct docblock return value comment Stripe::get_inline_cc_form()
* allow merchant to disable COD payment for virtual/downloadable orders
* tweak canMakePayment dev docs - add cart-dependent example use case
* only allow (show) COD if initially-selected shipping method(s) allow
* tweak `canMakePayment` payment extension API docs
* use $VID:$ substitution for `@since` version in new payment methods
* use FILTER_VALIDATE_BOOLEAN for payment method boolean options
* use more semantic `some` when hunting for COD-unsupported shipping
* clarify `canMakePayment` API docs
* re-select payment method if selected method disappears (e.g. COD) +
+ factor out early return into separate if at top for clarity
* allow payment methods to disable based on shipping or other factors:
- renamed 'initialized' array 'available' to match primary purpose of
`canMakePayment` api - whether payment method should be available
- trigger refresh of available payment methods when shopper chooses
different shipping method
- rename resolveCanMakePayments => refreshCanMakePayments
- tweaked some variable names and scope for clarity
- added comments to clarify things
Note this should not affect behaviour yet - no existing payment methods
use this new feature. COD payment method will need this - woocommerce/woocommerce-blocks#2831
* optimise refreshCanMakePayments:
- useShallowEqual to avoid unnecessary call when shipping methods have
not actually changed (but object value has)
* replace ("set") payment methods in store, was appending:
- payment methods may come and go depending on cart/checkout state
- the previous SET action appended provided payment methods to the
collection
- this prevents dynamic payment methods e.g. COD from being able to hide
i.e. disable
* cache test payment request to avoid unnecessary stripe API calls:
- in the canMakePayment callback there's a test payment to determine if
chrome pay/apple pay is set up and available
- canMakePayment is now called multiple times as checkout state changes
- now the results of the test payment are stored in variable, and
returned on subsequent calls
* set init flag to avoid additional attempts to init stripe API:
+ tweak naming of init flag
* Form/button stucture
* Use registerBlockComponent
* Context for add to cart form
* Working cart button
* Tidy up button component
* Add todos
* Revert reg block
* Hide stock indicator if not purchasable
* Hide terms if empty
* Add url and type to API
* Skip default category from term response
* Rename form element
* Form for product types
* Tidy up context provider and expand todos
* No longer using qty icon
* Update todos
* Correct text domain
* registerExperimentalBlockType
* Duplicate method
* Remove prevent default
* Update docblock
* Description for button code
* add state for selected saved token in payment data
* add handling for flipping payment status back to pristine when checkout has error
If payment status is successful client side, but the checkout state goes into an error after server side processing, then we reset payment status to pristine to allow for reprocessing of payment method client side.
This is skipped for saved payment method tokens because they effectively are _only_ processed server side.
* fix dependencies
* refactor stripe payment-request to extract things into smaller units
- adds/fixes typedefs
- fixes dependencies
- improves logic.
* implement memoizing for functions.
* if same shipping address is selected, just call updateWith immediately
* add separate handler for failed shipping rate retrieval
* improve logic around shipping rate fail/success status
* add notice suppression logic to store notices.
- this is implemented in checkout processor to suppress notices when express payment methods are active.
* add error detection for shipping address errors and update the shipping status accordingly
* update type-def
* set billingData before shippingData
This is needed because of the shipping data and billing data sync logic in use-checkout-address.
* have to tighten dependencies to prevent unnecessary firing
With us now adding error status setters for shippping, the potential for the shipping status changes to trigger the effect went up. So tightening the dependencies to only the stati we care about prevent unnecessary effect calls.
* refactor event handlers to be named and remove all listeners.
This is an undocumented api on the stripe `paymentRequest.on` return value, but I’m trusting it will be relatively stable for this api.
The need for this is caused by the fact that without it, the listeners are re-registered on the paymentRequest event everytime the paymentRequest modal is closed and reopened.
* fix typo in doc block
* Refactor usePaymentMethodRegistration so initialisation happens at same point as dispatch
* Update NoPaymentMethods conditonal
* Suggested changes to payment init
* always default "save my card for next time" checkbox to unchecked:
This is based on the previous checkout behaviour.
I.e. the shopper has to actively opt-in to save their card.
* Implement "save payment method for next purchase" in checkout:
- send "save card" option using existing post key
- wc-stripe-new-payment-method
- comment out inappropriate use of "save" when using a saved card (tbc)
* don't hard code the payment gateway name in 'save payment method' key
* refactor "save payment info" checkbox so payment methods can opt-in:
- Add options.allowSavePaymentToken to payment method
registration / config.
- Opt-in in Stripe CC, it allows saved cards.
- Remove render of "save my card" checkbox from Stripe CC UI component.
- Render "save my card" checkbox automatically in payment method tab
(based on allowSavePaymentToken option).
+ todo/follow up comments
* rejig "save my payment method" behaviour so it's generic:
- Any payment method that supports "save" can opt-in:
- options.allowSavePaymentToken = true/false
- handle `wc-XXX-new-payment-method` key server side to persist
- Add support in payment context/state reducer for storing checkbox
state, expose value and action via context
- Convert state flag to appropriate API key/value in payment processor
- Remove previous stripe-specific implementation
+ bonus add comment to payment context about preserving state in
PRISTINE action
* rename payment method "allow save" option, more consistent with UI
* remove last vestiges of gateway-specific "save card" impl:
- No need to pass CheckboxControl to payment methods; checkbox is
now handled automatically by checkout.
- Remove shouldSavePayment prop passing through various layers of
stripe payment processing code. (Now handled in context/processor.)
* change new option property name and shape. Also adds validation.
* update type-defs
* use more reliable `activePaymentMethod` for saved payment method
Co-authored-by: Darren Ethier <darren@roughsmootheng.in>
* fix arguments
* only set payment status to pristine if it isn’t already successful
* add server side handling for saved tokens
* ensure correct gateway is selected when using saved card:
- reset the active payment method when user selects saved payment method
(card); this ensures that the correct gateway is used when switching
from another gateway to a saved card
* enhance radiocontrol to receive option specific change events.
* implement specific option change events
This commit:
- ensures selecting a saved payment option updates active payment method for the selected option.
- Sets the saved token key for the selected option correctly.
* remove unnecessary php side code
* fix bug with default saved payment option not applying:
When the payment options are initialised, we now call the onChange
handler for the default (`is_default`) option. This triggers payment
success() so checkout succeeds with default payment method, even if user
doesn't touch payment options.
* fix effect dependencies
Co-authored-by: Rua Haszard <rua.haszard@automattic.com>
* add typedefs for store notice context
* improve useStoreNotices hook so returned interfaces are fairly constant
* fix dependencies, defaults, and add types
* fix dependencies
* fix dependencies
* improve functions exposed on validation context so they are more constant
* fixing dependencies
* normalize tokenId to string everywhere
Assuming the token is a number is a bad idea because it is feasible that source for some payment methods could be a string. Also when retrieved as an input value, the id will be a string anyways.
* refactor to move payment processing into it’s own effect
- this is the first step in trying to improve the createSource behaviour.
* memoize setValidationErrors so onPaymentProcessing event effect doesn’t re-run unnecessarily.
* Update assets/js/payment-method-extensions/payment-methods/stripe/credit-card/use-payment-processing.js
Co-authored-by: Albert Juhé Lluveras <contact@albertjuhe.com>
* fix docs alignment
Co-authored-by: Albert Juhé Lluveras <contact@albertjuhe.com>
* Update notices to say `card` instead of `card's`
* Track isEmpty per field so placeholders are not visible when focusing and defocusing other fields
* Make payment notices non-dissmissable, and removed on payment method switch
* Don't add validation notices
* implement nullish coalescing operator
Co-authored-by: Darren Ethier <darren@roughsmootheng.in>
* Remove unused shippingAsBilling prop from billing data context
* Move functions out of component and add docblocks
* Local address state
* Refactor into new custom hook
* Remove TODO and code fixed in core
* useShallowEqual to prevent updates on all field changes
* Fix stale validation errors
* cleanup
* Should be setting local state not global state for email and phone
* Combine useEffects and pass correct deps
* Update assets/js/base/hooks/checkout/use-checkout-address.js
Co-authored-by: Seghir Nadir <nadir.seghir@gmail.com>
* Prettier
* Move validation update check into updateValidationError
* Fix state updaters
* Fix context definition for setShippingAddress
* Fix validation updates
* errorId dep
* Reapply changes to checkout block
* Update equality checks
Co-authored-by: Seghir Nadir <nadir.seghir@gmail.com>
With these changes:
- If an observer returns an object wthout a type property an error is thrown and the emitter is aborted with an error type response.
- For anything else returned from an observer, it’s discarded.
Tests are updated for the new expectations
* Move validation calls to checkout API class
* Validate before payment
* Support additional error data
* Add coupon validation before payment, and hide hashes from user
* Implement validation and recalculation
* Abstract notice handler and implement legacy filters
* Handle generic cart item errors
* strip tags from coupon error messages woocommerce/woocommerce-blocks#2212
* Ensure item errors are surfaced when coupons are removed
* Fix wrong value passed to hook
* fix broken checkout when no payment method is there
* try fixing unit test errors
* if preview data has a receiveCart function use it, otherwise default to an anononymous function
* fix tests
Co-authored-by: Seghir Nadir <nadir.seghir@gmail.com>
Co-authored-by: Darren Ethier <darren@roughsmootheng.in>
* Convert woo notices into exceptions when processing legacy payments
* Prevent console errors when a message is not returned in the response
* include top level message property to capture REST error messages
* include capturing rest error messages on afterProcessing action
* clear notices before exception
Co-authored-by: Darren Ethier <darren@roughsmootheng.in>
* fix broken validation error handling after submit
* Add handling for when there are no observers for payment processing or all observers just return true.
* cheque no longer needs to hook into event emitter
* account for no data on complete status handling in reducer
* add handling for either no observers or all observers returning true for onAfterProcessingWithSuccess emitter
* Handle errors when loading payment methods
* Use an error boundary
* Fix missing initial state in block error boundary
* Cleanup
* Only show internal user messages if it's admin or in editor
* Fixes
* Add friendly error message
* factor out editor preview data for saved payment methods to previews
* add missing imports lost in rebase
* use editorcontext to provide preview data to payment method context
* remove unused `activePaymentMethod` prop in CheckoutProvider and PaymentMethodDataProvider
* don't set the preview saved card as the default
* fix js error with cart in editor - fix EditorContext, pass previewData:
- editor context preview prop has changed;
- update cart to pass { previewCart } in previewData prop
- correctly destructure cart from previewData in useStoreCart hook
- correct typedefs
- EditorProvider props.previewData - now just Object
- similar for EditorDataContext
- correct default for activePaymentMethod state - empty string as before
* preselect 'use a new payment method' in checkout block editor preview
* update unit tests for changes to editor context
* remove stripe.js registration because it is lazy loaded via the library used.
* refactor payment method registration to preserve registration order.
* register payment method asset handles as dependency on editor script as well.
* initial mapping out of stripe payment intents
* rename checkout processing statuses to be clearer
* Add new status and refactor checkout complete behaviour.
* Make sure payment result data is included in checkout processing response
* add payment intent handling
Still testing
* make sure promise is returned
* include site url with endpoint
* modify setComplete status to optionally receive redirectUrl for changing in state at the same time as setting status
* fix typo in property retrieval
* add error handling for after checkout processing event
* add notices area for payment methods
* implement error handling for stripe intents
* hook into stripe error processing and include error in payment response
* clear notices so they don’t show in block and merge payment details
* add notice handling to payment context
* modify error processing in checkout processor
* handle errors with fallback in checkout state context
* hook into after processing for stripe cc error handling
* set checkout to idle status if before processing emitters result in error
* Add emit response type-defs and normalize expectations for observer responses
* improve doc block
* switch checkoutIsComplete check to checkoutAfterProcessing for payment complete status change
* remove unneeded event emitters and consolidate some logic
* fix idle status set logic
* remove logic server side for getting payment method from paymentdata
* ensure stripe accounts for payment request type payment methods
* make sure legacy payment method handling always runs last
* add processedPaymentMethodId to payment method data context state
* switch checkout processor to use new processedPaymentMethod id for submission
* implement returning paymentMethodId from payment-request-express
* include paymentMethodId in stripe cc success return value
* include paymentMethodId in cheque success return value
* add active payment method setting and handling via checkout
express payment methods still need to implement:
- onClick when their button is clicked
- onClose when the express payment interface is closed (cancelled etc).
* don’t expose setActivePaymentMethod on the payment method interface
* remove/fix artifacts from earlier iterations of the pull
* rename `id` property to `name` property for payment method registration
* Revert "include paymentMethodId in cheque success return value"
This reverts commit fe4ee8aced6d67bbd9033263ce61844349d18250.
* Revert "include paymentMethodId in stripe cc success return value"
This reverts commit 359a1f0089866110ec204182f8ffa14ab099c425.
* Revert "implement returning paymentMethodId from payment-request-express"
This reverts commit 117c68980b0876dee0acc78cec7754ccfe2a9bb1.
* Revert "switch checkout processor to use new processedPaymentMethod id for submission"
This reverts commit c38a05b63626dfc1336c7bb0e86417b798a803d6.
* Revert "add processedPaymentMethodId to payment method data context state"
This reverts commit 3d7923e7297f3c76efde536d26eaf68464ba9583.
* improve isSuccess response check and variable name
* implement paymentMethodId config option
* doh php ain’t javascript
* add missing dependency from rebase
* use cart data to provide country and currency_code
* remove files that likely got added back in from a bad rebase.
* modify canMakePayment config property so it must be a function
* Feed cart data to registered payment methods `canMakePayment` function.
This can then be used by payment methods for determining whether to show the payment method or not.
* implement new canMakePayment signature for cheque
Now canMakePayment doesn’t need to be a promise (payment method registry will handle wrapping all values in a promise to treat them as promises.
* implement canMakePayment as a function
* add logic allowing payment method to be overridden via payment data in request
* hook in to trigger server side processing of stripe payment request
* improvements to shipping data context
- memoize event emitters
- split up emitted events (reduces how often events trigger)
- Include whether rate is being selected in exported data.
* expose `isSelectingRate` value to payment method interface
* fix typo in shipping emitters for emitter type
* include setting of shipping data in payment method success status call
- this also requires changing the nested order of providers in checkout provider
* fix priority logic for event emitters.
- lower priority is supposed to fire before higher priority.
* normalize postal code for comparisons
* move normalize functions into stripe-utils folder
* refactor stripePromise so that it provides a specific instance to each payment method.
This also provides it as a prop to the pm components.
* renadme apple pay express to payment request express
This adds full support for the stripe payment request api instead of just applePay (so GooglePay, MicrosoftPay and ApplePay are now supported).
Also adds numerous fixes to internal logic.
* add handling to skip core checkout validation logic if express payment method is handling payment
Express payment methods have their own internal validation so this removes the need for checkout validating fields. This is also necessary because checkout validation breaks the flow when making a payment using express payment methods because of the order of the flow for these methods.
* splitting out emmitter effects for checkout and improving logic
Splitting up effects limits the potential for firing off emitters more than needed.
* remove unnecessary ref definitions
* fix on cancel action erroring for payment request modal
* ensure unique stripe object for component and canPay
* set default total label if one isn’t configured on the server
* fix order of state changes
* simplify condition
* remove unnecessary dependency
* normalize to uppercase too
* simplify can make payment conditional
* update comment blocks
* remove calculating as a checkout status (making it separate)
* include checkout is calculating for determining whether to flip payment status to process
* only change payment method state for status changes if needed
* fix reducer for shipping state
* include checkoutIsCalculating for determining whether to show validation errors in checkout block
* change where currentStatus is defined
* fix bug with saved payment method option
* Counting helpers for shipping rates and packages
* Use new helpers
* Make shipping calculator use shipping context directly
* Totals should use current address
* Avoid useShippingRates
* Return rates and other items from useShippingRatse in useStoreCart instead
* Update tests
* Merge conflict
* Merge conflict
* move preview to editor data and alias it no nothing in frontend builds
* seperate context and provider
* pass previewData as a prop to provider
* address comments
* Add customer ID to checkout API response
* Add customer ID to checkout context
* Show/hide remember payment checkbox based on checkout context
* Pass via payment interface instead
* Missing commas
* Make validation errors appear
* Make validation errors appear all at once
* Simplify diff
* Expose shippingErrorStatus from shipping context
* Memoize currentErrorStatus
* Pass currentErrorStatus to observers
* Add missing type-def property
* Fix typo in constant name
* Refactor emitEvent so false responses don't return true
* Make onCheckoutProcessing observers return errorMessage and validationErrors properties
* remove usage of paymentstatus dispatcher from apple pay
* add type-def for payment data response objects
* make sure shape of payment data for stripe cc is as server expects
* include payment data in checkout processor request
* fix bug that got reintroduced in rebase
* rename typedef
* Add interface for setting an express payment error notice.
* fix typedefs
* remove usage of paymentstatus dispatcher from stripe cc
* remove usage of paymentstatus dispatcher from apple pay
* remove any existing express payment notice on click
* revert buggy change with abort payment call
- also ensure that completePayment sets applePayProcessing to false
* Allow for priority to be set on event emitters
* Add payment event emitters
* add new actions/status to checkout state context
* implement event emitters in payment data context
* refactor checkout state context to use new actions in event emitters
* refactor checkout processor to handle new event emitters
* fix type-defs for registered payment methods
* register observer for cheque payment method integration
* add inline todo
* fix sort
* fix tests and add test for priority usage in event emitters
* remove todo and just add explanatory comment
* condense sort logic
* lowercase test description
* abstract emitter callback to reduce code
* don’t process passed in errors if it’s undefined
* improve error response expectation for payment processing event observer
* Hook up checkout validation with context
* Make sure hasValidationErrors is up to date in onCheckoutProcessing
* Move validation check inside CheckoutProcessor's processCheckout
* Make sure all checkout form fields have a unique ID
* Don't clear checkout context errors in shipping context
* Move CheckoutProcessor to the top so scrollToTop works
* Do not disable Place Order Button if there are errors
* Split checkValidation and processCheckout in Checkout Provider
* Refactor event emitter to use Maps
* Save payment method errors to validation context
* Show an notice when a payment method has an error
* Make sure JS errors during payment are displayed
* Remove error notice when payment method doesn't return an error anymore
* Make sure payment methods know if shipping and billing addresses are the same
* Make sure checkout is only processed if payment methods didn't fail
* Make sure state input also has an id
* Clear input and select errors on unmount
* Pass id to CountryInput and StateInput
* Fix function name
* Add missing default context values
* Move onCheckoutCompleteError effect to CheckoutBlock
* Remove conditional from shipping setHasError
* Rename and move existing checkout provider to checkout-state provider.
This allows us to re-use the interface exposed on this provider for cart and checkout blocks.
* refactor checkout provider to implement the new checkout state provider.
* Add Cart provider and export
* fix type-defs
* fix editor context provider and ensure all `isEditor` checks come from this provider
* fix type definition
* implement cart provider
* add selecting rate resolution state to the cart store
* expose whether rate is being selected on useSelectShippingRate
* Cleanup and refactor ShippingDataProvider
- remove un-needed component and move shipping rates into context provider
- remove error handling (currently the ui/ux for the checkout should result in no errors and any api errors are non-recoverable).
- Add logic for shipping rate selection into context provider and add event emitters for it.
- increment/decrement checkout calculation counts when shipping rates are being selected.
* dispatch checkout error if there is an error
* disable place order button if checkout is calculating or has error
* update doc block
* fix convention for js comment blocks
* 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
* Make Product Price component accessible
* Render checkout form step number before the content instead of after
* Announce changes in the Shipping Rates Control results
* Render product name before product price in the Checkout sidebar
* Verify error element id exists before using it in describedBy
* Avoid reading 'Choose a shipping method' if no shipping methods are available
* Hide product image from screen readers if there is no alt text and make link not focusable
* Move Checkout block buttons below the sidebar
* Simplify selector
* Remove ternary to make code easier to understand
* Fix rebase issue
* Fix step number not visible for payment methods
* Server side changes for payment method integrations
Including adding a stripe class temporarily
* update needed npm packages (and add some types)
* updates to contexts
* remove stepContent from payment config for payment methods
* update payment method interface and typedefs
Exposing a components property to pass along components that payment methods can use (so we keep styles consistent for them)
* add apple pay and stripe cc integration and remove paypal
* remove save payment checkbox from checkout block
It is handled by payment methods.
* Include an id prop for tabs
* fix activePaymentMethod pass through on rendered payment method element
also adds an id for the rendered tab
* add styles for payment method fields
If payment methods use these classes for their fields then the styles will get applied. It _could_ allow for consistent styling, we may have to provide design documentation for this?
These are styles in cases where payment methods have to use elements provided by the gateway (eg. Stripe elements). In future iterations we could look at providing components to payment methods to use (if they aren’t restricted by the gateway).
* fix rebase conflict
* do a test payment request for applePay to determine if the current browser supports it
* don’t console.error for stripe loading.
* Fix placeholder errors in the editor
* improve styling and add missing validation for inline card element
* update pacakge-lock
* rename payment-methods-demo folder to payment-methods-extension
* expose checkbox control on payment method interface
* export payment-methods-extension to it’s own asset build
This allows us to more accurately demonstrate how payment extensions would hook in to the blocks.
* don’t enqueue a style that doesn’t exist
* add full stop to comments and remove obsolete comment blcok
* fix spacing
* switch `activeContent` to `content` for payment method registration config
* Checkout class tidyup
* CheckoutProcessor placeholder
* ShippingMethodDataX to ShippingDataX
* Remove billing from checkout provider
* Remove billing data hook
* Remove billing from payment methods state
* Update typedefs
* Billing context
* Fix billing and shipping context persistence bugs
* Remove address form change
* Move phone back; another PR can deal with this
* Remove unused state
* Add saved-payment-method options handling and improve payment method registration initialization
* add server side exposure of saved customer payment methods
* fix reducer for express payment method state
* fix default for customerPaymentMethods
* 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>
* Add Checkout form validation
* Add back validation when filling the address without having set a country
* Split TextInput and Select so they can be used with or without validation
* Cleanup
* Only display the missing country error if city, state or postcode are entered
* Fix CSS specificity conflict
* Remove unnecessary semicolon
* Rename areThereValidationErrors to hasValidationErrors
* restructure event-emit directory and convert emitters to promises
- also add emitEventWithAbort function
* implement event emitters as promises
* clean up logic
- return from for loop
- define response as const on each iteration.
- return true if loop completes successfully.
* rename event_emit folder to event-emit
* add errormessage handling to countryinput (along with storybook)
* add types for react
* Add validation context and implement
* implement validation context for country field validation
* tweak ValidationInputError so that it can receive property name for getting error from
* improve storybook webpack config to pull from tsconfig.json
* update storybook story to cover changes with context
* Wrap Checkout Provider with Validation Context Provider
* add screen-reader-text style to storybook
* add styles for input error validation to text input
* improve styling for ValidationInputError component
* add validation error handling to TotalsCouponCode component
And story
* make sure errors are cleared on successful receive/remove item
* dispatch loading cancellation on catching errors
This is needed because loading would be cancelled before the error is thrown so any error handling after the thrown error will not be able to rely on loading.
* implement validation setting for coupon errors
* add error color to labels on inputs too
* fix borders back and force border color
* remove extra structure and improve validation error with alignment for coupon code
* add aria-describedby for text inputs
* add back in validation context provider to fix rebase issue
* rework validation so it works for both checkout and cart
* Some styling tweaks
* more style fixes
* remove unnecessary method
* make sure new function is included in context defaults
* package.lock update? seems harmless so rolling with it.
* add snackbarnotices to notices system
* implement snackbar notices for coupon code ui
* improve styles with mobile styles as well
* some more css fixes
* use native filter
* remove usage of lodash filter and dont’ output container if there are no regular notices
* remove unnecessary duplication of styles
- load default snackbar styles from WordPress components
- override for frontend to make them fixed to the window (including mobile treatement).
* simplify css class generation (save some bytes)
* improve proptypes definition
h/t: @aljullu
* consistent style handle name
* increase bundle size budget
* 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>
* add isEditor to checkotu context and implement in provider usage
* modify configuration expectations for payment method registration api
* update registration of payment methods in demo
* implement new configuration in payment method components
* fix argument order and update jsdocs
- restructures `@woocommerce/base-context` imports so it pulls from `index.js` in the `base/context` folder. That way tree-shaking will be used if possible. This also helps with organizing the folder structure a bit better for the new contexts.
- Fixes all the various imports through the code due to the above change.
- Adds `CheckoutContextProvider`, `useCheckoutContext` and related files.
- Adds `PaymentMethodDataProvider`, `usePaymentMethodDataContext` and related files.
- Adds `ShippingMethodDataProvider`, `useShippingMethodDataContext` and related files.
- Adds typedefs used for the various context interfaces.
* Working on store provider
* Working on store provider
* Reducer implementation
* Implement core/notices
* Add notices to store coupon hook with context
* Improve store notice text and styling
* Improve JS side API for notices
* Wrap functions with context additon
* Update test to []
* Implement props feedback and useInstanceId
* Update assets/js/base/context/store-notices-context.js
Co-Authored-By: Darren Ethier <darren@roughsmootheng.in>
* Update assets/js/base/context/store-notices-context.js
Co-Authored-By: Darren Ethier <darren@roughsmootheng.in>
* remove instance id
Co-authored-by: Darren Ethier <darren@roughsmootheng.in>
* Add Feedback Prompt in Cart & Checkout blocks sidebar
* Add border
* Move getInspectorControls out of the component function
* Move feedback prompt to a HOC
* Add @todo comment to feedback link
* Use filter for withFeedbackPrompt
* Export withFeedbackPrompt from hocs index.js
* Typo
* Try moving the feedback texts to context
* Revert "Try moving the feedback texts to context"
This reverts commit 21f889b021ceea6fef722efab9663799829bc769.
* Revert "Use filter for withFeedbackPrompt"
This reverts commit 96bba029d61a383eafa2c0a1c08f7988e319b50d.
* Set feedback text in the HOC function
* Use arrow-function to simplify code
* Refactor
* Update NPM packages
* Switch JSON dependencies to new PHP files
* include->require
* include->require
* Remove from package and run audit fix
* Update wp-prettier
* Use version from asset file
* Fix eslint issues and test failures
* Update OriginalComponent docblocks
* Props are objects, not arrays
* Array to Object
* fix tests throwing unhandled rejection errors in node.
These tests were all testing Promise.rejects but then not properly catching the reject in the assertions.
* exclude rule for no short array syntax allowed
This is a WordPress core standard that we choose to ignore because it’s silly in our context to follow that rule (and we’re being consistent with WooCommerce Admin).
* 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
* add a context value validator and tests
This handles validation incoming value prop on a context provider with an object.
* implement context validator and fix related bugs
* rename context to better match it’s purpose
* correct spelling
* Update assets/js/base/context/utils.js
Co-Authored-By: Albert Juhé Lluveras <aljullu@gmail.com>
* tighten up the iteration
* 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