feat(affiliate): add core module, controllers, and route registration

This commit is contained in:
Dwindi Ramadhana
2026-06-01 00:57:42 +07:00
parent 396ca25be4
commit 53209c4381
10 changed files with 1678 additions and 0 deletions

View File

@@ -0,0 +1,252 @@
<?php
/**
* Affiliate Lifecycle
*
* Handles order status changes (refunds, cancellations) and auto-approvals.
*
* @package WooNooW\Modules\Affiliate
*/
namespace WooNooW\Modules\Affiliate;
if (!defined('ABSPATH')) exit;
class AffiliateLifecycle
{
/**
* Initialize lifecycle hooks
*/
public static function init()
{
// Cancel/Revert on order refund or cancellation
add_action('woocommerce_order_status_refunded', [__CLASS__, 'handle_order_cancelled']);
add_action('woocommerce_order_status_cancelled', [__CLASS__, 'handle_order_cancelled']);
add_action('woocommerce_order_status_failed', [__CLASS__, 'handle_order_cancelled']);
// Handle order completion - immediate approval
add_action('woocommerce_order_status_completed', [__CLASS__, 'handle_order_completed']);
// HPOS compatible hooks
add_action('woocommerce_order_status_changed', [__CLASS__, 'handle_hpos_status_changed'], 10, 4);
add_action('woocommerce_update_order', [__CLASS__, 'handle_order_updated'], 10, 2);
// Handle order deletion (trash + permanent delete)
add_action('before_delete_post', [__CLASS__, 'handle_order_deleted'], 10, 1);
add_action('woocommerce_delete_order', [__CLASS__, 'handle_order_deleted'], 10, 1);
// Action Scheduler Hook for auto-approval
add_action('woonoow_approve_referral', [__CLASS__, 'auto_approve_referral']);
}
/**
* Handle cancelled, refunded, or failed orders
*/
public static function handle_order_cancelled($order_id)
{
global $wpdb;
$referrals_table = $wpdb->prefix . 'woonoow_referrals';
// Get the order to determine the reason
$order = wc_get_order($order_id);
$reason = 'order_cancelled';
if ($order) {
$status = $order->get_status();
$reason = 'order_' . $status;
}
// Find pending or approved referral
$referral = $wpdb->get_row($wpdb->prepare(
"SELECT * FROM $referrals_table WHERE order_id = %d AND status IN ('pending', 'approved')",
$order_id
));
if ($referral) {
// If was already approved, this is a clawback - decrease affiliate earnings
if ($referral->status === 'approved') {
$affiliates_table = $wpdb->prefix . 'woonoow_affiliates';
$wpdb->query($wpdb->prepare(
"UPDATE $affiliates_table SET total_earnings = total_earnings - %f WHERE id = %d",
$referral->commission_amount,
$referral->affiliate_id
));
}
// Update status to rejected with reason
$wpdb->update(
$referrals_table,
[
'status' => 'rejected',
'cancelled_reason' => $reason,
'cancelled_at' => current_time('mysql')
],
['id' => $referral->id]
);
// Unschedule action if action scheduler exists
if (function_exists('as_unschedule_all_actions')) {
as_unschedule_all_actions('woonoow_approve_referral', ['referral_id' => $referral->id], 'woonoow_affiliate');
}
}
}
/**
* Handle order completion - check if referral should be approved
*/
public static function handle_order_completed($order_id)
{
global $wpdb;
$referrals_table = $wpdb->prefix . 'woonoow_referrals';
// Find pending referral for this order
$referral = $wpdb->get_row($wpdb->prepare(
"SELECT * FROM $referrals_table WHERE order_id = %d AND status = 'pending'",
$order_id
));
if (!$referral) return;
// Check if holding period is 0 (immediate approval on completion)
$holding_period = (int) get_option('woonoow_affiliate_holding_period', 14);
if ($holding_period === 0) {
// Immediate approval
self::auto_approve_referral($referral->id);
} else {
// If order was completed BEFORE the scheduled action time, approve now
// Otherwise, the scheduled action will approve later
// Check if the scheduled action time has already passed
$approval_time = strtotime($referral->created_at) + ($holding_period * DAY_IN_SECONDS);
if (time() >= $approval_time) {
self::auto_approve_referral($referral->id);
}
// If not, the scheduled Action Scheduler job will handle it
}
// Cancel the scheduled auto-approval since we're handling it now
if (function_exists('as_unschedule_all_actions')) {
as_unschedule_all_actions('woonoow_approve_referral', ['referral_id' => $referral->id], 'woonoow_affiliate');
}
}
/**
* Handle HPOS order status change
*/
public static function handle_hpos_status_changed($order_id, $from_status, $to_status, $order)
{
if ($to_status === 'completed') {
self::handle_order_completed($order_id);
}
}
/**
* Handle order update (HPOS compatible)
*/
public static function handle_order_updated($order_id, $order)
{
if (!$order) return;
// Check if order was just completed
$status = $order->get_status();
if ($status === 'completed') {
self::handle_order_completed($order_id);
}
}
/**
* Handle order deletion (permanent delete or trash)
*/
public static function handle_order_deleted($order_id)
{
// Check if this is a WooCommerce order
$order = wc_get_order($order_id);
if (!$order) return;
// Only process shop orders
$post_type = get_post_type($order_id);
if ($post_type !== 'shop_order') return;
global $wpdb;
$referrals_table = $wpdb->prefix . 'woonoow_referrals';
// Find any referral for this order
$referral = $wpdb->get_row($wpdb->prepare(
"SELECT * FROM $referrals_table WHERE order_id = %d",
$order_id
));
if ($referral) {
// If was already approved, this is a clawback - decrease affiliate earnings
if ($referral->status === 'approved') {
$affiliates_table = $wpdb->prefix . 'woonoow_affiliates';
$wpdb->query($wpdb->prepare(
"UPDATE $affiliates_table SET total_earnings = total_earnings - %f WHERE id = %d",
$referral->commission_amount,
$referral->affiliate_id
));
}
// Mark as rejected with "order_deleted" reason
$wpdb->update(
$referrals_table,
[
'status' => 'rejected',
'cancelled_reason' => 'order_deleted',
'cancelled_at' => current_time('mysql')
],
['id' => $referral->id]
);
// Unschedule any pending approval action
if (function_exists('as_unschedule_all_actions')) {
as_unschedule_all_actions('woonoow_approve_referral', ['referral_id' => $referral->id], 'woonoow_affiliate');
}
}
}
/**
* Action Scheduler callback for auto-approving a referral after the holding period
*/
public static function auto_approve_referral($referral_id)
{
global $wpdb;
$referrals_table = $wpdb->prefix . 'woonoow_referrals';
$affiliates_table = $wpdb->prefix . 'woonoow_affiliates';
// Find pending referral
$referral = $wpdb->get_row($wpdb->prepare(
"SELECT * FROM $referrals_table WHERE id = %d AND status = 'pending'",
$referral_id
));
if (!$referral) return; // Already processed or deleted
// Double check order status
$order = wc_get_order($referral->order_id);
if (!$order || in_array($order->get_status(), ['refunded', 'cancelled', 'failed'])) {
self::handle_order_cancelled($referral->order_id);
return;
}
// Approve referral
$wpdb->update(
$referrals_table,
[
'status' => 'approved',
'approved_at' => current_time('mysql')
],
['id' => $referral_id]
);
// Update Affiliate totals
$wpdb->query($wpdb->prepare(
"UPDATE $affiliates_table SET
total_referrals = total_referrals + 1,
total_earnings = total_earnings + %f
WHERE id = %d",
$referral->commission_amount,
$referral->affiliate_id
));
}
}

