=== TrustLens – Customer Risk Intelligence & Abuse Detection for WooCommerce ===
Contributors: webstepper, freemius
Tags: woocommerce, fraud prevention, return abuse, coupon abuse, chargebacks
Requires at least: 6.4
Tested up to: 6.9
Requires PHP: 7.4
Stable tag: 1.1.5
License: GPLv3 or later
License URI: https://www.gnu.org/licenses/gpl-3.0.html

Detect return abuse, coupon abuse, risky customers, and linked accounts in WooCommerce with behavior-based trust scores and risk segments.

== Description ==

**TrustLens** is a WooCommerce customer risk intelligence and abuse detection plugin that assigns every shopper a behavior-based trust score from 0 to 100.

Instead of guessing which customers are risky, TrustLens analyzes real store behavior — refunds, order patterns, coupon usage, category risk, linked accounts, and dispute history — to help you identify high-risk customers early.

At a glance, you can see each customer's trust score, risk segment, and the exact signals that changed it, so you can make confident decisions about refunds, store policies, customer management, and payment risk.

TrustLens focuses on behavioral fraud detection for WooCommerce — identifying risky customer behavior that traditional payment fraud tools often miss.

It helps surface the abuse patterns many stores struggle to spot early:

* serial returners
* coupon exploitation
* multi-account shoppers
* refund abuse
* risky customers linked across multiple accounts
* dispute and chargeback risk

The free version is manual by default, giving you the visibility and control to review customers before you take action. Pro adds optional automation, payment controls, dispute tracking, and advanced alerts for stores that need stricter workflows.

= Problems TrustLens Solves =

Many WooCommerce stores lose revenue from abuse patterns that stay hidden until the damage is already done.

Common examples include:

* customers repeatedly ordering items and returning them after use
* shoppers creating multiple accounts to reuse first-order coupons
* high refund rates hidden across hundreds of orders
* linked customer accounts bypassing store policies
* risky customers who later trigger disputes or chargebacks

Most store owners only notice these issues after they escalate. TrustLens helps you detect these patterns earlier, monitor behavior trends, and take action before abuse grows.

= What TrustLens Does =

TrustLens turns complex customer behavior into clear, actionable signals store owners can understand.

**Assigns every customer a trust score.** TrustLens calculates a 0-100 trust score for every customer using five detection modules running in the background. Customers are automatically grouped into six segments: **VIP**, **Trusted**, **Normal**, **Caution**, **Risk**, and **Critical**.

**Tracks the patterns that matter.** TrustLens analyzes refund rates, refund value, order completion and cancellation patterns, coupon abuse patterns, category-specific return behavior, and linked accounts across customer identifiers including addresses, phone numbers, IPs, payment methods, and device identifiers (user agent signals).

**Gives you actionable control.** Review detailed customer profiles, block abusive customers from checkout, allowlist trusted buyers, monitor store-wide risk trends, and export data for deeper analysis. The free version focuses on visibility and manual control; Pro adds optional automation, advanced notifications, webhooks, scheduled reports, chargeback tracking, and payment method risk controls.

= Free vs Pro at a glance =

The plugin on WordPress.org is the fully functional **free version**. It includes the complete trust scoring engine, all five detection modules, customer dashboard and management tools, manual blocking and allowlisting, the REST API, historical data analysis, and core notifications. There are no trial limits and no disabled core scoring features.

**Pro** (sold separately) adds deeper operational control for stores that need automation and payment-risk workflows: **Automation Rules**, **Webhooks**, **Scheduled Reports**, **Chargeback Tracking** for Stripe and WooPayments, **Payment Method Risk Controls**, and **10 advanced email notifications**.

If you need chargeback prevention for WooCommerce, TrustLens Pro helps you track disputes, monitor chargeback risk, identify repeat high-risk customers earlier, and respond with better data before payment problems escalate.

= Free Features =

