Below is a differential between the unpatched vulnerable code and the patched update, for reference.
--- a/storeengine/addons/affiliate/affiliate.php
+++ b/storeengine/addons/affiliate/affiliate.php
@@ -24,7 +24,8 @@
define( 'STOREENGINE_AFFILIATE_VERSION', '1.0' );
// Bump on any schema change under affiliate/database/ to trigger a
// re-sync via the central Addons schema manager.
- define( 'STOREENGINE_AFFILIATE_DB_VERSION', '1.1' );
+ // 1.2 — widened the affiliates.status ENUM (added rejected, suspended).
+ define( 'STOREENGINE_AFFILIATE_DB_VERSION', '1.2' );
define( 'STOREENGINE_AFFILIATE_DIR_PATH', STOREENGINE_ADDONS_DIR_PATH . 'affiliate/' );
define( 'STOREENGINE_AFFILIATE_ASSETS_DIR', STOREENGINE_PLUGIN_ROOT_URI . 'addons/affiliate/assets/' );
define( 'STOREENGINE_AFFILIATE_TEMPLATE_DIR', STOREENGINE_AFFILIATE_DIR_PATH . 'templates/' );
--- a/storeengine/addons/affiliate/ajax/affiliate-ajax.php
+++ b/storeengine/addons/affiliate/ajax/affiliate-ajax.php
@@ -72,6 +72,9 @@
if ( ! $status ) {
wp_send_json_error( esc_html__( 'Affiliate status is required.', 'storeengine' ) );
}
+ if ( ! Affiliate::is_valid_status( (string) $status ) ) {
+ wp_send_json_error( esc_html__( 'Invalid affiliate status.', 'storeengine' ) );
+ }
$ret = Affiliate::update( $affiliate_id, [ 'status' => $status ] );
--- a/storeengine/addons/affiliate/ajax/commission-ajax.php
+++ b/storeengine/addons/affiliate/ajax/commission-ajax.php
@@ -71,6 +71,11 @@
if ( 'approved' === $payload['status'] ) {
// Self-guards against re-crediting a non-pending commission.
$this->update_the_affiliate_commission( $payload['commission_id'] );
+
+ // Notify the affiliate only on the first transition into approved.
+ if ( 'approved' !== $prev_status ) {
+ do_action( 'storeengine/addons/affiliate/commission_approved', (int) $payload['commission_id'] );
+ }
}
// Manually rejecting an already-approved commission claws the funds back.
--- a/storeengine/addons/affiliate/ajax/payout-ajax.php
+++ b/storeengine/addons/affiliate/ajax/payout-ajax.php
@@ -9,6 +9,7 @@
use StoreEngineClassesAbstractAjaxHandler;
use StoreEngineAddonsAffiliatemodelsPayout;
use StoreEngineAddonsAffiliatemodelsAffiliateReport;
+use StoreEngineAddonsAffiliatemodelsCommission;
class PayoutAjax extends AbstractAjaxHandler {
@@ -82,6 +83,15 @@
AffiliateReport::release_balance( (int) $payout['affiliate_id'], (float) $payout['payout_amount'] );
}
+ // On the first transition into a completed/paid state, settle the
+ // affiliate's approved commissions (FIFO) so their commission rows reflect
+ // that they've been paid out — the payout ledger and the commission list
+ // stay in sync instead of "Paid" being a manual-only label.
+ $paid_states = [ 'completed', 'paid' ];
+ if ( in_array( $status, $paid_states, true ) && ! in_array( $prev_status, $paid_states, true ) ) {
+ Commission::mark_approved_as_paid( (int) $payout['affiliate_id'], (float) $payout['payout_amount'] );
+ }
+
$ret = Payout::update( $payout_id, [ 'status' => $status ] );
if ( is_wp_error( $ret ) ) {
--- a/storeengine/addons/affiliate/ajax/settings.php
+++ b/storeengine/addons/affiliate/ajax/settings.php
@@ -27,6 +27,7 @@
'commission_type' => 'string',
'commission_rate' => 'integer',
'allow_auto_commission' => 'boolean',
+ 'allow_self_referral' => 'boolean',
'allow_zero_commission' => 'boolean',
// Withdraw settings
'minimum_withdraw_amount' => 'float',
@@ -52,6 +53,7 @@
'commission_type' => $payload['commission_type'] ?? $default['commission_type'],
'commission_rate' => $payload['commission_rate'] ?? $default['commission_rate'],
'allow_auto_commission' => $payload['allow_auto_commission'] ?? $default['allow_auto_commission'],
+ 'allow_self_referral' => $payload['allow_self_referral'] ?? $default['allow_self_referral'],
'allow_zero_commission' => $payload['allow_zero_commission'] ?? $default['allow_zero_commission'],
// Withdraw settings
'minimum_withdraw_amount' => $payload['minimum_withdraw_amount'] ?? $default['minimum_withdraw_amount'],
--- a/storeengine/addons/affiliate/cookie-handler.php
+++ b/storeengine/addons/affiliate/cookie-handler.php
@@ -10,6 +10,7 @@
use StoreEngineUtilsHelper;
use StoreEngineAddonsAffiliateHelper as HelperAddon;
use StoreEngineAddonsAffiliatemodelsCommission;
+use StoreEngineAddonsAffiliatemodelsAffiliate as AffiliateModel;
use StoreEngineAddonsAffiliatemodelsReferral;
use StoreEngineAddonsAffiliatemodelsReferralTrack;
use StoreEngineAddonsAffiliatemodelsAffiliateReport;
@@ -133,6 +134,14 @@
$affiliate_id = (int) $affiliate_data->affiliate_id;
+ // Block self-referrals: an affiliate must not earn a commission on their
+ // own purchase (buyer matched to the affiliate by user id or email),
+ // unless the store explicitly opts in.
+ if ( ! HelperAddon::get_affiliate_setting( 'allow_self_referral' )
+ && self::is_self_referral( $order, $affiliate_id ) ) {
+ return;
+ }
+
// Commission on product revenue only — exclude tax and shipping.
// Filterable so stores can widen the base (e.g. include shipping).
$commission_base = (float) apply_filters(
@@ -159,4 +168,30 @@
}
}
+ /**
+ * Whether the order's buyer is the referring affiliate themselves — matched
+ * by WP user id (logged-in purchase) or by billing email (guest checkout
+ * using the affiliate's own email).
+ */
+ protected static function is_self_referral( Order $order, int $affiliate_id ): bool {
+ $affiliate = AffiliateModel::get_affiliates( [ 'affiliate_id' => $affiliate_id ] );
+ if ( empty( $affiliate ) ) {
+ return false;
+ }
+
+ $affiliate_user_id = (int) ( $affiliate['user_id'] ?? 0 );
+ $order_user_id = (int) $order->get_customer_id();
+ if ( $affiliate_user_id && $order_user_id && $affiliate_user_id === $order_user_id ) {
+ return true;
+ }
+
+ $affiliate_email = strtolower( trim( (string) ( $affiliate['user_email'] ?? '' ) ) );
+ $order_email = strtolower( trim( (string) $order->get_billing_email() ) );
+ if ( $affiliate_email && $order_email && $affiliate_email === $order_email ) {
+ return true;
+ }
+
+ return false;
+ }
+
}
--- a/storeengine/addons/affiliate/database/create-affiliate.php
+++ b/storeengine/addons/affiliate/database/create-affiliate.php
@@ -8,19 +8,54 @@
class CreateAffiliate {
+ /**
+ * Canonical order of the `status` ENUM. Keep in sync with
+ * {@see StoreEngineAddonsAffiliatemodelsAffiliate::statuses()}.
+ */
+ const STATUS_ENUM = [ 'active', 'inactive', 'pending', 'rejected', 'suspended' ];
+
public static function up( $prefix, $charset_collate ) {
$table_name = $prefix . 'affiliates';
+ $enum = "'" . implode( "', '", self::STATUS_ENUM ) . "'";
$sql = "CREATE TABLE IF NOT EXISTS {$table_name} (
`affiliate_id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`user_id` BIGINT(20) UNSIGNED NOT NULL,
`commission_type` ENUM('percentage', 'flat') NOT NULL,
`commission_rate` INT(3) UNSIGNED NOT NULL,
- `status` ENUM('active', 'inactive', 'pending') NOT NULL,
+ `status` ENUM({$enum}) NOT NULL,
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`affiliate_id`),
UNIQUE KEY `user_id` (`user_id`)
) $charset_collate;";
dbDelta( $sql );
+
+ // dbDelta cannot alter an existing ENUM definition, so widen it explicitly
+ // for stores created before `rejected`/`suspended` existed. Idempotent.
+ self::ensure_status_enum( $table_name );
+ }
+
+ /**
+ * Bring an existing `status` column up to the full ENUM. Runs on the
+ * version-triggered schema re-sync; no-op once already widened.
+ */
+ private static function ensure_status_enum( string $table_name ): void {
+ global $wpdb;
+
+ // $table_name is composed from $wpdb->prefix — no user input — so it is
+ // safe to interpolate (identifiers can't be bound as placeholders).
+ $column = $wpdb->get_row( "SHOW COLUMNS FROM `{$table_name}` LIKE 'status'" ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange
+
+ if ( ! $column || empty( $column->Type ) ) {
+ return;
+ }
+
+ foreach ( self::STATUS_ENUM as $value ) {
+ if ( false === strpos( $column->Type, "'{$value}'" ) ) {
+ $enum = "'" . implode( "', '", self::STATUS_ENUM ) . "'";
+ $wpdb->query( "ALTER TABLE `{$table_name}` MODIFY COLUMN `status` ENUM({$enum}) NOT NULL" ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange
+ return;
+ }
+ }
}
}
--- a/storeengine/addons/affiliate/database/create-commission.php
+++ b/storeengine/addons/affiliate/database/create-commission.php
@@ -27,11 +27,11 @@
// state (used for refund/cancellation reversals) explicitly. Idempotent:
// re-running MODIFY with the same definition is a no-op.
global $wpdb;
- // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
- $column = $wpdb->get_row( "SHOW COLUMNS FROM `{$table_name}` LIKE 'status'", ARRAY_A );
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Identifier passed via %i to prepare(); reading column definition on a custom StoreEngine table during migration.
+ $column = $wpdb->get_row( $wpdb->prepare( 'SHOW COLUMNS FROM %i LIKE %s', $table_name, 'status' ), ARRAY_A );
if ( $column && false === strpos( (string) $column['Type'], 'rejected' ) ) {
- // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
- $wpdb->query( "ALTER TABLE `{$table_name}` MODIFY COLUMN `status` ENUM('pending', 'approved', 'paid', 'rejected') NOT NULL" );
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Identifier passed via %i to prepare(); one-off ENUM widen migration on a custom StoreEngine table.
+ $wpdb->query( $wpdb->prepare( "ALTER TABLE %i MODIFY COLUMN `status` ENUM('pending', 'approved', 'paid', 'rejected') NOT NULL", $table_name ) );
}
}
}
--- a/storeengine/addons/affiliate/helper.php
+++ b/storeengine/addons/affiliate/helper.php
@@ -37,7 +37,13 @@
}
public static function get_affiliate_setting( $setting_name ) {
- $affiliate_settings = Affiliate::get_settings_saved_data();
+ // Fall back to defaults for keys the stored settings blob doesn't have
+ // yet (e.g. a setting added after the store last saved its options), so
+ // a missing key inherits its intended default instead of returning null.
+ $affiliate_settings = wp_parse_args(
+ Affiliate::get_settings_saved_data(),
+ Affiliate::get_settings_default_data()
+ );
return $affiliate_settings[ $setting_name ] ?? null;
}
--- a/storeengine/addons/affiliate/hooks.php
+++ b/storeengine/addons/affiliate/hooks.php
@@ -119,6 +119,11 @@
if ( $update && ! is_wp_error( $update ) ) {
HelperAddon::update_affiliate_commission( $commission['affiliate_id'], $commission['commission_amount'] );
+
+ // Fires whenever a commission transitions into `approved` (auto here,
+ // manual in Commission ajax). The affiliate-approved email listens on
+ // this to congratulate/motivate the affiliate.
+ do_action( 'storeengine/addons/affiliate/commission_approved', (int) $commission['commission_id'] );
}
}
@@ -201,6 +206,18 @@
}
}
+ // Rejected / suspended affiliates are locked out of the earnings dashboard
+ // — they cannot earn or track (referral tracking is gated on 'active'), so
+ // the dashboard would only show a dead referral link. Show a notice instead.
+ $affiliate_status = is_array( $affiliate_data ) ? ( $affiliate_data['status'] ?? '' ) : '';
+ if ( in_array( $affiliate_status, [ AffiliateModel::STATUS_REJECTED, AffiliateModel::STATUS_SUSPENDED ], true ) ) {
+ Template::get_template(
+ 'frontend-dashboard/pages/affiliate-locked.php',
+ [ 'status' => $affiliate_status ]
+ );
+ return;
+ }
+
// Ensure the affiliate has a referral code (referral row). Covers both a
// freshly self-healed record and any legacy affiliate missing its row.
if ( ! empty( $affiliate_data['affiliate_id'] ) && empty( $affiliate_data['referral_code'] ) ) {
--- a/storeengine/addons/affiliate/models/affiliate.php
+++ b/storeengine/addons/affiliate/models/affiliate.php
@@ -11,6 +11,51 @@
}
class Affiliate {
+
+ const STATUS_PENDING = 'pending';
+ const STATUS_ACTIVE = 'active';
+ const STATUS_INACTIVE = 'inactive';
+ const STATUS_REJECTED = 'rejected';
+ const STATUS_SUSPENDED = 'suspended';
+
+ /**
+ * Every valid affiliate status. Order matches the DB ENUM
+ * ({@see StoreEngineAddonsAffiliateDatabaseCreateAffiliate::STATUS_ENUM}).
+ *
+ * @return string[]
+ */
+ public static function statuses(): array {
+ return [
+ self::STATUS_ACTIVE,
+ self::STATUS_INACTIVE,
+ self::STATUS_PENDING,
+ self::STATUS_REJECTED,
+ self::STATUS_SUSPENDED,
+ ];
+ }
+
+ /**
+ * Whether the given string is a known affiliate status.
+ */
+ public static function is_valid_status( string $status ): bool {
+ return in_array( $status, self::statuses(), true );
+ }
+
+ /**
+ * Human-readable, translated label for a status value.
+ */
+ public static function status_label( string $status ): string {
+ $labels = [
+ self::STATUS_ACTIVE => __( 'Active', 'storeengine' ),
+ self::STATUS_INACTIVE => __( 'Inactive', 'storeengine' ),
+ self::STATUS_PENDING => __( 'Pending', 'storeengine' ),
+ self::STATUS_REJECTED => __( 'Rejected', 'storeengine' ),
+ self::STATUS_SUSPENDED => __( 'Suspended', 'storeengine' ),
+ ];
+
+ return $labels[ $status ] ?? ucfirst( $status );
+ }
+
public static function get_affiliates( $args = [] ) {
global $wpdb;
--- a/storeengine/addons/affiliate/models/commission.php
+++ b/storeengine/addons/affiliate/models/commission.php
@@ -103,6 +103,51 @@
]);
}
+ /**
+ * Mark an affiliate's approved commissions as paid, oldest first, until the
+ * cumulative commission amount covers the given payout amount.
+ *
+ * Payouts are recorded as an affiliate + amount (not linked to specific
+ * commission rows), so this reconciles them FIFO when a payout completes.
+ *
+ * @param int $affiliate_id Affiliate whose commissions to settle.
+ * @param float $amount Payout amount to cover.
+ *
+ * @return int Number of commissions marked paid.
+ */
+ public static function mark_approved_as_paid( int $affiliate_id, float $amount ): int {
+ global $wpdb;
+
+ if ( $affiliate_id <= 0 || $amount <= 0 ) {
+ return 0;
+ }
+
+ $rows = $wpdb->get_results( $wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
+ "SELECT commission_id, commission_amount
+ FROM {$wpdb->prefix}storeengine_affiliate_commissions
+ WHERE affiliate_id = %d AND status = 'approved'
+ ORDER BY created_at ASC, commission_id ASC",
+ $affiliate_id
+ ), ARRAY_A );
+
+ if ( empty( $rows ) ) {
+ return 0;
+ }
+
+ $running = 0.0;
+ $count = 0;
+ foreach ( $rows as $row ) {
+ if ( $running >= $amount ) {
+ break;
+ }
+ self::update( (int) $row['commission_id'], [ 'status' => 'paid' ] );
+ $running += (float) $row['commission_amount'];
+ $count++;
+ }
+
+ return $count;
+ }
+
public static function update( int $id, array $args ) {
global $wpdb;
--- a/storeengine/addons/affiliate/models/payout.php
+++ b/storeengine/addons/affiliate/models/payout.php
@@ -40,9 +40,9 @@
}
if ( $args['count'] ) {
- // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
+ // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Identifier passed via %i to prepare(); COUNT over a custom StoreEngine ledger table.
return (int) $wpdb->get_var(
- "SELECT COUNT(*) FROM {$table} WHERE payee_type = 'affiliate'"
+ $wpdb->prepare( 'SELECT COUNT(*) FROM %i WHERE payee_type = %s', $table, 'affiliate' )
);
// phpcs:enable
}
@@ -69,7 +69,7 @@
if ( $args['user_id'] ) {
$query .= $wpdb->prepare( ' AND a.user_id = %d', (int) $args['user_id'] );
- // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
+ // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Trusted table identifiers ($wpdb->prefix/users, repo table constant) interpolated; all user values bound via prepare(); custom StoreEngine tables.
return $wpdb->get_results( $query, ARRAY_A ) ?: [];
// phpcs:enable
}
@@ -80,7 +80,7 @@
$query .= $wpdb->prepare( ' AND u.display_name LIKE %s', '%' . $wpdb->esc_like( $args['search'] ) . '%' );
}
- // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
+ // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Trusted table identifiers interpolated; all user values bound via prepare(); custom StoreEngine tables.
return $wpdb->get_results( $wpdb->prepare(
"{$query} ORDER BY p.created_at DESC LIMIT %d, %d",
(int) $args['offset'],
--- a/storeengine/addons/affiliate/settings/affiliate.php
+++ b/storeengine/addons/affiliate/settings/affiliate.php
@@ -26,7 +26,13 @@
// Commission Settings
'commission_type' => 'percentage',
'commission_rate' => 10,
- 'allow_auto_commission' => false,
+ // Approve (and credit) a referral commission automatically once its
+ // order is paid. On by default so stores don't have to hand-approve
+ // every commission; admins can turn it off in Settings → Affiliate.
+ 'allow_auto_commission' => true,
+ // Off by default: an affiliate can't earn a commission on their own
+ // purchase (buyer matched to the affiliate by user id or email).
+ 'allow_self_referral' => false,
'allow_zero_commission' => true, // Withdraw settings
'minimum_withdraw_amount' => 10,
'is_enabled_paypal_withdraw' => false,
--- a/storeengine/addons/affiliate/shortcode/registration.php
+++ b/storeengine/addons/affiliate/shortcode/registration.php
@@ -15,6 +15,62 @@
public function __construct() {
add_shortcode( 'storeengine_affiliate_application', [ $this, 'registration_form' ] );
+ add_action( 'init', [ $this, 'register_shortcode_block' ], 20 );
+ }
+
+ /**
+ * Expose the affiliate registration form as a configurable block via the
+ * StoreEngine shortcode → block bridge, so the Affiliate Registration page
+ * (and any other page) can drop it in with editor controls. No-op when the
+ * bridge isn't present; the shortcode still works everywhere.
+ */
+ public function register_shortcode_block() {
+ if ( ! function_exists( 'storeengine_register_shortcode_block' ) ) {
+ return;
+ }
+
+ storeengine_register_shortcode_block( [
+ 'tag' => 'storeengine_affiliate_application',
+ 'owner' => 'storeengine',
+ 'title' => __( 'Affiliate Registration', 'storeengine' ),
+ 'category' => __( 'StoreEngine', 'storeengine' ),
+ 'description' => __( 'The affiliate program application / registration form.', 'storeengine' ),
+ 'icon' => 'groups',
+ 'keywords' => [ 'affiliate', 'registration', 'application', 'referral' ],
+ 'attributes' => [
+ [
+ 'name' => 'form_title',
+ 'label' => __( 'Form title', 'storeengine' ),
+ 'type' => 'text',
+ 'default' => __( 'Affiliate Registration Form', 'storeengine' ),
+ 'sanitize' => 'text',
+ ],
+ [
+ 'name' => 'button_text',
+ 'label' => __( 'Submit button label', 'storeengine' ),
+ 'type' => 'text',
+ 'default' => __( 'Register', 'storeengine' ),
+ 'sanitize' => 'text',
+ ],
+ [
+ 'name' => 'alert_text',
+ 'label' => __( 'Logged-out message', 'storeengine' ),
+ 'type' => 'text',
+ 'default' => __( 'Please login to apply for affiliate', 'storeengine' ),
+ 'group' => __( 'Advanced', 'storeengine' ),
+ 'sanitize' => 'text',
+ ],
+ [
+ 'name' => 'terms_url',
+ 'label' => __( 'Terms & conditions URL', 'storeengine' ),
+ 'type' => 'text',
+ 'default' => '',
+ 'placeholder' => __( 'Uses the Affiliate settings URL', 'storeengine' ),
+ 'group' => __( 'Advanced', 'storeengine' ),
+ 'sanitize' => 'url',
+ ],
+ ],
+ ] );
}
public function registration_form( $atts ) {
@@ -43,12 +99,38 @@
'show_logged_in_message' => true,
], $atts );
+ /**
+ * Filters whether the affiliate registration shortcode treats the
+ * current visitor as logged in.
+ *
+ * Returning `false` forces the public registration form to render even
+ * when a user is signed in — its purpose is page-builder editors
+ * (Elementor, Bricks, …), where the editing admin is logged in and would
+ * otherwise only ever see the "already logged in" branch. Consumers MUST
+ * scope their override to the builder's edit/preview context; leaving it
+ * on for the real front end would show signed-in visitors the
+ * account-creating form.
+ *
+ * @since 2.2.0
+ *
+ * @param bool $is_user_logged_in Default WordPress login state.
+ * @param array $attributes Resolved shortcode attributes.
+ */
+ $is_user_logged_in = (bool) apply_filters( 'storeengine/shortcode/affiliate_registration_is_user_logged_in', is_user_logged_in(), $attributes );
+
$affiliate_pending = false;
- if ( is_user_logged_in() ) {
+ if ( $is_user_logged_in ) {
$affiliate_details = Affiliate::get_affiliates( [ 'user_id' => get_current_user_id() ] );
$affiliate_pending = isset( $affiliate_details['status'] ) && 'pending' === $affiliate_details['status'];
}
- $attributes = wp_parse_args( $attributes, [ 'affiliate_pending' => $affiliate_pending ] );
+
+ // Pass the resolved state through so the template reuses this single
+ // evaluation instead of re-running the filter (which could drift if a
+ // consumer's callback isn't deterministic).
+ $attributes = wp_parse_args( $attributes, [
+ 'affiliate_pending' => $affiliate_pending,
+ 'is_user_logged_in' => $is_user_logged_in,
+ ] );
ob_start();
Template::get_template( 'affiliate/registration.php', $attributes);
--- a/storeengine/addons/affiliate/templates/frontend-dashboard/pages/affiliate-locked.php
+++ b/storeengine/addons/affiliate/templates/frontend-dashboard/pages/affiliate-locked.php
@@ -0,0 +1,34 @@
+<?php
+/**
+ * Affiliate dashboard — locked notice.
+ *
+ * Shown in place of the earnings dashboard when the current affiliate's account
+ * is `rejected` or `suspended`. Those accounts cannot earn or track referrals,
+ * so the full dashboard (with its dead referral link) is withheld.
+ *
+ * @var string $status Affiliate status (rejected|suspended).
+ */
+
+use StoreEngineAddonsAffiliatemodelsAffiliate;
+
+if ( ! defined( 'ABSPATH' ) ) {
+ exit;
+}
+
+$status = isset( $status ) ? (string) $status : '';
+
+if ( Affiliate::STATUS_SUSPENDED === $status ) {
+ $heading = __( 'Your affiliate account is suspended', 'storeengine' );
+ $message = __( 'Your affiliate account has been suspended, so referral tracking and commissions are paused. Please contact the store if you think this is a mistake.', 'storeengine' );
+} else {
+ $heading = __( 'Your affiliate application was not approved', 'storeengine' );
+ $message = __( 'Your affiliate application was not approved, so the affiliate dashboard is unavailable. Please contact the store if you have any questions.', 'storeengine' );
+}
+?>
+<div class="storeengine-affiliate-locked" style="max-width:560px;margin:40px auto;padding:32px;text-align:center;border:1px solid var(--storeengine-border-color,#DEDEDE);border-radius:10px;background:#fff;">
+ <span class="storeengine-status storeengine-status--<?php echo esc_attr( $status ); ?>">
+ <?php echo esc_html( Affiliate::status_label( $status ) ); ?>
+ </span>
+ <h2 class="storeengine-affiliate-locked__heading" style="margin:16px 0 8px;font-size:20px;"><?php echo esc_html( $heading ); ?></h2>
+ <p class="storeengine-affiliate-locked__message" style="margin:0;color:var(--storeengine-subtitle-color,#646C73);line-height:1.6;"><?php echo esc_html( $message ); ?></p>
+</div>
--- a/storeengine/addons/brand/brand.php
+++ b/storeengine/addons/brand/brand.php
@@ -149,14 +149,13 @@
* @return array
*/
public function inject_menu_item( array $menu ): array {
- $key = STOREENGINE_PLUGIN_SLUG . '-products';
-
- if ( isset( $menu[ $key ]['sub_items'] ) && is_array( $menu[ $key ]['sub_items'] ) ) {
- $menu[ $key ]['sub_items'][] = [
- 'slug' => 'brands',
- 'title' => __( 'Brands', 'storeengine' ),
- ];
- }
+ // Brands is its own raw-route page (?page=storeengine-brands); the
+ // Products group folds it in as a child — see Menu::menu_groups().
+ $menu[ STOREENGINE_PLUGIN_SLUG . '-brands' ] = [
+ 'title' => __( 'Brands', 'storeengine' ),
+ 'capability' => 'manage_options',
+ 'priority' => 14,
+ ];
return $menu;
}
--- a/storeengine/addons/brand/frontend.php
+++ b/storeengine/addons/brand/frontend.php
@@ -136,9 +136,9 @@
return $args;
}
- $brands = wp_unslash( $_REQUEST['brand'] );
+ $brands = map_deep( wp_unslash( $_REQUEST['brand'] ), 'sanitize_title' );
$brands = is_array( $brands ) ? $brands : [ $brands ];
- $brands = array_filter( array_map( 'sanitize_title', $brands ) );
+ $brands = array_filter( $brands );
// phpcs:enable WordPress.Security.NonceVerification.Recommended
if ( empty( $brands ) ) {
--- a/storeengine/addons/couriers/api.php
+++ b/storeengine/addons/couriers/api.php
@@ -0,0 +1,22 @@
+<?php
+
+namespace StoreEngineAddonsCouriers;
+
+use StoreEngineAddonsCouriersApiProvidersController;
+use StoreEngineAddonsCouriersApiSettingsController;
+use StoreEngineAddonsCouriersApiShipmentsController;
+use StoreEngineAddonsCouriersApiOAuthController;
+
+if ( ! defined( 'ABSPATH' ) ) {
+ exit;
+}
+
+final class Api {
+
+ public static function init(): void {
+ ProvidersController::init();
+ SettingsController::init();
+ ShipmentsController::init();
+ OAuthController::init();
+ }
+}
--- a/storeengine/addons/couriers/api/oauth-controller.php
+++ b/storeengine/addons/couriers/api/oauth-controller.php
@@ -0,0 +1,193 @@
+<?php
+/**
+ * REST endpoints for the courier OAuth (3-legged) connect flow.
+ *
+ * GET /couriers/oauth/{provider}/authorize-url → { url } to send the admin to
+ * GET /couriers/oauth/callback → provider redirect lands here
+ * POST /couriers/oauth/{provider}/disconnect → forget stored tokens
+ *
+ * The callback is intentionally public (the courier redirects a browser to it,
+ * with no WP nonce) and is instead guarded by the one-time `state` minted in
+ * authorize_url() — an unknown/expired state is rejected. On completion it
+ * 302-redirects the browser back to Settings → Couriers with a status flag.
+ *
+ * @package StoreEngineAddonsCouriers
+ */
+
+namespace StoreEngineAddonsCouriersApi;
+
+use StoreEngineAddonsCouriersClassesOAuth;
+use StoreEngineAddonsCouriersClassesRegistry;
+use WP_Error;
+use WP_REST_Request;
+
+if ( ! defined( 'ABSPATH' ) ) {
+ exit;
+}
+
+final class OAuthController {
+
+ const NS = 'storeengine/v1';
+
+ public static function init(): void {
+ add_action( 'rest_api_init', [ __CLASS__, 'register_routes' ] );
+ }
+
+ public static function register_routes(): void {
+ register_rest_route( self::NS, '/couriers/oauth/(?P<provider>[w-]+)/authorize-url', [
+ 'methods' => 'GET',
+ 'callback' => [ __CLASS__, 'authorize_url' ],
+ 'permission_callback' => [ __CLASS__, 'permission' ],
+ 'args' => [
+ 'provider' => [ 'type' => 'string', 'required' => true ],
+ ],
+ ] );
+
+ register_rest_route( self::NS, '/couriers/oauth/(?P<provider>[w-]+)/disconnect', [
+ 'methods' => 'POST',
+ 'callback' => [ __CLASS__, 'disconnect' ],
+ 'permission_callback' => [ __CLASS__, 'permission' ],
+ 'args' => [
+ 'provider' => [ 'type' => 'string', 'required' => true ],
+ ],
+ ] );
+
+ // Verify 2-legged (client_credentials / password) OAuth by minting a token.
+ register_rest_route( self::NS, '/couriers/oauth/(?P<provider>[w-]+)/test', [
+ 'methods' => 'POST',
+ 'callback' => [ __CLASS__, 'test' ],
+ 'permission_callback' => [ __CLASS__, 'permission' ],
+ 'args' => [
+ 'provider' => [ 'type' => 'string', 'required' => true ],
+ ],
+ ] );
+
+ // Public — validated by the one-time `state`, not a nonce.
+ register_rest_route( self::NS, '/couriers/oauth/callback', [
+ 'methods' => 'GET',
+ 'callback' => [ __CLASS__, 'callback' ],
+ 'permission_callback' => '__return_true',
+ ] );
+ }
+
+ public static function permission(): bool {
+ return current_user_can( 'manage_storeengine_settings' )
+ || current_user_can( 'manage_options' );
+ }
+
+ public static function authorize_url( WP_REST_Request $request ) {
+ $provider = (string) $request['provider'];
+ $oauth = OAuth::for_provider( $provider );
+
+ if ( ! $oauth ) {
+ return new WP_Error( 'storeengine_oauth_unsupported', __( 'This courier does not support OAuth.', 'storeengine' ), [ 'status' => 400 ] );
+ }
+ if ( ! $oauth->is_authorization_code() ) {
+ return new WP_Error( 'storeengine_oauth_not_interactive', __( 'This courier uses server credentials — no connect step is required.', 'storeengine' ), [ 'status' => 400 ] );
+ }
+ if ( ! $oauth->is_configured() ) {
+ return new WP_Error( 'storeengine_oauth_unconfigured', __( 'Enter and save the client ID and secret for this courier first.', 'storeengine' ), [ 'status' => 400 ] );
+ }
+
+ return rest_ensure_response( [ 'url' => $oauth->authorize_url() ] );
+ }
+
+ /**
+ * Uniform disconnect for any courier: revoke OAuth tokens for interactive
+ * couriers; for the rest (2-legged OAuth / API-key), "disconnect" clears the
+ * saved credentials so the card returns to a not-connected state.
+ */
+ public static function disconnect( WP_REST_Request $request ) {
+ $id = (string) $request['provider'];
+ $oauth = OAuth::for_provider( $id );
+
+ if ( $oauth ) {
+ $oauth->disconnect();
+ }
+
+ if ( ! $oauth || ! $oauth->is_authorization_code() ) {
+ $all = (array) get_option( 'storeengine_courier_settings', [] );
+ if ( isset( $all[ $id ] ) ) {
+ unset( $all[ $id ] );
+ update_option( 'storeengine_courier_settings', $all );
+ }
+ }
+
+ return rest_ensure_response( [ 'ok' => true, 'connected' => false ] );
+ }
+
+ /**
+ * Test a 2-legged (client_credentials / password) courier by minting a token
+ * from the saved client id/secret — the "auth check" for carriers that have
+ * no interactive connect step.
+ */
+ public static function test( WP_REST_Request $request ) {
+ $oauth = OAuth::for_provider( (string) $request['provider'] );
+ if ( ! $oauth ) {
+ return new WP_Error( 'storeengine_oauth_unsupported', __( 'This courier does not support OAuth.', 'storeengine' ), [ 'status' => 400 ] );
+ }
+ if ( ! $oauth->is_configured() ) {
+ return new WP_Error( 'storeengine_oauth_unconfigured', __( 'Enter and save this courier’s credentials first, then test the connection.', 'storeengine' ), [ 'status' => 400 ] );
+ }
+
+ $token = $oauth->access_token();
+ if ( ! $token ) {
+ return new WP_Error( 'storeengine_oauth_auth_failed', __( 'Could not authenticate with the courier — double-check the credentials.', 'storeengine' ), [ 'status' => 400 ] );
+ }
+
+ return rest_ensure_response( [ 'ok' => true, 'connected' => true ] );
+ }
+
+ /**
+ * Provider redirect target. Validates `state`, exchanges `code`, then bounces
+ * the browser back to the couriers settings screen with a status flag.
+ */
+ public static function callback( WP_REST_Request $request ) {
+ $state = (string) $request->get_param( 'state' );
+ $code = (string) $request->get_param( 'code' );
+ $error = (string) $request->get_param( 'error' );
+
+ $resolved = OAuth::consume_state( $state );
+ if ( ! $resolved ) {
+ return self::bounce( '', 'invalid_state' );
+ }
+
+ $provider = $resolved['provider'];
+
+ // The courier denied consent or reported an error.
+ if ( $error || '' === $code ) {
+ return self::bounce( $provider, $error ?: 'no_code' );
+ }
+
+ $oauth = OAuth::for_provider( $provider );
+ if ( ! $oauth ) {
+ return self::bounce( $provider, 'unsupported' );
+ }
+
+ $result = $oauth->exchange_code( $code );
+ if ( is_wp_error( $result ) ) {
+ return self::bounce( $provider, $result->get_error_code() ?: 'exchange_failed' );
+ }
+
+ return self::bounce( $provider, '' );
+ }
+
+ /**
+ * 302 back to Settings → Couriers with the outcome. Empty $error = success.
+ */
+ private static function bounce( string $provider, string $error ) {
+ $url = add_query_arg(
+ array_filter( [
+ 'page' => 'storeengine-settings',
+ 'path' => 'couriers',
+ 'se_oauth' => $provider,
+ 'oauth_status' => $error ? 'error' : 'success',
+ 'oauth_error' => $error ?: null,
+ ] ),
+ admin_url( 'admin.php' )
+ );
+
+ wp_safe_redirect( $url );
+ exit;
+ }
+}
--- a/storeengine/addons/couriers/api/providers-controller.php
+++ b/storeengine/addons/couriers/api/providers-controller.php
@@ -0,0 +1,123 @@
+<?php
+
+namespace StoreEngineAddonsCouriersApi;
+
+use StoreEngineAddonsCouriersClassesRegistry;
+use StoreEngineAddonsCouriersClassesOAuth;
+use WP_REST_Request;
+use WP_REST_Server;
+
+if ( ! defined( 'ABSPATH' ) ) {
+ exit;
+}
+
+final class ProvidersController {
+
+ const NS = 'storeengine/v1';
+
+ public static function init(): void {
+ add_action( 'rest_api_init', [ __CLASS__, 'register_routes' ] );
+ }
+
+ public static function register_routes(): void {
+ register_rest_route( self::NS, '/couriers/providers', [
+ 'methods' => WP_REST_Server::READABLE,
+ 'callback' => [ __CLASS__, 'list_all' ],
+ 'permission_callback' => [ __CLASS__, 'permission' ],
+ ] );
+
+ register_rest_route( self::NS, '/couriers/providers/pathao/cities', [
+ 'methods' => WP_REST_Server::READABLE,
+ 'callback' => [ __CLASS__, 'pathao_cities' ],
+ 'permission_callback' => [ __CLASS__, 'permission' ],
+ ] );
+
+ register_rest_route( self::NS, '/couriers/providers/pathao/cities/(?P<city_id>d+)/zones', [
+ 'methods' => WP_REST_Server::READABLE,
+ 'callback' => [ __CLASS__, 'pathao_zones' ],
+ 'permission_callback' => [ __CLASS__, 'permission' ],
+ ] );
+ }
+
+ public static function permission(): bool {
+ return current_user_can( 'manage_options' )
+ || current_user_can( 'manage_storeengine_settings' )
+ || current_user_can( 'edit_storeengine_orders' );
+ }
+
+ public static function list_all() {
+ $out = [];
+ foreach ( Registry::all() as $id => $provider ) {
+ $out[] = [
+ 'id' => $id,
+ 'label' => $provider->label(),
+ 'settings_schema' => $provider->settings_schema(),
+ 'oauth' => self::oauth_state( $id ),
+ // One uniform "connected" flag the UI reads for every courier:
+ // a live OAuth token for interactive couriers, saved credentials
+ // for everyone else. Drives the single Connect/Disconnect button.
+ 'connected' => self::is_connected( $id, $provider ),
+ // Setup docs + where to get credentials (staging vs production).
+ 'docs' => method_exists( $provider, 'docs' ) ? (array) $provider->docs() : [],
+ ];
+ }
+ return rest_ensure_response( $out );
+ }
+
+ private static function is_connected( string $id, $provider ): bool {
+ $oauth = OAuth::for_provider( $id );
+ if ( $oauth && $oauth->is_authorization_code() ) {
+ return $oauth->is_connected();
+ }
+ // "Connected" for non-interactive couriers = auth credentials present
+ // (not the full shipping config); is_authenticated() narrows to those.
+ if ( method_exists( $provider, 'is_authenticated' ) ) {
+ return (bool) $provider->is_authenticated();
+ }
+ return method_exists( $provider, 'is_configured' ) ? (bool) $provider->is_configured() : false;
+ }
+
+ /**
+ * OAuth connection state for a provider, so the settings UI can render a
+ * Connect / Disconnect control for the 3-legged (authorization_code) flow.
+ * `supported` is false for API-key providers and 2-legged carriers (which
+ * need no interactive connect step).
+ *
+ * @return array{supported:bool,grant?:string,interactive?:bool,configured?:bool,connected?:bool,expires_at?:int|null}
+ */
+ private static function oauth_state( string $id ): array {
+ $oauth = OAuth::for_provider( $id );
+ if ( ! $oauth ) {
+ return [ 'supported' => false ];
+ }
+
+ return [
+ 'supported' => true,
+ 'grant' => $oauth->grant(),
+ // Only the authorization_code grant needs a user-facing Connect button.
+ 'interactive' => $oauth->is_authorization_code(),
+ 'configured' => $oauth->is_configured(),
+ 'connected' => $oauth->is_connected(),
+ 'expires_at' => $oauth->expires_at(),
+ ];
+ }
+
+ public static function pathao_cities() {
+ // Pathao now ships in the storeengine-courier satellite; resolve it off
+ // the provider registry and duck-type its lookup helper rather than
+ // hard-referencing the concrete class (which no longer lives in Pro).
+ $pathao = Registry::get( 'pathao' );
+ if ( ! $pathao || ! method_exists( $pathao, 'list_cities' ) ) {
+ return rest_ensure_response( [] );
+ }
+ return rest_ensure_response( $pathao->list_cities() );
+ }
+
+ public static function pathao_zones( WP_REST_Request $request ) {
+ $pathao = Registry::get( 'pathao' );
+ if ( ! $pathao || ! method_exists( $pathao, 'list_zones' ) ) {
+ return rest_ensure_response( [] );
+ }
+ return rest_ensure_response( $pathao->list_zones( (int) $request['city_id'] ) );
+ }
+}
--- a/storeengine/addons/couriers/api/settings-controller.php
+++ b/storeengine/addons/couriers/api/settings-controller.php
@@ -0,0 +1,129 @@
+<?php
+
+namespace StoreEngineAddonsCouriersApi;
+
+use StoreEngineAddonsCouriersClassesAutoPush;
+use StoreEngineAddonsCouriersClassesOrderStatusSync;
+use StoreEngineAddonsCouriersClassesRegistry;
+use WP_REST_Request;
+use WP_REST_Server;
+
+if ( ! defined( 'ABSPATH' ) ) {
+ exit;
+}
+
+final class SettingsController {
+
+ const NS = 'storeengine/v1';
+ const OPT = 'storeengine_courier_settings';
+
+ public static function init(): void {
+ add_action( 'rest_api_init', [ __CLASS__, 'register_routes' ] );
+ }
+
+ public static function register_routes(): void {
+ register_rest_route( self::NS, '/couriers/settings', [
+ [
+ 'methods' => WP_REST_Server::READABLE,
+ 'callback' => [ __CLASS__, 'fetch' ],
+ 'permission_callback' => [ __CLASS__, 'permission' ],
+ ],
+ [
+ 'methods' => WP_REST_Server::EDITABLE,
+ 'callback' => [ __CLASS__, 'save' ],
+ 'permission_callback' => [ __CLASS__, 'permission' ],
+ ],
+ ] );
+ }
+
+ public static function permission(): bool {
+ return current_user_can( 'manage_storeengine_settings' )
+ || current_user_can( 'manage_options' );
+ }
+
+ public static function fetch() {
+ $saved = (array) get_option( self::OPT, [] );
+
+ // Mask secret-typed fields when returning.
+ $masked = [];
+ foreach ( Registry::all() as $id => $provider ) {
+ $cfg = is_array( $saved[ $id ] ?? null ) ? $saved[ $id ] : [];
+ $schema = $provider->settings_schema();
+ $row = [];
+ foreach ( $schema as $field ) {
+ $key = $field['key'];
+ $value = $cfg[ $key ] ?? '';
+ if ( ( $field['type'] ?? '' ) === 'password' && $value ) {
+ $value = '••••••••';
+ }
+ $row[ $key ] = $value;
+ }
+ $masked[ $id ] = $row;
+ }
+
+ return rest_ensure_response( [
+ 'providers' => $masked,
+ 'auto_push' => self::default_auto_push( AutoPush::get_auto_push_config() ),
+ 'sync' => OrderStatusSync::get_sync_config(),
+ ] );
+ }
+
+ public static function save( WP_REST_Request $request ) {
+ $body = (array) $request->get_json_params();
+ $saved = (array) get_option( self::OPT, [] );
+
+ // Allow either flat (legacy) or { providers, auto_push } shape on input.
+ $providers_in = isset( $body['providers'] ) && is_array( $body['providers'] )
+ ? $body['providers']
+ : $body;
+
+ foreach ( Registry::all() as $id => $provider ) {
+ if ( ! isset( $providers_in[ $id ] ) || ! is_array( $providers_in[ $id ] ) ) continue;
+ $incoming = $providers_in[ $id ];
+ $existing = is_array( $saved[ $id ] ?? null ) ? $saved[ $id ] : [];
+ $schema = $provider->settings_schema();
+ $next = $existing;
+
+ foreach ( $schema as $field ) {
+ $key = $field['key'];
+ $type = $field['type'] ?? 'string';
+ if ( ! array_key_exists( $key, $incoming ) ) continue;
+ $value = $incoming[ $key ];
+ // Skip masked-bullets so users can save without re-entering secrets.
+ if ( 'password' === $type && '••••••••' === $value ) continue;
+
+ if ( 'boolean' === $type ) {
+ $next[ $key ] = (bool) $value;
+ } else {
+ $next[ $key ] = sanitize_text_field( (string) $value );
+ }
+ }
+
+ $saved[ $id ] = $next;
+ }
+
+ update_option( self::OPT, $saved, false );
+
+ // Auto-push config lives in the same option, separate top-level key.
+ if ( isset( $body['auto_push'] ) && is_array( $body['auto_push'] ) ) {
+ AutoPush::set_auto_push_config( $body['auto_push'] );
+ }
+
+ // Status-sync config (auto_complete_on_delivered, flip_on_return).
+ if ( isset( $body['sync'] ) && is_array( $body['sync'] ) ) {
+ OrderStatusSync::set_sync_config( $body['sync'] );
+ }
+
+ return self::fetch();
+ }
+
+ protected static function default_auto_push( array $cfg ): array {
+ return [
+ 'enabled' => (bool) ( $cfg['enabled'] ?? false ),
+ 'provider' => (string) ( $cfg['provider'] ?? '' ),
+ 'default_weight_kg' => isset( $cfg['default_weight_kg'] ) ? (float) $cfg['default_weight_kg'] : 0.5,
+ 'use_cod_when' => (string) ( $cfg['use_cod_when'] ?? 'cod_payment_method' ),
+ 'cod_methods' => array_values( (array) ( $cfg['cod_methods'] ?? [] ) ),
+ ];
+ }
+}
--- a/storeengine/addons/couriers/api/shipments-controller.php
+++ b/storeengine/addons/couriers/api/shipments-controller.php
@@ -0,0 +1,162 @@
+<?php
+
+namespace StoreEngineAddonsCouriersApi;
+
+use StoreEngineUtilsHelper;
+use StoreEngineAddonsCouriersClassesAutoPush;
+use StoreEngineAddonsCouriersClassesOrderPayloadMapper;
+use StoreEngineAddonsCouriersClassesShipmentsService;
+use WP_Error;
+use WP_REST_Request;
+use WP_REST_Server;
+
+if ( ! defined( 'ABSPATH' ) ) {
+ exit;
+}
+
+final class ShipmentsController {
+
+ const NS = 'storeengine/v1';
+
+ public static function init(): void {
+ add_action( 'rest_api_init', [ __CLASS__, 'register_routes' ] );
+ }
+
+ public static function register_routes(): void {
+ register_rest_route( self::NS, '/couriers/shipments', [
+ [
+ 'methods' => WP_REST_Server::READABLE,
+ 'callback' => [ __CLASS__, 'list_all' ],
+ 'permission_callback' => [ __CLASS__, 'permission' ],
+ 'args' => [
+ 'order_id' => [ 'type' => 'integer' ],
+ 'provider' => [ 'type' => 'string' ],
+ 'status' => [ 'type' => 'string' ],
+ 'per_page' => [ 'type' => 'integer', 'default' => 50, 'minimum' => 1, 'maximum' => 100 ],
+ 'page' => [ 'type' => 'integer', 'default' => 1 ],
+ ],
+ ],
+ [
+ 'methods' => WP_REST_Server::CREATABLE,
+ 'callback' => [ __CLASS__, 'create' ],
+ 'permission_callback' => [ __CLASS__, 'permission' ],
+ 'args' => [
+ 'order_id' => [ 'type' => 'integer', 'required' => true ],
+ 'provider' => [ 'type' => 'string', 'required' => true ],
+ 'customer_name' => [ 'type' => 'string' ],
+ 'customer_phone' => [ 'type' => 'string' ],
+ 'customer_address' => [ 'type' => 'string' ],
+ 'city' => [ 'type' => 'string' ],
+ 'state' => [ 'type' => 'string' ],
+ 'postcode' => [ 'type' => 'string' ],
+ 'country' => [ 'type' => 'string' ],
+ 'cod_amount' => [ 'type' => 'number' ],
+ 'weight_kg' => [ 'type' => 'number' ],
+ 'item_description' => [ 'type' => 'string' ],
+ 'city_id' => [ 'type' => 'integer' ],
+ 'zone_id' => [ 'type' => 'integer' ],
+ 'delivery_type' => [ 'type' => 'integer' ],
+ 'vendor_id' => [ 'type' => 'integer' ],
+ ],
+ ],
+ ] );
+
+ register_rest_route( self::NS, '/couriers/shipments/(?P<id>d+)/track', [
+ 'methods' => WP_REST_Server::CREATABLE,
+ 'callback' => [ __CLASS__, 'track' ],
+ 'permission_callback' => [ __CLASS__, 'permission' ],
+ ] );
+
+ register_rest_route( self::NS, '/couriers/shipments/(?P<id>d+)/cancel', [
+ 'methods' => WP_REST_Server::CREATABLE,
+ 'callback' => [ __CLASS__, 'cancel' ],
+ 'permission_callback' => [ __CLASS__, 'permission' ],
+ ] );
+
+ register_rest_route( self::NS, '/couriers/orders/(?P<id>d+)/shipment-defaults', [
+ 'methods' => WP_REST_Server::READABLE,
+ 'callback' => [ __CLASS__, 'shipment_defaults' ],
+ 'permission_callback' => [ __CLASS__, 'permission' ],
+ ] );
+ }
+
+ public static function permission(): bool {
+ return current_user_can( 'manage_options' )
+ || current_user_can( 'edit_storeengine_orders' )
+ || current_user_can( 'manage_storeengine_settings' );
+ }
+
+ public static function list_all( WP_REST_Request $request ) {
+ return rest_ensure_response( ShipmentsService::all( $request->get_params() ) );
+ }
+
+ public static function create( WP_REST_Request $request ) {
+ $payload = $request->get_params();
+ $order_id = (int) $payload['order_id'];
+ $provider = (string) $payload['provider'];
+ unset( $payload['order_id'], $payload['provider'] );
+
+ $order = Helper::get_order( $order_id );
+ if ( $order && ! is_wp_error( $order ) ) {
+ $defaults = OrderPayloadMapper::build_payload( $order, AutoPush::get_auto_push_config() );
+ foreach ( $defaults as $k => $v ) {
+ if ( ! isset( $payload[ $k ] ) || '' === $payload[ $k ] || null === $payload[ $k ] ) {
+ $payload[ $k ] = $v;
+ }
+ }
+ // Provider extras (line items, subtotal) — admin doesn't type these.
+ $payload = array_merge( $payload, OrderPayloadMapper::build_provider_extras( $order, $provider ) );
+ }
+
+ $result = ShipmentsService::create_for_order( $order_id, $provider, $payload );
+ if ( empty( $result['ok'] ) ) {
+ return new WP_Error( 'create_failed', implode( ', ', $result['errors'] ?? [] ), [ 'status' => 400 ] );
+ }
+
+ return rest_ensure_response( ShipmentsService::get( (int) $result['shipment_id'] ) );
+ }
+
+ public static function track( WP_REST_Request $request ) {
+ $result = ShipmentsService::refresh_status( (int) $request['id'] );
+ if ( empty( $result['ok'] ) ) {
+ return new WP_Error( 'track_failed', implode( ', ', $result['errors'] ?? [] ), [ 'status' => 400 ] );
+ }
+ return rest_ensure_response( ShipmentsService::get( (int) $request['id'] ) );
+ }
+
+ public static function cancel( WP_REST_Request $request ) {
+ $result = ShipmentsService::cancel( (int) $request['id'] );
+ if ( empty( $result['ok'] ) ) {
+ return new WP_Error( 'cancel_failed', implode( ', ', $result['errors'] ?? [] ), [ 'status' => 400 ] );
+ }
+ return rest_ensure_response( ShipmentsService::get( (int) $request['id'] ) );
+ }
+
+ public static function shipment_defaults( WP_REST_Request $request ) {
+ $order = Helper::get_order( (int) $request['id'] );
+ if ( ! $order || is_wp_error( $order ) ) {
+ return new WP_Error( 'order_not_found', __( 'Order not found.', 'storeengine' ), [ 'status' => 404 ] );
+ }
+
+ $defaults = OrderPayloadMapper::build_payload( $order, AutoPush::get_auto_push_config() );
+ $line_items = OrderPayloadMapper::build_line_items( $order );
+
+ $subtotal = method_exists( $order, 'get_subtotal' )
+ ? (float) $order->get_subtotal()
+ : ( method_exists( $order, 'get_total' ) ? (float) $order->get_total() : 0.0 );
+
+ $status = method_exists( $order, 'get_status' ) ? (string) $order->get_status() : '';
+ $currency = method_exists( $order, 'get_currency' ) ? (string) $order->get_currency() : '';
+
+ return rest_ensure_response( array_merge( $defaults, [
+ '_meta' => [
+ 'order_id' => (int) ( method_exists( $order, 'get_id' ) ? $order->get_id() : $request['id'] ),
+ 'order_status' => $status,
+ 'currency' => $currency,
+ 'subtotal' => $subtotal,
+ 'line_item_count' => count( $line_items ),
+ 'line_items' => $line_items,
+ ],
+ ] ) );
+ }
+}
--- a/storeengine/addons/couriers/classes/abstract-provider.php
+++ b/storeengine/addons/couriers/classes/abstract-provider.php
@@ -0,0 +1,90 @@
+<?php
+
+namespace StoreEngineAddonsCouriersClasses;
+
+if ( ! defined( 'ABSPATH' ) ) {
+ exit;
+}
+
+abstract class AbstractProvider implements ProviderInterface {
+
+ /**
+ * @return array<string,mixed>
+ */
+ protected function settings(): array {
+ $all = (array) get_option( 'storeengine_courier_settings', [] );
+ return isset( $all[ $this->id() ] ) && is_array( $all[ $this->id() ] ) ? $all[ $this->id() ] : [];
+ }
+
+ protected function get_setting( string $key, $default = '' ) {
+ $s = $this->settings();
+ return $s[ $key ] ?? $default;
+ }
+
+ protected function http_post( string $url, array $body, array $headers = [] ): array {
+ $response = wp_remote_post( $url, [
+ 'headers' => array_merge( [ 'Content-Type' => 'application/json', 'Accept' => 'application/json' ], $headers ),
+ 'body' => wp_json_encode( $body ),
+ 'timeout' => 30,
+ 'data_format' => 'body',
+ ] );
+ return $this->parse_response( $response );
+ }
+
+ protected function http_get( string $url, array $headers = [] ): array {
+ $response = wp_remote_get( $url, [
+ 'headers' => array_merge( [ 'Accept' => 'application/json' ], $headers ),
+ 'timeout' => 30,
+ ] );
+ return $this->parse_response( $response );
+ }
+
+ /**
+ * Default raw → internal status mapper. Each provider should override
+ * to handle its own status vocabulary; this fallback covers the common
+ * lowercase aliases.
+ */
+ protected function map_status( string $raw ): string {
+ $s = strtolower( trim( $raw ) );
+
+ if ( '' === $s ) return ShipmentStatus::CREATED;
+
+ $exact = [
+ 'delivered' => ShipmentStatus::DELIVERED,
+ 'partial_delivered' => ShipmentStatus::DELIVERED,
+ 'cancelled' => ShipmentStatus::CANCELLED,
+ 'canceled' => ShipmentStatus::CANCELLED,
+ 'returned' => ShipmentStatus::RETURNED,
+ 'in_transit' => ShipmentStatus::IN_TRANSIT,
+ 'in transit' => ShipmentStatus::IN_TRANSIT,
+ 'out_for_delivery' => ShipmentStatus::OUT_FOR_DELIVERY,
+ 'out for delivery' => ShipmentStatus::OUT_FOR_DELIVERY,
+ 'picked_up' => ShipmentStatus::PICKED_UP,
+ 'in_review' => ShipmentStatus::CREATED,
+ ];
+ if ( isset( $exact[ $s ] ) ) return $exact[ $s ];
+
+ if ( false !== strpos( $s, 'return' ) ) return ShipmentStatus::RETURNED;
+ if ( false !== strpos( $s, 'cancel' ) ) return ShipmentStatus::CANCELLED;
+ if ( false !== strpos( $s, 'pickup' ) ) return ShipmentStatus::PICKED_UP;
+ if ( false !== strpos( $s, 'transit' ) || false !== strpos( $s, 'sorting' ) ) return ShipmentStatus::IN_TRANSIT;
+ if ( false !== strpos( $s, 'delivery' ) ) return ShipmentStatus::OUT_FOR_DELIVERY;
+
+ return ShipmentStatus::CREATED;
+ }
+
+ protected function parse_response( $response ): array {
+ if ( is_wp_error( $response ) ) {
+ return [ 'ok' => false, 'errors' => [ $response->get_error_message() ] ];
+ }
+ $code = wp_remote_retrieve_response_code( $response );
+ $body = json_decode( wp_remote_retrieve_body( $response ), true );
+
+ if ( $code < 200 || $code >= 300 ) {
+ $msg = is_array( $body ) && isset( $body['message'] ) ? $body['message'] : ( 'HTTP ' . $code );
+ return [ 'ok' => false, 'errors' => [ $msg ], 'raw' => $body ];
+ }
+
+ return [ 'ok' => true, 'raw' => is_array( $body ) ? $body : [] ];
+ }
+}
--- a/storeengine/addons/couriers/classes/auto-push.php
+++ b/storeengine/addons/couriers/classes/auto-push.php
@@ -0,0 +1,196 @@
+<?php
+
+namespace StoreEngineAddonsCouriersClasses;
+
+use StoreEngineUtilsHelper;
+
+if ( ! defined( 'ABSPATH' ) ) {
+ exit;
+}
+
+/**
+ * Optional: auto-push paid orders to a configured courier provider.
+ *
+ * Listens for `storeengine/payment_complete` and, if `auto_push.enabled`
+ * is true in the courier-settings option, calls the chosen provider's
+ * `create_shipment()` with the order's billing address. POS sales are
+ * skipped (cashier already handed the goods over). Online order numbers
+ * are tagged with `_storeengine_courier_auto_pushed` to prevent duplicates
+ * if the action fires twice (e.g. due to gateway retry).
+ */
+final class AutoPush {
+
+ const META_KEY = '_storeengine_courier_auto_pushed';
+ const OPT_KEY = 'storeengine_courier_settings';
+
+ const ASYNC_HOOK = 'storeengine/couriers/auto_push';
+
+ public static function init(): void {
+ add_action( 'storeengine/payment_complete', [ __CLASS__, 'maybe_push' ], 40 );
+ add_action( self::ASYNC_HOOK, [ __CLASS__, 'run_push' ], 10, 1 );
+ }
+
+ /**
+ * Runs inside the user-facing payment-complete request. Does only cheap local
+ * checks, then hands the courier API calls (which are external HTTP with a 30s
+ * timeout, one per vendor) to Action Scheduler so they never block checkout or
+ * a gateway callback. Falls back to inline execution only if Action Scheduler
+ * is unavailable.
+ */
+ public static function maybe_push( int $order_id ): void {
+ if ( ! $order_id ) {
+ return;
+ }
+
+ $cfg = self::get_auto_push_config();
+ if ( empty( $cfg['enabled'] ) || empty( $cfg['provider'] ) ) {
+ return;
+ }
+
+ // Skip POS sales — cashier hands goods to the customer in person.
+ if ( 'pos' === get_post_meta( $order_id, '_storeengine_pos_source', true ) ) {
+ return;
+ }
+
+ // Idempotency guard — already pushed (or queued and completed).
+ if ( get_post_meta( $order_id, self::META_KEY, true ) ) {
+ return;
+ }
+
+ if ( function_exists( 'as_enqueue_async_action' ) ) {
+ $args = [ 'order_id' => $order_id ];
+ if ( ! function_exists( 'as_next_scheduled_action' ) || false === as_next_scheduled_action( self::ASYNC_HOOK, $args, 'storeengine-couriers' ) ) {
+ as_enqueue_async_action( self::ASYNC_HOOK, $args, 'storeengine-couriers' );
+ }
+ return;
+ }
+
+ // Action Scheduler not loaded — do it inline as a last resort.
+ self::run_push( $order_id );
+ }
+
+ public static function get_auto_push_config(): array {
+ $all = (array) get_option( self::OPT_KEY, [] );
+ return is_array( $all['auto_push'] ?? null ) ? $all['auto_push'] : [];
+ }
+
+ public static function set_auto_push_config( array $cfg ): void {
+ $all = (array) get_option( self::OPT_KEY, [] );
+ $all['auto_push'] = [
+ 'enabled' => (bool) ( $cfg['enabled'] ?? false ),
+ 'provider' => isset( $cfg['provider'] ) ? sanitize_key( (string) $cfg['provider'] ) : '',
+ 'default_weight_kg' => isset( $cfg['default_weight_kg'] ) ? (float) $cfg['default_weight_kg'] : 0.5,
+ 'use_cod_when' => isset( $cfg['use_cod_when'] ) ? sanitize_key( (string) $cfg['use_cod_when'] ) : 'cod_payment_method',
+ 'cod_methods' => array_values( array_filter(
+ array_map( 'sanitize_text_field', (array) ( $cfg['cod_methods'] ?? [] ) )
+ ) ),
+ ];
+ update_option( self::OPT_KEY, $all, false );
+ }
+
+ /**
+ * The actual courier push (external HTTP). Runs via Action Scheduler, off the
+ * user-facing request. Re-checks config and the idempotency guard because the
+ * order/settings may have changed between enqueue and execution.
+ */
+ public static function run_push( int $order_id ): void {
+ if ( ! $order_id ) return;
+
+ $cfg = self::get_auto_push_config();
+ if ( empty( $cfg['enabled'] ) || empty( $cfg['provider'] ) ) {
+ return;
+ }
+
+ // Skip POS sales — cashier hands goods to the customer in person.
+ $source = get_post_meta( $order_id, '_storeengine_pos_source', true );
+ if ( 'pos' === $source ) return;
+
+ // Idempotency guard.
+ if ( get_post_meta( $order_id, self::META_KEY, true ) ) return;
+
+ $order = Helper::get_order( $order_id );
+ if ( ! $order ) return;
+
+ $payload = OrderPayloadMapper::build_payload( $order, $cfg );
+ if ( empty( $payload['customer_phone'] ) ) {
+ // No phone → courier APIs reject; record a note and bail.
+ update_post_meta( $order_id, self::META_KEY, 'skipped_no_phone' );
+ return;
+ }
+
+ $payload = array_merge(
+ $payload,
+ OrderPayloadMapper::build_provider_extras( $order, (string) $cfg['provider'] )
+ );
+
+ // Multi-vendor: split into one shipment per distinct vendor so each
+ // courier dispatch goes to the correct warehouse. Single-vendor orders
+ // still produce exactly one shipment.
+ $vendor_groups = self::group_items_by_vendor( $order );
+ $created_ids = [];
+
+ if ( count( $vendor_groups ) <= 1 ) {
+ $vendor_id = array_key_first( $vendor_groups );
+ $payload['vendor_id'] = $vendor_id ?: null;
+
+ $result = ShipmentsService::create_for_order(
+ $order_id,
+ (string) $cfg['provider'],
+ $payload
+ );
+ if ( ! empty( $result['ok'] ) ) {
+ $created_ids[] = (int) $result['shipment_id'];
+ }
+ } else {
+ foreach ( $vendor_groups as $vendor_id => $_lines ) {
+ $vendor_payload = $payload;
+ $vendor_payload['vendor_id'] = $vendor_id;
+ $result = ShipmentsService::create_for_order(
+ $order_id,
+ (string) $cfg['provider'],
+ $vendor_payload
+ );
+ if ( ! empty( $result['ok'] ) ) {
+ $created_ids[] = (int) $result['shipment_id'];
+ }
+ }
+ }
+
+ if ( $created_ids ) {
+ update_post_meta( $order_id, self::META_KEY, count( $created_ids ) > 1 ? implode( ',', $created_ids ) : (int) $created_ids[0] );
+
+ foreach ( $created_ids as $shipment_id ) {
+ do_action( 'storeengine/courier/auto_pushed', $order_id, $shipment_id, (string) $cfg['provider'] );
+ }
+ } else {
+ update_post_meta(
+ $order_id,
+ self::META_KEY,
+ 'failed:no_shipments_created'
+ );
+ }
+ }
+
+ /**
+ * Group an order's line