# BadActors.io Fraud Review for WooCommerce

A WordPress plugin that integrates WooCommerce with the BadActors.io fraud detection and review API to help merchants identify and prevent fraudulent orders. This plugin requires an account on https://badactors.io

## Features

### 1. API Integration & Settings
- **Secure Authentication**: Login with email/password to generate API tokens
- **Manual Token Entry**: Option to manually paste API tokens
- **Connection Testing**: Built-in API connection testing
- **Auto-Queue Settings**: Configure automatic order processing

### 2. Automatic Order Processing
- **Smart Queue System**: Automatically queues new orders using Action Scheduler
- **HPOS Compatible**: Full support for WooCommerce High-Performance Order Storage
- **Background Processing**: Orders are processed asynchronously via cron jobs
- **Duplicate Prevention**: Prevents duplicate API calls for already processed orders
- **Status-Based Triggering**: Only processes orders in eligible statuses (processing, completed, on-hold, pending)

### 3. Fraud Detection
- **Automatic Fraud Review Search**: After order processing, automatically searches for existing fraud reviews
- **Risk Scoring**: Displays calculated risk scores with color-coded indicators
- **Comprehensive Matching**: Matches customers by email, phone, name, and addresses
- **Review Details**: Shows chargeback status, notes, review dates, and dispute information

### 4. Order Admin Integration
- **Fraud Results Widget**: Sidebar widget on order admin pages showing fraud review results
- **Processing Status**: Real-time status of order processing and review searches
- **Manual Search**: Button to manually trigger fraud review searches
- **Bulk Requeue Action**: Bulk action to requeue multiple orders for fraud review search
- **Risk Score Display**: Color-coded risk indicators (low/medium/high)

### 5. Review Submission
- **Submit Reviews Widget**: Form to submit fraud reviews directly from order admin pages
- **Auto-Population**: Customer data automatically pulled from order information
- **Chargeback Tracking**: Checkbox to indicate if customer issued a chargeback
- **Custom Notes**: Text area for detailed fraud review notes
- **UUID Management**: Automatic tracking of review UUIDs for future reference

### 6. Review Management
- **Edit Existing Reviews**: Edit previously submitted reviews if status allows
- **Status Management**: Change review status between active and dismissed
- **Review History**: View existing reviews with full details
- **Dispute Indication**: Shows when customers have disputed reviews

## Installation

1. Upload the plugin files to `/wp-content/plugins/badactorsio/`
2. Activate the plugin through the WordPress admin panel
3. Ensure WooCommerce and Action Scheduler are installed and active
4. Configure your API credentials in WooCommerce > BadActors.io

## Configuration

### API Setup
1. Navigate to **WooCommerce > BadActors.io** in your WordPress admin
2. Enter your BadActors.io email and password
3. Click "Generate API Token" to authenticate
4. Alternatively, manually paste an API token if you have one
5. Test the connection to ensure everything is working

### Auto-Queue Settings
- **Enable Auto Queue**: Automatically process new orders (recommended)
- When enabled, orders will be queued for processing when they reach eligible statuses

## Usage

### Automatic Processing
When auto-queue is enabled, the plugin automatically:
1. Queues new orders for API submission
2. Creates order records in BadActors.io
3. Searches for existing fraud reviews
4. Stores results in local database for quick access

### Manual Operations
From any order admin page, you can:
- **Search for Reviews**: Manually trigger fraud review searches
- **Submit Reviews**: Report fraudulent customers
- **View Results**: See fraud review data with risk scores

### Bulk Operations
From the WooCommerce orders list page, you can:
- **Bulk Requeue Orders**: Select multiple orders and use the "Requeue for Fraud Review Search" bulk action to refresh fraud review data for multiple orders at once
- This is useful for:
  - Updating fraud review data for orders processed more than 24 hours ago
  - Re-checking orders after new fraud reports may have been submitted by other merchants
  - Processing orders that failed initial fraud review searches

### Review Submission
1. Open any order in the WooCommerce admin
2. Scroll to the "Submit Fraud Review" widget in the sidebar
3. Fill in the note and indicate if there was a chargeback
4. Submit the review to share with the BadActors.io network

## Database Structure

The plugin creates two custom tables:

### badactors_reviews
- Stores fraud review search results
- Fields: order_id, count, risk_status, data (serialized), timestamps

### badactors_order_meta
- Stores order and review UUIDs
- Fields: order_id, meta_key, meta_value, timestamps

## HPOS Compatibility

This plugin is fully compatible with WooCommerce's High-Performance Order Storage (HPOS):
- Uses proper WooCommerce order objects
- Hooks into HPOS-specific events
- Declares HPOS compatibility for WooCommerce

## Action Scheduler Integration

The plugin leverages Action Scheduler for:
- Asynchronous order processing
- Background fraud review searches
- Automatic retry of failed operations
- Cleanup of old logs

## API Endpoints Used

