=== Rankd Tax Exemption Certificates for WooCommerce ===
Contributors: coolhuntersgt, freemius
Tags: tax exemption, woocommerce, tax exempt, certificates, sales tax
Requires at least: 6.0
Tested up to: 7.1
Requires PHP: 7.4
WC requires at least: 6.0
WC tested up to: 11.0
Stable tag: 1.1.5
License: GPL-2.0+
License URI: https://www.gnu.org/licenses/gpl-2.0.html

This plugin exempts WooCommerce customers from tax by role or by hand, with a full audit trail of every change.

== Description ==

Rankd Tax Exemption Certificates for WooCommerce provides a complete, audit-ready tax exemption workflow for WooCommerce stores.

**Compatibility notice:** This plugin cannot guarantee compatibility with plugins that write directly to the WooCommerce customer session object rather than using the standard `woocommerce_customer_is_vat_exempt` filter. If your store uses such a plugin, this plugin may not function correctly for affected customers. See the Plugin Compatibility section below for details and resolution options.

**FREE FEATURES:**

* Role-based exemption — mark whole user roles (e.g. wholesale, non-profit) tax exempt from one setting (trust-based; Pro adds certificate-backed compliance for role members)
* Per-user override on the user profile: Always exempt, Never exempt (hard block), or follow role rules
* Tax Exemption status column and filter on the Users list screen
* Configurable admin access — choose which roles may manage exemption data
* Uninstalling never deletes your data unless you explicitly opt in via a setting
* Optional internal admin note field (not visible to customer)
* WooCommerce session-level exemption — tax removed at cart and checkout automatically
* HPOS (High-Performance Order Storage) compatible
* Read-only status notice on My Account → Account Details
* Settings tab under WooCommerce → Settings → Tax Exempt Certs
* User Switching plugin compatibility
* PDF invoice integration (WooCommerce PDF Invoices & Packing Slips, WP Overnight)
* Developer filter hooks for external system integration

**PRO FEATURES (via Freemius license):**

* Customer-facing Tax Exemption tab in My Account
* Certificate submission form — org name, exemption certificate number, exemption type, country, state/province
* Country-aware form — state dropdown and exemption types update dynamically per country
* International support — country-specific exemption types for US, CA, AU, GB, IN, all EU member states
* PDF and JPG certificate upload (max 5MB, stored in a protected directory served only through a permission-checked download handler)
* Pending / Approved / Rejected / Expired / Revoked / Superseded status system
* Admin review queue with pagination: WooCommerce → Tax Exempt Certs
* Approve / reject / revoke workflow — individual and bulk actions
* Admin manual certificate entry with Select2 AJAX user search
* Enforced expiry — exemption auto-disables on expiry date via WP-Cron
* Expired certificate renewal UX — prefilled resubmission form
* Renewal grace period — keep exempting while a renewal is under review (configurable)
* Past expiry date validation (client-side and server-side)
* Configurable expiry warning buffer (default: 30 days, max 90)
* Full email suite (WooCommerce template styled):
    * Customer: submission received, approved, rejected, expiry warning, expired
    * Customer: certificate revoked (optional — disabled by default, enable in WooCommerce → Settings → Emails)
    * Admin: new submission notification
* Automated document retention — optionally purge aged certificate files X years after they become inactive, while permanently preserving the certificate record and audit trail
* Dashboard widget — pending count, expiring soon alerts, status breakdown, export buttons
* CSV exports — expiry report, active accounts, full audit log
* Timestamped audit log per user (exportable per-user or full log)

== Requirements ==

* WordPress 6.0 or higher
* PHP 7.4 or higher
* WooCommerce 7.0 or higher (must be installed and active)

WooCommerce is the only required dependency.

== Installation ==

1. Upload the rankd-tax-exemption-certificates-for-woocommerce folder to /wp-content/plugins/
2. Activate via Plugins → Installed Plugins
3. Optionally mark whole roles tax exempt at WooCommerce → Settings → Tax Exempt Certs
4. For Pro: purchase a license and activate it from the license activation link on the settings tab

== Usage ==

= Marking a customer as tax exempt (Free) =

1. Go to Users → All Users
2. Click Edit on any user
3. Scroll to the Tax Exemption section
4. Check the Tax Exempt checkbox
5. Optionally add an internal note
6. Click Update User

Tax is removed from that customer's cart and checkout on their next page load.

= Certificate submission workflow (Pro) =

Customer flow:

1. Customer logs in and goes to My Account → Tax Exemption
2. Completes the form and uploads their certificate (PDF or JPG)
3. Receives confirmation email
4. Status shows as Pending until reviewed

Admin flow:

1. Admin receives notification email
2. Goes to WooCommerce → Tax Exempt Certs
3. Reviews the pending submission, views the certificate document
4. Approves (verifying the expiry date) or rejects (providing a reason)
5. Customer receives approval or rejection email

Expiry:

* WP-Cron runs nightly and auto-expires certificates past their expiry date
* Warning emails fire X days before expiry (configurable, default 30 days)
* Expired customers see a prefilled resubmission form in My Account
* If a renewal is pending review when the old certificate expires, exemption continues for the configured grace period

Role compliance (Pro):

* Members of Tax-Exempt Roles are NOT exempted until there is evidence: an approved certificate covering the order's jurisdiction, or your recorded override
* The Role Exempt tab of the review queue lists role members needing attention, with per-row and bulk actions: Add Certificate, Email for Certificate, or Override ("accept the risk", scoped to all or specific jurisdictions — the decision is written to the audit log)
* A certificate request email points the customer to the My Account submission form
* If the certificate backing a member later expires or is revoked, they automatically reappear for review

= Settings =

WooCommerce → Settings → Tax Exempt Certs:

* Tax-Exempt Roles: Users holding any of these roles are automatically tax exempt (free version). In Pro, role members are exempted only once there is evidence on file — an approved certificate covering the order's jurisdiction, or an override you record — so a role assignment alone never silently removes tax. Individual users can be excluded via the Never Exempt override on their profile. Default: none.

Pro adds:

* Expiry Warning (days): How many days before expiry to send the renewal reminder and allow early renewal submissions (1–90).
* Admin Notification Email: Where to send new submission alerts.
* Customer Contact Email: Address shown to customers when their exemption is revoked.
* Renewal Grace Period (days): How long to keep exempting after expiry while a renewal is pending review (0 disables).

== Screenshots ==

1. The Tax Exemption section on a user's profile screen (Users → Edit User) — the Always/Never/follow-role-rules override and internal note field. Free.
2. The Tax Exemption status column and filter dropdown on the Users list screen. Free.
3. The plugin's settings tab at WooCommerce → Settings → Tax Exempt Certs — Tax-Exempt Roles and Who Can Manage Exemptions. Free.
4. The customer-facing Tax Exemption tab under My Account, with the certificate submission form. Pro.
5. The admin Certificate Review Queue — pending, approved, and rejected certificates with Approve/Reject/Revoke actions. Pro.
6. The Role Exempt tab — role members who haven't yet provided certificate evidence, with per-row and bulk actions. Pro.
7. The dashboard widget showing pending certificates and expiring-soon alerts. Pro.

== FAQ ==

= What's the difference between the Free and Pro exemption models? =

Free is trust-based: mark a role as tax-exempt and every member of that role is exempted immediately, no evidence required. Pro adds a certificate-backed compliance layer — role members aren't exempted until there's an approved certificate on file covering the order's jurisdiction, or a recorded override accepting the risk. Individual users can always be excluded via the Never Exempt override regardless of tier.

= Will this conflict with my wholesale plugin or another tax/VAT plugin? =

Usually not — this plugin is designed to defer to exemptions granted by other systems rather than override them. It can conflict with plugins that write directly to the WooCommerce customer session object instead of using the standard `woocommerce_customer_is_vat_exempt` filter. See the Plugin Compatibility section below if a customer's exemption isn't applying correctly.

= What happens to my data if I deactivate or delete the plugin? =

Deactivating never touches your data. Deleting the plugin also leaves all data in place by default — certificates, overrides, settings, and the audit log are only removed if you explicitly opt in via the "Remove Data on Uninstall" setting before deleting.

= Which staff roles can manage tax exemption? =

Configurable at WooCommerce → Settings → Tax Exempt Certs → Who Can Manage Exemptions. Administrator is always included and can't be removed. Roles left out of that setting still get read-only access to certificate and status information, but can't make changes.

= Is this compatible with High-Performance Order Storage (HPOS)? =

Yes.

= What happens when a certificate expires? =

A scheduled daily check automatically expires certificates past their expiry date and removes the customer's exemption. If Expiry Warning is configured, a reminder email goes out X days beforehand, and the customer sees a prefilled renewal form in My Account. A configurable grace period can keep exemption active while a renewal is under review.

= Can a customer be exempt in some states/jurisdictions but not others? =

Yes (Pro) — certificates are jurisdiction-specific, and a customer can hold multiple certificates covering different states, provinces, or countries. Exemption is applied only when the order's destination matches an approved certificate's jurisdiction.

= Where are uploaded certificate documents stored, and are they secure? =