View File

@@ -0,0 +1,156 @@
<?php
/**
* Affiliate Manager
*
* Handles database table creation and core management.
*
* @package WooNooW\Modules\Affiliate
*/
namespace WooNooW\Modules\Affiliate;
if (!defined('ABSPATH')) exit;
class AffiliateManager
{
private static $affiliates_table = 'woonoow_affiliates';
private static $referrals_table = 'woonoow_referrals';
private static $payouts_table = 'woonoow_affiliate_payouts';
/**
* Initialize
*/
public static function init()
{
// Initialization logic for the manager if needed
}
/**
* Create database tables
*/
public static function create_tables()
{
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
$affiliates_table = $wpdb->prefix . self::$affiliates_table;
$referrals_table = $wpdb->prefix . self::$referrals_table;
$payouts_table = $wpdb->prefix . self::$payouts_table;
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
// Affiliates Table
$sql_affiliates = "CREATE TABLE $affiliates_table (
id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
user_id bigint(20) UNSIGNED NOT NULL,
referral_code varchar(50) NOT NULL,
coupon_id bigint(20) UNSIGNED DEFAULT NULL,
commission_rate decimal(10,2) NOT NULL DEFAULT '0.00',
custom_commission_rate decimal(10,2) DEFAULT NULL,
status varchar(20) NOT NULL DEFAULT 'pending',
total_referrals int(11) NOT NULL DEFAULT 0,
total_earnings decimal(19,4) NOT NULL DEFAULT '0.0000',
paid_earnings decimal(19,4) NOT NULL DEFAULT '0.0000',
payment_bank_name varchar(100) DEFAULT NULL,
payment_bank_account varchar(100) DEFAULT NULL,
payment_email varchar(100) DEFAULT NULL,
created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY user_id (user_id),
UNIQUE KEY referral_code (referral_code),
KEY status (status)
) $charset_collate;";
dbDelta($sql_affiliates);
// Add custom_commission_rate column if it doesn't exist (for existing installations)
if ($wpdb->get_var("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '$affiliates_table' AND COLUMN_NAME = 'custom_commission_rate'") == 0) {
$wpdb->query("ALTER TABLE $affiliates_table ADD COLUMN custom_commission_rate decimal(10,2) DEFAULT NULL AFTER commission_rate");
}
// Add payment details columns if they don't exist (for existing installations)
$payment_columns = ['payment_bank_name', 'payment_bank_account', 'payment_email'];
foreach ($payment_columns as $col) {
if ($wpdb->get_var("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '$affiliates_table' AND COLUMN_NAME = '$col'") == 0) {
$col_def = $col === 'payment_email' ? "varchar(100) DEFAULT NULL" : "varchar(100) DEFAULT NULL";
$wpdb->query("ALTER TABLE $affiliates_table ADD COLUMN $col $col_def AFTER paid_earnings");
}
}
// Add flexible payment_details JSON column
if ($wpdb->get_var("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '$affiliates_table' AND COLUMN_NAME = 'payment_details'") == 0) {
$wpdb->query("ALTER TABLE $affiliates_table ADD COLUMN payment_details longtext DEFAULT NULL AFTER payment_email");
}
// Add payment_method column
if ($wpdb->get_var("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '$affiliates_table' AND COLUMN_NAME = 'payment_method'") == 0) {
$wpdb->query("ALTER TABLE $affiliates_table ADD COLUMN payment_method varchar(50) DEFAULT NULL AFTER payment_details");
}
// Referrals Table
$sql_referrals = "CREATE TABLE $referrals_table (
id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
affiliate_id bigint(20) UNSIGNED NOT NULL,
order_id bigint(20) UNSIGNED NOT NULL,
customer_id bigint(20) UNSIGNED DEFAULT NULL,
commission_amount decimal(19,4) NOT NULL DEFAULT '0.0000',
currency varchar(10) NOT NULL DEFAULT 'USD',
status varchar(20) NOT NULL DEFAULT 'pending',
cancelled_reason varchar(100) DEFAULT NULL,
cancelled_at datetime DEFAULT NULL,
utm_source varchar(100) DEFAULT NULL,
utm_medium varchar(100) DEFAULT NULL,
utm_campaign varchar(255) DEFAULT NULL,
utm_content varchar(255) DEFAULT NULL,
utm_term varchar(255) DEFAULT NULL,
referrer_url varchar(500) DEFAULT NULL,
created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
approved_at datetime DEFAULT NULL,
paid_at datetime DEFAULT NULL,
PRIMARY KEY (id),
KEY affiliate_id (affiliate_id),
KEY order_id (order_id),
KEY status (status)
) $charset_collate;";
dbDelta($sql_referrals);
// Add cancelled columns if they don't exist (for existing installations)
if ($wpdb->get_var("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '$referrals_table' AND COLUMN_NAME = 'cancelled_reason'") == 0) {
$wpdb->query("ALTER TABLE $referrals_table ADD COLUMN cancelled_reason varchar(100) DEFAULT NULL AFTER status");
}
if ($wpdb->get_var("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '$referrals_table' AND COLUMN_NAME = 'cancelled_at'") == 0) {
$wpdb->query("ALTER TABLE $referrals_table ADD COLUMN cancelled_at datetime DEFAULT NULL AFTER cancelled_reason");
}
// Add UTM columns if they don't exist (for existing installations)
$utm_columns = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term', 'referrer_url'];
foreach ($utm_columns as $col) {
if ($wpdb->get_var("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '$referrals_table' AND COLUMN_NAME = '$col'") == 0) {
$col_def = $col === 'referrer_url' ? "varchar(500) DEFAULT NULL" : ($col === 'utm_campaign' || $col === 'utm_content' || $col === 'utm_term' ? "varchar(255) DEFAULT NULL" : "varchar(100) DEFAULT NULL");
$after_col = $col === 'utm_source' ? 'cancelled_at' : ($col === 'utm_medium' ? 'utm_source' : ($col === 'utm_campaign' ? 'utm_medium' : ($col === 'utm_content' ? 'utm_campaign' : ($col === 'utm_term' ? 'utm_content' : 'utm_term'))));
$wpdb->query("ALTER TABLE $referrals_table ADD COLUMN $col $col_def AFTER cancelled_at");
}
}
// Payouts Table
$sql_payouts = "CREATE TABLE $payouts_table (
id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
affiliate_id bigint(20) UNSIGNED NOT NULL,
amount decimal(19,4) NOT NULL,
currency varchar(10) NOT NULL DEFAULT 'USD',
method varchar(50) NOT NULL,
status varchar(20) NOT NULL DEFAULT 'pending',
notes text DEFAULT NULL,
created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
completed_at datetime DEFAULT NULL,
PRIMARY KEY (id),
KEY affiliate_id (affiliate_id),
KEY status (status)
) $charset_collate;";
dbDelta($sql_payouts);
}
}