* **Trust Score Engine** — Every customer receives a 0-100 trust score calculated from weighted behavioral signals
* **Customer Risk Segments** — Customers are automatically classified into VIP, Trusted, Normal, Caution, Risk, and Critical
* **Return Abuse Detection** — Detect serial returners by analyzing refund rates, refund frequency, and refund value
* **Order Pattern Analysis** — Monitor completion rates, cancellation patterns, and unusual order velocity
* **Coupon Abuse Detection** — Identify repeat first-order coupon use and coupon-then-refund patterns
* **Category-Aware Risk Scoring** — Apply extra risk when customers show high return rates in specific product categories
* **Linked Accounts Detection** — Identify customers operating multiple accounts using shared addresses, phone numbers, IPs, payment methods, and device identifiers (user agent signals)
* **Command Center Dashboard** — View store-wide risk analytics including trust score trends, segment distribution, refund activity, high-risk customers, and revenue protection insights
* **Customer Risk Profiles** — See detailed customer history, trust score signals, linked accounts, and event timelines
* **Customer Management Tools** — Search, filter, and manage customers using segments, scores, and risk indicators
* **Bulk Actions** — Block, unblock, allowlist, recalculate scores, or delete customers in bulk
* **Allowlist Protection** — Protect trusted customers from false positives — allowlisted customers keep the maximum trust score
* **Checkout Enforcement** — Blocked customers are prevented from adding items to cart or completing checkout
* **Historical Sync** — Analyze existing WooCommerce orders to build trust profiles for past customers without affecting frontend performance
* **Email Notifications** — Receive alerts for blocked checkout attempts, activation summaries, and weekly protection reports
* **REST API** — Access TrustLens data through 8 REST API endpoints for integrations and external systems
* **Configurable Scoring Thresholds** — Adjust minimum orders required for scoring, return risk levels, and checkout blocking settings
* **GDPR Compliance** — Integrates with WordPress privacy tools for customer data export and erasure requests
* **WooCommerce HPOS Compatibility** — Fully compatible with High-Performance Order Storage
* **Order Screen Integration** — Customer trust scores and segments appear directly on WooCommerce order edit pages

= Pro Features =

* **Automation Rules** — Create trigger-based rules that automatically run actions when customer risk changes
* **Webhooks** — Send real-time trust events and customer risk updates to external systems or custom endpoints
* **Scheduled Reports** — Receive daily, weekly, or monthly reports summarizing store risk activity and customer trends
* **Chargeback Tracking** — Track disputes and chargebacks for Stripe and WooPayments and incorporate them into customer trust scores
* **Payment Method Risk Controls** — Hide specific payment gateways for high-risk customers, linked accounts, or velocity spikes
* **Advanced Notifications** — Receive alerts for high-risk orders, repeat refunders, segment changes, velocity spikes, and dispute events

= Who TrustLens Is For =

* **WooCommerce store owners** dealing with serial returners, refund abuse, or risky customers
* **Operations managers** who need data to manage customer policies with confidence
* **Fraud prevention teams** looking beyond payment fraud signals
* **Stores with generous return policies** that attract both loyal customers and abuse

= How Trust Scoring Works =

Every customer begins with a base score of **50**. TrustLens detection modules analyze behavior and apply positive or negative signals:

* completed orders increase trust
* refunds decrease trust based on frequency and value
* coupon abuse patterns apply penalties
* high return rates in specific categories add additional risk
* linked accounts with risky customers reduce scores
* account age adds a loyalty bonus (up to +15 for long-standing customers)

Scores are always kept between 0 and 100. Customers below the configurable minimum order threshold (default: 3 orders) remain in the Normal segment until enough data exists for reliable scoring.

All scoring signals are visible in the customer profile so you can see exactly how each score was calculated.

= Built for Modern WooCommerce Stores =

TrustLens is designed for production WooCommerce stores and growing order volume.

Key architecture features include:

* asynchronous background processing via Action Scheduler
* WooCommerce HPOS compatibility
* REST API integration support
* batch-based historical order analysis
* lightweight checkout enforcement

These design choices let TrustLens analyze customer behavior without slowing down your store.

== 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? =