- `POST /v1/auth/login` - Authentication
- `POST /v1/order` - Create order records
- `GET /v1/review` - Search for fraud reviews
- `POST /v1/review` - Submit fraud reviews
- `GET /v1/review/{uuid}` - Get specific review
- `PUT /v1/review/{uuid}` - Update reviews
- `GET /v1/user` - Connection testing

## Requirements

- WordPress 5.0+
- WooCommerce 7.0+
- PHP 7.4+
- Action Scheduler (included with WooCommerce)
- BadActors.io API account

## Security Features

- Nonce verification for all admin actions
- Capability checks for user permissions
- Input sanitization and validation
- Secure API token storage
- SQL injection prevention

## External Services
This plugin connects to the BadActors API to compare customer information
to our system to find any matching fraud reports.

Basic order information is sent and stored in our system for potential fraud
analysis. That data includes order total, order date, WooCommerce order number,
total order item quantity, and billing postal code.

Additionally, when a merchant submits a fraud review, we store the customer's
contact information associated with that order, including first and last name,
email, phone number, and billing and shipping address. We never share any of a
customer's personal contact information with another merchant. It's stored
exclusively for the purpose of matching their fraud report to other orders
they submit.

Privacy Policy: [https://badactors.io/privacy-policy](https://badactors.io/privacy-policy)
Terms of Service: [https://badactors.io/terms-of-service](https://badactors.io/terms-of-service)

## Troubleshooting

### Common Issues

**Orders not being processed:**
- Check that auto-queue is enabled
- Verify API token is configured
- Check Action Scheduler logs in WooCommerce > Status > Scheduled Actions

**No fraud review data:**
- Ensure orders have been processed first (order UUID exists)
- Check that customer has required billing information
- Verify API connection is working

**Permission errors:**
- Ensure user has 'edit_shop_orders' capability
- Check user role permissions

### Debug Information
Error logs are written to the WordPress error log with the prefix "BadActors:". Check your error logs for detailed information about any issues.

# Fraud Review Auto-Refresh System

## Overview

The BadActors plugin includes an intelligent auto-refresh system designed to **prevent fraud before fulfillment** by continuously monitoring active orders for new fraud reviews posted by other merchants.

## How It Works

### 1. **Automatic Scheduled Refreshes**
- Runs **twice daily** (every 12 hours) via WordPress cron
- Checks for fraud review data older than **24 hours**
- Processes up to **50 orders** per run to avoid server overload

### 2. **Smart Order Selection - Active Orders Only**

The system **ONLY** refreshes orders in these statuses:
- `processing` - Orders being fulfilled
- `on-hold` - Orders awaiting action
- `pending` - Orders awaiting payment

**Why?** These orders haven't shipped yet, so there's still time to prevent fraud.

### 3. **What is NOT Refreshed**

To avoid excessive API calls and database bloat:
- ❌ Completed orders (already shipped)
- ❌ Cancelled orders (already handled)
- ❌ Refunded orders (already resolved)
- ❌ Failed orders (not relevant)
- ❌ Old orders with fraud reviews (no longer actionable)

### 4. **Manual Triggers**

Fraud reviews are also refreshed immediately when:
- ✅ Admin clicks "Refresh Search" button
- ✅ Merchant submits a new fraud review
- ✅ Merchant updates an existing fraud review

### 5. **Visual Indicators**

When viewing an **active order** (processing/on-hold/pending) with stale data (>24 hours old):
- 📋 Yellow warning appears: *"Fraud review data is older than 24 hours. New fraud reviews may have been posted. Click 'Refresh Search' before fulfilling."*
- Alerts merchant to check for new fraud reports before shipping

### WordPress Cron Schedule
- **Hook:** `badactors_refresh_stale_reviews`
- **Recurrence:** `twicedaily` (every 12 hours)
- **Registered on:** Plugin activation
- **Removed on:** Plugin deactivation/uninstall

## Configuration

### Customizing Monitored Statuses

Developers can filter which order statuses trigger automatic refreshes:

```php
add_filter('badactors_monitor_statuses', function($statuses) {
    // Default: ['wc-processing', 'wc-on-hold', 'wc-pending']

    // Add 'completed' status (not recommended - orders already shipped)
    $statuses[] = 'wc-completed';

    // Remove 'pending' if you don't want to monitor pending orders
    $statuses = array_diff($statuses, ['wc-pending']);

    return $statuses;
});
```

**Note:** Status names must include the `wc-` prefix for HPOS compatibility.

### Manual Refresh via WP-CLI

```bash
wp cron event run badactors_refresh_stale_reviews

```

## Support

For technical support or questions about the API integration, please contact BadActors.io support or check the WordPress error logs for detailed error information.

## Changelog

### Version 1.0.0
- Initial release
- Full API integration
- HPOS compatibility
- Action Scheduler integration
- Admin interface widgets
- Fraud review submission
- Automatic order processing

### Version 1.0.1
- Added Store selection
- Add Risk score to orders table

### Version 1.0.2
- Add domain validation to prevent staging sites submitting order to the production store account
- Better escape characters like + in email on api

### Version 1.0.3
- Validate country as two character code for API support