View File

@@ -0,0 +1,136 @@
<?php
/**
* Affiliate Module Bootstrap
*
* @package WooNooW\Modules\Affiliate
*/
namespace WooNooW\Modules\Affiliate;
if (!defined('ABSPATH')) exit;
use WooNooW\Core\ModuleRegistry;
class AffiliateModule
{
/**
* Initialize the affiliate module
*/
public static function init()
{
self::maybe_init_manager();
// Install tables on module enable
add_action('woonoow/module/enabled', [__CLASS__, 'on_module_enabled']);
// Run migrations on admin init
add_action('admin_init', [__CLASS__, 'run_migrations']);
}
/**
* Initialize manager if module is enabled
*/
public static function maybe_init_manager()
{
if (ModuleRegistry::is_enabled('affiliate')) {
self::ensure_tables();
AffiliateManager::init();
AffiliateTracker::init();
AffiliateLifecycle::init();
AffiliateSettings::init();
}
}
/**
* Ensure database tables exist and have all required columns
*/
private static function ensure_tables()
{
global $wpdb;
$table = $wpdb->prefix . 'woonoow_affiliates';
// Check if table exists
if ($wpdb->get_var("SHOW TABLES LIKE '$table'") !== $table) {
AffiliateManager::create_tables();
} else {
// Run migrations for existing tables
self::migrate_existing_tables();
}
}
/**
* Migrate existing tables to add missing columns
*/
private static function migrate_existing_tables()
{
global $wpdb;
$table = $wpdb->prefix . 'woonoow_affiliates';
$referrals_table = $wpdb->prefix . 'woonoow_referrals';
// Add custom_commission_rate column if missing
if ($wpdb->get_var("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '$table' AND COLUMN_NAME = 'custom_commission_rate'") == 0) {
$wpdb->query("ALTER TABLE $table ADD COLUMN custom_commission_rate decimal(10,2) DEFAULT NULL AFTER commission_rate");
}
// Add payment detail columns if missing
$payment_columns = ['payment_bank_name', 'payment_bank_account', 'payment_email'];
foreach ($payment_columns as $col) {
if ($wpdb->get_var("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '$table' AND COLUMN_NAME = '$col'") == 0) {
$wpdb->query("ALTER TABLE $table ADD COLUMN $col varchar(100) DEFAULT NULL AFTER paid_earnings");
}
}
// Add flexible payment_details and payment_method columns
if ($wpdb->get_var("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '$table' AND COLUMN_NAME = 'payment_details'") == 0) {
$wpdb->query("ALTER TABLE $table ADD COLUMN payment_details longtext DEFAULT NULL AFTER payment_email");
}
if ($wpdb->get_var("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '$table' AND COLUMN_NAME = 'payment_method'") == 0) {
$wpdb->query("ALTER TABLE $table ADD COLUMN payment_method varchar(50) DEFAULT NULL AFTER payment_details");
}
// Add referral attribution columns if missing.
if ($wpdb->get_var("SHOW TABLES LIKE '$referrals_table'") === $referrals_table) {
$referral_columns = [
'cancelled_reason' => ['definition' => 'varchar(100) DEFAULT NULL', 'after' => 'status'],
'cancelled_at' => ['definition' => 'datetime DEFAULT NULL', 'after' => 'cancelled_reason'],
'utm_source' => ['definition' => 'varchar(100) DEFAULT NULL', 'after' => 'cancelled_at'],
'utm_medium' => ['definition' => 'varchar(100) DEFAULT NULL', 'after' => 'utm_source'],
'utm_campaign' => ['definition' => 'varchar(255) DEFAULT NULL', 'after' => 'utm_medium'],
'utm_content' => ['definition' => 'varchar(255) DEFAULT NULL', 'after' => 'utm_campaign'],
'utm_term' => ['definition' => 'varchar(255) DEFAULT NULL', 'after' => 'utm_content'],
'referrer_url' => ['definition' => 'varchar(500) DEFAULT NULL', 'after' => 'utm_term'],
];
foreach ($referral_columns as $column => $schema) {
if ($wpdb->get_var("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '$referrals_table' AND COLUMN_NAME = '$column'") == 0) {
$wpdb->query("ALTER TABLE $referrals_table ADD COLUMN $column {$schema['definition']} AFTER {$schema['after']}");
}
}
}
}
/**
* Handle module enable
*/
public static function on_module_enabled($module_id)
{
if ($module_id === 'affiliate') {
AffiliateManager::create_tables();
}
}
/**
* Run migrations (called on admin_init)
*/
public static function run_migrations()
{
// Only run once per session (check transient)
if (get_transient('woonoow_affiliate_migrated')) {
return;
}
self::migrate_existing_tables();
set_transient('woonoow_affiliate_migrated', true, DAY_IN_SECONDS);
}
}

