=== TrustLens – Abuse & Fraud Prevention for WooCommerce ===
Contributors: webstepper, freemius
Tags: woocommerce, fraud prevention, customer management, returns, trust score
Requires at least: 6.4
Tested up to: 6.9
Requires PHP: 7.4
Stable tag: 1.1.4
License: GPLv3 or later
License URI: https://www.gnu.org/licenses/gpl-3.0.html

Stop return and coupon abuse in WooCommerce with behavior-based trust scores and linked-account detection. You decide—no auto-blocking.

== Description ==

**TrustLens** gives every WooCommerce customer a trust score based on real behavior — returns, order patterns, coupon usage, category risk, and linked accounts. Instead of guessing who’s problematic, you get clear, data‑driven intelligence with the exact signals behind every score.

Most store owners don’t see abuse until the damage is done. Serial returners, coupon exploiters, and multi‑account fraudsters quietly drain revenue. TrustLens surfaces these patterns early so you can act before they escalate — and it never auto‑blocks customers without your approval.

= What TrustLens Does =

**Scores every customer from 0 to 100** based on five detection modules running in the background. Customers are automatically sorted into six segments — VIP, Trusted, Normal, Caution, Risk, and Critical — so you can see your customer base at a glance.

**Tracks the patterns that matter.** Return rates, order cancellations, coupon abuse, category-specific return behavior, and linked accounts across multiple email addresses. Each signal is logged transparently so you can see exactly why a customer scored the way they did.

**Puts you in control.** TrustLens never auto-blocks anyone. You review the data, decide what to do, and take action when you're ready. Block a customer from checkout, add a VIP to the allowlist, or simply monitor the trends.

= Free vs Pro at a glance =

The plugin on WordPress.org is the **free version**: fully functional trust scoring, dashboard, customer management, blocking, allowlist, core notifications, REST API, and all five detection modules (returns, orders, coupons, categories, linked accounts). No time limits or locked features.

**Pro** (sold separately) adds: **Automation Rules**, **Webhooks**, **Scheduled Reports**, **Chargeback Tracking** (Stripe/WooPayments), and **10 advanced email notifications**. Pro code is not included in the free package; Pro tabs in the free version show promotional upgrade content only.

= Free Features =

* **Trust Score Engine** — Every customer gets a 0-100 score calculated from weighted behavioral signals
* **6 Customer Segments** — VIP, Trusted, Normal, Caution, Risk, and Critical with automatic classification
* **Return Abuse Detection** — Tracks refund rates, refund values, and return frequency patterns
* **Order Pattern Analysis** — Monitors completion rates, cancellations, and order velocity
* **Coupon Abuse Detection** — Identifies repeat first-order discount usage and coupon-then-refund patterns
* **Category-Aware Scoring** — Applies per-category return rate analysis with configurable risk weights
* **Linked Accounts Detection** — Finds customers using multiple accounts via address, phone, IP, payment method, and device fingerprinting
* **Command Center Dashboard** — 9-section analytics dashboard with 6 interactive charts, KPI cards, ROI scorecard, and top returner insights
* **Customer Management** — Searchable, filterable customer list with segment badges, scores, and detailed profile pages
* **Bulk Actions** — Block, unblock, allowlist, recalculate, or delete multiple customers at once
* **Customer Notes** — Add internal admin notes to individual customer profiles
* **Manual Blocking** — Block problematic customers from checkout with a customizable message
* **Allowlist Protection** — Protect VIP customers from false positives — allowlisted customers always score 100
* **Checkout Enforcement** — Blocked customers are stopped at checkout and add-to-cart with a clear message
* **Historical Sync** — Import existing WooCommerce orders to build trust profiles from day one, runs in the background
* **Email Notifications** — Blocked checkout alerts, welcome summary after activation, and weekly protection reports
* **REST API** — 8 endpoints for customer lookup, score retrieval, segment filtering, and external integrations
* **Module Controls** — Enable/disable detection modules and set linked-account penalty strength
* **GDPR Compliance** — Full integration with WordPress privacy tools for data export and erasure requests
* **CSV and JSON Export** — Export your entire customer list or individual profiles for offline analysis
* **Configurable Thresholds** — Adjust minimum orders for scoring, return rate risk levels, and blocking messages
* **WooCommerce HPOS** — Fully compatible with High-Performance Order Storage
* **Order Screen Integration** — Customer trust info displayed directly on WooCommerce order edit pages

