Plugin Directory

Changeset 3848522


Ignore:
Timestamp:
12/06/2026 09:31:34 PM (less than one hour ago)
Author:
printseek
Message:

Release 1.0.3: order sync on Processing, API-key save fix, real 128/256 icons, 1544x500 banner, remove dead webhook handler

Location:
printseek
Files:
4 added
4 deleted
19 edited
1 copied

Legend:

Unmodified
Added
Removed
  • printseek/tags/1.0.3/assets/js/admin.js

    r3430355 r3848522  
    1515        initProductPush();
    1616        initOrderSync();
    17         initConnectionTest();
    1817        initSettingsPage();
    1918        initAlertDismiss();
    … …  
    7271     */
    7372    function initOrderSync() {
    74         // Manual sync orders button
    75         $('.printseek-sync-orders').on('click', function(e) {
    76             e.preventDefault();
    77            
    78             var button = $(this);
    79             var originalText = button.text();
    80            
    81             button.prop('disabled', true).text(printseek_vars.i18n.syncing || 'Syncing...');
    82            
    83             $.ajax({
    84                 url: printseek_vars.ajax_url,
    85                 type: 'POST',
    86                 data: {
    87                     action: 'printseek_sync_orders',
    88                     nonce: printseek_vars.nonce
    89                 },
    90                 success: function(response) {
    91                     button.prop('disabled', false).text(originalText);
    92                    
    93                     if (response.success) {
    94                         showNotice(response.data.message, 'success');
    95                        
    96                         // Reload page after 2 seconds
    97                         setTimeout(function() {
    98                             location.reload();
    99                         }, 2000);
    100                     } else {
    101                         showNotice(response.data.message, 'error');
    102                     }
    103                 },
    104                 error: function() {
    105                     button.prop('disabled', false).text(originalText);
    106                     showNotice(printseek_vars.i18n.request_failed || 'Request failed. Please try again.', 'error');
    107                 }
    108             });
    109         });
    110        
    11173        // Single order sync button
    11274        $('#printseek-sync-order-btn').on('click', function(e) {
    … …  
    156118   
    157119    /**
    158      * Connection Test
    159      */
    160     function initConnectionTest() {
    161         $('.printseek-test-connection').on('click', function(e) {
    162             e.preventDefault();
    163            
    164             var button = $(this);
    165             var originalText = button.text();
    166             var statusDiv = $('.connection-status');
    167            
    168             button.prop('disabled', true).text(printseek_vars.i18n.testing || 'Testing...');
    169             statusDiv.html('<span class="printseek-spinner"></span> ' + (printseek_vars.i18n.testing_connection || 'Testing connection...'));
    170            
    171             $.ajax({
    172                 url: printseek_vars.ajax_url,
    173                 type: 'POST',
    174                 data: {
    175                     action: 'printseek_test_connection',
    176                     nonce: printseek_vars.nonce,
    177                     api_key: $('#printseek_api_key').val()
    178                 },
    179                 success: function(response) {
    180                     button.prop('disabled', false).text(originalText);
    181                    
    182                     if (response.success) {
    183                         statusDiv.html('<div class="printseek-success">✓ ' + response.data.message + '</div>');
    184                     } else {
    185                         statusDiv.html('<div class="printseek-error">✗ ' + response.data.message + '</div>');
    186                     }
    187                 },
    188                 error: function() {
    189                     button.prop('disabled', false).text(originalText);
    190                     statusDiv.html('<div class="printseek-error">✗ ' + (printseek_vars.i18n.connection_failed || 'Connection test failed') + '</div>');
    191                 }
    192             });
    193         });
    194     }
    195    
    196     /**
    197120     * Settings page functionality
    198121     */
    … …  
    287210   
    288211    /**
    289      * Show admin notice
    290      */
    291     function showNotice(message, type) {
    292         var noticeClass = type === 'success' ? 'notice-success' : 'notice-error';
    293         var notice = $('<div class="notice ' + noticeClass + ' is-dismissible"><p>' + message + '</p></div>');
    294        
    295         $('.wrap h1').first().after(notice);
    296        
    297         // Auto dismiss after 5 seconds
    298         setTimeout(function() {
    299             notice.fadeOut(function() {
    300                 $(this).remove();
    301             });
    302         }, 5000);
    303     }
    304    
    305     /**
    306212     * Bulk action confirmation
    307213     */
    … …  
    318224            }
    319225           
    320             var confirmMsg = printseek_vars.i18n.confirm_push || 'Push {count} product(s) to PrintSeek?';
     226            var confirmMsg = printseek_vars.i18n.confirm_push || 'Mark {count} product(s) as PrintSeek products?';
    321227            confirmMsg = confirmMsg.replace('{count}', selectedCount);
    322228           
  • printseek/tags/1.0.3/includes/admin/class-printseek-admin.php

    r3430355 r3848522  
    139139        wp_localize_script('printseek-admin', 'printseek_vars', array(
    140140            'ajax_url' => admin_url('admin-ajax.php'),
    141             'nonce' => wp_create_nonce('printseek_admin'),
    142141            'push_product_nonce' => wp_create_nonce('printseek_push_product'),
    143142            'sync_order_nonce' => wp_create_nonce('printseek_sync_single_order'),
    … …  
    149148                'saving' => __('Saving...', 'printseek'),
    150149                'sync_to_printseek' => __('Sync to PrintSeek', 'printseek'),
    151                 'testing_connection' => __('Testing connection...', 'printseek'),
    152                 'connection_failed' => __('Connection test failed', 'printseek'),
    153150                'select_product' => __('Please select at least one product.', 'printseek'),
    154                 'confirm_push' => __('Push {count} product(s) to PrintSeek?', 'printseek'),
     151                'confirm_push' => __('Mark {count} product(s) as PrintSeek products?', 'printseek'),
    155152            ),
    156153        ));
    … …  
    161158     */
    162159    public function render_dashboard() {
    163         $api = PrintSeek_API::instance();
    164         $connection = $api->check_connection();
     160        $connected = PrintSeek_Settings::instance()->verify_connection()['success'];
    165161       
    166162        // Get stats
    … …  
    176172            <div class="printseek-dashboard">
    177173                <!-- Connection Status Card -->
    178                 <div class="printseek-card printseek-connection-card <?php echo $connection['success'] ? 'connected' : 'disconnected'; ?>">
     174                <div class="printseek-card printseek-connection-card <?php echo $connected ? 'connected' : 'disconnected'; ?>">
    179175                    <div class="card-icon">
    180                     <?php if ($connection['success']): ?>
     176                    <?php if ($connected): ?>
    181177                            <span class="dashicons dashicons-yes-alt"></span>
    182178                    <?php else: ?>
    … …  
    186182                    <div class="card-content">
    187183                        <h3><?php esc_html_e('Connection Status', 'printseek'); ?></h3>
    188                         <?php if ($connection['success']): ?>
     184                        <?php if ($connected): ?>
    189185                            <p class="status-text connected"><?php esc_html_e('Connected to PrintSeek API', 'printseek'); ?></p>
    190186                            <?php if ($user_id): ?>
    … …  
    264260                            <span><?php esc_html_e('Settings', 'printseek'); ?></span>
    265261                        </a>
    266                         <a href="<?php echo esc_url('https://printsik.com'); ?>" target="_blank" class="action-btn">
     262                        <a href="<?php echo esc_url(PRINTSEEK_SITE_URL); ?>" target="_blank" class="action-btn">
    267263                            <span class="dashicons dashicons-external"></span>
    268264                            <span><?php esc_html_e('PrintSeek App', 'printseek'); ?></span>
    … …  
    303299                    <h2><span class="dashicons dashicons-sos"></span> <?php esc_html_e('Help & Support', 'printseek'); ?></h2>
    304300                    <div class="support-links">
    305                         <a href="<?php echo esc_url('https://printsik.com'); ?>" target="_blank" class="support-link">
     301                        <a href="<?php echo esc_url(PRINTSEEK_SITE_URL); ?>" target="_blank" class="support-link">
    306302                            <span class="dashicons dashicons-admin-site"></span>
    307303                            <span><?php esc_html_e('Visit PrintSeek', 'printseek'); ?></span>
    308304                        </a>
    309                         <a href="<?php echo esc_url('https://printsik.com/contact-us'); ?>" target="_blank" class="support-link">
     305                        <a href="<?php echo esc_url('mailto:' . PRINTSEEK_SUPPORT_EMAIL); ?>" class="support-link">
    310306                            <span class="dashicons dashicons-email"></span>
    311307                            <span><?php esc_html_e('Contact Support', 'printseek'); ?></span>
    … …  
    497493                                <?php
    498494                                if (!$order) continue;
    499                                 $printseek_status = $order->get_meta('_printseek_status') ?: 'synced';
    500495                                $printseek_order_id = $order->get_meta('_printseek_order_id');
    501496                                ?>
    … …  
    504499                                        <strong>#<?php echo esc_html($order->get_order_number()); ?></strong>
    505500                                        <?php if ($printseek_order_id): ?>
    506                                             <br><small class="printseek-id"><?php esc_html_e('PS:', 'printseek'); ?> <?php echo esc_html(substr($printseek_order_id, 0, 15)); ?>...</small>
     501                                            <br><small class="printseek-id"><?php echo esc_html($printseek_order_id); ?></small>
    507502                                        <?php endif; ?>
    508503                                    </td>
    … …  
    521516                                    </td>
    522517                                    <td class="order-status">
    523                                         <span class="status-badge <?php echo esc_attr($printseek_status); ?>">
    524                                             <?php
    525                                             $status_labels = array(
    526                                                 'synced' => __('Synced', 'printseek'),
    527                                                 'processing' => __('Processing', 'printseek'),
    528                                                 'shipped' => __('Shipped', 'printseek'),
    529                                                 'delivered' => __('Delivered', 'printseek'),
    530                                             );
    531                                             echo esc_html($status_labels[$printseek_status] ?? ucfirst($printseek_status));
    532                                             ?>
    533                                         </span>
     518                                        <span class="status-badge synced"><?php esc_html_e('Synced', 'printseek'); ?></span>
    534519                                    </td>
    535520                                    <td class="order-actions">
  • printseek/tags/1.0.3/includes/admin/class-printseek-settings.php

    r3430355 r3848522  
    22/**
    33 * PrintSeek Settings
     4 *
     5 * Both settings forms post to `admin-post.php?action=printseek_save_settings`; each saves only its own fields.
    46 */
    57
    … …  
    911
    1012class PrintSeek_Settings {
    11    
     13
    1214    /**
    1315     * Single instance
    1416     */
    1517    protected static $_instance = null;
    16    
     18
    1719    /**
    1820     * Instance
    … …  
    2426        return self::$_instance;
    2527    }
    26    
     28
    2729    /**
    2830     * Constructor
    2931     */
    3032    public function __construct() {
    31         // Register settings
    32         add_action('admin_init', array($this, 'register_settings'));
    33        
    34         // Handle settings form submission
    3533        add_action('admin_post_printseek_save_settings', array($this, 'save_settings'));
    3634    }
    37    
    38     /**
    39      * Register settings
    40      */
    41     public function register_settings() {
    42         register_setting('printseek_settings', 'printseek_api_key', array(
    43             'type' => 'string',
    44             'sanitize_callback' => 'sanitize_text_field',
    45             'default' => '',
    46         ));
    47         register_setting('printseek_settings', 'printseek_user_id', array(
    48             'type' => 'string',
    49             'sanitize_callback' => 'sanitize_text_field',
    50             'default' => '',
    51         ));
    52         register_setting('printseek_settings', 'printseek_auto_sync_orders', array(
    53             'type' => 'string',
    54             'sanitize_callback' => 'sanitize_text_field',
    55             'default' => 'yes',
    56         ));
    57         register_setting('printseek_settings', 'printseek_auto_sync_products', array(
    58             'type' => 'string',
    59             'sanitize_callback' => 'sanitize_text_field',
    60             'default' => 'no',
    61         ));
    62         register_setting('printseek_settings', 'printseek_webhook_secret', array(
    63             'type' => 'string',
    64             'sanitize_callback' => 'sanitize_text_field',
    65             'default' => '',
    66         ));
    67         register_setting('printseek_settings', 'printseek_debug_mode', array(
    68             'type' => 'string',
    69             'sanitize_callback' => 'sanitize_text_field',
    70             'default' => 'no',
    71         ));
    72     }
    73    
     35
     36    /**
     37     * Verify the saved API key with PrintSeek; on success keeps the account's user id.
     38     *
     39     * @return array { success: bool, error?: string }
     40     */
     41    public function verify_connection() {
     42        $api = PrintSeek_API::instance();
     43        $api->reload_credentials();
     44        $response = $api->verify_plugin();
     45
     46        if (empty($response['success'])) {
     47            return array(
     48                'success' => false,
     49                'error'   => isset($response['error']) ? $response['error'] : __('Failed to connect to PrintSeek API', 'printseek'),
     50            );
     51        }
     52
     53        update_option('printseek_user_id', sanitize_text_field($response['data']['userId']));
     54        return array('success' => true);
     55    }
     56
    7457    /**
    7558     * Render settings page
    7659     */
    7760    public function render_settings_page() {
    78         // Check if connection test was triggered
    79         $connection_test = null;
    80         if (isset($_POST['test_connection']) && check_admin_referer('printseek_test_connection')) {
    81             $api = PrintSeek_API::instance();
    82             $connection_test = $api->check_connection();
    83            
    84             // Auto-extract User ID on successful connection
    85             if ($connection_test['success']) {
    86                 $api_key = get_option('printseek_api_key', '');
    87                 $current_user_id = get_option('printseek_user_id', '');
    88                
    89                 if (!empty($api_key) && empty($current_user_id)) {
    90                     $verify_response = $api->verify_credentials($api_key);
    91                    
    92                     if (isset($verify_response['success']) && $verify_response['success']) {
    93                         $user_id = '';
    94                         if (isset($verify_response['data']['user']['_id'])) {
    95                             $user_id = $verify_response['data']['user']['_id'];
    96                         } elseif (isset($verify_response['data']['auth']['user']['_id'])) {
    97                             $user_id = $verify_response['data']['auth']['user']['_id'];
    98                         }
    99                        
    100                         if (!empty($user_id)) {
    101                             update_option('printseek_user_id', $user_id);
    102                             $connection_test['message'] = __('Connection successful! User ID auto-detected.', 'printseek');
    103                         }
    104                     }
    105                 }
    106             }
    107         }
    108        
     61        // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only notice after the redirect of save_settings()
     62        $notice = isset($_GET['printseek_notice']) ? sanitize_key(wp_unslash($_GET['printseek_notice'])) : '';
     63        // phpcs:enable WordPress.Security.NonceVerification.Recommended
     64        $connection_error = get_transient('printseek_connection_error');
     65        delete_transient('printseek_connection_error');
     66
    10967        $api_key = get_option('printseek_api_key', '');
    11068        $user_id = get_option('printseek_user_id', '');
    … …  
    11573            <h1 class="printseek-page-title"><?php esc_html_e('PrintSeek Settings', 'printseek'); ?></h1>
    11674           
    117             <?php if (isset($_GET['settings-updated'])): // phpcs:ignore WordPress.Security.NonceVerification.Recommended ?>
     75            <?php if ($notice === 'saved'): ?>
    11876                <div class="printseek-alert printseek-alert-success">
    11977                    <span class="dashicons dashicons-yes-alt"></span>
    12078                    <div>
    12179                        <strong><?php esc_html_e('Settings Saved!', 'printseek'); ?></strong>
    122                         <p><?php esc_html_e('Your settings have been saved successfully. Test the API connection below to verify everything is working.', 'printseek'); ?></p>
     80                    </div>
     81                </div>
     82            <?php elseif ($notice === 'connected'): ?>
     83                <div class="printseek-alert printseek-alert-success">
     84                    <span class="dashicons dashicons-yes-alt"></span>
     85                    <div>
     86                        <strong><?php esc_html_e('Connection Successful!', 'printseek'); ?></strong>
     87                        <p><?php esc_html_e('Your store is connected to PrintSeek API.', 'printseek'); ?></p>
     88                    </div>
     89                </div>
     90            <?php elseif ($notice === 'failed'): ?>
     91                <div class="printseek-alert printseek-alert-error">
     92                    <span class="dashicons dashicons-warning"></span>
     93                    <div>
     94                        <strong><?php esc_html_e('Connection Failed', 'printseek'); ?></strong>
     95                        <p><?php echo esc_html($connection_error); ?></p>
    12396                    </div>
    12497                </div>
    12598            <?php endif; ?>
    126            
    127             <?php if ($connection_test): ?>
    128                 <?php if ($connection_test['success']): ?>
    129                     <div class="printseek-alert printseek-alert-success">
    130                         <span class="dashicons dashicons-yes-alt"></span>
    131                         <div>
    132                             <strong><?php esc_html_e('Connection Successful!', 'printseek'); ?></strong>
    133                             <p><?php echo isset($connection_test['message']) ? esc_html($connection_test['message']) : esc_html__('Your store is connected to PrintSeek API.', 'printseek'); ?></p>
    134                         </div>
    135                     </div>
    136                 <?php else: ?>
    137                     <div class="printseek-alert printseek-alert-error">
    138                         <span class="dashicons dashicons-warning"></span>
    139                         <div>
    140                             <strong><?php esc_html_e('Connection Failed', 'printseek'); ?></strong>
    141                             <p><?php echo esc_html($connection_test['error']); ?></p>
    142                         </div>
    143                     </div>
    144                 <?php endif; ?>
    145             <?php endif; ?>
    146            
     99
    147100            <div class="printseek-settings-grid">
    148101                <!-- API Credentials Card -->
    … …  
    155108                        <p class="card-description"><?php esc_html_e('Enter your PrintSeek API credentials to connect your store.', 'printseek'); ?></p>
    156109                       
    157                         <form method="post" action="options.php" class="printseek-form">
    158                             <?php settings_fields('printseek_settings'); ?>
    159                            
     110                        <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" class="printseek-form">
     111                            <?php $this->form_fields('credentials'); ?>
     112
    160113                            <div class="form-group">
    161114                                <label for="printseek_api_key">
    … …  
    173126                                <p class="help-text"><?php esc_html_e('Find this in PrintSeek Dashboard → Connected Stores → WooCommerce', 'printseek'); ?></p>
    174127                            </div>
    175                            
    176                             <div class="form-group">
    177                                 <label for="printseek_user_id"><?php esc_html_e('User ID', 'printseek'); ?></label>
    178                                 <input
    179                                     type="text"
    180                                     id="printseek_user_id"
    181                                     name="printseek_user_id"
    182                                     value="<?php echo esc_attr($user_id); ?>"
    183                                     class="form-input"
    184                                     placeholder="<?php esc_attr_e('Auto-detected from API key', 'printseek'); ?>"
    185                                 />
    186                                 <p class="help-text"><?php esc_html_e('Optional - Will be auto-detected when you test the connection.', 'printseek'); ?></p>
    187                             </div>
    188                            
    189                             <div class="form-group">
    190                                 <label for="printseek_webhook_secret"><?php esc_html_e('Webhook Secret', 'printseek'); ?></label>
    191                                 <input
    192                                     type="text"
    193                                     id="printseek_webhook_secret"
    194                                     name="printseek_webhook_secret"
    195                                     value="<?php echo esc_attr(get_option('printseek_webhook_secret')); ?>"
    196                                     class="form-input"
    197                                     placeholder="<?php esc_attr_e('Enter webhook secret', 'printseek'); ?>"
    198                                 />
    199                                 <p class="help-text"><?php esc_html_e('For verifying webhook requests from PrintSeek.', 'printseek'); ?></p>
    200                             </div>
    201                            
    202                             <div class="webhook-url-box">
    203                                 <label><?php esc_html_e('Your Webhook URL', 'printseek'); ?></label>
    204                                 <div class="url-display">
    205                                     <code id="webhook-url"><?php echo esc_url(rest_url('printseek/v1/webhook')); ?></code>
    206                                     <button type="button" class="copy-btn" onclick="copyWebhookUrl()">
    207                                         <span class="dashicons dashicons-admin-page"></span>
    208                                     </button>
    209                                 </div>
    210                                 <p class="help-text"><?php esc_html_e('Add this URL in your PrintSeek dashboard to receive order updates.', 'printseek'); ?></p>
    211                             </div>
    212                            
     128
    213129                            <div class="form-actions">
    214130                                <button type="submit" class="btn btn-primary">
    … …  
    253169                        </div>
    254170                       
    255                         <form method="post" class="test-connection-form">
    256                             <?php wp_nonce_field('printseek_test_connection'); ?>
     171                        <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" class="test-connection-form">
     172                            <?php $this->form_fields('test'); ?>
    257173                            <button type="submit" name="test_connection" class="btn btn-secondary btn-full" <?php echo !$is_configured ? 'disabled' : ''; ?>>
    258174                                <span class="dashicons dashicons-update"></span>
    … …  
    263179                        <div class="info-box">
    264180                            <span class="dashicons dashicons-info"></span>
    265                             <p><?php esc_html_e('After saving your API key, click "Test API Connection" to verify everything is working correctly.', 'printseek'); ?></p>
     181                            <p><?php esc_html_e('Saving the API key verifies it with PrintSeek. Use "Test API Connection" to check it again.', 'printseek'); ?></p>
    266182                        </div>
    267183                    </div>
    … …  
    275191                    </div>
    276192                    <div class="card-body">
    277                         <form method="post" action="options.php" class="printseek-form">
    278                             <?php settings_fields('printseek_settings'); ?>
    279                             <!-- Hidden fields to preserve API credentials -->
    280                             <input type="hidden" name="printseek_api_key" value="<?php echo esc_attr($api_key); ?>" />
    281                             <input type="hidden" name="printseek_user_id" value="<?php echo esc_attr($user_id); ?>" />
    282                             <input type="hidden" name="printseek_webhook_secret" value="<?php echo esc_attr(get_option('printseek_webhook_secret')); ?>" />
     193                        <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" class="printseek-form">
     194                            <?php $this->form_fields('sync'); ?>
    283195                           
    284196                            <div class="toggle-group">
    … …  
    334246                    <div class="card-body">
    335247                        <div class="help-links">
    336                             <a href="<?php echo esc_url('https://printsik.com'); ?>" target="_blank" class="help-link">
     248                            <a href="<?php echo esc_url(PRINTSEEK_SITE_URL); ?>" target="_blank" class="help-link">
    337249                                <span class="dashicons dashicons-admin-home"></span>
    338250                                <span><?php esc_html_e('Visit PrintSeek', 'printseek'); ?></span>
    339251                            </a>
    340                             <a href="<?php echo esc_url('https://printsik.com/contact-us'); ?>" target="_blank" class="help-link">
     252                            <a href="<?php echo esc_url('mailto:' . PRINTSEEK_SUPPORT_EMAIL); ?>" class="help-link">
    341253                                <span class="dashicons dashicons-email"></span>
    342254                                <span><?php esc_html_e('Contact Support', 'printseek'); ?></span>
    … …  
    348260                            <ol>
    349261                                <li><?php esc_html_e('Get your API Key from PrintSeek Dashboard', 'printseek'); ?></li>
    350                                 <li><?php esc_html_e('Enter the API Key above and Save', 'printseek'); ?></li>
    351                                 <li><?php esc_html_e('Click "Test API Connection" to verify', 'printseek'); ?></li>
     262                                <li><?php esc_html_e('Enter the API Key above and Save — it is verified right away', 'printseek'); ?></li>
    352263                                <li><?php esc_html_e('Start linking products for fulfillment!', 'printseek'); ?></li>
    353264                            </ol>
    … …  
    361272   
    362273    /**
    363      * Save settings
     274     * Action, section and nonce of a settings form.
     275     *
     276     * @param string $section credentials | test | sync
     277     */
     278    private function form_fields($section) {
     279        ?>
     280        <input type="hidden" name="action" value="printseek_save_settings" />
     281        <input type="hidden" name="section" value="<?php echo esc_attr($section); ?>" />
     282        <?php
     283        wp_nonce_field('printseek_save_settings');
     284    }
     285
     286    /**
     287     * Save one settings form, then back to the settings page with a notice.
    364288     */
    365289    public function save_settings() {
    … …  
    367291            wp_die(esc_html__('Permission denied', 'printseek'));
    368292        }
    369        
    370         check_admin_referer('printseek_settings-options');
    371        
    372         // phpcs:disable WordPress.Security.ValidatedSanitizedInput.InputNotValidated -- Nonce verified above
    373         $api_key = isset($_POST['printseek_api_key']) ? sanitize_text_field(wp_unslash($_POST['printseek_api_key'])) : '';
    374         $user_id = isset($_POST['printseek_user_id']) ? sanitize_text_field(wp_unslash($_POST['printseek_user_id'])) : '';
    375         $webhook_secret = isset($_POST['printseek_webhook_secret']) ? sanitize_text_field(wp_unslash($_POST['printseek_webhook_secret'])) : '';
    376         // phpcs:enable WordPress.Security.ValidatedSanitizedInput.InputNotValidated
    377        
    378         // Auto-detect User ID from API key if not provided
    379         if (empty($user_id) && !empty($api_key)) {
    380             $api = PrintSeek_API::get_instance();
    381             $verify_response = $api->verify_credentials($api_key);
    382            
    383             if (isset($verify_response['success']) && $verify_response['success']) {
    384                 // Extract user ID from response
    385                 if (isset($verify_response['data']['user']['_id'])) {
    386                     $user_id = $verify_response['data']['user']['_id'];
    387                 } elseif (isset($verify_response['data']['auth']['user']['_id'])) {
    388                     $user_id = $verify_response['data']['auth']['user']['_id'];
     293        check_admin_referer('printseek_save_settings');
     294
     295        $section = isset($_POST['section']) ? sanitize_key(wp_unslash($_POST['section'])) : '';
     296        $notice = 'saved';
     297
     298        switch ($section) {
     299            case 'credentials':
     300                $api_key = isset($_POST['printseek_api_key']) ? sanitize_text_field(wp_unslash($_POST['printseek_api_key'])) : '';
     301                if ($api_key !== get_option('printseek_api_key')) {
     302                    update_option('printseek_api_key', $api_key);
     303                    delete_option('printseek_user_id');
    389304                }
    390             }
    391         }
    392        
    393         // Save settings
    394         update_option('printseek_api_key', $api_key);
    395         update_option('printseek_user_id', $user_id);
    396         update_option('printseek_auto_sync_orders', isset($_POST['printseek_auto_sync_orders']) ? 'yes' : 'no');
    397         update_option('printseek_webhook_secret', $webhook_secret);
    398         update_option('printseek_debug_mode', isset($_POST['printseek_debug_mode']) ? 'yes' : 'no');
    399        
    400         wp_safe_redirect(add_query_arg('settings-updated', 'true', wp_get_referer()));
     305                $notice = $api_key === '' ? 'saved' : $this->connection_notice();
     306                break;
     307            case 'test':
     308                $notice = $this->connection_notice();
     309                break;
     310            case 'sync':
     311                update_option('printseek_auto_sync_orders', isset($_POST['printseek_auto_sync_orders']) ? 'yes' : 'no');
     312                update_option('printseek_debug_mode', isset($_POST['printseek_debug_mode']) ? 'yes' : 'no');
     313                break;
     314            default:
     315                wp_die(esc_html__('Unknown settings form', 'printseek'));
     316        }
     317
     318        wp_safe_redirect(add_query_arg('printseek_notice', $notice, admin_url('admin.php?page=printseek-settings')));
    401319        exit;
    402320    }
     321
     322    /**
     323     * @return string connected | failed (the error is kept for the next page view)
     324     */
     325    private function connection_notice() {
     326        $result = $this->verify_connection();
     327        if ($result['success']) {
     328            return 'connected';
     329        }
     330        set_transient('printseek_connection_error', $result['error'], MINUTE_IN_SECONDS);
     331        return 'failed';
     332    }
    403333}
  • printseek/tags/1.0.3/includes/class-printseek-api.php

    r3430355 r3848522  
    4545   
    4646    /**
    47      * User ID from PrintSeek
    48      *
    49      * @var string
    50      * @since 1.0.0
    51      */
    52     private $user_id;
    53    
    54     /**
    5547     * Instance
    5648     *
    … …  
    7365        $this->api_url = PRINTSEEK_API_URL;
    7466        $this->api_key = get_option('printseek_api_key', '');
    75         $this->user_id = get_option('printseek_user_id', '');
    7667    }
    7768   
    … …  
    8374    public function reload_credentials() {
    8475        $this->api_key = get_option('printseek_api_key', '');
    85         $this->user_id = get_option('printseek_user_id', '');
    8676    }
    8777   
    … …  
    143133   
    144134    /**
    145      * Verify API credentials
    146      *
    147      * @since 1.0.0
    148      * @param string $api_key API key to verify
     135     * Verify the API key with PrintSeek and register this site's plugin.
     136     * Returns the store's userId and webhookSecret on success.
     137     *
     138     * @since 1.0.0
    149139     * @return array Response
    150140     */
    151     public function verify_credentials($api_key) {
    152         $temp_key = $this->api_key;
    153         $this->api_key = $api_key;
    154        
    155         $response = $this->request('api/auth/verify-token');
    156        
    157         $this->api_key = $temp_key;
    158        
    159         return $response;
    160     }
    161    
    162     /**
    163      * Verify plugin installation with PrintSeek
    164      *
    165      * @since 1.0.0
    166      * @return array Response
    167      */
    168141    public function verify_plugin() {
     142        if (empty($this->api_key)) {
     143            return array(
     144                'success' => false,
     145                'error'   => __('API key not configured', 'printseek')
     146            );
     147        }
     148
    169149        $data = array(
    170150            'siteUrl'       => get_site_url(),
    … …  
    173153            'wcVersion'     => defined('WC_VERSION') ? WC_VERSION : 'unknown',
    174154        );
    175        
     155
    176156        return $this->request('woocommerce/plugin/verify', 'POST', $data);
    177157    }
    178    
    179     /**
    180      * Get user profile
    181      *
    182      * @since 1.0.0
     158
     159    /**
     160     * Send an order to PrintSeek
     161     *
     162     * @since 1.2.0
     163     * @param array $order_data WooCommerce order in the REST shape
    183164     * @return array Response
    184165     */
    185     public function get_user_profile() {
    186         return $this->request('api/auth/me');
    187     }
    188    
    189     /**
    190      * Create order in PrintSeek
    191      *
    192      * @since 1.0.0
    193      * @param array $order_data Order data
    194      * @return array Response
    195      */
    196     public function create_order($order_data) {
    197         return $this->request('woocommerce/orders/sync', 'POST', $order_data);
    198     }
    199    
    200     /**
    201      * Sync order to PrintSeek (from WooCommerce)
    202      *
    203      * @since 1.0.0
    204      * @param array $order_data Order data
    205      * @return array Response
    206      */
    207     public function push_product($order_data) {
    208         return $this->request('woocommerce/orders/sync', 'POST', $order_data);
    209     }
    210    
    211     /**
    212      * Get orders from PrintSeek
    213      *
    214      * @since 1.0.0
    215      * @param array $params Query parameters
    216      * @return array Response
    217      */
    218     public function get_orders($params = array()) {
    219         $query_string = http_build_query($params);
    220         $endpoint = 'api/orders' . ($query_string ? '?' . $query_string : '');
    221        
    222         return $this->request($endpoint);
    223     }
    224    
    225     /**
    226      * Get single order
    227      *
    228      * @since 1.0.0
    229      * @param string $order_id Order ID
    230      * @return array Response
    231      */
    232     public function get_order($order_id) {
    233         return $this->request('api/orders/' . sanitize_text_field($order_id));
    234     }
    235    
    236     /**
    237      * Update order status
    238      *
    239      * @since 1.0.0
    240      * @param string $order_id Order ID
    241      * @param string $status New status
    242      * @return array Response
    243      */
    244     public function update_order_status($order_id, $status) {
    245         return $this->request('api/orders/' . sanitize_text_field($order_id), 'PATCH', array(
    246             'status' => sanitize_text_field($status)
     166    public function sync_order($order_data) {
     167        return $this->request('woocommerce/orders/sync', 'POST', array(
     168            'siteUrl' => get_site_url(),
     169            'order'   => $order_data,
    247170        ));
    248171    }
    249    
    250     /**
    251      * Place order for fulfillment
    252      *
    253      * @since 1.0.0
    254      * @param string $order_id Order ID
    255      * @return array Response
    256      */
    257     public function place_order($order_id) {
    258         return $this->request('api/orders/' . sanitize_text_field($order_id) . '/place', 'POST');
    259     }
    260    
    261     /**
    262      * Get product types/catalog
    263      *
    264      * @since 1.0.0
    265      * @return array Response
    266      */
    267     public function get_product_types() {
    268         return $this->request('api/product-types');
    269     }
    270    
    271     /**
    272      * Upload design file
    273      *
    274      * @since 1.0.0
    275      * @param string $file_path Path to file
    276      * @param string $design_type Design type (front, back, etc.)
    277      * @return array Response
    278      */
    279     public function upload_design($file_path, $design_type = 'front') {
    280         if (!file_exists($file_path)) {
    281             return array(
    282                 'success' => false,
    283                 'error'   => __('File not found', 'printseek')
    284             );
    285         }
    286        
    287         $url = trailingslashit($this->api_url) . 'api/uploads';
    288        
    289         $boundary = wp_generate_password(24, false);
    290        
    291         $headers = array(
    292             'Authorization' => 'Bearer ' . $this->api_key,
    293             'Content-Type'  => 'multipart/form-data; boundary=' . $boundary,
    294         );
    295        
    296         // Read file safely
    297         $file_contents = file_get_contents($file_path);
    298         if ($file_contents === false) {
    299             return array(
    300                 'success' => false,
    301                 'error'   => __('Could not read file', 'printseek')
    302             );
    303         }
    304        
    305         $filename = basename($file_path);
    306         $mime_type = wp_check_filetype($file_path)['type'] ?: 'application/octet-stream';
    307        
    308         $body = '';
    309         $body .= '--' . $boundary . "\r\n";
    310         $body .= 'Content-Disposition: form-data; name="' . $design_type . '"; filename="' . $filename . '"' . "\r\n";
    311         $body .= 'Content-Type: ' . $mime_type . "\r\n\r\n";
    312         $body .= $file_contents . "\r\n";
    313         $body .= '--' . $boundary . '--';
    314        
    315         $args = array(
    316             'headers' => $headers,
    317             'body'    => $body,
    318             'timeout' => 60,
    319         );
    320        
    321         $response = wp_remote_post($url, $args);
    322        
    323         if (is_wp_error($response)) {
    324             return array(
    325                 'success' => false,
    326                 'error'   => $response->get_error_message()
    327             );
    328         }
    329        
    330         $body = wp_remote_retrieve_body($response);
    331         return json_decode($body, true);
    332     }
    333    
    334     /**
    335      * Check connection status
    336      *
    337      * @since 1.0.0
    338      * @return array Response
    339      */
    340     public function check_connection() {
    341         if (empty($this->api_key)) {
    342             return array(
    343                 'success' => false,
    344                 'error'   => __('API key not configured', 'printseek')
    345             );
    346         }
    347        
    348         $response = $this->request('woocommerce/health');
    349        
    350         if (isset($response['success']) && $response['success']) {
    351             return array(
    352                 'success' => true,
    353                 'message' => __('Connected to PrintSeek API', 'printseek')
    354             );
    355         }
    356        
    357         // Try alternative health check
    358         $response = $this->request('api/health');
    359        
    360         if (isset($response['success']) && $response['success']) {
    361             return array(
    362                 'success' => true,
    363                 'message' => __('Connected to PrintSeek API', 'printseek')
    364             );
    365         }
    366        
    367         return array(
    368             'success' => false,
    369             'error'   => __('Failed to connect to PrintSeek API', 'printseek')
    370         );
    371     }
    372    
     172
    373173    /**
    374174     * Send webhook to PrintSeek
  • printseek/tags/1.0.3/includes/class-printseek-order-sync.php

    r3430355 r3848522  
    22/**
    33 * PrintSeek Order Sync
    4  * Handles order sync from PrintSeek to WooCommerce
     4 *
     5 * Sends orders with products pushed from PrintSeek to PrintSeek once they are paid (or COD) — status
     6 * `processing`/`completed` — and reports later status changes (e.g. a cancellation) of synced orders.
    57 */
    68
    … …  
    1012
    1113class PrintSeek_Order_Sync {
    12    
     14
     15    /**
     16     * WooCommerce statuses at which an order is ready to be printed.
     17     */
     18    const SYNC_STATUSES = array('processing', 'completed');
     19
    1320    /**
    1421     * Single instance
    1522     */
    1623    protected static $_instance = null;
    17    
     24
    1825    /**
    1926     * Instance
    … …  
    2532        return self::$_instance;
    2633    }
    27    
     34
    2835    /**
    2936     * Constructor
    3037     */
    3138    public function __construct() {
    32         // Hook into WooCommerce order creation
    33         add_action('woocommerce_new_order', array($this, 'sync_new_order'), 10, 1);
    34        
    35         // Hook into order status changes
    36         add_action('woocommerce_order_status_changed', array($this, 'sync_order_status'), 10, 3);
    37        
    38         // Add order meta box
     39        // Fires on checkout too (pending → processing), when the order already has its items.
     40        add_action('woocommerce_order_status_changed', array($this, 'on_status_changed'), 10, 4);
     41
    3942        add_action('add_meta_boxes', array($this, 'add_order_meta_box'));
    40        
    41         // Manual sync action
    42         add_action('wp_ajax_printseek_sync_orders', array($this, 'ajax_sync_orders'));
    4343        add_action('wp_ajax_printseek_sync_single_order', array($this, 'ajax_sync_single_order'));
    44        
    45         // Cron job for order status updates
    46         add_action('printseek_sync_order_status', array($this, 'sync_order_status_from_printseek'));
    47        
    48         // Schedule cron if not scheduled
    49         if (!wp_next_scheduled('printseek_sync_order_status')) {
    50             wp_schedule_event(time(), 'hourly', 'printseek_sync_order_status');
    51         }
    52     }
    53    
    54     /**
    55      * Sync new order to PrintSeek
    56      */
    57     public function sync_new_order($order_id) {
    58         // Check if auto sync is enabled
    59         if (get_option('printseek_auto_sync_orders') !== 'yes') {
     44    }
     45
     46    /**
     47     * Synced orders report the new status; others are sent once they reach a sync status.
     48     */
     49    public function on_status_changed($order_id, $old_status, $new_status, $order) {
     50        if ($this->is_synced($order)) {
     51            PrintSeek_API::instance()->send_webhook(array(
     52                'event'    => 'order.status_updated',
     53                'order_id' => $order->get_id(),
     54                'status'   => $new_status,
     55            ));
    6056            return;
    6157        }
    62        
    63         $order = wc_get_order($order_id);
    64        
    65         if (!$order) {
     58
     59        if (get_option('printseek_auto_sync_orders') !== 'yes' || !in_array($new_status, self::SYNC_STATUSES, true)) {
    6660            return;
    6761        }
    68        
    69         // Check if order contains PrintSeek products
    70         $has_printseek_products = false;
    71        
    72         foreach ($order->get_items() as $item) {
    73             $product_id = $item->get_product_id();
    74             $is_pushed = get_post_meta($product_id, '_printseek_pushed', true);
    75            
    76             if ($is_pushed) {
    77                 $has_printseek_products = true;
    78                 break;
    79             }
    80         }
    81        
    82         if (!$has_printseek_products) {
    83             return;
    84         }
    85        
    86         // Sync order
    87         $this->push_order_to_printseek($order_id);
    88     }
    89    
    90     /**
    91      * Push order to PrintSeek
    92      */
    93     public function push_order_to_printseek($order_id) {
    94         $order = wc_get_order($order_id);
    95        
    96         if (!$order) {
    97             return array(
    98                 'success' => false,
    99                 'message' => __('Order not found', 'printseek')
    100             );
    101         }
    102        
    103         // Check if already synced
    104         $printseek_order_id = $order->get_meta('_printseek_order_id');
    105         $already_synced = $order->get_meta('_printseek_synced');
    106        
    107         if ($printseek_order_id && ($already_synced === 'yes' || $already_synced === '1' || $already_synced === true)) {
     62
     63        if ($this->printseek_items($order)) {
     64            $this->push_order_to_printseek($order);
     65        }
     66    }
     67
     68    /**
     69     * Send an order to PrintSeek (once).
     70     *
     71     * @param WC_Order $order
     72     * @return array { success: bool, message: string }
     73     */
     74    public function push_order_to_printseek($order) {
     75        if ($this->is_synced($order)) {
    10876            return array(
    10977                'success' => true,
    11078                'message' => __('Order already synced to PrintSeek!', 'printseek'),
    111                 'order_id' => $printseek_order_id
    112             );
    113         }
    114        
    115         // Prepare order data
    116         $order_data = $this->prepare_order_data($order);
    117        
    118         // Send to API - always create new
    119         $api = PrintSeek_API::instance();
    120         $response = $api->push_product($order_data);
    121        
    122         if (isset($response['success']) && $response['success']) {
    123             $order_id_from_api = isset($response['data']['orderId']) ? $response['data']['orderId'] : '';
    124            
    125             // Save metadata - use 'yes' string for consistency with WordPress
    126             $order->update_meta_data('_printseek_synced', 'yes');
    127             $order->update_meta_data('_printseek_order_id', $order_id_from_api);
    128             $order->update_meta_data('_printseek_synced_at', current_time('mysql'));
    129             $order->save();
    130            
    131             // Add order note
    132             $order->add_order_note(__('Order synced to PrintSeek. Order ID: ', 'printseek') . $order_id_from_api);
    133            
    134             return array(
    135                 'success' => true,
    136                 'message' => __('Order synced successfully!', 'printseek'),
    137                 'order_id' => $order_id_from_api
    138             );
    139         } else {
    140             $error_message = isset($response['error']) ? $response['error'] : __('Unknown error', 'printseek');
    141            
    142             // Add order note
    143             $order->add_order_note(__('Failed to sync to PrintSeek: ', 'printseek') . $error_message);
    144            
     79            );
     80        }
     81
     82        $items = $this->printseek_items($order);
     83        if (!$items) {
    14584            return array(
    14685                'success' => false,
    147                 'message' => $error_message
    148             );
    149         }
    150     }
    151    
    152     /**
    153      * Prepare order data for API
    154      */
    155     private function prepare_order_data($order) {
    156         $items = array();
    157         $variants = array();
    158         $total_quantity = 0;
    159         $selected_colors = array();
    160         $selected_sizes = array();
    161        
    162         foreach ($order->get_items() as $item) {
    163             $product = $item->get_product();
    164             $product_id = $item->get_product_id();
    165            
    166             // Only include PrintSeek products
    167             $is_pushed = get_post_meta($product_id, '_printseek_pushed', true);
    168             if (!$is_pushed) {
    169                 continue;
    170             }
    171            
    172             $quantity = $item->get_quantity();
    173             $total_quantity += $quantity;
    174            
    175             $image_url = wp_get_attachment_url($product->get_image_id());
    176            
    177             // Get product type and variant from meta
    178             $product_type = get_post_meta($product_id, '_printseek_product_type', true);
    179             $variant_type = get_post_meta($product_id, '_printseek_variant', true);
    180            
    181             // Extract color and size from WooCommerce variation attributes
    182             $color = '';
    183             $size = '';
    184            
    185             // Check if this is a variation product
    186             if ($product && $product->is_type('variation')) {
    187                 $variation_attrs = $product->get_variation_attributes();
    188                 foreach ($variation_attrs as $attr_name => $attr_value) {
    189                     $attr_name_lower = strtolower($attr_name);
    190                     if (strpos($attr_name_lower, 'color') !== false || strpos($attr_name_lower, 'colour') !== false) {
    191                         $color = ucfirst($attr_value);
    192                     } elseif (strpos($attr_name_lower, 'size') !== false) {
    193                         $size = strtoupper($attr_value);
    194                     }
    195                 }
    196             }
    197            
    198             // Also check item meta for variations (WooCommerce stores selected attrs here)
    199             $item_meta = $item->get_meta_data();
    200             foreach ($item_meta as $meta) {
    201                 $meta_data = $meta->get_data();
    202                 $key_lower = strtolower($meta_data['key'] ?? '');
    203                 $meta_value = $meta_data['value'] ?? '';
    204                
    205                 // Skip if value is empty
    206                 if (empty($meta_value)) {
    207                     continue;
    208                 }
    209                
    210                 if (strpos($key_lower, 'color') !== false || strpos($key_lower, 'colour') !== false || $key_lower === 'pa_color' || $key_lower === 'pa_colour') {
    211                     $color = ucfirst($meta_value);
    212                 } elseif (strpos($key_lower, 'size') !== false || $key_lower === 'pa_size') {
    213                     // Normalize size to valid enum values (S, M, L, XL, XXL)
    214                     $raw_size = strtoupper($meta_value);
    215                     $size = $this->normalize_size($raw_size);
    216                 }
    217             }
    218            
    219             // Fallback: try to extract from product name (e.g., "T-Shirt - Black, M")
    220             if (empty($color) || empty($size)) {
    221                 $item_name = $item->get_name();
    222                 if (preg_match('/[-–]\s*([^,]+),\s*([A-Z]{1,3}L?)\s*$/i', $item_name, $matches)) {
    223                     if (empty($color)) {
    224                         $color = trim($matches[1]);
    225                     }
    226                     if (empty($size)) {
    227                         $size = $this->normalize_size(trim($matches[2]));
    228                     }
    229                 }
    230             }
    231            
    232             // Default values if still empty
    233             if (empty($color)) {
    234                 $color = 'Default';
    235             }
    236             if (empty($size)) {
    237                 $size = 'M';
    238             }
    239            
    240             // Add to variants array for frontend display
    241             $variants[] = array(
    242                 'id' => $product_id . '_' . count($variants),
    243                 'color' => $color,
    244                 'colorName' => $color,
    245                 'size' => $size,
    246                 'quantity' => $quantity,
    247             );
    248            
    249             // Track unique colors and sizes
    250             if (!in_array($color, $selected_colors)) {
    251                 $selected_colors[] = $color;
    252             }
    253             if (!in_array($size, $selected_sizes)) {
    254                 $selected_sizes[] = $size;
    255             }
    256            
    257             $items[] = array(
    258                 'product_id' => $product_id,
    259                 'product_name' => $item->get_name(),
    260                 'quantity' => $quantity,
    261                 'price' => floatval($item->get_total()),
    262                 'image_url' => $image_url,
    263                 'product_type' => $product_type ?: 'custom',
    264                 'variant' => $variant_type ?: 'standard',
    265                 'color' => $color,
    266                 'size' => $size,
    267             );
    268         }
    269        
    270         if (empty($items)) {
    271             return null;
    272         }
    273        
    274         // Get first item for main product data
    275         $first_item = $items[0];
    276        
    277         // Get customer name
    278         $first_name = $order->get_shipping_first_name() ?: $order->get_billing_first_name();
    279         $last_name = $order->get_shipping_last_name() ?: $order->get_billing_last_name();
    280         $full_name = trim($first_name . ' ' . $last_name);
    281         if (empty($full_name)) {
    282             $full_name = 'Customer';
    283         }
    284        
    285         // Get shipping address
    286         $shipping_address = array(
    287             'fullName' => $full_name,
    288             'firstName' => $first_name,
    289             'lastName' => $last_name,
    290             'phone' => $order->get_billing_phone(),
    291             'email' => $order->get_billing_email(),
    292             'addressLine1' => $order->get_shipping_address_1() ?: $order->get_billing_address_1(),
    293             'addressLine2' => $order->get_shipping_address_2() ?: $order->get_billing_address_2(),
    294             'city' => $order->get_shipping_city() ?: $order->get_billing_city(),
    295             'state' => $order->get_shipping_state() ?: $order->get_billing_state(),
    296             'pincode' => $order->get_shipping_postcode() ?: $order->get_billing_postcode(),
    297             'postalCode' => $order->get_shipping_postcode() ?: $order->get_billing_postcode(),
    298             'country' => $order->get_shipping_country() ?: $order->get_billing_country(),
     86                'message' => __('This order has no PrintSeek products.', 'printseek'),
     87            );
     88        }
     89
     90        $response = PrintSeek_API::instance()->sync_order($this->order_payload($order, $items));
     91
     92        if (empty($response['success'])) {
     93            $error_message = isset($response['error']) ? $response['error'] : __('Unknown error', 'printseek');
     94            $order->add_order_note(__('Failed to sync to PrintSeek: ', 'printseek') . $error_message);
     95            return array(
     96                'success' => false,
     97                'message' => $error_message,
     98            );
     99        }
     100
     101        $printseek_order_id = $response['data']['orderNumber'];
     102        $order->update_meta_data('_printseek_synced', 'yes');
     103        $order->update_meta_data('_printseek_order_id', $printseek_order_id);
     104        $order->update_meta_data('_printseek_synced_at', current_time('mysql'));
     105        $order->save();
     106        $order->add_order_note(__('Order synced to PrintSeek. Order ID: ', 'printseek') . $printseek_order_id);
     107
     108        return array(
     109            'success' => true,
     110            'message' => __('Order synced successfully!', 'printseek'),
    299111        );
    300        
    301         // Customer details for frontend display
    302         $customer_details = array(
    303             'name' => $full_name,
    304             'firstName' => $first_name,
    305             'lastName' => $last_name,
    306             'email' => $order->get_billing_email(),
    307             'phone' => $order->get_billing_phone(),
    308             'address' => $shipping_address['addressLine1'],
    309             'city' => $shipping_address['city'],
    310             'state' => $shipping_address['state'],
    311             'pincode' => $shipping_address['pincode'],
    312             'country' => $shipping_address['country'],
     112    }
     113
     114    /**
     115     * @param WC_Order $order
     116     */
     117    private function is_synced($order) {
     118        return $order->get_meta('_printseek_synced') === 'yes';
     119    }
     120
     121    /**
     122     * Lines of products pushed from PrintSeek.
     123     *
     124     * @param WC_Order $order
     125     * @return WC_Order_Item_Product[]
     126     */
     127    private function printseek_items($order) {
     128        return array_values(array_filter($order->get_items(), function ($item) {
     129            return get_post_meta($item->get_product_id(), '_printseek_pushed', true) === 'yes';
     130        }));
     131    }
     132
     133    /**
     134     * The order in the WooCommerce REST shape (`/wc/v3/orders/<id>`), with only the PrintSeek lines.
     135     *
     136     * @param WC_Order $order
     137     * @param WC_Order_Item_Product[] $items
     138     */
     139    private function order_payload($order, $items) {
     140        $date_paid = $order->get_date_paid();
     141
     142        return array(
     143            'id'             => $order->get_id(),
     144            'number'         => $order->get_order_number(),
     145            'status'         => $order->get_status(),
     146            'total'          => $order->get_total(),
     147            'payment_method' => $order->get_payment_method(),
     148            'date_paid'      => $date_paid ? $date_paid->date('c') : null,
     149            'billing'        => $order->get_address('billing'),
     150            'shipping'       => $order->get_address('shipping'),
     151            'line_items'     => array_map(array($this, 'line_payload'), $items),
    313152        );
    314        
    315         // Prepare data
    316         $data = array(
    317             'productName' => $first_item['product_name'],
    318             'productType' => $first_item['product_type'] ?: 'custom',
    319             'variant' => $first_item['variant'] ?: 'standard',
    320             'totalQuantity' => $total_quantity,
    321             'totalPrice' => floatval($order->get_total()),
    322             'paidAmount' => floatval($order->get_total()),
    323             'paymentStatus' => $order->is_paid() ? 'paid' : 'pending',
    324             'shippingType' => 'prepaid',
    325             'shippingAddress' => $shipping_address,
    326             'customerDetails' => $customer_details,
    327             'orderRemarks' => 'WooCommerce Order #' . $order->get_order_number(),
    328             'thumbnailUrl' => $first_item['image_url'],
    329             'source' => 'woocommerce',
    330             'woocommerceOrderId' => $order->get_id(),
    331             'orderNumber' => $order->get_order_number(),
    332             'siteUrl' => get_site_url(),
    333             // Variant details for frontend display (Color, Size, Quantity)
    334             'variants' => $variants,
    335             'selectedColors' => $selected_colors,
    336             'selectedSizes' => $selected_sizes,
     153    }
     154
     155    /**
     156     * One line; `meta_data` carries the chosen variation attributes (Colour, Size).
     157     * `$include_all` keeps the attributes WooCommerce otherwise hides because they are already in the item name.
     158     *
     159     * @param WC_Order_Item_Product $item
     160     */
     161    private function line_payload($item) {
     162        $meta_data = array();
     163        foreach ($item->get_formatted_meta_data('_', true) as $meta) {
     164            $meta_data[] = array(
     165                'key'   => $meta->display_key,
     166                'value' => trim(wp_strip_all_tags($meta->display_value)),
     167            );
     168        }
     169
     170        $image_id = $item->get_product() ? $item->get_product()->get_image_id() : 0;
     171
     172        return array(
     173            'product_id'   => $item->get_product_id(),
     174            'variation_id' => $item->get_variation_id(),
     175            'name'         => $item->get_name(),
     176            'quantity'     => $item->get_quantity(),
     177            'image'        => array('src' => $image_id ? wp_get_attachment_url($image_id) : ''),
     178            'meta_data'    => $meta_data,
    337179        );
    338        
    339         return $data;
    340     }
    341    
    342     /**
    343      * Sync order status changes
    344      */
    345     public function sync_order_status($order_id, $old_status, $new_status) {
    346         $order = wc_get_order($order_id);
    347        
    348         if (!$order) {
    349             return;
    350         }
    351        
    352         $printseek_order_id = $order->get_meta('_printseek_order_id');
    353        
    354         if (!$printseek_order_id) {
    355             return;
    356         }
    357        
    358         // Map WooCommerce status to PrintSeek status
    359         $status_map = array(
    360             'processing' => 'processing',
    361             'completed' => 'delivered',
    362             'cancelled' => 'cancelled',
    363             'refunded' => 'cancelled',
    364         );
    365        
    366         if (!isset($status_map[$new_status])) {
    367             return;
    368         }
    369        
    370         $printseek_status = $status_map[$new_status];
    371        
    372         // Update status in PrintSeek
    373         $api = PrintSeek_API::instance();
    374         $response = $api->update_order_status($printseek_order_id, $printseek_status);
    375        
    376         if (isset($response['success']) && $response['success']) {
    377             $order->add_order_note(__('Order status synced to PrintSeek: ', 'printseek') . $printseek_status);
    378         }
    379     }
    380    
    381     /**
    382      * Sync order status FROM PrintSeek (cron job)
    383      */
    384     public function sync_order_status_from_printseek() {
    385         // Get all orders synced to PrintSeek
    386         // phpcs:disable WordPress.DB.SlowDBQuery.slow_db_query_meta_key, WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- Required for order lookup
    387         $args = array(
    388             'limit' => -1,
    389             'meta_key' => '_printseek_synced',
    390             'meta_value' => 'yes',
    391             'status' => array('processing', 'on-hold'),
    392         );
    393         // phpcs:enable WordPress.DB.SlowDBQuery.slow_db_query_meta_key, WordPress.DB.SlowDBQuery.slow_db_query_meta_value
    394        
    395         $orders = wc_get_orders($args);
    396        
    397         foreach ($orders as $order) {
    398             $printseek_order_id = $order->get_meta('_printseek_order_id');
    399            
    400             if (!$printseek_order_id) {
    401                 continue;
    402             }
    403            
    404             // Get order status from PrintSeek
    405             $api = PrintSeek_API::instance();
    406             $response = $api->get_order($printseek_order_id);
    407            
    408             if (!isset($response['success']) || !$response['success']) {
    409                 continue;
    410             }
    411            
    412             $printseek_status = isset($response['data']['status']) ? $response['data']['status'] : '';
    413            
    414             // Map PrintSeek status to WooCommerce
    415             $status_map = array(
    416                 'delivered' => 'completed',
    417                 'cancelled' => 'cancelled',
    418                 'shipped' => 'processing',
    419             );
    420            
    421             if (!isset($status_map[$printseek_status])) {
    422                 continue;
    423             }
    424            
    425             $wc_status = $status_map[$printseek_status];
    426            
    427             // Update order status if different
    428             if ($order->get_status() !== $wc_status) {
    429                 $order->update_status($wc_status, __('Status updated from PrintSeek: ', 'printseek') . $printseek_status);
    430                
    431                 // Add tracking info if available
    432                 if (isset($response['data']['trackingNumber'])) {
    433                     $order->update_meta_data('_printseek_tracking_number', $response['data']['trackingNumber']);
    434                     $order->save();
    435                 }
    436             }
    437         }
    438     }
    439    
    440     /**
    441      * Add order meta box
     180    }
     181
     182    /**
     183     * Add order meta box (legacy order screen and HPOS).
    442184     */
    443185    public function add_order_meta_box() {
    444         add_meta_box(
    445             'printseek_order_info',
    446             __('PrintSeek POD', 'printseek'),
    447             array($this, 'render_order_meta_box'),
    448             'shop_order',
    449             'side',
    450             'high'
    451         );
    452        
    453         // WC HPOS compatibility
    454         add_meta_box(
    455             'printseek_order_info',
    456             __('PrintSeek POD', 'printseek'),
    457             array($this, 'render_order_meta_box'),
    458             'woocommerce_page_wc-orders',
    459             'side',
    460             'high'
    461         );
    462     }
    463    
     186        foreach (array('shop_order', 'woocommerce_page_wc-orders') as $screen) {
     187            add_meta_box(
     188                'printseek_order_info',
     189                __('PrintSeek POD', 'printseek'),
     190                array($this, 'render_order_meta_box'),
     191                $screen,
     192                'side',
     193                'high'
     194            );
     195        }
     196    }
     197
    464198    /**
    465199     * Render order meta box
    … …  
    467201    public function render_order_meta_box($post_or_order) {
    468202        $order = ($post_or_order instanceof WP_Post) ? wc_get_order($post_or_order->ID) : $post_or_order;
    469        
    470         $synced = $order->get_meta('_printseek_synced');
    471203        $printseek_order_id = $order->get_meta('_printseek_order_id');
    472         $tracking_number = $order->get_meta('_printseek_tracking_number');
    473         $printseek_status = $order->get_meta('_printseek_status');
    474        
     204
    475205        ?>
    476206        <div class="printseek-order-meta">
    477             <p>
    478                 <strong><?php esc_html_e('Sync Status:', 'printseek'); ?></strong><br>
    479                 <?php if ($synced === 'yes' || $synced === '1' || $synced === true): ?>
     207            <?php if ($this->is_synced($order)): ?>
     208                <p>
     209                    <strong><?php esc_html_e('Sync Status:', 'printseek'); ?></strong><br>
    480210                    <span style="color: green;">✓ <?php esc_html_e('Synced', 'printseek'); ?></span>
    481                 <?php else: ?>
    482                     <span style="color: gray;"><?php esc_html_e('Not synced', 'printseek'); ?></span>
    483                 <?php endif; ?>
    484             </p>
    485            
    486             <?php if ($printseek_order_id): ?>
     211                </p>
    487212                <p>
    488213                    <strong><?php esc_html_e('PrintSeek Order ID:', 'printseek'); ?></strong><br>
    489214                    <code style="font-size: 10px; word-break: break-all;"><?php echo esc_html($printseek_order_id); ?></code>
    490215                </p>
    491             <?php endif; ?>
    492            
    493             <?php if ($printseek_status): ?>
    494                 <p>
    495                     <strong><?php esc_html_e('PrintSeek Status:', 'printseek'); ?></strong><br>
    496                     <span class="printseek-status-badge"><?php echo esc_html(ucfirst($printseek_status)); ?></span>
    497                 </p>
    498             <?php endif; ?>
    499            
    500             <?php if ($tracking_number): ?>
    501                 <p>
    502                     <strong><?php esc_html_e('Tracking Number:', 'printseek'); ?></strong><br>
    503                     <code><?php echo esc_html($tracking_number); ?></code>
    504                 </p>
    505             <?php endif; ?>
    506            
    507             <?php
    508             $is_synced = ($synced === 'yes' || $synced === '1' || $synced === true) && $printseek_order_id;
    509             if ($is_synced):
    510             ?>
    511                 <div class="printseek-synced-notice" style="background: #d1fae5; border: 1px solid #10b981; padding: 10px; border-radius: 6px; margin-top: 10px;">
    512                     <p style="margin: 0; color: #065f46; font-size: 12px;">
    513                         <span class="dashicons dashicons-yes-alt" style="color: #10b981;"></span>
    514                         <?php esc_html_e('This order is already synced to PrintSeek.', 'printseek'); ?>
    515                     </p>
    516                 </div>
    517216            <?php else: ?>
     217                <p>
     218                    <strong><?php esc_html_e('Sync Status:', 'printseek'); ?></strong><br>
     219                    <span style="color: gray;"><?php esc_html_e('Not synced', 'printseek'); ?></span>
     220                </p>
    518221                <p>
    519222                    <button type="button" class="button button-primary" id="printseek-sync-order-btn" data-order-id="<?php echo absint($order->get_id()); ?>">
    … …  
    527230        <?php
    528231    }
    529    
     232
    530233    /**
    531234     * AJAX: Sync single order
    … …  
    533236    public function ajax_sync_single_order() {
    534237        check_ajax_referer('printseek_sync_single_order', 'nonce');
    535        
     238
    536239        if (!current_user_can('manage_woocommerce')) {
    537240            wp_send_json_error(array('message' => __('Permission denied', 'printseek')));
    538241        }
    539        
    540         $order_id = isset($_POST['order_id']) ? absint($_POST['order_id']) : 0;
    541        
    542         if (!$order_id) {
    543             wp_send_json_error(array('message' => __('Invalid order ID', 'printseek')));
    544         }
    545        
    546         $result = $this->push_order_to_printseek($order_id);
    547        
     242
     243        $order = wc_get_order(isset($_POST['order_id']) ? absint($_POST['order_id']) : 0);
     244        if (!$order) {
     245            wp_send_json_error(array('message' => __('Order not found', 'printseek')));
     246        }
     247
     248        $result = $this->push_order_to_printseek($order);
     249
    548250        if ($result['success']) {
    549251            wp_send_json_success(array('message' => $result['message']));
    550         } else {
    551             wp_send_json_error(array('message' => $result['message']));
    552         }
    553     }
    554    
    555     /**
    556      * AJAX: Sync orders
    557      */
    558     public function ajax_sync_orders() {
    559         check_ajax_referer('printseek_sync_orders', 'nonce');
    560        
    561         if (!current_user_can('manage_woocommerce')) {
    562             wp_send_json_error(array('message' => __('Permission denied', 'printseek')));
    563         }
    564        
    565         // Trigger sync
    566         $this->sync_order_status_from_printseek();
    567        
    568         wp_send_json_success(array('message' => __('Orders synced successfully!', 'printseek')));
    569     }
    570    
    571     /**
    572      * Normalize size values to valid enum (S, M, L, XL, XXL)
    573      * Maps common size variations to standard values
    574      *
    575      * @param string $raw_size Raw size string from WooCommerce
    576      * @return string Normalized size value
    577      */
    578     private function normalize_size($raw_size) {
    579         $raw_size = strtoupper(trim($raw_size));
    580        
    581         // Direct matches
    582         $valid_sizes = array('S', 'M', 'L', 'XL', 'XXL');
    583         if (in_array($raw_size, $valid_sizes, true)) {
    584             return $raw_size;
    585         }
    586        
    587         // Map common variations to standard sizes
    588         $size_map = array(
    589             // Small variations
    590             'SMALL' => 'S',
    591             'SM' => 'S',
    592             'SML' => 'S',
    593             'XSMALL' => 'S',
    594             'X-SMALL' => 'S',
    595             'XS' => 'S',
    596            
    597             // Medium variations
    598             'MEDIUM' => 'M',
    599             'MED' => 'M',
    600             'MD' => 'M',
    601            
    602             // Large variations
    603             'LARGE' => 'L',
    604             'LG' => 'L',
    605             'LRG' => 'L',
    606            
    607             // XL variations
    608             'XLARGE' => 'XL',
    609             'X-LARGE' => 'XL',
    610             'EXTRA LARGE' => 'XL',
    611             'EXTRA-LARGE' => 'XL',
    612             '1XL' => 'XL',
    613             '1X' => 'XL',
    614            
    615             // XXL variations
    616             'XXLARGE' => 'XXL',
    617             'XX-LARGE' => 'XXL',
    618             '2XL' => 'XXL',
    619             '2X' => 'XXL',
    620             'XXXL' => 'XXL',
    621             '3XL' => 'XXL',
    622             '3X' => 'XXL',
    623         );
    624        
    625         if (isset($size_map[$raw_size])) {
    626             return $size_map[$raw_size];
    627         }
    628        
    629         // Default to M if unknown
    630         return 'M';
     252        }
     253        wp_send_json_error(array('message' => $result['message']));
    631254    }
    632255}
  • printseek/tags/1.0.3/includes/class-printseek-product-sync.php

    r3430355 r3848522  
    6363     */
    6464    public function render_meta_box($post) {
    65         $product = wc_get_product($post->ID);
    6665        $pushed_to_printseek = get_post_meta($post->ID, '_printseek_pushed', true);
    67         $printseek_order_id = get_post_meta($post->ID, '_printseek_order_id', true);
     66        $printseek_sku = get_post_meta($post->ID, '_printseek_sku', true);
    6867       
    6968        ?>
    … …  
    7877            </p>
    7978           
    80             <?php if ($printseek_order_id): ?>
     79            <?php if ($printseek_sku): ?>
    8180                <p>
    82                     <strong><?php esc_html_e('Order ID:', 'printseek'); ?></strong><br>
    83                     <code><?php echo esc_html($printseek_order_id); ?></code>
     81                    <strong><?php esc_html_e('Design SKU:', 'printseek'); ?></strong><br>
     82                    <code><?php echo esc_html($printseek_sku); ?></code>
    8483                </p>
    8584            <?php endif; ?>
    86            
     85
     86            <?php if ($pushed_to_printseek !== 'yes'): ?>
    8787            <p>
    8888                <button type="button" class="button button-primary button-large" id="printseek-push-product" data-product-id="<?php echo absint( $post->ID ); ?>">
    … …  
    9696           
    9797            <div id="printseek-push-status" style="margin-top: 10px;"></div>
     98            <?php endif; ?>
    9899        </div>
    99100        <?php
    … …  
    162163   
    163164    /**
    164      * Prepare product data for API
    165      */
    166     private function prepare_product_data($product) {
    167         $image_url = wp_get_attachment_url($product->get_image_id());
    168        
    169         // Get variations if variable product
    170         $variants = array();
    171         if ($product->is_type('variable')) {
    172             $variations = $product->get_available_variations();
    173             foreach ($variations as $variation) {
    174                 $variant_obj = wc_get_product($variation['variation_id']);
    175                 $attributes = $variant_obj->get_attributes();
    176                
    177                 $color = isset($attributes['pa_color']) ? $attributes['pa_color'] : 'default';
    178                 $size = isset($attributes['pa_size']) ? $attributes['pa_size'] : 'M';
    179                
    180                 $variants[] = array(
    181                     'id' => 'v' . $variation['variation_id'],
    182                     'color' => $color,
    183                     'colorName' => ucfirst($color),
    184                     'size' => strtoupper($size),
    185                     'quantity' => 1
    186                 );
    187             }
    188         }
    189        
    190         // Prepare data matching your backend API structure
    191         $data = array(
    192             'productName' => $product->get_name(),
    193             'productType' => $this->get_product_type($product),
    194             'variant' => 'standard',
    195             'variantMode' => !empty($variants),
    196             'variants' => $variants,
    197             'totalQuantity' => 1,
    198             'totalPrice' => floatval($product->get_price()),
    199             'thumbnailUrl' => $image_url,
    200             'designs' => array(
    201                 'front' => $image_url ? array('url' => $image_url) : null,
    202             ),
    203             'shippingAddress' => array(
    204                 'fullName' => 'WooCommerce Product',
    205                 'phone' => '',
    206                 'email' => get_option('admin_email'),
    207                 'addressLine1' => 'Sample Address',
    208                 'city' => 'Sample City',
    209                 'state' => 'Sample State',
    210                 'postalCode' => '000000',
    211                 'country' => 'India'
    212             ),
    213             'source' => 'woocommerce',
    214             'woocommerceProductId' => $product->get_id(),
    215             'siteUrl' => get_site_url()
    216         );
    217        
    218         return $data;
    219     }
    220    
    221     /**
    222      * Get product type
    223      */
    224     private function get_product_type($product) {
    225         $categories = $product->get_category_ids();
    226        
    227         // Map WooCommerce categories to PrintSeek product types
    228         $type_mapping = array(
    229             't-shirt' => 'tshirt',
    230             'hoodie' => 'hoodie',
    231             'oversized' => 'oversized-tshirt',
    232             'polo' => 'polo',
    233         );
    234        
    235         foreach ($categories as $cat_id) {
    236             $cat = get_term($cat_id, 'product_cat');
    237             $slug = strtolower($cat->slug);
    238            
    239             foreach ($type_mapping as $key => $value) {
    240                 if (strpos($slug, $key) !== false) {
    241                     return $value;
    242                 }
    243             }
    244         }
    245        
    246         return 'tshirt'; // Default
    247     }
    248    
    249     /**
    250165     * Add bulk action
    251166     */
    252167    public function add_bulk_action($actions) {
    253         $actions['printseek_push'] = __('Push to PrintSeek', 'printseek');
     168        $actions['printseek_push'] = __('Mark as PrintSeek product', 'printseek');
    254169        return $actions;
    255170    }
    … …  
    296211    public function product_column_content($column, $post_id) {
    297212        if ($column === 'printseek_status') {
    298             $pushed = get_post_meta($post_id, '_printseek_pushed', true);
    299            
    300             if ($pushed) {
     213            if (get_post_meta($post_id, '_printseek_pushed', true) === 'yes') {
    301214                echo '<span style="color: green;">✓</span>';
    302215            } else {
  • printseek/tags/1.0.3/languages/printseek.pot

    r3430355 r3848522  
    55"Project-Id-Version: PrintSeek - Print on Demand 1.0.0\n"
    66"Report-Msgid-Bugs-To: https://wordpress.org/support/plugin/printseek\n"
    7 "Last-Translator: PrintSeek Team <support@printsik.com>\n"
    8 "Language-Team: PrintSeek Team <support@printsik.com>\n"
     7"Last-Translator: PrintSeek Team <abid.akram01@gmail.com>\n"
     8"Language-Team: PrintSeek Team <abid.akram01@gmail.com>\n"
    99"MIME-Version: 1.0\n"
    1010"Content-Type: text/plain; charset=UTF-8\n"
  • printseek/tags/1.0.3/printseek.php

    r3430355 r3848522  
    22/**
    33 * Plugin Name: Printseek: Print on Demand
    4  * Plugin URI: https://printsik.com/plugins/woocommerce
     4 * Plugin URI: https://lafangehclothing.com/dashboard/connect-store
    55 * Description: Connect your WooCommerce store with PrintSeek Print on Demand service. Push products, sync orders, and manage fulfillment seamlessly.
    6  * Version: 1.0.2
     6 * Version: 1.0.3
    77 * Author: PrintSeek Team
    8  * Author URI: https://printsik.com
     8 * Author URI: https://lafangehclothing.com
    99 * Text Domain: printseek
    1010 * Domain Path: /languages
    … …  
    1717 *
    1818 * @package PrintSeek_POD
    19  * @version 1.0.2
    20  * @author PrintSeek Team <support@printsik.com>
     19 * @version 1.0.3
     20 * @author PrintSeek Team <abid.akram01@gmail.com>
    2121 * @copyright 2024 PrintSeek
    2222 * @license GPL-2.0+
    … …  
    2929
    3030// Define plugin constants
    31 define('PRINTSEEK_VERSION', '1.0.2');
     31define('PRINTSEEK_VERSION', '1.0.3');
    3232define('PRINTSEEK_PLUGIN_FILE', __FILE__);
    3333define('PRINTSEEK_PLUGIN_DIR', plugin_dir_path(__FILE__));
    … …  
    3535define('PRINTSEEK_PLUGIN_BASENAME', plugin_basename(__FILE__));
    3636
    37 // API Configuration - Change this to your production API URL
    38 define('PRINTSEEK_API_URL', 'https://api.printsik.com');
    39 // define('PRINTSEEK_API_URL', 'http://localhost:3001'); // Uncomment for local development
     37// Backend API URL (the backend's BASE_URL). Override it in wp-config.php, e.g. for local development:
     38// define('PRINTSEEK_API_URL', 'http://localhost:4000');
     39if (!defined('PRINTSEEK_API_URL')) {
     40    define('PRINTSEEK_API_URL', 'https://api.printsik.com');
     41}
     42// Store website (the backend's FRONTEND_URL) for the dashboard links; overridable the same way.
     43if (!defined('PRINTSEEK_SITE_URL')) {
     44    define('PRINTSEEK_SITE_URL', 'https://lafangehclothing.com');
     45}
     46define('PRINTSEEK_SUPPORT_EMAIL', 'abid.akram01@gmail.com');
    4047
    4148/**
    … …  
    142149        require_once PRINTSEEK_PLUGIN_DIR . 'includes/class-printseek-product-sync.php';
    143150        require_once PRINTSEEK_PLUGIN_DIR . 'includes/class-printseek-order-sync.php';
    144         require_once PRINTSEEK_PLUGIN_DIR . 'includes/class-printseek-webhook-handler.php';
    145151    }
    146152   
    … …  
    200206            PrintSeek_Product_Sync::instance();
    201207            PrintSeek_Order_Sync::instance();
    202             PrintSeek_Webhook_Handler::instance();
    203208           
    204             // Notify PrintSeek that plugin is activated
    205             $this->notify_plugin_status('activated');
    206         }
     209            // Notify PrintSeek that the plugin is active — THROTTLED.
     210            // init() runs on `plugins_loaded`, which fires on EVERY request/page-load. Calling
     211            // notify_plugin_status() unconditionally here floods the backend with
     212            // `plugin.activated` webhooks (one per request). Send at most once per 12h instead.
     213            $this->maybe_notify_plugin_active();
     214        }
     215    }
     216   
     217    /**
     218     * Send a throttled "plugin active" heartbeat to PrintSeek.
     219     *
     220     * Because init() runs on every request, we must not notify every time. We notify at most
     221     * once per 12 hours and re-notify immediately when the plugin version changes. This keeps
     222     * the backend's "plugin installed" signal fresh without hammering the webhook endpoint.
     223     *
     224     * @since 1.0.0
     225     */
     226    private function maybe_notify_plugin_active() {
     227        if (get_transient('printseek_active_notified') === PRINTSEEK_VERSION) {
     228            return;
     229        }
     230        $this->notify_plugin_status('activated');
     231        set_transient('printseek_active_notified', PRINTSEEK_VERSION, 12 * HOUR_IN_SECONDS);
    207232    }
    208233   
    … …  
    232257        if (PRINTSEEK_PLUGIN_BASENAME === $file) {
    233258            $row_meta = array(
    234                 'docs'    => '<a href="' . esc_url('https://printsik.com/docs/woocommerce') . '" target="_blank">' .
     259                'docs'    => '<a href="' . esc_url(PRINTSEEK_SITE_URL) . '" target="_blank">' .
    235260                             esc_html__('Documentation', 'printseek') . '</a>',
    236                 'support' => '<a href="' . esc_url('https://printsik.com/support') . '" target="_blank">' .
     261                'support' => '<a href="' . esc_url('mailto:' . PRINTSEEK_SUPPORT_EMAIL) . '">' .
    237262                             esc_html__('Support', 'printseek') . '</a>',
    238263            );
    … …  
    248273     */
    249274    public function activate() {
    250         // Create necessary database tables
    251         $this->create_tables();
    252        
    253         // Set default options
    254275        add_option('printseek_version', PRINTSEEK_VERSION);
    255276        add_option('printseek_api_key', '');
    256277        add_option('printseek_auto_sync_orders', 'yes');
    257         add_option('printseek_auto_sync_products', 'no');
    258         add_option('printseek_webhook_secret', '');
    259278        add_option('printseek_debug_mode', 'no');
    260        
    261         // Schedule cron events
    262         if (!wp_next_scheduled('printseek_sync_order_status')) {
    263             wp_schedule_event(time(), 'hourly', 'printseek_sync_order_status');
    264         }
    265        
    266         // Flush rewrite rules
    267         flush_rewrite_rules();
    268        
     279
     280        // Leftovers of 1.0.x (hourly status cron, unused options).
     281        wp_clear_scheduled_hook('printseek_sync_order_status');
     282        delete_option('printseek_auto_sync_products');
     283        delete_option('printseek_webhook_secret');
     284
    269285        // Log activation
    270286        $this->log('Plugin activated', 'info');
    … …  
    277293     */
    278294    public function deactivate() {
    279         // Clear scheduled cron events
    280         wp_clear_scheduled_hook('printseek_sync_order_status');
    281        
    282         // Notify PrintSeek that plugin is deactivated
    283295        $this->notify_plugin_status('deactivated');
    284        
    285         // Flush rewrite rules
    286         flush_rewrite_rules();
    287        
     296
    288297        // Log deactivation
    289298        $this->log('Plugin deactivated', 'info');
    … …  
    315324        // Fire and forget - don't wait for response
    316325        $api->send_webhook($data);
    317     }
    318    
    319     /**
    320      * Create database tables
    321      *
    322      * @since 1.0.0
    323      */
    324     private function create_tables() {
    325         global $wpdb;
    326        
    327         $charset_collate = $wpdb->get_charset_collate();
    328        
    329         // Sync log table
    330         $table_name = $wpdb->prefix . 'printseek_sync_log';
    331        
    332         $sql = "CREATE TABLE IF NOT EXISTS $table_name (
    333             id bigint(20) NOT NULL AUTO_INCREMENT,
    334             sync_type varchar(50) NOT NULL,
    335             item_id varchar(100) NOT NULL,
    336             status varchar(20) NOT NULL,
    337             message text,
    338             created_at datetime DEFAULT CURRENT_TIMESTAMP,
    339             PRIMARY KEY (id),
    340             KEY sync_type (sync_type),
    341             KEY item_id (item_id),
    342             KEY status (status),
    343             KEY created_at (created_at)
    344         ) $charset_collate;";
    345        
    346         require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    347         dbDelta($sql);
    348326    }
    349327   
    … …  
    441419        }
    442420    }
    443    
    444     /**
    445      * Get plugin log file path
    446      * Uses wp_upload_dir() as per WordPress plugin guidelines
    447      *
    448      * @since 1.0.0
    449      * @return string|false Log file path or false on failure
    450      */
    451     public function get_log_file_path() {
    452         $log_dir = $this->get_log_directory();
    453        
    454         if (!$log_dir) {
    455             return false;
    456         }
    457        
    458         return trailingslashit($log_dir) . 'debug.log';
    459     }
    460421}
    461422
  • printseek/tags/1.0.3/readme.txt

    r3430355 r3848522  
    11=== Printseek: Print on Demand ===
    22Contributors: printseek
    3 Donate link: https://printsik.com
     3Donate link: https://lafangehclothing.com
    44Tags: print-on-demand, woocommerce, pod, fulfillment, dropshipping
    55Requires at least: 5.8
    66Tested up to: 6.9
    77Requires PHP: 7.4
    8 Stable tag: 1.0.2
     8Stable tag: 1.0.3
    99WC requires at least: 5.0
    1010WC tested up to: 9.0
    … …  
    2222* **One-Click Product Link** - Link your WooCommerce products to PrintSeek for fulfillment
    2323* **Automatic Order Sync** - Orders automatically sync to PrintSeek when customers purchase
    24 * **Real-Time Updates** - Receive order status updates via webhooks
     24* **Status Updates** - Cancellations and other order status changes are reported to PrintSeek
    2525* **Easy Dashboard** - Manage everything from WordPress admin panel
    2626* **Bulk Actions** - Link multiple products at once
    27 * **Order Tracking** - Track fulfillment status directly in WooCommerce
    2827* **HPOS Compatible** - Works with WooCommerce High-Performance Order Storage
    2928
    … …  
    4039* WooCommerce 5.0 or higher
    4140* PHP 7.4 or higher
    42 * PrintSeek account (sign up free at [printsik.com](https://printsik.com))
     41* PrintSeek account (sign up free at [lafangehclothing.com](https://lafangehclothing.com))
    4342
    44 = Links =
     43#### Links
    4544
    46 * [PrintSeek Website](https://printsik.com)
    47 * [Contact Support](https://printsik.com/contact-us)
     45- [PrintSeek Website](https://printsik.com/)
     46- [Contact Support](https://printsik.com/contact-us)
    4847
    4948== Installation ==
    … …  
    7574= How do I get a PrintSeek API key? =
    7675
    77 Sign up for a free account at [printsik.com](https://printsik.com), then navigate to your dashboard to find your API key.
     76Sign up for a free account at [lafangehclothing.com](https://lafangehclothing.com), then navigate to your dashboard to find your API key.
    7877
    7978= How do I link products to PrintSeek? =
    … …  
    8685= Are orders synced automatically? =
    8786
    88 Yes! Once you link a product, any new orders containing that product will automatically sync to PrintSeek.
    89 
    90 = What happens when an order is shipped? =
    91 
    92 PrintSeek sends a webhook notification, and your WooCommerce order is automatically updated with tracking information.
     87Yes. Once a paid or Cash on Delivery order containing a linked product reaches Processing, it syncs to PrintSeek with the chosen colour and size. Later status changes (e.g. Cancelled) are reported too.
    9388
    9489= Is this plugin compatible with HPOS? =
    … …  
    105100
    106101== Changelog ==
     102
     103= 1.0.3 =
     104* Fixed: Saving the API key no longer resets Auto Sync Orders and Debug Mode
     105* Fixed: Orders sync when they reach Processing (paid or COD), with their items, colour and size
     106* Improved: Saving the API key verifies it right away; the dashboard shows the real connection state
     107* Improved: Order status changes of synced orders are reported to PrintSeek
     108* Removed: Unused webhook receiver, hourly status cron and unused settings
    107109
    108110= 1.0.2 =
    … …  
    128130== Upgrade Notice ==
    129131
     132= 1.0.3 =
     133Order sync fixes. Requires the current PrintSeek API.
     134
    130135= 1.0.2 =
    131136Important fix: Log files now use WordPress uploads directory per plugin guidelines.
    … …  
    147152No personal data is collected by the plugin itself. Order data is transmitted securely to PrintSeek for fulfillment purposes only.
    148153
    149 For more information, see PrintSeek's privacy policy at https://printsik.com/privacy
     154For more information, see PrintSeek's privacy policy at https://lafangehclothing.com/privacy-policy
    150155
     156Contact (support, API and WordPress.org plugin review questions): abid.akram01@gmail.com.
     157
  • printseek/trunk/assets/js/admin.js

    r3430355 r3848522  
    1515        initProductPush();
    1616        initOrderSync();
    17         initConnectionTest();
    1817        initSettingsPage();
    1918        initAlertDismiss();
    … …  
    7271     */
    7372    function initOrderSync() {
    74         // Manual sync orders button
    75         $('.printseek-sync-orders').on('click', function(e) {
    76             e.preventDefault();
    77            
    78             var button = $(this);
    79             var originalText = button.text();
    80            
    81             button.prop('disabled', true).text(printseek_vars.i18n.syncing || 'Syncing...');
    82            
    83             $.ajax({
    84                 url: printseek_vars.ajax_url,
    85                 type: 'POST',
    86                 data: {
    87                     action: 'printseek_sync_orders',
    88                     nonce: printseek_vars.nonce
    89                 },
    90                 success: function(response) {
    91                     button.prop('disabled', false).text(originalText);
    92                    
    93                     if (response.success) {
    94                         showNotice(response.data.message, 'success');
    95                        
    96                         // Reload page after 2 seconds
    97                         setTimeout(function() {
    98                             location.reload();
    99                         }, 2000);
    100                     } else {
    101                         showNotice(response.data.message, 'error');
    102                     }
    103                 },
    104                 error: function() {
    105                     button.prop('disabled', false).text(originalText);
    106                     showNotice(printseek_vars.i18n.request_failed || 'Request failed. Please try again.', 'error');
    107                 }
    108             });
    109         });
    110        
    11173        // Single order sync button
    11274        $('#printseek-sync-order-btn').on('click', function(e) {
    … …  
    156118   
    157119    /**
    158      * Connection Test
    159      */
    160     function initConnectionTest() {
    161         $('.printseek-test-connection').on('click', function(e) {
    162             e.preventDefault();
    163            
    164             var button = $(this);
    165             var originalText = button.text();
    166             var statusDiv = $('.connection-status');
    167            
    168             button.prop('disabled', true).text(printseek_vars.i18n.testing || 'Testing...');
    169             statusDiv.html('<span class="printseek-spinner"></span> ' + (printseek_vars.i18n.testing_connection || 'Testing connection...'));
    170            
    171             $.ajax({
    172                 url: printseek_vars.ajax_url,
    173                 type: 'POST',
    174                 data: {
    175                     action: 'printseek_test_connection',
    176                     nonce: printseek_vars.nonce,
    177                     api_key: $('#printseek_api_key').val()
    178                 },
    179                 success: function(response) {
    180                     button.prop('disabled', false).text(originalText);
    181                    
    182                     if (response.success) {
    183                         statusDiv.html('<div class="printseek-success">✓ ' + response.data.message + '</div>');
    184                     } else {
    185                         statusDiv.html('<div class="printseek-error">✗ ' + response.data.message + '</div>');
    186                     }
    187                 },
    188                 error: function() {
    189                     button.prop('disabled', false).text(originalText);
    190                     statusDiv.html('<div class="printseek-error">✗ ' + (printseek_vars.i18n.connection_failed || 'Connection test failed') + '</div>');
    191                 }
    192             });
    193         });
    194     }
    195    
    196     /**
    197120     * Settings page functionality
    198121     */
    … …  
    287210   
    288211    /**
    289      * Show admin notice
    290      */
    291     function showNotice(message, type) {
    292         var noticeClass = type === 'success' ? 'notice-success' : 'notice-error';
    293         var notice = $('<div class="notice ' + noticeClass + ' is-dismissible"><p>' + message + '</p></div>');
    294        
    295         $('.wrap h1').first().after(notice);
    296        
    297         // Auto dismiss after 5 seconds
    298         setTimeout(function() {
    299             notice.fadeOut(function() {
    300                 $(this).remove();
    301             });
    302         }, 5000);
    303     }
    304    
    305     /**
    306212     * Bulk action confirmation
    307213     */
    … …  
    318224            }
    319225           
    320             var confirmMsg = printseek_vars.i18n.confirm_push || 'Push {count} product(s) to PrintSeek?';
     226            var confirmMsg = printseek_vars.i18n.confirm_push || 'Mark {count} product(s) as PrintSeek products?';
    321227            confirmMsg = confirmMsg.replace('{count}', selectedCount);
    322228           
  • printseek/trunk/includes/admin/class-printseek-admin.php

    r3430355 r3848522  
    139139        wp_localize_script('printseek-admin', 'printseek_vars', array(
    140140            'ajax_url' => admin_url('admin-ajax.php'),
    141             'nonce' => wp_create_nonce('printseek_admin'),
    142141            'push_product_nonce' => wp_create_nonce('printseek_push_product'),
    143142            'sync_order_nonce' => wp_create_nonce('printseek_sync_single_order'),
    … …  
    149148                'saving' => __('Saving...', 'printseek'),
    150149                'sync_to_printseek' => __('Sync to PrintSeek', 'printseek'),
    151                 'testing_connection' => __('Testing connection...', 'printseek'),
    152                 'connection_failed' => __('Connection test failed', 'printseek'),
    153150                'select_product' => __('Please select at least one product.', 'printseek'),
    154                 'confirm_push' => __('Push {count} product(s) to PrintSeek?', 'printseek'),
     151                'confirm_push' => __('Mark {count} product(s) as PrintSeek products?', 'printseek'),
    155152            ),
    156153        ));
    … …  
    161158     */
    162159    public function render_dashboard() {
    163         $api = PrintSeek_API::instance();
    164         $connection = $api->check_connection();
     160        $connected = PrintSeek_Settings::instance()->verify_connection()['success'];
    165161       
    166162        // Get stats
    … …  
    176172            <div class="printseek-dashboard">
    177173                <!-- Connection Status Card -->
    178                 <div class="printseek-card printseek-connection-card <?php echo $connection['success'] ? 'connected' : 'disconnected'; ?>">
     174                <div class="printseek-card printseek-connection-card <?php echo $connected ? 'connected' : 'disconnected'; ?>">
    179175                    <div class="card-icon">
    180                     <?php if ($connection['success']): ?>
     176                    <?php if ($connected): ?>
    181177                            <span class="dashicons dashicons-yes-alt"></span>
    182178                    <?php else: ?>
    … …  
    186182                    <div class="card-content">
    187183                        <h3><?php esc_html_e('Connection Status', 'printseek'); ?></h3>
    188                         <?php if ($connection['success']): ?>
     184                        <?php if ($connected): ?>
    189185                            <p class="status-text connected"><?php esc_html_e('Connected to PrintSeek API', 'printseek'); ?></p>
    190186                            <?php if ($user_id): ?>
    … …  
    264260                            <span><?php esc_html_e('Settings', 'printseek'); ?></span>
    265261                        </a>
    266                         <a href="<?php echo esc_url('https://printsik.com'); ?>" target="_blank" class="action-btn">
     262                        <a href="<?php echo esc_url(PRINTSEEK_SITE_URL); ?>" target="_blank" class="action-btn">
    267263                            <span class="dashicons dashicons-external"></span>
    268264                            <span><?php esc_html_e('PrintSeek App', 'printseek'); ?></span>
    … …  
    303299                    <h2><span class="dashicons dashicons-sos"></span> <?php esc_html_e('Help & Support', 'printseek'); ?></h2>
    304300                    <div class="support-links">
    305                         <a href="<?php echo esc_url('https://printsik.com'); ?>" target="_blank" class="support-link">
     301                        <a href="<?php echo esc_url(PRINTSEEK_SITE_URL); ?>" target="_blank" class="support-link">
    306302                            <span class="dashicons dashicons-admin-site"></span>
    307303                            <span><?php esc_html_e('Visit PrintSeek', 'printseek'); ?></span>
    308304                        </a>
    309                         <a href="<?php echo esc_url('https://printsik.com/contact-us'); ?>" target="_blank" class="support-link">
     305                        <a href="<?php echo esc_url('mailto:' . PRINTSEEK_SUPPORT_EMAIL); ?>" class="support-link">
    310306                            <span class="dashicons dashicons-email"></span>
    311307                            <span><?php esc_html_e('Contact Support', 'printseek'); ?></span>
    … …  
    497493                                <?php
    498494                                if (!$order) continue;
    499                                 $printseek_status = $order->get_meta('_printseek_status') ?: 'synced';
    500495                                $printseek_order_id = $order->get_meta('_printseek_order_id');
    501496                                ?>
    … …  
    504499                                        <strong>#<?php echo esc_html($order->get_order_number()); ?></strong>
    505500                                        <?php if ($printseek_order_id): ?>
    506                                             <br><small class="printseek-id"><?php esc_html_e('PS:', 'printseek'); ?> <?php echo esc_html(substr($printseek_order_id, 0, 15)); ?>...</small>
     501                                            <br><small class="printseek-id"><?php echo esc_html($printseek_order_id); ?></small>
    507502                                        <?php endif; ?>
    508503                                    </td>
    … …  
    521516                                    </td>
    522517                                    <td class="order-status">
    523                                         <span class="status-badge <?php echo esc_attr($printseek_status); ?>">
    524                                             <?php
    525                                             $status_labels = array(
    526                                                 'synced' => __('Synced', 'printseek'),
    527                                                 'processing' => __('Processing', 'printseek'),
    528                                                 'shipped' => __('Shipped', 'printseek'),
    529                                                 'delivered' => __('Delivered', 'printseek'),
    530                                             );
    531                                             echo esc_html($status_labels[$printseek_status] ?? ucfirst($printseek_status));
    532                                             ?>
    533                                         </span>
     518                                        <span class="status-badge synced"><?php esc_html_e('Synced', 'printseek'); ?></span>
    534519                                    </td>
    535520                                    <td class="order-actions">
  • printseek/trunk/includes/admin/class-printseek-settings.php

    r3430355 r3848522  
    22/**
    33 * PrintSeek Settings
     4 *
     5 * Both settings forms post to `admin-post.php?action=printseek_save_settings`; each saves only its own fields.
    46 */
    57
    … …  
    911
    1012class PrintSeek_Settings {
    11    
     13
    1214    /**
    1315     * Single instance
    1416     */
    1517    protected static $_instance = null;
    16    
     18
    1719    /**
    1820     * Instance
    … …  
    2426        return self::$_instance;
    2527    }
    26    
     28
    2729    /**
    2830     * Constructor
    2931     */
    3032    public function __construct() {
    31         // Register settings
    32         add_action('admin_init', array($this, 'register_settings'));
    33        
    34         // Handle settings form submission
    3533        add_action('admin_post_printseek_save_settings', array($this, 'save_settings'));
    3634    }
    37    
    38     /**
    39      * Register settings
    40      */
    41     public function register_settings() {
    42         register_setting('printseek_settings', 'printseek_api_key', array(
    43             'type' => 'string',
    44             'sanitize_callback' => 'sanitize_text_field',
    45             'default' => '',
    46         ));
    47         register_setting('printseek_settings', 'printseek_user_id', array(
    48             'type' => 'string',
    49             'sanitize_callback' => 'sanitize_text_field',
    50             'default' => '',
    51         ));
    52         register_setting('printseek_settings', 'printseek_auto_sync_orders', array(
    53             'type' => 'string',
    54             'sanitize_callback' => 'sanitize_text_field',
    55             'default' => 'yes',
    56         ));
    57         register_setting('printseek_settings', 'printseek_auto_sync_products', array(
    58             'type' => 'string',
    59             'sanitize_callback' => 'sanitize_text_field',
    60             'default' => 'no',
    61         ));
    62         register_setting('printseek_settings', 'printseek_webhook_secret', array(
    63             'type' => 'string',
    64             'sanitize_callback' => 'sanitize_text_field',
    65             'default' => '',
    66         ));
    67         register_setting('printseek_settings', 'printseek_debug_mode', array(
    68             'type' => 'string',
    69             'sanitize_callback' => 'sanitize_text_field',
    70             'default' => 'no',
    71         ));
    72     }
    73    
     35
     36    /**
     37     * Verify the saved API key with PrintSeek; on success keeps the account's user id.
     38     *
     39     * @return array { success: bool, error?: string }
     40     */
     41    public function verify_connection() {
     42        $api = PrintSeek_API::instance();
     43        $api->reload_credentials();
     44        $response = $api->verify_plugin();
     45
     46        if (empty($response['success'])) {
     47            return array(
     48                'success' => false,
     49                'error'   => isset($response['error']) ? $response['error'] : __('Failed to connect to PrintSeek API', 'printseek'),
     50            );
     51        }
     52
     53        update_option('printseek_user_id', sanitize_text_field($response['data']['userId']));
     54        return array('success' => true);
     55    }
     56
    7457    /**
    7558     * Render settings page
    7659     */
    7760    public function render_settings_page() {
    78         // Check if connection test was triggered
    79         $connection_test = null;
    80         if (isset($_POST['test_connection']) && check_admin_referer('printseek_test_connection')) {
    81             $api = PrintSeek_API::instance();
    82             $connection_test = $api->check_connection();
    83            
    84             // Auto-extract User ID on successful connection
    85             if ($connection_test['success']) {
    86                 $api_key = get_option('printseek_api_key', '');
    87                 $current_user_id = get_option('printseek_user_id', '');
    88                
    89                 if (!empty($api_key) && empty($current_user_id)) {
    90                     $verify_response = $api->verify_credentials($api_key);
    91                    
    92                     if (isset($verify_response['success']) && $verify_response['success']) {
    93                         $user_id = '';
    94                         if (isset($verify_response['data']['user']['_id'])) {
    95                             $user_id = $verify_response['data']['user']['_id'];
    96                         } elseif (isset($verify_response['data']['auth']['user']['_id'])) {
    97                             $user_id = $verify_response['data']['auth']['user']['_id'];
    98                         }
    99                        
    100                         if (!empty($user_id)) {
    101                             update_option('printseek_user_id', $user_id);
    102                             $connection_test['message'] = __('Connection successful! User ID auto-detected.', 'printseek');
    103                         }
    104                     }
    105                 }
    106             }
    107         }
    108        
     61        // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only notice after the redirect of save_settings()
     62        $notice = isset($_GET['printseek_notice']) ? sanitize_key(wp_unslash($_GET['printseek_notice'])) : '';
     63        // phpcs:enable WordPress.Security.NonceVerification.Recommended
     64        $connection_error = get_transient('printseek_connection_error');
     65        delete_transient('printseek_connection_error');
     66
    10967        $api_key = get_option('printseek_api_key', '');
    11068        $user_id = get_option('printseek_user_id', '');
    … …  
    11573            <h1 class="printseek-page-title"><?php esc_html_e('PrintSeek Settings', 'printseek'); ?></h1>
    11674           
    117             <?php if (isset($_GET['settings-updated'])): // phpcs:ignore WordPress.Security.NonceVerification.Recommended ?>
     75            <?php if ($notice === 'saved'): ?>
    11876                <div class="printseek-alert printseek-alert-success">
    11977                    <span class="dashicons dashicons-yes-alt"></span>
    12078                    <div>
    12179                        <strong><?php esc_html_e('Settings Saved!', 'printseek'); ?></strong>
    122                         <p><?php esc_html_e('Your settings have been saved successfully. Test the API connection below to verify everything is working.', 'printseek'); ?></p>
     80                    </div>
     81                </div>
     82            <?php elseif ($notice === 'connected'): ?>
     83                <div class="printseek-alert printseek-alert-success">
     84                    <span class="dashicons dashicons-yes-alt"></span>
     85                    <div>
     86                        <strong><?php esc_html_e('Connection Successful!', 'printseek'); ?></strong>
     87                        <p><?php esc_html_e('Your store is connected to PrintSeek API.', 'printseek'); ?></p>
     88                    </div>
     89                </div>
     90            <?php elseif ($notice === 'failed'): ?>
     91                <div class="printseek-alert printseek-alert-error">
     92                    <span class="dashicons dashicons-warning"></span>
     93                    <div>
     94                        <strong><?php esc_html_e('Connection Failed', 'printseek'); ?></strong>
     95                        <p><?php echo esc_html($connection_error); ?></p>
    12396                    </div>
    12497                </div>
    12598            <?php endif; ?>
    126            
    127             <?php if ($connection_test): ?>
    128                 <?php if ($connection_test['success']): ?>
    129                     <div class="printseek-alert printseek-alert-success">
    130                         <span class="dashicons dashicons-yes-alt"></span>
    131                         <div>
    132                             <strong><?php esc_html_e('Connection Successful!', 'printseek'); ?></strong>
    133                             <p><?php echo isset($connection_test['message']) ? esc_html($connection_test['message']) : esc_html__('Your store is connected to PrintSeek API.', 'printseek'); ?></p>
    134                         </div>
    135                     </div>
    136                 <?php else: ?>
    137                     <div class="printseek-alert printseek-alert-error">
    138                         <span class="dashicons dashicons-warning"></span>
    139                         <div>
    140                             <strong><?php esc_html_e('Connection Failed', 'printseek'); ?></strong>
    141                             <p><?php echo esc_html($connection_test['error']); ?></p>
    142                         </div>
    143                     </div>
    144                 <?php endif; ?>
    145             <?php endif; ?>
    146            
     99
    147100            <div class="printseek-settings-grid">
    148101                <!-- API Credentials Card -->
    … …  
    155108                        <p class="card-description"><?php esc_html_e('Enter your PrintSeek API credentials to connect your store.', 'printseek'); ?></p>
    156109                       
    157                         <form method="post" action="options.php" class="printseek-form">
    158                             <?php settings_fields('printseek_settings'); ?>
    159                            
     110                        <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" class="printseek-form">
     111                            <?php $this->form_fields('credentials'); ?>
     112
    160113                            <div class="form-group">
    161114                                <label for="printseek_api_key">
    … …  
    173126                                <p class="help-text"><?php esc_html_e('Find this in PrintSeek Dashboard → Connected Stores → WooCommerce', 'printseek'); ?></p>
    174127                            </div>
    175                            
    176                             <div class="form-group">
    177                                 <label for="printseek_user_id"><?php esc_html_e('User ID', 'printseek'); ?></label>
    178                                 <input
    179                                     type="text"
    180                                     id="printseek_user_id"
    181                                     name="printseek_user_id"
    182                                     value="<?php echo esc_attr($user_id); ?>"
    183                                     class="form-input"
    184                                     placeholder="<?php esc_attr_e('Auto-detected from API key', 'printseek'); ?>"
    185                                 />
    186                                 <p class="help-text"><?php esc_html_e('Optional - Will be auto-detected when you test the connection.', 'printseek'); ?></p>
    187                             </div>
    188                            
    189                             <div class="form-group">
    190                                 <label for="printseek_webhook_secret"><?php esc_html_e('Webhook Secret', 'printseek'); ?></label>
    191                                 <input
    192                                     type="text"
    193                                     id="printseek_webhook_secret"
    194                                     name="printseek_webhook_secret"
    195                                     value="<?php echo esc_attr(get_option('printseek_webhook_secret')); ?>"
    196                                     class="form-input"
    197                                     placeholder="<?php esc_attr_e('Enter webhook secret', 'printseek'); ?>"
    198                                 />
    199                                 <p class="help-text"><?php esc_html_e('For verifying webhook requests from PrintSeek.', 'printseek'); ?></p>
    200                             </div>
    201                            
    202                             <div class="webhook-url-box">
    203                                 <label><?php esc_html_e('Your Webhook URL', 'printseek'); ?></label>
    204                                 <div class="url-display">
    205                                     <code id="webhook-url"><?php echo esc_url(rest_url('printseek/v1/webhook')); ?></code>
    206                                     <button type="button" class="copy-btn" onclick="copyWebhookUrl()">
    207                                         <span class="dashicons dashicons-admin-page"></span>
    208                                     </button>
    209                                 </div>
    210                                 <p class="help-text"><?php esc_html_e('Add this URL in your PrintSeek dashboard to receive order updates.', 'printseek'); ?></p>
    211                             </div>
    212                            
     128
    213129                            <div class="form-actions">
    214130                                <button type="submit" class="btn btn-primary">
    … …  
    253169                        </div>
    254170                       
    255                         <form method="post" class="test-connection-form">
    256                             <?php wp_nonce_field('printseek_test_connection'); ?>
     171                        <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" class="test-connection-form">
     172                            <?php $this->form_fields('test'); ?>
    257173                            <button type="submit" name="test_connection" class="btn btn-secondary btn-full" <?php echo !$is_configured ? 'disabled' : ''; ?>>
    258174                                <span class="dashicons dashicons-update"></span>
    … …  
    263179                        <div class="info-box">
    264180                            <span class="dashicons dashicons-info"></span>
    265                             <p><?php esc_html_e('After saving your API key, click "Test API Connection" to verify everything is working correctly.', 'printseek'); ?></p>
     181                            <p><?php esc_html_e('Saving the API key verifies it with PrintSeek. Use "Test API Connection" to check it again.', 'printseek'); ?></p>
    266182                        </div>
    267183                    </div>
    … …  
    275191                    </div>
    276192                    <div class="card-body">
    277                         <form method="post" action="options.php" class="printseek-form">
    278                             <?php settings_fields('printseek_settings'); ?>
    279                             <!-- Hidden fields to preserve API credentials -->
    280                             <input type="hidden" name="printseek_api_key" value="<?php echo esc_attr($api_key); ?>" />
    281                             <input type="hidden" name="printseek_user_id" value="<?php echo esc_attr($user_id); ?>" />
    282                             <input type="hidden" name="printseek_webhook_secret" value="<?php echo esc_attr(get_option('printseek_webhook_secret')); ?>" />
     193                        <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" class="printseek-form">
     194                            <?php $this->form_fields('sync'); ?>
    283195                           
    284196                            <div class="toggle-group">
    … …  
    334246                    <div class="card-body">
    335247                        <div class="help-links">
    336                             <a href="<?php echo esc_url('https://printsik.com'); ?>" target="_blank" class="help-link">
     248                            <a href="<?php echo esc_url(PRINTSEEK_SITE_URL); ?>" target="_blank" class="help-link">
    337249                                <span class="dashicons dashicons-admin-home"></span>
    338250                                <span><?php esc_html_e('Visit PrintSeek', 'printseek'); ?></span>
    339251                            </a>
    340                             <a href="<?php echo esc_url('https://printsik.com/contact-us'); ?>" target="_blank" class="help-link">
     252                            <a href="<?php echo esc_url('mailto:' . PRINTSEEK_SUPPORT_EMAIL); ?>" class="help-link">
    341253                                <span class="dashicons dashicons-email"></span>
    342254                                <span><?php esc_html_e('Contact Support', 'printseek'); ?></span>
    … …  
    348260                            <ol>
    349261                                <li><?php esc_html_e('Get your API Key from PrintSeek Dashboard', 'printseek'); ?></li>
    350                                 <li><?php esc_html_e('Enter the API Key above and Save', 'printseek'); ?></li>
    351                                 <li><?php esc_html_e('Click "Test API Connection" to verify', 'printseek'); ?></li>
     262                                <li><?php esc_html_e('Enter the API Key above and Save — it is verified right away', 'printseek'); ?></li>
    352263                                <li><?php esc_html_e('Start linking products for fulfillment!', 'printseek'); ?></li>
    353264                            </ol>
    … …  
    361272   
    362273    /**
    363      * Save settings
     274     * Action, section and nonce of a settings form.
     275     *
     276     * @param string $section credentials | test | sync
     277     */
     278    private function form_fields($section) {
     279        ?>
     280        <input type="hidden" name="action" value="printseek_save_settings" />
     281        <input type="hidden" name="section" value="<?php echo esc_attr($section); ?>" />
     282        <?php
     283        wp_nonce_field('printseek_save_settings');
     284    }
     285
     286    /**
     287     * Save one settings form, then back to the settings page with a notice.
    364288     */
    365289    public function save_settings() {
    … …  
    367291            wp_die(esc_html__('Permission denied', 'printseek'));
    368292        }
    369        
    370         check_admin_referer('printseek_settings-options');
    371        
    372         // phpcs:disable WordPress.Security.ValidatedSanitizedInput.InputNotValidated -- Nonce verified above
    373         $api_key = isset($_POST['printseek_api_key']) ? sanitize_text_field(wp_unslash($_POST['printseek_api_key'])) : '';
    374         $user_id = isset($_POST['printseek_user_id']) ? sanitize_text_field(wp_unslash($_POST['printseek_user_id'])) : '';
    375         $webhook_secret = isset($_POST['printseek_webhook_secret']) ? sanitize_text_field(wp_unslash($_POST['printseek_webhook_secret'])) : '';
    376         // phpcs:enable WordPress.Security.ValidatedSanitizedInput.InputNotValidated
    377        
    378         // Auto-detect User ID from API key if not provided
    379         if (empty($user_id) && !empty($api_key)) {
    380             $api = PrintSeek_API::get_instance();
    381             $verify_response = $api->verify_credentials($api_key);
    382            
    383             if (isset($verify_response['success']) && $verify_response['success']) {
    384                 // Extract user ID from response
    385                 if (isset($verify_response['data']['user']['_id'])) {
    386                     $user_id = $verify_response['data']['user']['_id'];
    387                 } elseif (isset($verify_response['data']['auth']['user']['_id'])) {
    388                     $user_id = $verify_response['data']['auth']['user']['_id'];
     293        check_admin_referer('printseek_save_settings');
     294
     295        $section = isset($_POST['section']) ? sanitize_key(wp_unslash($_POST['section'])) : '';
     296        $notice = 'saved';
     297
     298        switch ($section) {
     299            case 'credentials':
     300                $api_key = isset($_POST['printseek_api_key']) ? sanitize_text_field(wp_unslash($_POST['printseek_api_key'])) : '';
     301                if ($api_key !== get_option('printseek_api_key')) {
     302                    update_option('printseek_api_key', $api_key);
     303                    delete_option('printseek_user_id');
    389304                }
    390             }
    391         }
    392        
    393         // Save settings
    394         update_option('printseek_api_key', $api_key);
    395         update_option('printseek_user_id', $user_id);
    396         update_option('printseek_auto_sync_orders', isset($_POST['printseek_auto_sync_orders']) ? 'yes' : 'no');
    397         update_option('printseek_webhook_secret', $webhook_secret);
    398         update_option('printseek_debug_mode', isset($_POST['printseek_debug_mode']) ? 'yes' : 'no');
    399        
    400         wp_safe_redirect(add_query_arg('settings-updated', 'true', wp_get_referer()));
     305                $notice = $api_key === '' ? 'saved' : $this->connection_notice();
     306                break;
     307            case 'test':
     308                $notice = $this->connection_notice();
     309                break;
     310            case 'sync':
     311                update_option('printseek_auto_sync_orders', isset($_POST['printseek_auto_sync_orders']) ? 'yes' : 'no');
     312                update_option('printseek_debug_mode', isset($_POST['printseek_debug_mode']) ? 'yes' : 'no');
     313                break;
     314            default:
     315                wp_die(esc_html__('Unknown settings form', 'printseek'));
     316        }
     317
     318        wp_safe_redirect(add_query_arg('printseek_notice', $notice, admin_url('admin.php?page=printseek-settings')));
    401319        exit;
    402320    }
     321
     322    /**
     323     * @return string connected | failed (the error is kept for the next page view)
     324     */
     325    private function connection_notice() {
     326        $result = $this->verify_connection();
     327        if ($result['success']) {
     328            return 'connected';
     329        }
     330        set_transient('printseek_connection_error', $result['error'], MINUTE_IN_SECONDS);
     331        return 'failed';
     332    }
    403333}
  • printseek/trunk/includes/class-printseek-api.php

    r3430355 r3848522  
    4545   
    4646    /**
    47      * User ID from PrintSeek
    48      *
    49      * @var string
    50      * @since 1.0.0
    51      */
    52     private $user_id;
    53    
    54     /**
    5547     * Instance
    5648     *
    … …  
    7365        $this->api_url = PRINTSEEK_API_URL;
    7466        $this->api_key = get_option('printseek_api_key', '');
    75         $this->user_id = get_option('printseek_user_id', '');
    7667    }
    7768   
    … …  
    8374    public function reload_credentials() {
    8475        $this->api_key = get_option('printseek_api_key', '');
    85         $this->user_id = get_option('printseek_user_id', '');
    8676    }
    8777   
    … …  
    143133   
    144134    /**
    145      * Verify API credentials
    146      *
    147      * @since 1.0.0
    148      * @param string $api_key API key to verify
     135     * Verify the API key with PrintSeek and register this site's plugin.
     136     * Returns the store's userId and webhookSecret on success.
     137     *
     138     * @since 1.0.0
    149139     * @return array Response
    150140     */
    151     public function verify_credentials($api_key) {
    152         $temp_key = $this->api_key;
    153         $this->api_key = $api_key;
    154        
    155         $response = $this->request('api/auth/verify-token');
    156        
    157         $this->api_key = $temp_key;
    158        
    159         return $response;
    160     }
    161    
    162     /**
    163      * Verify plugin installation with PrintSeek
    164      *
    165      * @since 1.0.0
    166      * @return array Response
    167      */
    168141    public function verify_plugin() {
     142        if (empty($this->api_key)) {
     143            return array(
     144                'success' => false,
     145                'error'   => __('API key not configured', 'printseek')
     146            );
     147        }
     148
    169149        $data = array(
    170150            'siteUrl'       => get_site_url(),
    … …  
    173153            'wcVersion'     => defined('WC_VERSION') ? WC_VERSION : 'unknown',
    174154        );
    175        
     155
    176156        return $this->request('woocommerce/plugin/verify', 'POST', $data);
    177157    }
    178    
    179     /**
    180      * Get user profile
    181      *
    182      * @since 1.0.0
     158
     159    /**
     160     * Send an order to PrintSeek
     161     *
     162     * @since 1.2.0
     163     * @param array $order_data WooCommerce order in the REST shape
    183164     * @return array Response
    184165     */
    185     public function get_user_profile() {
    186         return $this->request('api/auth/me');
    187     }
    188    
    189     /**
    190      * Create order in PrintSeek
    191      *
    192      * @since 1.0.0
    193      * @param array $order_data Order data
    194      * @return array Response
    195      */
    196     public function create_order($order_data) {
    197         return $this->request('woocommerce/orders/sync', 'POST', $order_data);
    198     }
    199    
    200     /**
    201      * Sync order to PrintSeek (from WooCommerce)
    202      *
    203      * @since 1.0.0
    204      * @param array $order_data Order data
    205      * @return array Response
    206      */
    207     public function push_product($order_data) {
    208         return $this->request('woocommerce/orders/sync', 'POST', $order_data);
    209     }
    210    
    211     /**
    212      * Get orders from PrintSeek
    213      *
    214      * @since 1.0.0
    215      * @param array $params Query parameters
    216      * @return array Response
    217      */
    218     public function get_orders($params = array()) {
    219         $query_string = http_build_query($params);
    220         $endpoint = 'api/orders' . ($query_string ? '?' . $query_string : '');
    221        
    222         return $this->request($endpoint);
    223     }
    224    
    225     /**
    226      * Get single order
    227      *
    228      * @since 1.0.0
    229      * @param string $order_id Order ID
    230      * @return array Response
    231      */
    232     public function get_order($order_id) {
    233         return $this->request('api/orders/' . sanitize_text_field($order_id));
    234     }
    235    
    236     /**
    237      * Update order status
    238      *
    239      * @since 1.0.0
    240      * @param string $order_id Order ID
    241      * @param string $status New status
    242      * @return array Response
    243      */
    244     public function update_order_status($order_id, $status) {
    245         return $this->request('api/orders/' . sanitize_text_field($order_id), 'PATCH', array(
    246             'status' => sanitize_text_field($status)
     166    public function sync_order($order_data) {
     167        return $this->request('woocommerce/orders/sync', 'POST', array(
     168            'siteUrl' => get_site_url(),
     169            'order'   => $order_data,
    247170        ));
    248171    }
    249    
    250     /**
    251      * Place order for fulfillment
    252      *
    253      * @since 1.0.0
    254      * @param string $order_id Order ID
    255      * @return array Response
    256      */
    257     public function place_order($order_id) {
    258         return $this->request('api/orders/' . sanitize_text_field($order_id) . '/place', 'POST');
    259     }
    260    
    261     /**
    262      * Get product types/catalog
    263      *
    264      * @since 1.0.0
    265      * @return array Response
    266      */
    267     public function get_product_types() {
    268         return $this->request('api/product-types');
    269     }
    270    
    271     /**
    272      * Upload design file
    273      *
    274      * @since 1.0.0
    275      * @param string $file_path Path to file
    276      * @param string $design_type Design type (front, back, etc.)
    277      * @return array Response
    278      */
    279     public function upload_design($file_path, $design_type = 'front') {
    280         if (!file_exists($file_path)) {
    281             return array(
    282                 'success' => false,
    283                 'error'   => __('File not found', 'printseek')
    284             );
    285         }
    286        
    287         $url = trailingslashit($this->api_url) . 'api/uploads';
    288        
    289         $boundary = wp_generate_password(24, false);
    290        
    291         $headers = array(
    292             'Authorization' => 'Bearer ' . $this->api_key,
    293             'Content-Type'  => 'multipart/form-data; boundary=' . $boundary,
    294         );
    295        
    296         // Read file safely
    297         $file_contents = file_get_contents($file_path);
    298         if ($file_contents === false) {
    299             return array(
    300                 'success' => false,
    301                 'error'   => __('Could not read file', 'printseek')
    302             );
    303         }
    304        
    305         $filename = basename($file_path);
    306         $mime_type = wp_check_filetype($file_path)['type'] ?: 'application/octet-stream';
    307        
    308         $body = '';
    309         $body .= '--' . $boundary . "\r\n";
    310         $body .= 'Content-Disposition: form-data; name="' . $design_type . '"; filename="' . $filename . '"' . "\r\n";
    311         $body .= 'Content-Type: ' . $mime_type . "\r\n\r\n";
    312         $body .= $file_contents . "\r\n";
    313         $body .= '--' . $boundary . '--';
    314        
    315         $args = array(
    316             'headers' => $headers,
    317             'body'    => $body,
    318             'timeout' => 60,
    319         );
    320        
    321         $response = wp_remote_post($url, $args);
    322        
    323         if (is_wp_error($response)) {
    324             return array(
    325                 'success' => false,
    326                 'error'   => $response->get_error_message()
    327             );
    328         }
    329        
    330         $body = wp_remote_retrieve_body($response);
    331         return json_decode($body, true);
    332     }
    333    
    334     /**
    335      * Check connection status
    336      *
    337      * @since 1.0.0
    338      * @return array Response
    339      */
    340     public function check_connection() {
    341         if (empty($this->api_key)) {
    342             return array(
    343                 'success' => false,
    344                 'error'   => __('API key not configured', 'printseek')
    345             );
    346         }
    347        
    348         $response = $this->request('woocommerce/health');
    349        
    350         if (isset($response['success']) && $response['success']) {
    351             return array(
    352                 'success' => true,
    353                 'message' => __('Connected to PrintSeek API', 'printseek')
    354             );
    355         }
    356        
    357         // Try alternative health check
    358         $response = $this->request('api/health');
    359        
    360         if (isset($response['success']) && $response['success']) {
    361             return array(
    362                 'success' => true,
    363                 'message' => __('Connected to PrintSeek API', 'printseek')
    364             );
    365         }
    366        
    367         return array(
    368             'success' => false,
    369             'error'   => __('Failed to connect to PrintSeek API', 'printseek')
    370         );
    371     }
    372    
     172
    373173    /**
    374174     * Send webhook to PrintSeek
  • printseek/trunk/includes/class-printseek-order-sync.php

    r3430355 r3848522  
    22/**
    33 * PrintSeek Order Sync
    4  * Handles order sync from PrintSeek to WooCommerce
     4 *
     5 * Sends orders with products pushed from PrintSeek to PrintSeek once they are paid (or COD) — status
     6 * `processing`/`completed` — and reports later status changes (e.g. a cancellation) of synced orders.
    57 */
    68
    … …  
    1012
    1113class PrintSeek_Order_Sync {
    12    
     14
     15    /**
     16     * WooCommerce statuses at which an order is ready to be printed.
     17     */
     18    const SYNC_STATUSES = array('processing', 'completed');
     19
    1320    /**
    1421     * Single instance
    1522     */
    1623    protected static $_instance = null;
    17    
     24
    1825    /**
    1926     * Instance
    … …  
    2532        return self::$_instance;
    2633    }
    27    
     34
    2835    /**
    2936     * Constructor
    3037     */
    3138    public function __construct() {
    32         // Hook into WooCommerce order creation
    33         add_action('woocommerce_new_order', array($this, 'sync_new_order'), 10, 1);
    34        
    35         // Hook into order status changes
    36         add_action('woocommerce_order_status_changed', array($this, 'sync_order_status'), 10, 3);
    37        
    38         // Add order meta box
     39        // Fires on checkout too (pending → processing), when the order already has its items.
     40        add_action('woocommerce_order_status_changed', array($this, 'on_status_changed'), 10, 4);
     41
    3942        add_action('add_meta_boxes', array($this, 'add_order_meta_box'));
    40        
    41         // Manual sync action
    42         add_action('wp_ajax_printseek_sync_orders', array($this, 'ajax_sync_orders'));
    4343        add_action('wp_ajax_printseek_sync_single_order', array($this, 'ajax_sync_single_order'));
    44        
    45         // Cron job for order status updates
    46         add_action('printseek_sync_order_status', array($this, 'sync_order_status_from_printseek'));
    47        
    48         // Schedule cron if not scheduled
    49         if (!wp_next_scheduled('printseek_sync_order_status')) {
    50             wp_schedule_event(time(), 'hourly', 'printseek_sync_order_status');
    51         }
    52     }
    53    
    54     /**
    55      * Sync new order to PrintSeek
    56      */
    57     public function sync_new_order($order_id) {
    58         // Check if auto sync is enabled
    59         if (get_option('printseek_auto_sync_orders') !== 'yes') {
     44    }
     45
     46    /**
     47     * Synced orders report the new status; others are sent once they reach a sync status.
     48     */
     49    public function on_status_changed($order_id, $old_status, $new_status, $order) {
     50        if ($this->is_synced($order)) {
     51            PrintSeek_API::instance()->send_webhook(array(
     52                'event'    => 'order.status_updated',
     53                'order_id' => $order->get_id(),
     54                'status'   => $new_status,
     55            ));
    6056            return;
    6157        }
    62        
    63         $order = wc_get_order($order_id);
    64        
    65         if (!$order) {
     58
     59        if (get_option('printseek_auto_sync_orders') !== 'yes' || !in_array($new_status, self::SYNC_STATUSES, true)) {
    6660            return;
    6761        }
    68        
    69         // Check if order contains PrintSeek products
    70         $has_printseek_products = false;
    71        
    72         foreach ($order->get_items() as $item) {
    73             $product_id = $item->get_product_id();
    74             $is_pushed = get_post_meta($product_id, '_printseek_pushed', true);
    75            
    76             if ($is_pushed) {
    77                 $has_printseek_products = true;
    78                 break;
    79             }
    80         }
    81        
    82         if (!$has_printseek_products) {
    83             return;
    84         }
    85        
    86         // Sync order
    87         $this->push_order_to_printseek($order_id);
    88     }
    89    
    90     /**
    91      * Push order to PrintSeek
    92      */
    93     public function push_order_to_printseek($order_id) {
    94         $order = wc_get_order($order_id);
    95        
    96         if (!$order) {
    97             return array(
    98                 'success' => false,
    99                 'message' => __('Order not found', 'printseek')
    100             );
    101         }
    102        
    103         // Check if already synced
    104         $printseek_order_id = $order->get_meta('_printseek_order_id');
    105         $already_synced = $order->get_meta('_printseek_synced');
    106        
    107         if ($printseek_order_id && ($already_synced === 'yes' || $already_synced === '1' || $already_synced === true)) {
     62
     63        if ($this->printseek_items($order)) {
     64            $this->push_order_to_printseek($order);
     65        }
     66    }
     67
     68    /**
     69     * Send an order to PrintSeek (once).
     70     *
     71     * @param WC_Order $order
     72     * @return array { success: bool, message: string }
     73     */
     74    public function push_order_to_printseek($order) {
     75        if ($this->is_synced($order)) {
    10876            return array(
    10977                'success' => true,
    11078                'message' => __('Order already synced to PrintSeek!', 'printseek'),
    111                 'order_id' => $printseek_order_id
    112             );
    113         }
    114        
    115         // Prepare order data
    116         $order_data = $this->prepare_order_data($order);
    117        
    118         // Send to API - always create new
    119         $api = PrintSeek_API::instance();
    120         $response = $api->push_product($order_data);
    121        
    122         if (isset($response['success']) && $response['success']) {
    123             $order_id_from_api = isset($response['data']['orderId']) ? $response['data']['orderId'] : '';
    124            
    125             // Save metadata - use 'yes' string for consistency with WordPress
    126             $order->update_meta_data('_printseek_synced', 'yes');
    127             $order->update_meta_data('_printseek_order_id', $order_id_from_api);
    128             $order->update_meta_data('_printseek_synced_at', current_time('mysql'));
    129             $order->save();
    130            
    131             // Add order note
    132             $order->add_order_note(__('Order synced to PrintSeek. Order ID: ', 'printseek') . $order_id_from_api);
    133            
    134             return array(
    135                 'success' => true,
    136                 'message' => __('Order synced successfully!', 'printseek'),
    137                 'order_id' => $order_id_from_api
    138             );
    139         } else {
    140             $error_message = isset($response['error']) ? $response['error'] : __('Unknown error', 'printseek');
    141            
    142             // Add order note
    143             $order->add_order_note(__('Failed to sync to PrintSeek: ', 'printseek') . $error_message);
    144            
     79            );
     80        }
     81
     82        $items = $this->printseek_items($order);
     83        if (!$items) {
    14584            return array(
    14685                'success' => false,
    147                 'message' => $error_message
    148             );
    149         }
    150     }
    151    
    152     /**
    153      * Prepare order data for API
    154      */
    155     private function prepare_order_data($order) {
    156         $items = array();
    157         $variants = array();
    158         $total_quantity = 0;
    159         $selected_colors = array();
    160         $selected_sizes = array();
    161        
    162         foreach ($order->get_items() as $item) {
    163             $product = $item->get_product();
    164             $product_id = $item->get_product_id();
    165            
    166             // Only include PrintSeek products
    167             $is_pushed = get_post_meta($product_id, '_printseek_pushed', true);
    168             if (!$is_pushed) {
    169                 continue;
    170             }
    171            
    172             $quantity = $item->get_quantity();
    173             $total_quantity += $quantity;
    174            
    175             $image_url = wp_get_attachment_url($product->get_image_id());
    176            
    177             // Get product type and variant from meta
    178             $product_type = get_post_meta($product_id, '_printseek_product_type', true);
    179             $variant_type = get_post_meta($product_id, '_printseek_variant', true);
    180            
    181             // Extract color and size from WooCommerce variation attributes
    182             $color = '';
    183             $size = '';
    184            
    185             // Check if this is a variation product
    186             if ($product && $product->is_type('variation')) {
    187                 $variation_attrs = $product->get_variation_attributes();
    188                 foreach ($variation_attrs as $attr_name => $attr_value) {
    189                     $attr_name_lower = strtolower($attr_name);
    190                     if (strpos($attr_name_lower, 'color') !== false || strpos($attr_name_lower, 'colour') !== false) {
    191                         $color = ucfirst($attr_value);
    192                     } elseif (strpos($attr_name_lower, 'size') !== false) {
    193                         $size = strtoupper($attr_value);
    194                     }
    195                 }
    196             }
    197            
    198             // Also check item meta for variations (WooCommerce stores selected attrs here)
    199             $item_meta = $item->get_meta_data();
    200             foreach ($item_meta as $meta) {
    201                 $meta_data = $meta->get_data();
    202                 $key_lower = strtolower($meta_data['key'] ?? '');
    203                 $meta_value = $meta_data['value'] ?? '';
    204                
    205                 // Skip if value is empty
    206                 if (empty($meta_value)) {
    207                     continue;
    208                 }
    209                
    210                 if (strpos($key_lower, 'color') !== false || strpos($key_lower, 'colour') !== false || $key_lower === 'pa_color' || $key_lower === 'pa_colour') {
    211                     $color = ucfirst($meta_value);
    212                 } elseif (strpos($key_lower, 'size') !== false || $key_lower === 'pa_size') {
    213                     // Normalize size to valid enum values (S, M, L, XL, XXL)
    214                     $raw_size = strtoupper($meta_value);
    215                     $size = $this->normalize_size($raw_size);
    216                 }
    217             }
    218            
    219             // Fallback: try to extract from product name (e.g., "T-Shirt - Black, M")
    220             if (empty($color) || empty($size)) {
    221                 $item_name = $item->get_name();
    222                 if (preg_match('/[-–]\s*([^,]+),\s*([A-Z]{1,3}L?)\s*$/i', $item_name, $matches)) {
    223                     if (empty($color)) {
    224                         $color = trim($matches[1]);
    225                     }
    226                     if (empty($size)) {
    227                         $size = $this->normalize_size(trim($matches[2]));
    228                     }
    229                 }
    230             }
    231            
    232             // Default values if still empty
    233             if (empty($color)) {
    234                 $color = 'Default';
    235             }
    236             if (empty($size)) {
    237                 $size = 'M';
    238             }
    239            
    240             // Add to variants array for frontend display
    241             $variants[] = array(
    242                 'id' => $product_id . '_' . count($variants),
    243                 'color' => $color,
    244                 'colorName' => $color,
    245                 'size' => $size,
    246                 'quantity' => $quantity,
    247             );
    248            
    249             // Track unique colors and sizes
    250             if (!in_array($color, $selected_colors)) {
    251                 $selected_colors[] = $color;
    252             }
    253             if (!in_array($size, $selected_sizes)) {
    254                 $selected_sizes[] = $size;
    255             }
    256            
    257             $items[] = array(
    258                 'product_id' => $product_id,
    259                 'product_name' => $item->get_name(),
    260                 'quantity' => $quantity,
    261                 'price' => floatval($item->get_total()),
    262                 'image_url' => $image_url,
    263                 'product_type' => $product_type ?: 'custom',
    264                 'variant' => $variant_type ?: 'standard',
    265                 'color' => $color,
    266                 'size' => $size,
    267             );
    268         }
    269        
    270         if (empty($items)) {
    271             return null;
    272         }
    273        
    274         // Get first item for main product data
    275         $first_item = $items[0];
    276        
    277         // Get customer name
    278         $first_name = $order->get_shipping_first_name() ?: $order->get_billing_first_name();
    279         $last_name = $order->get_shipping_last_name() ?: $order->get_billing_last_name();
    280         $full_name = trim($first_name . ' ' . $last_name);
    281         if (empty($full_name)) {
    282             $full_name = 'Customer';
    283         }
    284        
    285         // Get shipping address
    286         $shipping_address = array(
    287             'fullName' => $full_name,
    288             'firstName' => $first_name,
    289             'lastName' => $last_name,
    290             'phone' => $order->get_billing_phone(),
    291             'email' => $order->get_billing_email(),
    292             'addressLine1' => $order->get_shipping_address_1() ?: $order->get_billing_address_1(),
    293             'addressLine2' => $order->get_shipping_address_2() ?: $order->get_billing_address_2(),
    294             'city' => $order->get_shipping_city() ?: $order->get_billing_city(),
    295             'state' => $order->get_shipping_state() ?: $order->get_billing_state(),
    296             'pincode' => $order->get_shipping_postcode() ?: $order->get_billing_postcode(),
    297             'postalCode' => $order->get_shipping_postcode() ?: $order->get_billing_postcode(),
    298             'country' => $order->get_shipping_country() ?: $order->get_billing_country(),
     86                'message' => __('This order has no PrintSeek products.', 'printseek'),
     87            );
     88        }
     89
     90        $response = PrintSeek_API::instance()->sync_order($this->order_payload($order, $items));
     91
     92        if (empty($response['success'])) {
     93            $error_message = isset($response['error']) ? $response['error'] : __('Unknown error', 'printseek');
     94            $order->add_order_note(__('Failed to sync to PrintSeek: ', 'printseek') . $error_message);
     95            return array(
     96                'success' => false,
     97                'message' => $error_message,
     98            );
     99        }
     100
     101        $printseek_order_id = $response['data']['orderNumber'];
     102        $order->update_meta_data('_printseek_synced', 'yes');
     103        $order->update_meta_data('_printseek_order_id', $printseek_order_id);
     104        $order->update_meta_data('_printseek_synced_at', current_time('mysql'));
     105        $order->save();
     106        $order->add_order_note(__('Order synced to PrintSeek. Order ID: ', 'printseek') . $printseek_order_id);
     107
     108        return array(
     109            'success' => true,
     110            'message' => __('Order synced successfully!', 'printseek'),
    299111        );
    300        
    301         // Customer details for frontend display
    302         $customer_details = array(
    303             'name' => $full_name,
    304             'firstName' => $first_name,
    305             'lastName' => $last_name,
    306             'email' => $order->get_billing_email(),
    307             'phone' => $order->get_billing_phone(),
    308             'address' => $shipping_address['addressLine1'],
    309             'city' => $shipping_address['city'],
    310             'state' => $shipping_address['state'],
    311             'pincode' => $shipping_address['pincode'],
    312             'country' => $shipping_address['country'],
     112    }
     113
     114    /**
     115     * @param WC_Order $order
     116     */
     117    private function is_synced($order) {
     118        return $order->get_meta('_printseek_synced') === 'yes';
     119    }
     120
     121    /**
     122     * Lines of products pushed from PrintSeek.
     123     *
     124     * @param WC_Order $order
     125     * @return WC_Order_Item_Product[]
     126     */
     127    private function printseek_items($order) {
     128        return array_values(array_filter($order->get_items(), function ($item) {
     129            return get_post_meta($item->get_product_id(), '_printseek_pushed', true) === 'yes';
     130        }));
     131    }
     132
     133    /**
     134     * The order in the WooCommerce REST shape (`/wc/v3/orders/<id>`), with only the PrintSeek lines.
     135     *
     136     * @param WC_Order $order
     137     * @param WC_Order_Item_Product[] $items
     138     */
     139    private function order_payload($order, $items) {
     140        $date_paid = $order->get_date_paid();
     141
     142        return array(
     143            'id'             => $order->get_id(),
     144            'number'         => $order->get_order_number(),
     145            'status'         => $order->get_status(),
     146            'total'          => $order->get_total(),
     147            'payment_method' => $order->get_payment_method(),
     148            'date_paid'      => $date_paid ? $date_paid->date('c') : null,
     149            'billing'        => $order->get_address('billing'),
     150            'shipping'       => $order->get_address('shipping'),
     151            'line_items'     => array_map(array($this, 'line_payload'), $items),
    313152        );
    314        
    315         // Prepare data
    316         $data = array(
    317             'productName' => $first_item['product_name'],
    318             'productType' => $first_item['product_type'] ?: 'custom',
    319             'variant' => $first_item['variant'] ?: 'standard',
    320             'totalQuantity' => $total_quantity,
    321             'totalPrice' => floatval($order->get_total()),
    322             'paidAmount' => floatval($order->get_total()),
    323             'paymentStatus' => $order->is_paid() ? 'paid' : 'pending',
    324             'shippingType' => 'prepaid',
    325             'shippingAddress' => $shipping_address,
    326             'customerDetails' => $customer_details,
    327             'orderRemarks' => 'WooCommerce Order #' . $order->get_order_number(),
    328             'thumbnailUrl' => $first_item['image_url'],
    329             'source' => 'woocommerce',
    330             'woocommerceOrderId' => $order->get_id(),
    331             'orderNumber' => $order->get_order_number(),
    332             'siteUrl' => get_site_url(),
    333             // Variant details for frontend display (Color, Size, Quantity)
    334             'variants' => $variants,
    335             'selectedColors' => $selected_colors,
    336             'selectedSizes' => $selected_sizes,
     153    }
     154
     155    /**
     156     * One line; `meta_data` carries the chosen variation attributes (Colour, Size).
     157     * `$include_all` keeps the attributes WooCommerce otherwise hides because they are already in the item name.
     158     *
     159     * @param WC_Order_Item_Product $item
     160     */
     161    private function line_payload($item) {
     162        $meta_data = array();
     163        foreach ($item->get_formatted_meta_data('_', true) as $meta) {
     164            $meta_data[] = array(
     165                'key'   => $meta->display_key,
     166                'value' => trim(wp_strip_all_tags($meta->display_value)),
     167            );
     168        }
     169
     170        $image_id = $item->get_product() ? $item->get_product()->get_image_id() : 0;
     171
     172        return array(
     173            'product_id'   => $item->get_product_id(),
     174            'variation_id' => $item->get_variation_id(),
     175            'name'         => $item->get_name(),
     176            'quantity'     => $item->get_quantity(),
     177            'image'        => array('src' => $image_id ? wp_get_attachment_url($image_id) : ''),
     178            'meta_data'    => $meta_data,
    337179        );
    338        
    339         return $data;
    340     }
    341    
    342     /**
    343      * Sync order status changes
    344      */
    345     public function sync_order_status($order_id, $old_status, $new_status) {
    346         $order = wc_get_order($order_id);
    347        
    348         if (!$order) {
    349             return;
    350         }
    351        
    352         $printseek_order_id = $order->get_meta('_printseek_order_id');
    353        
    354         if (!$printseek_order_id) {
    355             return;
    356         }
    357        
    358         // Map WooCommerce status to PrintSeek status
    359         $status_map = array(
    360             'processing' => 'processing',
    361             'completed' => 'delivered',
    362             'cancelled' => 'cancelled',
    363             'refunded' => 'cancelled',
    364         );
    365        
    366         if (!isset($status_map[$new_status])) {
    367             return;
    368         }
    369        
    370         $printseek_status = $status_map[$new_status];
    371        
    372         // Update status in PrintSeek
    373         $api = PrintSeek_API::instance();
    374         $response = $api->update_order_status($printseek_order_id, $printseek_status);
    375        
    376         if (isset($response['success']) && $response['success']) {
    377             $order->add_order_note(__('Order status synced to PrintSeek: ', 'printseek') . $printseek_status);
    378         }
    379     }
    380    
    381     /**
    382      * Sync order status FROM PrintSeek (cron job)
    383      */
    384     public function sync_order_status_from_printseek() {
    385         // Get all orders synced to PrintSeek
    386         // phpcs:disable WordPress.DB.SlowDBQuery.slow_db_query_meta_key, WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- Required for order lookup
    387         $args = array(
    388             'limit' => -1,
    389             'meta_key' => '_printseek_synced',
    390             'meta_value' => 'yes',
    391             'status' => array('processing', 'on-hold'),
    392         );
    393         // phpcs:enable WordPress.DB.SlowDBQuery.slow_db_query_meta_key, WordPress.DB.SlowDBQuery.slow_db_query_meta_value
    394        
    395         $orders = wc_get_orders($args);
    396        
    397         foreach ($orders as $order) {
    398             $printseek_order_id = $order->get_meta('_printseek_order_id');
    399            
    400             if (!$printseek_order_id) {
    401                 continue;
    402             }
    403            
    404             // Get order status from PrintSeek
    405             $api = PrintSeek_API::instance();
    406             $response = $api->get_order($printseek_order_id);
    407            
    408             if (!isset($response['success']) || !$response['success']) {
    409                 continue;
    410             }
    411            
    412             $printseek_status = isset($response['data']['status']) ? $response['data']['status'] : '';
    413            
    414             // Map PrintSeek status to WooCommerce
    415             $status_map = array(
    416                 'delivered' => 'completed',
    417                 'cancelled' => 'cancelled',
    418                 'shipped' => 'processing',
    419             );
    420            
    421             if (!isset($status_map[$printseek_status])) {
    422                 continue;
    423             }
    424            
    425             $wc_status = $status_map[$printseek_status];
    426            
    427             // Update order status if different
    428             if ($order->get_status() !== $wc_status) {
    429                 $order->update_status($wc_status, __('Status updated from PrintSeek: ', 'printseek') . $printseek_status);
    430                
    431                 // Add tracking info if available
    432                 if (isset($response['data']['trackingNumber'])) {
    433                     $order->update_meta_data('_printseek_tracking_number', $response['data']['trackingNumber']);
    434                     $order->save();
    435                 }
    436             }
    437         }
    438     }
    439    
    440     /**
    441      * Add order meta box
     180    }
     181
     182    /**
     183     * Add order meta box (legacy order screen and HPOS).
    442184     */
    443185    public function add_order_meta_box() {
    444         add_meta_box(
    445             'printseek_order_info',
    446             __('PrintSeek POD', 'printseek'),
    447             array($this, 'render_order_meta_box'),
    448             'shop_order',
    449             'side',
    450             'high'
    451         );
    452        
    453         // WC HPOS compatibility
    454         add_meta_box(
    455             'printseek_order_info',
    456             __('PrintSeek POD', 'printseek'),
    457             array($this, 'render_order_meta_box'),
    458             'woocommerce_page_wc-orders',
    459             'side',
    460             'high'
    461         );
    462     }
    463    
     186        foreach (array('shop_order', 'woocommerce_page_wc-orders') as $screen) {
     187            add_meta_box(
     188                'printseek_order_info',
     189                __('PrintSeek POD', 'printseek'),
     190                array($this, 'render_order_meta_box'),
     191                $screen,
     192                'side',
     193                'high'
     194            );
     195        }
     196    }
     197
    464198    /**
    465199     * Render order meta box
    … …  
    467201    public function render_order_meta_box($post_or_order) {
    468202        $order = ($post_or_order instanceof WP_Post) ? wc_get_order($post_or_order->ID) : $post_or_order;
    469        
    470         $synced = $order->get_meta('_printseek_synced');
    471203        $printseek_order_id = $order->get_meta('_printseek_order_id');
    472         $tracking_number = $order->get_meta('_printseek_tracking_number');
    473         $printseek_status = $order->get_meta('_printseek_status');
    474        
     204
    475205        ?>
    476206        <div class="printseek-order-meta">
    477             <p>
    478                 <strong><?php esc_html_e('Sync Status:', 'printseek'); ?></strong><br>
    479                 <?php if ($synced === 'yes' || $synced === '1' || $synced === true): ?>
     207            <?php if ($this->is_synced($order)): ?>
     208                <p>
     209                    <strong><?php esc_html_e('Sync Status:', 'printseek'); ?></strong><br>
    480210                    <span style="color: green;">✓ <?php esc_html_e('Synced', 'printseek'); ?></span>
    481                 <?php else: ?>
    482                     <span style="color: gray;"><?php esc_html_e('Not synced', 'printseek'); ?></span>
    483                 <?php endif; ?>
    484             </p>
    485            
    486             <?php if ($printseek_order_id): ?>
     211                </p>
    487212                <p>
    488213                    <strong><?php esc_html_e('PrintSeek Order ID:', 'printseek'); ?></strong><br>
    489214                    <code style="font-size: 10px; word-break: break-all;"><?php echo esc_html($printseek_order_id); ?></code>
    490215                </p>
    491             <?php endif; ?>
    492            
    493             <?php if ($printseek_status): ?>
    494                 <p>
    495                     <strong><?php esc_html_e('PrintSeek Status:', 'printseek'); ?></strong><br>
    496                     <span class="printseek-status-badge"><?php echo esc_html(ucfirst($printseek_status)); ?></span>
    497                 </p>
    498             <?php endif; ?>
    499            
    500             <?php if ($tracking_number): ?>
    501                 <p>
    502                     <strong><?php esc_html_e('Tracking Number:', 'printseek'); ?></strong><br>
    503                     <code><?php echo esc_html($tracking_number); ?></code>
    504                 </p>
    505             <?php endif; ?>
    506            
    507             <?php
    508             $is_synced = ($synced === 'yes' || $synced === '1' || $synced === true) && $printseek_order_id;
    509             if ($is_synced):
    510             ?>
    511                 <div class="printseek-synced-notice" style="background: #d1fae5; border: 1px solid #10b981; padding: 10px; border-radius: 6px; margin-top: 10px;">
    512                     <p style="margin: 0; color: #065f46; font-size: 12px;">
    513                         <span class="dashicons dashicons-yes-alt" style="color: #10b981;"></span>
    514                         <?php esc_html_e('This order is already synced to PrintSeek.', 'printseek'); ?>
    515                     </p>
    516                 </div>
    517216            <?php else: ?>
     217                <p>
     218                    <strong><?php esc_html_e('Sync Status:', 'printseek'); ?></strong><br>
     219                    <span style="color: gray;"><?php esc_html_e('Not synced', 'printseek'); ?></span>
     220                </p>
    518221                <p>
    519222                    <button type="button" class="button button-primary" id="printseek-sync-order-btn" data-order-id="<?php echo absint($order->get_id()); ?>">
    … …  
    527230        <?php
    528231    }
    529    
     232
    530233    /**
    531234     * AJAX: Sync single order
    … …  
    533236    public function ajax_sync_single_order() {
    534237        check_ajax_referer('printseek_sync_single_order', 'nonce');
    535        
     238
    536239        if (!current_user_can('manage_woocommerce')) {
    537240            wp_send_json_error(array('message' => __('Permission denied', 'printseek')));
    538241        }
    539        
    540         $order_id = isset($_POST['order_id']) ? absint($_POST['order_id']) : 0;
    541        
    542         if (!$order_id) {
    543             wp_send_json_error(array('message' => __('Invalid order ID', 'printseek')));
    544         }
    545        
    546         $result = $this->push_order_to_printseek($order_id);
    547        
     242
     243        $order = wc_get_order(isset($_POST['order_id']) ? absint($_POST['order_id']) : 0);
     244        if (!$order) {
     245            wp_send_json_error(array('message' => __('Order not found', 'printseek')));
     246        }
     247
     248        $result = $this->push_order_to_printseek($order);
     249
    548250        if ($result['success']) {
    549251            wp_send_json_success(array('message' => $result['message']));
    550         } else {
    551             wp_send_json_error(array('message' => $result['message']));
    552         }
    553     }
    554    
    555     /**
    556      * AJAX: Sync orders
    557      */
    558     public function ajax_sync_orders() {
    559         check_ajax_referer('printseek_sync_orders', 'nonce');
    560        
    561         if (!current_user_can('manage_woocommerce')) {
    562             wp_send_json_error(array('message' => __('Permission denied', 'printseek')));
    563         }
    564        
    565         // Trigger sync
    566         $this->sync_order_status_from_printseek();
    567        
    568         wp_send_json_success(array('message' => __('Orders synced successfully!', 'printseek')));
    569     }
    570    
    571     /**
    572      * Normalize size values to valid enum (S, M, L, XL, XXL)
    573      * Maps common size variations to standard values
    574      *
    575      * @param string $raw_size Raw size string from WooCommerce
    576      * @return string Normalized size value
    577      */
    578     private function normalize_size($raw_size) {
    579         $raw_size = strtoupper(trim($raw_size));
    580        
    581         // Direct matches
    582         $valid_sizes = array('S', 'M', 'L', 'XL', 'XXL');
    583         if (in_array($raw_size, $valid_sizes, true)) {
    584             return $raw_size;
    585         }
    586        
    587         // Map common variations to standard sizes
    588         $size_map = array(
    589             // Small variations
    590             'SMALL' => 'S',
    591             'SM' => 'S',
    592             'SML' => 'S',
    593             'XSMALL' => 'S',
    594             'X-SMALL' => 'S',
    595             'XS' => 'S',
    596            
    597             // Medium variations
    598             'MEDIUM' => 'M',
    599             'MED' => 'M',
    600             'MD' => 'M',
    601            
    602             // Large variations
    603             'LARGE' => 'L',
    604             'LG' => 'L',
    605             'LRG' => 'L',
    606            
    607             // XL variations
    608             'XLARGE' => 'XL',
    609             'X-LARGE' => 'XL',
    610             'EXTRA LARGE' => 'XL',
    611             'EXTRA-LARGE' => 'XL',
    612             '1XL' => 'XL',
    613             '1X' => 'XL',
    614            
    615             // XXL variations
    616             'XXLARGE' => 'XXL',
    617             'XX-LARGE' => 'XXL',
    618             '2XL' => 'XXL',
    619             '2X' => 'XXL',
    620             'XXXL' => 'XXL',
    621             '3XL' => 'XXL',
    622             '3X' => 'XXL',
    623         );
    624        
    625         if (isset($size_map[$raw_size])) {
    626             return $size_map[$raw_size];
    627         }
    628        
    629         // Default to M if unknown
    630         return 'M';
     252        }
     253        wp_send_json_error(array('message' => $result['message']));
    631254    }
    632255}
  • printseek/trunk/includes/class-printseek-product-sync.php

    r3430355 r3848522  
    6363     */
    6464    public function render_meta_box($post) {
    65         $product = wc_get_product($post->ID);
    6665        $pushed_to_printseek = get_post_meta($post->ID, '_printseek_pushed', true);
    67         $printseek_order_id = get_post_meta($post->ID, '_printseek_order_id', true);
     66        $printseek_sku = get_post_meta($post->ID, '_printseek_sku', true);
    6867       
    6968        ?>
    … …  
    7877            </p>
    7978           
    80             <?php if ($printseek_order_id): ?>
     79            <?php if ($printseek_sku): ?>
    8180                <p>
    82                     <strong><?php esc_html_e('Order ID:', 'printseek'); ?></strong><br>
    83                     <code><?php echo esc_html($printseek_order_id); ?></code>
     81                    <strong><?php esc_html_e('Design SKU:', 'printseek'); ?></strong><br>
     82                    <code><?php echo esc_html($printseek_sku); ?></code>
    8483                </p>
    8584            <?php endif; ?>
    86            
     85
     86            <?php if ($pushed_to_printseek !== 'yes'): ?>
    8787            <p>
    8888                <button type="button" class="button button-primary button-large" id="printseek-push-product" data-product-id="<?php echo absint( $post->ID ); ?>">
    … …  
    9696           
    9797            <div id="printseek-push-status" style="margin-top: 10px;"></div>
     98            <?php endif; ?>
    9899        </div>
    99100        <?php
    … …  
    162163   
    163164    /**
    164      * Prepare product data for API
    165      */
    166     private function prepare_product_data($product) {
    167         $image_url = wp_get_attachment_url($product->get_image_id());
    168        
    169         // Get variations if variable product
    170         $variants = array();
    171         if ($product->is_type('variable')) {
    172             $variations = $product->get_available_variations();
    173             foreach ($variations as $variation) {
    174                 $variant_obj = wc_get_product($variation['variation_id']);
    175                 $attributes = $variant_obj->get_attributes();
    176                
    177                 $color = isset($attributes['pa_color']) ? $attributes['pa_color'] : 'default';
    178                 $size = isset($attributes['pa_size']) ? $attributes['pa_size'] : 'M';
    179                
    180                 $variants[] = array(
    181                     'id' => 'v' . $variation['variation_id'],
    182                     'color' => $color,
    183                     'colorName' => ucfirst($color),
    184                     'size' => strtoupper($size),
    185                     'quantity' => 1
    186                 );
    187             }
    188         }
    189        
    190         // Prepare data matching your backend API structure
    191         $data = array(
    192             'productName' => $product->get_name(),
    193             'productType' => $this->get_product_type($product),
    194             'variant' => 'standard',
    195             'variantMode' => !empty($variants),
    196             'variants' => $variants,
    197             'totalQuantity' => 1,
    198             'totalPrice' => floatval($product->get_price()),
    199             'thumbnailUrl' => $image_url,
    200             'designs' => array(
    201                 'front' => $image_url ? array('url' => $image_url) : null,
    202             ),
    203             'shippingAddress' => array(
    204                 'fullName' => 'WooCommerce Product',
    205                 'phone' => '',
    206                 'email' => get_option('admin_email'),
    207                 'addressLine1' => 'Sample Address',
    208                 'city' => 'Sample City',
    209                 'state' => 'Sample State',
    210                 'postalCode' => '000000',
    211                 'country' => 'India'
    212             ),
    213             'source' => 'woocommerce',
    214             'woocommerceProductId' => $product->get_id(),
    215             'siteUrl' => get_site_url()
    216         );
    217        
    218         return $data;
    219     }
    220    
    221     /**
    222      * Get product type
    223      */
    224     private function get_product_type($product) {
    225         $categories = $product->get_category_ids();
    226        
    227         // Map WooCommerce categories to PrintSeek product types
    228         $type_mapping = array(
    229             't-shirt' => 'tshirt',
    230             'hoodie' => 'hoodie',
    231             'oversized' => 'oversized-tshirt',
    232             'polo' => 'polo',
    233         );
    234        
    235         foreach ($categories as $cat_id) {
    236             $cat = get_term($cat_id, 'product_cat');
    237             $slug = strtolower($cat->slug);
    238            
    239             foreach ($type_mapping as $key => $value) {
    240                 if (strpos($slug, $key) !== false) {
    241                     return $value;
    242                 }
    243             }
    244         }
    245        
    246         return 'tshirt'; // Default
    247     }
    248    
    249     /**
    250165     * Add bulk action
    251166     */
    252167    public function add_bulk_action($actions) {
    253         $actions['printseek_push'] = __('Push to PrintSeek', 'printseek');
     168        $actions['printseek_push'] = __('Mark as PrintSeek product', 'printseek');
    254169        return $actions;
    255170    }
    … …  
    296211    public function product_column_content($column, $post_id) {
    297212        if ($column === 'printseek_status') {
    298             $pushed = get_post_meta($post_id, '_printseek_pushed', true);
    299            
    300             if ($pushed) {
     213            if (get_post_meta($post_id, '_printseek_pushed', true) === 'yes') {
    301214                echo '<span style="color: green;">✓</span>';
    302215            } else {
  • printseek/trunk/languages/printseek.pot

    r3430355 r3848522  
    55"Project-Id-Version: PrintSeek - Print on Demand 1.0.0\n"
    66"Report-Msgid-Bugs-To: https://wordpress.org/support/plugin/printseek\n"
    7 "Last-Translator: PrintSeek Team <support@printsik.com>\n"
    8 "Language-Team: PrintSeek Team <support@printsik.com>\n"
     7"Last-Translator: PrintSeek Team <abid.akram01@gmail.com>\n"
     8"Language-Team: PrintSeek Team <abid.akram01@gmail.com>\n"
    99"MIME-Version: 1.0\n"
    1010"Content-Type: text/plain; charset=UTF-8\n"
  • printseek/trunk/printseek.php

    r3430355 r3848522  
    22/**
    33 * Plugin Name: Printseek: Print on Demand
    4  * Plugin URI: https://printsik.com/plugins/woocommerce
     4 * Plugin URI: https://lafangehclothing.com/dashboard/connect-store
    55 * Description: Connect your WooCommerce store with PrintSeek Print on Demand service. Push products, sync orders, and manage fulfillment seamlessly.
    6  * Version: 1.0.2
     6 * Version: 1.0.3
    77 * Author: PrintSeek Team
    8  * Author URI: https://printsik.com
     8 * Author URI: https://lafangehclothing.com
    99 * Text Domain: printseek
    1010 * Domain Path: /languages
    … …  
    1717 *
    1818 * @package PrintSeek_POD
    19  * @version 1.0.2
    20  * @author PrintSeek Team <support@printsik.com>
     19 * @version 1.0.3
     20 * @author PrintSeek Team <abid.akram01@gmail.com>
    2121 * @copyright 2024 PrintSeek
    2222 * @license GPL-2.0+
    … …  
    2929
    3030// Define plugin constants
    31 define('PRINTSEEK_VERSION', '1.0.2');
     31define('PRINTSEEK_VERSION', '1.0.3');
    3232define('PRINTSEEK_PLUGIN_FILE', __FILE__);
    3333define('PRINTSEEK_PLUGIN_DIR', plugin_dir_path(__FILE__));
    … …  
    3535define('PRINTSEEK_PLUGIN_BASENAME', plugin_basename(__FILE__));
    3636
    37 // API Configuration - Change this to your production API URL
    38 define('PRINTSEEK_API_URL', 'https://api.printsik.com');
    39 // define('PRINTSEEK_API_URL', 'http://localhost:3001'); // Uncomment for local development
     37// Backend API URL (the backend's BASE_URL). Override it in wp-config.php, e.g. for local development:
     38// define('PRINTSEEK_API_URL', 'http://localhost:4000');
     39if (!defined('PRINTSEEK_API_URL')) {
     40    define('PRINTSEEK_API_URL', 'https://api.printsik.com');
     41}
     42// Store website (the backend's FRONTEND_URL) for the dashboard links; overridable the same way.
     43if (!defined('PRINTSEEK_SITE_URL')) {
     44    define('PRINTSEEK_SITE_URL', 'https://lafangehclothing.com');
     45}
     46define('PRINTSEEK_SUPPORT_EMAIL', 'abid.akram01@gmail.com');
    4047
    4148/**
    … …  
    142149        require_once PRINTSEEK_PLUGIN_DIR . 'includes/class-printseek-product-sync.php';
    143150        require_once PRINTSEEK_PLUGIN_DIR . 'includes/class-printseek-order-sync.php';
    144         require_once PRINTSEEK_PLUGIN_DIR . 'includes/class-printseek-webhook-handler.php';
    145151    }
    146152   
    … …  
    200206            PrintSeek_Product_Sync::instance();
    201207            PrintSeek_Order_Sync::instance();
    202             PrintSeek_Webhook_Handler::instance();
    203208           
    204             // Notify PrintSeek that plugin is activated
    205             $this->notify_plugin_status('activated');
    206         }
     209            // Notify PrintSeek that the plugin is active — THROTTLED.
     210            // init() runs on `plugins_loaded`, which fires on EVERY request/page-load. Calling
     211            // notify_plugin_status() unconditionally here floods the backend with
     212            // `plugin.activated` webhooks (one per request). Send at most once per 12h instead.
     213            $this->maybe_notify_plugin_active();
     214        }
     215    }
     216   
     217    /**
     218     * Send a throttled "plugin active" heartbeat to PrintSeek.
     219     *
     220     * Because init() runs on every request, we must not notify every time. We notify at most
     221     * once per 12 hours and re-notify immediately when the plugin version changes. This keeps
     222     * the backend's "plugin installed" signal fresh without hammering the webhook endpoint.
     223     *
     224     * @since 1.0.0
     225     */
     226    private function maybe_notify_plugin_active() {
     227        if (get_transient('printseek_active_notified') === PRINTSEEK_VERSION) {
     228            return;
     229        }
     230        $this->notify_plugin_status('activated');
     231        set_transient('printseek_active_notified', PRINTSEEK_VERSION, 12 * HOUR_IN_SECONDS);
    207232    }
    208233   
    … …  
    232257        if (PRINTSEEK_PLUGIN_BASENAME === $file) {
    233258            $row_meta = array(
    234                 'docs'    => '<a href="' . esc_url('https://printsik.com/docs/woocommerce') . '" target="_blank">' .
     259                'docs'    => '<a href="' . esc_url(PRINTSEEK_SITE_URL) . '" target="_blank">' .
    235260                             esc_html__('Documentation', 'printseek') . '</a>',
    236                 'support' => '<a href="' . esc_url('https://printsik.com/support') . '" target="_blank">' .
     261                'support' => '<a href="' . esc_url('mailto:' . PRINTSEEK_SUPPORT_EMAIL) . '">' .
    237262                             esc_html__('Support', 'printseek') . '</a>',
    238263            );
    … …  
    248273     */
    249274    public function activate() {
    250         // Create necessary database tables
    251         $this->create_tables();
    252        
    253         // Set default options
    254275        add_option('printseek_version', PRINTSEEK_VERSION);
    255276        add_option('printseek_api_key', '');
    256277        add_option('printseek_auto_sync_orders', 'yes');
    257         add_option('printseek_auto_sync_products', 'no');
    258         add_option('printseek_webhook_secret', '');
    259278        add_option('printseek_debug_mode', 'no');
    260        
    261         // Schedule cron events
    262         if (!wp_next_scheduled('printseek_sync_order_status')) {
    263             wp_schedule_event(time(), 'hourly', 'printseek_sync_order_status');
    264         }
    265        
    266         // Flush rewrite rules
    267         flush_rewrite_rules();
    268        
     279
     280        // Leftovers of 1.0.x (hourly status cron, unused options).
     281        wp_clear_scheduled_hook('printseek_sync_order_status');
     282        delete_option('printseek_auto_sync_products');
     283        delete_option('printseek_webhook_secret');
     284
    269285        // Log activation
    270286        $this->log('Plugin activated', 'info');
    … …  
    277293     */
    278294    public function deactivate() {
    279         // Clear scheduled cron events
    280         wp_clear_scheduled_hook('printseek_sync_order_status');
    281        
    282         // Notify PrintSeek that plugin is deactivated
    283295        $this->notify_plugin_status('deactivated');
    284        
    285         // Flush rewrite rules
    286         flush_rewrite_rules();
    287        
     296
    288297        // Log deactivation
    289298        $this->log('Plugin deactivated', 'info');
    … …  
    315324        // Fire and forget - don't wait for response
    316325        $api->send_webhook($data);
    317     }
    318    
    319     /**
    320      * Create database tables
    321      *
    322      * @since 1.0.0
    323      */
    324     private function create_tables() {
    325         global $wpdb;
    326        
    327         $charset_collate = $wpdb->get_charset_collate();
    328        
    329         // Sync log table
    330         $table_name = $wpdb->prefix . 'printseek_sync_log';
    331        
    332         $sql = "CREATE TABLE IF NOT EXISTS $table_name (
    333             id bigint(20) NOT NULL AUTO_INCREMENT,
    334             sync_type varchar(50) NOT NULL,
    335             item_id varchar(100) NOT NULL,
    336             status varchar(20) NOT NULL,
    337             message text,
    338             created_at datetime DEFAULT CURRENT_TIMESTAMP,
    339             PRIMARY KEY (id),
    340             KEY sync_type (sync_type),
    341             KEY item_id (item_id),
    342             KEY status (status),
    343             KEY created_at (created_at)
    344         ) $charset_collate;";
    345        
    346         require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    347         dbDelta($sql);
    348326    }
    349327   
    … …  
    441419        }
    442420    }
    443    
    444     /**
    445      * Get plugin log file path
    446      * Uses wp_upload_dir() as per WordPress plugin guidelines
    447      *
    448      * @since 1.0.0
    449      * @return string|false Log file path or false on failure
    450      */
    451     public function get_log_file_path() {
    452         $log_dir = $this->get_log_directory();
    453        
    454         if (!$log_dir) {
    455             return false;
    456         }
    457        
    458         return trailingslashit($log_dir) . 'debug.log';
    459     }
    460421}
    461422
  • printseek/trunk/readme.txt

    r3430355 r3848522  
    11=== Printseek: Print on Demand ===
    22Contributors: printseek
    3 Donate link: https://printsik.com
     3Donate link: https://lafangehclothing.com
    44Tags: print-on-demand, woocommerce, pod, fulfillment, dropshipping
    55Requires at least: 5.8
    66Tested up to: 6.9
    77Requires PHP: 7.4
    8 Stable tag: 1.0.2
     8Stable tag: 1.0.3
    99WC requires at least: 5.0
    1010WC tested up to: 9.0
    … …  
    2222* **One-Click Product Link** - Link your WooCommerce products to PrintSeek for fulfillment
    2323* **Automatic Order Sync** - Orders automatically sync to PrintSeek when customers purchase
    24 * **Real-Time Updates** - Receive order status updates via webhooks
     24* **Status Updates** - Cancellations and other order status changes are reported to PrintSeek
    2525* **Easy Dashboard** - Manage everything from WordPress admin panel
    2626* **Bulk Actions** - Link multiple products at once
    27 * **Order Tracking** - Track fulfillment status directly in WooCommerce
    2827* **HPOS Compatible** - Works with WooCommerce High-Performance Order Storage
    2928
    … …  
    4039* WooCommerce 5.0 or higher
    4140* PHP 7.4 or higher
    42 * PrintSeek account (sign up free at [printsik.com](https://printsik.com))
     41* PrintSeek account (sign up free at [lafangehclothing.com](https://lafangehclothing.com))
    4342
    44 = Links =
     43#### Links
    4544
    46 * [PrintSeek Website](https://printsik.com)
    47 * [Contact Support](https://printsik.com/contact-us)
     45- [PrintSeek Website](https://printsik.com/)
     46- [Contact Support](https://printsik.com/contact-us)
    4847
    4948== Installation ==
    … …  
    7574= How do I get a PrintSeek API key? =
    7675
    77 Sign up for a free account at [printsik.com](https://printsik.com), then navigate to your dashboard to find your API key.
     76Sign up for a free account at [lafangehclothing.com](https://lafangehclothing.com), then navigate to your dashboard to find your API key.
    7877
    7978= How do I link products to PrintSeek? =
    … …  
    8685= Are orders synced automatically? =
    8786
    88 Yes! Once you link a product, any new orders containing that product will automatically sync to PrintSeek.
    89 
    90 = What happens when an order is shipped? =
    91 
    92 PrintSeek sends a webhook notification, and your WooCommerce order is automatically updated with tracking information.
     87Yes. Once a paid or Cash on Delivery order containing a linked product reaches Processing, it syncs to PrintSeek with the chosen colour and size. Later status changes (e.g. Cancelled) are reported too.
    9388
    9489= Is this plugin compatible with HPOS? =
    … …  
    105100
    106101== Changelog ==
     102
     103= 1.0.3 =
     104* Fixed: Saving the API key no longer resets Auto Sync Orders and Debug Mode
     105* Fixed: Orders sync when they reach Processing (paid or COD), with their items, colour and size
     106* Improved: Saving the API key verifies it right away; the dashboard shows the real connection state
     107* Improved: Order status changes of synced orders are reported to PrintSeek
     108* Removed: Unused webhook receiver, hourly status cron and unused settings
    107109
    108110= 1.0.2 =
    … …  
    128130== Upgrade Notice ==
    129131
     132= 1.0.3 =
     133Order sync fixes. Requires the current PrintSeek API.
     134
    130135= 1.0.2 =
    131136Important fix: Log files now use WordPress uploads directory per plugin guidelines.
    … …  
    147152No personal data is collected by the plugin itself. Order data is transmitted securely to PrintSeek for fulfillment purposes only.
    148153
    149 For more information, see PrintSeek's privacy policy at https://printsik.com/privacy
     154For more information, see PrintSeek's privacy policy at https://lafangehclothing.com/privacy-policy
    150155
     156Contact (support, API and WordPress.org plugin review questions): abid.akram01@gmail.com.
     157
Note: See TracChangeset for help on using the changeset viewer.