View File

@@ -0,0 +1,71 @@
<?php
/**
* Affiliate Module Settings Schema
*
* Defines the settings schema for the Affiliate module.
*
* @package WooNooW\Modules\Affiliate
*/
namespace WooNooW\Modules\Affiliate;
class AffiliateSettings {
public static function init() {
// Register settings schema
add_filter('woonoow/module_settings_schema', [__CLASS__, 'register_schema']);
}
/**
* Register affiliate settings schema
*/
public static function register_schema($schemas) {
$schemas['affiliate'] = [
'woonoow_affiliate_default_rate' => [
'type' => 'number',
'label' => __('Default Commission Rate (%)', 'woonoow'),
'description' => __('The default commission rate percentage for affiliates.', 'woonoow'),
'placeholder' => '10',
'default' => 10,
'min' => 0,
'max' => 100,
],
'woonoow_affiliate_holding_period' => [
'type' => 'number',
'label' => __('Holding Period (Days)', 'woonoow'),
'description' => __('Number of days before a referral becomes eligible for payout (e.g. to account for refunds). Set to 0 for immediate approval on order completion.', 'woonoow'),
'placeholder' => '14',
'default' => 14,
'min' => 0,
],
'woonoow_affiliate_payment_methods' => [
'type' => 'multiselect',
'label' => __('Available Payment Methods', 'woonoow'),
'description' => __('Select which payment methods affiliates can use to receive payouts.', 'woonoow'),
'options' => [
'bank_transfer' => __('Bank Transfer', 'woonoow'),
'paypal' => __('PayPal', 'woonoow'),
'wise' => __('Wise', 'woonoow'),
'skrill' => __('Skrill', 'woonoow'),
'payoneer' => __('Payoneer', 'woonoow'),
'custom' => __('Custom (Notes)', 'woonoow'),
],
'default' => ['bank_transfer'],
],
'woonoow_affiliate_auto_approve' => [
'type' => 'toggle',
'label' => __('Auto-Approve Affiliates', 'woonoow'),
'description' => __('Automatically approve new affiliate applications.', 'woonoow'),
'default' => false,
],
'woonoow_affiliate_allow_self_referral' => [
'type' => 'toggle',
'label' => __('Allow Self-Referrals', 'woonoow'),
'description' => __('Allow affiliates to earn commission when their own user account places an order.', 'woonoow'),
'default' => false,
],
];
return $schemas;
}
}