= Pro Features =

* **Automation Rules** — Create trigger-based rules that fire actions automatically (e.g., when a customer drops to Critical, send an alert and flag for review)
* **Webhooks** — Send real-time event data to external systems, Slack, Zapier, or custom endpoints
* **Scheduled Reports** — Automated email reports on a daily, weekly, or monthly schedule
* **Chargeback Tracking** — Record and track disputes, wins, and losses per customer with score impact
* **10 Advanced Notifications** — High-risk order alerts, velocity detection, high-value order warnings, repeat refunder alerts, segment change notifications, score recovery notices, new customer risk alerts, daily digest, monthly revenue protection reports, and chargeback filed alerts

= Who Is TrustLens For? =

* **WooCommerce store owners** tired of dealing with serial returners and refund abuse
* **Operations managers** who need data to make decisions about customer policies
* **Fraud prevention teams** looking for behavioral signals beyond payment fraud
* **Stores with generous return policies** that attract abuse alongside legitimate returns

= How Scoring Works =

Every customer starts at a base score of **50**. Detection modules analyze behavior and produce positive or negative signals:

* Completed orders increase trust
* Refunds decrease trust proportionally to frequency and value
* Coupon abuse patterns apply penalties
* High return rates in specific categories carry extra weight
* Linked accounts with risky customers reduce scores further
* Account age adds a loyalty bonus (up to +15 for accounts older than one year)

Scores are clamped between 0 and 100. Customers below a configurable minimum order count (default: 3) remain in the Normal segment until enough data is collected.

All scoring signals are logged and visible on the customer detail page, so you always know exactly why a score changed.

== Installation ==

1. Upload the `trustlens` folder to `/wp-content/plugins/` or install directly from the WordPress plugin repository
2. Activate the plugin through the **Plugins** menu
3. Navigate to **TrustLens > Dashboard** to see the command center
4. Go to **TrustLens > Settings** to configure scoring thresholds, blocking, and notifications
5. Run **Historical Sync** from the dashboard to import existing customer data from WooCommerce orders

The historical sync runs in the background and does not affect site performance.

== Frequently Asked Questions ==

= Does TrustLens work with guest checkout? =

Yes. Customers are identified by a hash of their email address, so guest and registered customers are tracked equally. If a guest later registers, their history carries over.

= Will TrustLens automatically block customers? =

No. TrustLens is an intelligence tool — it surfaces data and patterns, but blocking is always a manual decision made by you. This prevents false positives from harming legitimate customers.

= How does linked accounts detection work? =

TrustLens creates fingerprints from shipping addresses, billing addresses, phone numbers, IP addresses, payment methods, and device user agents. When multiple customer accounts share fingerprints, they are flagged as linked. This helps detect multi-account abuse like repeated first-order discounts.

= What happens when I block a customer? =

Blocked customers see a customizable message when they try to add items to their cart or proceed to checkout. The block applies to both logged-in users and guest checkouts matching the blocked email. All blocked checkout attempts are logged.

= Can I undo a block? =

Yes. You can unblock a customer at any time from their profile page or the customer list. You can also add customers to the allowlist, which locks their score at 100 and prevents any negative signals from affecting them.

= Does this slow down my store? =

No. Score calculations run asynchronously via Action Scheduler (the same system WooCommerce uses). Checkout blocking uses a lightweight email-hash lookup. The historical sync processes orders in small batches in the background.

= Is TrustLens compatible with WooCommerce HPOS? =

Yes. TrustLens declares full compatibility with High-Performance Order Storage and works with both legacy and HPOS-enabled stores.

= Does TrustLens store personal data? =