By default, no. The free version is manual: it surfaces customer risk data, and you decide when to block or allowlist someone. Pro can optionally automate specific actions, including alerts, order holds, verification requirements, and customer blocking if you configure automation rules or chargeback auto-blocking.

= 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.

= Can TrustLens help reduce return abuse and refund abuse in WooCommerce? =

Yes. TrustLens tracks refund rate, refund value, refund frequency, category-specific return behavior, and related customer patterns over time. This helps you spot serial returners and high-risk refund behavior earlier instead of reviewing refunds one order at a time.

= Can TrustLens help with chargebacks and disputes? =

Yes. TrustLens Pro includes chargeback and dispute tracking for Stripe and WooPayments, plus manual dispute recording. Dispute history can affect customer trust scores, and you can use that data to identify risky customers earlier and reduce payment risk in your store.

= 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.

= What happens right after I install TrustLens? =

New WooCommerce orders are analyzed automatically after activation. If you already have historical orders, you can run Historical Sync from the dashboard to build trust profiles from your existing store data without slowing down the frontend.

= 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.

= Does TrustLens send customer data to an external service? =

No. TrustLens works inside your WordPress and WooCommerce installation. It does not send customer data to the plugin developer or to any default third-party service. External delivery only happens if you explicitly configure features like webhooks or email notifications.

= 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. Matching identifiers used for linked-account detection are pseudonymized using keyed HMAC-SHA256 hashes, preventing the raw values from being exposed or reused across sites. 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.

= Can I get alerts and reports by email? =

Yes. The free version includes core email notifications such as blocked checkout alerts, a welcome summary, and a weekly summary. Pro adds advanced alerts, daily digests, monthly revenue protection reports, and scheduled email reports.

= 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.5 =
* **Added:** Shared TrustLens mail sender with recipient validation, structured error capture, and rolling email delivery logs.
* **Added:** Keyed HMAC-SHA256 hashing for customer identifiers and linked-account fingerprints.
* **Changed:** Refreshed the WordPress.org plugin title, description, FAQs, and search-focused copy for clearer positioning around customer risk, abuse detection, disputes, and chargebacks.
* **Changed:** Split the admin controller into focused pages, settings, notices, and AJAX service classes for cleaner maintenance.
* **Fixed:** Welcome summary is now marked sent only after successful delivery and can retry after transient mail failures.
* **Fixed:** Test notification now uses the same delivery path as real emails and surfaces detailed mailer errors when available.
* **Fixed:** Scheduled reports now honor weekly/monthly recipient settings, support comma-separated recipient lists, run at the configured due time, and include a working manual "Send Now" path.
* **Fixed:** Stored scheduled reports now track real per-recipient delivery results, retry failed sends, and avoid false-positive "sent" logs.
* **Fixed:** Privacy export and erasure now include signals, linked-account fingerprints, category stats, and automation logs.
* **Fixed:** Automation actions now write canonical action IDs and analytics/ROI reporting now read the correct action names.
* **Fixed:** Customer blocking now logs `customer_blocked` events consistently so reports and event-based metrics stay accurate.
* **Fixed:** Customer state changes now use consistent canonical events and webhook wiring for blocked, unblocked, and allowlisted flows.
* **Improved:** Notification and report cron hooks are now reconciled during runtime, cleared when disabled, and cleaned up correctly on uninstall.
* **Improved:** Reset and customer delete flows now clear all related operational data, logs, and derived records consistently.
* **Removed:** TrustLens-specific auto-update notice and one-click auto-update toggle so plugin updates are managed only through standard WordPress controls.
* **Removed:** Remaining active `md5()` usage from plugin code, replacing it with SHA-256 for internal dedupe keys.

= 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:** At that time, REST API routes for customer events and recalculate used the then-current 32-character email hash format.
* **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 and, when available, the customer email stored in TrustLens
* 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.5 =
Mail, privacy, reporting, and customer-risk reliability release: shared email sending, keyed customer/fingerprint hashing, corrected automation analytics, accurate scheduled reports, customer-state consistency, cron cleanup, and refreshed WordPress.org copy.

= 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.
