'category', 'product_shipping_class' => 'shipping_class', 'product_type' => 'product_type', ); /** * Condition fields the saved rules use, and the rules they were read from. * * @var array{0: mixed, 1: array}|null */ private $used_fields = null; /** * Fields whose product facts changed this request (cached rates are refreshed at shutdown). * * @var array */ private $changed = array(); /** * {@inheritDoc} */ public function id() { return 'shipping-rules'; } /** * {@inheritDoc} */ public function title() { return __( 'Shipping method rules', 'admin-powerups-for-woocommerce' ); } /** * {@inheritDoc} */ public function description() { return __( 'Hide or offer shipping methods by cart total, shipping class, category, country and more, and hide other options when free shipping is available.', 'admin-powerups-for-woocommerce' ); } /** * {@inheritDoc} */ public function category() { return 'operations'; } /** * {@inheritDoc} */ public function location() { return __( 'Cart and checkout', 'admin-powerups-for-woocommerce' ); } /** * {@inheritDoc} */ public function icon() { return 'truck'; } /** * {@inheritDoc} */ public function autoload_settings() { return true; } /** * {@inheritDoc} * * @return array> */ public function fields() { return array( array( 'id' => 'free_hides_others', 'type' => 'toggle', 'label' => __( 'When free shipping is available, hide the other methods', 'admin-powerups-for-woocommerce' ), 'description' => __( 'Customers only see the free option once they qualify.', 'admin-powerups-for-woocommerce' ), 'default' => false, ), array( 'id' => 'keep_pickup', 'type' => 'toggle', 'label' => __( 'Keep local pickup', 'admin-powerups-for-woocommerce' ), 'description' => __( 'Still offer pickup next to free shipping.', 'admin-powerups-for-woocommerce' ), 'default' => true, 'show_if' => array( 'free_hides_others', '1' ), ), array( 'id' => 'rules', 'type' => 'checkout_rules', 'label' => __( 'Rules', 'admin-powerups-for-woocommerce' ), 'description' => __( '“Hide” removes the methods when the conditions match. “Only offer” shows them only when the conditions match. Pick a method type (“Any Flat rate”) or one method in one zone.', 'admin-powerups-for-woocommerce' ), 'default' => array(), 'payment' => false, 'targets' => 'shipping_methods', 'targets_label' => __( 'Shipping methods', 'admin-powerups-for-woocommerce' ), ), ); } /** * Sanitize a setting. Rules JSON that can't be read keeps the saved rules. * * @since 1.0.0 * @param array $field Field schema. * @param mixed $value Raw value. * @return mixed */ protected function sanitize_field( array $field, $value ) { if ( 'checkout_rules' !== $field['type'] ) { return parent::sanitize_field( $field, $value ); } $current = $this->setting( 'rules' ); return Rules::sanitize( $value, false, 'shipping_methods', is_array( $current ) ? $current : array() ); } /** * Register the rules builder (works while the power-up is off). * * @since 1.0.0 * @param string $tab Tab being shown. * @return void */ public function admin_screen( $tab ) { add_action( 'apwc_render_field_checkout_rules', array( RulesField::class, 'render' ), 10, 3 ); RulesField::enqueue(); } /** * {@inheritDoc} */ public function boot() { add_filter( 'woocommerce_package_rates', array( $this, 'filter' ), 50, 2 ); add_filter( 'woocommerce_cart_shipping_packages', array( $this, 'fingerprint' ) ); // Cached rates don't know about product facts the rules check: refresh them when one changes. add_action( 'set_object_terms', array( $this, 'terms_changed' ), 10, 6 ); add_action( 'woocommerce_product_object_updated_props', array( $this, 'props_changed' ), 10, 2 ); add_action( 'edited_product_cat', array( $this, 'category_changed' ) ); add_action( 'delete_product_cat', array( $this, 'category_changed' ) ); add_action( 'shutdown', array( $this, 'refresh_rates' ) ); } /** * Condition fields the saved rules use. * * @since 1.0.0 * @return array */ private function used_fields() { $rules = $this->setting( 'rules' ); if ( null === $this->used_fields || $this->used_fields[0] !== $rules ) { $used = array(); foreach ( Rules::well_formed( $rules ) as $rule ) { foreach ( $rule['conditions'] as $condition ) { if ( is_string( $condition['field'] ?? null ) ) { $used[ $condition['field'] ] = true; } } } $this->used_fields = array( $rules, $used ); } return $this->used_fields[1]; } /** * Note that a product fact changed; cached rates are refreshed once, at the end of the request. * * @param string $field Condition field. * @return void */ private function mark( $field ) { if ( isset( $this->used_fields()[ $field ] ) ) { $this->changed[ $field ] = true; } } /** * A product's categories, shipping class or type changed. * * @since 1.0.0 * @param int $object_id Object ID. * @param array $terms Terms given. * @param array $tt_ids Term taxonomy IDs now. * @param string $taxonomy Taxonomy. * @param bool $append Appended. * @param array $old_tt_ids Term taxonomy IDs before. * @return void */ public function terms_changed( $object_id, $terms, $tt_ids, $taxonomy, $append, $old_tt_ids ) { if ( ! isset( self::TAXONOMY_FIELDS[ $taxonomy ] ) ) { return; } $now = array_map( 'intval', (array) $tt_ids ); $before = array_map( 'intval', (array) $old_tt_ids ); sort( $now ); sort( $before ); if ( $now !== $before ) { $this->mark( self::TAXONOMY_FIELDS[ $taxonomy ] ); } } /** * A product (or variation) became virtual/downloadable or stopped being one. Other props * (stock, price) never refresh rates. * * @since 1.0.0 * @param WC_Product $product Product. * @param string[] $props Updated props. * @return void */ public function props_changed( $product, $props ) { if ( array_intersect( array( 'virtual', 'downloadable' ), (array) $props ) ) { $this->mark( 'product_type' ); } } /** * A category was edited (e.g. moved under another parent) or deleted. * * @since 1.0.0 * @return void */ public function category_changed() { $this->mark( 'category' ); } /** * Refresh cached shipping rates once if a product fact the rules use changed this request. * Direct meta/SQL writes (some importers) don't fire the hooks, so they don't refresh rates. * * @since 1.0.0 * @return void */ public function refresh_rates() { if ( ! $this->changed || ! class_exists( WC_Cache_Helper::class ) ) { return; } $fields = array_keys( $this->changed ); $this->changed = array(); WC_Cache_Helper::get_transient_version( 'shipping', true ); /** * Fires after cached shipping rates were refreshed because a product fact the shipping * rules use changed (category, shipping class, type, virtual/downloadable). At most once * per request. The refresh drops every shopper's cached rates, so live carrier rates are * fetched again. * * @since 1.0.0 * @param string[] $fields Condition fields whose facts changed. */ do_action( 'apwc_shipping_rules_refresh_rates', $fields ); } /** * Rates are cached per package; add what rules check but the package doesn't contain (the * customer's role) so the cache refreshes when it changes, e.g. on login. * * @since 1.0.0 * @param array> $packages Packages. * @return array> */ public function fingerprint( $packages ) { // Every setting is in the key, so turning an option on or off refreshes cached rates too. $key = md5( wp_json_encode( array( Context::roles( get_current_user_id() ), $this->settings() ) ) ); foreach ( $packages as &$package ) { $package['apwc_rules'] = $key; } return $packages; } /** * Remove rates the rules take away. * * @since 1.0.0 * @param WC_Shipping_Rate[] $rates Rates by ID. * @param array $package Package. * @return WC_Shipping_Rate[] */ public function filter( $rates, $package ) { if ( ! is_array( $rates ) || ! $rates ) { return $rates; } $method = static fn( $rate ) => $rate instanceof WC_Shipping_Rate ? $rate->get_method_id() : ''; $rules = (array) $this->setting( 'rules' ); if ( $rules ) { $remove = Rules::removals( $rules, Context::from_package( (array) $package ), static function ( $id, $target ) use ( $rates, $method ) { // A target is one method ("flat_rate:3") or every method of a type ("flat_rate"). return $id === $target || ( false === strpos( $target, ':' ) && $method( $rates[ $id ] ?? null ) === $target ); }, array_map( 'strval', array_keys( $rates ) ) ); $rates = array_diff_key( $rates, array_flip( $remove ) ); } if ( $this->setting( 'free_hides_others' ) ) { $free = array_filter( $rates, static fn( $rate ) => 'free_shipping' === $method( $rate ) ); if ( $free ) { $keep = $this->setting( 'keep_pickup' ) ? array_filter( $rates, static fn( $rate ) => in_array( $method( $rate ), array( 'local_pickup', 'pickup_location' ), true ) ) : array(); $rates = $free + $keep; } } return $rates; } }