TrustLens stores customer email addresses and behavioral data (order counts, refund counts, trust scores) in custom database tables. All fingerprint data (addresses, phone numbers, IPs) is stored as one-way MD5 hashes. The plugin integrates with WordPress privacy tools — customers can request data export or erasure through the standard WordPress privacy workflow.

= Can I access TrustLens data from external systems? =

Yes. TrustLens includes a REST API with 8 endpoints for looking up customers, retrieving scores, filtering by segment, and triggering recalculations. API access requires either the `manage_woocommerce` capability or a valid API key configured in settings.

= What is the minimum data needed for accurate scoring? =

By default, customers need at least 3 orders before they move out of the Normal segment. You can adjust this threshold in Settings > General. Customers below the threshold still accumulate signals — they just aren't classified until enough data exists.

= Does the free version include all detection modules? =

Yes. All five detection modules (returns, orders, coupons, categories, linked accounts) are included in the free version. Pro adds automation, webhooks, scheduled reports, chargeback tracking, and advanced notifications.

== Screenshots ==

1. **Command Center Dashboard** — Full analytics overview with health score, KPI cards, trust score trends, and segment distribution
2. **Customer List** — Searchable, sortable list with segment badges, trust scores, return rates, and quick actions
3. **Customer Detail Page** — Complete customer profile with score history, event timeline, linked accounts, and all behavioral signals
4. **Trust Score Trends Chart** — 30-day trend line showing average trust score movement across your customer base
5. **Revenue Protection Overview** — ROI scorecard showing money protected, money at risk, protection rate, and actions taken
6. **Detection Overview** — Coupon abuse stats and chargeback tracking at a glance
7. **Settings Page** — Configure scoring thresholds, checkout blocking message, and notification preferences
8. **Order Integration** — Customer trust score and segment displayed on the WooCommerce order edit screen
9. **Linked Accounts View** — Multi-account detection showing matched fingerprints and risk indicators

== Changelog ==

= 1.1.4 =
* **Added:** Dashboard chart cards now show polished empty-state UI for Trust Score Trends, Refund Activity, Activity by Hour, and Protection Trend when data is unavailable.
* **Fixed:** Historical Sync completion summary now reports the actual profiled customer count from the TrustLens customer table.
* **Fixed:** Dashboard health attention messaging now aligns with actual risk-customer counts.
* **Improved:** Historical Sync backfill now reconstructs historical events with original timestamps and keeps rebuilds idempotent.
* **Docs:** Deployment guide now documents only Freemius ZIP based WordPress.org deploy flow.

= 1.1.3 =
* **Added:** Historical Sync now backfills coupon behavior metrics (`total_coupons_used`, `first_order_coupons`, `coupon_then_refund`) from older WooCommerce orders.
* **Added:** Historical Sync now rebuilds category aggregates and linked-account fingerprints from historical orders for more accurate scoring inputs.
* **Added:** Historical Sync now reconstructs historical timeline events (orders, refunds, coupon events) using original order/refund timestamps.
* **Improved:** Sync backfill paths are re-sync safe and remove previously generated synthetic sync events before rebuilding.

= 1.1.2 =
* **Fixed:** Historical Sync now safely handles WooCommerce refund objects and no longer fails with `OrderRefund::get_billing_email()` errors.
* **Fixed:** Empty dashboard sync flow now always shows the correct progress UI when sync starts.
* **Improved:** Sync batch AJAX failures now recover UI state instead of leaving controls hidden.
* **Added:** Reliable activation redirect to TrustLens dashboard after plugin activation.

= 1.1.1 =
* **Fixed:** Historical Sync now surfaces precise server error messages instead of generic AJAX failures.
* **Fixed:** Optimized sync startup order counting to avoid loading all order IDs in memory.
* **Fixed:** Corrected sync customer totals to count only newly inserted customers across batches.
* **Improved:** Refactored duplicated batch-processing logic into a shared internal helper for consistency.
* **Improved:** Removed unused sync polling code path and dead AJAX endpoint, and hardened Action Scheduler fallbacks.
* **Fixed:** Ensured WordPress pointer assets are enqueued on TrustLens admin pages to prevent Freemius pointer JS errors.