In a protected directory outside direct web access (via `.htaccess` on Apache, with an Nginx compatibility notice shown if detected), served only through a permission-checked download handler — never a public URL.

== Wholesale & Third-Party Compatibility ==

This plugin includes a developer filter for external systems to opt individual users out of its management entirely.

Example — wholesale plugin integration:

    add_filter( 'rankd_tx_skip_user', function( $skip, $user_id ) {
        // Tell this plugin to ignore users managed by your wholesale system.
        if ( has_wholesale_exemption( $user_id ) ) return true;
        return $skip;
    }, 10, 2 );

The plugin also supports additional exemption sources via:

    add_filter( 'rankd_tx_exemption_sources', function( $sources, $user_id ) {
        if ( has_wholesale_exemption( $user_id ) ) $sources[] = 'wholesale';
        return $sources;
    }, 10, 2 );

Exemption is applied if ANY source returns active. This plugin never removes an exemption granted by another system.

== Data Storage ==

USER META (wp_usermeta):

* `_rankd_tx_is_exempt` — String. Per-user override: `always`, `never`, or absent (follow role rules). Legacy `1` values from the pre-1.5.0 checkbox are read as `always`.
* `_rankd_tx_exempt_note` — String. Admin note. Never shown to customer.

CUSTOM TABLES (Pro):

* `{prefix}rankd_tx_certificates` — One row per certificate submission.
* `{prefix}rankd_tx_audit_log` — One row per status change event.

UPLOADS (Pro):

* wp-content/uploads/rankd-tax-exempt-certs/
* Protected by .htaccess (Apache/LiteSpeed) plus an index.php fallback. Files are served only through a permission-checked PHP download handler. Nginx requires a one-time server rule — see Server Compatibility below.

== Invoice Plugin Integration ==

Tax exemption details are automatically added to PDF invoices for:

* WooCommerce PDF Invoices & Packing Slips (WP Overnight) — fires after order details table on invoices, proformas, and credit notes
* WooCommerce PDF Invoices (WP Overnight older plugin) — fires after order table
* WooCommerce order confirmation and My Account receipt pages — visible to the ordering customer and store managers only

The notice includes: Organization name, Certificate number, Jurisdiction, Certificate expiry date. It always reflects the certificate that covered the order at purchase time, even if the customer's status changes later.

Developer filters:

* `rankd_tx_show_invoice_notice` — return false to suppress entirely
* `rankd_tx_invoice_document_types` — array of document types to show on (default: invoice, proforma, credit-note)
* `rankd_tx_invoice_notice_html` — replace the full notice HTML (args: $html, $order)

== Plugin Compatibility & Tax Exemption Conflicts ==

**Important:** This plugin cannot guarantee compatibility with plugins that write directly to the WooCommerce customer session object rather than using the `woocommerce_customer_is_vat_exempt` filter. These plugins bypass the filter system entirely and no priority adjustment will resolve the conflict.

= How this plugin handles conflicts =

WooCommerce determines tax exemption via a single boolean flag on the customer session. This plugin hooks into this system at filter priority 20, which means:

* Any plugin setting exemption to true at priority 10 or lower will be respected — this plugin will not override it
* Any plugin setting exemption to false at priority 10 or lower may prevent this plugin from applying its own exemption, even if the customer is marked exempt here

This is by design. This plugin deliberately avoids overriding other systems that have already made an exemption decision.

= Developer integration — excluding users =

If you are building or maintaining a plugin that manages tax exemption for certain users, you can tell this plugin to step aside entirely for those users using the `rankd_tx_skip_user` filter:

    add_filter( 'rankd_tx_skip_user', function( $skip, $user_id ) {
        if ( my_plugin_manages_this_user( $user_id ) ) {
            return true;
        }
        return $skip;
    }, 10, 2 );

When `rankd_tx_skip_user` returns true for a user:

* The Tax Exemption Override does not appear on their WordPress user profile
* This plugin does not fire any checkout exemption logic for them
* Their tax status is entirely controlled by your plugin

= Recommended approach for site owners =

1. Use `rankd_tx_skip_user` to exclude users managed by the other plugin. This is the cleanest solution and eliminates the conflict at the source.
2. Manage each user in only one system. Regular customers through this plugin; special user types, like wholesale customers, through the plugin that handles their exemption.
3. Check filter priority. If the conflicting plugin uses the `woocommerce_customer_is_vat_exempt` filter, adjusting its priority relative to this plugin (priority 20) may resolve the conflict. Contact the other plugin's developer for guidance.

== Server Compatibility ==

= Apache / LiteSpeed =

Fully supported. The plugin writes an .htaccess file to the certificate upload directory that blocks all direct HTTP access. No additional configuration required.

