Plugin Directory

Changeset 3803428


Ignore:
Timestamp:
11/15/2026 02:52:19 PM (2 days ago)
Author:
garidium
Message:

bug fixes

Location:
g-ffl-checkout/trunk
Files:
8 edited

Legend:

Unmodified
Added
Removed
  • g-ffl-checkout/trunk/README.txt

    r3767076 r3803428  
    66Tested up to: 7.1
    77Requires PHP: 7.0
    8 Stable tag: 2.2.7
     8Stable tag: 2.2.8
    99License: GPL v3+
    1010License URI: https://www.gnu.org/licenses/gpl-3.0.html
    … …  
    145145
    146146== Changelog ==
     14761. v2.2.8 Blocks fixes and security updates
    14714860. v2.2.7 Blocks default Map Location Bug Fixes
    14814959. v2.2.6 Various bug fixes
  • g-ffl-checkout/trunk/blocks/class-ffl-blocks-integration.php

    r3767076 r3803428  
    267267     */
    268268    public function get_script_data() {
    269         $aKey = esc_attr(get_option('ffl_api_key_option'));
     269        $api_configured = !empty(get_option('ffl_api_key_option'));
    270270        $plugin_url = plugin_dir_url(dirname(__FILE__));
    271271
    … …  
    316316
    317317        return array(
    318             'apiKey' => $aKey,
     318            'apiConfigured' => $api_configured,
    319319            'pluginDirectory' => $plugin_url . 'public/',
    320320            'requiresFflSelector' => $requires_ffl,
  • g-ffl-checkout/trunk/blocks/class-ffl-store-api-extension.php

    r3745189 r3803428  
    1616
    1717    const IDENTIFIER = 'g-ffl-checkout';
     18    private $profile_shipping_order = null;
     19    private $restored_shipping = false;
    1820
    1921    /**
    … …  
    3941            'callback' => array($this, 'handle_ffl_update'),
    4042        ));
     43
     44        // Let the browser use the server's current cart classification after selection.
     45        woocommerce_store_api_register_endpoint_data(array(
     46            'endpoint' => \Automattic\WooCommerce\StoreApi\Schemas\V1\CartSchema::IDENTIFIER,
     47            'namespace' => self::IDENTIFIER,
     48            'data_callback' => function () {
     49                $destination = array();
     50                foreach ($this->shipping_destination_fields() as $field) {
     51                    $destination[$field] = WC()->customer ? WC()->customer->{'get_shipping_' . $field}() : '';
     52                }
     53                return array(
     54                    'dealer_shipping' => (bool) (WC()->session && WC()->session->get('ffl_block_shipping_selected')
     55                        && $this->shipping_cart_type() === 'dealer'),
     56                    'restored_shipping' => $this->restored_shipping,
     57                    'shipping_destination' => $destination,
     58                );
     59            },
     60            'schema_callback' => function () {
     61                $properties = array();
     62                foreach ($this->shipping_destination_fields() as $field) {
     63                    $properties[$field] = array('type' => 'string');
     64                }
     65                return array(
     66                    'dealer_shipping' => array('type' => 'boolean', 'readonly' => true),
     67                    'restored_shipping' => array('type' => 'boolean', 'readonly' => true),
     68                    'shipping_destination' => array('type' => 'object', 'properties' => $properties, 'readonly' => true),
     69                );
     70            },
     71            'schema_type' => ARRAY_A,
     72        ));
     73
     74        // Keep the cart destination available before rates/taxes are calculated.
     75        add_action('woocommerce_before_calculate_totals', array($this, 'sync_dealer_shipping'));
     76        add_action('woocommerce_cart_emptied', array($this, 'clear_dealer_shipping'));
     77        add_action('woocommerce_before_customer_object_save', array($this, 'preserve_profile_shipping'));
    4178
    4279        // Save FFL data to order when checkout processes
    … …  
    187224     */
    188225    public function handle_ffl_update($data) {
     226        $this->restored_shipping = false;
    189227        if (!WC()->session) {
    190228            return;
    … …  
    192230
    193231        if (!empty($data['ffl_license_number'])) {
     232            $compliance_mode = isset($data['compliance_mode']) && is_string($data['compliance_mode'])
     233                ? ffl_normalize_compliance_type($data['compliance_mode']) : '';
     234            if ($this->shipping_cart_type($compliance_mode) === 'dealer') {
     235                foreach (array('ffl_premise_street', 'ffl_premise_city', 'ffl_premise_state', 'ffl_premise_zip') as $field) {
     236                    if (empty($data[$field]) || !is_string($data[$field]) || trim($data[$field]) === '') {
     237                        throw new \Automattic\WooCommerce\StoreApi\Exceptions\RouteException(
     238                            'ffl_incomplete_dealer_address',
     239                            'The selected dealer has an incomplete shipping address. Please select another dealer.',
     240                            400
     241                        );
     242                    }
     243                }
     244            }
     245            WC()->session->set('ffl_block_compliance_mode', $compliance_mode);
    194246            WC()->session->set('ffl_license_number', sanitize_text_field($data['ffl_license_number']));
    195247            WC()->session->set('ffl_expiration', sanitize_text_field(isset($data['ffl_expiration']) ? $data['ffl_expiration'] : ''));
    … …  
    205257        // Handle clearing FFL selection
    206258        if (isset($data['clear_ffl']) && $data['clear_ffl']) {
     259            WC()->session->__unset('ffl_block_compliance_mode');
    207260            WC()->session->set('ffl_license_number', '');
    208261            WC()->session->set('ffl_expiration', '');
    … …  
    214267            WC()->session->set('ffl_premise_state', '');
    215268            WC()->session->set('ffl_premise_zip', '');
     269            $this->restore_customer_shipping();
     270        } elseif (!empty($data['ffl_license_number'])) {
     271            WC()->session->set('ffl_block_shipping_selected', true);
     272            $this->sync_dealer_shipping();
     273        }
     274    }
     275
     276    private function shipping_destination_fields() {
     277        return array('company', 'address_1', 'address_2', 'city', 'state', 'postcode', 'country');
     278    }
     279
     280    /** Store API requests do not carry the checkout page's compliance query string. */
     281    private function shipping_cart_type($compliance_mode = null) {
     282        if (!WC()->cart || !WC()->customer || isset($_COOKIE['g_ffl_checkout_candr_override'])) {
     283            return 'customer';
     284        }
     285        // Evaluate the customer's original destination, not the selected dealer's state.
     286        $original = WC()->session ? WC()->session->get('ffl_block_original_shipping') : null;
     287        $state = is_array($original) ? ($original['state'] ?? '') : WC()->customer->get_shipping_state();
     288        $state = $state ?: WC()->customer->get_billing_state();
     289        if ($compliance_mode === null) {
     290            $compliance_mode = WC()->session ? WC()->session->get('ffl_block_compliance_mode', '') : '';
     291        }
     292        // Only apply an explicitly active mode that matches the merchant's configured rule.
     293        $type = $compliance_mode && $state && ffl_get_state_compliance_type($state) === $compliance_mode
     294            ? $compliance_mode : false;
     295        $rule = $type === 'custom' ? ffl_get_state_compliance_rule($state) : false;
     296        $has_dealer_items = false;
     297        $has_customer_items = false;
     298        foreach (WC()->cart->get_cart() as $item) {
     299            $product = $item['data'];
     300            $requires_dealer = product_is_firearm($product)
     301                || ($type === 'ammunition' && product_is_ammunition($product))
     302                || $type === 'all_non_firearms'
     303                || ($type === 'custom' && ffl_product_matches_custom_compliance($product, $rule));
     304            $has_dealer_items = $has_dealer_items || $requires_dealer;
     305            $has_customer_items = $has_customer_items || !$requires_dealer;
     306        }
     307        return $has_dealer_items ? ($has_customer_items ? 'mixed' : 'dealer') : 'customer';
     308    }
     309
     310    /** Use a dealer destination in the cart session, never in the billing address. */
     311    public function sync_dealer_shipping() {
     312        if (!WC()->session || !WC()->customer || !WC()->cart
     313            || !WC()->session->get('ffl_block_shipping_selected')) {
     314            return;
     315        }
     316
     317        // Cart contents are authoritative; do not trust the browser's mixed-cart flag.
     318        if (WC()->cart->cart_context !== 'store-api' || WC()->cart->is_empty()
     319            || !WC()->session->get('ffl_license_number') || isset($_COOKIE['g_ffl_checkout_candr_override'])) {
     320            $this->restore_customer_shipping();
     321            return;
     322        }
     323        $cart_type = $this->shipping_cart_type();
     324        if ($cart_type !== 'dealer') {
     325            $this->restore_customer_shipping();
     326            // Keep the selection so removing the regular items can restore dealer shipping.
     327            if ($cart_type === 'mixed') {
     328                WC()->session->set('ffl_block_shipping_selected', true);
     329            }
     330            return;
     331        }
     332
     333        $destination = array(
     334            'company' => WC()->session->get('ffl_name', ''),
     335            'address_1' => WC()->session->get('ffl_premise_street', ''),
     336            'address_2' => '',
     337            'city' => WC()->session->get('ffl_premise_city', ''),
     338            'state' => WC()->session->get('ffl_premise_state', ''),
     339            'postcode' => WC()->session->get('ffl_premise_zip', ''),
     340            'country' => 'US',
     341        );
     342        foreach (array('address_1', 'city', 'state', 'postcode') as $field) {
     343            if (empty($destination[$field])) {
     344                throw new \Automattic\WooCommerce\StoreApi\Exceptions\RouteException(
     345                    'ffl_incomplete_dealer_address',
     346                    'The selected dealer has an incomplete shipping address. Please select another dealer.',
     347                    400
     348                );
     349            }
     350        }
     351
     352        if (null === WC()->session->get('ffl_block_original_shipping', null)) {
     353            $original = array();
     354            foreach ($this->shipping_destination_fields() as $field) {
     355                $original[$field] = WC()->customer->{'get_shipping_' . $field}();
     356            }
     357            WC()->session->set('ffl_block_original_shipping', $original);
     358        }
     359        foreach ($destination as $field => $value) {
     360            WC()->customer->{'set_shipping_' . $field}($value);
     361        }
     362        // WC()->customer uses WooCommerce's session data store. No billing setters.
     363        WC()->customer->save();
     364    }
     365
     366    /** Clearing the dealer or switching to a mixed cart restores the shopper's destination. */
     367    public function restore_customer_shipping() {
     368        if (!WC()->session || !WC()->customer) {
     369            return;
     370        }
     371        $original = WC()->session->get('ffl_block_original_shipping', null);
     372        if (is_array($original)) {
     373            $this->restored_shipping = true;
     374            foreach ($this->shipping_destination_fields() as $field) {
     375                WC()->customer->{'set_shipping_' . $field}($original[$field] ?? '');
     376            }
     377            WC()->customer->save();
     378        }
     379        WC()->session->__unset('ffl_block_original_shipping');
     380        WC()->session->__unset('ffl_block_shipping_selected');
     381    }
     382
     383    public function clear_dealer_shipping() {
     384        if (WC()->session && WC()->session->get('ffl_block_shipping_selected')) {
     385            $this->handle_ffl_update(array('clear_ffl' => true));
     386        }
     387    }
     388
     389    /** Blocks copies order addresses to account defaults at submission; retain the saved shipping address. */
     390    public function preserve_profile_shipping($customer) {
     391        if (!$this->profile_shipping_order || $customer === WC()->customer || !$customer->get_id()
     392            || $customer->get_id() !== $this->profile_shipping_order->get_customer_id()) {
     393            return;
     394        }
     395        $saved = new WC_Customer($customer->get_id());
     396        foreach ($this->shipping_destination_fields() as $field) {
     397            $customer->{'set_shipping_' . $field}($saved->{'get_shipping_' . $field}());
    216398        }
    217399    }
    … …  
    224406     */
    225407    public function save_ffl_data_to_order($order, $request) {
     408        $this->profile_shipping_order = null;
    226409        $extensions = $request->get_param('extensions');
    227410        $ffl_data = isset($extensions[self::IDENTIFIER]) ? $extensions[self::IDENTIFIER] : array();
    … …  
    293476                $is_mixed = order_contains_mixed_cart();
    294477            }
     478            if (WC()->session && WC()->session->get('ffl_block_shipping_selected')) {
     479                $is_mixed = $this->shipping_cart_type() === 'mixed';
     480            }
    295481
    296482            $mixed_cart_support = get_option('ffl_mixed_cart_support') === 'Yes';
    … …  
    301487                $order->set_shipping_company('');
    302488            } elseif (!$is_mixed) {
     489                // A Blocks draft may previously have contained customer-bound items.
     490                $order->delete_meta_data('_is_mixed_cart_order');
     491                $this->profile_shipping_order = $order;
    303492                // For non-mixed FFL orders, set shipping address to FFL address
    304493                if (!empty($ffl_name)) {
    … …  
    353542        $order->save();
    354543
    355         // Clear FFL session data after saving
     544        // Blocks can save a draft before payment or recalculate after a failed attempt.
     545        // Keep the selected destination until the cart is emptied or the dealer is cleared.
    356546        if (WC()->session) {
    357             WC()->session->set('ffl_license_number', '');
    358             WC()->session->set('ffl_expiration', '');
    359             WC()->session->set('ffl_name', '');
    360             WC()->session->set('ffl_phone', '');
    361             WC()->session->set('ffl_onfile', '');
    362             WC()->session->set('ffl_premise_street', '');
    363             WC()->session->set('ffl_premise_city', '');
    364             WC()->session->set('ffl_premise_state', '');
    365             WC()->session->set('ffl_premise_zip', '');
     547            if (!WC()->session->get('ffl_block_shipping_selected')) {
     548                WC()->session->set('ffl_license_number', '');
     549                WC()->session->set('ffl_expiration', '');
     550                WC()->session->set('ffl_name', '');
     551                WC()->session->set('ffl_phone', '');
     552                WC()->session->set('ffl_onfile', '');
     553                WC()->session->set('ffl_premise_street', '');
     554                WC()->session->set('ffl_premise_city', '');
     555                WC()->session->set('ffl_premise_state', '');
     556                WC()->session->set('ffl_premise_zip', '');
     557            }
    366558            WC()->session->set('ffl_uploaded_documents', array());
    367559        }
    … …  
    398590                : array();
    399591            $is_mixed_cart = !empty($ffl_data['is_mixed_cart']);
     592        }
     593        if (WC()->session && WC()->session->get('ffl_block_shipping_selected')) {
     594            // Match save_ffl_data_to_order(): Store API requests do not carry the
     595            // checkout page's compliance query string, and draft/browser flags can be stale.
     596            $is_mixed_cart = $this->shipping_cart_type() === 'mixed';
    400597        }
    401598
  • g-ffl-checkout/trunk/blocks/js/ffl-block-checkout.js

    r3664395 r3803428  
    7878        }
    7979
    80         if (!settings.apiKey) {
     80        if (!settings.apiConfigured) {
    8181            console.log('FFL Block Checkout: No API key configured, skipping initialization');
    8282            return;
    … …  
    8484
    8585        console.log('FFL Block Checkout: Initializing with settings', {
    86             apiKey: settings.apiKey ? '***' : 'missing',
     86            apiConfigured: settings.apiConfigured,
    8787            requiresFflSelector: settings.requiresFflSelector,
    8888            hasFirearms: settings.hasFirearms,
    … …  
    106106    function setupGlobalVariables() {
    107107        window.g_ffl_plugin_directory = settings.pluginDirectory || '';
    108         window.aKey = settings.apiKey;
    109108        window.wMes = settings.checkoutMessage || '';
    110109        window.wMesAmmo = settings.ammoCheckoutMessage || '';
    … …  
    558557            if (typeof initFFLJs === 'function') {
    559558                console.log('FFL Block Checkout: Calling initFFLJs()');
    560                 initFFLJs(settings.apiKey, 'woocommerce_checkout_order_review');
     559                initFFLJs(null, 'woocommerce_checkout_order_review');
    561560            } else {
    562561                console.log('FFL Block Checkout: ERROR - initFFLJs() function not found. ffl-api-public.js may not have loaded.');
    … …  
    623622    // ============================================
    624623
     624    var fflUpdateQueue = Promise.resolve();
     625    var fflUpdateVersion = 0;
     626
    625627    function setupFFLSelectionBridge() {
     628        var lastLicense = '';
    626629        // Listen for the custom event dispatched by ffl-widget.js
    627630        document.addEventListener('ffl-dealer-selected', function (e) {
    … …  
    629632            var fflData = e.detail;
    630633            if (fflData && fflData.license_number) {
    631                 fflSelected = true;
     634                lastLicense = fflData.license_number;
    632635                pushFFLDataToStoreAPI(fflData);
    633                 enablePlaceOrder();
    634636                setTimeout(syncAllDocumentUploadSections, 0);
    635637                setTimeout(syncAllDocumentUploadSections, 300);
    … …  
    640642        document.addEventListener('ffl-dealer-cleared', function () {
    641643            console.log('FFL Block Checkout: ffl-dealer-cleared event received');
     644            lastLicense = '';
    642645            fflSelected = false;
    643646            disablePlaceOrder();
    … …  
    647650
    648651        // Backup: poll localStorage for changes (in case event is missed)
    649         var lastLicense = '';
    650652        var pollInterval = setInterval(function () {
    651653            var stored = localStorage.getItem('selectedFFL') || '';
    … …  
    656658                    if (data && data.license_number) {
    657659                        console.log('FFL Block Checkout: Detected FFL selection via localStorage poll');
    658                         fflSelected = true;
    659660                        pushFFLDataToStoreAPI(data);
    660                         enablePlaceOrder();
    661661                    }
    662662                } catch (ex) {
    … …  
    668668                fflSelected = false;
    669669                disablePlaceOrder();
     670                clearFFLDataFromStoreAPI();
    670671            }
    671672        }, 1000);
    … …  
    696697            is_ffl_order: true,
    697698            is_mixed_cart: settings.isMixedCart || false,
     699            compliance_mode: getActiveComplianceTypeNow(),
    698700        };
    699701
    700         // Use WooCommerce Blocks extensionCartUpdate
    701         try {
    702             if (typeof wc !== 'undefined' && wc.blocksCheckout && typeof wc.blocksCheckout.extensionCartUpdate === 'function') {
    703                 wc.blocksCheckout.extensionCartUpdate({
    704                     namespace: 'g-ffl-checkout',
    705                     data: extensionData,
    706                 });
    707                 console.log('FFL Block Checkout: Pushed FFL data to Store API via extensionCartUpdate');
    708             } else {
    709                 console.log('FFL Block Checkout: extensionCartUpdate not available (wc.blocksCheckout:', typeof wc !== 'undefined' ? typeof wc.blocksCheckout : 'wc undefined', '), using AJAX fallback');
    710                 pushFFLDataViaAjax(extensionData);
    711             }
    712         } catch (err) {
    713             console.log('FFL Block Checkout: Error pushing to Store API, using AJAX fallback', err);
    714             pushFFLDataViaAjax(extensionData);
    715         }
    716 
    717         // For non-mixed carts, keep customer shipping address aligned to billing.
    718         // Do not write FFL premise address into customer shipping fields, otherwise
    719         // WooCommerce can persist dealer address as the customer's default.
    720         if (!settings.isMixedCart) {
    721             syncShippingAddressToBilling();
    722         }
    723     }
    724 
    725     /**
    726      * Fallback: push FFL data via AJAX to store in WC session.
    727      */
    728     function pushFFLDataViaAjax(extensionData) {
    729         var ajaxUrl = (window.fflcheckout_ajax && window.fflcheckout_ajax.ajaxurl) ||
    730                       (window.ffl_widget_data && window.ffl_widget_data.ajaxurl) || '';
    731         if (!ajaxUrl) return;
    732 
    733         var nonce = (window.fflcheckout_ajax && window.fflcheckout_ajax.checkout_nonce) ||
    734                     (window.ffl_widget_data && window.ffl_widget_data.checkout_nonce) || '';
    735 
    736         var formData = new FormData();
    737         formData.append('action', 'ffl_block_store_session');
    738         formData.append('nonce', nonce);
    739         for (var key in extensionData) {
    740             if (extensionData.hasOwnProperty(key)) {
    741                 formData.append(key, extensionData[key]);
    742             }
    743         }
    744 
    745         fetch(ajaxUrl, {
    746             method: 'POST',
    747             body: formData,
    748             credentials: 'same-origin',
    749         }).catch(function (err) {
    750             console.log('FFL Block Checkout: AJAX fallback failed', err);
    751         });
    752     }
    753 
    754     /**
    755      * Keep shipping address in sync with billing address.
    756      * This avoids persisting selected FFL dealer addresses into customer profile defaults.
    757      */
    758     function syncShippingAddressToBilling() {
    759         try {
    760             if (typeof wp !== 'undefined' && wp.data && typeof wp.data.dispatch === 'function' && typeof wp.data.select === 'function') {
    761                 var selector = wp.data.select('wc/store/cart');
    762                 var customerData = selector && typeof selector.getCustomerData === 'function' ? selector.getCustomerData() : null;
    763                 var billingAddress = customerData && customerData.billingAddress ? customerData.billingAddress : null;
    764 
    765                 if (!billingAddress) {
    766                     return;
    767                 }
    768 
    769                 var dispatch = wp.data.dispatch('wc/store/cart');
    770                 if (dispatch && typeof dispatch.setShippingAddress === 'function') {
    771                     dispatch.setShippingAddress({
    772                         first_name: billingAddress.first_name || '',
    773                         last_name: billingAddress.last_name || '',
    774                         company: billingAddress.company || '',
    775                         address_1: billingAddress.address_1 || '',
    776                         address_2: billingAddress.address_2 || '',
    777                         city: billingAddress.city || '',
    778                         state: billingAddress.state || '',
    779                         postcode: billingAddress.postcode || '',
    780                         country: billingAddress.country || 'US',
    781                     });
    782                     console.log('FFL Block Checkout: Synced shipping address to billing (FFL data stored separately)');
    783                 }
    784             }
    785         } catch (e) {
    786             console.log('FFL Block Checkout: Could not sync shipping address to billing via wp.data', e);
    787         }
     702        queueFFLUpdate(extensionData, fflData);
     703    }
     704
     705    // Dealer shipping must never become billing through Blocks' "same address" option.
     706    function ensureSeparateBillingAddress(confirmedDealerShipping) {
     707        if ((!confirmedDealerShipping && settings.isMixedCart) || !isSelectorRequiredNow()) return;
     708        var store = wp.data.select('wc/store/checkout');
     709        var actions = wp.data.dispatch('wc/store/checkout');
     710        if (!store || !actions || typeof actions.__internalSetUseShippingAsBilling !== 'function') {
     711            throw new Error('Unable to show a separate billing address. Please reload checkout.');
     712        }
     713        if (store.getUseShippingAsBilling()) {
     714            actions.__internalSetUseShippingAsBilling(false);
     715        }
     716    }
     717
     718    function setFFLSyncValidation(message, hidden) {
     719        if (typeof wp === 'undefined' || !wp.data) return;
     720        var validation = wp.data.dispatch('wc/store/validation');
     721        if (!validation) return;
     722        if (message && typeof validation.setValidationErrors === 'function') {
     723            validation.setValidationErrors({ 'ffl-dealer-sync': { message: message, hidden: !!hidden } });
     724        } else if (!message && typeof validation.clearValidationError === 'function') {
     725            validation.clearValidationError('ffl-dealer-sync');
     726        }
     727    }
     728
     729    function queueFFLUpdate(extensionData, dealer) {
     730        var version = ++fflUpdateVersion;
     731        disablePlaceOrder();
     732        setFFLSyncValidation('Please wait while the shipping destination is updated.', true);
     733
     734        // Serialize selection/clear requests so a slower old selection cannot win.
     735        fflUpdateQueue = fflUpdateQueue.then(function () {
     736            if (typeof wc === 'undefined' || !wc.blocksCheckout || typeof wc.blocksCheckout.extensionCartUpdate !== 'function') {
     737                throw new Error('Unable to update shipping. Please reload checkout and select your dealer again.');
     738            }
     739            if (dealer && !settings.isMixedCart && isSelectorRequiredNow()) {
     740                ensureSeparateBillingAddress();
     741            }
     742            // Keep dirty billing edits intact. Update only local shipping after success.
     743            return wc.blocksCheckout.extensionCartUpdate({ namespace: 'g-ffl-checkout', data: extensionData });
     744        }).then(function () {
     745            if (version !== fflUpdateVersion) return;
     746            var destination = null;
     747            var cartStore = wp.data.select('wc/store/cart');
     748            var cartData = cartStore.getCartData();
     749            var confirmed = cartData.extensions && cartData.extensions['g-ffl-checkout'];
     750            if (!confirmed || typeof confirmed.dealer_shipping !== 'boolean') {
     751                throw new Error('Unable to confirm the shipping destination. Please reload checkout.');
     752            }
     753            if (dealer && confirmed.dealer_shipping && isSelectorRequiredNow()) {
     754                // Recheck after the server classifies the current cart, including compliance items.
     755                ensureSeparateBillingAddress(true);
     756                destination = confirmed.shipping_destination;
     757            } else if (confirmed.restored_shipping || (!dealer && !settings.isMixedCart)) {
     758                // Use the server snapshot, which also survives a checkout page reload.
     759                destination = confirmed.shipping_destination;
     760            }
     761            if (destination) {
     762                var current = cartStore.getCustomerData().shippingAddress || {};
     763                wp.data.dispatch('wc/store/cart').setShippingAddress(Object.assign({}, current, destination));
     764            }
     765            setFFLSyncValidation('');
     766            if (dealer) enablePlaceOrder();
     767            console.log('FFL Block Checkout: Store API confirmed shipping destination update');
     768        }).catch(function (error) {
     769            if (version !== fflUpdateVersion) return;
     770            disablePlaceOrder();
     771            var message = error && error.message ? error.message : 'Unable to update shipping. Please select your dealer again.';
     772            setFFLSyncValidation(message, false);
     773            var notice = document.getElementById('ffl-block-checkout-notice');
     774            if (notice) notice.textContent = message;
     775            console.error('FFL Block Checkout: Shipping destination update failed', error);
     776        });
     777        return fflUpdateQueue;
    788778    }
    789779
    … …  
    894884     */
    895885    function clearFFLDataFromStoreAPI() {
    896         try {
    897             if (typeof wc !== 'undefined' && wc.blocksCheckout && typeof wc.blocksCheckout.extensionCartUpdate === 'function') {
    898                 wc.blocksCheckout.extensionCartUpdate({
    899                     namespace: 'g-ffl-checkout',
    900                     data: { clear_ffl: true },
    901                 });
    902                 console.log('FFL Block Checkout: Cleared FFL data from Store API');
    903             }
    904         } catch (err) {
    905             console.log('FFL Block Checkout: Error clearing FFL data from Store API', err);
    906         }
     886        queueFFLUpdate({ clear_ffl: true }, null);
    907887    }
    908888
    … …  
    15851565            css += shippingBlock + ' .wc-block-components-address-form__company { display: none !important; }\n';
    15861566        } else {
     1567            if (!settings.isMixedCart) {
     1568                try {
     1569                    ensureSeparateBillingAddress();
     1570                    css += shippingBlock + ' .wc-block-checkout__use-address-for-billing { display: none !important; }\n';
     1571                } catch (error) { console.error(error); }
     1572            }
    15871573            // FFL-only (or mixed without support): hide all except first/last name
    15881574            var hideFields = ['company', 'address_1', 'address_2', 'city', 'state', 'postcode', 'country', 'phone'];
  • g-ffl-checkout/trunk/g-ffl-api.php

    r3767076 r3803428  
    1717 * Plugin URI:        garidium.com/g-ffl-api
    1818 * Description:       g-FFL Checkout
    19  * Version:           2.2.7
     19 * Version:           2.2.8
    2020 * WC requires at least: 3.0.0
    2121 * WC tested up to:   8.7.0
    … …  
    4848 * Rename this for your plugin and update it as you release new versions.
    4949 */
    50 define('G_FFL_API_VERSION', '2.2.7');
     50define('G_FFL_API_VERSION', '2.2.8');
    5151
    5252/**
  • g-ffl-checkout/trunk/public/class-ffl-api-public.php

    r3767076 r3803428  
    717717    function ffl_init_map()
    718718    {
    719         $aKey = get_option('ffl_api_key_option');
     719        if (!get_option('ffl_api_key_option')) {
     720            return;
     721        }
    720722        $wMes = get_option('ffl_checkout_message') != '' ? get_option('ffl_checkout_message') : '<b>Federal law dictates that your online firearms purchase must be delivered to a federally licensed firearms dealer (FFL) before you can take possession.</b> This process is called a Transfer. Enter your zip code, radius, and FFL name (optional), then click the Find button to get a list of FFL dealers in your area. Select the FFL dealer you want the firearm shipped to. <b><u>Before Checking Out, Contact your selected FFL dealer to confirm they are currently accepting transfers</u></b>. You can also confirm transfer costs.';
    721723        $wMesAmmo = get_option('ffl_ammo_checkout_message') != '' ? get_option('ffl_ammo_checkout_message') : 'Ammo Compliance Message';
    … …  
    780782                <script type="text/javascript">
    781783                    let g_ffl_plugin_directory = "' . esc_attr(plugin_dir_url(__FILE__)) . '";   
    782                     let aKey = "' . esc_attr($aKey) . '";
    783784                    let wMes = `' . wp_kses_post($wMes) . '`;
    784785                    let wMesAmmo = `' . wp_kses_post($wMesAmmo) . '`;
    … …  
    808809                    document.addEventListener("DOMContentLoaded", function() {
    809810                        if (typeof initFFLJs === "function") {
    810                             initFFLJs(aKey, hok);
     811                            initFFLJs(null, hok);
    811812                        } else {
    812813                            console.error("FFL: initFFLJs is not available — ffl-api-public.js did not load on this page.");
    … …  
    22872288        // Get required data
    22882289        $license_number = sanitize_text_field($_POST['license_number'] ?? '');
    2289         $api_key = sanitize_text_field($_POST['api_key'] ?? '');
     2290        // Credentials belong to this store; never accept a browser-supplied key.
     2291        $api_key = get_option('ffl_api_key_option', '');
    22902292        $file = $_FILES['document'];
    22912293       
    … …  
    22952297       
    22962298        if (empty($api_key)) {
    2297             wp_send_json_error(array('message' => 'API key is required'));
     2299            wp_send_json_error(array('message' => 'API key is not configured'));
    22982300        }
    22992301       
  • g-ffl-checkout/trunk/public/js/ffl-api-public.js

    r3745189 r3803428  
    315315
    316316
    317 function initFFLJs(fKey, hook) {
    318         console.log('Initializing FFL JS with:', { fKey, hook });
     317// Keep the legacy first argument for integrations; credentials stay on the server.
     318function initFFLJs(unusedApiKey, hook) {
     319        console.log('Initializing FFL JS with:', { hook });
    319320
    320321        // Prevent duplicate init caused by repeated script enqueue or checkout refresh cycles.
    … …  
    527528        FFL.init({
    528529                container : 'ffl_container',
    529                 apiKey: fKey,
    530530                cBack : getSelected
    531531        });
  • g-ffl-checkout/trunk/public/js/ffl-widget.js

    r3767076 r3803428  
    999999    generate: function(config) {
    10001000        var container = config.container || '';
    1001         var apiKey = config.apiKey || '';
    10021001        var geoKey = config.geoKey || '';
    10031002        var callback = config.cBack || '';
    1004 
    1005         if (apiKey === '') {
    1006             alert('Please define your g-FFL API key!');
    1007             return false;
    1008         }
    10091003
    10101004        var containerElement = document.getElementById(container);
    … …  
    10251019
    10261020        // Store configuration globally for use by other scripts
    1027         window.fflApiKey = apiKey;
    10281021        window.fflGeoKey = geoKey;
    10291022        window.fflCallback = callback;
    … …  
    12371230                }
    12381231               
    1239                 // Check for required variables
    1240                 if (typeof aKey === 'undefined' || !aKey) {
    1241                     alert('API key not available. Please reload the page and try again.');
    1242                     return;
    1243                 }
    1244                
    12451232                if (typeof ffl_widget_data === 'undefined' || !ffl_widget_data.ajaxurl || !ffl_widget_data.checkout_nonce) {
    12461233                    alert('AJAX configuration not available. Please reload the page and try again.');
    … …  
    12491236               
    12501237                console.log('C&R Upload Debug:', {
    1251                     'aKey': aKey ? 'Available' : 'Missing',
    12521238                    'ajaxurl': ffl_widget_data.ajaxurl,
    12531239                    'nonce': ffl_widget_data.checkout_nonce ? 'Available' : 'Missing'
    … …  
    12651251                formData.append('document', file);
    12661252                formData.append('license_number', licenseValue);
    1267                 formData.append('api_key', aKey);
    12681253                formData.append('action', 'ffl_upload_candr_document');
    12691254                formData.append('security', ffl_widget_data.checkout_nonce);
Note: See TracChangeset for help on using the changeset viewer.