= 1.1.0 =
* **Added:** New dedicated **Payment Controls** settings tab.
* **Added:** Pro **Payment Method Risk Controls** to hide selected gateways for risky segments at checkout.
* **Added:** Pro **Velocity Protection** for temporary gateway restrictions during high order-attempt spikes.
* **Added:** Pro **Linked Account Protection** using linked-account fingerprints (address, phone, IP, device) for real-time gateway restriction decisions.
* **Improved:** Restriction event logging now includes trigger reasons and linked-account risk context for auditability.

= 1.0.6 =
* **Added:** Redesigned Pro upsell experience with polished value panels, comparison rows, and improved CTAs across Automation, Notifications, Webhooks, Reports, and Chargebacks.
* **Improved:** Unified upsell rendering via a shared component for more consistent styling and messaging.
* **Improved:** Dashboard empty state now always shows the Historical Sync action (with clearer guidance when no eligible historical orders exist).
* **Fixed:** Removed obsolete locked-notification upsell styles and redundant upsell markup paths.

= 1.0.5 =
* UI Improvements.

= 1.0.4 =
* **Added:** Automation is now a dedicated menu (TrustLens → Automation) with its own page and dashboard-style layout.
* **Added:** Chargebacks (Pro) settings tab: enable/disable module and "Auto-block after N lost disputes" with proper save.
* **Added:** Test notification: 15-second timeout and clear message when mail/SMTP is not configured.
* **Changed:** Automation removed from Settings tab; old Automation tab URL redirects to the new Automation page.
* **Changed:** Modal styling (card look, accent bar, overlay blur, improved header/body/footer and close button).
* **Changed:** Global "Enable Notifications" now applies to all notifications (Standard and Pro).
* **Changed:** Pro notifications list refactored to a single source of truth (no duplicate markup).
* **Fixed:** API tab no longer shows the stored key hash when a key exists; placeholder and copy instructions shown instead.
* **Fixed:** API documentation: endpoints table matches implementation (lookup, update customer, events, recalculate, stats/segments); example response corrected.
* **Fixed:** REST API routes for customer events and recalculate now use 32-char hash pattern (MD5).
* **Fixed:** Data tab: starting Historical Sync from Settings → Data now shows progress bar and updates correctly.
* **Fixed:** Test notification no longer spins indefinitely when server mail is not configured.
* **Other:** Redundancy cleanups on Automation, Data, and Notifications pages; Chart.js not loaded on Automation page.

= 1.0.3 =
* Bug fixes

= 1.0.2 =
* Dashboard and customer pages UI refinements (spacing, sizing, alignment, and visual polish).
* Improved color system with reusable segment variables and a primary plugin color token.
* Split admin styles into page-specific files for better maintainability and scoped loading.
* Test data generation now seeds higher trust scores in the 80-95 range.

= 1.0.1 =
* Release packaging and deployment workflow updates (no functional changes).

= 1.0.0 =

**Core Engine**

* Trust score calculation engine with weighted signal aggregation (0-100 scale)
* 6-tier customer segmentation: VIP, Trusted, Normal, Caution, Risk, Critical
* Account age loyalty bonus (up to +15 points for 1+ year accounts)
* Configurable minimum order threshold before segment classification
* Allowlist system with automatic score override to 100

**Detection Modules**

* Return abuse detection — refund rate, refund value, and return frequency analysis
* Order pattern analysis — completion rates, cancellation tracking, order velocity
* Coupon abuse detection — first-order discount exploitation and coupon-then-refund patterns
* Category-aware scoring — per-category return rate tracking with weighted penalties
* Linked accounts detection — multi-account identification via address, phone, IP, payment, and device fingerprinting

**Dashboard & Analytics**