View File

@@ -0,0 +1,416 @@
<?php
/**
* Affiliate Tracker
*
* Handles referral tracking via cookies and order creation.
*
* @package WooNooW\Modules\Affiliate
*/
namespace WooNooW\Modules\Affiliate;
if (!defined('ABSPATH')) exit;
class AffiliateTracker
{
const COOKIE_NAME = 'woonoow_ref';
const COOKIE_EXPIRES = 30; // days
/**
* Initialize tracking hooks
*/
public static function init()
{
error_log('[AffiliateTracker] init() called');
// Intercept referral links on init
add_action('init', [__CLASS__, 'capture_referral_link']);
// Hook into WooCommerce order creation (legacy checkout)
add_action('woocommerce_checkout_order_processed', [__CLASS__, 'record_referral'], 10, 3);
// Hook into WooCommerce 8.3+ block checkout
add_action('woocommerce_store_api_checkout_order_processed', [__CLASS__, 'record_referral_block'], 10, 1);
// Hook into new order creation (universal)
add_action('woocommerce_new_order', [__CLASS__, 'record_referral_new_order'], 10, 2);
// Hook for all order status changes
add_action('woocommerce_order_status_changed', [__CLASS__, 'handle_order_status_changed'], 10, 4);
// Hook for REST API order creation
add_action('rest_after_insert_shop_order', [__CLASS__, 'handle_rest_order_created'], 10, 3);
error_log('[AffiliateTracker] All hooks registered');
}
/**
* Handle order status change - track completed orders
*/
public static function handle_order_status_changed($order_id, $from_status, $to_status, $order)
{
if ($to_status === 'completed') {
self::process_order_for_referral($order_id);
}
}
/**
* Handle REST API order creation
*/
public static function handle_rest_order_created($order, $request, $creating)
{
if ($creating) {
self::process_order_for_referral($order->get_id());
}
}
/**
* Record referral from block checkout (Store API)
*/
public static function record_referral_block($order)
{
if (is_numeric($order)) {
$order = wc_get_order($order);
}
if ($order) {
self::process_order_for_referral($order->get_id());
}
}
/**
* Record referral from woocommerce_new_order hook
*/
public static function record_referral_new_order($order_id, $order)
{
error_log('[AffiliateTracker] woocommerce_new_order hook fired for order: ' . $order_id);
self::process_order_for_referral($order_id);
}
/**
* Capture ?ref=CODE from URL and set cookie
* Also captures UTM parameters for referral attribution
*/
public static function capture_referral_link()
{
error_log('[AffiliateTracker] capture_referral_link called, ref=' . ($_GET['ref'] ?? 'none'));
$options = [
'expires' => time() + (self::COOKIE_EXPIRES * DAY_IN_SECONDS),
'path' => '/',
'secure' => is_ssl(),
'samesite' => 'Lax'
];
// Capture referral code
if (isset($_GET['ref']) && !empty($_GET['ref'])) {
$referral_code = sanitize_text_field($_GET['ref']);
$result = setcookie(self::COOKIE_NAME, $referral_code, $options);
$_COOKIE[self::COOKIE_NAME] = $referral_code;
error_log('[AffiliateTracker] Set woonoow_ref cookie: ' . $referral_code . ', result=' . ($result ? 'true' : 'false'));
error_log('[AffiliateTracker] Cookie options: ' . json_encode($options));
} else {
// Check if cookie already exists from previous visit
if (isset($_COOKIE[self::COOKIE_NAME])) {
error_log('[AffiliateTracker] No ref param, but existing cookie: ' . $_COOKIE[self::COOKIE_NAME]);
} else {
error_log('[AffiliateTracker] No ref param and no existing cookie');
}
}
// Capture UTM parameters
$utm_params = [];
$utm_keys = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term'];
foreach ($utm_keys as $key) {
if (isset($_GET[$key]) && !empty($_GET[$key])) {
$utm_params[$key] = sanitize_text_field($_GET[$key]);
}
}
// Capture referrer URL
if (isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER'])) {
$utm_params['referrer_url'] = esc_url_raw($_SERVER['HTTP_REFERER']);
}
// Store UTM params in cookie if any captured
if (!empty($utm_params)) {
$utm_json = json_encode($utm_params);
setcookie(self::COOKIE_NAME . '_utm', $utm_json, $options);
$_COOKIE[self::COOKIE_NAME . '_utm'] = $utm_json;
error_log('[AffiliateTracker] Set woonoow_ref_utm cookie');
}
}
/**
* Get active affiliate for an order
* Checks both coupons and cookies.
*/
public static function get_affiliate_for_order($order)
{
global $wpdb;
$table = $wpdb->prefix . 'woonoow_affiliates';
// 1. Check if a coupon is used that maps to an affiliate
$used_coupons = $order->get_coupon_codes();
if (!empty($used_coupons)) {
foreach ($used_coupons as $code) {
$coupon = new \WC_Coupon($code);
if ($coupon->get_id()) {
$affiliate = $wpdb->get_row($wpdb->prepare(
"SELECT * FROM $table WHERE coupon_id = %d AND status = 'active'",
$coupon->get_id()
));
if ($affiliate) return $affiliate;
}
}
}
// 2. Check referral code stored on the order by SPA checkout
$order_referral_code = $order->get_meta('_woonoow_referral_code');
if (!empty($order_referral_code)) {
$affiliate = $wpdb->get_row($wpdb->prepare(
"SELECT * FROM $table WHERE referral_code = %s AND status = 'active'",
sanitize_text_field($order_referral_code)
));
if ($affiliate) return $affiliate;
}
// 3. Fallback to cookie
if (isset($_COOKIE[self::COOKIE_NAME])) {
$referral_code = sanitize_text_field($_COOKIE[self::COOKIE_NAME]);
$affiliate = $wpdb->get_row($wpdb->prepare(
"SELECT * FROM $table WHERE referral_code = %s AND status = 'active'",
$referral_code
));
if ($affiliate) return $affiliate;
}
return null;
}
/**
* Get referral record for a specific order
* Used by admin API to display affiliate info on order details
*/
public static function get_referral_for_order($order_id)
{
global $wpdb;
$referrals_table = $wpdb->prefix . 'woonoow_referrals';
return $wpdb->get_row($wpdb->prepare(
"SELECT * FROM $referrals_table WHERE order_id = %d",
$order_id
));
}
/**
* Record referral when order is processed (Checkout)
*/
public static function record_referral($order_id, $posted_data, $order)
{
self::process_order_for_referral($order_id);
}
/**
* Record referral when order is created via Admin
*/
public static function record_referral_admin($post_id)
{
$order = wc_get_order($post_id);
if ($order) {
self::process_order_for_referral($post_id);
}
}
/**
* Process order and create pending referral record
*/
private static function process_order_for_referral($order_id)
{
error_log('[AffiliateTracker] process_order_for_referral() called for order: ' . $order_id);
global $wpdb;
$order = wc_get_order($order_id);
if (!$order) {
error_log('[AffiliateTracker] Order not found: ' . $order_id);
return;
}
// Check if referral already exists for this order
$referrals_table = $wpdb->prefix . 'woonoow_referrals';
$exists = $wpdb->get_var($wpdb->prepare("SELECT id FROM $referrals_table WHERE order_id = %d", $order_id));
if ($exists) {
error_log('[AffiliateTracker] Referral already exists for order: ' . $order_id);
return;
}
$affiliate = self::get_affiliate_for_order($order);
if (!$affiliate) {
error_log('[AffiliateTracker] No affiliate found for order: ' . $order_id);
return;
}
error_log('[AffiliateTracker] Found affiliate: ' . $affiliate->referral_code . ' (rate: ' . ($affiliate->custom_commission_rate ?? 'null') . ')');
// Prevent self-referrals (unless admin override is enabled)
$order_user_id = $order->get_user_id();
if ((int)$order_user_id === (int)$affiliate->user_id) {
error_log('[AffiliateTracker] Self-referral detected, blocking');
$allow_self_referral = get_option('woonoow_affiliate_allow_self_referral', false);
if (!$allow_self_referral) return;
}
// Calculate commission
// Priority: Product rate > Affiliate custom rate > Global default
$global_default_rate = (float) get_option('woonoow_affiliate_default_rate', 10);
$affiliate_custom_rate = !empty($affiliate->custom_commission_rate) ? (float) $affiliate->custom_commission_rate : null;
// Get order items - try WC method first, fallback to direct DB query
$items = self::get_order_items($order_id);
error_log('[AffiliateTracker] Order items: ' . count($items));
$total_commission = 0;
if (!empty($items)) {
foreach ($items as $item) {
$product_id = (int) $item['product_id'];
$line_total = (float) $item['line_total'];
// Check for product-specific affiliate rate
$product_rate = get_post_meta($product_id, '_woonoow_affiliate_commission_rate', true);
$product_enabled = get_post_meta($product_id, '_woonoow_affiliate_enabled', true) === 'yes';
error_log('[AffiliateTracker] Product ' . $product_id . ': enabled=' . ($product_enabled ? 'yes' : 'no') . ', rate=' . $product_rate . ', line_total=' . $line_total);
// Determine rate for this item (only if product affiliate is enabled)
$item_rate = null;
if ($product_enabled && $product_rate !== '') {
$item_rate = (float) $product_rate;
error_log('[AffiliateTracker] Using product rate: ' . $item_rate);
} elseif ($affiliate_custom_rate !== null) {
$item_rate = $affiliate_custom_rate;
error_log('[AffiliateTracker] Using affiliate rate: ' . $item_rate);
} else {
$item_rate = $global_default_rate;
error_log('[AffiliateTracker] Using global rate: ' . $item_rate);
}
if ($item_rate > 0 && $line_total > 0) {
$total_commission += ($line_total * $item_rate) / 100;
error_log('[AffiliateTracker] Added: ' . ($line_total * $item_rate / 100));
}
}
} else {
// Fallback to subtotal if no items (legacy)
$subtotal = (float)$order->get_subtotal();
$commission_rate = $affiliate_custom_rate ?? $global_default_rate;
if ($commission_rate <= 0) return;
$total_commission = ($subtotal * $commission_rate) / 100;
}
if ($total_commission <= 0) {
error_log('[AffiliateTracker] Commission is 0, skipping');
return;
}
error_log('[AffiliateTracker] Total commission: ' . $total_commission);
// Get UTM parameters from cookie
$utm_data = [];
if (isset($_COOKIE[self::COOKIE_NAME . '_utm'])) {
$utm_data = json_decode($_COOKIE[self::COOKIE_NAME . '_utm'], true) ?: [];
}
// Insert pending referral
$insert_data = [
'affiliate_id' => $affiliate->id,
'order_id' => $order_id,
'customer_id' => $order->get_user_id() ?: null,
'commission_amount' => $total_commission,
'currency' => $order->get_currency(),
'status' => 'pending'
];
// Add UTM data if available
if (!empty($utm_data)) {
foreach (['utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term', 'referrer_url'] as $utm_key) {
if (isset($utm_data[$utm_key])) {
$insert_data[$utm_key] = $utm_data[$utm_key];
}
}
}
$inserted = $wpdb->insert($referrals_table, $insert_data);
if (!$inserted) {
error_log('[AffiliateTracker] Failed to insert referral for order ' . $order_id . ': ' . $wpdb->last_error);
return;
}
$referral_id = $wpdb->insert_id;
// Fire event for notifications
do_action('woonoow/affiliate/referral_received', $referral_id, $affiliate, $order);
// Trigger email notification to affiliate
$user = get_userdata($affiliate->user_id);
if ($user) {
do_action('woonoow/email/trigger', 'affiliate_new_referral', $user->user_email, [
'affiliate_name' => $user->display_name,
'commission_amount' => $total_commission,
'currency' => $order->get_currency(),
'order_number' => $order->get_order_number()
]);
}
// Schedule auto-approval (e.g., 14 days) via Action Scheduler
if (function_exists('as_schedule_single_action')) {
$approval_days = get_option('woonoow_affiliate_holding_period', 14);
$timestamp = time() + ($approval_days * DAY_IN_SECONDS);
as_schedule_single_action($timestamp, 'woonoow_approve_referral', ['referral_id' => $referral_id], 'woonoow_affiliate');
}
}
/**
* Get order items - direct DB query for HPOS compatibility
*/
private static function get_order_items($order_id)
{
global $wpdb;
// First try HPOS order_product_lookup table (more reliable with HPOS)
// Force fresh query by using wpdb::query with direct table
$order_id_int = (int) $order_id;
$items = $wpdb->get_results($wpdb->prepare(
"SELECT product_id, product_qty, product_net_revenue as line_total
FROM {$wpdb->prefix}wc_order_product_lookup
WHERE order_id = %d",
$order_id_int
), ARRAY_A);
error_log('[AffiliateTracker] get_order_items() HPOS query returned: ' . count($items) . ' items for order ' . $order_id_int);
// If no results from HPOS table, try legacy order_items table
if (empty($items)) {
$items = $wpdb->get_results($wpdb->prepare(
"SELECT oim_product.meta_value as product_id, oim_total.meta_value as line_total
FROM {$wpdb->prefix}woocommerce_order_items oi
LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta oim_product ON oi.order_item_id = oim_product.order_item_id AND oim_product.meta_key = '_product_id'
LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta oim_total ON oi.order_item_id = oim_total.order_item_id AND oim_total.meta_key = '_line_total'
WHERE oi.order_id = %d AND oi.order_item_type = 'line_item'",
$order_id
), ARRAY_A);
}
// Convert to standard format
$result = [];
foreach ($items as $item) {
$product_id = isset($item['product_id']) ? (int) $item['product_id'] : 0;
if ($product_id > 0) {
$result[] = [
'product_id' => $product_id,
'line_total' => (float) ($item['line_total'] ?? 0)
];
}
}
return $result;
}
}