= Nginx =

The .htaccess file has no effect on Nginx servers. If your site runs Nginx, add the following block to your server configuration to protect uploaded certificate files:

    location ~* /uploads/rankd-tax-exempt-certs/ {
        deny all;
        return 403;
    }

The plugin displays a persistent admin notice if it detects an Nginx server or a missing .htaccess file, with instructions for your hosting provider or server administrator. The notice can be dismissed once the configuration is confirmed.

= Other servers =

A fallback index.php is also written to the directory to prevent directory listing on servers that process neither .htaccess nor Nginx location blocks.

== Scheduled Tasks ==

Certificate expiry enforcement and warning emails run as daily scheduled actions via **Action Scheduler** — the background job system built into WooCommerce. No hosting configuration, wp-config changes, or extra plugins are required.

You can view, monitor, and manually run the plugin's scheduled actions at **WooCommerce → Status → Scheduled Actions** (search for "rankd_tx").

As a safety net, if the checks have not completed in over 36 hours the plugin displays an admin notice with a one-click **Run checks now** button, so a store manager can trigger the expiry check and warning emails immediately from the dashboard.

For additional reliability on very low-traffic sites, a server-side cron job in your hosting control panel is optional hardening:

    curl -s "https://yoursite.com/wp-cron.php?doing_wp_cron" > /dev/null

== Developer Reference ==

Filters:

* `rankd_tx_skip_user` — Return true to exclude a user from this plugin.
* `rankd_tx_exemption_sources` — Add external exemption sources.
* `rankd_tx_tax_id_labels` — Modify the per-country tax ID label map.
* `rankd_tx_exemption_types_map` — Modify the per-country exemption type lists.
* `rankd_tx_generic_exempt_types` — Modify the generic exemption type fallback list.
* `rankd_tx_settings` — Add/modify settings fields.
* `rankd_tx_review_queue_per_page` — Change review queue page size (default 50).
* `rankd_tx_show_invoice_notice`, `rankd_tx_invoice_document_types`, `rankd_tx_invoice_notice_html` — see Invoice Plugin Integration.

Actions:

* `rankd_tx_certificate_submitted` — Fires on new submission. Args: $user_id, $cert_id
* `rankd_tx_certificate_approved` — Fires on approval. Args: $user_id, $cert_id, $expiry_date
* `rankd_tx_certificate_rejected` — Fires on rejection. Args: $user_id, $cert_id, $reason
* `rankd_tx_certificate_revoked` — Fires on revocation. Args: $user_id, $cert_id, $reason
* `rankd_tx_certificate_expiry_warning` — Fires on warning. Args: $user_id, $cert_id, $expiry_date
* `rankd_tx_certificate_expired` — Fires on expiry. Args: $user_id, $cert_id

== Uninstalling ==

By default, deleting the plugin via the WordPress admin Plugins screen removes
NOTHING beyond scheduled tasks — deactivating never removes data, and neither
does deleting, unless you explicitly opt in.

To permanently remove all plugin data on uninstall, enable "Remove Data on
Uninstall" at WooCommerce → Settings → Tax Exempt Certs before deleting the
plugin. With that enabled, uninstalling removes:

* All plugin options
* All user meta (`_rankd_tx_is_exempt`, `_rankd_tx_exempt_note`)
* All order meta (`_rankd_tx_was_exempt`, `_rankd_tx_sources`, `_rankd_tx_cert_id`)
* Both custom database tables (Pro)
* Scheduled cron jobs

Uploaded certificate files are never deleted automatically, even with this
setting enabled — remove them manually if required:
`wp-content/uploads/rankd-tax-exempt-certs/`

== Changelog ==

= 1.1.5 = (8/13/2026)
* Confirmed tested up to WordPress 7.1 and WooCommerce 11.0

= 1.1.4 = (8/13/2026)
* Tested with WordPress 7.1 and WooCommerce 11.0
* Fixed: uninstall cleanup used a raw internal WordPress reference that could silently skip removing this plugin's admin capability from roles on some hosts; now uses the reliable WordPress API instead
* Fixed: an internal version number was out of sync with the plugin's actual version

= 1.1.3 = (7/28/2026)
* Fixed: order stamping on order edit page 
* Fixed: "Constant already defined" warnings during plugin activation/reactivation. 
* Changed: declared compatibility with WooCommerce's Cart & Checkout Blocks feature

= 1.1.2 =
* Removed temporary debug logging added while investigating the order-badge inconsistency 

= 1.1.1 =
* Changed: removed documentation of the admin order-edit-screen tax-exempt badge and order-stamping meta

= 1.1.0 =
* Initial public release.