* 9-section command center dashboard with store health score
* 6 interactive Chart.js charts: trust trends, segment distribution, refund activity, hourly activity, category return rates, monthly protection trend
* KPI cards: total customers, average trust score, new high-risk, events (24h), total orders, return rate
* ROI scorecard with money protected, money at risk, protection rate, and actions taken
* Top returners table and high-risk customer attention list

**Customer Management**

* Searchable customer list with segment, score, and return rate columns
* Customer detail page with full behavioral history and signal breakdown
* Manual block and unblock with checkout enforcement
* Allowlist management for VIP protection
* CSV export for full customer list
* JSON export for individual customer profiles

**Integrations**

* WooCommerce order edit screen integration showing trust score
* REST API with 8 endpoints and API key authentication
* GDPR data export and erasure via WordPress privacy tools
* WooCommerce High-Performance Order Storage (HPOS) compatibility
* Action Scheduler for asynchronous score processing

**Notifications**

* Blocked checkout email alert
* Welcome summary (24 hours after activation)
* Weekly protection summary report

**Historical Sync**

* Background import of existing WooCommerce orders
* Progress tracking with start/stop/resume controls
* Batch processing without site performance impact

== External Services ==

This plugin may connect to external services as described below.

= Freemius SDK =

This plugin uses the [Freemius](https://freemius.com) SDK for optional usage tracking, license management, and plugin updates.

**When data is sent:**

* During plugin activation, only if the user explicitly opts in
* When checking for plugin updates
* When activating or deactivating a Pro license

**What data is sent:**

* Site URL, WordPress version, and PHP version
* Plugin version and activation status
* Admin email (only if opted in)
* License key (Pro version only)

**Important:** No data is sent unless you explicitly opt in during plugin activation. You can skip the opt-in entirely and use the free version without sharing any data.

* Service: [Freemius](https://freemius.com)
* Terms of Service: [https://freemius.com/terms/](https://freemius.com/terms/)
* Privacy Policy: [https://freemius.com/privacy/](https://freemius.com/privacy/)

= Webhooks (Pro, Optional) =

When webhooks are enabled in TrustLens settings (Pro feature), the plugin sends HTTP POST requests to URLs configured by the administrator.

**When data is sent:**

* When a customer's trust score is updated (if enabled)
* When a customer is blocked (if enabled)
* When a checkout is blocked (if enabled)
* When a high-risk order is placed (if enabled)
* When testing webhook connectivity

**What data is sent:**

* Customer email hash (not the actual email address)
* Trust score and customer segment
* Event type and timestamp
* Order details for high-risk order events (order ID, total, status)
* Site URL and site name

**Important:** Webhook endpoints are entirely configured by you. No data is sent to any third-party service unless you explicitly add webhook URLs. The plugin does not send data to the plugin developer or any default external service.

== Upgrade Notice ==

= 1.1.4 =
Dashboard UX and sync consistency release: adds chart empty states and improves historical sync completion/reporting accuracy.

= 1.1.3 =
Historical sync accuracy release: backfills coupon/category/linked-account behavior metrics and reconstructs historical events for improved scoring and reporting.

= 1.1.2 =
Sync stability and UX release: fixes refund-related sync crashes, improves empty-state progress behavior, and adds reliable post-activation dashboard redirect.

= 1.1.1 =
Sync reliability release: clearer sync errors, more robust batch processing, and cleanup of unused sync code paths.

= 1.1.0 =
New Payment Controls tab with advanced Pro gateway restrictions (risk segment, velocity, and linked-account protection).

= 1.0.6 =
Professional upsell redesign and clearer dashboard sync onboarding.

= 1.0.5 =
UI Improvements.

= 1.0.4 =
Automation is now its own menu (TrustLens → Automation). API and Data tabs fixes, modal styling, notification improvements, and test email timeout.

= 1.0.3 =
Bug fixes.

= 1.0.2 =
UI/UX refinement release with modular CSS organization and improved test-data seeding.

= 1.0.1 =
Maintenance release. No functional changes.

= 1.0.0 =
First release. Install TrustLens and run the historical sync to start building customer trust profiles immediately.
