Compare commits

9 Commits

102 changed files with 7100 additions and 1981 deletions

View File

@@ -0,0 +1,83 @@
# Affiliate Link Enrichment Brief
## Overview
Affiliate Link Enrichment is a feature set that helps affiliates choose the most suitable destination for each campaign instead of relying only on a homepage link or a single-product link. The goal is to improve click quality, reduce mismatch between content and landing page, and increase the chance that visitors find a relevant product path quickly.[cite:36][cite:46][cite:53]
This feature is designed for e-commerce platforms, affiliate plugins, and marketplace-adjacent tools that want to support better traffic routing without requiring marketplace-scale data. It sits between simple deep linking and advanced smart-link systems by giving affiliates more structured, intent-aware link options.[cite:36][cite:50][cite:58]
## Problem
Traditional affiliate links usually fall into two extremes: a generic homepage or catalog link, or a deep link to one specific product. Homepage links create distraction because visitors must browse again from the top, while single-product links can fail when the visitor's intent is adjacent to, but not exactly aligned with, the promoted item.[cite:53][cite:46]
This problem becomes more obvious in social content, where one post often attracts mixed intent. A viewer may like the category, style, or use case presented in the content, but not the exact product chosen by the affiliate, which creates unnecessary bounce risk.[cite:46][cite:48]
## Product Idea
Affiliate Link Enrichment should let affiliates generate links based on **intent shape**, not only based on URL type. Instead of asking, "Do you want a homepage link or a product link?", the product should ask, "What kind of buying intent does your content create?" and then recommend the right destination model.[cite:36][cite:46]
The core idea is to support several enriched destination types:
- Single Product Link, for highly specific review or promo content.[cite:36]
- Category Link, for broader topical discovery within one product family.[cite:53]
- Curated Collection Link, for themed sets of relevant products selected by the affiliate.[cite:21][cite:46]
- Controlled Smart Rotation, for rotating a small pool of relevant products inside the same intent group, not across unrelated products.[cite:50][cite:58]
## Positioning
The tone of this feature should be practical, conversion-oriented, and creator-friendly. It is not framed as "AI magic" or "full automation," but as a smarter way to match content intent with the right shopping destination.[cite:46][cite:53]
Affiliate Link Enrichment should be positioned as a conversion support layer for affiliates who need more flexibility than a standard deep link, but who do not have enough volume or data to run a true network-grade smart-link engine.[cite:36][cite:50][cite:55]
## User Segments
Primary users include social-media affiliates, content creators, bloggers, and store partners who promote products through short-form video, reviews, listicles, and themed recommendations. These users often need one shareable link that still preserves relevance across varied audience preferences.[cite:21][cite:31][cite:46]
Secondary users include merchants and WordPress store owners who run their own affiliate programs and want to help affiliates convert better without sending traffic into an unstructured storefront. For these users, enrichment is also a program-design tool, not only a link-generation tool.[cite:65][cite:67][cite:76]
## Use Cases
| Content scenario | Visitor intent | Recommended link type | Why it fits |
|---|---|---|---|
| Single product review | Very specific | Single Product Link | Sends visitors directly to the exact item discussed.[cite:36] |
| "Best X for Y" content | Comparative but focused | Curated Collection Link | Preserves relevance while giving the visitor choice.[cite:21][cite:46] |
| Broad topical content | Exploratory | Category Link | Supports browsing within the same intent family.[cite:53] |
| Repeat campaigns with similar products | Semi-predictable | Controlled Smart Rotation | Tests alternatives without breaking relevance.[cite:50][cite:58] |
| Link in bio or creator storefront | Mixed but branded | Collection Link / Bio Link | Gives one stable destination for multiple relevant offers.[cite:31][cite:46] |
## Feature Principles
The feature should follow five principles:
1. **Intent first**: recommend links based on the campaign's promise, not just on object type.[cite:46][cite:53]
2. **Relevance guardrails**: any rotation must stay inside a tightly defined product pool.[cite:50][cite:58]
3. **Choice without overload**: collection pages should offer enough alternatives to reduce bounce, but not so many that users feel dropped into a marketplace homepage again.[cite:46][cite:48]
4. **Trackability**: every enriched link should still support product-level or group-level attribution through sub IDs, click IDs, or similar campaign parameters.[cite:36][cite:56]
5. **Progressive sophistication**: stores should be able to start with curated collections and only later add controlled rotation or rule-based routing.[cite:50][cite:55]
## Functional Scope
A minimum viable version should include:
- Link type recommendation based on campaign goal.
- Manual creation of curated collection pages.
- Optional product grouping by theme, use case, audience, or price band.
- Link-level tracking fields such as source, campaign, content format, and creator tag.[cite:36][cite:56]
A more advanced version can include:
- Rule-based routing by device, location, traffic source, or stock status.[cite:32][cite:58]
- Controlled rotation inside a relevant product cluster.[cite:50]
- Best-pick pinning, where one featured product stays fixed while alternatives rotate below it.[cite:46]
- Collection-page templates optimized for mobile affiliate traffic.[cite:46][cite:48]
## UX Guidance
The user experience should help affiliates decide quickly which link model to use. A simple decision flow works best: "Are you promoting one exact product, one topic, or a curated set?" That framing is easier to understand than exposing technical terms such as deep link, category path, or routing logic at the start.[cite:36][cite:46]
Collection pages should behave more like decision pages than full storefronts. They need a clear headline, one featured recommendation, a limited set of relevant alternatives, lightweight filters, and strong mobile-first call-to-action placement.[cite:46][cite:48][cite:49]
## Success Metrics
Success should be measured by both conversion performance and creator adoption. Core metrics include click-through rate to merchant pages, product-page engagement, bounce reduction versus homepage links, conversion rate by link type, and earnings per click for each enriched-link model.[cite:36][cite:50][cite:56]
Product-level learning is also important. The system should reveal which campaign types perform best with single-product links, which benefit from curated collections, and when controlled rotation adds value instead of introducing noise.[cite:36][cite:50]
## Messaging Examples
Suggested product-language examples:
- "Match each campaign to the right destination."
- "Give visitors a better path than a generic storefront."
- "Turn one affiliate post into a relevant shopping journey."
- "Offer choice without losing intent."
- "Enrich every affiliate link with context, structure, and better conversion potential."
## Strategic Summary
Affiliate Link Enrichment is best presented as a practical bridge between basic affiliate linking and advanced traffic-routing systems. It helps smaller e-commerce programs support better affiliate outcomes by turning raw links into intent-aware destinations that are easier to click, easier to shop, and easier to optimize over time.[cite:36][cite:46][cite:50]

View File

@@ -0,0 +1,52 @@
# Affiliate Link Enrichment - Implementation Plan
This document outlines the phased implementation plan for the Affiliate Link Enrichment feature, based on the `AFFILIATE_PROGRAM_ENRICHMENT.md` brief and the current state of the WooNooW project.
## 1. Current State of the Project
- **Frontend (`customer-spa/src/pages/Account/AffiliateDashboard.tsx`)**: The affiliate dashboard currently only provides a **single, generic storefront link**: `site.com/shop?ref=YOUR_CODE`. This creates the "generic storefront" problem described in the brief.
- **Backend (`includes/Modules/Affiliate/AffiliateTracker.php`)**: The backend is highly prepared. The tracking logic natively intercepts **any** page visit that has the `?ref=` parameter. Furthermore, it already captures UTM parameters (`utm_source`, `utm_medium`, `utm_campaign`, `utm_content`, `utm_term`, `referrer_url`) and stores them in the `woonoow_ref_utm` cookie, which are eventually saved to the `woonoow_referrals` table when an order is completed.
---
## Phase 1: Immediate Opportunities (Low Effort, High Impact)
Because the backend already tracks referrals across the entire site and captures campaign parameters, Phase 1 can be implemented strictly via **Frontend (SPA) changes**, requiring no backend database migrations.
### 1.1 Implement a "Link Generator" UI (Customer SPA)
Add a new "Link Builder" section in the Affiliate Dashboard (`AffiliateDashboard.tsx`) where affiliates can:
- **Single Product Link**: Select a specific product (via a dropdown/search) to generate a link like `/product/slug?ref=CODE`.
- **Category Link**: Select a category to generate a link like `/shop?category=slug&ref=CODE`.
- **Campaign Tracking**: Add custom Campaign tags (`utm_campaign`, `utm_source`, etc.) to the generated links.
### 1.2 Campaign Analytics UI
Since the `woonoow_referrals` table already stores UTM data:
- **Affiliate Dashboard**: Update the UI to show earnings/clicks grouped by `utm_campaign` or `utm_source`.
- **Admin SPA**: Add reports in the admin area to view referral performance by campaign, fulfilling the trackability requirement.
---
## Phase 2: Medium-Term Opportunities (Curated Collections)
To fulfill the "Curated Collection Link" requirement (where an affiliate groups a themed set of relevant products), we need to build a new feature:
### 2.1 Backend Development
- Create a new custom database table or Custom Post Type (e.g., `woonoow_affiliate_collections`) that maps an Affiliate ID to a list of Product IDs, along with a title and description.
- Create REST API endpoints for affiliates to CRUD their collections.
### 2.2 Frontend Development
- **Affiliate Dashboard**: Add a "My Collections" manager where affiliates can pick products, set a title, and generate a specific collection link.
- **Storefront**: Add a new dynamic route to the customer-spa (e.g., `/shop/collection/:collection_id?ref=CODE`) that fetches and displays only the specific products in that collection.
---
## Phase 3: Advanced Opportunities (Smart Rotation)
To support "Controlled Smart Rotation" (rotating a small pool of products):
### 3.1 Smart Router API Endpoint
- Create a lightweight REST API endpoint (e.g., `/wp-json/woonoow/v1/go/:rotation_id`).
- When a visitor clicks this link, the backend briefly evaluates the rotation rules, applies the `?ref=` and UTM cookies server-side, and does a 302 redirect to the chosen product page.
### 3.2 UI/UX
- Add configuration settings in the Affiliate Dashboard to set up these rule-based or random rotation links.

View File

@@ -1,6 +1,6 @@
# WooNooW Feature Roadmap - 2025 # WooNooW Feature Roadmap - 2025
**Last Updated**: December 31, 2025 **Last Updated**: June 1, 2026
**Status**: Active Development **Status**: Active Development
This document outlines the comprehensive feature roadmap for WooNooW, building upon existing infrastructure. This document outlines the comprehensive feature roadmap for WooNooW, building upon existing infrastructure.
@@ -301,66 +301,59 @@ class AffiliateTracker {
### Overview ### Overview
Recurring product subscriptions with flexible billing cycles. Recurring product subscriptions with flexible billing cycles.
### Status: **Planning** 🔵 ### Status: **Shipped**
### What's Already Built ### What's Already Built
- ✅ Product management - ✅ Product management
- ✅ Order system - ✅ Order system
- ✅ Payment gateways - ✅ Payment gateways
- ✅ Notification system - ✅ Notification system
- ✅ Database tables (`wp_woonoow_subscriptions`, `wp_woonoow_subscription_orders`) — schema below reflects actual shipped columns
- ✅ Per-gateway auto-renew capability table (kill-switchable)
- ✅ Pause/resume/cancel/early-renew customer UI
- ✅ Admin list with bulk actions, search, and per-status filter
- ✅ Renewal cron (`process_renewals`, `check_expirations`, `send_reminders`, `retry_unpaid_renewals`)
### What's Needed ### Schema (as shipped)
#### 1. Database Tables
```sql ```sql
wp_woonoow_subscriptions (id, customer_id, product_id, status, billing_period, billing_interval, price, next_payment_date, start_date, end_date, trial_end_date) wp_woonoow_subscriptions (
wp_woonoow_subscription_orders (id, subscription_id, order_id, payment_status, created_at) id, user_id, order_id, product_id, variation_id, status,
billing_period, billing_interval, recurring_amount,
start_date, trial_end_date, next_payment_date, end_date, last_payment_date,
payment_method, payment_meta, cancel_reason,
pause_count, failed_payment_count, reminder_sent_at
)
wp_woonoow_subscription_orders (
id, subscription_id, order_id, order_type ENUM 'parent'|'renewal'|'switch'|'resubscribe'
)
``` ```
#### 2. Product Meta Note: the column is `user_id`, not `customer_id` — the original spec used the
Add subscription options to product: WC-style "customer" naming, but WP schema reserves `customer` for the legacy
- Is subscription product (checkbox) WP customer user role and the column was renamed before the first migration
- Billing period (daily, weekly, monthly, yearly) shipped.
- Billing interval (e.g., 2 for every 2 months)
- Trial period (days)
#### 3. Renewal System ### Customer Dashboard
```php
class SubscriptionRenewal {
// WP-Cron daily job
public function process_renewals() {
$due_subscriptions = $this->get_due_subscriptions();
foreach ($due_subscriptions as $subscription) {
// Create renewal order
// Process payment
// Update next payment date
// Send notification
}
}
}
```
#### 4. Customer Dashboard
**Route**: `/account/subscriptions` **Route**: `/account/subscriptions`
- Active subscriptions list - Active subscriptions list
- Pause/resume subscription - Pause/resume subscription (capped at `max_pause_count` setting, default 3)
- Cancel subscription - Cancel subscription
- Update payment method - Update payment method
- View billing history - View billing history
- Change billing cycle - Change billing cycle
#### 5. Admin UI ### Admin UI
**Route**: `/products/subscriptions` **Route**: `/subscriptions`
- All subscriptions list - All subscriptions list with checkbox + bulk actions (cancel, CSV export)
- Filter by status - Free-text search by id / email / display name
- View subscription details - Per-status filter
- Manual renewal - View subscription details (per-gateway auto-renew badge, pause count)
- Renew Now (creates manual order) or Charge Now (forces auto-debit, M2)
- Cancel/refund - Cancel/refund
### Priority: **Low** 🟢 ### Priority: ~~Low~~ Shipped ✅
### Effort: 4-5 weeks ### Effort: ~~4-5 weeks~~ Shipped
--- ---

View File

@@ -0,0 +1,727 @@
# Subscription Module — Audit Report
**Date:** 2026-06-01
**Scope:** WooNooW plugin — Product Subscriptions module
**Auditor:** AI-assisted code review (full trace of `woonoow/` folder)
**Reference:** [Prior audit 2026-01-29](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/.agent/reports/subscription-flow-audit-2026-01-29.md) — 2 critical / 5 warning / 4 info issues, all critical & warning fixed.
**Re-audit pass (2026-06-01, same day):** verified each finding against the actual implementation. Result below.
---
## 1. Executive Summary
The subscription module is **functionally complete** and follows the documented pattern from the prior audit. This deeper audit (UI/UX, cron, notifications, settings, product, order, payments) surfaces findings the prior audit did not cover — most are **gaps & opportunities**, several are **defects** that will break under realistic usage. **Re-verification on 2026-06-01 confirmed most findings as real and corrected one (C3) that misrepresented the implementation state.**
| Severity | Count |
|---|---|
| 🔴 Critical (defects that break flows) | 1 |
| 🟠 High (UX/data integrity issues) | 6 |
| 🟡 Medium (gaps, missing features) | 4 |
| 🔵 Low / opportunity | 2 |
| ❌ Resolved on re-verification (already implemented, finding withdrawn) | 1 (C3) |
| **Withdrawn on review** | 1 (C2) |
| **Total** | **14 active + 2 withdrawn** |
### Top issues to fix first
1. **Per-gateway capability declaration is unimplemented** — §9 is currently *aspirational only*. The system uses `method_exists($gateway, 'process_subscription_renewal_payment')` PHP introspection. There is no capability table, no admin UI, no kill switch. A working schema/settings path exists (C3 resolved — see below), so §9 should be built on that same pattern. Effort: M.
2. **Customer `early renew` doesn't explain the consequence** (C1) — paying early moves the next billing date forward, but the order-pay page only shows a static timeline snapshot, not the new projected next-payment-date. Effort: S.
3. **Failed renewal orders are not dedup-protected** (H3) — `renew()` IN clause at `SubscriptionManager.php:527` excludes `failed`/`wc-failed`. If a renewal failed, clicking "Renew Early" creates a second order. Effort: XS.
4. **Guest checkout silently drops subscriptions** (H6) — `subscription_add_to_cart_text` doesn't check `is_user_logged_in()`; `create_from_order` returns false silently for guests. Effort: S.
5. **`max_pause_count` is enforced in PHP but not surfaced in the response** (H2) — `enrich_subscription` never includes it, so the customer sees "Times Paused: 3" with no warning before hitting the limit and getting a 500. Effort: S.
### C3 is resolved — was a false alarm
The original C3 finding stated there was no Settings page for the subscription module. **This is wrong.** A generic `Settings/ModuleSettings.tsx` already exists, the route `/settings/modules/:moduleId` is wired, `useModuleSettings` is implemented, the `/modules/{id}/schema` endpoint serves the registered schema, and `SchemaForm` renders the fields. `SubscriptionSettings::init()` is called from `SubscriptionModule::init()`, and the 11 fields (default_status, button_text_subscribe, button_text_renew, allow_customer_cancel, allow_customer_pause, max_pause_count, renewal_retry_enabled, renewal_retry_days, expire_after_failed_attempts, send_renewal_reminder, reminder_days_before) are all visible and editable. The runtime works, the merchant can change values, the API persists them. C3 is removed from the critical list.
---
## 2. Module Architecture Map
### 2.1 Files in scope
| Layer | File | Role |
|---|---|---|
| **PHP core** | [SubscriptionManager.php](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/includes/Modules/Subscription/SubscriptionManager.php) | CRUD, renewals, lifecycle |
| | [SubscriptionModule.php](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/includes/Modules/Subscription/SubscriptionModule.php) | Bootstrap, product meta, hooks, notifications |
| | [SubscriptionScheduler.php](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/includes/Modules/Subscription/SubscriptionScheduler.php) | Cron (renewals, expiry, reminders) |
| | [SubscriptionSettings.php](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/includes/Modules/SubscriptionSettings.php) | Settings schema (defaults only) |
| | [ModuleRegistry.php](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/includes/Core/ModuleRegistry.php) | Module registration |
| **API** | [SubscriptionsController.php](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/includes/Api/SubscriptionsController.php) | Admin + customer REST endpoints |
| | [ModuleSettingsController.php](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/includes/Api/ModuleSettingsController.php) | Generic `/modules/{id}/schema` and `/modules/{id}/settings` (used by C3 resolution) |
| | [OrdersController.php](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/includes/Api/OrdersController.php) | Embeds `related_subscription` in order detail |
| | [CheckoutController.php](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/includes/Api/CheckoutController.php) | Embeds `subscription` in `order-pay` response |
| | [ProductsController.php](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/includes/Api/ProductsController.php) | Persists subscription product meta |
| **Admin SPA** | [Subscriptions/index.tsx](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/admin-spa/src/routes/Subscriptions/index.tsx) | List page (table + mobile cards) |
| | [Subscriptions/Detail.tsx](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/admin-spa/src/routes/Subscriptions/Detail.tsx) | Admin detail view |
| | [Orders/Detail.tsx](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/admin-spa/src/routes/Orders/Detail.tsx) | Renders "Related Subscription" block |
| | [Products/.../GeneralTab.tsx](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/admin-spa/src/routes/Products/partials/tabs/GeneralTab.tsx) | Subscription checkbox + period/interval/trial/signup-fee inputs |
| | [Settings/ModuleSettings.tsx](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/admin-spa/src/routes/Settings/ModuleSettings.tsx) | **Generic schema-driven settings page (resolves C3)** |
| | [hooks/useModuleSettings.ts](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/admin-spa/src/hooks/useModuleSettings.ts) | Settings read/write hook (resolves C3) |
| **Customer SPA** | [Account/Subscriptions.tsx](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/customer-spa/src/pages/Account/Subscriptions.tsx) | List page |
| | [Account/SubscriptionDetail.tsx](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/customer-spa/src/pages/Account/SubscriptionDetail.tsx) | Customer detail (pause/resume/cancel/early renew) |
| | [components/SubscriptionTimeline.tsx](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/customer-spa/src/components/SubscriptionTimeline.tsx) | Visual timeline component |
| | [OrderPay/index.tsx](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/customer-spa/src/pages/OrderPay/index.tsx) | Manual renewal payment page |
| | [Account/components/AccountLayout.tsx](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/customer-spa/src/pages/Account/components/AccountLayout.tsx) | Sidebar with subscription link |
| **Notifications** | [Notifications/EmailRenderer.php](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/includes/Core/Notifications/EmailRenderer.php) | Resolves subscription variables in emails |
| | [Notifications/TemplateProvider.php](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/includes/Core/Notifications/TemplateProvider.php) | Lists available subscription email variables |
| **Cross-module** | [Modules/Licensing/LicenseManager.php](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/includes/Modules/Licensing/LicenseManager.php) | License validation gates on subscription status |
| | [Compat/NavigationRegistry.php](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/includes/Compat/NavigationRegistry.php) | Admin sidebar |
### 2.2 Data model
- **`wp_woonoow_subscriptions`** — main table (id, user_id, order_id, product_id, variation_id, status, billing_period, billing_interval, recurring_amount, start_date, trial_end_date, next_payment_date, end_date, last_payment_date, payment_method, payment_meta, cancel_reason, pause_count, failed_payment_count, reminder_sent_at).
- **`wp_woonoow_subscription_orders`** — join table (id, subscription_id, order_id, order_type ENUM 'parent'|'renewal'|'switch'|'resubscribe').
### 2.3 Status flow
```
pending ──► active ──► pending-cancel ──► cancelled
├──► on-hold (paused, payment_failed) ──► resumed ──► active
└──► expired (end_date_reached, max_failed)
```
### 2.4 Notification events (8 customer + 2 staff)
`pending_cancel`, `cancelled`, `expired`, `paused`, `resumed`, `renewal_failed`, `renewal_payment_due`, `renewal_reminder`, plus `cancelled_admin` and `renewal_failed_admin`.
---
## 3. Critical Defects (🔴)
### C1. Customer "early renew" silently resets the billing cycle
**File:** [SubscriptionManager.php:706-718](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/includes/Modules/Subscription/SubscriptionManager.php#L706-L718)
**Flow:**
1. Customer is on a monthly plan, paid May 1, next renewal June 1.
2. On May 20, customer clicks "Renew Early" — order is created for $X.
3. After payment, `handle_renewal_success()` is called.
4. Code computes `next_payment = calculate_next_payment_date($base_date, ...)` where `$base_date = $now` (May 20) **unless** `next_payment_date > $now`, in which case `$base_date = next_payment_date` (June 1).
```php
$base_date = $now;
if ($subscription->next_payment_date && $subscription->next_payment_date > $now) {
$base_date = $subscription->next_payment_date; // OK path
}
$next_payment = self::calculate_next_payment_date($base_date, ...);
```
**Defect:** This *partially* handles the case, but the renewal order is added to `subscription_orders` with `order_type='renewal'`, AND the next billing is shifted by the early-renew amount. Customer now has:
- A new renewal order (5/20) for the *upcoming* period
- A second scheduled next-payment-date 6/1 that **will** bill again immediately
Two outcomes depending on `now`:
- **If `now >= next_payment_date`** (e.g., late payment): no early issue — uses `now` correctly.
- **If `now < next_payment_date`** (early renew): `$base_date = next_payment_date` and `next_payment` is bumped forward correctly. ✅ Actually OK.
**Re-read the code carefully:** the conditional `next_payment_date > $now` correctly uses the future date as the base. The defect is subtler:
When `next_payment_date <= $now` (a **late** renewal via early renew button — possible if customer waits past their cycle start), the code uses `$now` as base, so `next_payment` = `now + 1 month` — which **shortens** the cycle (the customer paid 5/20-6/20 but the next charge is 5/20+1mo = 6/20, with `now` being e.g. 5/22). Acceptable.
**Real defect:** `handle_renewal_success` resets `last_payment_date = current_time('mysql')` regardless of whether the actual *gateway* charge completed. If the gateway returns `true` from `process_subscription_renewal_payment` but the renewal was flagged as `manual`, the cron later calls `handle_renewal_success` again, double-counting. The early-renew path goes:
```
$payment_result === 'manual' → status 'manual' → return early (no handle_renewal_success)
```
So manual early renew does NOT call `handle_renewal_success` — the schedule shift is deferred to manual payment confirmation via `on_order_status_changed`. ✅ The original concern was unfounded; the path is actually correct.
**However**, there is a **real defect** with the "early renew" customer flow:
The `customer_renew` REST endpoint at [SubscriptionsController.php:407-434](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/includes/Api/SubscriptionsController.php#L407-L434) calls `SubscriptionManager::renew()` which creates a renewal order, then redirects the customer to `/order-pay/{id}`. Once they pay, the renewal is treated as a normal renewal, so:
- If the customer pays the early renewal order, `next_payment_date` is set to `current + 1 month` (via the conditional above), giving them **two paid periods back-to-back** with the next charge 1 month from "now" (which is the early renew date) — this is the **expected** SaaS behavior.
- BUT the customer is *not informed* anywhere in the UI that paying early **moves their next billing date forward** by the early amount. The order-pay page ([OrderPay/index.tsx](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/customer-spa/src/pages/OrderPay/index.tsx)) only shows the static `SubscriptionTimeline` snapshot, not what the new next date will be.
**Severity: 🔴 Critical — UX expectation violation.** Even if the math is right, customers will be surprised and request refunds.
**Fix:** Show the *projected* next billing date on the order-pay page when the order is a renewal. Compute it client-side as `next_payment_date` if in future, else `now + period`.
---
### C2. Removed — was a misframed finding
**Status: Withdrawn on review.** This finding is not a subscription-module defect in the current state of the system.
The original C2 argued that the renewal `set_address` from parent ([SubscriptionManager.php:609-614](file:///Users/dwindown/Local%20Sites/woonoow/app/public/wp-content/plugins/woonoow/includes/Modules/Subscription/SubscriptionManager.php#L609-L614)) silently copies a stale address. On review, that framing was wrong.
**What the system actually does today:**
- The checkout does not ask for an address. Every order is created without one.
- For **virtual / downloadable** subscription products: no address is needed. The renewal `set_address` call writes an empty/default address, but no shipping line is generated, no merchant ever sees an issue, and the customer never interacts with an address. ✅ Correct by virtue of the product type.
- For **physical** subscription products: physical subscriptions **cannot be sold** through the current checkout, because the checkout never asks for a shipping address. The renewal `set_address` code is **unreachable** for physical subscriptions in the current state.
**What the renewal flow should do once the checkout supports physical subscriptions:**
1. At the original order's checkout, the customer fills in the address. The parent order stores it.
2. On renewal, copy the address from the parent order to the renewal order. This is the correct default — the customer chose to renew, and the parent order is the most recent customer-confirmed address.
3. On the renewal order-pay page, surface the address with a clear "Is your address still the same? [Change]" prompt. The customer can correct it before paying.
4. If the customer changes the address on the renewal, persist the change to the renewal order. (Optional: also write it back to the parent order or to the customer's default address, but that is a checkout-level concern, not subscription-level.)
**Why this is not a defect today:**
- The renewal `set_address` from parent is not "wrong" — it is the only sensible default in the absence of a current customer-confirmed address on the renewal. Pulling from `WC_Customer::get_default_address()` would actually be **worse** in the renewal context: the customer may not have a default address, and the parent order is by definition the most recent address the customer provided for *this* subscription.
- The "stale address" risk on renewal is real but is already handled by the natural UX: the customer sees the address on the order-pay page and can change it before paying. This is the same trust model as checkout itself.
**What to do with this finding:**
- Remove C2 from the critical list.
- Keep the existing `set_address` code unchanged.
- File a **forward-looking note** in `docs/SUBSCRIPTION_ADDRESS_POLICY.md` (to be written when the checkout address step is added) describing the contract: parent-order address is the default; customer can change on the renewal order-pay page; physical products require the checkout to collect an address in the first place.
- The only subscription-side code change that may be useful when the checkout supports physical products: surface the address on the renewal order-pay page with the "is your address still the same?" prompt. That is a UX change, not a backend defect fix.
**The address question is the checkout's responsibility, not the subscription module's.** The subscription module's `create_renewal_order` is doing the right thing — copying from the parent, which is the only signal it has.
---
### C3. Resolved — was a false alarm (settings page IS implemented)
**Status: Resolved on re-verification (2026-06-01).** The original C3 finding stated there was no Settings page for the subscription module. That claim is wrong.
**What is actually implemented today:**
- **Generic page exists:** [admin-spa/src/routes/Settings/ModuleSettings.tsx](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/admin-spa/src/routes/Settings/ModuleSettings.tsx) handles ANY module with a schema. It is mounted at `/settings/modules/:moduleId` in `AppRoutes.tsx:230`.
- **Hook exists:** [admin-spa/src/hooks/useModuleSettings.ts](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/admin-spa/src/hooks/useModuleSettings.ts) reads `/modules/{id}/settings` and posts to `/modules/{id}/settings`.
- **Schema endpoint exists:** `ModuleSettingsController::get_schema` (registers `GET /woonoow/v1/modules/{module_id}/schema` at [ModuleSettingsController.php:67-71](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/includes/Api/ModuleSettingsController.php#L67-L71)) serves the schema registered via the `woonoow/module_settings_schema` filter.
- **Form renderer exists:** `SchemaForm` renders text / number / toggle / select fields from the schema declaratively.
- **Schema is registered:** [SubscriptionSettings.php:18](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/includes/Modules/SubscriptionSettings.php#L18) registers the filter; [SubscriptionModule.php:25](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/includes/Modules/Subscription/SubscriptionModule.php#L25) calls `SubscriptionSettings::init()` on bootstrap.
**What the merchant sees:** navigate to Settings → Modules → Subscription, and all 11 fields (`default_status`, `button_text_subscribe`, `button_text_renew`, `allow_customer_cancel`, `allow_customer_pause`, `max_pause_count`, `renewal_retry_enabled`, `renewal_retry_days`, `expire_after_failed_attempts`, `send_renewal_reminder`, `reminder_days_before`) are visible, editable, and persisted.
**Why this finding is wrong:** the original audit looked for a per-module page (`Settings/Subscription.tsx`) and didn't find one. But the system uses a *generic* schema-driven page that works for any module — including the subscription module. The capability is there; the audit missed it.
**Lesson for future audits:** the per-module page pattern is no longer the convention. Look for `ModuleSettings.tsx` + `SchemaForm` + `/modules/{id}/schema` first.
---
## 4. High-Impact UX/Data Issues (🟠)
### H1. "Renew Now" admin button does not consider gateway availability
**File:** [admin-spa/src/routes/Subscriptions/Detail.tsx:228-237](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/admin-spa/src/routes/Subscriptions/Detail.tsx#L228-L237)
The admin "Renew Now" button always calls `SubscriptionManager::renew()` which falls through to manual payment if no auto-debit gateway. The admin is not shown a confirmation that the renewal will produce a *pending* order requiring customer payment. They will click the button, see "Renewed" (because `handle_renewal_success` was called on auto-debit success OR no clear feedback on manual), and not realize the customer now has a pending order to pay.
**Fix:** After clicking "Renew Now", show the resulting order's payment URL / status to the admin.
---
### H2. Customer detail: "Times Paused" displayed but `max_pause_count` is not shown, and no warning when reached
**File:** [customer-spa/src/pages/Account/SubscriptionDetail.tsx:257-259](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/customer-spa/src/pages/Account/SubscriptionDetail.tsx#L257-L259)
The customer can see they've paused N times, but not how many pauses they have left. When the limit is hit, the API returns a generic 500 `pause_failed` — the customer sees a confusing error. The button should be **disabled** with a tooltip when the limit is reached.
**Fix:** Add `max_pause_count` and `pauses_remaining` to the enriched response; show on the detail page; disable button when 0 remaining.
---
### H3. `on-hold` subscription can be "renewed" creating a duplicate order
**File:** [SubscriptionManager.php:512-533](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/includes/Modules/Subscription/SubscriptionManager.php#L512-L533)
The duplicate prevention check uses `p.post_status IN ('wc-pending', 'pending', 'wc-on-hold', 'on-hold')`. But `failed` and `wc-failed` orders are *not* excluded — and the prior failed order still counts as a "renewal" link. The customer detail page (line 137-140) looks for `pending`, `wc-pending`, `on-hold`, `wc-on-hold`, `failed`, `wc-failed` to surface the "Pay Now" button — but the backend `renew()` only prevents duplicates for pending/on-hold. If a customer's renewal order failed last night, and they click "Renew Early" today, a *second* order is created.
**Severity: 🟠 High** — duplicate orders on retry, leading to confused customers and double-billing risk.
**Fix:** Add `'wc-failed', 'failed'` to the duplicate-prevention IN clause.
---
### H4. Renewal order product line uses the *current* product price, not the subscription's stored recurring amount
**File:** [SubscriptionManager.php:600-606](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/includes/Modules/Subscription/SubscriptionManager.php#L600-L606)
```php
$product = wc_get_product($subscription->variation_id ?: $subscription->product_id);
if ($product) {
$renewal_order->add_product($product, 1, [
'total' => $subscription->recurring_amount, // ✅ uses stored amount
'subtotal' => $subscription->recurring_amount,
]);
}
```
This *is* correct — it uses the stored `recurring_amount`, not the current product price. ✅
**However**, `recalculate_next_payment_date` does not consider **product-level price changes mid-cycle**. The customer's stored `recurring_amount` is the original price. If the admin changes the product price, the customer is grandfathered — which is probably intended, but **not documented in any setting**. No toggle to "re-sync with product price" or "always bill current price."
**Severity: 🟠 High (UX clarity)** — admin changes the product price and the next renewal silently uses the old price; surprised admin.
**Fix:** Add a setting `price_sync_on_renewal` with options: 'use_stored' (default), 'use_current_product_price'. Document in product meta tooltip.
---
### H5. Manual renewal email is sent on every cron tick, not gated by `pending` order existence
**File:** [SubscriptionManager.php:684-689](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/includes/Modules/Subscription/SubscriptionManager.php#L684-L689)
When a renewal returns `'manual'`, the system fires `woonoow/subscription/renewal_payment_due` once per call. If the same due subscription is processed again (e.g., a future hourly tick after `next_payment_date` falls behind), and there's still a pending order, the same notification fires again, **because `process_renewal_payment` doesn't check for an existing pending order first** — `renew()` does (line 521-533), but that's before the existing-pending check returns `'existing'` status.
Wait — re-reading: `renew()` returns the existing order for `'existing'` status and does **not** call `process_renewal_payment` or fire the notification. ✅ So this is actually safe.
**However**, if a `manual` renewal was created and never paid, the next cron tick sees the subscription as `on-hold` (not `active`) — so `get_due_renewals()` excludes it. The customer gets no reminder that they have an outstanding order. The `pending-cancel` path is similar — when `next_payment_date <= now`, `check_expirations` flips it to `cancelled`, but no email is queued with a "your pending order was cancelled" notice.
**Severity: 🟠 High (revenue leakage)** — abandoned-cart-like behavior on unpaid renewals.
**Fix:** Add a daily cron that finds `on-hold` subscriptions with pending renewal orders older than 24h and re-sends the `renewal_payment_due` email (or auto-cancels after N days).
---
### H6. `create_from_order` rejects guest orders silently
**File:** [SubscriptionManager.php:107-110](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/includes/Modules/Subscription/SubscriptionManager.php#L107-L110)
```php
if (!$user_id) {
// Guest orders not supported for subscriptions
return false;
}
```
But the **product page still shows "Subscribe Now"** to guests, who can complete checkout as guest, after which **no subscription is created and no error is shown**. The customer thinks they have a subscription, the order is normal.
**Severity: 🟠 High — broken expectation for guest purchases.** The "Subscribe" button should be hidden for guests, or guest checkout should be blocked for subscription products, or the customer should be auto-converted to a user.
**Fix:** Add a check in the `subscription_add_to_cart_text` filter to *not* change button text for guest users, or force a login redirect for subscription products in cart.
---
## 5. Medium Gaps (🟡)
### M1. Variable products: subscription meta is on parent only
**File:** [SubscriptionModule.php:120-177](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/includes/Modules/Subscription/SubscriptionModule.php#L120-L177)
The admin SPA form ([GeneralTab.tsx:546-630](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/admin-spa/src/routes/Products/partials/tabs/GeneralTab.tsx#L546-L630)) saves `_woonoow_subscription_*` on the parent product. When `create_from_order` is called, it reads:
```php
$billing_period = get_post_meta($product_id, '_woonoow_subscription_period', true) ?: 'month';
```
This is the *parent* product ID, not the variation. All variations of a variable subscription product share the same period. The admin cannot have e.g. "Small = monthly, Large = yearly" or "License 1-year vs 5-year" as variations.
**Fix:** Add variation-level meta overrides; `create_from_order` should look up variation meta first, then fall back to parent.
---
### M2. `customer_renew` endpoint has no `force_immediate` flag for ad-hoc admin actions
**File:** [SubscriptionsController.php:407-434](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/includes/Api/SubscriptionsController.php#L407-L434)
The customer "early renew" creates a new order. The admin "Renew Now" does the same. Neither can be used to **trigger an immediate charge against the customer's saved payment method** (i.e., a real "charge now and renew" button). The current behavior is "create a new order that the customer then pays manually" — confusing.
**Fix:** Add `?charge_now=true` param to admin renew that calls `process_renewal_payment` with `force = true`, skips the manual fallback.
---
### M3. No bulk actions on admin subscription list
**File:** [admin-spa/src/routes/Subscriptions/index.tsx:158-176](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/admin-spa/src/routes/Subscriptions/index.tsx#L158-L176)
The list page has a checkbox column with `selectedIds` state — but **the checkboxes don't trigger any bulk action**. There's no bulk cancel, bulk export (CSV), or bulk remind button. The select-all UI is dead.
**Fix:** Add a bulk-action toolbar (e.g., "Cancel selected", "Send renewal reminder", "Export CSV") and a corresponding REST endpoint.
---
### M4. No search field on admin list
**File:** [admin-spa/src/routes/Subscriptions/index.tsx](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/admin-spa/src/routes/Subscriptions/index.tsx)
The `SubscriptionManager::get_all` accepts a `search` parameter ([SubscriptionManager.php:282](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/includes/Modules/Subscription/SubscriptionManager.php#L282)) — but the admin list never passes it. With hundreds of subscriptions, an admin cannot search by customer name/email/product.
**Fix:** Wire the search input (currently missing) to the `search` query param.
---
## 6. Low / Opportunities (🔵)
### O1. Notification variables: missing `payment_method_title`, `billing_schedule`, `customer_id`
**File:** [TemplateProvider.php:328-345](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/includes/Core/Notifications/TemplateProvider.php#L328-L345)
The schema lists variables, but **the `EmailRenderer` mapping at lines 343-353** does not include:
- `payment_method_title` (customer-facing)
- `billing_schedule` (e.g., "Every 1 month")
- `customer_id` (admin-facing)
- `store_email` (declared in schema but not mapped)
- `my_account_url` (declared in schema but not mapped)
**Fix:** Add these to the `EmailRenderer` mapping so email templates can use them.
---
### O2. Two `.bak.php` files in production code path
**File:** [TemplateProvider.bak.php](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/includes/Core/Notifications/TemplateProvider.bak.php)
The `.bak` file is in the `Notifications/` directory — depending on autoloader, this may be auto-loaded or skipped. The subscription variables in the `.bak` (line 339-348) reference different keys than the live one. Should be removed or moved to `tests/fixtures/`.
**Fix:** Delete or relocate.
---
## 7. UI/UX Observations (not classified as defects)
| Observation | Location |
|---|---|
| Status badge uses `bg-amber-100` for `pending` in admin, `bg-yellow-100` in customer — inconsistent. | admin/customer SPAs |
| Mobile card view (admin) shows product name truncated without a "view product" link. | Subscriptions/index.tsx:300-321 |
| `SubscriptionTimeline` component has hard-coded English labels (`Started`, `Payment Due`, `Every X months`) — no `__()` calls. Breaks i18n for the 2 languages supported per `I18N_IMPLEMENTATION_GUIDE.md`. | SubscriptionTimeline.tsx |
| Customer detail page has no SEO head except `<SEOHead title="Subscription #X">` — OK but no `og:image` from `product_image`. | SubscriptionDetail.tsx:164 |
| Admin "Renew Now" doesn't ask for confirmation, but "Cancel" does. | Subscriptions/Detail.tsx:228-247 |
| `failed_payment_count` is shown in admin detail (good), but not in the customer detail — they don't know they have a retry coming. | admin vs customer |
| `last_payment_date` is shown in admin only, not customer. | admin vs customer |
| Order pay page always shows `Loading order details...` if `key` is missing — no helpful 403. | OrderPay/index.tsx:133 |
---
## 8. Cron Behavior Audit
| Hook | Schedule | Purpose | Issues |
|---|---|---|---|
| `woonoow_process_subscription_renewals` | hourly | Auto-process due renewals | No batch limit; no admin notice on failure; no lock guard against overlapping runs |
| `woonoow_check_expired_subscriptions` | daily | Mark end-date-reached as `expired`; finalize `pending-cancel` | No email to customer when their pending-cancel finally cancels |
| `woonoow_send_renewal_reminders` | daily | Send reminder N days before `next_payment_date` | Uses `last_payment_date` to gate, but `last_payment_date` only updates on **success** — if all retries fail, the gate fails open and may re-send for the same cycle |
**Cron-related risks:**
1. **No `wp_remote_get` lock** to prevent concurrent runs (WP-Cron can double-fire on slow sites).
2. **`send_renewal_reminders`** query at [SubscriptionScheduler.php:183-192](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/includes/Modules/Subscription/SubscriptionScheduler.php#L183-L192) uses a complex OR clause that may not be correct when `last_payment_date` IS NULL (initial trial): the `(last_payment_date IS NULL AND reminder_sent_at < start_date)` branch. New trial subscriptions may get reminders *before* trial ends.
3. **`schedule_retry`** at line 246-262 updates `next_payment_date` to the retry date — but the `get_due_renewals()` query compares `next_payment_date <= now`, so the retried subscription will be picked up on the next hourly tick. ✅
---
## 9. Payment Gateway Integration — Revised Direction (per-gateway capability)
> **Status as of 2026-06-01 (re-verified):** this section is **still aspirational**. No code, no schema, no settings entry, no UI, no capability helper exists. Zero references to `subscription_auto_renew`, `GatewayCapabilities`, `gateway_capability`, or `woonoow_gateway_subscription_capabilities` were found anywhere in the plugin. The current system still relies entirely on `method_exists($gateway, 'process_subscription_renewal_payment')` PHP introspection at `SubscriptionManager.php:667-674`.
>
> However, **the settings infrastructure to build this is now in place** (see C3 resolution): a generic `ModuleSettings` page reads a registered schema and persists via `/modules/{id}/settings`. §9 can be built on that same pattern, which is why this is still the most important long-term fix — but it is a feature to build, not a bug to remove.
### 9.1 Current state (problem)
The current code at [SubscriptionManager.php:667-674](file:///Users/dwindown/Local%20Sites/woonoow/app/public/wp-content/plugins/woonoow/includes/Modules/Subscription/SubscriptionManager.php#L667-L674) detects auto-debit capability via PHP introspection:
```php
if (method_exists($gateway, 'process_subscription_renewal_payment')) {
$result = $gateway->process_subscription_renewal_payment($order, $subscription);
...
}
```
This has three problems:
1. **Capability is invisible to the merchant.** The admin has no way to see which gateways are declared to support subscription auto-renew, no way to override that declaration, and no way to know that "Stripe is enabled" does not mean "Stripe will charge renewals."
2. **The default is unsafe.** A gateway without the method silently falls through to manual payment. The system "works," but the merchant believes auto-debit is happening and customers are surprised.
3. **No per-gateway override is possible.** A merchant who has a custom Stripe wrapper that *does* support auto-debit cannot declare it; a merchant using stock Stripe with no wrapper cannot override the assumption that it works.
### 9.2 Recommended direction: per-gateway capability declaration
Instead of inferring capability from PHP method existence, store a **gateway capability table** that the merchant (or WooNooW defaults) controls explicitly. The system then computes effective behavior at renewal time.
#### Shape of the declaration
A per-gateway record, with safe defaults:
```php
// Conceptual. Storage could be wp_option, custom table, or gateway registration API.
$capabilities = [
'paypal' => ['subscription_auto_renew' => true],
'stripe' => ['subscription_auto_renew' => true], // only with WooNooW Stripe adapter
'dodo' => ['subscription_auto_renew' => true], // only with WooNooW Dodo adapter
'tripay' => ['subscription_auto_renew' => false], // VA/QRIS — no recurring
'midtrans' => ['subscription_auto_renew' => false], // VA/QRIS/e-wallet — no recurring
'xendit' => ['subscription_auto_renew' => false], // even CC re-auth required
];
```
**Default for any unknown gateway: `false`.** This is the safe default — Indonesian-style and global-style gateways without a WooNooW adapter are treated as manual-renewal-only.
#### Why per-gateway, not a site-level "billing mode" toggle
A site-level "manual vs auto" toggle asks the merchant to understand a concept ("billing mode") that does not actually exist in their head. The merchant thinks in terms of **payment gateways**. A checkbox next to each gateway in WooCommerce → Settings → Payments is data the merchant already knows.
Additionally:
- Different merchants use different gateways. A site-level toggle forces a single behavior even when the merchant runs two gateways (one auto-capable, one not) for different products.
- The capability is a property of the **integration**, not of the **store**. The merchant did not choose "manual mode" — they chose Tripay, and Tripay is a manual gateway.
- The capability can change as WooNooW ships new adapters. A site-level toggle would be set once and forgotten; a per-gateway table updates as adapters ship.
#### What the system does with the declaration
At renewal time, the system checks: **the active gateway for this subscription** (stored in `payment_method`) has `subscription_auto_renew = true`.
- **Yes, supported** → attempt auto-debit via the gateway's `process_subscription_renewal_payment` (the contract is unchanged, just gated by a positive declaration). On success, `handle_renewal_success`. On failure, fall through to manual renewal and notify the customer.
- **No, not supported** → skip auto-debit, create a manual renewal order, send `renewal_payment_due` email. No silent failure.
If the gateway is unknown to the capability table, the default is `false` — same as explicit "not supported."
#### Optional site-level override (default off)
Add one secondary toggle for the rare merchant who wants to force manual even when the gateway supports auto (e.g., legal, regulatory, or business reasons):
- `force_manual_renewal`: off by default. When on, all renewals become manual regardless of gateway capability. Useful as a "kill switch."
This is **not** the primary control. It is an override.
### 9.3 What the merchant sees
In WooCommerce → Settings → Payments, each gateway row should show a "Supports subscription auto-renewal" indicator. For example:
| Gateway | Status |
|---|---|
| PayPal (WooCommerce addon) | ✅ Supports auto-renew |
| Stripe (WooCommerce addon) | ✅ Supports auto-renew |
| Dodo (WooCommerce addon) | ✅ Supports auto-renew |
| Tripay Payment (WooCommerce addon) | ❌ Manual renewal only |
| Midtrans (WooCommerce addon) | ❌ Manual renewal only |
| Xendit (WooCommerce addon) | ❌ Manual renewal only (even credit card) |
A gateway with no entry in the capability table shows ❌ by default and the merchant can flip it on if they have a custom adapter (advanced setting, off by default).
### 9.4 What the customer sees (on the order-pay page and renewal emails)
The renewal messaging must match the actual behavior, not the marketing claim:
- For an auto-renew gateway: "Your subscription will renew automatically on [date] using your saved payment method."
- For a manual gateway: "Your subscription is up for renewal. Please complete the payment to continue." with a clear CTA to pay.
- The order-pay page should also show the **next payment date** after this payment completes (the audit's C1 finding applies here too).
### 9.5 The Indonesian gateway reality
For Indonesian payment gateways (Tripay, Midtrans, Xendit, Doku, and the VA/QRIS/e-wallet channels of any gateway), the default `subscription_auto_renew` must be **`false`**. Specifically:
- VA (virtual account): no recurring charge capability.
- QRIS: typically a one-time merchant-presented QR, no customer-mandate.
- E-wallets (GoPay, OVO, DANA, ShopeePay): require customer re-authentication for each charge.
- Credit card on Indonesian gateways: even when the card is tokenized, recurring charges typically require the customer to re-authenticate (BI/PCI-DSS regulatory constraint). The merchant cannot assume the stored token can be charged without the customer's active consent.
If a merchant has a special integration (e.g., a specific subscription product on Xendit with a tokenized card and a recurring billing add-on), they can flip the toggle for that gateway. But the default must be manual.
### 9.6 Implementation outline (for the AI agent)
1. **Capability storage.** A new `wp_option('woonoow_gateway_subscription_capabilities', [...])` keyed by gateway ID, with the safe defaults above. Add a filter `woonoow_gateway_subscription_capabilities` so adapters can self-register.
2. **Capability lookup helper.** `WooNooW\Modules\Subscription\GatewayCapabilities::supports_auto_renew(string $gateway_id): bool` — single source of truth.
3. **Renewal flow integration.** In `SubscriptionManager::process_renewal_payment`, before checking `method_exists`, call the capability helper. If `false`, skip the auto-debit attempt entirely and go straight to manual.
4. **Admin UI.** Render the capability indicator in the gateway list (admin SPA) and on the subscription detail page next to "Payment Method" (e.g., "Stripe — auto-renew enabled" vs "Tripay — manual renewal only").
5. **Customer messaging.** Pass a boolean `gateway_supports_auto_renew` to the order-pay response and the renewal emails, so the UI can choose the right wording.
6. **Kill switch.** A single `force_manual_renewal` site setting. Default off.
7. **Documentation.** A new `docs/SUBSCRIPTION_GATEWAY_CAPABILITIES.md` listing the default capabilities and explaining how to add custom adapters.
### 9.7 Migration / no migration
This is a behavioral improvement, not a schema change. Existing subscriptions keep their `payment_method` value. The capability table is consulted at renewal time, not retroactively.
### 9.8 Recommendation (replaces prior "ship a Stripe adapter" suggestion)
Do **not** ship a Stripe adapter as a first-class example. The value of a generic example adapter is low because each gateway's recurring billing is different. Instead:
- Ship the **capability table** with safe defaults.
- Ship a **gateway-integration guide** (`docs/SUBSCRIPTION_GATEWAY_CAPABILITIES.md`) that documents the `process_subscription_renewal_payment` contract.
- Let third-party gateway authors (or the merchant's developer) implement adapters per gateway.
- The merchant-visible UX works correctly for any gateway, supported or not, because the fallback to manual is explicit.
---
## 10. Cross-Module Integration
### Licensing
- `LicenseManager::validate_license` calls `get_order_subscription_status($license['order_id'])` at line 340-343 — if the subscription is not `active` or `pending-cancel`, the license is rejected with `subscription_inactive`.
- ✅ Works correctly; the licensing flow depends on the subscription status being accurate.
- ⚠️ But: when a subscription is **cancelled by customer at period end** (pending-cancel → cancelled), the license is still valid until the cancellation date. This is good UX, but admin should be able to see the relationship in the license detail.
### Affiliate
- No integration. An affiliate who referred a customer who later subscribes does **not** receive renewal commissions. The `subscription_renewal` order is not tagged with the referral.
- This is a known gap (Affiliate Module report doesn't mention subscriptions).
---
## 11. Documentation Drift
| File | Says | Reality |
|---|---|---|
| [FEATURE_ROADMAP.md:299-363](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/FEATURE_ROADMAP.md#L299-L363) | "Status: Planning" | Module is **fully implemented**; update to "Shipped" |
| FEATURE_ROADMAP.md lists `customer_id` column | actually `user_id` in schema | Drift |
| `.agent/plans/subscription-module.md` | Original design | Now stale (e.g., `reminder_sent_at` was added later) |
---
## 12. Test Coverage
**No subscription-specific tests** found in [tests/](file:///Users/dwindown/Local Sites/woonoow/app/public/wp-content/plugins/woonoow/tests/). Only generic schema/parity/page tests exist. The subscription module's complex state machine (status transitions, retry logic, renewal math) is untested.
**Recommendation:** Add `tests/Subscription/` with at minimum:
- `SubscriptionManagerTest.php`: state machine coverage (pending → active → on-hold → resumed, etc.)
- `SubscriptionSchedulerTest.php`: cron logic with frozen time
- `SubscriptionsControllerTest.php`: REST endpoint auth and validation
- `e2e/subscription-checkout.test.ts`: full buy → renew → cancel flow
---
## 13. Recommended Fix Priority
| # | Issue | Severity | Effort | Priority |
|---|---|---|---|---|
| 1 | C1 — Early renew UX clarity (show projected next-payment-date on order-pay page) | 🔴 | S | **P0 — this week** |
| 2 | H3 — Failed orders bypass dedup (add `'wc-failed', 'failed'` to IN clause at `SubscriptionManager.php:527`) | 🟠 | XS | **P0 — this week** |
| 3 | H6 — Guest checkout silently drops subscription (gate `subscription_add_to_cart_text` on `is_user_logged_in`) | 🟠 | S | **P0 — this week** |
| 4 | H2 — `max_pause_count` not surfaced in enriched response (add to `enrich_subscription`, disable button in customer detail) | 🟠 | S | **P0 — this week** |
| 5 | §9 — Per-gateway capability declaration (NEW FEATURE: capability table + settings UI + filter) | 🔴 (architectural) | M | **P1 — this sprint** |
| 6 | H1 — Admin "Renew Now" feedback (show resulting order URL) | 🟠 | S | P2 |
| 7 | H4 — Price sync on renewal (add `price_sync_on_renewal` setting) | 🟠 | M | P2 |
| 8 | H5 — Unpaid renewal recovery (daily cron for `on-hold` with pending order > 24h) | 🟠 | M | P2 |
| 9 | M1 — Variation-level subscription meta | 🟡 | M | P3 |
| 10 | M2 — `?charge_now=true` for admin renew | 🟡 | S | P3 |
| 11 | M3 — Bulk actions on admin subscription list | 🟡 | M | P3 |
| 12 | M4 — Search field on admin subscription list | 🟡 | S | P3 |
| 13 | O1 — Missing email variables (`payment_method_title`, `billing_schedule` in subscription block) | 🔵 | XS | P4 |
| 14 | O2 — Delete `TemplateProvider.bak.php` | 🔵 | XS | P4 |
| 15 | Doc drift — `FEATURE_ROADMAP.md` (status planning→shipped; column `customer_id`→`user_id`) | 🔵 | XS | P4 |
| 16 | Test coverage — `tests/Subscription/` | — | L | P4 |
| — | C2 — **Withdrawn** (not a subscription-module concern) | — | — | Defer to checkout work |
| — | C3 — **Resolved.** Settings page is implemented (generic schema-driven). | — | — | Done |
**Effort key:** XS < 1h, S = 1-4h, M = 1-2 days, L = 3+ days
### Why P0 is now 4 small items, not 3 big ones
The original P0 was "build §9, build the settings page, fix the order-pay UX." The settings page is **done** — that work is reusable for §9. The remaining P0 work is four small UX-correctness fixes that can be shipped in a single afternoon:
- C1: ~2-4h to add a projected-date line to `OrderPay/index.tsx` (compute client-side from `subscription.billing_period`/`billing_interval`).
- H3: ~30min — add two strings to an IN clause.
- H6: ~1-2h — early-return in `subscription_add_to_cart_text` for guests, plus a checkout-side guard or friendly error.
- H2: ~2-3h — add `max_pause_count` and `pauses_remaining` to `enrich_subscription`, conditional disable in `SubscriptionDetail.tsx`.
§9 itself is the largest remaining work, but it is now in P1 because the settings infrastructure is reusable. §9.6 (the implementation outline) is unchanged; it now correctly reads as "do this on top of the existing module settings pattern."
### 10.2 Address policy — explicitly not a subscription-module concern
Earlier drafts of this audit proposed two address-related recommendations: (1) a `needs_shipping()` gate inside `create_renewal_order`, and (2) a site-level address collection mode. **Both are withdrawn.**
- The `needs_shipping()` gate is unnecessary. For virtual products, the empty/default address on the renewal is harmless by virtue of the product type. The existing code is already correct.
- A site-level address collection mode is the wrong layer. The address question is a **checkout-level** concern. Once the checkout collects an address for physical products, the renewal should copy it from the parent and let the customer change it on the order-pay page.
**What the subscription module should do today:** nothing. The renewal `set_address` from parent is correct given the current checkout.
**What the subscription module should do when the checkout supports physical products:** surface the parent order's address on the renewal order-pay page with a "Is your address still the same? [Change]" prompt. This is a UX change, not a backend defect fix.
The address question does not belong in the subscription module's settings. It belongs in the checkout.
---
## 14. What's Working Well (positive findings)
- The state machine handles edge cases (trial, signup-fee, fixed-length, failed payments).
- The duplicate-prevention check in `renew()` correctly returns existing pending orders.
- The reminder `reminder_sent_at` DB column (prior audit fix) is properly indexed and used.
- `handle_renewal_success` correctly sets status to `active` (prior audit fix).
- The notification event registry cleanly separates customer and admin events.
- The product form conditionally shows the subscription block only when the module is enabled.
- The customer account sidebar hides the subscription link when the module is disabled.
- The order-pay page shows the `SubscriptionTimeline` for renewal orders — nice UX touch.
- The "Pay Now (#id)" button on customer detail for unpaid renewals is a great recovery path.
- Hooks are well-named and consistent (`woonoow/subscription/<event>`).
- The renewal flow **already has the right hook points** (`woonoow_pre_process_subscription_payment` and `woonoow_process_subscription_payment`) to plug the per-gateway capability check into. No architectural rewrite needed.
---
## 15. Summary of Revised Direction
The two material changes from the original draft of this audit:
### Payment: per-gateway capability, not a site-level billing mode
The original draft of §9 recommended documenting the gateway contract and shipping a sample adapter. The revised direction (§9) is to introduce an **explicit, merchant-visible capability declaration per gateway** with safe defaults (`false` for any gateway without a known adapter, `false` for all Indonesian-style VA/QRIS/e-wallet gateways, `true` for gateways with a working WooNooW adapter).
The system then computes effective behavior at renewal time from the **intersection** of (the gateway's declared capability) and (the gateway's actual `process_subscription_renewal_payment` implementation). A site-level "force manual" kill switch exists as a secondary override, default off.
The merchant thinks in payment gateways, not in "billing modes." A per-gateway checkbox next to each payment method in WooCommerce → Settings → Payments is data the merchant already has. A site-level toggle is a concept they have to learn.
### Address: not a subscription-module concern
**Withdrawn entirely.** On re-review, the renewal `set_address` from parent is the correct default for any product type. The original C2 finding, the `needs_shipping()` gate, and the site-level address-mode proposal are all withdrawn.
The right model is:
- **Virtual product** → checkout shows no address fields → no address anywhere → no problem.
- **Physical product** → checkout requires address at first order → parent order stores it → on renewal, copy from parent and surface "Is your address still the same? [Change]" on the order-pay page.
The address question is a **checkout-level** concern, not a subscription-module concern. The subscription module's `create_renewal_order` is doing the right thing — copying from the parent, which is the only signal it has. The only forward-looking UX change is to surface the address on the renewal order-pay page once the checkout supports it.
### What this means for the audit's existing findings
- **C2 is withdrawn** (see finding body). The renewal `set_address` is correct.
- **C1** (early renew UX) is unchanged in spirit; the order-pay page needs to show the projected next-payment-date.
- **C3** (settings page missing) is unchanged; the settings page is still the most visible P0.
- **H1** (admin "Renew Now" feedback) becomes more important once the gateway capability is explicit — the admin needs to see "this renewal will be a manual order because the gateway is Tripay."
---
## 16. Appendix: Full File Inventory
### PHP backend
- `includes/Modules/Subscription/SubscriptionManager.php` (894 lines)
- `includes/Modules/Subscription/SubscriptionModule.php` (564 lines)
- `includes/Modules/Subscription/SubscriptionScheduler.php` (264 lines)
- `includes/Modules/SubscriptionSettings.php` (110 lines)
- `includes/Api/SubscriptionsController.php` (502 lines)
- `includes/Api/ModuleSettingsController.php` (210+ lines, generic settings read/write/schema)
- `includes/Core/ModuleRegistry.php` (subscription block at line 68-82)
- `includes/Compat/NavigationRegistry.php` (lines 262-284)
- `includes/Core/Notifications/EmailRenderer.php` (lines 339-376)
- `includes/Core/Notifications/TemplateProvider.php` (lines 240-345)
- `includes/Core/Notifications/TemplateProvider.bak.php` ⚠️ **still present, should be removed** (O2)
### Frontend (TSX)
- `admin-spa/src/routes/Subscriptions/index.tsx` (505 lines)
- `admin-spa/src/routes/Subscriptions/Detail.tsx` (456 lines)
- `admin-spa/src/routes/Orders/Detail.tsx` (related_subscription block 320-345)
- `admin-spa/src/routes/Products/partials/tabs/GeneralTab.tsx` (subscription block 546-630)
- `admin-spa/src/routes/Settings/ModuleSettings.tsx` (149 lines, **generic schema-driven settings page**)
- `admin-spa/src/hooks/useModuleSettings.ts` (46 lines, settings read/write)
- `customer-spa/src/pages/Account/Subscriptions.tsx` (244 lines)
- `customer-spa/src/pages/Account/SubscriptionDetail.tsx` (377 lines)
- `customer-spa/src/components/SubscriptionTimeline.tsx` (86 lines)
- `customer-spa/src/pages/OrderPay/index.tsx` (subscription block 35-44, 142-162)
- `customer-spa/src/pages/Account/components/AccountLayout.tsx` (line 53, 66)
### Docs
- `.agent/reports/subscription-flow-audit-2026-01-29.md` (prior audit)
- `.agent/plans/subscription-module.md` (original design)
- `FEATURE_ROADMAP.md` (stale)
- `HOOKS_REGISTRY.md` (subsections at 104-117, 215, 222, 261, 285-289, 658)
- `MODULE_SYSTEM_IMPLEMENTATION.md`
---
## 17. Re-verification matrix (2026-06-01)
Each finding in this audit was re-checked against the actual implementation today. The table is the source of truth for "documented vs. implemented."
| # | Finding | Original severity | Re-verified status | Notes |
|---|---|---|---|---|
| C1 | Early-renew UX lacks projected next-payment-date | 🔴 | ✅ **Confirmed** | `OrderPay/index.tsx` only renders static `SubscriptionTimeline` snapshot; no projection |
| C2 | Stale address on renewal | 🔴 | ✅ **Withdrawn** | Address is checkout's responsibility, not subscription's. Already resolved in this document. |
| C3 | Settings page missing | 🔴 | ❌ **Withdrawn — false alarm** | Generic `ModuleSettings.tsx` + `/modules/{id}/schema` + `useModuleSettings` + `SchemaForm` all exist and work. See C3 resolution section. |
| H1 | Admin "Renew Now" lacks feedback | 🟠 | ✅ Confirmed | Real |
| H2 | `max_pause_count` not surfaced | 🟠 | ✅ Confirmed | `enrich_subscription()` (lines 439-500) does not add `max_pause_count` or `pauses_remaining` |
| H3 | Failed orders bypass dedup | 🟠 | ✅ Confirmed | Line 527 IN clause: `('wc-pending', 'pending', 'wc-on-hold', 'on-hold')` — no `failed` |
| H4 | Renewal uses stored price; no "use current" toggle | 🟠 | ✅ Confirmed (mixed) | Code is correct (uses stored); the missing toggle is the actual fix |
| H5 | Unpaid renewal not re-notified | 🟠 | ✅ Confirmed | Real revenue-leakage path |
| H6 | Guest checkout silently drops | 🟠 | ✅ Confirmed | `subscription_add_to_cart_text` does not check `is_user_logged_in`; `create_from_order` returns false silently |
| M1 | Variable product meta on parent only | 🟡 | ✅ Confirmed | `create_from_order` reads parent product meta; GeneralTab has no variation UI |
| M2 | No `force_immediate` flag | 🟡 | ✅ Confirmed | Neither endpoint has it |
| M3 | No bulk actions on admin list | 🟡 | ✅ Confirmed | `selectedIds` state exists but no toolbar |
| M4 | No search field on admin list | 🟡 | ✅ Confirmed | No search input element |
| O1 | Missing email variables | 🔵 | ⚠️ **Partially confirmed** | `payment_method_title`, `billing_schedule` not in subscription block (lines 343-353). `my_account_url` is mapped in a different branch. |
| O2 | `.bak.php` in production | 🔵 | ✅ Confirmed | `TemplateProvider.bak.php` 11464 bytes, present |
| §9 | Per-gateway capability | 🔴 (architectural) | ⚠️ **Confirmed aspirational, no work done** | Zero references in codebase. Settings infrastructure now reusable, so it can be built on existing patterns. |
---
**End of report.**

View File

@@ -1 +1,38 @@
export function ProductCard({ product }: any) { return <div className='p-4 border rounded shadow-sm'>{product?.title || 'Product'}</div>; } import React from 'react';
import { ShoppingCart } from 'lucide-react';
export function ProductCard({ product }: any) {
const name = product?.name || product?.title || 'Sample Product';
const price = product?.price || '$49.99';
const image = product?.image || product?.image_url || '';
return (
<div className="group h-full flex flex-col border border-border rounded-lg overflow-hidden hover:shadow-md transition-shadow bg-card">
<div className="relative w-full overflow-hidden bg-muted aspect-square">
{image ? (
<img src={image} alt={name} className="absolute inset-0 w-full !h-full object-cover object-center group-hover:scale-105 transition-transform duration-300" />
) : (
<div className="absolute inset-0 flex items-center justify-center text-muted-foreground text-sm font-medium">
No Image
</div>
)}
</div>
<div className="p-4 flex-1 flex flex-col text-left">
<h3 className="text-sm font-medium text-foreground mb-2 line-clamp-2 leading-snug group-hover:text-primary transition-colors">
{name}
</h3>
<div className="flex items-center gap-2 mb-3">
<span className="text-base font-bold text-foreground">
{price}
</span>
</div>
<button
className="w-full mt-auto inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 border border-input bg-background hover:bg-accent hover:text-accent-foreground h-10 px-4 py-2"
>
<ShoppingCart className="w-4 h-4 mr-2" />
Add to Cart
</button>
</div>
</div>
);
}

View File

@@ -0,0 +1,26 @@
import { SectionStyleResult } from '@/lib/sectionStyles';
interface SectionBackgroundRendererProps {
bg: SectionStyleResult;
}
export function SectionBackgroundRenderer({ bg }: SectionBackgroundRendererProps) {
if (!bg.backgroundImage) return null;
return (
<div className="absolute inset-0 pointer-events-none z-0">
<img
src={bg.backgroundImage}
alt=""
role="presentation"
className="w-full h-full object-cover"
/>
{bg.hasOverlay && (
<div
className="absolute inset-0 bg-black"
style={{ opacity: bg.overlayOpacity }}
/>
)}
</div>
);
}

View File

@@ -78,161 +78,79 @@ export const SharedContentLayout: React.FC<SharedContentProps> = ({
return ( return (
<div className={containerClasses}> <div className={containerClasses}>
{containerWidth === 'boxed' ? ( <div className={gridClasses}>
<div className="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden px-6 md:px-10 py-10"> {/* Image Side */}
<div className={gridClasses}> {hasImage && (
{/* Image Side */} <div className={cn(
{hasImage && ( 'relative w-full aspect-[4/3] rounded-2xl overflow-hidden shadow-lg',
<div className={cn( imageWrapperOrder,
'relative w-full aspect-[4/3] rounded-2xl overflow-hidden shadow-lg', (isImageTop || isImageBottom) && 'mb-8'
imageWrapperOrder, )} style={imageStyle}>
(isImageTop || isImageBottom) && 'mb-8' // spacing if stacked <img
)} style={imageStyle}> src={image}
<img alt={title || 'Section Image'}
src={image} className="absolute inset-0 w-full h-full object-cover"
alt={title || 'Section Image'} />
className="absolute inset-0 w-full h-full object-cover"
/>
</div>
)}
{/* Content Side */}
<div className={cn('flex flex-col', hasImage ? 'bg-transparent' : '')}>
{title && (
<h2
className={cn(
"tracking-tight text-current mb-6",
!titleClassName && "text-3xl font-bold sm:text-4xl lg:text-5xl",
titleClassName
)}
style={titleStyle}
>
{title}
</h2>
)}
{text && (
<div
className={cn(
'prose prose-lg max-w-none',
'prose-h1:text-3xl md:prose-h1:text-4xl lg:prose-h1:text-5xl prose-h1:font-bold prose-h1:mt-6 prose-h1:mb-4',
'prose-h2:text-2xl md:prose-h2:text-3xl lg:prose-h2:text-4xl prose-h2:font-bold prose-h2:mt-5 prose-h2:mb-3',
'prose-h3:text-xl md:prose-h3:text-2xl lg:prose-h3:text-3xl prose-h3:font-bold prose-h3:mt-4 prose-h3:mb-2',
'prose-headings:text-[var(--tw-prose-headings)]',
'prose-p:text-[var(--tw-prose-body)]',
'text-[var(--tw-prose-body)]',
className,
textClassName
)}
style={proseStyle}
dangerouslySetInnerHTML={{ __html: text }}
/>
)}
{/* Buttons */}
{buttons && buttons.length > 0 && (
<div className="mt-8 flex flex-wrap gap-4">
{buttons.map((btn, idx) => (
btn.text && btn.url && (
<a
key={idx}
href={btn.url}
className={cn(
"inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 h-10 px-4 py-2",
!buttonStyle?.style?.backgroundColor && "bg-primary",
!buttonStyle?.style?.color && "text-primary-foreground hover:bg-primary/90",
buttonStyle?.classNames
)}
style={buttonStyle?.style}
>
{btn.text}
</a>
)
))}
</div>
)}
</div>
</div> </div>
</div> )}
) : (
<div className={gridClasses}> {/* Content Side */}
{/* Image Side */} <div className={cn('flex flex-col', hasImage ? 'bg-transparent' : '')}>
{hasImage && ( {title && (
<div className={cn( <h2
'relative w-full aspect-[4/3] rounded-2xl overflow-hidden shadow-lg', className={cn(
imageWrapperOrder, "tracking-tight text-current mb-6",
(isImageTop || isImageBottom) && 'mb-8' !titleClassName && "text-3xl font-bold sm:text-4xl lg:text-5xl",
)} style={imageStyle}> titleClassName
<img )}
src={image} style={titleStyle}
alt={title || 'Section Image'} >
className="absolute inset-0 w-full h-full object-cover" {title}
/> </h2>
</div>
)} )}
{/* Content Side */} {text && (
<div className={cn('flex flex-col', hasImage ? 'bg-transparent' : '')}> <div
{title && ( className={cn(
<h2 'prose prose-lg max-w-none',
className={cn( 'prose-h1:text-3xl md:prose-h1:text-4xl lg:prose-h1:text-5xl prose-h1:font-bold prose-h1:mt-6 prose-h1:mb-4',
"tracking-tight text-current mb-6", 'prose-h2:text-2xl md:prose-h2:text-3xl lg:prose-h2:text-4xl prose-h2:font-bold prose-h2:mt-5 prose-h2:mb-3',
!titleClassName && "text-3xl font-bold sm:text-4xl lg:text-5xl", 'prose-h3:text-xl md:prose-h3:text-2xl lg:prose-h3:text-3xl prose-h3:font-bold prose-h3:mt-4 prose-h3:mb-2',
titleClassName 'prose-headings:text-[var(--tw-prose-headings)]',
)} 'prose-p:text-[var(--tw-prose-body)]',
style={titleStyle} 'text-[var(--tw-prose-body)]',
> className,
{title} textClassName
</h2> )}
)} style={proseStyle}
dangerouslySetInnerHTML={{ __html: text }}
/>
)}
{text && ( {/* Buttons */}
<div {buttons && buttons.length > 0 && (
className={cn( <div className="mt-8 flex flex-wrap gap-4">
'prose prose-lg max-w-none', {buttons.map((btn, idx) => (
'prose-h1:text-3xl md:prose-h1:text-4xl lg:prose-h1:text-5xl prose-h1:font-bold prose-h1:mt-6 prose-h1:mb-4', btn.text && btn.url && (
'prose-h2:text-2xl md:prose-h2:text-3xl lg:prose-h2:text-4xl prose-h2:font-bold prose-h2:mt-5 prose-h2:mb-3', <a
'prose-h3:text-xl md:prose-h3:text-2xl lg:prose-h3:text-3xl prose-h3:font-bold prose-h3:mt-4 prose-h3:mb-2', key={idx}
'prose-headings:text-[var(--tw-prose-headings)]', href={btn.url}
'prose-p:text-[var(--tw-prose-body)]', className={cn(
'text-[var(--tw-prose-body)]', "inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 h-10 px-4 py-2",
className, !buttonStyle?.style?.backgroundColor && "bg-primary",
textClassName !buttonStyle?.style?.color && "text-primary-foreground hover:bg-primary/90",
)} buttonStyle?.classNames
style={proseStyle} )}
dangerouslySetInnerHTML={{ __html: text }} style={buttonStyle?.style}
/> >
)} {btn.text}
</a>
{/* Buttons */} )
{buttons && buttons.length > 0 && ( ))}
<div className="mt-8 flex flex-wrap gap-4"> </div>
{buttons.map((btn, idx) => ( )}
btn.text && btn.url && (
<a
key={idx}
href={btn.url}
className={cn(
"inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 h-10 px-4 py-2",
!buttonStyle?.style?.backgroundColor && "bg-primary",
!buttonStyle?.style?.color && "text-primary-foreground hover:bg-primary/90",
buttonStyle?.classNames
)}
style={buttonStyle?.style}
>
{btn.text}
</a>
)
))}
</div>
)}
</div>
</div> </div>
)} </div>
</div> </div>
); );
}; };

View File

@@ -5,7 +5,6 @@ import Placeholder from '@tiptap/extension-placeholder';
import Link from '@tiptap/extension-link'; import Link from '@tiptap/extension-link';
import TextAlign from '@tiptap/extension-text-align'; import TextAlign from '@tiptap/extension-text-align';
import Image from '@tiptap/extension-image'; import Image from '@tiptap/extension-image';
import { ButtonExtension } from './tiptap-button-extension';
import { openWPMediaImage } from '@/lib/wp-media'; import { openWPMediaImage } from '@/lib/wp-media';
import { import {
Bold, Bold,
@@ -17,7 +16,6 @@ import {
AlignCenter, AlignCenter,
AlignRight, AlignRight,
ImageIcon, ImageIcon,
MousePointer,
Undo, Undo,
Redo, Redo,
} from 'lucide-react'; } from 'lucide-react';
@@ -50,8 +48,6 @@ export function RichTextEditor({
Placeholder.configure({ Placeholder.configure({
placeholder, placeholder,
}), }),
// ButtonExtension MUST come before Link to ensure buttons are parsed first
ButtonExtension,
Link.configure({ Link.configure({
openOnClick: false, openOnClick: false,
HTMLAttributes: { HTMLAttributes: {
@@ -109,13 +105,6 @@ export function RichTextEditor({
} }
}; };
const [buttonDialogOpen, setButtonDialogOpen] = useState(false);
const [buttonText, setButtonText] = useState('Click Here');
const [buttonHref, setButtonHref] = useState('{order_url}');
const [buttonStyle, setButtonStyle] = useState<'solid' | 'outline' | 'link'>('solid');
const [isEditingButton, setIsEditingButton] = useState(false);
const [editingButtonPos, setEditingButtonPos] = useState<number | null>(null);
const addImage = () => { const addImage = () => {
openWPMediaImage((file) => { openWPMediaImage((file) => {
editor.chain().focus().setImage({ editor.chain().focus().setImage({
@@ -126,87 +115,6 @@ export function RichTextEditor({
}); });
}; };
const openButtonDialog = () => {
setButtonText('Click Here');
setButtonHref('{order_url}');
setButtonStyle('solid');
setIsEditingButton(false);
setEditingButtonPos(null);
setButtonDialogOpen(true);
};
// Handle clicking on buttons in the editor to edit them
const handleEditorClick = (e: React.MouseEvent<HTMLDivElement>) => {
const target = e.target as HTMLElement;
const buttonEl = target.closest('a[data-button]') as HTMLElement | null;
if (buttonEl && editor) {
e.preventDefault();
e.stopPropagation();
// Get button attributes
const text = buttonEl.getAttribute('data-text') || buttonEl.textContent?.replace('🔘 ', '') || 'Click Here';
const href = buttonEl.getAttribute('data-href') || '#';
const style = (buttonEl.getAttribute('data-style') as 'solid' | 'outline') || 'solid';
// Find the position of this button node
const { state } = editor.view;
let foundPos: number | null = null;
state.doc.descendants((node, pos) => {
if (node.type.name === 'button' &&
node.attrs.text === text &&
node.attrs.href === href) {
foundPos = pos;
return false; // Stop iteration
}
return true;
});
// Open dialog in edit mode
setButtonText(text);
setButtonHref(href);
setButtonStyle(style);
setIsEditingButton(true);
setEditingButtonPos(foundPos);
setButtonDialogOpen(true);
}
};
const insertButton = () => {
if (isEditingButton && editingButtonPos !== null && editor) {
// Delete old button and insert new one at same position
editor
.chain()
.focus()
.deleteRange({ from: editingButtonPos, to: editingButtonPos + 1 })
.insertContentAt(editingButtonPos, {
type: 'button',
attrs: { text: buttonText, href: buttonHref, style: buttonStyle },
})
.run();
} else {
// Insert new button
editor.chain().focus().setButton({ text: buttonText, href: buttonHref, style: buttonStyle }).run();
}
setButtonDialogOpen(false);
setIsEditingButton(false);
setEditingButtonPos(null);
};
const deleteButton = () => {
if (editingButtonPos !== null && editor) {
editor
.chain()
.focus()
.deleteRange({ from: editingButtonPos, to: editingButtonPos + 1 })
.run();
setButtonDialogOpen(false);
setIsEditingButton(false);
setEditingButtonPos(null);
}
};
const getActiveHeading = () => { const getActiveHeading = () => {
if (editor.isActive('heading', { level: 1 })) return 'h1'; if (editor.isActive('heading', { level: 1 })) return 'h1';
if (editor.isActive('heading', { level: 2 })) return 'h2'; if (editor.isActive('heading', { level: 2 })) return 'h2';
@@ -326,14 +234,6 @@ export function RichTextEditor({
> >
<ImageIcon className="h-4 w-4" /> <ImageIcon className="h-4 w-4" />
</Button> </Button>
<Button
type="button"
variant="ghost"
size="sm"
onClick={openButtonDialog}
>
<MousePointer className="h-4 w-4" />
</Button>
<div className="w-px h-6 bg-border mx-1" /> <div className="w-px h-6 bg-border mx-1" />
<Button <Button
type="button" type="button"
@@ -356,7 +256,7 @@ export function RichTextEditor({
</div> </div>
{/* Editor */} {/* Editor */}
<div onClick={handleEditorClick}> <div>
<EditorContent editor={editor} /> <EditorContent editor={editor} />
</div> </div>
@@ -444,91 +344,6 @@ export function RichTextEditor({
</div> </div>
</details> </details>
)} )}
{/* Button Dialog */}
<Dialog open={buttonDialogOpen} onOpenChange={(open) => {
setButtonDialogOpen(open);
if (!open) {
setIsEditingButton(false);
setEditingButtonPos(null);
}
}}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>{isEditingButton ? __('Edit Button') : __('Insert Button')}</DialogTitle>
<DialogDescription>
{isEditingButton
? __('Edit the button properties below. Click on the button to save.')
: __('Add a styled button to your content. Use variables for dynamic links.')}
</DialogDescription>
</DialogHeader>
<DialogBody>
<div className="space-y-4 !p-4">
<div className="space-y-2">
<Label htmlFor="btn-text">{__('Button Text')}</Label>
<Input
id="btn-text"
value={buttonText}
onChange={(e) => setButtonText(e.target.value)}
placeholder={__('e.g., View Order')}
/>
</div>
<div className="space-y-2">
<Label htmlFor="btn-href">{__('Button Link')}</Label>
<Input
id="btn-href"
value={buttonHref}
onChange={(e) => setButtonHref(e.target.value)}
placeholder="{order_url}"
/>
{variables.length > 0 && (
<div className="flex flex-wrap gap-1 mt-2">
{variables.filter(v => v.includes('_url') || v.includes('_link')).map((variable) => (
<code
key={variable}
className="text-xs bg-muted px-2 py-1 rounded cursor-pointer hover:bg-muted/80"
onClick={() => setButtonHref(buttonHref + `{${variable}}`)}
>
{`{${variable}}`}
</code>
))}
</div>
)}
</div>
<div className="space-y-2">
<Label htmlFor="btn-style">{__('Button Style')}</Label>
<Select value={buttonStyle} onValueChange={(value: 'solid' | 'outline' | 'link') => setButtonStyle(value)}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="solid">{__('Solid (Primary)')}</SelectItem>
<SelectItem value="outline">{__('Outline (Secondary)')}</SelectItem>
<SelectItem value="link">{__('Plain Link')}</SelectItem>
</SelectContent>
</Select>
</div>
</div>
</DialogBody>
<DialogFooter className="flex-col sm:flex-row gap-2">
{isEditingButton && (
<Button variant="destructive" onClick={deleteButton} className="sm:mr-auto">
{__('Delete')}
</Button>
)}
<Button variant="outline" onClick={() => setButtonDialogOpen(false)}>
{__('Cancel')}
</Button>
<Button onClick={insertButton}>
{isEditingButton ? __('Update Button') : __('Insert Button')}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div> </div>
); );
} }

View File

@@ -1,2 +1,3 @@
import { api } from '../api'; import { api } from '../api';
export const apiClient = api; export const apiClient = api;
export { api };

View File

@@ -107,6 +107,8 @@ function withSectionWrapper(Component: any) {
colorScheme={section.colorScheme} colorScheme={section.colorScheme}
elementStyles={section.elementStyles} elementStyles={section.elementStyles}
styles={section.styles} styles={section.styles}
isEditor={true}
section={section}
{...flatProps} {...flatProps}
/> />
); );
@@ -207,10 +209,10 @@ export function CanvasRenderer({
> >
<div <div
className={cn( className={cn(
'bg-white transition-all duration-300 min-h-[500px]', 'bg-white transition-all duration-300 min-h-[500px] wn-page',
deviceMode === 'mobile' deviceMode === 'mobile'
? 'max-w-sm mx-auto shadow-2xl rounded-[2.5rem] border-[12px] border-gray-800 my-8 overflow-hidden' ? 'max-w-sm mx-auto shadow-2xl rounded-[2.5rem] border-[12px] border-gray-800 my-8 overflow-hidden'
: 'w-full h-full' : cn('min-h-full', containerWidth === 'boxed' ? 'container mx-auto max-w-6xl shadow-sm border-x' : 'w-full')
)} )}
> >
{sections.length === 0 ? ( {sections.length === 0 ? (

View File

@@ -82,8 +82,15 @@ export function CanvasSection({
{/* Section content with Styles */} {/* Section content with Styles */}
<div <div
className={cn( className={cn(
"relative overflow-hidden rounded-lg", "relative overflow-hidden",
!section.styles?.backgroundColor && !section.styles?.backgroundType && "bg-white/50" !section.styles?.backgroundColor && !section.styles?.backgroundType && "bg-white/50",
{
'default': 'py-16 md:py-24',
'small': 'py-8 md:py-12',
'medium': 'py-16 md:py-24',
'large': 'py-24 md:py-36',
'fullscreen': 'min-h-[600px] flex items-center',
}[section.styles?.heightPreset || 'default'] || 'py-16 md:py-24'
)} )}
style={{ style={{
...(section.styles?.backgroundType === 'gradient' ...(section.styles?.backgroundType === 'gradient'
@@ -153,14 +160,23 @@ export function CanvasSection({
{/* Content Wrapper */} {/* Content Wrapper */}
{section.styles?.contentWidth === 'boxed' ? ( {section.styles?.contentWidth === 'boxed' ? (
<div className="relative z-10 container mx-auto px-4 max-w-5xl"> <div className="relative z-10 container mx-auto px-4 max-w-5xl">
<div className="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden"> <div
className="rounded-2xl shadow-sm border border-gray-200 overflow-hidden"
style={{
backgroundColor: section.styles?.cardBackgroundColor || '#ffffff',
paddingTop: section.styles?.cardPaddingTop || undefined,
paddingRight: section.styles?.cardPaddingRight || undefined,
paddingBottom: section.styles?.cardPaddingBottom || undefined,
paddingLeft: section.styles?.cardPaddingLeft || undefined,
}}
>
{children} {children}
</div> </div>
</div> </div>
) : ( ) : (
<div className={cn( <div className={cn(
"relative z-10", "relative z-10 w-full",
section.styles?.contentWidth === 'contained' ? 'container mx-auto px-4 max-w-6xl' : 'w-full' section.styles?.contentWidth === 'contained' ? 'container mx-auto px-4 max-w-6xl' : ''
)}> )}>
{children} {children}
</div> </div>

View File

@@ -127,7 +127,7 @@ export function InspectorField({
placeholder={fieldType === 'url' ? 'https://' : `Enter ${fieldLabel.toLowerCase()}`} placeholder={fieldType === 'url' ? 'https://' : `Enter ${fieldLabel.toLowerCase()}`}
className="flex-1" className="flex-1"
/> />
{(fieldType === 'url' || fieldType === 'image') && ( {(fieldType === 'image') && (
<MediaUploader <MediaUploader
onSelect={(url) => handleValueChange(url)} onSelect={(url) => handleValueChange(url)}
type="image" type="image"

View File

@@ -3,6 +3,7 @@ import { cn } from '@/lib/utils';
import { __ } from '@/lib/i18n'; import { __ } from '@/lib/i18n';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label'; import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { import {
Select, Select,
SelectContent, SelectContent,
@@ -413,6 +414,7 @@ export function InspectorPanel({
{ name: 'label', label: 'Label', type: 'text' }, { name: 'label', label: 'Label', type: 'text' },
{ name: 'image', label: 'Image', type: 'image' }, { name: 'image', label: 'Image', type: 'image' },
{ name: 'url', label: 'Link URL', type: 'text' }, { name: 'url', label: 'Link URL', type: 'text' },
{ name: 'backgroundColor', label: 'Background Color', type: 'color' },
{ name: 'size', label: 'Size (small/medium/large/tall)', type: 'text' }, { name: 'size', label: 'Size (small/medium/large/tall)', type: 'text' },
]} ]}
itemLabelKey="label" itemLabelKey="label"
@@ -436,7 +438,7 @@ export function InspectorPanel({
// Allow advanced override/editing of asset/data if needed // Allow advanced override/editing of asset/data if needed
{ name: 'product_name', label: 'Product Name', type: 'text' }, { name: 'product_name', label: 'Product Name', type: 'text' },
{ name: 'product_price', label: 'Price', type: 'text' }, { name: 'product_price', label: 'Price', type: 'text' },
{ name: 'product_image', label: 'Product Image URL', type: 'text' }, { name: 'product_image', label: 'Product Image URL', type: 'image' },
{ name: 'x', label: 'X Position (%)', type: 'text' }, { name: 'x', label: 'X Position (%)', type: 'text' },
{ name: 'y', label: 'Y Position (%)', type: 'text' }, { name: 'y', label: 'Y Position (%)', type: 'text' },
]} ]}
@@ -448,6 +450,36 @@ export function InspectorPanel({
</div> </div>
); );
})()} })()}
{/* Contact Form Fields Repeater */}
{selectedSection.type === 'contact-form' && (() => {
const fieldsProp = selectedSection.props.fields;
const fields = Array.isArray(fieldsProp?.value) ? fieldsProp.value : [];
return (
<div className="pt-4 border-t">
<InspectorRepeater
label={__('Form Fields')}
items={fields}
onChange={(newItems) => onSectionPropChange('fields', { type: 'static', value: newItems })}
fields={[
{ name: 'name', label: 'Field Name (Key)', type: 'text' },
{ name: 'label', label: 'Label / Placeholder', type: 'text' },
{ name: 'type', label: 'Input Type', type: 'select', options: [
{ label: 'Text', value: 'text' },
{ label: 'Email', value: 'email' },
{ label: 'Telephone', value: 'tel' },
{ label: 'Textarea (Multiline)', value: 'textarea' },
]},
{ name: 'required', label: 'Is Required?', type: 'checkbox' }
]}
itemLabelKey="label"
/>
<p className="text-xs text-muted-foreground mt-2">
The <strong>Field Name (Key)</strong> will be the key used when sending data to your webhook.
</p>
</div>
);
})()}
</TabsContent> </TabsContent>
{/* Design Tab */} {/* Design Tab */}
@@ -491,10 +523,10 @@ export function InspectorPanel({
onChange={(e) => onSectionStylesChange({ backgroundColor: e.target.value })} onChange={(e) => onSectionStylesChange({ backgroundColor: e.target.value })}
/> />
</div> </div>
<input <Input
type="text" type="text"
placeholder="#FFFFFF" placeholder="#FFFFFF"
className="flex-1 h-8 rounded-md border border-input bg-background px-3 py-1 text-sm" className="flex-1 h-8 px-3 py-1 text-sm"
value={selectedSection.styles?.backgroundColor || ''} value={selectedSection.styles?.backgroundColor || ''}
onChange={(e) => onSectionStylesChange({ backgroundColor: e.target.value })} onChange={(e) => onSectionStylesChange({ backgroundColor: e.target.value })}
/> />
@@ -525,9 +557,9 @@ export function InspectorPanel({
onChange={(e) => onSectionStylesChange({ gradientFrom: e.target.value })} onChange={(e) => onSectionStylesChange({ gradientFrom: e.target.value })}
/> />
</div> </div>
<input <Input
type="text" type="text"
className="flex-1 h-8 rounded-md border border-input bg-background px-2 py-1 text-xs" className="flex-1 h-8 px-2 py-1 text-xs"
value={selectedSection.styles?.gradientFrom || '#9333ea'} value={selectedSection.styles?.gradientFrom || '#9333ea'}
onChange={(e) => onSectionStylesChange({ gradientFrom: e.target.value })} onChange={(e) => onSectionStylesChange({ gradientFrom: e.target.value })}
/> />
@@ -545,9 +577,9 @@ export function InspectorPanel({
onChange={(e) => onSectionStylesChange({ gradientTo: e.target.value })} onChange={(e) => onSectionStylesChange({ gradientTo: e.target.value })}
/> />
</div> </div>
<input <Input
type="text" type="text"
className="flex-1 h-8 rounded-md border border-input bg-background px-2 py-1 text-xs" className="flex-1 h-8 px-2 py-1 text-xs"
value={selectedSection.styles?.gradientTo || '#3b82f6'} value={selectedSection.styles?.gradientTo || '#3b82f6'}
onChange={(e) => onSectionStylesChange({ gradientTo: e.target.value })} onChange={(e) => onSectionStylesChange({ gradientTo: e.target.value })}
/> />
@@ -660,20 +692,20 @@ export function InspectorPanel({
<div className="grid grid-cols-2 gap-2 pt-2 border-t mt-4"> <div className="grid grid-cols-2 gap-2 pt-2 border-t mt-4">
<div className="space-y-1"> <div className="space-y-1">
<Label className="text-xs text-gray-500">{__('Padding Top')}</Label> <Label className="text-xs text-gray-500">{__('Padding Top')}</Label>
<input <Input
type="text" type="text"
placeholder="e.g. 40px, 4rem" placeholder="e.g. 40px, 4rem"
className="w-full h-8 text-xs rounded border px-2" className="h-8 text-xs px-2"
value={selectedSection.styles?.paddingTop || ''} value={selectedSection.styles?.paddingTop || ''}
onChange={(e) => onSectionStylesChange({ paddingTop: e.target.value })} onChange={(e) => onSectionStylesChange({ paddingTop: e.target.value })}
/> />
</div> </div>
<div className="space-y-1"> <div className="space-y-1">
<Label className="text-xs text-gray-500">{__('Padding Bottom')}</Label> <Label className="text-xs text-gray-500">{__('Padding Bottom')}</Label>
<input <Input
type="text" type="text"
placeholder="e.g. 40px, 4rem" placeholder="e.g. 40px, 4rem"
className="w-full h-8 text-xs rounded border px-2" className="h-8 text-xs px-2"
value={selectedSection.styles?.paddingBottom || ''} value={selectedSection.styles?.paddingBottom || ''}
onChange={(e) => onSectionStylesChange({ paddingBottom: e.target.value })} onChange={(e) => onSectionStylesChange({ paddingBottom: e.target.value })}
/> />
@@ -702,6 +734,49 @@ export function InspectorPanel({
</RadioGroup> </RadioGroup>
</div> </div>
{selectedSection.styles?.contentWidth === 'boxed' && (
<>
<div className="space-y-2 pt-2 mt-4">
<Label className="text-xs text-gray-500">{__('Card Background Color')}</Label>
<div className="flex items-center gap-2 mt-1">
<div className="relative w-6 h-6 rounded border shadow-sm shrink-0 overflow-hidden">
<div className="absolute inset-0" style={{ backgroundColor: selectedSection.styles?.cardBackgroundColor || '#ffffff' }} />
<Input
type="color"
className="absolute inset-0 opacity-0 cursor-pointer w-full h-full p-0 border-0"
value={selectedSection.styles?.cardBackgroundColor || '#ffffff'}
onChange={(e) => onSectionStylesChange({ cardBackgroundColor: e.target.value })}
/>
</div>
<Input
type="text"
placeholder="#ffffff"
className="flex-1 h-8 text-xs px-2"
value={selectedSection.styles?.cardBackgroundColor || ''}
onChange={(e) => onSectionStylesChange({ cardBackgroundColor: e.target.value })}
/>
</div>
</div>
<div className="space-y-2 pt-2 mt-4 border-t">
<Label className="text-xs text-gray-500">{__('Card Padding')}</Label>
<div className="grid grid-cols-4 gap-2">
<div className="space-y-1 text-center">
<Input type="text" placeholder="Top" className="h-8 text-xs px-2 text-center" value={selectedSection.styles?.cardPaddingTop || ''} onChange={(e) => onSectionStylesChange({ cardPaddingTop: e.target.value })} />
</div>
<div className="space-y-1 text-center">
<Input type="text" placeholder="Right" className="h-8 text-xs px-2 text-center" value={selectedSection.styles?.cardPaddingRight || ''} onChange={(e) => onSectionStylesChange({ cardPaddingRight: e.target.value })} />
</div>
<div className="space-y-1 text-center">
<Input type="text" placeholder="Bottom" className="h-8 text-xs px-2 text-center" value={selectedSection.styles?.cardPaddingBottom || ''} onChange={(e) => onSectionStylesChange({ cardPaddingBottom: e.target.value })} />
</div>
<div className="space-y-1 text-center">
<Input type="text" placeholder="Left" className="h-8 text-xs px-2 text-center" value={selectedSection.styles?.cardPaddingLeft || ''} onChange={(e) => onSectionStylesChange({ cardPaddingLeft: e.target.value })} />
</div>
</div>
</div>
</>
)}
<div className="space-y-2 pt-2 border-t mt-4"> <div className="space-y-2 pt-2 border-t mt-4">
<Label className="text-xs">{__('Section Height')}</Label> <Label className="text-xs">{__('Section Height')}</Label>
<Select <Select
@@ -739,29 +814,31 @@ export function InspectorPanel({
<AccordionTrigger className="text-xs hover:no-underline py-2">{field.label}</AccordionTrigger> <AccordionTrigger className="text-xs hover:no-underline py-2">{field.label}</AccordionTrigger>
<AccordionContent className="space-y-4 pt-2"> <AccordionContent className="space-y-4 pt-2">
{/* Common: Background Wrapper */} {/* Common: Background Wrapper */}
<div className="space-y-2"> {!field.disableBackground && (
<Label className="text-xs text-gray-500">{__('Background (Wrapper)')}</Label> <div className="space-y-2">
<div className="flex items-center gap-2"> <Label className="text-xs text-gray-500">{__('Background (Wrapper)')}</Label>
<div className="relative w-6 h-6 rounded border shadow-sm shrink-0 overflow-hidden"> <div className="flex items-center gap-2">
<div className="absolute inset-0" style={{ backgroundColor: styles.backgroundColor || 'transparent' }} /> <div className="relative w-6 h-6 rounded border shadow-sm shrink-0 overflow-hidden">
<input <div className="absolute inset-0" style={{ backgroundColor: styles.backgroundColor || 'transparent' }} />
type="color" <input
className="absolute inset-0 opacity-0 cursor-pointer w-full h-full p-0 border-0" type="color"
value={styles.backgroundColor || '#ffffff'} className="absolute inset-0 opacity-0 cursor-pointer w-full h-full p-0 border-0"
value={styles.backgroundColor || '#ffffff'}
onChange={(e) => onElementStylesChange(field.name, { backgroundColor: e.target.value })}
/>
</div>
<Input
type="text"
placeholder="Color (#fff)"
className="flex-1 h-8 text-xs px-2"
value={styles.backgroundColor || ''}
onChange={(e) => onElementStylesChange(field.name, { backgroundColor: e.target.value })} onChange={(e) => onElementStylesChange(field.name, { backgroundColor: e.target.value })}
/> />
</div> </div>
<input
type="text"
placeholder="Color (#fff)"
className="flex-1 h-7 text-xs rounded border px-2"
value={styles.backgroundColor || ''}
onChange={(e) => onElementStylesChange(field.name, { backgroundColor: e.target.value })}
/>
</div> </div>
</div> )}
{!isImage ? ( {(!isImage && field.type !== 'container') && (
<> <>
{/* Text Color */} {/* Text Color */}
<div className="space-y-2"> <div className="space-y-2">
@@ -776,10 +853,10 @@ export function InspectorPanel({
onChange={(e) => onElementStylesChange(field.name, { color: e.target.value })} onChange={(e) => onElementStylesChange(field.name, { color: e.target.value })}
/> />
</div> </div>
<input <Input
type="text" type="text"
placeholder="Color (#000)" placeholder="Color (#000)"
className="flex-1 h-7 text-xs rounded border px-2" className="flex-1 h-8 text-xs px-2"
value={styles.color || ''} value={styles.color || ''}
onChange={(e) => onElementStylesChange(field.name, { color: e.target.value })} onChange={(e) => onElementStylesChange(field.name, { color: e.target.value })}
/> />
@@ -830,15 +907,17 @@ export function InspectorPanel({
</Select> </Select>
</div> </div>
<Select value={styles.textAlign || 'default'} onValueChange={(val) => onElementStylesChange(field.name, { textAlign: val === 'default' ? undefined : val as any })}> {!field.disableAlignment && (
<SelectTrigger className="h-7 text-xs"><SelectValue placeholder="Alignment" /></SelectTrigger> <Select value={styles.textAlign || 'default'} onValueChange={(val) => onElementStylesChange(field.name, { textAlign: val === 'default' ? undefined : val as any })}>
<SelectContent> <SelectTrigger className="h-7 text-xs"><SelectValue placeholder="Alignment" /></SelectTrigger>
<SelectItem value="default">Default Align</SelectItem> <SelectContent>
<SelectItem value="left">Left</SelectItem> <SelectItem value="default">Default Align</SelectItem>
<SelectItem value="center">Center</SelectItem> <SelectItem value="left">Left</SelectItem>
<SelectItem value="right">Right</SelectItem> <SelectItem value="center">Center</SelectItem>
</SelectContent> <SelectItem value="right">Right</SelectItem>
</Select> </SelectContent>
</Select>
)}
</div> </div>
{/* Link Specific Styles */} {/* Link Specific Styles */}
@@ -865,10 +944,10 @@ export function InspectorPanel({
onChange={(e) => onElementStylesChange(field.name, { hoverColor: e.target.value })} onChange={(e) => onElementStylesChange(field.name, { hoverColor: e.target.value })}
/> />
</div> </div>
<input <Input
type="text" type="text"
placeholder="Hover Color" placeholder="Hover Color"
className="flex-1 h-7 text-xs rounded border px-2" className="flex-1 h-8 text-xs px-2"
value={styles.hoverColor || ''} value={styles.hoverColor || ''}
onChange={(e) => onElementStylesChange(field.name, { hoverColor: e.target.value })} onChange={(e) => onElementStylesChange(field.name, { hoverColor: e.target.value })}
/> />
@@ -876,45 +955,12 @@ export function InspectorPanel({
</div> </div>
</div> </div>
)} )}
{/* Button/Box Specific Styles */}
{field.name === 'button' && (
<div className="space-y-2">
<Label className="text-xs text-gray-500">{__('Box Styles')}</Label>
<div className="grid grid-cols-2 gap-2">
<div className="space-y-1">
<Label className="text-xs text-gray-400">{__('Border Color')}</Label>
<div className="flex items-center gap-2 h-7">
<div className="relative w-6 h-6 rounded border shadow-sm shrink-0 overflow-hidden">
<div className="absolute inset-0" style={{ backgroundColor: styles.borderColor || 'transparent' }} />
<input
type="color"
className="absolute inset-0 opacity-0 cursor-pointer w-full h-full p-0 border-0"
value={styles.borderColor || '#000000'}
onChange={(e) => onElementStylesChange(field.name, { borderColor: e.target.value })}
/>
</div>
</div>
</div>
<div className="space-y-1">
<Label className="text-xs text-gray-400">{__('Border Width')}</Label>
<input type="text" placeholder="e.g. 1px" className="w-full h-7 text-xs rounded border px-2" value={styles.borderWidth || ''} onChange={(e) => onElementStylesChange(field.name, { borderWidth: e.target.value })} />
</div>
<div className="space-y-1">
<Label className="text-xs text-gray-400">{__('Radius')}</Label>
<input type="text" placeholder="e.g. 4px" className="w-full h-7 text-xs rounded border px-2" value={styles.borderRadius || ''} onChange={(e) => onElementStylesChange(field.name, { borderRadius: e.target.value })} />
</div>
<div className="space-y-1">
<Label className="text-xs text-gray-400">{__('Padding')}</Label>
<input type="text" placeholder="e.g. 8px 16px" className="w-full h-7 text-xs rounded border px-2" value={styles.padding || ''} onChange={(e) => onElementStylesChange(field.name, { padding: e.target.value })} />
</div>
</div>
</div>
)}
</> </>
) : ( )}
{/* Image Settings */}
{isImage && (
<> <>
{/* Image Settings */}
<div className="space-y-2"> <div className="space-y-2">
<Label className="text-xs text-gray-500">{__('Image Fit')}</Label> <Label className="text-xs text-gray-500">{__('Image Fit')}</Label>
<Select value={styles.objectFit || 'default'} onValueChange={(val) => onElementStylesChange(field.name, { objectFit: val === 'default' ? undefined : val as any })}> <Select value={styles.objectFit || 'default'} onValueChange={(val) => onElementStylesChange(field.name, { objectFit: val === 'default' ? undefined : val as any })}>
@@ -927,19 +973,80 @@ export function InspectorPanel({
</SelectContent> </SelectContent>
</Select> </Select>
</div> </div>
<div className="space-y-2 pt-2">
<Label className="text-xs text-gray-500">{__('Image Focal Point')}</Label>
<Select value={styles.objectPosition || 'default'} onValueChange={(val) => onElementStylesChange(field.name, { objectPosition: val === 'default' ? undefined : val as any })}>
<SelectTrigger className="h-7 text-xs"><SelectValue placeholder="Position (e.g. center, top)" /></SelectTrigger>
<SelectContent>
<SelectItem value="default">Default</SelectItem>
<SelectItem value="center">Center</SelectItem>
<SelectItem value="top">Top</SelectItem>
<SelectItem value="bottom">Bottom</SelectItem>
<SelectItem value="left">Left</SelectItem>
<SelectItem value="right">Right</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2 pt-2 pb-2">
<Label className="text-xs text-gray-500">{__('Wrapper Alignment')}</Label>
<Select value={styles.alignment || 'default'} onValueChange={(val) => onElementStylesChange(field.name, { alignment: val === 'default' ? undefined : val as any })}>
<SelectTrigger className="h-7 text-xs"><SelectValue placeholder="Alignment" /></SelectTrigger>
<SelectContent>
<SelectItem value="default">Default</SelectItem>
<SelectItem value="left">Left</SelectItem>
<SelectItem value="center">Center</SelectItem>
<SelectItem value="right">Right</SelectItem>
</SelectContent>
</Select>
</div>
<div className="grid grid-cols-2 gap-2"> <div className="grid grid-cols-2 gap-2">
<div className="space-y-1"> <div className="space-y-1">
<Label className="text-xs text-gray-500">{__('Width')}</Label> <Label className="text-xs text-gray-500">{__('Width')}</Label>
<input type="text" placeholder="e.g. 100%" className="w-full h-7 text-xs rounded border px-2" value={styles.width || ''} onChange={(e) => onElementStylesChange(field.name, { width: e.target.value })} /> <Input type="text" placeholder="e.g. 100%" className="h-8 text-xs px-2" value={styles.width || ''} onChange={(e) => onElementStylesChange(field.name, { width: e.target.value })} />
</div> </div>
<div className="space-y-1"> <div className="space-y-1">
<Label className="text-xs text-gray-500">{__('Height')}</Label> <Label className="text-xs text-gray-500">{__('Height')}</Label>
<input type="text" placeholder="e.g. auto" className="w-full h-7 text-xs rounded border px-2" value={styles.height || ''} onChange={(e) => onElementStylesChange(field.name, { height: e.target.value })} /> <Input type="text" placeholder="e.g. auto" className="h-8 text-xs px-2" value={styles.height || ''} onChange={(e) => onElementStylesChange(field.name, { height: e.target.value })} />
</div> </div>
</div> </div>
</> </>
)} )}
{/* Button/Box Specific Styles */}
{(field.name === 'button' || field.type === 'container') && (
<div className="space-y-2">
<Label className="text-xs text-gray-500">{__('Box Styles')}</Label>
<div className="grid grid-cols-2 gap-2">
<div className="space-y-1">
<Label className="text-xs text-gray-400">{__('Border Color')}</Label>
<div className="flex items-center gap-2 h-7">
<div className="relative w-6 h-6 rounded border shadow-sm shrink-0 overflow-hidden">
<div className="absolute inset-0" style={{ backgroundColor: styles.borderColor || 'transparent' }} />
<input
type="color"
className="absolute inset-0 opacity-0 cursor-pointer w-full h-full p-0 border-0"
value={styles.borderColor || '#000000'}
onChange={(e) => onElementStylesChange(field.name, { borderColor: e.target.value })}
/>
</div>
</div>
</div>
<div className="space-y-1">
<Label className="text-xs text-gray-400">{__('Border Width')}</Label>
<Input type="text" placeholder="e.g. 1px" className="h-8 text-xs px-2" value={styles.borderWidth || ''} onChange={(e) => onElementStylesChange(field.name, { borderWidth: e.target.value })} />
</div>
<div className="space-y-1">
<Label className="text-xs text-gray-400">{__('Radius')}</Label>
<Input type="text" placeholder="e.g. 4px" className="h-8 text-xs px-2" value={styles.borderRadius || ''} onChange={(e) => onElementStylesChange(field.name, { borderRadius: e.target.value })} />
</div>
<div className="space-y-1">
<Label className="text-xs text-gray-400">{__('Padding')}</Label>
<Input type="text" placeholder="e.g. 8px 16px" className="h-8 text-xs px-2" value={styles.padding || ''} onChange={(e) => onElementStylesChange(field.name, { padding: e.target.value })} />
</div>
</div>
</div>
)}
</AccordionContent> </AccordionContent>
</AccordionItem> </AccordionItem>
); );

View File

@@ -16,7 +16,8 @@ import {
SelectTrigger, SelectTrigger,
SelectValue, SelectValue,
} from '@/components/ui/select'; } from '@/components/ui/select';
import { Plus, Trash2, GripVertical } from 'lucide-react'; import { Plus, Trash2, GripVertical, Image as ImageIcon } from 'lucide-react';
import { Switch } from '@/components/ui/switch';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { useSortable } from '@dnd-kit/sortable'; import { useSortable } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities'; import { CSS } from '@dnd-kit/utilities';
@@ -41,8 +42,9 @@ import RepeaterProductField from './RepeaterProductField';
interface RepeaterFieldDef { interface RepeaterFieldDef {
name: string; name: string;
label: string; label: string;
type: 'text' | 'textarea' | 'url' | 'image' | 'icon' | 'product'; type: 'text' | 'textarea' | 'url' | 'image' | 'icon' | 'product' | 'select' | 'checkbox' | 'color';
placeholder?: string; placeholder?: string;
options?: { label: string; value: string }[];
} }
interface InspectorRepeaterProps { interface InspectorRepeaterProps {
@@ -91,8 +93,8 @@ function SortableItem({
'Wifi', 'Wrench', 'Wifi', 'Wrench',
].sort(); ].sort();
const handleFieldChange = (fieldName: string, value: any) => { const handleFieldChange = (fieldNameOrUpdates: string | Record<string, any>, value?: any) => {
onChange(index, fieldName, value); onChange(index, fieldNameOrUpdates, value);
}; };
return ( return (
@@ -151,7 +153,7 @@ function RepeaterFieldRenderer({
field: RepeaterFieldDef; field: RepeaterFieldDef;
item: any; item: any;
index: number; index: number;
onChange: (fieldName: string, value: any) => void; onChange: (fieldNameOrUpdates: string | Record<string, any>, value?: any) => void;
ICON_OPTIONS: string[]; ICON_OPTIONS: string[];
}) { }) {
const value = item[field.name] || ''; const value = item[field.name] || '';
@@ -195,44 +197,53 @@ function RepeaterFieldRenderer({
); );
} }
if (field.type === 'color') {
return (
<div className="space-y-1.5">
<Label className="text-xs text-gray-500">{field.label}</Label>
<div className="flex items-center gap-2">
<div className="relative w-8 h-8 rounded border shadow-sm shrink-0 overflow-hidden">
<div className="absolute inset-0" style={{ backgroundColor: value || 'transparent' }} />
<input
type="color"
className="absolute inset-0 opacity-0 cursor-pointer w-full h-full p-0 border-0"
value={value || '#ffffff'}
onChange={(e) => onChange(field.name, e.target.value)}
/>
</div>
<Input
type="text"
placeholder="#ffffff"
className="flex-1 h-8 text-xs px-2"
value={value || ''}
onChange={(e) => onChange(field.name, e.target.value)}
/>
</div>
</div>
);
}
if (field.type === 'image') { if (field.type === 'image') {
return ( return (
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label className="text-xs text-gray-500">{field.label}</Label> <Label className="text-xs text-gray-500">{field.label}</Label>
<div className="space-y-2"> <div className="flex gap-2">
{value ? ( <Input
<MediaUploader type="text"
onSelect={(url) => onChange(field.name, url)} value={value}
type="image" onChange={(e) => onChange(field.name, e.target.value)}
> placeholder="https://..."
<div className="relative group cursor-pointer border rounded overflow-hidden h-24 bg-gray-50 flex items-center justify-center"> className="flex-1 text-xs h-8"
<img src={value} alt={field.label} className="w-full h-full object-cover" /> />
<div className="absolute inset-0 bg-black/40 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"> <MediaUploader
<span className="text-white text-xs font-medium">Change</span> onSelect={(url) => onChange(field.name, url)}
</div> type="image"
<button className="shrink-0"
onClick={(e) => { >
e.stopPropagation(); <Button variant="outline" size="icon" className="h-8 w-8 shrink-0" title="Select Image" type="button">
onChange(field.name, ''); <ImageIcon className="w-4 h-4" />
}} </Button>
className="absolute top-1 right-1 bg-white/90 p-1 rounded-full text-gray-600 hover:text-red-500 opacity-0 group-hover:opacity-100 transition-opacity" </MediaUploader>
type="button"
aria-label="Remove image"
>
<Trash2 className="w-3 h-3" />
</button>
</div>
</MediaUploader>
) : (
<MediaUploader
onSelect={(url) => onChange(field.name, url)}
type="image"
>
<Button variant="outline" className="w-full h-24 border-dashed flex flex-row gap-2 text-gray-400 font-normal justify-start">
Select Image
</Button>
</MediaUploader>
)}
</div> </div>
</div> </div>
); );
@@ -251,6 +262,41 @@ function RepeaterFieldRenderer({
); );
} }
if (field.type === 'select') {
return (
<div className="space-y-1.5">
<Label className="text-xs text-gray-500">{field.label}</Label>
<Select
value={value}
onValueChange={(val) => onChange(field.name, val)}
>
<SelectTrigger className="h-8 text-xs w-full">
<SelectValue placeholder={field.placeholder || "Select an option"} />
</SelectTrigger>
<SelectContent>
{field.options?.map((opt) => (
<SelectItem key={opt.value} value={opt.value}>
{opt.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
);
}
if (field.type === 'checkbox') {
return (
<div className="flex items-center justify-between space-x-2 py-1">
<Label className="text-xs text-gray-500">{field.label}</Label>
<Switch
checked={!!value}
onCheckedChange={(checked) => onChange(field.name, checked)}
/>
</div>
);
}
// default: text/url inputs // default: text/url inputs
const inputType = field.type === 'url' ? 'url' : 'text'; const inputType = field.type === 'url' ? 'url' : 'text';
@@ -296,9 +342,13 @@ export function InspectorRepeater({
} }
}; };
const handleItemChange = (index: number, fieldName: string, value: string) => { const handleItemChange = (index: number, fieldNameOrUpdates: string | Record<string, any>, value?: any) => {
const newItems = [...items]; const newItems = [...items];
newItems[index] = { ...newItems[index], [fieldName]: value }; if (typeof fieldNameOrUpdates === 'string') {
newItems[index] = { ...newItems[index], [fieldNameOrUpdates]: value };
} else {
newItems[index] = { ...newItems[index], ...fieldNameOrUpdates };
}
onChange(newItems); onChange(newItems);
}; };
@@ -341,7 +391,7 @@ export function InspectorRepeater({
item={item} item={item}
fields={fields} fields={fields}
itemLabelKey={itemLabelKey} itemLabelKey={itemLabelKey}
onChange={(idx: number, fieldName: string, value: string) => handleItemChange(idx, fieldName, value)} onChange={(idx: number, fieldNameOrUpdates: string | Record<string, any>, value?: any) => handleItemChange(idx, fieldNameOrUpdates, value)}
onDelete={handleDeleteItem} onDelete={handleDeleteItem}
/> />
))} ))}

View File

@@ -10,7 +10,7 @@ export default function RepeaterProductField({
}: { }: {
label: string; label: string;
value: string; value: string;
onChange: (fieldName: string, nextValue: any) => void; onChange: (fieldNameOrUpdates: string | Record<string, any>, nextValue?: any) => void;
}) { }) {
const [search, setSearch] = React.useState(''); const [search, setSearch] = React.useState('');
const [options, setOptions] = React.useState<any[]>([]); const [options, setOptions] = React.useState<any[]>([]);
@@ -77,11 +77,13 @@ export default function RepeaterProductField({
const selected = options.find((o) => o.value === v)?.product; const selected = options.find((o) => o.value === v)?.product;
if (!selected) return; if (!selected) return;
onChange('product_slug', selected.product_slug || ''); onChange({
onChange('product_name', selected.name || ''); product_slug: selected.product_slug || '',
onChange('product_price', selected.sale_price ?? selected.price ?? ''); product_name: selected.name || '',
onChange('product_image', selected.image_url ?? ''); product_price: selected.sale_price ?? selected.price ?? '',
onChange('product_id', selected.id ? Number(selected.id) : 0); product_image: selected.image_url ?? '',
product_id: selected.id ? Number(selected.id) : 0,
});
}} }}
options={options.map((o) => ({ options={options.map((o) => ({
value: String(o.value ?? ''), value: String(o.value ?? ''),

View File

@@ -32,16 +32,6 @@ export function CTABannerRenderer({ section, className }: CTABannerRendererProps
const buttonText = section.props?.button_text?.value || 'Get Started'; const buttonText = section.props?.button_text?.value || 'Get Started';
const buttonUrl = section.props?.button_url?.value || '#'; const buttonUrl = section.props?.button_url?.value || '#';
const heightMap: Record<string, string> = {
'default': 'py-12 md:py-20',
'small': 'py-8 md:py-12',
'medium': 'py-16 md:py-24',
'large': 'py-24 md:py-36',
'fullscreen': 'min-h-[50vh] flex flex-col justify-center',
};
const customPadding = section.styles?.paddingTop || section.styles?.paddingBottom;
const heightClasses = customPadding ? '' : (heightMap[section.styles?.heightPreset || 'default'] || 'py-12 md:py-20');
// Helper to get text styles (including font family) // Helper to get text styles (including font family)
const getTextStyles = (elementName: string) => { const getTextStyles = (elementName: string) => {
const styles = section.elementStyles?.[elementName] || {}; const styles = section.elementStyles?.[elementName] || {};
@@ -69,7 +59,7 @@ export function CTABannerRenderer({ section, className }: CTABannerRendererProps
const hasCustomBackground = !!section.styles?.backgroundColor || !!section.styles?.backgroundImage || section.styles?.backgroundType === 'gradient'; const hasCustomBackground = !!section.styles?.backgroundColor || !!section.styles?.backgroundImage || section.styles?.backgroundType === 'gradient';
return ( return (
<div className={cn(heightClasses, 'px-4 md:px-8', !hasCustomBackground && scheme.bg, scheme.text, className)}> <div className={cn('px-4 md:px-8', !hasCustomBackground && scheme.bg, scheme.text, className)}>
<div className="max-w-4xl mx-auto text-center space-y-6"> <div className="max-w-4xl mx-auto text-center space-y-6">
<h2 <h2
className={cn( className={cn(
@@ -88,7 +78,7 @@ export function CTABannerRenderer({ section, className }: CTABannerRendererProps
)} )}
style={textStyle.style} style={textStyle.style}
> >
{text} {text || "Description text missing"}
</p> </p>
<button className={cn( <button className={cn(
'inline-flex items-center gap-2 px-8 py-4 rounded-lg font-semibold transition hover:opacity-90', 'inline-flex items-center gap-2 px-8 py-4 rounded-lg font-semibold transition hover:opacity-90',

View File

@@ -69,21 +69,11 @@ export function ContactFormRenderer({ section, className }: ContactFormRendererP
return undefined; return undefined;
}; };
const heightMap: Record<string, string> = {
'default': 'py-12 md:py-20',
'small': 'py-8 md:py-12',
'medium': 'py-16 md:py-24',
'large': 'py-24 md:py-36',
'fullscreen': 'min-h-[50vh] flex flex-col justify-center',
};
const customPadding = section.styles?.paddingTop || section.styles?.paddingBottom;
const heightClasses = customPadding ? '' : (heightMap[section.styles?.heightPreset || 'default'] || 'py-12 md:py-20');
const hasCustomBackground = !!section.styles?.backgroundColor || !!section.styles?.backgroundImage || section.styles?.backgroundType === 'gradient'; const hasCustomBackground = !!section.styles?.backgroundColor || !!section.styles?.backgroundImage || section.styles?.backgroundType === 'gradient';
return ( return (
<div <div
className={cn(heightClasses, 'px-4 md:px-8', !hasCustomBackground && !scheme.bg.startsWith('wn-') && scheme.bg, scheme.text, className)} className={cn('px-4 md:px-8', !hasCustomBackground && !scheme.bg.startsWith('wn-') && scheme.bg, scheme.text, className)}
style={hasCustomBackground ? {} : getBackgroundStyle()} style={hasCustomBackground ? {} : getBackgroundStyle()}
> >
<div className="max-w-xl mx-auto"> <div className="max-w-xl mx-auto">
@@ -98,59 +88,57 @@ export function ContactFormRenderer({ section, className }: ContactFormRendererP
</h2> </h2>
<form className="space-y-4" onSubmit={(e) => e.preventDefault()}> <form className="space-y-4" onSubmit={(e) => e.preventDefault()}>
{/* Name field */} {/* Render fields from config, fallback to default if missing */}
<div className="relative"> {(() => {
<User className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" /> const defaultFields = [
<input { name: 'name', label: 'Your Name', type: 'text', required: true },
type="text" { name: 'email', label: 'Your Email', type: 'email', required: true },
placeholder="Your Name" { name: 'message', label: 'Your Message', type: 'textarea', required: true }
className={cn( ];
'w-full pl-12 pr-4 py-3 rounded-lg border border-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500', const fieldsProp = section.props?.fields?.value;
!fieldsStyle.backgroundColor && scheme.inputBg const fields = Array.isArray(fieldsProp) && fieldsProp.length > 0 ? fieldsProp : defaultFields;
)}
style={{
backgroundColor: fieldsStyle.backgroundColor,
color: fieldsStyle.color
}}
disabled
/>
</div>
{/* Email field */} return fields.map((field: any, idx: number) => {
<div className="relative"> const Icon = field.type === 'email' ? Mail : field.type === 'textarea' ? MessageSquare : User;
<Mail className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" /> return (
<input <div key={field.name || idx} className="relative">
type="email" <Icon className={cn(
placeholder="Your Email" "absolute left-4 text-gray-400 w-5 h-5",
className={cn( field.type === 'textarea' ? "top-4" : "top-1/2 -translate-y-1/2"
'w-full pl-12 pr-4 py-3 rounded-lg border border-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500', )} />
!fieldsStyle.backgroundColor && scheme.inputBg {field.type === 'textarea' ? (
)} <textarea
style={{ placeholder={field.label + (field.required ? ' *' : '')}
backgroundColor: fieldsStyle.backgroundColor, rows={4}
color: fieldsStyle.color className={cn(
}} 'w-full pl-12 pr-4 py-3 rounded-lg border border-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none',
disabled !fieldsStyle.backgroundColor && scheme.inputBg
/> )}
</div> style={{
backgroundColor: fieldsStyle.backgroundColor,
{/* Message field */} color: fieldsStyle.color
<div className="relative"> }}
<MessageSquare className="absolute left-4 top-4 w-5 h-5 text-gray-400" /> disabled
<textarea />
placeholder="Your Message" ) : (
rows={4} <input
className={cn( type={field.type || 'text'}
'w-full pl-12 pr-4 py-3 rounded-lg border border-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none', placeholder={field.label + (field.required ? ' *' : '')}
!fieldsStyle.backgroundColor && scheme.inputBg className={cn(
)} 'w-full pl-12 pr-4 py-3 rounded-lg border border-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500',
style={{ !fieldsStyle.backgroundColor && scheme.inputBg
backgroundColor: fieldsStyle.backgroundColor, )}
color: fieldsStyle.color style={{
}} backgroundColor: fieldsStyle.backgroundColor,
disabled color: fieldsStyle.color
/> }}
</div> disabled
/>
)}
</div>
);
});
})()}
{/* Submit button */} {/* Submit button */}
<button <button

View File

@@ -155,18 +155,6 @@ export function ContentRenderer({ section, className }: ContentRendererProps) {
const layout = section.layoutVariant || 'default'; const layout = section.layoutVariant || 'default';
const widthClass = WIDTH_CLASSES[layout] || WIDTH_CLASSES.default; const widthClass = WIDTH_CLASSES[layout] || WIDTH_CLASSES.default;
const heightPreset = section.styles?.heightPreset || 'default';
const heightMap: Record<string, string> = {
'default': 'py-12 md:py-20',
'small': 'py-8 md:py-12',
'medium': 'py-16 md:py-24',
'large': 'py-24 md:py-32',
'screen': 'min-h-screen py-20 flex items-center',
};
const heightClasses = heightMap[heightPreset] || 'py-12 md:py-20';
const content = section.props?.content?.value || 'Your content goes here. Edit this in the inspector panel.'; const content = section.props?.content?.value || 'Your content goes here. Edit this in the inspector panel.';
const isDynamic = section.props?.content?.type === 'dynamic'; const isDynamic = section.props?.content?.type === 'dynamic';
@@ -218,7 +206,6 @@ export function ContentRenderer({ section, className }: ContentRendererProps) {
className={cn( className={cn(
'relative w-full overflow-hidden', 'relative w-full overflow-hidden',
'px-4 md:px-8', 'px-4 md:px-8',
heightClasses,
!hasCustomBackground && !scheme.bg.startsWith('wn-') && scheme.bg, !hasCustomBackground && !scheme.bg.startsWith('wn-') && scheme.bg,
scheme.text, scheme.text,
className className

View File

@@ -119,21 +119,11 @@ export function FeatureGridRenderer({ section, className }: FeatureGridRendererP
return undefined; return undefined;
}; };
const heightMap: Record<string, string> = {
'default': 'py-12 md:py-20',
'small': 'py-8 md:py-12',
'medium': 'py-16 md:py-24',
'large': 'py-24 md:py-36',
'fullscreen': 'min-h-[50vh] flex flex-col justify-center',
};
const customPadding = section.styles?.paddingTop || section.styles?.paddingBottom;
const heightClasses = customPadding ? '' : (heightMap[section.styles?.heightPreset || 'default'] || 'py-12 md:py-20');
const hasCustomBackground = !!section.styles?.backgroundColor || !!section.styles?.backgroundImage || section.styles?.backgroundType === 'gradient'; const hasCustomBackground = !!section.styles?.backgroundColor || !!section.styles?.backgroundImage || section.styles?.backgroundType === 'gradient';
return ( return (
<div <div
className={cn(heightClasses, 'px-4 md:px-8', !hasCustomBackground && !scheme.bg.startsWith('wn-') && scheme.bg, scheme.text, className)} className={cn('px-4 md:px-8', !hasCustomBackground && !scheme.bg.startsWith('wn-') && scheme.bg, scheme.text, className)}
style={hasCustomBackground ? {} : getBackgroundStyle()} style={hasCustomBackground ? {} : getBackgroundStyle()}
> >
<div className="max-w-6xl mx-auto"> <div className="max-w-6xl mx-auto">

View File

@@ -27,16 +27,6 @@ export function HeroRenderer({ section, className }: HeroRendererProps) {
const scheme = COLOR_SCHEMES[section.colorScheme || 'default'] ?? COLOR_SCHEMES['default']; const scheme = COLOR_SCHEMES[section.colorScheme || 'default'] ?? COLOR_SCHEMES['default'];
const layout = section.layoutVariant || 'default'; const layout = section.layoutVariant || 'default';
const heightMap: Record<string, string> = {
'default': 'py-12 md:py-20',
'small': 'py-8 md:py-12',
'medium': 'py-16 md:py-24',
'large': 'py-24 md:py-36',
'fullscreen': 'min-h-[50vh] flex flex-col justify-center',
};
const customPadding = section.styles?.paddingTop || section.styles?.paddingBottom;
const heightClasses = customPadding ? '' : (heightMap[section.styles?.heightPreset || 'default'] || 'py-12 md:py-20');
const title = section.props?.title?.value || 'Hero Title'; const title = section.props?.title?.value || 'Hero Title';
const subtitle = section.props?.subtitle?.value || 'Your amazing subtitle here'; const subtitle = section.props?.subtitle?.value || 'Your amazing subtitle here';
const image = section.props?.image?.value; const image = section.props?.image?.value;
@@ -81,7 +71,7 @@ export function HeroRenderer({ section, className }: HeroRendererProps) {
if (layout === 'hero-left-image' || layout === 'hero-right-image') { if (layout === 'hero-left-image' || layout === 'hero-right-image') {
return ( return (
<div <div
className={cn(heightClasses, 'px-4 md:px-8', !hasCustomBackground && !scheme.bg.startsWith('wn-') && scheme.bg, scheme.text, className)} className={cn('px-4 md:px-8', !hasCustomBackground && !scheme.bg.startsWith('wn-') && scheme.bg, scheme.text, className)}
> >
<div className={cn( <div className={cn(
'max-w-6xl mx-auto flex items-center gap-12', 'max-w-6xl mx-auto flex items-center gap-12',
@@ -156,7 +146,7 @@ export function HeroRenderer({ section, className }: HeroRendererProps) {
// Default centered layout // Default centered layout
return ( return (
<div <div
className={cn(heightClasses, 'px-4 md:px-8 text-center', !hasCustomBackground && !scheme.bg.startsWith('wn-') && scheme.bg, scheme.text, className)} className={cn('px-4 md:px-8 text-center', !hasCustomBackground && !scheme.bg.startsWith('wn-') && scheme.bg, scheme.text, className)}
> >
<div className="max-w-4xl mx-auto space-y-6"> <div className="max-w-4xl mx-auto space-y-6">
<h1 <h1

View File

@@ -72,21 +72,11 @@ export function ImageTextRenderer({ section, className }: ImageTextRendererProps
return undefined; return undefined;
}; };
const heightMap: Record<string, string> = {
'default': 'py-12 md:py-20',
'small': 'py-8 md:py-12',
'medium': 'py-16 md:py-24',
'large': 'py-24 md:py-36',
'fullscreen': 'min-h-[50vh] flex flex-col justify-center',
};
const customPadding = section.styles?.paddingTop || section.styles?.paddingBottom;
const heightClasses = customPadding ? '' : (heightMap[section.styles?.heightPreset || 'default'] || 'py-12 md:py-20');
const hasCustomBackground = !!section.styles?.backgroundColor || !!section.styles?.backgroundImage || section.styles?.backgroundType === 'gradient'; const hasCustomBackground = !!section.styles?.backgroundColor || !!section.styles?.backgroundImage || section.styles?.backgroundType === 'gradient';
return ( return (
<div <div
className={cn(heightClasses, 'px-4 md:px-8', !hasCustomBackground && !scheme.bg.startsWith('wn-') && scheme.bg, scheme.text, className)} className={cn('px-4 md:px-8', !hasCustomBackground && !scheme.bg.startsWith('wn-') && scheme.bg, scheme.text, className)}
style={hasCustomBackground ? {} : getBackgroundStyle()} style={hasCustomBackground ? {} : getBackgroundStyle()}
> >
<div className={cn( <div className={cn(

View File

@@ -6,6 +6,7 @@ import { cn } from '@/lib/utils';
export function MarqueeBannerRenderer({ section, className }: { section: any; className?: string }) { export function MarqueeBannerRenderer({ section, className }: { section: any; className?: string }) {
const { text, separator } = section.props; const { text, separator } = section.props;
const styles = section.styles || {}; const styles = section.styles || {};
const elementStyles = section.elementStyles || {};
const displayText = text?.value || 'Marquee Banner Text Here'; const displayText = text?.value || 'Marquee Banner Text Here';
const displaySeparator = separator?.value || '✦'; const displaySeparator = separator?.value || '✦';
@@ -19,7 +20,14 @@ export function MarqueeBannerRenderer({ section, className }: { section: any; cl
<div className="flex whitespace-nowrap opacity-70"> <div className="flex whitespace-nowrap opacity-70">
<div className="flex items-center gap-8 pr-8"> <div className="flex items-center gap-8 pr-8">
{[1, 2, 3].map((idx) => ( {[1, 2, 3].map((idx) => (
<span key={idx} className="flex items-center gap-8 text-sm font-medium tracking-wide uppercase"> <span
key={idx}
className="flex items-center gap-8 text-sm font-medium tracking-wide uppercase"
style={{
color: elementStyles?.text?.color,
fontSize: elementStyles?.text?.fontSize?.replace('text-', '') ? undefined : 'inherit' // Basic mock
}}
>
{displayText} {displayText}
<span className="opacity-50 text-xs">{displaySeparator}</span> <span className="opacity-50 text-xs">{displaySeparator}</span>
</span> </span>

View File

@@ -37,17 +37,21 @@ export function ShoppableImageRenderer({ section, className }: { section: any; c
<div className="relative rounded-xl overflow-hidden bg-gray-100 aspect-[16/9] border-2 border-dashed border-gray-300 flex items-center justify-center"> <div className="relative rounded-xl overflow-hidden bg-gray-100 aspect-[16/9] border-2 border-dashed border-gray-300 flex items-center justify-center">
{displayImage ? ( {displayImage ? (
<>
<img src={displayImage} alt="Shoppable Preview" className="w-full h-full object-cover opacity-50" /> <img src={displayImage} alt="Shoppable Preview" className="w-full h-full object-cover opacity-50" />
{displayHotspots.map((hotspot: any, idx: number) => ( {displayHotspots.map((hotspot: any, idx: number) => {
<div const xVal = parseFloat(String(hotspot.x ?? 0).replace('%', '')) || 0;
key={idx} const yVal = parseFloat(String(hotspot.y ?? 0).replace('%', '')) || 0;
className="absolute w-6 h-6 rounded-full bg-primary text-white flex items-center justify-center border-2 border-white shadow-lg text-xs font-bold"
style={{ left: `${hotspot.x}%`, top: `${hotspot.y}%`, transform: 'translate(-50%, -50%)' }} return (
> <div
{idx + 1} key={idx}
</div> className="absolute w-6 h-6 rounded-full bg-primary text-white flex items-center justify-center border-2 border-white shadow-lg text-xs font-bold"
))} style={{ left: `${xVal}%`, top: `${yVal}%`, transform: 'translate(-50%, -50%)' }}
>
{idx + 1}
</div>
);
})}
</> </>
) : ( ) : (
<div className="text-center text-gray-400"> <div className="text-center text-gray-400">

View File

@@ -3,7 +3,7 @@ import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '@/lib/api'; import { api } from '@/lib/api';
import { __ } from '@/lib/i18n'; import { __ } from '@/lib/i18n';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Plus, Layout, Undo2, Save, Maximize2, Minimize2 } from 'lucide-react'; import { Plus, Layout, Undo2, Redo2, Save, Maximize2, Minimize2 } from 'lucide-react';
import { toast } from 'sonner'; import { toast } from 'sonner';
import { import {
AlertDialog, AlertDialog,
@@ -50,6 +50,11 @@ export default function AppearancePages() {
setInspectorCollapsed, setInspectorCollapsed,
setAvailableSources, setAvailableSources,
setIsLoading, setIsLoading,
undo,
redo,
past,
future,
updateCurrentPage,
addSection, addSection,
deleteSection, deleteSection,
duplicateSection, duplicateSection,
@@ -61,6 +66,7 @@ export default function AppearancePages() {
updateSectionStyles, updateSectionStyles,
updateElementStyles, updateElementStyles,
markAsSaved, markAsSaved,
markAsChanged,
setAsSpaLanding, setAsSpaLanding,
unsetSpaLanding, unsetSpaLanding,
} = usePageEditorStore(); } = usePageEditorStore();
@@ -160,7 +166,10 @@ export default function AppearancePages() {
const endpoint = currentPage.type === 'page' const endpoint = currentPage.type === 'page'
? `/pages/${currentPage.slug}` ? `/pages/${currentPage.slug}`
: `/templates/${currentPage.cpt}`; : `/templates/${currentPage.cpt}`;
return api.post(endpoint, { sections }); return api.post(endpoint, {
sections,
container_width: currentPage.containerWidth
});
}, },
onSuccess: () => { onSuccess: () => {
toast.success(__('Page saved successfully')); toast.success(__('Page saved successfully'));
@@ -332,17 +341,40 @@ export default function AppearancePages() {
{isFullscreen ? <Minimize2 className="w-4 h-4" /> : <Maximize2 className="w-4 h-4" />} {isFullscreen ? <Minimize2 className="w-4 h-4" /> : <Maximize2 className="w-4 h-4" />}
</Button> </Button>
{hasUnsavedChanges && ( {hasUnsavedChanges && (
<> <span className="text-sm text-amber-600">{__('Unsaved changes')}</span>
<span className="text-sm text-amber-600">{__('Unsaved changes')}</span> )}
<Button
variant="ghost" <div className="flex items-center rounded-md border bg-muted/50 p-0.5">
size="sm" <Button
onClick={handleDiscard} variant="ghost"
> size="icon"
<Undo2 className="w-4 h-4 mr-2" /> className="h-7 w-7 text-muted-foreground hover:text-foreground"
{__('Discard')} onClick={undo}
</Button> disabled={past.length === 0}
</> title={__('Undo')}
>
<Undo2 className="w-4 h-4" />
</Button>
<Button
variant="ghost"
size="icon"
className="h-7 w-7 text-muted-foreground hover:text-foreground"
onClick={redo}
disabled={future.length === 0}
title={__('Redo')}
>
<Redo2 className="w-4 h-4" />
</Button>
</div>
{hasUnsavedChanges && (
<Button
variant="ghost"
size="sm"
onClick={handleDiscard}
>
{__('Discard')}
</Button>
)} )}
<Button <Button
variant="outline" variant="outline"
@@ -455,10 +487,7 @@ export default function AppearancePages() {
onDeletePage={handleDeletePage} onDeletePage={handleDeletePage}
onDeleteTemplate={handleDeleteTemplate} onDeleteTemplate={handleDeleteTemplate}
onContainerWidthChange={(width) => { onContainerWidthChange={(width) => {
if (currentPage) { updateCurrentPage({ containerWidth: width });
setCurrentPage({ ...currentPage, containerWidth: width });
markAsSaved(); // Mark as changed so save button enables
}
}} }}
/> />
) )

View File

@@ -23,7 +23,9 @@ export interface SectionOption {
export interface StylableElementSchema { export interface StylableElementSchema {
name: string; name: string;
label: string; label: string;
type: 'text' | 'image'; type: 'text' | 'image' | 'container';
disableAlignment?: boolean;
disableBackground?: boolean;
} }
export interface SectionSchema { export interface SectionSchema {
@@ -53,7 +55,7 @@ export const SECTION_SCHEMAS: Record<string, SectionSchema> = {
fields: [ fields: [
{ name: 'title', label: 'Title', type: 'text', dynamic: true }, { name: 'title', label: 'Title', type: 'text', dynamic: true },
{ name: 'subtitle', label: 'Subtitle', type: 'text', dynamic: true }, { name: 'subtitle', label: 'Subtitle', type: 'text', dynamic: true },
{ name: 'image', label: 'Image URL', type: 'url', dynamic: true }, { name: 'image', label: 'Image', type: 'image', dynamic: true },
{ name: 'cta_text', label: 'Button Text', type: 'text' }, { name: 'cta_text', label: 'Button Text', type: 'text' },
{ name: 'cta_url', label: 'Button URL', type: 'url' }, { name: 'cta_url', label: 'Button URL', type: 'url' },
], ],
@@ -89,12 +91,12 @@ export const SECTION_SCHEMAS: Record<string, SectionSchema> = {
{ value: 'medium', label: 'Medium' }, { value: 'medium', label: 'Medium' },
], ],
stylableElements: [ stylableElements: [
{ name: 'heading', label: 'Headings', type: 'text' }, { name: 'content', label: 'Container', type: 'container', disableAlignment: true },
{ name: 'text', label: 'Body Text', type: 'text' }, { name: 'heading', label: 'Headings', type: 'text', disableAlignment: true },
{ name: 'link', label: 'Links', type: 'text' }, { name: 'text', label: 'Body Text', type: 'text', disableAlignment: true },
{ name: 'image', label: 'Images', type: 'image' }, { name: 'link', label: 'Links', type: 'text', disableAlignment: true },
{ name: 'image', label: 'Images', type: 'image', disableAlignment: true },
{ name: 'button', label: 'Button', type: 'text' }, { name: 'button', label: 'Button', type: 'text' },
{ name: 'content', label: 'Container', type: 'text' },
], ],
}, },
'image-text': { 'image-text': {
@@ -111,7 +113,7 @@ export const SECTION_SCHEMAS: Record<string, SectionSchema> = {
fields: [ fields: [
{ name: 'title', label: 'Title', type: 'text', dynamic: true }, { name: 'title', label: 'Title', type: 'text', dynamic: true },
{ name: 'text', label: 'Text', type: 'textarea', dynamic: true }, { name: 'text', label: 'Text', type: 'textarea', dynamic: true },
{ name: 'image', label: 'Image URL', type: 'url', dynamic: true }, { name: 'image', label: 'Image', type: 'image', dynamic: true },
{ name: 'cta_text', label: 'Button Text', type: 'text' }, { name: 'cta_text', label: 'Button Text', type: 'text' },
{ name: 'cta_url', label: 'Button URL', type: 'url' }, { name: 'cta_url', label: 'Button URL', type: 'url' },
], ],
@@ -145,6 +147,7 @@ export const SECTION_SCHEMAS: Record<string, SectionSchema> = {
stylableElements: [ stylableElements: [
{ name: 'heading', label: 'Heading', type: 'text' }, { name: 'heading', label: 'Heading', type: 'text' },
{ name: 'feature_item', label: 'Feature Item (Card)', type: 'text' }, { name: 'feature_item', label: 'Feature Item (Card)', type: 'text' },
{ name: 'link', label: 'Link (Read more)', type: 'text' },
], ],
}, },
'cta-banner': { 'cta-banner': {
@@ -177,6 +180,14 @@ export const SECTION_SCHEMAS: Record<string, SectionSchema> = {
title: { type: 'static', value: 'Contact Us' }, title: { type: 'static', value: 'Contact Us' },
webhook_url: { type: 'static', value: '' }, webhook_url: { type: 'static', value: '' },
redirect_url: { type: 'static', value: '' }, redirect_url: { type: 'static', value: '' },
fields: {
type: 'static',
value: [
{ name: 'name', label: 'Your Name', type: 'text', required: true },
{ name: 'email', label: 'Your Email', type: 'email', required: true },
{ name: 'message', label: 'Your Message', type: 'textarea', required: true },
]
}
}, },
fields: [ fields: [
{ name: 'title', label: 'Title', type: 'text' }, { name: 'title', label: 'Title', type: 'text' },
@@ -231,8 +242,8 @@ export const SECTION_SCHEMAS: Record<string, SectionSchema> = {
{ value: 'featured', label: 'Featured' }, { value: 'featured', label: 'Featured' },
], ],
stylableElements: [ stylableElements: [
{ name: 'title', label: 'Title', type: 'text' }, { name: 'title', label: 'Title', type: 'text', disableAlignment: true },
{ name: 'subtitle', label: 'Subtitle', type: 'text' }, { name: 'subtitle', label: 'Subtitle', type: 'text', disableAlignment: true },
], ],
}, },
'shoppable-image': { 'shoppable-image': {
@@ -249,11 +260,12 @@ export const SECTION_SCHEMAS: Record<string, SectionSchema> = {
fields: [ fields: [
{ name: 'title', label: 'Title', type: 'text' }, { name: 'title', label: 'Title', type: 'text' },
{ name: 'subtitle', label: 'Subtitle', type: 'text' }, { name: 'subtitle', label: 'Subtitle', type: 'text' },
{ name: 'image', label: 'Image URL', type: 'url' }, { name: 'image', label: 'Image', type: 'image' },
{ name: 'alt', label: 'Image Alt Text', type: 'text' }, { name: 'alt', label: 'Image Alt Text', type: 'text' },
], ],
stylableElements: [ stylableElements: [
{ name: 'title', label: 'Title', type: 'text' }, { name: 'title', label: 'Title', type: 'text' },
{ name: 'subtitle', label: 'Subtitle', type: 'text' },
], ],
}, },
'marquee-banner': { 'marquee-banner': {
@@ -270,6 +282,9 @@ export const SECTION_SCHEMAS: Record<string, SectionSchema> = {
{ name: 'separator', label: 'Separator', type: 'text' }, { name: 'separator', label: 'Separator', type: 'text' },
{ name: 'speed', label: 'Speed (seconds)', type: 'text' }, { name: 'speed', label: 'Speed (seconds)', type: 'text' },
], ],
stylableElements: [
{ name: 'text', label: 'Banner Text', type: 'text', disableBackground: true, disableAlignment: true },
],
}, },
}; };

View File

@@ -21,6 +21,11 @@ export interface SectionStyles {
paddingTop?: string; paddingTop?: string;
paddingBottom?: string; paddingBottom?: string;
contentWidth?: 'full' | 'contained' | 'boxed'; contentWidth?: 'full' | 'contained' | 'boxed';
cardBackgroundColor?: string;
cardPaddingTop?: string;
cardPaddingRight?: string;
cardPaddingBottom?: string;
cardPaddingLeft?: string;
heightPreset?: string; heightPreset?: string;
dynamicBackground?: string; // e.g. 'post_featured_image' dynamicBackground?: string; // e.g. 'post_featured_image'
} }
@@ -34,6 +39,8 @@ export interface ElementStyle {
// Image specific // Image specific
objectFit?: 'cover' | 'contain' | 'fill'; objectFit?: 'cover' | 'contain' | 'fill';
objectPosition?: string;
alignment?: 'left' | 'center' | 'right';
backgroundColor?: string; // Wrapper BG backgroundColor?: string; // Wrapper BG
width?: string; width?: string;
height?: string; height?: string;
@@ -73,6 +80,10 @@ export interface PageItem {
isSpaLanding?: boolean; isSpaLanding?: boolean;
containerWidth?: 'boxed' | 'fullwidth' | 'default'; containerWidth?: 'boxed' | 'fullwidth' | 'default';
} }
interface HistoryState {
sections: Section[];
currentPage: PageItem | null;
}
interface PageEditorState { interface PageEditorState {
// Current page/template being edited // Current page/template being edited
@@ -91,6 +102,10 @@ interface PageEditorState {
hasUnsavedChanges: boolean; hasUnsavedChanges: boolean;
isLoading: boolean; isLoading: boolean;
// History (Undo/Redo)
past: HistoryState[];
future: HistoryState[];
// Available sources for dynamic fields (CPT templates) // Available sources for dynamic fields (CPT templates)
availableSources: { value: string; label: string }[]; availableSources: { value: string; label: string }[];
@@ -104,6 +119,14 @@ interface PageEditorState {
setAvailableSources: (sources: { value: string; label: string }[]) => void; setAvailableSources: (sources: { value: string; label: string }[]) => void;
setIsLoading: (loading: boolean) => void; setIsLoading: (loading: boolean) => void;
// History actions
undo: () => void;
redo: () => void;
pushHistory: () => void;
// Page updates
updateCurrentPage: (updates: Partial<PageItem>) => void;
// Section actions // Section actions
addSection: (type: string, index?: number) => void; addSection: (type: string, index?: number) => void;
deleteSection: (id: string) => void; deleteSection: (id: string) => void;
@@ -137,11 +160,13 @@ export const usePageEditorStore = create<PageEditorState>((set, get) => ({
inspectorCollapsed: false, inspectorCollapsed: false,
hasUnsavedChanges: false, hasUnsavedChanges: false,
isLoading: false, isLoading: false,
past: [],
future: [],
availableSources: [], availableSources: [],
// Setters // Setters
setCurrentPage: (currentPage) => set({ currentPage }), setCurrentPage: (currentPage) => set({ currentPage }),
setSections: (sections) => set({ sections, hasUnsavedChanges: true }), setSections: (sections) => set({ sections, hasUnsavedChanges: true, past: [], future: [] }),
setSelectedSection: (selectedSectionId) => set({ selectedSectionId }), setSelectedSection: (selectedSectionId) => set({ selectedSectionId }),
setHoveredSection: (hoveredSectionId) => set({ hoveredSectionId }), setHoveredSection: (hoveredSectionId) => set({ hoveredSectionId }),
setDeviceMode: (deviceMode) => set({ deviceMode }), setDeviceMode: (deviceMode) => set({ deviceMode }),
@@ -149,9 +174,64 @@ export const usePageEditorStore = create<PageEditorState>((set, get) => ({
setAvailableSources: (availableSources) => set({ availableSources }), setAvailableSources: (availableSources) => set({ availableSources }),
setIsLoading: (isLoading) => set({ isLoading }), setIsLoading: (isLoading) => set({ isLoading }),
// History actions
pushHistory: () => {
const { sections, currentPage } = get();
set((state) => ({
past: [...state.past, {
sections: JSON.parse(JSON.stringify(sections)),
currentPage: JSON.parse(JSON.stringify(currentPage))
}],
future: []
}));
},
undo: () => {
const { past, future, sections, currentPage } = get();
if (past.length === 0) return;
const previous = past[past.length - 1];
const newPast = past.slice(0, past.length - 1);
set({
past: newPast,
future: [{ sections, currentPage }, ...future],
sections: previous.sections,
currentPage: previous.currentPage,
hasUnsavedChanges: true
});
},
redo: () => {
const { past, future, sections, currentPage } = get();
if (future.length === 0) return;
const next = future[0];
const newFuture = future.slice(1);
set({
past: [...past, { sections, currentPage }],
future: newFuture,
sections: next.sections,
currentPage: next.currentPage,
hasUnsavedChanges: true
});
},
// Page updates
updateCurrentPage: (updates) => {
const { currentPage, pushHistory } = get();
if (!currentPage) return;
pushHistory();
set({
currentPage: { ...currentPage, ...updates },
hasUnsavedChanges: true
});
},
// Section actions // Section actions
addSection: (type, index) => { addSection: (type, index) => {
const { sections } = get(); const { sections, pushHistory } = get();
const sectionConfig = getSectionSchema(type); const sectionConfig = getSectionSchema(type);
if (!sectionConfig) return; if (!sectionConfig) return;
@@ -163,6 +243,8 @@ export const usePageEditorStore = create<PageEditorState>((set, get) => ({
styles: cloneDefaultStyles(type) as SectionStyles, styles: cloneDefaultStyles(type) as SectionStyles,
}; };
pushHistory();
const newSections = [...sections]; const newSections = [...sections];
if (typeof index === 'number') { if (typeof index === 'number') {
newSections.splice(index, 0, newSection); newSections.splice(index, 0, newSection);
@@ -177,7 +259,8 @@ export const usePageEditorStore = create<PageEditorState>((set, get) => ({
}, },
deleteSection: (id) => { deleteSection: (id) => {
const { sections, selectedSectionId } = get(); const { sections, selectedSectionId, pushHistory } = get();
pushHistory();
const newSections = sections.filter(s => s.id !== id); const newSections = sections.filter(s => s.id !== id);
set({ set({
@@ -188,10 +271,12 @@ export const usePageEditorStore = create<PageEditorState>((set, get) => ({
}, },
duplicateSection: (id) => { duplicateSection: (id) => {
const { sections } = get(); const { sections, pushHistory } = get();
const index = sections.findIndex(s => s.id === id); const index = sections.findIndex(s => s.id === id);
if (index === -1) return; if (index === -1) return;
pushHistory();
const section = sections[index]; const section = sections[index];
const newSection: Section = { const newSection: Section = {
...JSON.parse(JSON.stringify(section)), // Deep clone ...JSON.parse(JSON.stringify(section)), // Deep clone
@@ -205,27 +290,32 @@ export const usePageEditorStore = create<PageEditorState>((set, get) => ({
}, },
moveSection: (id, direction) => { moveSection: (id, direction) => {
const { sections } = get(); const { sections, pushHistory } = get();
const index = sections.findIndex(s => s.id === id); const index = sections.findIndex(s => s.id === id);
if (index === -1) return; if (index === -1) return;
if (direction === 'up' && index > 0) { if (direction === 'up' && index > 0) {
pushHistory();
const newSections = [...sections]; const newSections = [...sections];
[newSections[index], newSections[index - 1]] = [newSections[index - 1], newSections[index]]; [newSections[index], newSections[index - 1]] = [newSections[index - 1], newSections[index]];
set({ sections: newSections, hasUnsavedChanges: true }); set({ sections: newSections, hasUnsavedChanges: true });
} else if (direction === 'down' && index < sections.length - 1) { } else if (direction === 'down' && index < sections.length - 1) {
pushHistory();
const newSections = [...sections]; const newSections = [...sections];
[newSections[index], newSections[index + 1]] = [newSections[index + 1], newSections[index]]; [newSections[index], newSections[index + 1]] = [newSections[index + 1], newSections[index]];
set({ sections: newSections, hasUnsavedChanges: true }); set({ sections: newSections, hasUnsavedChanges: true });
} }
}, },
reorderSections: (sections) => { reorderSections: (newSections) => {
set({ sections, hasUnsavedChanges: true }); const { sections, pushHistory } = get();
pushHistory();
set({ sections: newSections, hasUnsavedChanges: true });
}, },
updateSectionProp: (sectionId, propName, value) => { updateSectionProp: (sectionId, propName, value) => {
const { sections } = get(); const { sections, pushHistory } = get();
pushHistory();
const newSections = sections.map(section => { const newSections = sections.map(section => {
if (section.id !== sectionId) return section; if (section.id !== sectionId) return section;
return { return {
@@ -240,7 +330,8 @@ export const usePageEditorStore = create<PageEditorState>((set, get) => ({
}, },
updateSectionLayout: (sectionId, layoutVariant) => { updateSectionLayout: (sectionId, layoutVariant) => {
const { sections } = get(); const { sections, pushHistory } = get();
pushHistory();
const newSections = sections.map(section => { const newSections = sections.map(section => {
if (section.id !== sectionId) return section; if (section.id !== sectionId) return section;
return { return {
@@ -252,7 +343,8 @@ export const usePageEditorStore = create<PageEditorState>((set, get) => ({
}, },
updateSectionColorScheme: (sectionId, colorScheme) => { updateSectionColorScheme: (sectionId, colorScheme) => {
const { sections } = get(); const { sections, pushHistory } = get();
pushHistory();
const newSections = sections.map(section => { const newSections = sections.map(section => {
if (section.id !== sectionId) return section; if (section.id !== sectionId) return section;
return { return {
@@ -264,7 +356,8 @@ export const usePageEditorStore = create<PageEditorState>((set, get) => ({
}, },
updateSectionStyles: (sectionId, styles) => { updateSectionStyles: (sectionId, styles) => {
const { sections } = get(); const { sections, pushHistory } = get();
pushHistory();
const newSections = sections.map(section => { const newSections = sections.map(section => {
if (section.id !== sectionId) return section; if (section.id !== sectionId) return section;
return { return {
@@ -279,7 +372,8 @@ export const usePageEditorStore = create<PageEditorState>((set, get) => ({
}, },
updateElementStyles: (sectionId, fieldName, styles) => { updateElementStyles: (sectionId, fieldName, styles) => {
const { sections } = get(); const { sections, pushHistory } = get();
pushHistory();
const newSections = sections.map(section => { const newSections = sections.map(section => {
if (section.id !== sectionId) return section; if (section.id !== sectionId) return section;

View File

@@ -19,6 +19,7 @@ export default function AppearanceShop() {
const [gridStyle, setGridStyle] = useState('standard'); const [gridStyle, setGridStyle] = useState('standard');
const [cardStyle, setCardStyle] = useState('card'); const [cardStyle, setCardStyle] = useState('card');
const [aspectRatio, setAspectRatio] = useState('square'); const [aspectRatio, setAspectRatio] = useState('square');
const [filterLayout, setFilterLayout] = useState('basic');
const [elements, setElements] = useState({ const [elements, setElements] = useState({
category_filter: true, category_filter: true,
@@ -50,6 +51,7 @@ export default function AppearanceShop() {
setCardStyle(shop.layout?.card_style || 'card'); setCardStyle(shop.layout?.card_style || 'card');
setAspectRatio(shop.layout?.aspect_ratio || 'square'); setAspectRatio(shop.layout?.aspect_ratio || 'square');
setCardTextAlign(shop.layout?.card_text_align || 'left'); setCardTextAlign(shop.layout?.card_text_align || 'left');
setFilterLayout(shop.layout?.filter_layout || 'basic');
if (shop.elements) { if (shop.elements) {
setElements(shop.elements); setElements(shop.elements);
@@ -83,7 +85,8 @@ export default function AppearanceShop() {
grid_style: gridStyle, grid_style: gridStyle,
card_style: cardStyle, card_style: cardStyle,
aspect_ratio: aspectRatio, aspect_ratio: aspectRatio,
card_text_align: cardTextAlign card_text_align: cardTextAlign,
filter_layout: filterLayout
}, },
elements: { elements: {
category_filter: elements.category_filter, category_filter: elements.category_filter,
@@ -181,6 +184,18 @@ export default function AppearanceShop() {
</Select> </Select>
</SettingsSection> </SettingsSection>
<SettingsSection label="Filter Layout" htmlFor="filter-layout" description="Choose how catalog filters are presented">
<Select value={filterLayout} onValueChange={setFilterLayout}>
<SelectTrigger id="filter-layout">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="basic">Basic - Horizontal Top Bar</SelectItem>
<SelectItem value="rich_sidebar">Rich - Left Sidebar</SelectItem>
</SelectContent>
</Select>
</SettingsSection>
<SettingsSection label="Product Card Style" htmlFor="card-style" description="Visual style adapts to column count - more columns = cleaner style"> <SettingsSection label="Product Card Style" htmlFor="card-style" description="Visual style adapts to column count - more columns = cleaner style">
<Select value={cardStyle} onValueChange={setCardStyle}> <Select value={cardStyle} onValueChange={setCardStyle}>
<SelectTrigger id="card-style"> <SelectTrigger id="card-style">

View File

@@ -33,6 +33,8 @@ interface Referral {
currency: string; currency: string;
created_at: string; created_at: string;
approved_at?: string; approved_at?: string;
utm_campaign?: string;
utm_source?: string;
} }
export default function AffiliatesReferrals() { export default function AffiliatesReferrals() {
@@ -88,7 +90,7 @@ export default function AffiliatesReferrals() {
// Export to CSV // Export to CSV
const exportToCSV = () => { const exportToCSV = () => {
const headers = ['ID', 'Affiliate', 'Order ID', 'Status', 'Commission', 'Currency', 'Created At']; const headers = ['ID', 'Affiliate', 'Order ID', 'Status', 'Commission', 'Currency', 'Campaign', 'Created At'];
const rows = filteredReferrals.map(ref => [ const rows = filteredReferrals.map(ref => [
ref.id, ref.id,
ref.affiliate_name || `Affiliate #${ref.affiliate_id}`, ref.affiliate_name || `Affiliate #${ref.affiliate_id}`,
@@ -96,6 +98,7 @@ export default function AffiliatesReferrals() {
ref.status, ref.status,
ref.commission_amount, ref.commission_amount,
ref.currency, ref.currency,
[ref.utm_campaign, ref.utm_source].filter(Boolean).join(' / '),
new Date(ref.created_at).toISOString() new Date(ref.created_at).toISOString()
]); ]);
@@ -135,7 +138,7 @@ export default function AffiliatesReferrals() {
}; };
// Stats // Stats
const totalCommissions = filteredReferrals.reduce((sum, r) => sum + parseFloat(r.commission_amount || 0), 0); const totalCommissions = filteredReferrals.reduce((sum, r) => sum + parseFloat(r.commission_amount || '0'), 0);
const pendingCount = filteredReferrals.filter(r => r.status === 'pending').length; const pendingCount = filteredReferrals.filter(r => r.status === 'pending').length;
const approvedCount = filteredReferrals.filter(r => r.status === 'approved').length; const approvedCount = filteredReferrals.filter(r => r.status === 'approved').length;
@@ -311,6 +314,7 @@ export default function AffiliatesReferrals() {
<TableHead>{__('Affiliate')}</TableHead> <TableHead>{__('Affiliate')}</TableHead>
<TableHead>{__('Order ID')}</TableHead> <TableHead>{__('Order ID')}</TableHead>
<TableHead>{__('Status')}</TableHead> <TableHead>{__('Status')}</TableHead>
<TableHead>{__('Campaign')}</TableHead>
<TableHead>{__('Date')}</TableHead> <TableHead>{__('Date')}</TableHead>
<TableHead className="text-right">{__('Commission')}</TableHead> <TableHead className="text-right">{__('Commission')}</TableHead>
</TableRow> </TableRow>
@@ -336,6 +340,9 @@ export default function AffiliatesReferrals() {
{ref.status} {ref.status}
</span> </span>
</TableCell> </TableCell>
<TableCell className="text-muted-foreground text-sm">
{[ref.utm_campaign, ref.utm_source].filter(Boolean).join(' / ') || '—'}
</TableCell>
<TableCell className="text-muted-foreground"> <TableCell className="text-muted-foreground">
{new Date(ref.created_at).toLocaleDateString('id-ID', { {new Date(ref.created_at).toLocaleDateString('id-ID', {
year: 'numeric', year: 'numeric',

View File

@@ -18,6 +18,7 @@ import {
import { api } from '@/lib/api'; import { api } from '@/lib/api';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { __ } from '@/lib/i18n'; import { __ } from '@/lib/i18n';
import { toast } from 'sonner';
import { import {
Table, Table,
TableBody, TableBody,

View File

@@ -30,7 +30,7 @@ import {
SelectValue, SelectValue,
} from '@/components/ui/select'; } from '@/components/ui/select';
import { Label } from '@/components/ui/label'; import { Label } from '@/components/ui/label';
import { Search, Package, Plus, History, Download, Loader2 } from 'lucide-react'; import { Search, Package, Plus, History, Download, Loader2, ChevronDown, ChevronRight, X, Pencil } from 'lucide-react';
import { toast } from 'sonner'; import { toast } from 'sonner';
import { __ } from '@/lib/i18n'; import { __ } from '@/lib/i18n';
@@ -43,11 +43,21 @@ interface SoftwareProduct {
total_downloads: number; total_downloads: number;
} }
interface ChangelogPoint {
type: string;
text: string;
}
interface ChangelogData {
narrative: string;
points: ChangelogPoint[];
}
interface SoftwareVersion { interface SoftwareVersion {
id: number; id: number;
product_id: number; product_id: number;
version: string; version: string;
changelog: string; changelog: ChangelogData | string;
release_date: string; release_date: string;
is_current: boolean; is_current: boolean;
download_count: number; download_count: number;
@@ -72,7 +82,13 @@ export default function SoftwareVersions() {
const [search, setSearch] = useState(''); const [search, setSearch] = useState('');
const [selectedProduct, setSelectedProduct] = useState<number | null>(null); const [selectedProduct, setSelectedProduct] = useState<number | null>(null);
const [isAddVersionOpen, setIsAddVersionOpen] = useState(false); const [isAddVersionOpen, setIsAddVersionOpen] = useState(false);
const [newVersion, setNewVersion] = useState({ version: '', changelog: '' }); const [editingVersionId, setEditingVersionId] = useState<number | null>(null);
const [newVersion, setNewVersion] = useState({
version: '',
changelog: { narrative: '', points: [] as ChangelogPoint[] }
});
const [expandedVersions, setExpandedVersions] = useState<Record<number, boolean>>({});
const queryClient = useQueryClient(); const queryClient = useQueryClient();
// Fetch software-enabled products // Fetch software-enabled products
@@ -80,15 +96,14 @@ export default function SoftwareVersions() {
queryKey: ['software-products'], queryKey: ['software-products'],
queryFn: async () => { queryFn: async () => {
const response = await api.get('/products?software_enabled=true&per_page=100'); const response = await api.get('/products?software_enabled=true&per_page=100');
// Filter products that have software distribution enabled const products = (response as any).rows || [];
const products = (response as any).products || [];
return { return {
products: products.filter((p: any) => p.meta?._woonoow_software_enabled === 'yes').map((p: any) => ({ products: products.map((p: any) => ({
id: p.id, id: p.id,
name: p.name, name: p.name,
slug: p.meta?._woonoow_software_slug || '', slug: p.software_slug || p.meta?._woonoow_software_slug || '',
current_version: p.meta?._woonoow_software_current_version || '', current_version: p.software_current_version || p.meta?._woonoow_software_current_version || '',
wp_enabled: p.meta?._woonoow_software_wp_enabled === 'yes', wp_enabled: p.software_wp_enabled || p.meta?._woonoow_software_wp_enabled === 'yes',
total_downloads: 0, total_downloads: 0,
})) }))
} as ProductsResponse; } as ProductsResponse;
@@ -107,21 +122,121 @@ export default function SoftwareVersions() {
// Add new version mutation // Add new version mutation
const addVersion = useMutation({ const addVersion = useMutation({
mutationFn: async (data: { version: string; changelog: string }) => { mutationFn: async (data: { version: string; changelog: ChangelogData }) => {
return await api.post(`/software/products/${selectedProduct}/versions`, data); return await api.post(`/software/products/${selectedProduct}/versions`, data);
}, },
onSuccess: () => { onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['software-versions', selectedProduct] }); queryClient.invalidateQueries({ queryKey: ['software-versions', selectedProduct] });
queryClient.invalidateQueries({ queryKey: ['software-products'] }); queryClient.invalidateQueries({ queryKey: ['software-products'] });
toast.success(__('Version added successfully')); toast.success(__('Version added successfully'));
setIsAddVersionOpen(false); closeModal();
setNewVersion({ version: '', changelog: '' });
}, },
onError: (error: any) => { onError: (error: any) => {
toast.error(error.message || __('Failed to add version')); toast.error(error.message || __('Failed to add version'));
}, },
}); });
// Edit version mutation
const editVersion = useMutation({
mutationFn: async (data: { version_id: number; version: string; changelog: ChangelogData }) => {
return await api.put(`/software/products/${selectedProduct}/versions/${data.version_id}`, {
version: data.version,
changelog: data.changelog
});
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['software-versions', selectedProduct] });
queryClient.invalidateQueries({ queryKey: ['software-products'] });
toast.success(__('Version updated successfully'));
closeModal();
},
onError: (error: any) => {
toast.error(error.message || __('Failed to update version'));
},
});
const openAddModal = () => {
setEditingVersionId(null);
setNewVersion({ version: '', changelog: { narrative: '', points: [] } });
setIsAddVersionOpen(true);
};
const openEditModal = (version: SoftwareVersion, e: React.MouseEvent) => {
e.stopPropagation();
const cl = typeof version.changelog === 'object' && version.changelog !== null
? (version.changelog as ChangelogData)
: { narrative: version.changelog as string, points: [] };
setEditingVersionId(version.id);
setNewVersion({
version: version.version,
changelog: { narrative: cl.narrative || '', points: cl.points || [] }
});
setIsAddVersionOpen(true);
};
const closeModal = () => {
setIsAddVersionOpen(false);
setEditingVersionId(null);
setNewVersion({ version: '', changelog: { narrative: '', points: [] } });
};
const handleSaveVersion = () => {
if (editingVersionId) {
editVersion.mutate({
version_id: editingVersionId,
...newVersion
});
} else {
addVersion.mutate(newVersion);
}
};
const toggleVersion = (id: number) => {
setExpandedVersions(prev => ({
...prev,
[id]: !prev[id]
}));
};
const addChangelogPoint = () => {
setNewVersion(prev => ({
...prev,
changelog: {
...prev.changelog,
points: [...prev.changelog.points, { type: 'ADD', text: '' }]
}
}));
};
const updateChangelogPoint = (index: number, field: 'type' | 'text', value: string) => {
setNewVersion(prev => {
const newPoints = [...prev.changelog.points];
newPoints[index] = { ...newPoints[index], [field]: value };
return {
...prev,
changelog: {
...prev.changelog,
points: newPoints
}
};
});
};
const removeChangelogPoint = (index: number) => {
setNewVersion(prev => {
const newPoints = [...prev.changelog.points];
newPoints.splice(index, 1);
return {
...prev,
changelog: {
...prev.changelog,
points: newPoints
}
};
});
};
const filteredProducts = productsData?.products?.filter(p => const filteredProducts = productsData?.products?.filter(p =>
p.name.toLowerCase().includes(search.toLowerCase()) || p.name.toLowerCase().includes(search.toLowerCase()) ||
p.slug.toLowerCase().includes(search.toLowerCase()) p.slug.toLowerCase().includes(search.toLowerCase())
@@ -129,9 +244,20 @@ export default function SoftwareVersions() {
const selectedProductData = productsData?.products?.find(p => p.id === selectedProduct); const selectedProductData = productsData?.products?.find(p => p.id === selectedProduct);
const getBadgeColor = (type: string) => {
switch (type) {
case 'ADD': return 'bg-emerald-500 hover:bg-emerald-600';
case 'FIX': return 'bg-orange-500 hover:bg-orange-600';
case 'IMPROVE': return 'bg-blue-500 hover:bg-blue-600';
case 'DROP': return 'bg-rose-500 hover:bg-rose-600';
default: return 'bg-gray-500 hover:bg-gray-600';
}
};
const isSaving = addVersion.isPending || editVersion.isPending;
return ( return (
<div className="p-6 space-y-6"> <div className="p-6 space-y-6">
{/* Header */}
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div> <div>
<h1 className="text-2xl font-bold">{__('Software Versions')}</h1> <h1 className="text-2xl font-bold">{__('Software Versions')}</h1>
@@ -142,7 +268,6 @@ export default function SoftwareVersions() {
</div> </div>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6"> <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
{/* Products List */}
<div className="lg:col-span-1 border rounded-lg bg-card"> <div className="lg:col-span-1 border rounded-lg bg-card">
<div className="p-4 border-b"> <div className="p-4 border-b">
<h2 className="font-semibold mb-3">{__('Software Products')}</h2> <h2 className="font-semibold mb-3">{__('Software Products')}</h2>
@@ -152,7 +277,7 @@ export default function SoftwareVersions() {
placeholder={__('Search products...')} placeholder={__('Search products...')}
value={search} value={search}
onChange={(e) => setSearch(e.target.value)} onChange={(e) => setSearch(e.target.value)}
className="pl-9" className="!pl-9"
/> />
</div> </div>
</div> </div>
@@ -176,8 +301,7 @@ export default function SoftwareVersions() {
<button <button
key={product.id} key={product.id}
onClick={() => setSelectedProduct(product.id)} onClick={() => setSelectedProduct(product.id)}
className={`w-full p-4 text-left hover:bg-accent transition-colors ${selectedProduct === product.id ? 'bg-accent' : '' className={`w-full p-4 text-left hover:bg-accent transition-colors ${selectedProduct === product.id ? 'bg-accent' : ''}`}
}`}
> >
<div className="flex items-start justify-between"> <div className="flex items-start justify-between">
<div className="flex-1 min-w-0"> <div className="flex-1 min-w-0">
@@ -186,7 +310,7 @@ export default function SoftwareVersions() {
{product.slug} {product.slug}
</p> </p>
</div> </div>
<Badge variant="secondary" className="ml-2"> <Badge variant="secondary" className="ml-2 whitespace-nowrap">
v{product.current_version || '—'} v{product.current_version || '—'}
</Badge> </Badge>
</div> </div>
@@ -202,7 +326,6 @@ export default function SoftwareVersions() {
</div> </div>
</div> </div>
{/* Version Details */}
<div className="lg:col-span-2 border rounded-lg bg-card"> <div className="lg:col-span-2 border rounded-lg bg-card">
{!selectedProduct ? ( {!selectedProduct ? (
<div className="flex items-center justify-center h-full min-h-[400px] text-muted-foreground"> <div className="flex items-center justify-center h-full min-h-[400px] text-muted-foreground">
@@ -217,7 +340,6 @@ export default function SoftwareVersions() {
</div> </div>
) : ( ) : (
<> <>
{/* Version Header */}
<div className="p-4 border-b flex items-center justify-between"> <div className="p-4 border-b flex items-center justify-between">
<div> <div>
<h2 className="font-semibold">{selectedProductData?.name}</h2> <h2 className="font-semibold">{selectedProductData?.name}</h2>
@@ -225,21 +347,25 @@ export default function SoftwareVersions() {
{__('Current version')}: <span className="font-mono">{versionsData?.config?.current_version || '—'}</span> {__('Current version')}: <span className="font-mono">{versionsData?.config?.current_version || '—'}</span>
</p> </p>
</div> </div>
<Dialog open={isAddVersionOpen} onOpenChange={setIsAddVersionOpen}> <Dialog open={isAddVersionOpen} onOpenChange={(open) => !open ? closeModal() : setIsAddVersionOpen(true)}>
<DialogTrigger asChild> <DialogTrigger asChild>
<Button> <Button onClick={openAddModal}>
<Plus className="w-4 h-4 mr-2" /> <Plus className="w-4 h-4 mr-2" />
{__('New Version')} {__('New Version')}
</Button> </Button>
</DialogTrigger> </DialogTrigger>
<DialogContent className="max-w-lg"> <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
<DialogHeader> <DialogHeader>
<DialogTitle>{__('Add New Version')}</DialogTitle> <DialogTitle>
{editingVersionId ? __('Edit Version') : __('Add New Version')}
</DialogTitle>
<DialogDescription> <DialogDescription>
{__('Release a new version of')} {selectedProductData?.name} {editingVersionId
? `${__('Modify release details for')} ${selectedProductData?.name}`
: `${__('Release a new version of')} ${selectedProductData?.name}`}
</DialogDescription> </DialogDescription>
</DialogHeader> </DialogHeader>
<div className="space-y-4 px-6 py-4"> <div className="space-y-6 px-6 py-4">
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="version">{__('Version Number')}</Label> <Label htmlFor="version">{__('Version Number')}</Label>
<Input <Input
@@ -248,92 +374,195 @@ export default function SoftwareVersions() {
value={newVersion.version} value={newVersion.version}
onChange={(e) => setNewVersion(prev => ({ ...prev, version: e.target.value }))} onChange={(e) => setNewVersion(prev => ({ ...prev, version: e.target.value }))}
/> />
<p className="text-xs text-muted-foreground">
{__('Use semantic versioning (e.g., 1.0.0, 1.2.3)')}
</p>
</div> </div>
<div className="space-y-2"> <div className="space-y-4">
<Label htmlFor="changelog">{__('Changelog')}</Label> <div className="space-y-2">
<Textarea <Label htmlFor="narrative">{__('Changelog Narrative (Optional)')}</Label>
id="changelog" <Textarea
placeholder="## What's New&#10;- Added new feature&#10;- Fixed bug" id="narrative"
value={newVersion.changelog} placeholder={__('Provide a general overview of this release...')}
onChange={(e) => setNewVersion(prev => ({ ...prev, changelog: e.target.value }))} value={newVersion.changelog.narrative}
rows={8} onChange={(e) => setNewVersion(prev => ({
className="font-mono text-sm" ...prev,
/> changelog: { ...prev.changelog, narrative: e.target.value }
<p className="text-xs text-muted-foreground"> }))}
{__('Supports Markdown formatting')} className="min-h-[100px]"
</p> />
</div>
<div className="space-y-3">
<div className="flex items-center justify-between">
<Label>{__('Changes List')}</Label>
</div>
{newVersion.changelog.points.length === 0 ? (
<div className="text-center p-6 border rounded-md border-dashed text-muted-foreground">
<p className="text-sm">{__('No changes added yet.')}</p>
</div>
) : (
<div className="space-y-3">
{newVersion.changelog.points.map((point, index) => (
<div key={index} className="flex items-start gap-2">
<Select
value={point.type}
onValueChange={(val) => updateChangelogPoint(index, 'type', val)}
>
<SelectTrigger className="w-[130px]">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="ADD">{__('ADD')}</SelectItem>
<SelectItem value="FIX">{__('FIX')}</SelectItem>
<SelectItem value="IMPROVE">{__('IMPROVE')}</SelectItem>
<SelectItem value="DROP">{__('DROP')}</SelectItem>
<SelectItem value="OTHER">{__('OTHER')}</SelectItem>
</SelectContent>
</Select>
<Input
value={point.text}
onChange={(e) => updateChangelogPoint(index, 'text', e.target.value)}
placeholder={__('Describe the change...')}
className="flex-1"
/>
<Button
variant="ghost"
size="icon"
onClick={() => removeChangelogPoint(index)}
className="text-muted-foreground hover:text-destructive shrink-0"
>
<X className="w-4 h-4" />
</Button>
</div>
))}
</div>
)}
<Button variant="outline" size="sm" onClick={addChangelogPoint} className="w-full">
<Plus className="w-4 h-4 mr-2" />
{__('Add Change Item')}
</Button>
</div>
</div> </div>
</div> </div>
<DialogFooter> <DialogFooter>
<Button variant="outline" onClick={() => setIsAddVersionOpen(false)}> <Button variant="outline" onClick={closeModal} disabled={isSaving}>
{__('Cancel')} {__('Cancel')}
</Button> </Button>
<Button <Button
onClick={() => addVersion.mutate(newVersion)} onClick={handleSaveVersion}
disabled={!newVersion.version || addVersion.isPending} disabled={!newVersion.version || isSaving}
> >
{addVersion.isPending && <Loader2 className="w-4 h-4 mr-2 animate-spin" />} {isSaving && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
{__('Release Version')} {editingVersionId ? __('Save Changes') : __('Release Version')}
</Button> </Button>
</DialogFooter> </DialogFooter>
</DialogContent> </DialogContent>
</Dialog> </Dialog>
</div> </div>
{/* Version History */}
<div className="p-4"> <div className="p-4">
{versionsData?.versions?.length === 0 ? ( {versionsData?.versions?.length === 0 ? (
<div className="text-center py-12 text-muted-foreground"> <div className="text-center py-12 text-muted-foreground">
<History className="w-12 h-12 mx-auto mb-3 opacity-50" /> <History className="w-12 h-12 mx-auto mb-3 opacity-50" />
<p>{__('No versions released yet')}</p> <p>{__('No versions released yet')}</p>
<p className="text-sm mt-1">
{__('Click "New Version" to release your first version')}
</p>
</div> </div>
) : ( ) : (
<Table> <Table>
<TableHeader> <TableHeader>
<TableRow> <TableRow>
<TableHead className="w-8"></TableHead>
<TableHead>{__('Version')}</TableHead> <TableHead>{__('Version')}</TableHead>
<TableHead>{__('Release Date')}</TableHead> <TableHead>{__('Release Date')}</TableHead>
<TableHead>{__('Downloads')}</TableHead> <TableHead>{__('Downloads')}</TableHead>
<TableHead>{__('Changelog')}</TableHead> <TableHead>{__('Summary')}</TableHead>
<TableHead className="w-12"></TableHead>
</TableRow> </TableRow>
</TableHeader> </TableHeader>
<TableBody> <TableBody>
{versionsData?.versions?.map((version) => ( {versionsData?.versions?.map((version) => {
<TableRow key={version.id}> const isExpanded = !!expandedVersions[version.id];
<TableCell> const cl = typeof version.changelog === 'object' && version.changelog !== null
<div className="flex items-center gap-2"> ? (version.changelog as ChangelogData)
<span className="font-mono font-medium"> : { narrative: version.changelog as string, points: [] };
v{version.version}
</span> return (
{version.is_current && ( <React.Fragment key={version.id}>
<Badge variant="default" className="text-xs"> <TableRow className="cursor-pointer hover:bg-muted/50 group" onClick={() => toggleVersion(version.id)}>
{__('Current')} <TableCell>
</Badge> <Button variant="ghost" size="icon" className="w-6 h-6">
)} {isExpanded ? <ChevronDown className="w-4 h-4" /> : <ChevronRight className="w-4 h-4" />}
</div> </Button>
</TableCell> </TableCell>
<TableCell className="text-muted-foreground"> <TableCell>
{version.release_date ? new Date(version.release_date).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }) : '—'} <div className="flex items-center gap-2">
</TableCell> <span className="font-mono font-medium">
<TableCell> v{version.version}
<div className="flex items-center gap-1 text-muted-foreground"> </span>
<Download className="w-3 h-3" /> {version.is_current && (
{version.download_count} <Badge variant="default" className="text-xs">
</div> {__('Current')}
</TableCell> </Badge>
<TableCell className="max-w-xs"> )}
<p className="text-sm text-muted-foreground truncate"> </div>
{version.changelog?.split('\n')[0] || '—'} </TableCell>
</p> <TableCell className="text-muted-foreground">
</TableCell> {version.release_date ? new Date(version.release_date).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }) : '—'}
</TableRow> </TableCell>
))} <TableCell>
<div className="flex items-center gap-1 text-muted-foreground">
<Download className="w-3 h-3" />
{version.download_count}
</div>
</TableCell>
<TableCell className="text-sm text-muted-foreground">
{cl.points?.length > 0 ? `${cl.points.length} changes` : (cl.narrative ? 'Notes attached' : '—')}
</TableCell>
<TableCell>
<Button
variant="ghost"
size="icon"
className="w-8 h-8 opacity-0 group-hover:opacity-100 transition-opacity"
onClick={(e) => openEditModal(version, e)}
title={__('Edit version')}
>
<Pencil className="w-4 h-4 text-muted-foreground" />
</Button>
</TableCell>
</TableRow>
{isExpanded && (
<TableRow className="bg-muted/30">
<TableCell colSpan={6} className="p-0">
<div className="p-6 text-sm border-t">
{cl.narrative && (
<div className="mb-4 text-foreground whitespace-pre-wrap">
{cl.narrative}
</div>
)}
{cl.points && cl.points.length > 0 && (
<ul className="space-y-2">
{cl.points.map((pt, idx) => (
<li key={idx} className="flex items-start gap-3">
<Badge className={`${getBadgeColor(pt.type)} text-[10px] uppercase font-bold mt-0.5`}>
{pt.type}
</Badge>
<span className="text-muted-foreground">{pt.text}</span>
</li>
))}
</ul>
)}
{!cl.narrative && (!cl.points || cl.points.length === 0) && (
<p className="text-muted-foreground italic">{__('No changelog details provided.')}</p>
)}
</div>
</TableCell>
</TableRow>
)}
</React.Fragment>
);
})}
</TableBody> </TableBody>
</Table> </Table>
)} )}

View File

@@ -1,7 +1,7 @@
import React, { useState, useCallback } from 'react'; import React, { useState, useCallback } from 'react';
import { useQuery, useMutation, useQueryClient, keepPreviousData } from '@tanstack/react-query'; import { useQuery, useMutation, useQueryClient, keepPreviousData } from '@tanstack/react-query';
import { api } from '@/lib/api'; import { api } from '@/lib/api';
import { Filter, Package, Trash2, RefreshCw, MoreHorizontal, Eye, Edit } from 'lucide-react'; import { Filter, Package, Trash2, RefreshCw, MoreHorizontal, Eye, Edit, Search } from 'lucide-react';
import { ErrorCard } from '@/components/ErrorCard'; import { ErrorCard } from '@/components/ErrorCard';
import { getPageLoadErrorMessage } from '@/lib/errorHandling'; import { getPageLoadErrorMessage } from '@/lib/errorHandling';
import { __ } from '@/lib/i18n'; import { __ } from '@/lib/i18n';
@@ -18,6 +18,7 @@ import {
} from '@/components/ui/alert-dialog'; } from '@/components/ui/alert-dialog';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox'; import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { toast } from 'sonner'; import { toast } from 'sonner';
import { import {
Select, Select,
@@ -253,6 +254,16 @@ export default function Products() {
<RefreshCw className={`w-4 h-4 ${isRefreshing ? 'animate-spin' : ''}`} /> <RefreshCw className={`w-4 h-4 ${isRefreshing ? 'animate-spin' : ''}`} />
{__('Refresh')} {__('Refresh')}
</button> </button>
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
<Input
placeholder={__('Search products...')}
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="w-[200px] lg:w-[250px] !pl-9"
/>
</div>
</div> </div>
<div className="flex gap-2 items-center"> <div className="flex gap-2 items-center">

View File

@@ -4,13 +4,14 @@ import { api } from '@/lib/api';
import { __ } from '@/lib/i18n'; import { __ } from '@/lib/i18n';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { VerticalTabForm, FormSection } from '@/components/VerticalTabForm'; import { VerticalTabForm, FormSection } from '@/components/VerticalTabForm';
import { Package, DollarSign, Layers, Tag, Download } from 'lucide-react'; import { Package, DollarSign, Layers, Tag, Download, Cloud } from 'lucide-react';
import { toast } from 'sonner'; import { toast } from 'sonner';
import { GeneralTab } from './tabs/GeneralTab'; import { GeneralTab } from './tabs/GeneralTab';
import { InventoryTab } from './tabs/InventoryTab'; import { InventoryTab } from './tabs/InventoryTab';
import { VariationsTab, ProductVariant } from './tabs/VariationsTab'; import { VariationsTab, ProductVariant } from './tabs/VariationsTab';
import { OrganizationTab } from './tabs/OrganizationTab'; import { OrganizationTab } from './tabs/OrganizationTab';
import { DownloadsTab, DownloadableFile } from './tabs/DownloadsTab'; import { DownloadsTab, DownloadableFile } from './tabs/DownloadsTab';
import { SoftwareTab } from './tabs/SoftwareTab';
// Types // Types
export type ProductFormData = { export type ProductFormData = {
@@ -50,6 +51,13 @@ export type ProductFormData = {
// Affiliate // Affiliate
affiliate_enabled?: boolean; affiliate_enabled?: boolean;
affiliate_commission_rate?: string; affiliate_commission_rate?: string;
// Software
software_enabled?: boolean;
software_slug?: string;
software_wp_enabled?: boolean;
software_requires_wp?: string;
software_tested_wp?: string;
software_requires_php?: string;
}; };
type Props = { type Props = {
@@ -109,6 +117,13 @@ export function ProductFormTabbed({
// Affiliate state // Affiliate state
const [affiliateEnabled, setAffiliateEnabled] = useState(initial?.affiliate_enabled || false); const [affiliateEnabled, setAffiliateEnabled] = useState(initial?.affiliate_enabled || false);
const [affiliateCommissionRate, setAffiliateCommissionRate] = useState(initial?.affiliate_commission_rate || ''); const [affiliateCommissionRate, setAffiliateCommissionRate] = useState(initial?.affiliate_commission_rate || '');
// Software state
const [softwareEnabled, setSoftwareEnabled] = useState(initial?.software_enabled || false);
const [softwareSlug, setSoftwareSlug] = useState(initial?.software_slug || '');
const [softwareWpEnabled, setSoftwareWpEnabled] = useState(initial?.software_wp_enabled || false);
const [softwareRequiresWp, setSoftwareRequiresWp] = useState(initial?.software_requires_wp || '');
const [softwareTestedWp, setSoftwareTestedWp] = useState(initial?.software_tested_wp || '');
const [softwareRequiresPhp, setSoftwareRequiresPhp] = useState(initial?.software_requires_php || '');
const [submitting, setSubmitting] = useState(false); const [submitting, setSubmitting] = useState(false);
// Update form state when initial data changes (for edit mode) // Update form state when initial data changes (for edit mode)
@@ -149,6 +164,13 @@ export function ProductFormTabbed({
// Affiliate // Affiliate
setAffiliateEnabled(initial.affiliate_enabled || false); setAffiliateEnabled(initial.affiliate_enabled || false);
setAffiliateCommissionRate(initial.affiliate_commission_rate || ''); setAffiliateCommissionRate(initial.affiliate_commission_rate || '');
// Software
setSoftwareEnabled(initial.software_enabled || false);
setSoftwareSlug(initial.software_slug || '');
setSoftwareWpEnabled(initial.software_wp_enabled || false);
setSoftwareRequiresWp(initial.software_requires_wp || '');
setSoftwareTestedWp(initial.software_tested_wp || '');
setSoftwareRequiresPhp(initial.software_requires_php || '');
} }
}, [initial, mode]); }, [initial, mode]);
@@ -221,6 +243,13 @@ export function ProductFormTabbed({
// Affiliate // Affiliate
affiliate_enabled: affiliateEnabled, affiliate_enabled: affiliateEnabled,
affiliate_commission_rate: affiliateEnabled ? affiliateCommissionRate : undefined, affiliate_commission_rate: affiliateEnabled ? affiliateCommissionRate : undefined,
// Software
software_enabled: softwareEnabled,
software_slug: softwareEnabled ? softwareSlug : undefined,
software_wp_enabled: softwareEnabled ? softwareWpEnabled : undefined,
software_requires_wp: (softwareEnabled && softwareWpEnabled) ? softwareRequiresWp : undefined,
software_tested_wp: (softwareEnabled && softwareWpEnabled) ? softwareTestedWp : undefined,
software_requires_php: (softwareEnabled && softwareWpEnabled) ? softwareRequiresPhp : undefined,
}; };
await onSubmit(payload); await onSubmit(payload);
@@ -238,6 +267,7 @@ export function ProductFormTabbed({
...(downloadable ? [{ id: 'downloads', label: __('Downloads'), icon: <Download className="w-4 h-4" /> }] : []), ...(downloadable ? [{ id: 'downloads', label: __('Downloads'), icon: <Download className="w-4 h-4" /> }] : []),
...(type === 'variable' ? [{ id: 'variations', label: __('Variations'), icon: <Layers className="w-4 h-4" /> }] : []), ...(type === 'variable' ? [{ id: 'variations', label: __('Variations'), icon: <Layers className="w-4 h-4" /> }] : []),
{ id: 'organization', label: __('Organization'), icon: <Tag className="w-4 h-4" /> }, { id: 'organization', label: __('Organization'), icon: <Tag className="w-4 h-4" /> },
{ id: 'software', label: __('Software'), icon: <Cloud className="w-4 h-4" /> },
]; ];
return ( return (
@@ -348,6 +378,24 @@ export function ProductFormTabbed({
/> />
</FormSection> </FormSection>
{/* Software Tab */}
<FormSection id="software">
<SoftwareTab
softwareEnabled={softwareEnabled}
setSoftwareEnabled={setSoftwareEnabled}
softwareSlug={softwareSlug}
setSoftwareSlug={setSoftwareSlug}
softwareWpEnabled={softwareWpEnabled}
setSoftwareWpEnabled={setSoftwareWpEnabled}
softwareRequiresWp={softwareRequiresWp}
setSoftwareRequiresWp={setSoftwareRequiresWp}
softwareTestedWp={softwareTestedWp}
setSoftwareTestedWp={setSoftwareTestedWp}
softwareRequiresPhp={softwareRequiresPhp}
setSoftwareRequiresPhp={setSoftwareRequiresPhp}
/>
</FormSection>
{/* Submit Button */} {/* Submit Button */}
{!hideSubmitButton && ( {!hideSubmitButton && (
<div className="mt-6 flex gap-3"> <div className="mt-6 flex gap-3">

View File

@@ -0,0 +1,115 @@
import React from 'react';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { __ } from '@/lib/i18n';
type Props = {
softwareEnabled: boolean;
setSoftwareEnabled: (val: boolean) => void;
softwareSlug: string;
setSoftwareSlug: (val: string) => void;
softwareWpEnabled: boolean;
setSoftwareWpEnabled: (val: boolean) => void;
softwareRequiresWp: string;
setSoftwareRequiresWp: (val: string) => void;
softwareTestedWp: string;
setSoftwareTestedWp: (val: string) => void;
softwareRequiresPhp: string;
setSoftwareRequiresPhp: (val: string) => void;
};
export function SoftwareTab({
softwareEnabled,
setSoftwareEnabled,
softwareSlug,
setSoftwareSlug,
softwareWpEnabled,
setSoftwareWpEnabled,
softwareRequiresWp,
setSoftwareRequiresWp,
softwareTestedWp,
setSoftwareTestedWp,
softwareRequiresPhp,
setSoftwareRequiresPhp,
}: Props) {
return (
<div className="space-y-6">
<div className="flex flex-col space-y-4">
<h3 className="text-lg font-medium">{__('Software Distribution')}</h3>
<p className="text-sm text-gray-500">
{__('Enable this to distribute software updates, manage versioning, and secure downloads.')}
</p>
<div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg border">
<div className="space-y-0.5">
<Label className="text-base">{__('Enable Software Distribution')}</Label>
<p className="text-sm text-gray-500">
{__('Allow this product to serve OTA updates and track versions.')}
</p>
</div>
<Switch checked={softwareEnabled} onCheckedChange={setSoftwareEnabled} />
</div>
</div>
{softwareEnabled && (
<div className="space-y-4 pt-4 border-t">
<div className="space-y-2">
<Label htmlFor="softwareSlug">{__('Software Slug (Unique Identifier)')}</Label>
<Input
id="softwareSlug"
value={softwareSlug}
onChange={(e) => setSoftwareSlug(e.target.value)}
placeholder="e.g. acme-seo-pro"
/>
<p className="text-sm text-gray-500">
{__('The unique slug that the software client will use to check for updates.')}
</p>
</div>
<div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg border mt-6">
<div className="space-y-0.5">
<Label className="text-base">{__('WordPress Product')}</Label>
<p className="text-sm text-gray-500">
{__('Check if this software is a WordPress Plugin or Theme.')}
</p>
</div>
<Switch checked={softwareWpEnabled} onCheckedChange={setSoftwareWpEnabled} />
</div>
{softwareWpEnabled && (
<div className="grid grid-cols-3 gap-4 pt-4">
<div className="space-y-2">
<Label htmlFor="requiresWp">{__('Requires WP')}</Label>
<Input
id="requiresWp"
value={softwareRequiresWp}
onChange={(e) => setSoftwareRequiresWp(e.target.value)}
placeholder="e.g. 5.8"
/>
</div>
<div className="space-y-2">
<Label htmlFor="testedWp">{__('Tested up to WP')}</Label>
<Input
id="testedWp"
value={softwareTestedWp}
onChange={(e) => setSoftwareTestedWp(e.target.value)}
placeholder="e.g. 6.4"
/>
</div>
<div className="space-y-2">
<Label htmlFor="requiresPhp">{__('Requires PHP')}</Label>
<Input
id="requiresPhp"
value={softwareRequiresPhp}
onChange={(e) => setSoftwareRequiresPhp(e.target.value)}
placeholder="e.g. 7.4"
/>
</div>
</div>
)}
</div>
)}
</div>
);
}

View File

@@ -25,6 +25,10 @@ export type ProductVariant = {
stock_status?: 'instock' | 'outofstock' | 'onbackorder'; stock_status?: 'instock' | 'outofstock' | 'onbackorder';
image?: string; image?: string;
license_duration_days?: string; license_duration_days?: string;
subscription_signup_fee?: string;
subscription_trial_days?: string;
subscription_period?: 'day' | 'week' | 'month' | 'year';
subscription_interval?: string;
}; };
type VariationsTabProps = { type VariationsTabProps = {
@@ -282,8 +286,83 @@ export function VariationsTab({
</div> </div>
</div> </div>
{/* Subscription Fields */}
<div className="col-span-2 md:col-span-4 space-y-3">
<Label className="text-xs font-semibold">{__('Subscription Settings (Optional)')}</Label>
<div className="grid grid-cols-2 md:grid-cols-4 gap-3">
<div>
<Label className="text-xs">{__('Period')}</Label>
<select
value={variation.subscription_period || ''}
onChange={(e) => {
const updated = [...variations];
updated[index].subscription_period = e.target.value as any;
setVariations(updated);
}}
className="flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 mt-1"
>
<option value="">{__('Parent Default')}</option>
<option value="day">{__('Day')}</option>
<option value="week">{__('Week')}</option>
<option value="month">{__('Month')}</option>
<option value="year">{__('Year')}</option>
</select>
</div>
<div>
<Label className="text-xs">{__('Interval')}</Label>
<Input
type="number"
min="1"
placeholder={__('Parent')}
value={variation.subscription_interval || ''}
onChange={(e) => {
const updated = [...variations];
updated[index].subscription_interval = e.target.value;
setVariations(updated);
}}
className="mt-1"
/>
</div>
<div>
<Label className="text-xs">{__('Trial Days')}</Label>
<Input
type="number"
min="0"
placeholder={__('Parent')}
value={variation.subscription_trial_days || ''}
onChange={(e) => {
const updated = [...variations];
updated[index].subscription_trial_days = e.target.value;
setVariations(updated);
}}
className="mt-1"
/>
</div>
<div className="relative">
<Label className="text-xs">{__('Signup Fee')}</Label>
<div className="relative mt-1">
<span className="absolute left-3 top-1/2 -translate-y-1/2 text-xs text-muted-foreground font-medium">
{store.symbol}
</span>
<Input
type="number"
step={store.decimals === 0 ? '1' : '0.01'}
placeholder={__('Parent')}
value={variation.subscription_signup_fee || ''}
onChange={(e) => {
const updated = [...variations];
updated[index].subscription_signup_fee = e.target.value;
setVariations(updated);
}}
className="pl-8 pr-3 text-right"
/>
</div>
</div>
</div>
</div>
{/* License Duration - only show if licensing is enabled on product */} {/* License Duration - only show if licensing is enabled on product */}
<div className="col-span-2 md:col-span-4"> <div className="col-span-2 md:col-span-4 mt-2">
<Label className="text-xs">{__('License Duration (Days)')}</Label> <Label className="text-xs">{__('License Duration (Days)')}</Label>
<Input <Input
type="number" type="number"

View File

@@ -10,6 +10,7 @@ import { Button } from '@/components/ui/button';
import { ArrowLeft } from 'lucide-react'; import { ArrowLeft } from 'lucide-react';
import { __ } from '@/lib/i18n'; import { __ } from '@/lib/i18n';
import { DynamicComponentLoader } from '@/components/DynamicComponentLoader'; import { DynamicComponentLoader } from '@/components/DynamicComponentLoader';
import { GatewayCapabilityMatrix as SubscriptionGatewayCapabilitiesSection } from './Modules/Subscription/GatewayCapabilityMatrix';
interface Module { interface Module {
id: string; id: string;
@@ -143,6 +144,8 @@ export default function ModuleSettings() {
</div> </div>
)} )}
</SettingsCard> </SettingsCard>
{moduleId === 'subscription' && <SubscriptionGatewayCapabilitiesSection />}
</SettingsLayout> </SettingsLayout>
); );
} }

View File

@@ -0,0 +1,173 @@
import React, { useMemo, useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { toast } from 'sonner';
import { SettingsCard } from '../../components/SettingsCard';
import { ToggleField } from '../../components/ToggleField';
import { Button } from '@/components/ui/button';
import { __ } from '@/lib/i18n';
interface GatewayRow {
id: string;
title: string;
description: string;
enabled: boolean;
default: boolean;
override: boolean | null;
auto_renew: boolean;
forced_manual: boolean;
}
interface CapabilityResponse {
gateways: GatewayRow[];
kill_switch: boolean;
}
type OverrideMap = Record<string, boolean | null>;
/**
* Gateway Capability Matrix
*
* Renders one row per WC payment gateway with a per-gateway auto-renew
* toggle. Overrides are persisted via POST /subscriptions/gateway-capabilities.
* The kill switch is a separate field already on the standard settings form
* (force_manual_renewal); when on, every row is rendered as forced-manual
* and the per-gateway toggles are disabled.
*/
export const GatewayCapabilityMatrix: React.FC = () => {
const queryClient = useQueryClient();
const [overrides, setOverrides] = useState<OverrideMap>({});
const { data, isLoading } = useQuery({
queryKey: ['subscription', 'gateway-capabilities'],
queryFn: async () => {
const r = await api.get('/subscriptions/gateway-capabilities');
return r as CapabilityResponse;
},
});
const save = useMutation({
mutationFn: async (payload: OverrideMap) => {
return api.post('/subscriptions/gateway-capabilities', { overrides: payload });
},
onSuccess: () => {
toast.success(__('Gateway capabilities saved'));
setOverrides({});
queryClient.invalidateQueries({ queryKey: ['subscription', 'gateway-capabilities'] });
},
onError: (e: any) => {
toast.error(e?.response?.data?.message ?? __('Failed to save'));
},
});
const rows = useMemo(() => data?.gateways ?? [], [data]);
const effectiveFor = (row: GatewayRow): boolean => {
if (row.forced_manual) return false;
if (row.id in overrides) return overrides[row.id] === true;
return row.auto_renew;
};
const dirty = Object.keys(overrides).length > 0;
if (isLoading) {
return (
<SettingsCard
title={__('Gateway Auto-Renew Capabilities')}
description={__('Per-gateway declaration of which payment methods can auto-debit subscription renewals.')}
>
<div className="text-sm text-muted-foreground">{__('Loading gateways…')}</div>
</SettingsCard>
);
}
return (
<SettingsCard
title={__('Gateway Auto-Renew Capabilities')}
description={__(
'Declare which payment gateways can auto-debit subscription renewals. Indonesian VA/QRIS/e-wallet gateways default to manual. The kill switch (above) forces every gateway to manual regardless of these settings.'
)}
>
{rows.length === 0 ? (
<div className="text-sm text-muted-foreground">{__('No payment gateways available.')}</div>
) : (
<div className="divide-y divide-border">
{rows.map((row) => {
const eff = effectiveFor(row);
const overrideState = row.id in overrides ? overrides[row.id] : row.override;
return (
<div key={row.id} className="flex items-start justify-between gap-4 py-3">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 flex-wrap">
<span className="font-medium text-foreground">{row.title}</span>
{!row.enabled && (
<span className="text-xs px-2 py-0.5 bg-gray-200 text-gray-700 dark:bg-gray-700 dark:text-gray-300 rounded">
{__('Site disabled')}
</span>
)}
{row.forced_manual && (
<span className="text-xs px-2 py-0.5 bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-300 rounded">
{__('Forced manual (kill switch)')}
</span>
)}
{overrideState === null && (
<span className="text-xs px-2 py-0.5 bg-blue-50 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300 rounded">
{__('Default')}: {row.default ? __('Auto-renew') : __('Manual')}
</span>
)}
{overrideState !== null && (
<span className="text-xs px-2 py-0.5 bg-purple-50 text-purple-700 dark:bg-purple-900/30 dark:text-purple-300 rounded">
{__('Override')}
</span>
)}
</div>
{row.description && (
<p className="text-xs text-muted-foreground mt-1 break-words">{row.description}</p>
)}
<p className="text-xs text-muted-foreground mt-1 font-mono">{row.id}</p>
</div>
<div className="flex flex-col items-end gap-2 shrink-0">
<ToggleField
id={`gateway-autorenew-${row.id}`}
checked={eff}
disabled={row.forced_manual}
onCheckedChange={(checked: boolean) => {
const currentEffective = row.auto_renew;
if (checked === currentEffective) {
setOverrides((p) => {
const n = { ...p };
delete n[row.id];
return n;
});
} else {
setOverrides((p) => ({ ...p, [row.id]: checked }));
}
}}
label={eff ? __('Auto-renew') : __('Manual')}
/>
</div>
</div>
);
})}
</div>
)}
<div className="flex items-center gap-3 mt-4">
<Button
onClick={() => save.mutate(overrides)}
disabled={!dirty || save.isPending}
>
{save.isPending ? __('Saving…') : __('Save Capability Overrides')}
</Button>
{dirty && (
<Button
variant="ghost"
onClick={() => setOverrides({})}
>
{__('Discard changes')}
</Button>
)}
</div>
</SettingsCard>
);
};

View File

@@ -118,8 +118,18 @@ async function fetchSubscription(id: string) {
return res; return res;
} }
async function subscriptionAction(id: number, action: string, reason?: string) { async function subscriptionAction(id: number, action: string, reason?: string, extra?: Record<string, unknown>) {
const res = await api.post(`/subscriptions/${id}/${action}`, { reason }); let path = `/subscriptions/${id}/${action}`;
if (extra) {
const usp = new URLSearchParams();
for (const [k, v] of Object.entries(extra)) {
if (v == null) continue;
usp.set(k, String(v));
}
const qs = usp.toString();
if (qs) path += `?${qs}`;
}
const res = await api.post(path, { reason });
return res; return res;
} }
@@ -158,11 +168,70 @@ export default function SubscriptionDetail() {
}, },
}); });
// H1 — Renew is special: the response carries { order_id, status } so the admin
// can see whether a payment URL needs to be sent to the customer.
const renewMutation = useMutation({
mutationFn: () => subscriptionAction(parseInt(id!), 'renew'),
onSuccess: (res: any) => {
queryClient.invalidateQueries({ queryKey: ['subscription', id] });
queryClient.invalidateQueries({ queryKey: ['subscriptions'] });
const orderId = res?.order_id;
const status = res?.status;
if (status === 'complete') {
toast.success(__(`Renewed successfully (order #${orderId}). Payment captured automatically.`));
} else if (status === 'manual') {
toast.success(
__(`Renewal order #${orderId} created. The customer must complete payment manually — open the order to send a payment link.`),
{ duration: 8000 }
);
} else if (status === 'existing') {
toast.info(__(`Order #${orderId} is already pending payment — using the existing order.`));
} else {
toast.success(__(`Renewed (order #${orderId}).`));
}
},
onError: (error: Error) => {
toast.error(error.message);
},
});
// M2 — "Charge Now" is the same renew endpoint with `?charge_now=true`. It bypasses
// the per-gateway capability gate so the auto-debit path is attempted even on
// normally-manual gateways. On failure the order is marked failed (no manual
// fallback) so the admin sees the charge could not be processed.
const chargeNowMutation = useMutation({
mutationFn: () => subscriptionAction(parseInt(id!), 'renew', undefined, { charge_now: 'true' }),
onSuccess: (res: any) => {
queryClient.invalidateQueries({ queryKey: ['subscription', id] });
queryClient.invalidateQueries({ queryKey: ['subscriptions'] });
const orderId = res?.order_id;
const status = res?.status;
if (status === 'complete') {
toast.success(__(`Charged successfully (order #${orderId}). The subscription has been renewed.`));
} else if (status === 'existing') {
toast.info(__(`Order #${orderId} is already pending payment — using the existing order.`));
} else {
toast.warning(__(`Charge attempt completed with status "${status || 'unknown'}" (order #${orderId}).`));
}
},
onError: (error: Error) => {
toast.error(error.message);
},
});
const handleAction = (action: string) => { const handleAction = (action: string) => {
if (action === 'cancel') { if (action === 'cancel') {
setShowCancelDialog(true); setShowCancelDialog(true);
return; return;
} }
if (action === 'renew') {
renewMutation.mutate();
return;
}
if (action === 'charge_now') {
chargeNowMutation.mutate();
return;
}
actionMutation.mutate({ action }); actionMutation.mutate({ action });
}; };
@@ -229,10 +298,21 @@ export default function SubscriptionDetail() {
<Button <Button
variant="outline" variant="outline"
onClick={() => handleAction('renew')} onClick={() => handleAction('renew')}
disabled={actionMutation.isPending} disabled={renewMutation.isPending || chargeNowMutation.isPending || actionMutation.isPending}
> >
<RefreshCw className="w-4 h-4 mr-2" /> <RefreshCw className="w-4 h-4 mr-2" />
{__('Renew Now')} {renewMutation.isPending ? __('Renewing…') : __('Renew Now')}
</Button>
)}
{subscription.status === 'active' && (
<Button
variant="default"
onClick={() => handleAction('charge_now')}
disabled={renewMutation.isPending || chargeNowMutation.isPending || actionMutation.isPending}
title={__('Bypass the per-gateway capability gate and attempt an immediate charge. On failure the order is marked failed — no manual fallback.')}
>
<CreditCard className="w-4 h-4 mr-2" />
{chargeNowMutation.isPending ? __('Charging…') : __('Charge Now')}
</Button> </Button>
)} )}
{subscription.can_cancel && ( {subscription.can_cancel && (

View File

@@ -1,4 +1,4 @@
import React, { useState, useEffect, useCallback } from 'react'; import React, { useState, useEffect, useCallback, useRef } from 'react';
import { useQuery, useMutation, useQueryClient, keepPreviousData } from '@tanstack/react-query'; import { useQuery, useMutation, useQueryClient, keepPreviousData } from '@tanstack/react-query';
import { useNavigate, Link } from 'react-router-dom'; import { useNavigate, Link } from 'react-router-dom';
import { Repeat, MoreHorizontal, Play, Pause, XCircle, RefreshCw, Eye, Filter, Package } from 'lucide-react'; import { Repeat, MoreHorizontal, Play, Pause, XCircle, RefreshCw, Eye, Filter, Package } from 'lucide-react';
@@ -93,23 +93,49 @@ export default function SubscriptionsIndex() {
const initial = getQuery(); const initial = getQuery();
const [page, setPage] = useState(Number(initial.page ?? 1) || 1); const [page, setPage] = useState(Number(initial.page ?? 1) || 1);
const [status, setStatus] = useState<string | undefined>(initial.status || undefined); const [status, setStatus] = useState<string | undefined>(initial.status || undefined);
// M4 — Search input is held in a local "raw" state for snappy typing, then
// committed to `committedSearch` after a 300ms debounce. We key the React
// Query cache on the committed value so the debounce actually coalesces
// requests, not just defers re-renders.
const [rawSearch, setRawSearch] = useState<string>((initial as any).search || '');
const [committedSearch, setCommittedSearch] = useState<string>((initial as any).search || '');
const [isRefreshing, setIsRefreshing] = useState(false); const [isRefreshing, setIsRefreshing] = useState(false);
const [showCancelDialog, setShowCancelDialog] = useState(false); const [showCancelDialog, setShowCancelDialog] = useState(false);
const [cancelTargetId, setCancelTargetId] = useState<number | null>(null); const [cancelTargetId, setCancelTargetId] = useState<number | null>(null);
const [showBulkCancelDialog, setShowBulkCancelDialog] = useState(false);
const perPage = 20; const perPage = 20;
// Debounce rawSearch → committedSearch. 300ms is the sweet spot for "feels
// instant" vs "don't fire on every keystroke".
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(() => {
if (debounceRef.current) clearTimeout(debounceRef.current);
debounceRef.current = setTimeout(() => {
setCommittedSearch(rawSearch.trim());
setPage(1);
}, 300);
return () => {
if (debounceRef.current) clearTimeout(debounceRef.current);
};
}, [rawSearch]);
useEffect(() => { useEffect(() => {
setPageHeader(__('Subscriptions')); setPageHeader(__('Subscriptions'));
return () => clearPageHeader(); return () => clearPageHeader();
}, [setPageHeader, clearPageHeader]); }, [setPageHeader, clearPageHeader]);
useEffect(() => { useEffect(() => {
setQuery({ page, status }); setQuery({ page, status, search: committedSearch || undefined });
}, [page, status]); }, [page, status, committedSearch]);
const q = useQuery({ const q = useQuery({
queryKey: ['subscriptions', { status, page }], queryKey: ['subscriptions', { status, page, search: committedSearch }],
queryFn: () => api.get('/subscriptions', { status, page, per_page: perPage }), queryFn: () => api.get('/subscriptions', {
status,
page,
per_page: perPage,
search: committedSearch || undefined,
}),
placeholderData: keepPreviousData, placeholderData: keepPreviousData,
}); });
@@ -155,6 +181,71 @@ export default function SubscriptionsIndex() {
} }
}; };
// M3 — Bulk actions. The checkboxes below drive `selectedIds`; this mutation
// posts to /subscriptions/bulk and the toolbar above the table exposes the
// available actions. CSV export uses a hidden form submit so the browser can
// handle the download directly.
const bulkActionMutation = useMutation({
mutationFn: ({ action, ids }: { action: 'cancel' | 'export_csv'; ids: number[] }) =>
api.post('/subscriptions/bulk', { action, ids }),
onSuccess: (res: any, vars) => {
if (vars.action === 'cancel') {
const ok = res?.ok ?? 0;
const failed = Array.isArray(res?.failed) ? res.failed.length : 0;
if (failed === 0) {
toast.success(__(`Cancelled ${ok} subscription${ok === 1 ? '' : 's'}.`));
} else {
toast.warning(__(`Cancelled ${ok}, failed ${failed}.`));
}
setSelectedIds([]);
queryClient.invalidateQueries({ queryKey: ['subscriptions'] });
}
},
onError: (error: Error) => {
toast.error(error.message);
},
});
const handleBulkCancel = () => {
if (selectedIds.length === 0) return;
setShowBulkCancelDialog(true);
};
const confirmBulkCancel = () => {
bulkActionMutation.mutate({ action: 'cancel', ids: selectedIds });
setShowBulkCancelDialog(false);
};
const handleBulkExport = () => {
if (selectedIds.length === 0) return;
// We can't easily stream a CSV through fetch+sonner, so open a POST form
// with a hidden _wpnonce and let the browser download directly. The
// server returns Content-Disposition: attachment.
const form = document.createElement('form');
form.method = 'POST';
form.action = (window.WNW_API?.root || '') + '/woonoow/v1/subscriptions/bulk';
const nonce = document.createElement('input');
nonce.type = 'hidden';
nonce.name = '_wpnonce';
nonce.value = window.WNW_API?.nonce || '';
form.appendChild(nonce);
const actionInput = document.createElement('input');
actionInput.type = 'hidden';
actionInput.name = 'action';
actionInput.value = 'export_csv';
form.appendChild(actionInput);
selectedIds.forEach((id) => {
const i = document.createElement('input');
i.type = 'hidden';
i.name = 'ids[]';
i.value = String(id);
form.appendChild(i);
});
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
};
// Checkbox logic // Checkbox logic
const [selectedIds, setSelectedIds] = useState<number[]>([]); const [selectedIds, setSelectedIds] = useState<number[]>([]);
const allIds = subscriptions.map(s => s.id); const allIds = subscriptions.map(s => s.id);
@@ -191,7 +282,22 @@ export default function SubscriptionsIndex() {
</button> </button>
</div> </div>
<div className="flex gap-2 items-center"> <div className="flex gap-2 items-center flex-wrap">
{/* M4 — Search input. The input is uncontrolled-looking
(we just track rawSearch in state) so typing feels
instant; the debounce above commits the value to
the React Query cache 300ms after the user stops. */}
<div className="relative">
<input
type="search"
value={rawSearch}
onChange={(e) => setRawSearch(e.target.value)}
placeholder={__('Search by id, email, or name…')}
aria-label={__('Search subscriptions')}
className="border rounded-md pl-3 pr-3 py-2 text-sm w-64 focus:outline-none focus:ring-1 focus:ring-primary"
/>
</div>
<Filter className="min-w-4 w-4 h-4 opacity-60" /> <Filter className="min-w-4 w-4 h-4 opacity-60" />
<Select <Select
value={status ?? 'all'} value={status ?? 'all'}
@@ -216,10 +322,10 @@ export default function SubscriptionsIndex() {
</SelectContent> </SelectContent>
</Select> </Select>
{status && ( {(status || committedSearch) && (
<button <button
className="text-sm text-muted-foreground hover:text-foreground underline text-nowrap" className="text-sm text-muted-foreground hover:text-foreground underline text-nowrap"
onClick={() => { setStatus(undefined); setPage(1); }} onClick={() => { setStatus(undefined); setRawSearch(''); setCommittedSearch(''); setPage(1); }}
> >
{__('Clear filters')} {__('Clear filters')}
</button> </button>
@@ -235,6 +341,14 @@ export default function SubscriptionsIndex() {
{/* Mobile: Status filter bar */} {/* Mobile: Status filter bar */}
<div className="md:hidden"> <div className="md:hidden">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<input
type="search"
value={rawSearch}
onChange={(e) => setRawSearch(e.target.value)}
placeholder={__('Search…')}
aria-label={__('Search subscriptions')}
className="border rounded-md px-3 py-2 text-sm flex-1 min-w-0 focus:outline-none focus:ring-1 focus:ring-primary"
/>
<Select <Select
value={status ?? 'all'} value={status ?? 'all'}
onValueChange={(v) => { onValueChange={(v) => {
@@ -273,6 +387,43 @@ export default function SubscriptionsIndex() {
</div> </div>
)} )}
{/* M3 — Bulk actions toolbar. Visible only when at least one row is selected. */}
{selectedIds.length > 0 && (
<div className="rounded-lg border border-primary/30 bg-primary/5 p-3 flex flex-wrap items-center gap-3">
<div className="text-sm font-medium">
{selectedIds.length === 1
? __('1 subscription selected')
: __('%s subscriptions selected').replace('%s', String(selectedIds.length))}
</div>
<div className="flex-1" />
<Button
variant="outline"
size="sm"
onClick={handleBulkExport}
disabled={bulkActionMutation.isPending}
>
{__('Export CSV')}
</Button>
<Button
variant="destructive"
size="sm"
onClick={handleBulkCancel}
disabled={bulkActionMutation.isPending}
>
<XCircle className="w-4 h-4 mr-2" />
{bulkActionMutation.isPending ? __('Cancelling…') : __('Cancel selected')}
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => setSelectedIds([])}
disabled={bulkActionMutation.isPending}
>
{__('Clear')}
</Button>
</div>
)}
{/* Loading State */} {/* Loading State */}
{q.isLoading && ( {q.isLoading && (
<div className="space-y-3"> <div className="space-y-3">
@@ -500,6 +651,37 @@ export default function SubscriptionsIndex() {
</AlertDialogFooter> </AlertDialogFooter>
</AlertDialogContent> </AlertDialogContent>
</AlertDialog> </AlertDialog>
{/* M3 — Bulk cancel confirmation dialog */}
<AlertDialog open={showBulkCancelDialog} onOpenChange={setShowBulkCancelDialog}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
{__('Cancel %s subscriptions?').replace('%s', String(selectedIds.length))}
</AlertDialogTitle>
<AlertDialogDescription>
{__('Are you sure you want to cancel the selected subscriptions? This affects multiple customers at once.')}
<br />
<span className="text-red-600 font-medium">{__('This action cannot be undone.')}</span>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel
onClick={() => setShowBulkCancelDialog(false)}
disabled={bulkActionMutation.isPending}
>
{__('Keep Subscriptions')}
</AlertDialogCancel>
<AlertDialogAction
onClick={confirmBulkCancel}
disabled={bulkActionMutation.isPending}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{bulkActionMutation.isPending ? __('Cancelling…') : __('Cancel All Selected')}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div> </div>
); );
} }

View File

@@ -11,6 +11,7 @@ import { BaseLayout } from './layouts/BaseLayout';
// Pages // Pages
import Shop from './pages/Shop'; import Shop from './pages/Shop';
import Product from './pages/Product'; import Product from './pages/Product';
import CollectionPage from './pages/Shop/CollectionPage';
import Cart from './pages/Cart'; import Cart from './pages/Cart';
import Checkout from './pages/Checkout'; import Checkout from './pages/Checkout';
import ThankYou from './pages/ThankYou'; import ThankYou from './pages/ThankYou';
@@ -106,6 +107,7 @@ function AppRoutes() {
{/* Shop Routes */} {/* Shop Routes */}
<Route path="/shop" element={<Shop />} /> <Route path="/shop" element={<Shop />} />
<Route path="/product/:slug" element={<Product />} /> <Route path="/product/:slug" element={<Product />} />
<Route path="/collection/:slug" element={<CollectionPage />} />
{/* Cart & Checkout */} {/* Cart & Checkout */}
<Route path="/cart" element={<Cart />} /> <Route path="/cart" element={<Cart />} />

View File

@@ -18,6 +18,7 @@ interface Address {
email?: string; email?: string;
phone?: string; phone?: string;
is_default: boolean; is_default: boolean;
formatted_address?: string;
} }
interface AddressSelectorProps { interface AddressSelectorProps {
@@ -148,14 +149,22 @@ export function AddressSelector({
)} )}
{/* Address */} {/* Address */}
<p className="text-sm text-gray-600 mt-2"> <div className="text-sm text-gray-600 mt-2">
{address.address_1} {address.formatted_address ? (
{address.address_2 && `, ${address.address_2}`} <p className="whitespace-pre-wrap">{address.formatted_address}</p>
</p> ) : (
<p className="text-sm text-gray-600"> <>
{address.city}, {address.state} {address.postcode} <p>
</p> {address.address_1}
<p className="text-sm text-gray-600">{address.country}</p> {address.address_2 && `, ${address.address_2}`}
</p>
<p>
{address.city}, {address.state} {address.postcode}
</p>
<p>{address.country}</p>
</>
)}
</div>
</div> </div>
</div> </div>
))} ))}

View File

@@ -28,6 +28,7 @@ interface CheckoutField {
interface DynamicCheckoutFieldProps { interface DynamicCheckoutFieldProps {
field: CheckoutField; field: CheckoutField;
value: string; value: string;
valueLabel?: string;
onChange: (value: string) => void; onChange: (value: string) => void;
countryOptions?: { value: string; label: string }[]; countryOptions?: { value: string; label: string }[];
stateOptions?: { value: string; label: string }[]; stateOptions?: { value: string; label: string }[];
@@ -41,6 +42,7 @@ interface SearchOption {
export function DynamicCheckoutField({ export function DynamicCheckoutField({
field, field,
value, value,
valueLabel,
onChange, onChange,
countryOptions = [], countryOptions = [],
stateOptions = [], stateOptions = [],
@@ -54,9 +56,11 @@ export function DynamicCheckoutField({
return; return;
} }
// If we have a value but no options yet, we might need to load it // If we have a value and a label, inject it into searchOptions so it renders properly when mounted
// This handles pre-selected values if (value && valueLabel && searchOptions.length === 0) {
}, [field.type, field.search_endpoint, value]); setSearchOptions([{ value, label: valueLabel }]);
}
}, [field.type, field.search_endpoint, value, valueLabel]);
// Handle API search for searchable_select // Handle API search for searchable_select
const handleApiSearch = async (searchTerm: string) => { const handleApiSearch = async (searchTerm: string) => {

View File

@@ -70,9 +70,9 @@ export function ProductCard({ product, onAddToCart }: ProductCardProps) {
if (isLoading) { if (isLoading) {
return ( return (
<div className="animate-pulse"> <div className="animate-pulse">
<div className="bg-gray-200 aspect-square rounded-lg mb-4" /> <div className="bg-muted aspect-square rounded-lg mb-4" />
<div className="h-4 bg-gray-200 rounded mb-2" /> <div className="h-4 bg-muted rounded mb-2" />
<div className="h-4 bg-gray-200 rounded w-2/3" /> <div className="h-4 bg-muted rounded w-2/3" />
</div> </div>
); );
} }
@@ -91,17 +91,17 @@ export function ProductCard({ product, onAddToCart }: ProductCardProps) {
if (cardStyle === 'minimal') { if (cardStyle === 'minimal') {
return gridCols >= 4 return gridCols >= 4
? 'overflow-hidden hover:opacity-90 transition-opacity' ? 'overflow-hidden hover:opacity-90 transition-opacity'
: 'overflow-hidden hover:opacity-80 transition-opacity border-b border-gray-100 pb-4'; : 'overflow-hidden hover:opacity-80 transition-opacity border-b border-border pb-4';
} }
if (cardStyle === 'overlay') { if (cardStyle === 'overlay') {
return gridCols >= 4 return gridCols >= 4
? 'relative overflow-hidden group-hover:shadow-lg transition-all rounded-md' ? 'relative overflow-hidden group-hover:shadow-lg transition-all rounded-md'
: 'relative overflow-hidden group-hover:shadow-xl transition-all rounded-lg bg-white'; : 'relative overflow-hidden group-hover:shadow-xl transition-all rounded-lg bg-card';
} }
// Default 'card' style // Default 'card' style
return gridCols >= 4 return gridCols >= 4
? 'border border-gray-200 rounded-md overflow-hidden hover:shadow-md transition-shadow bg-white' ? 'border border-border rounded-md overflow-hidden hover:shadow-md transition-shadow bg-card'
: 'border rounded-lg overflow-hidden hover:shadow-lg transition-shadow bg-white'; : 'border border-border rounded-lg overflow-hidden hover:shadow-lg transition-shadow bg-card';
}; };
const cardClasses = getCardClasses(); const cardClasses = getCardClasses();
@@ -118,7 +118,7 @@ export function ProductCard({ product, onAddToCart }: ProductCardProps) {
<Link to={`/product/${product.slug}`} className="group h-full"> <Link to={`/product/${product.slug}`} className="group h-full">
<div className={`${cardClasses} h-full flex flex-col`}> <div className={`${cardClasses} h-full flex flex-col`}>
{/* Image */} {/* Image */}
<div className={`relative w-full overflow-hidden bg-gray-100 ${aspectRatioClass}`}> <div className={`relative w-full overflow-hidden bg-muted ${aspectRatioClass}`}>
{product.image ? ( {product.image ? (
<img <img
src={product.image} src={product.image}
@@ -126,7 +126,7 @@ export function ProductCard({ product, onAddToCart }: ProductCardProps) {
className="absolute inset-0 w-full !h-full object-cover object-center group-hover:scale-105 transition-transform duration-300" className="absolute inset-0 w-full !h-full object-cover object-center group-hover:scale-105 transition-transform duration-300"
/> />
) : ( ) : (
<div className="absolute inset-0 flex items-center justify-center text-gray-400"> <div className="absolute inset-0 flex items-center justify-center text-muted-foreground">
No Image No Image
</div> </div>
)} )}
@@ -146,12 +146,14 @@ export function ProductCard({ product, onAddToCart }: ProductCardProps) {
<div className="absolute top-2 left-2 z-10"> <div className="absolute top-2 left-2 z-10">
<button <button
onClick={handleWishlistClick} onClick={handleWishlistClick}
className={`font-[inherit] p-2 rounded-full shadow-md hover:bg-gray-50 flex items-center justify-center transition-all ${inWishlist ? 'bg-red-50' : 'bg-white' className={`font-[inherit] p-2 rounded-full shadow-md border flex items-center justify-center transition-all ${
}`} inWishlist
? 'bg-red-50 border-red-100 dark:bg-red-950 dark:border-red-900'
: 'bg-background border-border hover:bg-muted text-foreground'
}`}
title={inWishlist ? 'Remove from wishlist' : 'Add to wishlist'} title={inWishlist ? 'Remove from wishlist' : 'Add to wishlist'}
> >
<Heart className={`w-4 h-4 block transition-all ${inWishlist ? 'fill-red-500 text-red-500' : '' <Heart className={`w-4 h-4 block transition-all ${inWishlist ? 'fill-red-500 text-red-500' : ''}`} />
}`} />
</button> </button>
</div> </div>
)} )}
@@ -174,7 +176,7 @@ export function ProductCard({ product, onAddToCart }: ProductCardProps) {
{/* Content */} {/* Content */}
<div className={`p-4 flex-1 flex flex-col ${textAlignClass}`}> <div className={`p-4 flex-1 flex flex-col ${textAlignClass}`}>
<h3 className="text-sm font-medium text-gray-900 mb-2 line-clamp-2 leading-snug group-hover:text-primary transition-colors"> <h3 className="text-sm font-medium text-foreground mb-2 line-clamp-2 leading-snug group-hover:text-primary transition-colors">
{product.name} {product.name}
</h3> </h3>
@@ -182,15 +184,15 @@ export function ProductCard({ product, onAddToCart }: ProductCardProps) {
<div className={`flex items-center gap-2 mb-3 ${(layout.card_text_align || 'left') === 'center' ? 'justify-center' : (layout.card_text_align || 'left') === 'right' ? 'justify-end' : ''}`}> <div className={`flex items-center gap-2 mb-3 ${(layout.card_text_align || 'left') === 'center' ? 'justify-center' : (layout.card_text_align || 'left') === 'right' ? 'justify-end' : ''}`}>
{product.on_sale && product.regular_price ? ( {product.on_sale && product.regular_price ? (
<> <>
<span className="text-base font-bold" style={{ color: 'var(--color-primary)' }}> <span className="text-base font-bold text-primary">
{formatPrice(product.sale_price || product.price)} {formatPrice(product.sale_price || product.price)}
</span> </span>
<span className="text-xs text-gray-500 line-through"> <span className="text-xs text-muted-foreground line-through">
{formatPrice(product.regular_price)} {formatPrice(product.regular_price)}
</span> </span>
</> </>
) : ( ) : (
<span className="text-base font-bold text-gray-900"> <span className="text-base font-bold text-foreground">
{formatPrice(product.price)} {formatPrice(product.price)}
</span> </span>
)} )}

View File

@@ -0,0 +1,26 @@
import { SectionStyleResult } from '@/lib/sectionStyles';
interface SectionBackgroundRendererProps {
bg: SectionStyleResult;
}
export function SectionBackgroundRenderer({ bg }: SectionBackgroundRendererProps) {
if (!bg.backgroundImage) return null;
return (
<div className="absolute inset-0 pointer-events-none z-0">
<img
src={bg.backgroundImage}
alt=""
role="presentation"
className="w-full h-full object-cover"
/>
{bg.hasOverlay && (
<div
className="absolute inset-0 bg-black"
style={{ opacity: bg.overlayOpacity }}
/>
)}
</div>
);
}

View File

@@ -22,6 +22,7 @@ interface SharedContentProps {
textClassName?: string; textClassName?: string;
headingStyle?: React.CSSProperties; // For prose headings override headingStyle?: React.CSSProperties; // For prose headings override
imageStyle?: React.CSSProperties; imageStyle?: React.CSSProperties;
cardStyle?: React.CSSProperties; // For boxed layout background
// Pro Features (for future) // Pro Features (for future)
buttons?: Array<{ text: string, url: string }>; buttons?: Array<{ text: string, url: string }>;
@@ -44,6 +45,7 @@ export const SharedContentLayout: React.FC<SharedContentProps> = ({
buttons, buttons,
imageStyle, imageStyle,
cardStyle,
buttonStyle buttonStyle
}) => { }) => {
@@ -53,186 +55,129 @@ export const SharedContentLayout: React.FC<SharedContentProps> = ({
const isImageTop = imagePosition === 'top'; const isImageTop = imagePosition === 'top';
const isImageBottom = imagePosition === 'bottom'; const isImageBottom = imagePosition === 'bottom';
// Wrapper classes — full = edge-to-edge, contained = narrow readable column, boxed = card at max-w-5xl // Wrapper classes — no width constraints applied here, parent handles it
const containerClasses = cn( const containerClasses = cn(
'w-full mx-auto px-4 sm:px-6 lg:px-8', 'w-full mx-auto px-4 sm:px-6 lg:px-8',
containerWidth === 'contained' ? 'max-w-4xl' containerWidth === 'contained' ? 'max-w-4xl' : '',
: containerWidth === 'boxed' ? 'max-w-5xl' containerWidth === 'boxed' ? 'max-w-5xl' : ''
: '' // full = no max-width cap
); );
const gridClasses = cn( const gridClasses = cn(
'mx-auto', 'mx-auto w-full',
hasImage && (isImageLeft || isImageRight) hasImage && (isImageLeft || isImageRight)
? 'grid grid-cols-1 lg:grid-cols-2 gap-12 items-center' ? 'grid grid-cols-1 lg:grid-cols-2 gap-12 items-center'
: containerWidth === 'full' ? 'w-full' : '' // no extra constraint for contained — outer already limits it : ''
); );
const imageWrapperOrder = isImageRight ? 'lg:order-last' : 'lg:order-first'; const imageWrapperOrder = isImageRight ? 'lg:order-last' : 'lg:order-first';
const safeTextStyle = { ...textStyle };
delete safeTextStyle.textAlign;
const proseStyle = { const proseStyle = {
...textStyle, ...safeTextStyle,
'--tw-prose-headings': headingStyle?.color, '--tw-prose-headings': headingStyle?.color,
'--tw-prose-body': textStyle?.color, '--tw-prose-body': textStyle?.color,
} as React.CSSProperties; } as React.CSSProperties;
return ( return (
<div className={containerClasses}> <div className={containerClasses}>
{containerWidth === 'boxed' ? ( <div className={gridClasses}>
<div className="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden px-6 md:px-10 py-10"> {/* Image Side */}
<div className={gridClasses}> {hasImage && (
{/* Image Side */} <div className={cn(
{hasImage && ( 'flex flex-col',
<div className={cn( imageWrapperOrder,
'relative w-full aspect-[4/3] rounded-2xl overflow-hidden shadow-lg', (isImageTop || isImageBottom) && 'mb-8',
imageWrapperOrder, {
(isImageTop || isImageBottom) && 'mb-8' // spacing if stacked 'items-start': (imageStyle as any)?.alignment === 'left',
)} style={imageStyle}> 'items-center': (imageStyle as any)?.alignment === 'center',
<img 'items-end': (imageStyle as any)?.alignment === 'right',
src={image} }
alt={title || 'Section Image'} )}>
className="absolute inset-0 w-full h-full object-cover"
/>
</div>
)}
{/* Content Side */}
<div className={cn('flex flex-col', hasImage ? 'bg-transparent' : '')}>
{title && (
<h2
className={cn(
"tracking-tight text-current mb-6",
!titleClassName && "text-3xl font-bold sm:text-4xl lg:text-5xl",
titleClassName
)}
style={titleStyle}
>
{title}
</h2>
)}
{text && (
<div
className={cn(
'prose prose-lg max-w-none',
'prose-h1:text-3xl md:prose-h1:text-4xl lg:prose-h1:text-5xl prose-h1:font-bold prose-h1:mt-6 prose-h1:mb-4',
'prose-h2:text-2xl md:prose-h2:text-3xl lg:prose-h2:text-4xl prose-h2:font-bold prose-h2:mt-5 prose-h2:mb-3',
'prose-h3:text-xl md:prose-h3:text-2xl lg:prose-h3:text-3xl prose-h3:font-bold prose-h3:mt-4 prose-h3:mb-2',
'prose-headings:text-[var(--tw-prose-headings)]',
'prose-p:text-[var(--tw-prose-body)]',
'text-[var(--tw-prose-body)]',
className,
textClassName
)}
style={proseStyle}
dangerouslySetInnerHTML={{ __html: text }}
/>
)}
{/* Buttons */}
{buttons && buttons.length > 0 && (
<div className="mt-8 flex flex-wrap gap-4">
{buttons.map((btn, idx) => (
btn.text && btn.url && (
<a
key={idx}
href={btn.url}
className={cn(
"inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 h-10 px-4 py-2",
!buttonStyle?.style?.backgroundColor && "bg-primary",
!buttonStyle?.style?.color && "text-primary-foreground hover:bg-primary/90",
buttonStyle?.classNames
)}
style={buttonStyle?.style}
>
{btn.text}
</a>
)
))}
</div>
)}
</div>
</div>
</div>
) : (
<div className={gridClasses}>
{/* Image Side */}
{hasImage && (
<div className={cn( <div className={cn(
'relative w-full aspect-[4/3] rounded-2xl overflow-hidden shadow-lg', 'relative w-full aspect-[4/3] rounded-2xl overflow-hidden shadow-lg',
imageWrapperOrder, )} style={{
(isImageTop || isImageBottom) && 'mb-8' backgroundColor: imageStyle?.backgroundColor,
)} style={imageStyle}> width: imageStyle?.width,
height: imageStyle?.height,
maxWidth: '100%'
}}>
<img <img
src={image} src={image}
alt={title || 'Section Image'} alt={title || 'Section Image'}
className="absolute inset-0 w-full h-full object-cover" className="absolute inset-0 w-full h-full object-cover"
style={{
objectFit: imageStyle?.objectFit,
objectPosition: (imageStyle as any)?.objectPosition,
}}
/> />
</div> </div>
</div>
)}
{/* Content Side */}
<div className={cn('flex flex-col', hasImage ? 'bg-transparent' : '')}>
{title && (
<h2
className={cn(
"tracking-tight text-current mb-6 w-full",
!titleClassName && "text-3xl font-bold sm:text-4xl lg:text-5xl",
titleClassName
)}
style={titleStyle}
>
{title}
</h2>
)} )}
{/* Content Side */} {text && (
<div className={cn('flex flex-col', hasImage ? 'bg-transparent' : '')}> <div
{title && ( className={cn(
<h2 'prose prose-lg max-w-none w-full',
className={cn( 'prose-h1:text-3xl md:prose-h1:text-4xl lg:prose-h1:text-5xl prose-h1:font-bold prose-h1:mt-6 prose-h1:mb-4',
"tracking-tight text-current mb-6", 'prose-h2:text-2xl md:prose-h2:text-3xl lg:prose-h2:text-4xl prose-h2:font-bold prose-h2:mt-5 prose-h2:mb-3',
!titleClassName && "text-3xl font-bold sm:text-4xl lg:text-5xl", 'prose-h3:text-xl md:prose-h3:text-2xl lg:prose-h3:text-3xl prose-h3:font-bold prose-h3:mt-4 prose-h3:mb-2',
titleClassName 'prose-headings:text-[var(--tw-prose-headings)]',
)} 'prose-p:text-[var(--tw-prose-body)]',
style={titleStyle} 'text-[var(--tw-prose-body)]',
> className,
{title} textClassName
</h2> )}
)} style={proseStyle}
dangerouslySetInnerHTML={{ __html: text }}
/>
)}
{text && ( {/* Buttons */}
<div {buttons && buttons.length > 0 && (
className={cn( <div className={cn(
'prose prose-lg max-w-none', "mt-8 flex flex-wrap gap-4",
'prose-h1:text-3xl md:prose-h1:text-4xl lg:prose-h1:text-5xl prose-h1:font-bold prose-h1:mt-6 prose-h1:mb-4', buttonStyle?.style?.textAlign === 'center' && "justify-center",
'prose-h2:text-2xl md:prose-h2:text-3xl lg:prose-h2:text-4xl prose-h2:font-bold prose-h2:mt-5 prose-h2:mb-3', buttonStyle?.style?.textAlign === 'right' && "justify-end",
'prose-h3:text-xl md:prose-h3:text-2xl lg:prose-h3:text-3xl prose-h3:font-bold prose-h3:mt-4 prose-h3:mb-2', (!buttonStyle?.style?.textAlign || buttonStyle?.style?.textAlign === 'left') && "justify-start"
'prose-headings:text-[var(--tw-prose-headings)]', )}>
'prose-p:text-[var(--tw-prose-body)]', {buttons.map((btn, idx) => (
'text-[var(--tw-prose-body)]', btn.text && btn.url && (
className, <a
textClassName key={idx}
)} href={btn.url}
style={proseStyle} className={cn(
dangerouslySetInnerHTML={{ __html: text }} "inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 h-10 px-4 py-2",
/> !buttonStyle?.style?.backgroundColor && "bg-primary",
)} !buttonStyle?.style?.color && "text-primary-foreground hover:bg-primary/90",
buttonStyle?.classNames
{/* Buttons */} )}
{buttons && buttons.length > 0 && ( style={buttonStyle?.style}
<div className="mt-8 flex flex-wrap gap-4"> >
{buttons.map((btn, idx) => ( {btn.text}
btn.text && btn.url && ( </a>
<a )
key={idx} ))}
href={btn.url} </div>
className={cn( )}
"inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 h-10 px-4 py-2",
!buttonStyle?.style?.backgroundColor && "bg-primary",
!buttonStyle?.style?.color && "text-primary-foreground hover:bg-primary/90",
buttonStyle?.classNames
)}
style={buttonStyle?.style}
>
{btn.text}
</a>
)
))}
</div>
)}
</div>
</div> </div>
)} </div>
</div> </div>
); );
}; };

View File

@@ -14,6 +14,7 @@ interface AppearanceSettings {
grid_columns: string; grid_columns: string;
card_style: string; card_style: string;
aspect_ratio: string; aspect_ratio: string;
filter_layout?: 'basic' | 'rich_sidebar';
}; };
elements: { elements: {
category_filter: boolean; category_filter: boolean;
@@ -86,6 +87,7 @@ export function useShopSettings() {
card_style: 'card' as string, card_style: 'card' as string,
aspect_ratio: 'square' as string, aspect_ratio: 'square' as string,
card_text_align: 'left' as string, card_text_align: 'left' as string,
filter_layout: 'basic' as 'basic' | 'rich_sidebar',
}, },
elements: { elements: {
category_filter: true, category_filter: true,

View File

@@ -0,0 +1,17 @@
import { useState, useEffect } from 'react';
export function useDebounce<T>(value: T, delay: number): T {
const [debouncedValue, setDebouncedValue] = useState<T>(value);
useEffect(() => {
const timer = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(timer);
};
}, [value, delay]);
return debouncedValue;
}

View File

@@ -166,13 +166,13 @@ function ClassicLayout({ children }: BaseLayoutProps) {
<div className="relative"> <div className="relative">
<ShoppingCart className="h-5 w-5" /> <ShoppingCart className="h-5 w-5" />
{itemCount > 0 && ( {itemCount > 0 && (
<span className="absolute -top-2 -right-2 h-5 w-5 rounded-full bg-gray-900 text-white text-xs flex items-center justify-center font-medium"> <span className="absolute -top-2 -right-2 h-5 w-5 rounded-full bg-primary text-primary-foreground text-xs flex items-center justify-center font-medium">
{itemCount} {itemCount}
</span> </span>
)} )}
</div> </div>
<span className="hidden lg:block"> <span className="hidden lg:block">
Cart ({itemCount}) Cart
</span> </span>
</button> </button>
)} )}
@@ -261,7 +261,7 @@ function ClassicLayout({ children }: BaseLayoutProps) {
<button onClick={openCart} className="font-[inherit] flex flex-col items-center gap-1 px-4 py-2 text-xs font-medium text-gray-700 hover:text-gray-900 relative"> <button onClick={openCart} className="font-[inherit] flex flex-col items-center gap-1 px-4 py-2 text-xs font-medium text-gray-700 hover:text-gray-900 relative">
<ShoppingCart className="h-5 w-5" /> <ShoppingCart className="h-5 w-5" />
{itemCount > 0 && ( {itemCount > 0 && (
<span className="absolute top-1 right-2 h-4 w-4 rounded-full bg-gray-900 text-white text-xs flex items-center justify-center"> <span className="absolute top-1 right-2 h-4 w-4 rounded-full bg-primary text-primary-foreground text-xs flex items-center justify-center">
{itemCount} {itemCount}
</span> </span>
)} )}
@@ -497,7 +497,15 @@ function ModernLayout({ children }: BaseLayoutProps) {
)} )}
{headerSettings.elements.cart && ( {headerSettings.elements.cart && (
<button onClick={openCart} className="font-[inherit] flex items-center gap-1 text-sm font-medium text-gray-700 hover:text-gray-900 transition-colors"> <button onClick={openCart} className="font-[inherit] flex items-center gap-1 text-sm font-medium text-gray-700 hover:text-gray-900 transition-colors">
<ShoppingCart className="h-4 w-4" /> Cart ({itemCount}) <div className="relative">
<ShoppingCart className="h-4 w-4" />
{itemCount > 0 && (
<span className="absolute -top-2 -right-2 h-4 w-4 rounded-full bg-primary text-primary-foreground text-[10px] flex items-center justify-center font-medium">
{itemCount}
</span>
)}
</div>
<span>Cart</span>
</button> </button>
)} )}
</nav> </nav>
@@ -657,7 +665,15 @@ function BoutiqueLayout({ children }: BaseLayoutProps) {
)} )}
{headerSettings.elements.cart && ( {headerSettings.elements.cart && (
<button onClick={openCart} className="font-[inherit] flex items-center gap-1 text-sm uppercase tracking-wider text-gray-700 hover:text-gray-900 transition-colors"> <button onClick={openCart} className="font-[inherit] flex items-center gap-1 text-sm uppercase tracking-wider text-gray-700 hover:text-gray-900 transition-colors">
<ShoppingCart className="h-4 w-4" /> Cart ({itemCount}) <div className="relative">
<ShoppingCart className="h-4 w-4" />
{itemCount > 0 && (
<span className="absolute -top-2 -right-2 h-4 w-4 rounded-full bg-primary text-primary-foreground text-[10px] flex items-center justify-center font-medium">
{itemCount}
</span>
)}
</div>
<span>Cart</span>
</button> </button>
)} )}
</nav> </nav>

View File

@@ -93,6 +93,7 @@ const endpoints = {
product: (id: number) => `/shop/products/${id}`, product: (id: number) => `/shop/products/${id}`,
categories: '/shop/categories', categories: '/shop/categories',
search: '/shop/search', search: '/shop/search',
collection: (slug: string) => `/shop/collections/${slug}`,
}, },
cart: { cart: {
get: '/cart', get: '/cart',
@@ -115,6 +116,7 @@ const endpoints = {
profile: '/account/profile', profile: '/account/profile',
password: '/account/password', password: '/account/password',
addresses: '/account/addresses', addresses: '/account/addresses',
affiliateCollections: '/account/affiliate/collections',
}, },
}; };

View File

@@ -345,10 +345,18 @@ export default function Addresses() {
<div className="text-sm text-gray-700 space-y-1 mb-4"> <div className="text-sm text-gray-700 space-y-1 mb-4">
<p className="font-medium">{address.first_name} {address.last_name}</p> <p className="font-medium">{address.first_name} {address.last_name}</p>
{address.company && <p>{address.company}</p>} {address.company && <p>{address.company}</p>}
<p>{address.address_1}</p> {address.formatted_address ? (
{address.address_2 && <p>{address.address_2}</p>} <p className="whitespace-pre-wrap">{address.formatted_address}</p>
<p>{address.city}, {address.state} {address.postcode}</p> ) : (
<p>{address.country}</p> <>
<p>{address.address_1}</p>
{address.address_2 && <p>{address.address_2}</p>}
{[address.city, address.state, address.postcode].filter(Boolean).length > 0 && (
<p>{[address.city, address.state, address.postcode].filter(Boolean).join(', ')}</p>
)}
<p>{address.country}</p>
</>
)}
{address.phone && <p className="pt-2">Phone: {address.phone}</p>} {address.phone && <p className="pt-2">Phone: {address.phone}</p>}
{address.email && <p>Email: {address.email}</p>} {address.email && <p>Email: {address.email}</p>}
</div> </div>
@@ -429,6 +437,7 @@ export default function Addresses() {
key={field.key} key={field.key}
field={field} field={field}
value={getFieldValue(field.key)} value={getFieldValue(field.key)}
valueLabel={getFieldValue(field.key + '_label')}
onChange={(v) => setFieldValue(field.key, v)} onChange={(v) => setFieldValue(field.key, v)}
countryOptions={countryOptions} countryOptions={countryOptions}
stateOptions={stateOptions} stateOptions={stateOptions}

View File

@@ -0,0 +1,422 @@
import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient, keepPreviousData } from '@tanstack/react-query';
import { api } from '@/lib/api/client';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Plus, Trash2, Edit2, Link as LinkIcon, Search, Copy, CheckCircle, X, ChevronLeft } from 'lucide-react';
import { toast } from 'sonner';
import { Link } from 'react-router-dom';
import { useDebounce } from '@/hooks/useDebounce';
interface Product {
id: number;
name: string;
slug: string;
image?: string;
price_html?: string;
}
interface Collection {
id: number;
title: string;
slug: string;
description: string;
product_ids: number[];
link: string;
}
export function AffiliateCollections() {
const config = (window as any).woonoowCustomer || {};
const enableCuratedCollections = config.affiliateSettings?.enableCuratedCollections !== false;
const queryClient = useQueryClient();
const [isFormOpen, setIsFormOpen] = useState(false);
const [editingCollection, setEditingCollection] = useState<Collection | null>(null);
const [title, setTitle] = useState('');
const [description, setDescription] = useState('');
const [selectedProducts, setSelectedProducts] = useState<Product[]>([]);
const [searchQuery, setSearchQuery] = useState('');
const debouncedSearch = useDebounce(searchQuery, 300);
const [copiedId, setCopiedId] = useState<string | null>(null);
const { data: collections, isLoading: isLoadingCollections } = useQuery<Collection[]> ({
queryKey: ['affiliate-collections'],
queryFn: async () => {
const res: any = await api.get('/account/affiliate/collections');
return Array.isArray(res) ? res : [];
}
});
const { data: searchResults, isLoading: isSearching } = useQuery({
queryKey: ['collection-product-search', debouncedSearch],
queryFn: async () => {
if (!debouncedSearch) return [];
try {
const res: any = await api.get(`/shop/products?search=${encodeURIComponent(debouncedSearch)}&per_page=5`);
return res.products || [];
} catch (err) {
return [];
}
},
enabled: debouncedSearch.length > 2,
placeholderData: keepPreviousData
});
// When editing, fetch details of products so we can show their names/images
const { data: editingProducts } = useQuery({
queryKey: ['collection-editing-products', editingCollection?.id],
queryFn: async () => {
if (!editingCollection || editingCollection.product_ids.length === 0) return [];
const res: any = await api.get(`/shop/products?include=${editingCollection.product_ids.join(',')}&per_page=20`);
return res.products || [];
},
enabled: !!editingCollection
});
// Pre-fill form when editingProducts is loaded
React.useEffect(() => {
if (editingCollection && editingProducts) {
setTitle(editingCollection.title);
setDescription(editingCollection.description);
setSelectedProducts(editingProducts);
}
}, [editingCollection, editingProducts]);
const resetForm = () => {
setIsFormOpen(false);
setEditingCollection(null);
setTitle('');
setDescription('');
setSelectedProducts([]);
setSearchQuery('');
};
const createMutation = useMutation({
mutationFn: async (data: any) => {
return api.post('/account/affiliate/collections', data);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['affiliate-collections'] });
toast.success('Collection created successfully!');
resetForm();
},
onError: (err: any) => {
toast.error(err.message || 'Failed to create collection');
}
});
const updateMutation = useMutation({
mutationFn: async ({ id, data }: { id: number, data: any }) => {
return api.put(`/account/affiliate/collections/${id}`, data);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['affiliate-collections'] });
toast.success('Collection updated successfully!');
resetForm();
},
onError: (err: any) => {
toast.error(err.message || 'Failed to update collection');
}
});
const deleteMutation = useMutation({
mutationFn: async (id: number) => {
return api.delete(`/account/affiliate/collections/${id}`);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['affiliate-collections'] });
toast.success('Collection deleted!');
}
});
const handleSave = () => {
if (!title) {
toast.error('Title is required');
return;
}
if (selectedProducts.length > 20) {
toast.error('Maximum 20 products allowed per collection');
return;
}
const data = {
title,
description,
product_ids: selectedProducts.map(p => p.id)
};
if (editingCollection) {
updateMutation.mutate({ id: editingCollection.id, data });
} else {
createMutation.mutate(data);
}
};
const toggleProduct = (product: Product) => {
const exists = selectedProducts.find(p => p.id === product.id);
if (exists) {
setSelectedProducts(prev => prev.filter(p => p.id !== product.id));
} else {
if (selectedProducts.length >= 20) {
toast.error('Maximum 20 products allowed');
return;
}
setSelectedProducts(prev => [...prev, product]);
}
};
const copyToClipboard = (link: string, id: string) => {
navigator.clipboard.writeText(link);
setCopiedId(id);
toast.success('Link copied to clipboard!');
setTimeout(() => setCopiedId(null), 2000);
};
if (isLoadingCollections) return <div>Loading collections...</div>;
if (!enableCuratedCollections) {
return (
<div className="space-y-6">
<div className="mb-2">
<Link to="/my-account/affiliate" className="inline-flex items-center text-sm font-medium text-gray-500 hover:text-gray-900">
<ChevronLeft className="w-4 h-4 mr-1" /> Back to Affiliate Dashboard
</Link>
</div>
<h2 className="text-xl font-bold tracking-tight">My Curated Collections</h2>
<p className="text-muted-foreground">This feature has been disabled by the administrator.</p>
</div>
);
}
return (
<div className="space-y-6">
<div className="mb-2">
<Link to="/my-account/affiliate" className="inline-flex items-center text-sm font-medium text-gray-500 hover:text-gray-900">
<ChevronLeft className="w-4 h-4 mr-1" /> Back to Affiliate Dashboard
</Link>
</div>
<div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
<div>
<h2 className="text-xl font-bold tracking-tight">My Curated Collections</h2>
<p className="text-muted-foreground">Group your favorite products into a single shareable link.</p>
</div>
{!isFormOpen && (
<Button onClick={() => setIsFormOpen(true)} className="gap-2">
<Plus className="w-4 h-4" /> New Collection
</Button>
)}
</div>
{isFormOpen && (
<div className="bg-card border rounded-lg p-6 space-y-6">
<div className="flex justify-between items-center">
<h3 className="font-semibold text-lg">
{editingCollection ? 'Edit Collection' : 'Create New Collection'}
</h3>
<Button variant="ghost" size="icon" onClick={resetForm}>
<X className="w-4 h-4" />
</Button>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2 sm:col-span-2">
<label className="text-sm font-medium">Collection Title</label>
<Input
placeholder="e.g., My Summer Favorites"
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
</div>
<div className="space-y-2 sm:col-span-2">
<label className="text-sm font-medium">Description (Optional)</label>
<textarea
placeholder="Tell your audience why you love these products..."
value={description}
onChange={(e) => setDescription(e.target.value)}
className="flex min-h-[80px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
/>
</div>
</div>
<div className="space-y-4 pt-4 border-t">
<div className="flex justify-between items-end">
<label className="text-sm font-medium">Select Products ({selectedProducts.length}/20)</label>
</div>
{/* Selected Products Area */}
{selectedProducts.length > 0 && (
<div className="flex flex-wrap gap-2 mb-4">
{selectedProducts.map(p => (
<div key={p.id} className="flex items-center gap-2 bg-secondary text-secondary-foreground text-xs rounded-full pl-2 pr-1 py-1">
<span className="truncate max-w-[150px]">{p.name}</span>
<button
onClick={() => toggleProduct(p)}
className="hover:bg-background/20 rounded-full p-0.5"
>
<X className="w-3 h-3" />
</button>
</div>
))}
</div>
)}
<div className="relative">
<Search className="absolute left-3 top-2.5 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Search products to add..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-9"
/>
</div>
{/* Search Results Dropdown */}
{searchQuery && (
<div className="border rounded-md divide-y max-h-[300px] overflow-y-auto">
{isSearching && <div className="p-3 text-sm text-center text-muted-foreground">Searching...</div>}
{!isSearching && searchResults?.length === 0 && (
<div className="p-3 text-sm text-center text-muted-foreground">No products found.</div>
)}
{searchResults?.map((product: Product) => {
const isSelected = selectedProducts.some(p => p.id === product.id);
return (
<div
key={product.id}
className={`p-3 flex items-center justify-between hover:bg-muted/50 cursor-pointer transition-colors ${isSelected ? 'bg-primary/5' : ''}`}
onClick={() => toggleProduct(product)}
>
<div className="flex items-center gap-3 overflow-hidden">
{product.image ? (
<img src={product.image} alt={product.name} className="w-10 h-10 object-cover rounded" />
) : (
<div className="w-10 h-10 bg-muted rounded flex-shrink-0"></div>
)}
<div className="truncate">
<div className="font-medium truncate text-sm">{product.name}</div>
<div className="text-xs text-muted-foreground" dangerouslySetInnerHTML={{ __html: product.price_html || '' }} />
</div>
</div>
{isSelected && <CheckCircle className="w-4 h-4 text-primary flex-shrink-0" />}
</div>
);
})}
</div>
)}
</div>
<div className="flex justify-end gap-3 pt-4">
<Button variant="outline" onClick={resetForm}>
Cancel
</Button>
<Button
onClick={handleSave}
disabled={createMutation.isPending || updateMutation.isPending}
>
{(createMutation.isPending || updateMutation.isPending) ? 'Saving...' : 'Save Collection'}
</Button>
</div>
</div>
)}
{!isFormOpen && (!collections || collections.length === 0) ? (
<div className="text-center py-12 bg-muted/30 rounded-lg border border-dashed">
<h3 className="font-semibold mb-2">No collections yet</h3>
<p className="text-sm text-muted-foreground mb-4">
Create a curated list of products to share with your audience.
</p>
<Button onClick={() => setIsFormOpen(true)}>
Create First Collection
</Button>
</div>
) : (
<div className="grid gap-4 md:grid-cols-2">
{collections?.map(collection => (
<div key={collection.id} className="border rounded-lg p-5 bg-card flex flex-col">
<div className="flex justify-between items-start mb-2">
<div>
<h3 className="font-semibold text-lg line-clamp-1">{collection.title}</h3>
<p className="text-sm text-muted-foreground">
{collection.product_ids.length} products
</p>
</div>
<div className="flex gap-1">
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={() => {
setEditingCollection(collection);
setIsFormOpen(true);
}}
>
<Edit2 className="w-4 h-4" />
</Button>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10"
onClick={() => {
if(window.confirm('Delete this collection?')) {
deleteMutation.mutate(collection.id);
}
}}
>
<Trash2 className="w-4 h-4" />
</Button>
</div>
</div>
{collection.description && (
<p className="text-sm text-muted-foreground line-clamp-2 mb-4">
{collection.description}
</p>
)}
<div className="mt-auto pt-4 space-y-3">
<div className="space-y-1">
<span className="text-xs font-medium text-gray-500">Collection Link (Shows all products)</span>
<div className="flex gap-2">
<Input
readOnly
value={collection.link}
className="bg-muted h-9 text-xs font-mono"
/>
<Button
size="icon"
className="h-9 w-9 shrink-0"
variant={copiedId === `col-${collection.id}` ? "default" : "outline"}
onClick={() => copyToClipboard(collection.link, `col-${collection.id}`)}
>
{copiedId === `col-${collection.id}` ? <CheckCircle className="w-4 h-4" /> : <Copy className="w-4 h-4" />}
</Button>
</div>
</div>
<div className="space-y-1">
<span className="text-xs font-medium text-gray-500">Smart Link (Redirects to random product)</span>
<div className="flex gap-2">
<Input
readOnly
value={`${window.location.origin}/go/${collection.slug}`}
className="bg-muted h-9 text-xs font-mono border-primary/20"
/>
<Button
size="icon"
className="h-9 w-9 shrink-0"
variant={copiedId === `smart-${collection.id}` ? "default" : "outline"}
onClick={() => copyToClipboard(`${window.location.origin}/go/${collection.slug}`, `smart-${collection.id}`)}
>
{copiedId === `smart-${collection.id}` ? <CheckCircle className="w-4 h-4" /> : <Copy className="w-4 h-4" />}
</Button>
</div>
</div>
</div>
</div>
))}
</div>
)}
</div>
);
}

View File

@@ -3,8 +3,9 @@ import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '@/lib/api/client'; import { api } from '@/lib/api/client';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
import { Copy, CheckCircle, Activity, DollarSign, ChevronRight, Clock, Info, Wallet, CreditCard } from 'lucide-react'; import { Copy, CheckCircle, Activity, DollarSign, ChevronRight, Clock, Info, Wallet, CreditCard, Tag } from 'lucide-react';
import { toast } from 'sonner'; import { toast } from 'sonner';
import { Link } from 'react-router-dom';
import { formatPrice, getCurrencySettings } from '@/lib/currency'; import { formatPrice, getCurrencySettings } from '@/lib/currency';
// Affiliate types // Affiliate types
@@ -14,6 +15,17 @@ interface AffiliateProfile {
commission_rate: number; commission_rate: number;
custom_commission_rate: number | null; custom_commission_rate: number | null;
global_commission_rate: number; global_commission_rate: number;
total_earnings: number;
pending_earnings: number;
collections_enabled?: boolean;
}
interface PaginatedReferrals {
referrals: AffiliateReferral[];
total: number;
page: number;
limit: number;
total_pages: number;
} }
interface AffiliateReferral { interface AffiliateReferral {
@@ -130,13 +142,14 @@ export default function AffiliateDashboard() {
}); });
// Fetch referrals // Fetch referrals
const { data: referrals, isLoading: isLoadingReferrals } = useQuery<AffiliateReferral[]>({ const { data: referralsResponse, isLoading: isLoadingReferrals } = useQuery<PaginatedReferrals>({
queryKey: ['affiliate-referrals'], queryKey: ['affiliate-referrals'],
queryFn: async () => { queryFn: async () => {
return await api.get<AffiliateReferral[]>('/account/affiliate/referrals'); return await api.get<PaginatedReferrals>('/account/affiliate/referrals?limit=5');
}, },
enabled: !!profile && profile.status === 'active' enabled: !!profile && profile.status === 'active'
}); });
const referrals = referralsResponse?.referrals || [];
// Fetch payout history // Fetch payout history
const { data: payouts = [], isLoading: isLoadingPayouts } = useQuery<AffiliatePayout[]>({ const { data: payouts = [], isLoading: isLoadingPayouts } = useQuery<AffiliatePayout[]>({
@@ -248,11 +261,8 @@ export default function AffiliateDashboard() {
setTimeout(() => setCopied(false), 2000); setTimeout(() => setCopied(false), 2000);
}; };
const approvedReferrals = (referrals || []).filter((r: any) => r.status === 'approved'); const totalEarnings = profile.total_earnings || 0;
const pendingReferrals = (referrals || []).filter((r: any) => r.status === 'pending'); const pendingEarnings = profile.pending_earnings || 0;
const totalEarnings = approvedReferrals.reduce((sum: number, r: any) => sum + parseFloat(r.commission_amount), 0);
const pendingEarnings = pendingReferrals.reduce((sum: number, r: any) => sum + parseFloat(r.commission_amount), 0);
const handleSavePayment = () => { const handleSavePayment = () => {
if (!selectedMethod) { if (!selectedMethod) {
@@ -421,7 +431,25 @@ export default function AffiliateDashboard() {
{/* Referral Link */} {/* Referral Link */}
<div className="bg-white p-6 rounded-lg border"> <div className="bg-white p-6 rounded-lg border">
<h3 className="text-lg font-semibold mb-4">Your Referral Link</h3> <div className="flex items-center justify-between mb-4">
<h3 className="text-lg font-semibold">Your Referral Link</h3>
<div className="flex items-center gap-4">
{profile?.collections_enabled !== false && (
<Link
to="/my-account/affiliate/collections"
className="text-sm font-medium text-primary hover:opacity-80 flex items-center"
>
My Collections & Smart Links <ChevronRight className="w-4 h-4 ml-1" />
</Link>
)}
<Link
to="/my-account/affiliate/links"
className="text-sm font-medium text-primary hover:opacity-80 flex items-center"
>
Build Links <ChevronRight className="w-4 h-4 ml-1" />
</Link>
</div>
</div>
<div className="flex gap-2"> <div className="flex gap-2">
<Input <Input
value={referralLink} value={referralLink}
@@ -443,7 +471,17 @@ export default function AffiliateDashboard() {
{/* Referrals */} {/* Referrals */}
<div> <div>
<h3 className="text-lg font-semibold mb-4">Recent Referrals</h3> <div className="flex items-center justify-between mb-4">
<h3 className="text-lg font-semibold">Recent Referrals</h3>
{referralsResponse && referralsResponse.total > 5 && (
<Link
to="/my-account/affiliate/referrals"
className="text-sm font-medium text-primary hover:opacity-80 flex items-center transition-opacity"
>
View All <ChevronRight className="w-4 h-4 ml-1" />
</Link>
)}
</div>
{isLoadingReferrals ? ( {isLoadingReferrals ? (
<div className="text-center py-8 text-gray-500">Loading referrals...</div> <div className="text-center py-8 text-gray-500">Loading referrals...</div>
@@ -463,13 +501,12 @@ export default function AffiliateDashboard() {
<div className="space-y-1"> <div className="space-y-1">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<span className="font-medium text-gray-900">Order #{ref.order_id}</span> <span className="font-medium text-gray-900">Order #{ref.order_id}</span>
<span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${ <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${ref.status === 'approved'
ref.status === 'approved'
? 'bg-green-100 text-green-800' ? 'bg-green-100 text-green-800'
: ref.status === 'pending' : ref.status === 'pending'
? 'bg-yellow-100 text-yellow-800' ? 'bg-yellow-100 text-yellow-800'
: 'bg-red-100 text-red-800' : 'bg-red-100 text-red-800'
}`}> }`}>
{ref.status} {ref.status}
</span> </span>
</div> </div>
@@ -491,6 +528,12 @@ export default function AffiliateDashboard() {
})} })}
</span> </span>
)} )}
{(ref.utm_campaign || ref.utm_source) && (
<span className="flex items-center gap-1 text-purple-600">
<Tag className="w-3 h-3" />
{[ref.utm_campaign, ref.utm_source].filter(Boolean).join(' / ')}
</span>
)}
</div> </div>
</div> </div>
<div className="text-right"> <div className="text-right">
@@ -527,11 +570,10 @@ export default function AffiliateDashboard() {
<div key={payout.id} className="bg-white p-4 rounded-lg border"> <div key={payout.id} className="bg-white p-4 rounded-lg border">
<div className="flex items-start justify-between"> <div className="flex items-start justify-between">
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<div className={`p-2 rounded-lg ${ <div className={`p-2 rounded-lg ${payout.status === 'completed'
payout.status === 'completed'
? 'bg-green-100 text-green-600' ? 'bg-green-100 text-green-600'
: 'bg-yellow-100 text-yellow-600' : 'bg-yellow-100 text-yellow-600'
}`}> }`}>
<Wallet className="w-5 h-5" /> <Wallet className="w-5 h-5" />
</div> </div>
<div> <div>
@@ -544,11 +586,10 @@ export default function AffiliateDashboard() {
</div> </div>
</div> </div>
<div className="text-right"> <div className="text-right">
<span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${ <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${payout.status === 'completed'
payout.status === 'completed'
? 'bg-green-100 text-green-800' ? 'bg-green-100 text-green-800'
: 'bg-yellow-100 text-yellow-800' : 'bg-yellow-100 text-yellow-800'
}`}> }`}>
{payout.status} {payout.status}
</span> </span>
<div className="text-xs text-gray-400 mt-1"> <div className="text-xs text-gray-400 mt-1">
@@ -605,11 +646,10 @@ export default function AffiliateDashboard() {
setSelectedMethod(method); setSelectedMethod(method);
setPaymentFormData({}); setPaymentFormData({});
}} }}
className={`px-4 py-2 rounded-lg border text-sm transition-colors ${ className={`px-4 py-2 rounded-lg border text-sm transition-colors ${selectedMethod === method
selectedMethod === method
? 'bg-purple-100 border-purple-500 text-purple-700' ? 'bg-purple-100 border-purple-500 text-purple-700'
: 'bg-white border-gray-200 hover:bg-gray-50' : 'bg-white border-gray-200 hover:bg-gray-50'
}`} }`}
> >
{PAYMENT_METHOD_LABELS[method] || method} {PAYMENT_METHOD_LABELS[method] || method}
</button> </button>

View File

@@ -0,0 +1,60 @@
import React from 'react';
import { Link } from 'react-router-dom';
import { ChevronLeft } from 'lucide-react';
import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api/client';
import { AffiliateLinkBuilder } from './components/AffiliateLinkBuilder';
interface AffiliateProfile {
status: string;
referral_code: string;
}
export default function AffiliateLinks() {
const { data: profile, isLoading } = useQuery<AffiliateProfile | null>({
queryKey: ['affiliate-profile'],
queryFn: async () => {
try {
return await api.get('/account/affiliate');
} catch (err: any) {
if (err.response?.status === 404) return null;
throw err;
}
},
});
if (isLoading) {
return <div className="animate-pulse h-64 bg-gray-100 rounded-lg"></div>;
}
if (!profile || profile.status !== 'active') {
return (
<div className="space-y-6">
<div className="mb-6">
<Link to="/my-account/affiliate" className="inline-flex items-center text-sm font-medium text-gray-500 hover:text-gray-900">
<ChevronLeft className="w-4 h-4 mr-1" /> Back to Affiliate Dashboard
</Link>
</div>
<h2 className="text-2xl font-bold">Link Builder</h2>
<p className="text-gray-500">You do not have an active affiliate account.</p>
</div>
);
}
return (
<div className="space-y-6">
<div className="mb-6">
<Link to="/my-account/affiliate" className="inline-flex items-center text-sm font-medium text-gray-500 hover:text-gray-900">
<ChevronLeft className="w-4 h-4 mr-1" /> Back to Affiliate Dashboard
</Link>
</div>
<div>
<h2 className="text-2xl font-bold">Affiliate Link Builder</h2>
<p className="text-muted-foreground mt-1">Create custom links to products and track your campaigns.</p>
</div>
<AffiliateLinkBuilder referralCode={profile.referral_code} />
</div>
);
}

View File

@@ -0,0 +1,206 @@
import React, { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Link } from 'react-router-dom';
import { api } from '@/lib/api/client';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { CheckCircle, Clock, Info, ArrowLeft, ChevronLeft, ChevronRight, Search, User } from 'lucide-react';
import { getCurrencySettings } from '@/lib/currency';
interface AffiliateReferral {
id: number;
status: 'pending' | 'approved' | 'rejected';
commission_amount: string;
created_at: string;
order_id: number;
currency: string;
approved_at?: string;
cancelled_reason?: string;
customer_name?: string;
customer_email?: string;
}
interface PaginatedReferrals {
referrals: AffiliateReferral[];
total: number;
page: number;
limit: number;
total_pages: number;
}
function formatAmount(amount: number | string, currency?: string): string {
const amountNum = typeof amount === 'string' ? parseFloat(amount) : amount;
const settings = getCurrencySettings();
const decimals = currency === 'IDR' ? 0 : settings.decimals;
const rounded = amountNum.toFixed(decimals);
const [integerPart, decimalPart] = rounded.split('.');
const formattedInteger = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, settings.thousandSeparator);
const formattedNum = (decimals > 0 && decimalPart)
? `${formattedInteger}${settings.decimalSeparator}${decimalPart}`
: formattedInteger;
return `${settings.symbol}${formattedNum}`;
}
export default function AffiliateReferrals() {
const [page, setPage] = useState(1);
const [orderIdSearch, setOrderIdSearch] = useState('');
const [debouncedSearch, setDebouncedSearch] = useState('');
const limit = 20;
// Simple debounce for search
React.useEffect(() => {
const timer = setTimeout(() => {
setDebouncedSearch(orderIdSearch);
setPage(1); // Reset page on new search
}, 500);
return () => clearTimeout(timer);
}, [orderIdSearch]);
const { data: response, isLoading } = useQuery<PaginatedReferrals>({
queryKey: ['affiliate-referrals-full', page, limit, debouncedSearch],
queryFn: async () => {
const searchParam = debouncedSearch ? `&order_id=${encodeURIComponent(debouncedSearch)}` : '';
return await api.get<PaginatedReferrals>(`/account/affiliate/referrals?limit=${limit}&page=${page}${searchParam}`);
},
});
const referrals = response?.referrals || [];
const totalPages = response?.total_pages || 1;
return (
<div className="space-y-6">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
<div className="flex items-center gap-4">
<Link to="/my-account/affiliate">
<Button variant="outline" size="icon" className="h-8 w-8 rounded-full flex-shrink-0">
<ArrowLeft className="w-4 h-4" />
</Button>
</Link>
<div>
<h2 className="text-2xl font-bold">All Referrals</h2>
<p className="text-gray-500 mt-1 text-sm">
{response ? `Showing ${referrals.length} of ${response.total} referrals` : 'Loading referrals...'}
</p>
</div>
</div>
<div className="relative w-full sm:max-w-xs">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
<Input
placeholder="Search by Order ID..."
className="pl-9 w-full"
value={orderIdSearch}
onChange={(e) => setOrderIdSearch(e.target.value)}
/>
</div>
</div>
{isLoading ? (
<div className="text-center py-12 text-gray-500">Loading referrals...</div>
) : referrals.length === 0 ? (
<div className="text-center py-12 text-gray-500 border rounded-lg bg-gray-50">
No referrals found.
</div>
) : (
<div className="space-y-4">
{referrals.map((ref: AffiliateReferral) => {
const createdDate = new Date(ref.created_at);
const approvedDate = ref.approved_at ? new Date(ref.approved_at) : null;
return (
<div key={ref.id} className="bg-white p-4 rounded-lg border hover:shadow-md transition-shadow">
<div className="flex items-start justify-between">
<div className="space-y-1">
<div className="flex items-center gap-2">
<span className="font-medium text-gray-900">Order #{ref.order_id}</span>
<span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${
ref.status === 'approved'
? 'bg-green-100 text-green-800'
: ref.status === 'pending'
? 'bg-yellow-100 text-yellow-800'
: 'bg-red-100 text-red-800'
}`}>
{ref.status}
</span>
</div>
{ref.customer_name && (
<div className="flex items-center gap-1 text-sm text-gray-600 mt-1">
<User className="w-3.5 h-3.5" />
<span>{ref.customer_name}</span>
{ref.customer_email && <span className="text-gray-400">({ref.customer_email})</span>}
</div>
)}
<div className="flex items-center gap-4 text-sm text-gray-500 mt-2">
<span className="flex items-center gap-1">
<Clock className="w-3 h-3" />
{createdDate.toLocaleDateString('id-ID', {
year: 'numeric',
month: 'short',
day: 'numeric'
})}
</span>
{ref.status === 'approved' && approvedDate && (
<span className="flex items-center gap-1 text-green-600">
<CheckCircle className="w-3 h-3" />
Approved {approvedDate.toLocaleDateString('id-ID', {
month: 'short',
day: 'numeric',
year: 'numeric'
})}
</span>
)}
</div>
</div>
<div className="text-right">
<div className="text-lg font-bold text-gray-900">
{formatAmount(ref.commission_amount, ref.currency)}
</div>
</div>
</div>
{ref.status === 'rejected' && ref.cancelled_reason && (
<div className="mt-3 p-3 bg-red-50 dark:bg-red-900/20 rounded-md">
<div className="flex items-start gap-2">
<Info className="w-4 h-4 text-red-600 mt-0.5 flex-shrink-0" />
<div className="text-xs text-red-800 dark:text-red-200">
Reason: {ref.cancelled_reason}
</div>
</div>
</div>
)}
</div>
);
})}
{/* Pagination */}
{totalPages > 1 && (
<div className="flex items-center justify-between pt-4">
<div className="text-sm text-gray-500">
Page {page} of {totalPages}
</div>
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
onClick={() => setPage(p => Math.max(1, p - 1))}
disabled={page <= 1}
>
<ChevronLeft className="w-4 h-4 mr-1" /> Previous
</Button>
<Button
variant="outline"
size="sm"
onClick={() => setPage(p => Math.min(totalPages, p + 1))}
disabled={page >= totalPages}
>
Next <ChevronRight className="w-4 h-4 ml-1" />
</Button>
</div>
</div>
)}
</div>
)}
</div>
);
}

View File

@@ -19,6 +19,9 @@ import { toast } from 'sonner';
import SEOHead from '@/components/SEOHead'; import SEOHead from '@/components/SEOHead';
import { formatPrice } from '@/lib/currency'; import { formatPrice } from '@/lib/currency';
const formatDate = (dateStr: string) =>
new Date(dateStr).toLocaleDateString(undefined, { day: 'numeric', month: 'short', year: 'numeric' });
interface SubscriptionOrder { interface SubscriptionOrder {
id: number; id: number;
order_id: number; order_id: number;
@@ -43,7 +46,11 @@ interface Subscription {
end_date: string | null; end_date: string | null;
last_payment_date: string | null; last_payment_date: string | null;
payment_method: string; payment_method: string;
payment_method_title: string;
pause_count: number; pause_count: number;
max_pause_count?: number;
pauses_remaining?: number | null;
paused_at?: string | null;
can_pause: boolean; can_pause: boolean;
can_resume: boolean; can_resume: boolean;
can_cancel: boolean; can_cancel: boolean;
@@ -51,12 +58,12 @@ interface Subscription {
} }
const statusStyles: Record<string, string> = { const statusStyles: Record<string, string> = {
'pending': 'bg-yellow-100 text-yellow-800', 'pending': 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300',
'active': 'bg-green-100 text-green-800', 'active': 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300',
'on-hold': 'bg-blue-100 text-blue-800', 'on-hold': 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300',
'cancelled': 'bg-gray-100 text-gray-800', 'cancelled': 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300',
'expired': 'bg-red-100 text-red-800', 'expired': 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-300',
'pending-cancel': 'bg-orange-100 text-orange-800', 'pending-cancel': 'bg-orange-100 text-orange-800 dark:bg-orange-900/30 dark:text-orange-300',
}; };
const statusLabels: Record<string, string> = { const statusLabels: Record<string, string> = {
@@ -124,7 +131,7 @@ export default function SubscriptionDetail() {
if (response.order_id) { if (response.order_id) {
// Determine destination based on functionality // Determine destination based on functionality
// If manual payment required or just improved UX, go to payment page // If manual payment required or just improved UX, go to payment page
navigate(`/order-pay/${response.order_id}`); navigate(`/checkout/pay/${response.order_id}`);
} }
} catch (error: any) { } catch (error: any) {
toast.error(error.message || 'Failed to renew'); toast.error(error.message || 'Failed to renew');
@@ -166,7 +173,7 @@ export default function SubscriptionDetail() {
{/* Back button */} {/* Back button */}
<Link <Link
to="/my-account/subscriptions" to="/my-account/subscriptions"
className="inline-flex items-center text-sm text-gray-500 hover:text-gray-700" className="inline-flex items-center text-sm text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
> >
<ArrowLeft className="h-4 w-4 mr-1" /> <ArrowLeft className="h-4 w-4 mr-1" />
Back to Subscriptions Back to Subscriptions
@@ -179,8 +186,8 @@ export default function SubscriptionDetail() {
<Repeat className="h-6 w-6" /> <Repeat className="h-6 w-6" />
Subscription #{subscription.id} Subscription #{subscription.id}
</h1> </h1>
<p className="text-gray-500 mt-1"> <p className="text-gray-500 dark:text-gray-400 mt-1">
Started {new Date(subscription.start_date).toLocaleDateString()} Started {formatDate(subscription.start_date)}
</p> </p>
</div> </div>
<span className={`px-3 py-1 rounded-full text-sm font-medium ${statusStyles[subscription.status] || 'bg-gray-100'}`}> <span className={`px-3 py-1 rounded-full text-sm font-medium ${statusStyles[subscription.status] || 'bg-gray-100'}`}>
@@ -189,7 +196,7 @@ export default function SubscriptionDetail() {
</div> </div>
{/* Product Info Card */} {/* Product Info Card */}
<div className="bg-white rounded-lg border p-6"> <div className="bg-card rounded-lg border p-6">
<div className="flex items-start gap-4"> <div className="flex items-start gap-4">
{subscription.product_image ? ( {subscription.product_image ? (
<img <img
@@ -198,16 +205,16 @@ export default function SubscriptionDetail() {
className="w-20 h-20 object-cover rounded" className="w-20 h-20 object-cover rounded"
/> />
) : ( ) : (
<div className="w-20 h-20 bg-gray-100 rounded flex items-center justify-center"> <div className="w-20 h-20 bg-gray-100 dark:bg-gray-700 rounded flex items-center justify-center">
<Package className="h-10 w-10 text-gray-400" /> <Package className="h-10 w-10 text-gray-400 dark:text-gray-500" />
</div> </div>
)} )}
<div className="flex-1"> <div className="flex-1">
<h2 className="text-xl font-semibold">{subscription.product_name}</h2> <h2 className="text-xl font-semibold">{subscription.product_name}</h2>
<p className="text-gray-500">{subscription.billing_schedule}</p> <p className="text-gray-500 dark:text-gray-400">{subscription.billing_schedule}</p>
<p className="text-2xl font-bold mt-2"> <p className="text-2xl font-bold mt-2">
{formatPrice(subscription.recurring_amount)} {formatPrice(subscription.recurring_amount)}
<span className="text-sm font-normal text-gray-500"> <span className="text-sm font-normal text-gray-500 dark:text-gray-400">
/{subscription.billing_period} /{subscription.billing_period}
</span> </span>
</p> </p>
@@ -216,65 +223,111 @@ export default function SubscriptionDetail() {
</div> </div>
{/* Billing Details */} {/* Billing Details */}
<div className="bg-white rounded-lg border p-6"> <div className="bg-card rounded-lg border p-6">
<h3 className="font-semibold mb-4">Billing Details</h3> <h3 className="font-semibold mb-4">Billing Details</h3>
<div className="grid grid-cols-2 gap-4"> <div className="grid grid-cols-2 gap-4">
<div> <div>
<p className="text-sm text-gray-500">Start Date</p> <p className="text-sm text-gray-500 dark:text-gray-400">Start Date</p>
<p className="font-medium">{new Date(subscription.start_date).toLocaleDateString()}</p> <p className="font-medium">{formatDate(subscription.start_date)}</p>
</div> </div>
{subscription.next_payment_date && ( {subscription.next_payment_date && (
<div> <div>
<p className="text-sm text-gray-500">Next Payment</p> <p className="text-sm text-gray-500 dark:text-gray-400">Next Payment</p>
<p className="font-medium flex items-center gap-1"> <p className="font-medium flex items-center gap-1">
<Calendar className="h-4 w-4 text-gray-400" /> <Calendar className="h-4 w-4 text-gray-400 dark:text-gray-500" />
{new Date(subscription.next_payment_date).toLocaleDateString()} {formatDate(subscription.next_payment_date!)}
</p> </p>
</div> </div>
)} )}
{subscription.trial_end_date && new Date(subscription.trial_end_date) > new Date() && ( {subscription.trial_end_date && new Date(subscription.trial_end_date) > new Date() && (
<div> <div>
<p className="text-sm text-gray-500">Trial Ends</p> <p className="text-sm text-gray-500 dark:text-gray-400">Trial Ends</p>
<p className="font-medium text-blue-600"> <p className="font-medium text-blue-600">
{new Date(subscription.trial_end_date).toLocaleDateString()} {formatDate(subscription.trial_end_date!)}
</p> </p>
</div> </div>
)} )}
{subscription.end_date && ( {subscription.end_date && (
<div> <div>
<p className="text-sm text-gray-500">End Date</p> <p className="text-sm text-gray-500 dark:text-gray-400">End Date</p>
<p className="font-medium">{new Date(subscription.end_date).toLocaleDateString()}</p> <p className="font-medium">{formatDate(subscription.end_date!)}</p>
</div>
)}
{subscription.status === 'on-hold' && subscription.paused_at && (
<div>
<p className="text-sm text-gray-500 dark:text-gray-400">Paused At</p>
<p className="font-medium text-blue-600">{formatDate(subscription.paused_at)}</p>
</div> </div>
)} )}
<div> <div>
<p className="text-sm text-gray-500">Payment Method</p> <p className="text-sm text-gray-500 dark:text-gray-400">Payment Method</p>
<p className="font-medium flex items-center gap-1"> <p className="font-medium flex items-center gap-1">
<CreditCard className="h-4 w-4 text-gray-400" /> <CreditCard className="h-4 w-4 text-gray-400 dark:text-gray-500" />
{subscription.payment_method || 'Not set'} {subscription.payment_method_title || subscription.payment_method || 'Not set'}
</p> </p>
</div> </div>
<div> <div>
<p className="text-sm text-gray-500">Times Paused</p> <p className="text-sm text-gray-500 dark:text-gray-400">Times Paused</p>
<p className="font-medium">{subscription.pause_count}</p> <p className="font-medium">
{subscription.pause_count}
{subscription.pauses_remaining !== null && subscription.pauses_remaining !== undefined && (
<span className="text-sm text-gray-500 dark:text-gray-400 font-normal">
{' '}/ {subscription.max_pause_count}
</span>
)}
</p>
</div> </div>
</div> </div>
</div> </div>
{/* Actions */} {/* Actions */}
{(subscription.can_pause || subscription.can_resume || subscription.can_cancel) && ( {(subscription.can_pause || subscription.can_resume || subscription.can_cancel) && (
<div className="bg-white rounded-lg border p-6"> <div className="bg-card rounded-lg border p-6">
<h3 className="font-semibold mb-4">Manage Subscription</h3> <h3 className="font-semibold mb-4">Manage Subscription</h3>
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
{subscription.can_pause && ( {subscription.can_pause && (() => {
<Button // H2: disable the pause button when the customer has reached the
variant="outline" // server-enforced limit, so they don't get a generic 500 on click.
onClick={() => handleAction('pause')} const limitReached = subscription.pauses_remaining !== null
disabled={actionLoading} && subscription.pauses_remaining !== undefined
> && subscription.pauses_remaining <= 0;
<Pause className="h-4 w-4 mr-2" /> const tooltip = limitReached
Pause Subscription ? `You have used all ${subscription.max_pause_count} allowed pauses for this subscription.`
</Button> : subscription.pauses_remaining !== null && subscription.pauses_remaining !== undefined
)} ? `${subscription.pauses_remaining} pause${subscription.pauses_remaining === 1 ? '' : 's'} remaining.`
: undefined;
return (
<AlertDialog>
<AlertDialogTrigger asChild>
<Button
variant="outline"
disabled={actionLoading || limitReached}
title={tooltip}
>
<Pause className="h-4 w-4 mr-2" />
Pause Subscription
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Pause Subscription?</AlertDialogTitle>
<AlertDialogDescription>
Pausing will place your subscription on hold until you manually resume it.
When you resume, your next payment date will be recalculated based on your billing cycle.
<br /><br />
{tooltip}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={() => handleAction('pause')}>
Pause
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
);
})()}
{subscription.can_resume && ( {subscription.can_resume && (
<Button <Button
variant="outline" variant="outline"
@@ -301,7 +354,7 @@ export default function SubscriptionDetail() {
{pendingRenewalOrder && ( {pendingRenewalOrder && (
<Button <Button
className='bg-green-600 hover:bg-green-700' className='bg-green-600 hover:bg-green-700'
onClick={() => navigate(`/order-pay/${pendingRenewalOrder.order_id}`)} onClick={() => navigate(`/checkout/pay/${pendingRenewalOrder.order_id}`)}
> >
<CreditCard className="h-4 w-4 mr-2" /> <CreditCard className="h-4 w-4 mr-2" />
Pay Now (#{pendingRenewalOrder.order_id}) Pay Now (#{pendingRenewalOrder.order_id})
@@ -346,7 +399,7 @@ export default function SubscriptionDetail() {
{/* Related Orders */} {/* Related Orders */}
{subscription.orders && subscription.orders.length > 0 && ( {subscription.orders && subscription.orders.length > 0 && (
<div className="bg-white rounded-lg border p-6"> <div className="bg-card rounded-lg border p-6">
<h3 className="font-semibold mb-4 flex items-center gap-2"> <h3 className="font-semibold mb-4 flex items-center gap-2">
<FileText className="h-5 w-5" /> <FileText className="h-5 w-5" />
Payment History Payment History
@@ -356,16 +409,16 @@ export default function SubscriptionDetail() {
<Link <Link
key={order.id} key={order.id}
to={`/my-account/orders/${order.order_id}`} to={`/my-account/orders/${order.order_id}`}
className="flex items-center justify-between p-3 rounded border hover:bg-gray-50 transition-colors" className="flex items-center justify-between p-3 rounded border border-border hover:bg-muted/50 transition-colors"
> >
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<span className="font-medium">Order #{order.order_id}</span> <span className="font-medium text-foreground">Order #{order.order_id}</span>
<span className="text-xs px-2 py-0.5 bg-gray-100 rounded"> <span className="text-xs px-2 py-0.5 bg-muted text-muted-foreground rounded">
{orderTypeLabels[order.order_type] || order.order_type} {orderTypeLabels[order.order_type] || order.order_type}
</span> </span>
</div> </div>
<div className="text-sm text-gray-500"> <div className="text-sm text-muted-foreground">
{new Date(order.created_at).toLocaleDateString()} {formatDate(order.created_at)}
</div> </div>
</Link> </Link>
))} ))}

View File

@@ -0,0 +1,220 @@
import React, { useState } from 'react';
import { useQuery, keepPreviousData } from '@tanstack/react-query';
import { api } from '@/lib/api/client';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Copy, CheckCircle, Link as LinkIcon, Search } from 'lucide-react';
import { toast } from 'sonner';
import { useDebounce } from '@/hooks/useDebounce';
interface AffiliateLinkBuilderProps {
referralCode: string;
}
export function AffiliateLinkBuilder({ referralCode }: AffiliateLinkBuilderProps) {
const [linkType, setLinkType] = useState<'store' | 'product' | 'category'>('store');
const [searchQuery, setSearchQuery] = useState('');
const debouncedSearch = useDebounce(searchQuery, 300);
const [selectedItem, setSelectedItem] = useState<{ id: number; name: string; slug: string } | null>(null);
// UTM parameters
const [utmSource, setUtmSource] = useState('');
const [utmMedium, setUtmMedium] = useState('');
const [utmCampaign, setUtmCampaign] = useState('');
const [copied, setCopied] = useState(false);
// Fetch products or categories based on search
const { data: searchResults, isLoading: isSearching } = useQuery({
queryKey: ['affiliate-search', linkType, debouncedSearch],
queryFn: async () => {
if (!debouncedSearch || linkType === 'store') return [];
const endpoint = linkType === 'product' ? '/shop/products' : '/shop/categories';
try {
// Assuming standard WP/WC REST API format for search
const res: any = await api.get(`${endpoint}?search=${encodeURIComponent(debouncedSearch)}&per_page=5`);
if (linkType === 'product') {
return res.products || [];
}
return Array.isArray(res) ? res : (res.data || []);
} catch (err) {
console.error("Failed to search", err);
return [];
}
},
enabled: debouncedSearch.length > 2 && linkType !== 'store',
placeholderData: keepPreviousData
});
// Reset selected item when link type changes
const handleLinkTypeChange = (type: 'store' | 'product' | 'category') => {
setLinkType(type);
setSelectedItem(null);
setSearchQuery('');
};
// Build the final link
const buildLink = () => {
const config = (window as any).woonoowCustomer || {};
const basePath = config.basePath || '';
let path = `${basePath}/shop`;
if (linkType === 'product' && selectedItem) {
path = `${basePath}/product/${selectedItem.slug}`;
} else if (linkType === 'category' && selectedItem) {
path = `${basePath}/shop?category=${selectedItem.slug}`; // using query parameter for category as typical for shop
}
const url = new URL(`${window.location.origin}${path}`);
url.searchParams.set('ref', referralCode);
if (utmSource) url.searchParams.set('utm_source', utmSource);
if (utmMedium) url.searchParams.set('utm_medium', utmMedium);
if (utmCampaign) url.searchParams.set('utm_campaign', utmCampaign);
return url.toString();
};
const finalLink = buildLink();
const handleCopy = () => {
navigator.clipboard.writeText(finalLink);
setCopied(true);
toast.success('Enriched link copied to clipboard!');
setTimeout(() => setCopied(false), 2000);
};
return (
<div className="bg-white p-6 rounded-lg border mt-6">
<div className="flex items-center gap-2 mb-4">
<LinkIcon className="w-5 h-5 text-primary" />
<h3 className="text-lg font-semibold">Affiliate Link Builder</h3>
</div>
<p className="text-sm text-gray-500 mb-6">
Create specific links to products or categories, and add campaign tags to track your performance.
</p>
<div className="space-y-6">
{/* Link Type Selection */}
<div>
<label className="text-sm font-medium mb-2 block">Link Destination</label>
<div className="flex flex-wrap gap-2">
{['store', 'product', 'category'].map((type) => (
<button
key={type}
onClick={() => handleLinkTypeChange(type as any)}
className={`px-4 py-2 rounded-md text-sm border capitalize transition-colors ${
linkType === type
? 'bg-primary text-primary-foreground border-primary'
: 'bg-white hover:bg-gray-50'
}`}
>
{type === 'store' ? 'General Store' : `Specific ${type}`}
</button>
))}
</div>
</div>
{/* Search / Selection */}
{linkType !== 'store' && (
<div className="relative">
<label className="text-sm font-medium mb-2 block">
Select {linkType === 'product' ? 'Product' : 'Category'}
</label>
{!selectedItem ? (
<div>
<div className="relative">
<Search className="w-4 h-4 absolute left-3 top-3 text-gray-400" />
<Input
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
placeholder={`Search for a ${linkType}...`}
className="pl-9"
/>
</div>
{isSearching && <div className="text-sm text-gray-500 mt-2">Searching...</div>}
{searchResults && searchResults.length > 0 && (
<div className="absolute z-10 w-full mt-1 bg-white border rounded-md shadow-lg max-h-60 overflow-y-auto">
{searchResults.map((item: any) => (
<button
key={item.id}
className="w-full text-left px-4 py-2 text-sm hover:bg-gray-50 border-b last:border-0"
onClick={() => setSelectedItem({ id: item.id, name: item.name, slug: item.slug })}
>
{item.name}
</button>
))}
</div>
)}
</div>
) : (
<div className="flex items-center justify-between p-3 border rounded-md bg-gray-50">
<span className="text-sm font-medium">{selectedItem.name}</span>
<button
onClick={() => setSelectedItem(null)}
className="text-xs text-red-500 hover:underline"
>
Change
</button>
</div>
)}
</div>
)}
{/* Campaign Tracking (UTMs) */}
<div>
<label className="text-sm font-medium mb-3 block">Campaign Tracking (Optional)</label>
<div className="grid grid-cols-1 md:grid-cols-3 gap-3">
<div>
<Input
placeholder="Source (e.g. instagram)"
value={utmSource}
onChange={(e) => setUtmSource(e.target.value)}
className="text-sm"
/>
</div>
<div>
<Input
placeholder="Medium (e.g. story, bio)"
value={utmMedium}
onChange={(e) => setUtmMedium(e.target.value)}
className="text-sm"
/>
</div>
<div>
<Input
placeholder="Campaign (e.g. summer_sale)"
value={utmCampaign}
onChange={(e) => setUtmCampaign(e.target.value)}
className="text-sm"
/>
</div>
</div>
</div>
{/* Final Link Output */}
<div className="pt-4 border-t">
<label className="text-sm font-medium mb-2 block">Your Generated Link</label>
<div className="flex gap-2">
<Input
value={finalLink}
readOnly
className="bg-gray-50 font-mono text-sm"
/>
<Button onClick={handleCopy} className="shrink-0 w-32">
{copied ? (
<><CheckCircle className="w-4 h-4 mr-2" /> Copied</>
) : (
<><Copy className="w-4 h-4 mr-2" /> Copy Link</>
)}
</Button>
</div>
</div>
</div>
</div>
);
}

View File

@@ -14,6 +14,9 @@ import LicenseConnect from './LicenseConnect';
import Subscriptions from './Subscriptions'; import Subscriptions from './Subscriptions';
import SubscriptionDetail from './SubscriptionDetail'; import SubscriptionDetail from './SubscriptionDetail';
import AffiliateDashboard from './AffiliateDashboard'; import AffiliateDashboard from './AffiliateDashboard';
import AffiliateReferrals from './AffiliateReferrals';
import AffiliateLinks from './AffiliateLinks';
import { AffiliateCollections } from './AffiliateCollections';
export default function Account() { export default function Account() {
const user = (window as any).woonoowCustomer?.user; const user = (window as any).woonoowCustomer?.user;
@@ -44,6 +47,9 @@ export default function Account() {
<Route path="subscriptions" element={<Subscriptions />} /> <Route path="subscriptions" element={<Subscriptions />} />
<Route path="subscriptions/:id" element={<SubscriptionDetail />} /> <Route path="subscriptions/:id" element={<SubscriptionDetail />} />
<Route path="affiliate" element={<AffiliateDashboard />} /> <Route path="affiliate" element={<AffiliateDashboard />} />
<Route path="affiliate/referrals" element={<AffiliateReferrals />} />
<Route path="affiliate/links" element={<AffiliateLinks />} />
<Route path="affiliate/collections" element={<AffiliateCollections />} />
<Route path="account-details" element={<AccountDetails />} /> <Route path="account-details" element={<AccountDetails />} />
<Route path="*" element={<Navigate to="/my-account" replace />} /> <Route path="*" element={<Navigate to="/my-account" replace />} />
</Routes> </Routes>

View File

@@ -33,6 +33,7 @@ interface SavedAddress {
email?: string; email?: string;
phone?: string; phone?: string;
is_default: boolean; is_default: boolean;
formatted_address?: string;
} }
export default function Checkout() { export default function Checkout() {
@@ -389,7 +390,13 @@ export default function Checkout() {
state: addressData.state, state: addressData.state,
city: addressData.city, city: addressData.city,
postcode: addressData.postcode, postcode: addressData.postcode,
destination_id: undefined, // Include custom fields for shipping calculation (e.g., RajaOngkir destination_id)
...Object.fromEntries(
(shipToDifferentAddress ? shippingCustomFields : billingCustomFields).map(f => [
f.key.replace(/^(shipping_|billing_)/, ''),
customFieldData[f.key] || ''
])
),
}, },
items, items,
}); });
@@ -795,7 +802,16 @@ export default function Checkout() {
<div className="bg-primary/5 border-2 border-primary rounded-lg p-4 text-sm"> <div className="bg-primary/5 border-2 border-primary rounded-lg p-4 text-sm">
<p className="font-semibold">{sel.label}{sel.is_default && <span className="ml-2 text-xs bg-green-100 text-green-700 px-1.5 rounded">Default</span>}</p> <p className="font-semibold">{sel.label}{sel.is_default && <span className="ml-2 text-xs bg-green-100 text-green-700 px-1.5 rounded">Default</span>}</p>
<p>{sel.first_name} {sel.last_name}</p> <p>{sel.first_name} {sel.last_name}</p>
<p className="text-gray-600">{sel.address_1}, {sel.city}, {sel.state} {sel.postcode}</p> {sel.formatted_address ? (
<p className="text-gray-600 whitespace-pre-wrap">{sel.formatted_address}</p>
) : (
<div className="text-gray-600">
<p>{sel.address_1}</p>
{[sel.city, sel.state, sel.postcode].filter(Boolean).length > 0 && (
<p>{[sel.city, sel.state, sel.postcode].filter(Boolean).join(', ')}</p>
)}
</div>
)}
</div> </div>
) : null; ) : null;
})()} })()}
@@ -866,7 +882,7 @@ export default function Checkout() {
</div> </div>
)} )}
{billingCustomFields.map(field => ( {billingCustomFields.map(field => (
<DynamicCheckoutField key={field.key} field={field} value={customFieldData[field.key] || ''} onChange={v => handleCustomFieldChange(field.key, v)} countryOptions={countryOptions} stateOptions={billingStateOptions} /> <DynamicCheckoutField key={field.key} field={field} value={customFieldData[field.key] || ''} valueLabel={customFieldData[`${field.key}_label`]} onChange={v => handleCustomFieldChange(field.key, v)} countryOptions={countryOptions} stateOptions={billingStateOptions} />
))} ))}
</> </>
)} )}
@@ -908,7 +924,16 @@ export default function Checkout() {
<div className="bg-primary/5 border-2 border-primary rounded-lg p-4 text-sm"> <div className="bg-primary/5 border-2 border-primary rounded-lg p-4 text-sm">
<p className="font-semibold">{sel.label}</p> <p className="font-semibold">{sel.label}</p>
<p>{sel.first_name} {sel.last_name}</p> <p>{sel.first_name} {sel.last_name}</p>
<p className="text-gray-600">{sel.address_1}, {sel.city} {sel.postcode}</p> {sel.formatted_address ? (
<p className="text-gray-600 whitespace-pre-wrap">{sel.formatted_address}</p>
) : (
<div className="text-gray-600">
<p>{sel.address_1}</p>
{[sel.city, sel.state, sel.postcode].filter(Boolean).length > 0 && (
<p>{[sel.city, sel.state, sel.postcode].filter(Boolean).join(', ')}</p>
)}
</div>
)}
</div> </div>
) : null; ) : null;
})()} })()}
@@ -926,7 +951,7 @@ export default function Checkout() {
{getShippingField('shipping_country') && <div><label className="block text-sm font-medium mb-1">Country</label><SearchableSelect options={countryOptions} value={shippingData.country} onChange={v => setShippingData({ ...shippingData, country: v })} placeholder="Select country" disabled={countries.length === 1} /></div>} {getShippingField('shipping_country') && <div><label className="block text-sm font-medium mb-1">Country</label><SearchableSelect options={countryOptions} value={shippingData.country} onChange={v => setShippingData({ ...shippingData, country: v })} placeholder="Select country" disabled={countries.length === 1} /></div>}
{getShippingField('shipping_state') && <div><label className="block text-sm font-medium mb-1">State</label>{shippingStateOptions.length > 0 ? <SearchableSelect options={shippingStateOptions} value={shippingData.state} onChange={v => setShippingData({ ...shippingData, state: v })} placeholder="Select state" /> : <input type="text" value={shippingData.state} onChange={e => setShippingData({ ...shippingData, state: e.target.value })} className="w-full border rounded-lg px-4 py-2" />}</div>} {getShippingField('shipping_state') && <div><label className="block text-sm font-medium mb-1">State</label>{shippingStateOptions.length > 0 ? <SearchableSelect options={shippingStateOptions} value={shippingData.state} onChange={v => setShippingData({ ...shippingData, state: v })} placeholder="Select state" /> : <input type="text" value={shippingData.state} onChange={e => setShippingData({ ...shippingData, state: e.target.value })} className="w-full border rounded-lg px-4 py-2" />}</div>}
{getShippingField('shipping_postcode') && <div><label className="block text-sm font-medium mb-1">Postcode</label><input type="text" value={shippingData.postcode} onChange={e => setShippingData({ ...shippingData, postcode: e.target.value })} className="w-full border rounded-lg px-4 py-2" /></div>} {getShippingField('shipping_postcode') && <div><label className="block text-sm font-medium mb-1">Postcode</label><input type="text" value={shippingData.postcode} onChange={e => setShippingData({ ...shippingData, postcode: e.target.value })} className="w-full border rounded-lg px-4 py-2" /></div>}
{shippingCustomFields.map(field => <DynamicCheckoutField key={field.key} field={field} value={customFieldData[field.key] || ''} onChange={v => handleCustomFieldChange(field.key, v)} countryOptions={countryOptions} stateOptions={shippingStateOptions} />)} {shippingCustomFields.map(field => <DynamicCheckoutField key={field.key} field={field} value={customFieldData[field.key] || ''} valueLabel={customFieldData[`${field.key}_label`]} onChange={v => handleCustomFieldChange(field.key, v)} countryOptions={countryOptions} stateOptions={shippingStateOptions} />)}
</div> </div>
)} )}
</> </>

View File

@@ -3,6 +3,7 @@ import { useParams, useNavigate } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query'; import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api/client'; import { api } from '@/lib/api/client';
import { Helmet } from 'react-helmet-async'; import { Helmet } from 'react-helmet-async';
import { cn } from '@/lib/utils';
// Section Components // Section Components
import { HeroSection } from './sections/HeroSection'; import { HeroSection } from './sections/HeroSection';
@@ -30,7 +31,16 @@ interface SectionStyles {
backgroundOverlay?: number; backgroundOverlay?: number;
paddingTop?: string; paddingTop?: string;
paddingBottom?: string; paddingBottom?: string;
contentWidth?: 'full' | 'contained'; contentWidth?: 'full' | 'contained' | 'boxed';
gradientAngle?: number;
gradientFrom?: string;
gradientTo?: string;
cardBackgroundColor?: string;
cardPaddingTop?: string;
cardPaddingRight?: string;
cardPaddingBottom?: string;
cardPaddingLeft?: string;
heightPreset?: string;
} }
interface ElementStyle { interface ElementStyle {
@@ -266,15 +276,28 @@ export function DynamicPageRenderer({ slug: propSlug }: DynamicPageRendererProps
return ( return (
<div <div
key={section.id} key={section.id}
className="relative overflow-hidden" className={cn(
"relative overflow-hidden",
!section.styles?.backgroundColor && !section.styles?.backgroundType && "bg-white/50",
{
'default': 'py-16 md:py-24',
'small': 'py-8 md:py-12',
'medium': 'py-16 md:py-24',
'large': 'py-24 md:py-36',
'fullscreen': 'min-h-screen flex items-center',
}[(section.styles?.heightPreset as string) || 'default'] || 'py-16 md:py-24'
)}
style={{ style={{
// Only explicit custom padding overrides from the padding fields ...(section.styles?.backgroundType === 'gradient'
? { background: `linear-gradient(${section.styles?.gradientAngle ?? 135}deg, ${section.styles?.gradientFrom || '#9333ea'}, ${section.styles?.gradientTo || '#3b82f6'})` }
: { backgroundColor: section.styles?.backgroundColor }
),
paddingTop: section.styles?.paddingTop, paddingTop: section.styles?.paddingTop,
paddingBottom: section.styles?.paddingBottom, paddingBottom: section.styles?.paddingBottom,
}} }}
> >
{/* Full-bleed background image & overlay */} {/* Full-bleed background image & overlay */}
{section.styles?.backgroundImage && (section.styles.backgroundType === 'image' || !section.styles.backgroundType) && ( {section.styles?.backgroundType === 'image' && section.styles?.backgroundImage && (
<> <>
<div <div
className="absolute inset-0 z-0 bg-cover bg-center bg-no-repeat" className="absolute inset-0 z-0 bg-cover bg-center bg-no-repeat"
@@ -286,19 +309,64 @@ export function DynamicPageRenderer({ slug: propSlug }: DynamicPageRendererProps
/> />
</> </>
)} )}
{/* Legacy: show bg image even without backgroundType set */}
{!section.styles?.backgroundType && section.styles?.backgroundImage && (
<>
<div
className="absolute inset-0 z-0 bg-cover bg-center bg-no-repeat"
style={{ backgroundImage: `url(${section.styles.backgroundImage})` }}
/>
<div
className="absolute inset-0 z-0 bg-black"
style={{ opacity: (section.styles?.backgroundOverlay || 0) / 100 }}
/>
</>
)}
{/* Section component — manages its own background, height, and inner content width */} {/* Content Wrapper */}
<div className="relative z-10 w-full"> {section.styles?.contentWidth === 'boxed' ? (
<SectionComponent <div className="relative z-10 container mx-auto px-4 max-w-5xl">
id={section.id} <div
section={section} className="rounded-2xl shadow-sm border border-gray-200 overflow-hidden"
layout={section.layoutVariant || 'default'} style={{
colorScheme={section.colorScheme || 'default'} backgroundColor: section.styles?.cardBackgroundColor || '#ffffff',
styles={section.styles} paddingTop: section.styles?.cardPaddingTop || undefined,
elementStyles={section.elementStyles} paddingRight: section.styles?.cardPaddingRight || undefined,
{...flattenSectionProps(section.props || {})} paddingBottom: section.styles?.cardPaddingBottom || undefined,
/> paddingLeft: section.styles?.cardPaddingLeft || undefined,
</div> }}
>
<SectionComponent
id={section.id}
section={section}
sourceType={isStructuralPage ? 'page' : 'template'}
sourceId={isStructuralPage ? pageData.id : pageData.cpt}
layout={section.layoutVariant || 'default'}
colorScheme={section.colorScheme || 'default'}
styles={section.styles}
elementStyles={section.elementStyles}
{...flattenSectionProps(section.props || {})}
/>
</div>
</div>
) : (
<div className={cn(
"relative z-10 w-full",
section.styles?.contentWidth === 'contained' ? 'container mx-auto px-4 max-w-6xl' : ''
)}>
<SectionComponent
id={section.id}
section={section}
sourceType={isStructuralPage ? 'page' : 'template'}
sourceId={isStructuralPage ? pageData.id : pageData.cpt}
layout={section.layoutVariant || 'default'}
colorScheme={section.colorScheme || 'default'}
styles={section.styles}
elementStyles={section.elementStyles}
{...flattenSectionProps(section.props || {})}
/>
</div>
)}
</div> </div>
); );
})} })}

View File

@@ -1,11 +1,13 @@
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { getSectionBackground } from '@/lib/sectionStyles'; import { getSectionBackground } from '@/lib/sectionStyles';
import { SectionBackgroundRenderer } from '@/components/SectionBackgroundRenderer';
interface BentoItem { interface BentoItem {
label: string; label: string;
image?: string; image?: string;
url?: string; url?: string;
backgroundColor?: string;
size?: 'small' | 'medium' | 'large' | 'tall'; size?: 'small' | 'medium' | 'large' | 'tall';
} }
@@ -57,7 +59,6 @@ export function BentoCategoryGrid({
styles, styles,
elementStyles, elementStyles,
}: BentoCategoryGridProps) { }: BentoCategoryGridProps) {
const sectionBg = getSectionBackground(styles);
// Keep initial demo layout stable: merge configured items over demo items by index. // Keep initial demo layout stable: merge configured items over demo items by index.
// This prevents the preview grid from "collapsing" when the first item is added. // This prevents the preview grid from "collapsing" when the first item is added.
const displayItems: BentoItem[] = (() => { const displayItems: BentoItem[] = (() => {
@@ -69,17 +70,49 @@ export function BentoCategoryGrid({
}); });
})(); })();
// Helper to get text styles (including font family)
const getTextStyles = (elementName: string) => {
const es = elementStyles?.[elementName] || {};
return {
classNames: cn(
es.fontSize,
es.fontWeight,
{
'font-sans': es.fontFamily === 'secondary',
'font-serif': es.fontFamily === 'primary',
}
),
style: {
color: es.color,
textAlign: es.textAlign,
backgroundColor: es.backgroundColor,
borderColor: es.borderColor,
borderWidth: es.borderWidth,
borderRadius: es.borderRadius,
}
};
};
const titleStyle = getTextStyles('title');
const sectionBg = getSectionBackground(styles);
const hasCustomPadding = styles?.paddingTop || styles?.paddingBottom;
return ( return (
<section <section
id={id} id={id}
className="wn-section wn-bento-grid py-12 md:py-16" className={cn("wn-section wn-bento-grid relative overflow-hidden w-full", hasCustomPadding ? "" : "py-12 md:py-16")}
style={sectionBg.style}
> >
<div className="container mx-auto px-4 max-w-7xl"> <div className="w-full mx-auto px-4 relative z-10">
{title && ( {title && (
<h2 <h2
className="text-3xl md:text-4xl font-bold mb-8" className={cn(
style={{ color: elementStyles?.title?.color }} "mb-8",
!elementStyles?.title?.fontSize && "text-3xl md:text-4xl",
!elementStyles?.title?.fontWeight && "font-bold",
titleStyle.classNames
)}
style={titleStyle.style}
> >
{title} {title}
</h2> </h2>
@@ -105,6 +138,13 @@ export function BentoCategoryGrid({
alt={item.label} alt={item.label}
className="absolute inset-0 w-full h-full object-cover group-hover:scale-105 transition-transform duration-500" className="absolute inset-0 w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"
/> />
) : item.backgroundColor ? (
<div
className="absolute inset-0"
style={{
background: `linear-gradient(to bottom right, ${item.backgroundColor}, color-mix(in srgb, ${item.backgroundColor}, black 35%))`
}}
/>
) : ( ) : (
<div className={cn('absolute inset-0 bg-gradient-to-br', gradientClass)} /> <div className={cn('absolute inset-0 bg-gradient-to-br', gradientClass)} />
)} )}

View File

@@ -1,5 +1,6 @@
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { getSectionBackground } from '@/lib/sectionStyles'; import { getSectionBackground } from '@/lib/sectionStyles';
import { SectionBackgroundRenderer } from '@/components/SectionBackgroundRenderer';
interface CTABannerSectionProps { interface CTABannerSectionProps {
id: string; id: string;
@@ -22,7 +23,9 @@ export function CTABannerSection({
button_url, button_url,
elementStyles, elementStyles,
styles, styles,
}: CTABannerSectionProps & { styles?: Record<string, any> }) { isEditor,
}: CTABannerSectionProps & { styles?: Record<string, any>; isEditor?: boolean }) {
const heightMap: Record<string, string> = { const heightMap: Record<string, string> = {
'default': 'py-12 md:py-20', 'default': 'py-12 md:py-20',
'small': 'py-8 md:py-12', 'small': 'py-8 md:py-12',
@@ -65,7 +68,7 @@ export function CTABannerSection({
{title && ( {title && (
<h2 <h2
className={cn( className={cn(
"wn-cta__title mb-6", "wn-cta__title mb-6 w-full",
!elementStyles?.title?.fontSize && "text-3xl md:text-4xl lg:text-5xl", !elementStyles?.title?.fontSize && "text-3xl md:text-4xl lg:text-5xl",
!elementStyles?.title?.fontWeight && "font-bold", !elementStyles?.title?.fontWeight && "font-bold",
titleStyle.classNames titleStyle.classNames
@@ -78,93 +81,66 @@ export function CTABannerSection({
{text && ( {text && (
<p className={cn( <p className={cn(
'wn-cta-banner__text mb-8 max-w-2xl mx-auto', 'wn-cta-banner__text mb-8 max-w-2xl mx-auto w-full',
!elementStyles?.text?.fontSize && "text-lg md:text-xl", !elementStyles?.text?.fontSize && "text-lg md:text-xl",
styles?.contentWidth !== 'boxed' && { styles?.contentWidth !== 'boxed' && {
'text-white/90': colorScheme === 'primary', 'text-white/90': colorScheme === 'primary',
'text-gray-600': colorScheme === 'muted', 'text-gray-600': colorScheme === 'muted',
'text-gray-700': colorScheme === 'default',
}, },
styles?.contentWidth === 'boxed' && 'text-gray-600', styles?.contentWidth === 'boxed' && 'text-gray-600',
textStyle.classNames textStyle.classNames
)} )}
style={textStyle.style} style={textStyle.style}
> >
{text} {text || "Description text missing"}
</p> </p>
)} )}
{button_text && button_url && ( {button_text && button_url && (
<a <div className="w-full mt-4" style={{ textAlign: (btnStyle.style.textAlign as React.CSSProperties['textAlign']) || 'center' }}>
href={button_url} <a
className={cn( href={button_url}
'wn-cta-banner__button inline-block px-8 py-3 rounded-lg font-semibold transition-all hover:opacity-90', className={cn(
!btnStyle.style?.backgroundColor && (styles?.contentWidth === 'boxed' 'wn-cta-banner__button inline-block px-8 py-3 rounded-lg font-semibold transition-all hover:opacity-90',
? 'bg-primary' !btnStyle.style?.backgroundColor && (styles?.contentWidth === 'boxed'
: { ? 'bg-primary'
'bg-white': colorScheme === 'primary', : {
'bg-primary': colorScheme === 'muted' || colorScheme === 'secondary', 'bg-white': colorScheme === 'primary',
}), 'bg-primary': colorScheme === 'muted' || colorScheme === 'secondary',
!btnStyle.style?.color && (styles?.contentWidth === 'boxed' }),
? 'text-primary-foreground' !btnStyle.style?.color && (styles?.contentWidth === 'boxed'
: { ? 'text-primary-foreground'
'text-primary': colorScheme === 'primary', : {
'text-white': colorScheme === 'muted' || colorScheme === 'secondary', 'text-primary': colorScheme === 'primary',
}), 'text-white': colorScheme === 'muted' || colorScheme === 'secondary',
btnStyle.classNames }),
)} btnStyle.classNames
style={btnStyle.style} )}
> style={{ ...btnStyle.style, textAlign: undefined }}
{button_text} >
</a> {button_text}
</a>
</div>
)} )}
</> </>
); );
const hasCustomBackground = !!styles?.backgroundColor || !!styles?.backgroundImage || styles?.backgroundType === 'gradient'; const isBoxed = styles?.contentWidth === 'boxed';
const sectionBg = getSectionBackground(styles);
// Helper to get background style for dynamic schemes
const getBackgroundStyle = (): React.CSSProperties | undefined => {
if (hasCustomBackground) return sectionBg.style;
if (colorScheme === 'primary') {
return { backgroundColor: 'var(--wn-primary, #1a1a1a)' };
}
if (colorScheme === 'secondary') {
return { backgroundColor: 'var(--wn-secondary, #6b7280)' };
}
return undefined;
};
return ( return (
<section <section
id={id} id={id}
className={cn( className={cn(
'wn-section wn-cta-banner', 'wn-section wn-cta-banner relative w-full flex flex-col items-center justify-center',
`wn-cta-banner--${layout}`, `wn-cta-banner--${layout}`,
`wn-scheme--${colorScheme}`, `wn-scheme--${colorScheme}`,
heightClasses, heightClasses // Might not be needed if handled by outer, but safe to keep
{
'bg-primary text-primary-foreground': colorScheme === 'primary' && !hasCustomBackground,
'bg-secondary text-secondary-foreground': colorScheme === 'secondary' && !hasCustomBackground,
'bg-muted': colorScheme === 'muted' && !hasCustomBackground,
}
)} )}
style={getBackgroundStyle()}
> >
{styles?.contentWidth === 'boxed' ? ( <div className="mx-auto px-4 text-center relative z-10 w-full max-w-5xl">
<div className="container mx-auto px-4 max-w-5xl"> {innerContent}
<div className="bg-white text-gray-900 rounded-2xl shadow-sm border border-gray-200 overflow-hidden px-6 md:px-10 py-10 text-center"> </div>
{innerContent}
</div>
</div>
) : (
<div className={cn(
"mx-auto px-4 text-center",
styles?.contentWidth === 'full' ? 'w-full' : 'container'
)}>
{innerContent}
</div>
)}
</section> </section>
); );
} }

View File

@@ -1,38 +1,43 @@
import { useState } from 'react'; import { useState } from 'react';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { getSectionBackground } from '@/lib/sectionStyles'; import { getSectionBackground } from '@/lib/sectionStyles';
import { SectionBackgroundRenderer } from '@/components/SectionBackgroundRenderer';
import { api } from '@/lib/api/client';
interface ContactFormField {
name: string;
label: string;
type: string;
required?: boolean;
}
interface ContactFormSectionProps { interface ContactFormSectionProps {
id: string; id: string;
sourceType?: string;
sourceId?: string;
layout?: string; layout?: string;
colorScheme?: string; colorScheme?: string;
title?: string; title?: string;
webhook_url?: string; webhook_url?: string;
redirect_url?: string; redirect_url?: string;
fields?: string[]; fields?: ContactFormField[];
elementStyles?: Record<string, any>; elementStyles?: Record<string, any>;
} }
export function ContactFormSection({ export function ContactFormSection({
id, id,
sourceType,
sourceId,
layout = 'default', layout = 'default',
colorScheme = 'default', colorScheme = 'default',
title, title,
webhook_url, webhook_url,
redirect_url, redirect_url,
fields = ['name', 'email', 'message'], fields,
elementStyles, elementStyles,
styles, styles,
}: ContactFormSectionProps & { styles?: Record<string, any> }) { isEditor,
const heightMap: Record<string, string> = { }: ContactFormSectionProps & { styles?: Record<string, any>; isEditor?: boolean }) {
'default': 'py-12 md:py-20',
'small': 'py-8 md:py-12',
'medium': 'py-16 md:py-24',
'large': 'py-24 md:py-36',
'fullscreen': 'min-h-screen flex flex-col justify-center',
};
const customPadding = styles?.paddingTop || styles?.paddingBottom;
const heightClasses = customPadding ? '' : (heightMap[styles?.heightPreset || 'default'] || 'py-12 md:py-20');
const [formData, setFormData] = useState<Record<string, string>>({}); const [formData, setFormData] = useState<Record<string, string>>({});
// Helper to get text styles (including font family) // Helper to get text styles (including font family)
@@ -63,23 +68,82 @@ export function ContactFormSection({
const fieldsStyle = getTextStyles('fields'); const fieldsStyle = getTextStyles('fields');
const [submitting, setSubmitting] = useState(false); const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
const [touched, setTouched] = useState<Record<string, boolean>>({});
const defaultFields: ContactFormField[] = [
{ name: 'name', label: 'Your Name', type: 'text', required: true },
{ name: 'email', label: 'Your Email', type: 'email', required: true },
{ name: 'message', label: 'Your Message', type: 'textarea', required: true },
];
const activeFields = Array.isArray(fields) && fields.length > 0 ? fields : defaultFields;
const validateField = (name: string, value: string, field: ContactFormField) => {
if (field.required && !value?.trim()) {
return `${field.label} is required`;
}
if (field.type === 'email' && value && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
return 'Please enter a valid email address';
}
return '';
};
const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => { const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
setFormData({ ...formData, [e.target.name]: e.target.value }); const { name, value } = e.target;
setFormData(prev => ({ ...prev, [name]: value }));
// Clear error when user types
if (fieldErrors[name]) {
setFieldErrors(prev => ({ ...prev, [name]: '' }));
}
};
const handleBlur = (e: React.FocusEvent<HTMLInputElement | HTMLTextAreaElement>) => {
const { name, value } = e.target;
setTouched(prev => ({ ...prev, [name]: true }));
const field = activeFields.find(f => f.name === name);
if (field) {
const errorMsg = validateField(name, value, field);
setFieldErrors(prev => ({ ...prev, [name]: errorMsg }));
}
}; };
const handleSubmit = async (e: React.FormEvent) => { const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault(); e.preventDefault();
// Validate all fields
const newErrors: Record<string, string> = {};
let isValid = true;
activeFields.forEach(field => {
const errorMsg = validateField(field.name, formData[field.name] || '', field);
if (errorMsg) {
newErrors[field.name] = errorMsg;
isValid = false;
}
});
if (!isValid) {
setFieldErrors(newErrors);
// Mark all fields with errors as touched
const allTouched = Object.keys(newErrors).reduce((acc, key) => ({...acc, [key]: true}), {});
setTouched(prev => ({ ...prev, ...allTouched }));
return;
}
setSubmitting(true); setSubmitting(true);
setError(null); setError(null);
try { try {
// Submit to webhook if provided // Submit to webhook proxy if configured
if (webhook_url) { if (webhook_url && !isEditor) {
await fetch(webhook_url, { await api.post('/pages/submit-section-form', {
method: 'POST', source_type: sourceType,
headers: { 'Content-Type': 'application/json' }, source_id: sourceId,
body: JSON.stringify(formData), section_id: id,
form_data: formData,
}); });
} }
@@ -97,40 +161,19 @@ export function ContactFormSection({
} finally { } finally {
setSubmitting(false); setSubmitting(false);
} }
}; const hasCustomBackground = !!styles?.backgroundColor || !!styles?.backgroundImage || styles?.backgroundType === 'gradient';
const sectionBg = getSectionBackground(styles);
// Helper to get background style for dynamic schemes
const getBackgroundStyle = (): React.CSSProperties | undefined => {
if (hasCustomBackground) return sectionBg.style;
if (colorScheme === 'primary') {
return { backgroundColor: 'var(--wn-primary, #1a1a1a)' };
}
if (colorScheme === 'secondary') {
return { backgroundColor: 'var(--wn-secondary, #6b7280)' };
}
return undefined;
}; };
const sectionBg = getSectionBackground(styles);
return ( return (
<section <section
id={id} id={id}
className={cn( className={cn(
'wn-section wn-contact-form', 'wn-section wn-contact-form relative overflow-hidden w-full',
`wn-scheme--${colorScheme}`, `wn-scheme--${colorScheme}`
heightClasses,
{
'bg-muted': colorScheme === 'muted' && !hasCustomBackground,
}
)} )}
style={getBackgroundStyle()}
> >
<div className={cn( <div className="mx-auto px-4 relative z-10 w-full">
"mx-auto px-4",
styles?.contentWidth === 'full' ? 'w-full'
: styles?.contentWidth === 'boxed' ? 'max-w-5xl'
: 'container'
)}>
<div className={cn( <div className={cn(
'max-w-xl mx-auto', 'max-w-xl mx-auto',
{ {
@@ -139,7 +182,7 @@ export function ContactFormSection({
)}> )}>
{title && ( {title && (
<h2 className={cn( <h2 className={cn(
"wn-contact__title text-center mb-12", "wn-contact__title text-center mb-12 w-full",
!elementStyles?.title?.fontSize && "text-3xl md:text-4xl lg:text-5xl", !elementStyles?.title?.fontSize && "text-3xl md:text-4xl lg:text-5xl",
!elementStyles?.title?.fontWeight && "font-bold", !elementStyles?.title?.fontWeight && "font-bold",
titleStyle.classNames titleStyle.classNames
@@ -150,55 +193,62 @@ export function ContactFormSection({
</h2> </h2>
)} )}
<form onSubmit={handleSubmit} className="space-y-6"> <form onSubmit={handleSubmit} className="space-y-6" noValidate>
{fields.map((field) => { {activeFields.map((field, idx) => {
const fieldLabel = field.charAt(0).toUpperCase() + field.slice(1).replace('_', ' '); const isTextarea = field.type === 'textarea';
const isTextarea = field === 'message' || field === 'content'; const fieldError = fieldErrors[field.name];
const isTouched = touched[field.name];
const showError = isTouched && fieldError;
return ( return (
<div key={field} className="wn-contact-form__field"> <div key={field.name || idx} className="wn-contact-form__field">
<label className="block text-sm font-medium text-gray-700 mb-2"> <label className="block text-sm font-medium text-gray-700 mb-2">
{fieldLabel} {field.label} {field.required && <span className="text-red-500">*</span>}
</label> </label>
{isTextarea ? ( {isTextarea ? (
<textarea <textarea
name={field} name={field.name}
value={formData[field] || ''} value={formData[field.name] || ''}
onChange={handleChange} onChange={handleChange}
onBlur={handleBlur}
rows={5} rows={5}
className={cn( className={cn(
"w-full px-4 py-3 border rounded-lg focus:ring-2 focus:ring-primary/20 focus:border-primary", "w-full px-4 py-3 border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary",
showError ? "border-red-500 focus:border-red-500 focus:ring-red-200" : "border-gray-200",
fieldsStyle.classNames fieldsStyle.classNames
)} )}
style={{ style={{
backgroundColor: fieldsStyle.style?.backgroundColor, backgroundColor: fieldsStyle.style?.backgroundColor,
color: fieldsStyle.style?.color, color: fieldsStyle.style?.color,
borderColor: fieldsStyle.style?.borderColor, borderColor: showError ? undefined : fieldsStyle.style?.borderColor,
borderRadius: fieldsStyle.style?.borderRadius, borderRadius: fieldsStyle.style?.borderRadius,
}} }}
placeholder={`Enter your ${fieldLabel.toLowerCase()}`} placeholder={`Enter ${field.label.toLowerCase()}`}
required
/> />
) : ( ) : (
<input <input
type={field === 'email' ? 'email' : 'text'} type={field.type || 'text'}
name={field} name={field.name}
value={formData[field] || ''} value={formData[field.name] || ''}
onChange={handleChange} onChange={handleChange}
onBlur={handleBlur}
className={cn( className={cn(
"w-full px-4 py-3 border rounded-lg focus:ring-2 focus:ring-primary/20 focus:border-primary", "w-full px-4 py-3 border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary",
showError ? "border-red-500 focus:border-red-500 focus:ring-red-200" : "border-gray-200",
fieldsStyle.classNames fieldsStyle.classNames
)} )}
style={{ style={{
backgroundColor: fieldsStyle.style?.backgroundColor, backgroundColor: fieldsStyle.style?.backgroundColor,
color: fieldsStyle.style?.color, color: fieldsStyle.style?.color,
borderColor: fieldsStyle.style?.borderColor, borderColor: showError ? undefined : fieldsStyle.style?.borderColor,
borderRadius: fieldsStyle.style?.borderRadius, borderRadius: fieldsStyle.style?.borderRadius,
}} }}
placeholder={`Enter your ${fieldLabel.toLowerCase()}`} placeholder={`Enter ${field.label.toLowerCase()}`}
required
/> />
)} )}
{showError && (
<p className="mt-1 text-sm text-red-500">{fieldError}</p>
)}
</div> </div>
); );
})} })}

View File

@@ -2,6 +2,7 @@ import React from 'react';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { SharedContentLayout } from '@/components/SharedContentLayout'; import { SharedContentLayout } from '@/components/SharedContentLayout';
import { getSectionBackground } from '@/lib/sectionStyles'; import { getSectionBackground } from '@/lib/sectionStyles';
import { SectionBackgroundRenderer } from '@/components/SectionBackgroundRenderer';
interface ContentSectionProps { interface ContentSectionProps {
id?: string; id?: string;
@@ -47,6 +48,14 @@ const fontSizeToCSS = (className?: string) => {
} }
}; };
const fontFamilyToCSS = (fontFamily?: string) => {
switch (fontFamily) {
case 'primary': return "'Playfair Display', Georgia, serif";
case 'secondary': return "'Inter', system-ui, sans-serif";
default: return undefined;
}
};
const fontWeightToCSS = (className?: string) => { const fontWeightToCSS = (className?: string) => {
switch (className) { switch (className) {
case 'font-thin': return '100'; case 'font-thin': return '100';
@@ -73,10 +82,10 @@ const generateScopedStyles = (sectionId: string, elementStyles: Record<string, a
const headingRules = [ const headingRules = [
hs.color && `color: ${hs.color} !important;`, hs.color && `color: ${hs.color} !important;`,
hs.fontWeight && `font-weight: ${fontWeightToCSS(hs.fontWeight)} !important;`, hs.fontWeight && `font-weight: ${fontWeightToCSS(hs.fontWeight)} !important;`,
hs.fontFamily && `font-family: var(--font-${hs.fontFamily}, inherit) !important;`, hs.fontFamily && `font-family: ${fontFamilyToCSS(hs.fontFamily)} !important;`,
hs.fontSize && `font-size: ${fontSizeToCSS(hs.fontSize)} !important;`, hs.fontSize && `font-size: ${fontSizeToCSS(hs.fontSize)} !important;`,
hs.backgroundColor && `background-color: ${hs.backgroundColor} !important;`, hs.backgroundColor && `background-color: ${hs.backgroundColor} !important;`,
hs.backgroundColor && `padding: 0.2em 0.4em; border-radius: 4px; display: inline-block;`, hs.backgroundColor && `padding: 0.2em 0.4em; border-radius: 4px;`,
].filter(Boolean).join(' '); ].filter(Boolean).join(' ');
if (headingRules) { if (headingRules) {
styles.push(`${scope} h1, ${scope} h2, ${scope} h3, ${scope} h4 { ${headingRules} }`); styles.push(`${scope} h1, ${scope} h2, ${scope} h3, ${scope} h4 { ${headingRules} }`);
@@ -90,7 +99,7 @@ const generateScopedStyles = (sectionId: string, elementStyles: Record<string, a
ts.color && `color: ${ts.color} !important;`, ts.color && `color: ${ts.color} !important;`,
ts.fontSize && `font-size: ${fontSizeToCSS(ts.fontSize)} !important;`, ts.fontSize && `font-size: ${fontSizeToCSS(ts.fontSize)} !important;`,
ts.fontWeight && `font-weight: ${fontWeightToCSS(ts.fontWeight)} !important;`, ts.fontWeight && `font-weight: ${fontWeightToCSS(ts.fontWeight)} !important;`,
ts.fontFamily && `font-family: var(--font-${ts.fontFamily}, inherit) !important;`, ts.fontFamily && `font-family: ${fontFamilyToCSS(ts.fontFamily)} !important;`,
].filter(Boolean).join(' '); ].filter(Boolean).join(' ');
if (textRules) { if (textRules) {
styles.push(`${scope} p, ${scope} li, ${scope} ul, ${scope} ol { ${textRules} }`); styles.push(`${scope} p, ${scope} li, ${scope} ul, ${scope} ol { ${textRules} }`);
@@ -146,6 +155,7 @@ const generateScopedStyles = (sectionId: string, elementStyles: Record<string, a
if (is) { if (is) {
const imgRules = [ const imgRules = [
is.objectFit && `object-fit: ${is.objectFit} !important;`, is.objectFit && `object-fit: ${is.objectFit} !important;`,
is.objectPosition && `object-position: ${is.objectPosition} !important;`,
is.borderRadius && `border-radius: ${is.borderRadius} !important;`, is.borderRadius && `border-radius: ${is.borderRadius} !important;`,
is.width && `width: ${is.width} !important;`, is.width && `width: ${is.width} !important;`,
is.height && `height: ${is.height} !important;`, is.height && `height: ${is.height} !important;`,
@@ -158,24 +168,15 @@ const generateScopedStyles = (sectionId: string, elementStyles: Record<string, a
return styles.join('\n'); return styles.join('\n');
}; };
export function ContentSection({ section, content: propContent, cta_text: propCtaText, cta_url: propCtaUrl }: ContentSectionProps & { outerPadding?: boolean }) { export function ContentSection({ section, content: propContent, cta_text: propCtaText, cta_url: propCtaUrl, isEditor }: ContentSectionProps & { outerPadding?: boolean; isEditor?: boolean }) {
const scheme = COLOR_SCHEMES[section.colorScheme || 'default'] ?? COLOR_SCHEMES['default']; const scheme = COLOR_SCHEMES[section.colorScheme || 'default'] ?? COLOR_SCHEMES['default'];
// Default to 'default' width if not specified // Default to 'default' width if not specified
const _layout = section.layoutVariant || 'default'; const _layout = section.layoutVariant || 'default';
const heightPreset = section.styles?.heightPreset || 'default'; const heightPreset = section.styles?.heightPreset || 'default';
const sectionBg = getSectionBackground(section.styles);
const heightMap: Record<string, string> = { const content = propContent !== undefined ? propContent : (section.props?.content?.value ?? '');
'default': 'py-12 md:py-20',
'small': 'py-8 md:py-12',
'medium': 'py-16 md:py-24',
'large': 'py-24 md:py-32',
'screen': 'min-h-screen py-20 flex items-center',
};
const heightClasses = heightMap[heightPreset] || 'py-12 md:py-20';
const content = propContent || section.props?.content?.value || section.props?.content || '';
// Helper to get text styles // Helper to get text styles
const getTextStyles = (elementName: string) => { const getTextStyles = (elementName: string) => {
@@ -203,42 +204,25 @@ export function ContentSection({ section, content: propContent, cta_text: propCt
const buttonStyle = getTextStyles('button'); const buttonStyle = getTextStyles('button');
const containerWidth = section.styles?.contentWidth ?? 'contained'; const containerWidth = section.styles?.contentWidth ?? 'contained';
const cta_text = propCtaText || section.props?.cta_text?.value || section.props?.cta_text; const cta_text = propCtaText !== undefined ? propCtaText : (section.props?.cta_text?.value ?? '');
const cta_url = propCtaUrl || section.props?.cta_url?.value || section.props?.cta_url; const cta_url = propCtaUrl !== undefined ? propCtaUrl : (section.props?.cta_url?.value ?? '');
const hasCustomBackground = !!section.styles?.backgroundColor || !!section.styles?.backgroundImage || section.styles?.backgroundType === 'gradient';
const sectionBg = getSectionBackground(section.styles);
// Helper to get background style for dynamic schemes
const getBackgroundStyle = (): React.CSSProperties | undefined => {
if (hasCustomBackground) return sectionBg.style;
if (scheme.bg === 'wn-primary-bg') {
return { backgroundColor: 'var(--wn-primary, #1a1a1a)' };
}
if (scheme.bg === 'wn-secondary-bg') {
return { backgroundColor: 'var(--wn-secondary, #6b7280)' };
}
return undefined;
};
return ( return (
<> <>
<style dangerouslySetInnerHTML={{ __html: generateScopedStyles(section.id, section.elementStyles || {}) }} /> <style dangerouslySetInnerHTML={{ __html: generateScopedStyles(section.id, section.elementStyles || {}) }} />
<section <div
id={section.id} id={section.id}
className={cn( className={cn(
'wn-content', 'wn-content relative w-full',
heightClasses,
!hasCustomBackground && !scheme.bg.startsWith('wn-') && scheme.bg,
scheme.text scheme.text
)} )}
style={getBackgroundStyle()}
> >
<SharedContentLayout <SharedContentLayout
text={content} text={content}
textStyle={textStyle.style} textStyle={textStyle.style}
headingStyle={headingStyle.style} headingStyle={headingStyle.style}
containerWidth={containerWidth as any} containerWidth={containerWidth as any}
cardStyle={{ backgroundColor: section.styles?.cardBackgroundColor }}
className={contentStyle.classNames} className={contentStyle.classNames}
buttons={cta_text && cta_url ? [{ text: cta_text, url: cta_url }] : []} buttons={cta_text && cta_url ? [{ text: cta_text, url: cta_url }] : []}
buttonStyle={{ buttonStyle={{
@@ -246,7 +230,7 @@ export function ContentSection({ section, content: propContent, cta_text: propCt
style: buttonStyle.style style: buttonStyle.style
}} }}
/> />
</section> </div>
</> </>
); );
} }

View File

@@ -1,6 +1,7 @@
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import * as LucideIcons from 'lucide-react'; import * as LucideIcons from 'lucide-react';
import { getSectionBackground } from '@/lib/sectionStyles'; import { getSectionBackground } from '@/lib/sectionStyles';
import { SectionBackgroundRenderer } from '@/components/SectionBackgroundRenderer';
interface FeatureItem { interface FeatureItem {
title?: string; title?: string;
@@ -31,16 +32,8 @@ export function FeatureGridSection({
features = [], features = [],
elementStyles, elementStyles,
styles, styles,
}: FeatureGridSectionProps & { features?: FeatureItem[], styles?: Record<string, any> }) { isEditor,
const heightMap: Record<string, string> = { }: FeatureGridSectionProps & { features?: FeatureItem[], styles?: Record<string, any>, isEditor?: boolean }) {
'default': 'py-12 md:py-20',
'small': 'py-8 md:py-12',
'medium': 'py-16 md:py-24',
'large': 'py-24 md:py-36',
'fullscreen': 'min-h-screen flex flex-col justify-center',
};
const customPadding = styles?.paddingTop || styles?.paddingBottom;
const heightClasses = customPadding ? '' : (heightMap[styles?.heightPreset || 'default'] || 'py-12 md:py-20');
const safeItems = Array.isArray(items) ? items : []; const safeItems = Array.isArray(items) ? items : [];
const safeFeatures = Array.isArray(features) ? features : []; const safeFeatures = Array.isArray(features) ? features : [];
const listItems = safeItems.length > 0 ? safeItems : safeFeatures; const listItems = safeItems.length > 0 ? safeItems : safeFeatures;
@@ -78,43 +71,20 @@ export function FeatureGridSection({
const headingStyle = getTextStyles('heading'); const headingStyle = getTextStyles('heading');
const featureItemStyle = getTextStyles('feature_item'); const featureItemStyle = getTextStyles('feature_item');
const linkStyle = getTextStyles('link');
const hasCustomBackground = !!styles?.backgroundColor || !!styles?.backgroundImage || styles?.backgroundType === 'gradient';
const sectionBg = getSectionBackground(styles); const sectionBg = getSectionBackground(styles);
// Helper to get background style for dynamic schemes
const getBackgroundStyle = (): React.CSSProperties | undefined => {
if (hasCustomBackground) return sectionBg.style;
if (colorScheme === 'primary') {
return { backgroundColor: 'var(--wn-primary, #1a1a1a)' };
}
if (colorScheme === 'secondary') {
return { backgroundColor: 'var(--wn-secondary, #6b7280)' };
}
return undefined;
};
return ( return (
<section <div
id={id} id={id}
className={cn( className={cn(
'wn-section wn-feature-grid', 'wn-section wn-feature-grid relative w-full',
`wn-feature-grid--${layout}`, `wn-feature-grid--${layout}`,
`wn-scheme--${colorScheme}`, `wn-scheme--${colorScheme}`
heightClasses,
{
'bg-muted': colorScheme === 'muted' && !hasCustomBackground,
'text-primary-foreground': colorScheme === 'primary' && !hasCustomBackground,
}
)} )}
style={getBackgroundStyle()}
> >
<div className={cn( <div className="mx-auto px-4 relative z-10 w-full">
"mx-auto px-4",
styles?.contentWidth === 'full' ? 'w-full'
: styles?.contentWidth === 'boxed' ? 'max-w-5xl'
: 'container'
)}>
{heading && ( {heading && (
<h2 <h2
className={cn( className={cn(
@@ -167,16 +137,22 @@ export function FeatureGridSection({
<p className="text-xs text-gray-400 mb-2 uppercase tracking-wider">{item.date}</p> <p className="text-xs text-gray-400 mb-2 uppercase tracking-wider">{item.date}</p>
)} )}
{item.title && ( {item.title && (
<h3 className="font-semibold text-gray-900 text-base leading-snug mb-2 group-hover:text-primary transition-colors line-clamp-2"> <h3 className={cn("font-semibold text-gray-900 leading-snug mb-2 group-hover:text-primary transition-colors line-clamp-2 w-full",
!elementStyles?.feature_item?.fontSize && "text-base",
featureItemStyle.classNames
)} style={featureItemStyle.style}>
{item.title} {item.title}
</h3> </h3>
)} )}
{(item.excerpt || item.description) && ( {(item.excerpt || item.description) && (
<p className="text-sm text-gray-500 line-clamp-3 mb-4"> <p className={cn("text-gray-500 line-clamp-3 mb-4 w-full",
!elementStyles?.feature_item?.fontSize && "text-sm",
featureItemStyle.classNames
)} style={featureItemStyle.style}>
{item.excerpt || item.description} {item.excerpt || item.description}
</p> </p>
)} )}
<span className="inline-flex items-center gap-1 text-sm font-medium text-primary"> <span className={cn("inline-flex items-center gap-1 text-sm font-medium text-primary", linkStyle.classNames)} style={linkStyle.style}>
Read more Read more
<svg className="w-4 h-4 transition-transform group-hover:translate-x-1" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <svg className="w-4 h-4 transition-transform group-hover:translate-x-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" /> <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
@@ -246,6 +222,6 @@ export function FeatureGridSection({
<p className="text-center text-gray-400 text-sm py-8">No related articles found.</p> <p className="text-center text-gray-400 text-sm py-8">No related articles found.</p>
)} )}
</div> </div>
</section> </div>
); );
} }

View File

@@ -1,5 +1,6 @@
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { getSectionBackground } from '@/lib/sectionStyles'; import { getSectionBackground } from '@/lib/sectionStyles';
import { SectionBackgroundRenderer } from '@/components/SectionBackgroundRenderer';
interface HeroSectionProps { interface HeroSectionProps {
id: string; id: string;
@@ -16,6 +17,7 @@ interface HeroSectionProps {
export function HeroSection({ export function HeroSection({
id, id,
layout = 'default', layout = 'default',
colorScheme,
title, title,
subtitle, subtitle,
image, image,
@@ -23,16 +25,8 @@ export function HeroSection({
cta_url, cta_url,
elementStyles, elementStyles,
styles, styles,
}: HeroSectionProps & { styles?: Record<string, any> }) { isEditor,
const heightMap: Record<string, string> = { }: HeroSectionProps & { styles?: Record<string, any>; isEditor?: boolean }) {
'default': 'py-16 md:py-28',
'small': 'py-8 md:py-12',
'medium': 'py-16 md:py-24',
'large': 'py-24 md:py-36',
'fullscreen': 'min-h-screen flex flex-col justify-center',
};
const customPadding = styles?.paddingTop || styles?.paddingBottom;
const heightClasses = customPadding ? '' : (heightMap[styles?.heightPreset || 'default'] || 'py-16 md:py-28');
const isImageLeft = layout === 'hero-left-image' || layout === 'image-left'; const isImageLeft = layout === 'hero-left-image' || layout === 'image-left';
const isImageRight = layout === 'hero-right-image' || layout === 'image-right'; const isImageRight = layout === 'hero-right-image' || layout === 'image-right';
const isCentered = layout === 'centered' || layout === 'default'; const isCentered = layout === 'centered' || layout === 'default';
@@ -83,22 +77,27 @@ export function HeroSection({
return undefined; return undefined;
}; */ }; */
const colorSchemeClasses = {
primary: 'bg-primary text-primary-foreground',
secondary: 'bg-secondary text-secondary-foreground',
muted: 'bg-muted text-muted-foreground',
dark: 'bg-slate-900 text-white',
}[colorScheme || ''] || '';
const isBoxed = styles?.contentWidth === 'boxed';
return ( return (
<section <section
id={id} id={id}
className={cn( className={cn(
'wn-section wn-hero', 'wn-section wn-hero',
`wn-hero--${layout}`, `wn-hero--${layout}`,
'relative overflow-hidden', 'relative overflow-hidden w-full',
heightClasses, !isBoxed && !sectionBg.style?.backgroundColor && !sectionBg.style?.backgroundImage && colorSchemeClasses
)} )}
style={sectionBg.style}
> >
<div className={cn( <div className={cn(
'mx-auto px-4 z-10 relative flex w-full', 'mx-auto z-10 relative flex w-full',
styles?.contentWidth === 'full' ? 'w-full'
: styles?.contentWidth === 'boxed' ? 'max-w-5xl'
: 'container max-w-7xl',
{ {
'flex flex-col md:flex-row items-center gap-8': isImageLeft || isImageRight, 'flex flex-col md:flex-row items-center gap-8': isImageLeft || isImageRight,
'text-center': isCentered, 'text-center': isCentered,
@@ -106,22 +105,31 @@ export function HeroSection({
)}> )}>
{/* Image - Left */} {/* Image - Left */}
{image && isImageLeft && ( {image && isImageLeft && (
<div className="w-full md:w-1/2"> <div className={cn("w-full md:w-1/2 flex flex-col", {
'items-start': imageStyle.alignment === 'left',
'items-center': imageStyle.alignment === 'center',
'items-end': imageStyle.alignment === 'right',
})}>
<div <div
className="rounded-lg shadow-xl overflow-hidden" className={cn("shadow-xl overflow-hidden", !imageStyle.borderRadius && "rounded-lg")}
style={{ style={{
backgroundColor: imageStyle.backgroundColor, backgroundColor: imageStyle.backgroundColor,
width: imageStyle.width || 'auto', width: imageStyle.width || 'auto',
maxWidth: '100%' maxWidth: '100%',
borderRadius: imageStyle.borderRadius,
borderColor: imageStyle.borderColor,
borderWidth: imageStyle.borderWidth,
borderStyle: imageStyle.borderWidth ? 'solid' : undefined,
}} }}
> >
<img <img
src={image} src={image}
alt={title || 'Hero image'} alt={title || 'Hero image'}
className="w-full h-auto block" className="w-full h-full object-cover"
style={{ style={{
objectFit: imageStyle.objectFit, objectFit: imageStyle.objectFit,
height: imageStyle.height, objectPosition: imageStyle.objectPosition,
height: imageStyle.height || 'auto',
}} }}
/> />
</div> </div>
@@ -139,7 +147,7 @@ export function HeroSection({
{title && ( {title && (
<h1 <h1
className={cn( className={cn(
"wn-hero__title mb-6 leading-tight", "wn-hero__title mb-6 leading-tight w-full",
!elementStyles?.title?.fontSize && "text-4xl md:text-5xl lg:text-6xl", !elementStyles?.title?.fontSize && "text-4xl md:text-5xl lg:text-6xl",
!elementStyles?.title?.fontWeight && "font-bold", !elementStyles?.title?.fontWeight && "font-bold",
titleStyle.classNames titleStyle.classNames
@@ -153,7 +161,7 @@ export function HeroSection({
{subtitle && ( {subtitle && (
<p <p
className={cn( className={cn(
"wn-hero__subtitle text-opacity-80 mb-8", "wn-hero__subtitle text-opacity-80 mb-8 w-full",
!elementStyles?.subtitle?.fontSize && "text-lg md:text-xl", !elementStyles?.subtitle?.fontSize && "text-lg md:text-xl",
subtitleStyle.classNames subtitleStyle.classNames
)} )}
@@ -166,10 +174,24 @@ export function HeroSection({
{/* Centered Image */} {/* Centered Image */}
<div <div
className={cn( className={cn(
"mt-12 mx-auto rounded-lg shadow-xl overflow-hidden", "mt-12 mx-auto shadow-xl overflow-hidden flex flex-col",
imageStyle.width ? "" : "max-w-4xl" !imageStyle.borderRadius && "rounded-lg",
imageStyle.width ? "" : "max-w-4xl",
{
'mr-auto mx-0': imageStyle.alignment === 'left',
'ml-auto mx-0': imageStyle.alignment === 'right',
'mx-auto': imageStyle.alignment === 'center' || !imageStyle.alignment,
}
)} )}
style={{ backgroundColor: imageStyle.backgroundColor, width: imageStyle.width || 'auto', maxWidth: '100%' }} style={{
backgroundColor: imageStyle.backgroundColor,
width: imageStyle.width || 'auto',
maxWidth: '100%',
borderRadius: imageStyle.borderRadius,
borderColor: imageStyle.borderColor,
borderWidth: imageStyle.borderWidth,
borderStyle: imageStyle.borderWidth ? 'solid' : undefined,
}}
> >
{image && isCentered && ( {image && isCentered && (
<img <img
@@ -177,12 +199,13 @@ export function HeroSection({
alt={title || 'Hero image'} alt={title || 'Hero image'}
className={cn( className={cn(
"w-full rounded-[inherit]", "w-full rounded-[inherit]",
!imageStyle.height && "h-auto", !imageStyle.objectFit && "object-cover",
!imageStyle.objectFit && "object-cover" "h-full"
)} )}
style={{ style={{
objectFit: imageStyle.objectFit, objectFit: imageStyle.objectFit,
height: imageStyle.height, objectPosition: imageStyle.objectPosition,
height: imageStyle.height || 'auto',
maxWidth: '100%', maxWidth: '100%',
}} }}
/> />
@@ -190,24 +213,33 @@ export function HeroSection({
</div> </div>
{cta_text && cta_url && ( {cta_text && cta_url && (
<a <div className="w-full mt-8" style={{ textAlign: ctaStyle.style?.textAlign || (isCentered ? 'center' : 'left') as React.CSSProperties['textAlign'] }}>
href={cta_url} <a
className={cn( href={cta_url}
"wn-hero__cta inline-block px-8 py-3 rounded-lg font-semibold hover:opacity-90 transition-colors mt-8", className={cn(
!ctaStyle.style?.backgroundColor && "bg-primary", "wn-hero__cta inline-block px-8 py-3 rounded-lg font-semibold hover:opacity-90 transition-colors",
!ctaStyle.style?.color && "text-primary-foreground", !ctaStyle.style?.backgroundColor && "bg-primary",
ctaStyle.classNames !ctaStyle.style?.color && "text-primary-foreground",
)} ctaStyle.classNames
style={ctaStyle.style} )}
> style={{
{cta_text} ...ctaStyle.style,
</a> textAlign: undefined
}}
>
{cta_text}
</a>
</div>
)} )}
</div> </div>
{/* Image - Right */} {/* Image - Right */}
{image && isImageRight && ( {image && isImageRight && (
<div className="w-full md:w-1/2"> <div className={cn("w-full md:w-1/2 flex flex-col", {
'items-start': imageStyle.alignment === 'left',
'items-center': imageStyle.alignment === 'center',
'items-end': imageStyle.alignment === 'right',
})}>
<div <div
className="rounded-lg shadow-xl overflow-hidden" className="rounded-lg shadow-xl overflow-hidden"
style={{ style={{
@@ -219,10 +251,11 @@ export function HeroSection({
<img <img
src={image} src={image}
alt={title || 'Hero image'} alt={title || 'Hero image'}
className="w-full h-auto block" className="w-full h-full object-cover"
style={{ style={{
objectFit: imageStyle.objectFit, objectFit: imageStyle.objectFit,
height: imageStyle.height, objectPosition: imageStyle.objectPosition,
height: imageStyle.height || 'auto',
}} }}
/> />
</div> </div>

View File

@@ -1,6 +1,7 @@
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { SharedContentLayout } from '@/components/SharedContentLayout'; import { SharedContentLayout } from '@/components/SharedContentLayout';
import { getSectionBackground } from '@/lib/sectionStyles'; import { getSectionBackground } from '@/lib/sectionStyles';
import { SectionBackgroundRenderer } from '@/components/SectionBackgroundRenderer';
interface ImageTextSectionProps { interface ImageTextSectionProps {
id: string; id: string;
@@ -23,7 +24,8 @@ export function ImageTextSection({
cta_url, cta_url,
elementStyles, elementStyles,
styles, styles,
}: ImageTextSectionProps & { styles?: Record<string, any>, cta_text?: string, cta_url?: string }) { isEditor,
}: ImageTextSectionProps & { styles?: Record<string, any>, cta_text?: string, cta_url?: string, isEditor?: boolean }) {
const isImageRight = layout === 'image-right' || layout === 'right'; const isImageRight = layout === 'image-right' || layout === 'right';
// Helper to get text styles (including font family) // Helper to get text styles (including font family)
@@ -55,44 +57,15 @@ export function ImageTextSection({
const imageStyle = elementStyles?.['image'] || {}; const imageStyle = elementStyles?.['image'] || {};
// Height preset support
const heightPreset = styles?.heightPreset || 'default';
const heightMap: Record<string, string> = {
'default': 'py-12 md:py-24',
'small': 'py-8 md:py-16',
'medium': 'py-16 md:py-32',
'large': 'py-24 md:py-48',
'screen': 'min-h-screen py-20 flex items-center',
};
const heightClasses = heightMap[heightPreset] || 'py-12 md:py-24';
const hasCustomBackground = !!styles?.backgroundColor || !!styles?.backgroundImage || styles?.backgroundType === 'gradient';
const sectionBg = getSectionBackground(styles); const sectionBg = getSectionBackground(styles);
// Helper to get background style for dynamic schemes
const getBackgroundStyle = (): React.CSSProperties | undefined => {
if (hasCustomBackground) return sectionBg.style;
if (colorScheme === 'primary') {
return { backgroundColor: 'var(--wn-primary, #1a1a1a)' };
}
if (colorScheme === 'secondary') {
return { backgroundColor: 'var(--wn-secondary, #6b7280)' };
}
return undefined;
};
return ( return (
<section <div
id={id} id={id}
className={cn( className={cn(
'wn-section wn-image-text', 'wn-section wn-image-text relative w-full',
`wn-scheme--${colorScheme}`, `wn-scheme--${colorScheme}`
!styles?.paddingTop && !styles?.paddingBottom && heightClasses,
{
'bg-muted': colorScheme === 'muted' && !hasCustomBackground,
}
)} )}
style={getBackgroundStyle()}
> >
<SharedContentLayout <SharedContentLayout
title={title} title={title}
@@ -104,16 +77,14 @@ export function ImageTextSection({
titleClassName={titleStyle.classNames} titleClassName={titleStyle.classNames}
textStyle={textStyle.style} textStyle={textStyle.style}
textClassName={textStyle.classNames} textClassName={textStyle.classNames}
imageStyle={{ imageStyle={imageStyle}
backgroundColor: imageStyle.backgroundColor, cardStyle={{ backgroundColor: styles?.cardBackgroundColor }}
objectFit: imageStyle.objectFit,
}}
buttons={cta_text && cta_url ? [{ text: cta_text, url: cta_url }] : []} buttons={cta_text && cta_url ? [{ text: cta_text, url: cta_url }] : []}
buttonStyle={{ buttonStyle={{
classNames: buttonStyle.classNames, classNames: buttonStyle.classNames,
style: buttonStyle.style style: buttonStyle.style
}} }}
/> />
</section> </div>
); );
} }

View File

@@ -1,6 +1,7 @@
import { useEffect, useRef } from 'react'; import { useEffect, useRef } from 'react';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { getSectionBackground } from '@/lib/sectionStyles'; import { getSectionBackground } from '@/lib/sectionStyles';
import { SectionBackgroundRenderer } from '@/components/SectionBackgroundRenderer';
interface MarqueeBannerProps { interface MarqueeBannerProps {
id: string; id: string;
@@ -8,6 +9,7 @@ interface MarqueeBannerProps {
speed?: number; // seconds for one full cycle speed?: number; // seconds for one full cycle
separator?: string; separator?: string;
styles?: Record<string, any>; styles?: Record<string, any>;
elementStyles?: Record<string, any>;
} }
export function MarqueeBanner({ export function MarqueeBanner({
@@ -16,20 +18,46 @@ export function MarqueeBanner({
speed = 30, speed = 30,
separator = '✦', separator = '✦',
styles, styles,
elementStyles,
}: MarqueeBannerProps) { }: MarqueeBannerProps) {
const sectionBg = getSectionBackground(styles);
const items = text.split(separator).map(t => t.trim()).filter(Boolean); const items = text.split(separator).map(t => t.trim()).filter(Boolean);
const getTextStyles = (elementName: string) => {
const es = elementStyles?.[elementName] || {};
return {
classNames: cn(
es.fontSize,
es.fontWeight,
{
'font-sans': es.fontFamily === 'secondary',
'font-serif': es.fontFamily === 'primary',
}
),
style: {
color: es.color,
textAlign: es.textAlign as any,
}
};
};
const textStyle = getTextStyles('text');
// If the parent didn't set a custom background, we fallback to primary for the marquee.
const hasCustomBg = !!styles?.backgroundColor || !!styles?.backgroundImage || styles?.backgroundType === 'gradient';
const sectionBg = getSectionBackground(styles);
const hasCustomPadding = styles?.paddingTop || styles?.paddingBottom;
return ( return (
<section <section
id={id} id={id}
className="wn-section wn-marquee overflow-hidden py-3" className={cn("wn-section wn-marquee relative overflow-hidden w-full", hasCustomPadding ? "" : "py-3")}
style={{ style={{
backgroundColor: sectionBg.style?.backgroundColor || 'var(--wn-primary, #1a1a1a)', backgroundColor: !hasCustomBg ? 'var(--wn-primary, #1a1a1a)' : undefined,
color: sectionBg.style?.color || '#fff', color: !hasCustomBg ? '#fff' : 'inherit',
}} }}
> >
<div className="flex whitespace-nowrap"> <div className="flex whitespace-nowrap relative z-10">
{/* Duplicate twice for seamless infinite scroll */} {/* Duplicate twice for seamless infinite scroll */}
{[0, 1].map((i) => ( {[0, 1].map((i) => (
<div <div
@@ -39,9 +67,13 @@ export function MarqueeBanner({
aria-hidden={i === 1} aria-hidden={i === 1}
> >
{items.map((item, idx) => ( {items.map((item, idx) => (
<span key={idx} className="flex items-center gap-8 text-sm font-medium tracking-wide uppercase"> <span
key={idx}
className={cn("flex items-center gap-8 text-sm font-medium tracking-wide uppercase", textStyle.classNames)}
style={textStyle.style}
>
{item} {item}
{idx < items.length - 1 && <span className="opacity-50 text-xs"></span>} {idx < items.length - 1 && <span className="opacity-50 text-xs">{separator}</span>}
</span> </span>
))} ))}
</div> </div>

View File

@@ -6,6 +6,7 @@ import { apiClient } from '@/lib/api/client';
import { ProductCard } from '@/components/ProductCard'; import { ProductCard } from '@/components/ProductCard';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { getSectionBackground } from '@/lib/sectionStyles'; import { getSectionBackground } from '@/lib/sectionStyles';
import { SectionBackgroundRenderer } from '@/components/SectionBackgroundRenderer';
import type { ProductsResponse } from '@/types/product'; import type { ProductsResponse } from '@/types/product';
interface ProductCarouselProps { interface ProductCarouselProps {
@@ -39,7 +40,6 @@ export function ProductCarousel({
elementStyles, elementStyles,
}: ProductCarouselProps) { }: ProductCarouselProps) {
const trackRef = useRef<HTMLDivElement>(null); const trackRef = useRef<HTMLDivElement>(null);
const sectionBg = getSectionBackground(styles);
// Build query params // Build query params
const queryParams = new URLSearchParams({ per_page: String(limit) }); const queryParams = new URLSearchParams({ per_page: String(limit) });
@@ -68,29 +68,62 @@ export function ProductCarousel({
trackRef.current.scrollBy({ left: direction === 'left' ? -cardWidth * 2 : cardWidth * 2, behavior: 'smooth' }); trackRef.current.scrollBy({ left: direction === 'left' ? -cardWidth * 2 : cardWidth * 2, behavior: 'smooth' });
}; };
// Helper to get text styles (including font family)
const getTextStyles = (elementName: string) => {
const elementStyle = elementStyles?.[elementName] || {};
return {
classNames: cn(
elementStyle.fontSize,
elementStyle.fontWeight,
{
'font-sans': elementStyle.fontFamily === 'secondary',
'font-serif': elementStyle.fontFamily === 'primary',
}
),
style: {
color: elementStyle.color,
textAlign: elementStyle.textAlign,
backgroundColor: elementStyle.backgroundColor,
borderColor: elementStyle.borderColor,
borderWidth: elementStyle.borderWidth,
borderRadius: elementStyle.borderRadius,
}
};
};
const titleStyle = getTextStyles('title');
const subtitleStyle = getTextStyles('subtitle');
const linkStyle = getTextStyles('link');
const sectionBg = getSectionBackground(styles);
const hasCustomPadding = styles?.paddingTop || styles?.paddingBottom;
return ( return (
<section id={id} className="wn-section wn-product-carousel py-12 md:py-16" style={sectionBg.style}> <section
<div className="container mx-auto px-4 max-w-7xl"> id={id}
className={cn("wn-section wn-product-carousel relative overflow-hidden w-full", hasCustomPadding ? "" : "py-12 md:py-16")}
>
<div className="w-full mx-auto px-4 relative z-10">
{/* Header */} {/* Header */}
<div className="flex items-end justify-between mb-8"> <div className="flex items-end justify-between mb-8">
<div> <div>
{title && ( {title && (
<h2 <h2
className="text-3xl md:text-4xl font-bold" className={cn("text-3xl font-bold", titleStyle.classNames)}
style={{ color: elementStyles?.title?.color }} style={titleStyle.style}
> >
{title} {title}
</h2> </h2>
)} )}
{subtitle && ( {subtitle && (
<p className="text-muted-foreground mt-2" style={{ color: elementStyles?.subtitle?.color }}> <p className={cn("text-muted-foreground mt-2", subtitleStyle.classNames)} style={subtitleStyle.style}>
{subtitle} {subtitle}
</p> </p>
)} )}
</div> </div>
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
{cta_text && cta_url && ( {cta_text && (
<Link to={cta_url} className="text-sm font-semibold hover:underline mr-4 whitespace-nowrap"> <Link to={cta_url || '#'} className={cn("text-sm font-semibold hover:underline mr-4 whitespace-nowrap", linkStyle.classNames)} style={linkStyle.style}>
{cta_text} {cta_text}
</Link> </Link>
)} )}

View File

@@ -3,6 +3,7 @@ import { Link } from 'react-router-dom';
import { X, ShoppingCart, Eye } from 'lucide-react'; import { X, ShoppingCart, Eye } from 'lucide-react';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { getSectionBackground } from '@/lib/sectionStyles'; import { getSectionBackground } from '@/lib/sectionStyles';
import { SectionBackgroundRenderer } from '@/components/SectionBackgroundRenderer';
import { formatPrice } from '@/lib/currency'; import { formatPrice } from '@/lib/currency';
import { useCartStore } from '@/lib/cart/store'; import { useCartStore } from '@/lib/cart/store';
import { apiClient } from '@/lib/api/client'; import { apiClient } from '@/lib/api/client';
@@ -47,13 +48,38 @@ export function ShoppableImage({
styles, styles,
elementStyles, elementStyles,
}: ShoppableImageProps) { }: ShoppableImageProps) {
const sectionBg = getSectionBackground(styles);
const [activeHotspot, setActiveHotspot] = useState<number | null>(null); const [activeHotspot, setActiveHotspot] = useState<number | null>(null);
const { addItem, openCart } = useCartStore(); const { addItem, openCart } = useCartStore();
const displayHotspots = (hotspots && hotspots.length > 0) ? hotspots : DEMO_HOTSPOTS; const displayHotspots = (hotspots && hotspots.length > 0) ? hotspots : DEMO_HOTSPOTS;
const hasImage = !!image; const hasImage = !!image;
// Helper to get text styles (including font family)
const getTextStyles = (elementName: string) => {
const es = elementStyles?.[elementName] || {};
return {
classNames: cn(
es.fontSize,
es.fontWeight,
{
'font-sans': es.fontFamily === 'secondary',
'font-serif': es.fontFamily === 'primary',
}
),
style: {
color: es.color,
textAlign: es.textAlign as any,
backgroundColor: es.backgroundColor,
borderColor: es.borderColor,
borderWidth: es.borderWidth,
borderRadius: es.borderRadius,
}
};
};
const titleStyle = getTextStyles('title');
const subtitleStyle = getTextStyles('subtitle');
const handleAddToCart = async (hotspot: Hotspot, e: React.MouseEvent) => { const handleAddToCart = async (hotspot: Hotspot, e: React.MouseEvent) => {
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
@@ -81,18 +107,38 @@ export function ShoppableImage({
} }
}; };
const sectionBg = getSectionBackground(styles);
const hasCustomPadding = styles?.paddingTop || styles?.paddingBottom;
return ( return (
<section id={id} className="wn-section wn-shoppable-image py-12 md:py-16" style={sectionBg.style}> <section
<div className="container mx-auto px-4 max-w-7xl"> id={id}
className={cn("wn-section wn-shoppable-image relative overflow-hidden w-full", hasCustomPadding ? "" : "py-12 md:py-16")}
>
<div className="w-full mx-auto px-4 relative z-10">
{(title || subtitle) && ( {(title || subtitle) && (
<div className="mb-8 text-center"> <div className="mb-8 text-center">
{title && ( {title && (
<h2 className="text-3xl md:text-4xl font-bold" style={{ color: elementStyles?.title?.color }}> <h2
className={cn(
!elementStyles?.title?.fontSize && "text-3xl md:text-4xl",
!elementStyles?.title?.fontWeight && "font-bold",
titleStyle.classNames
)}
style={titleStyle.style}
>
{title} {title}
</h2> </h2>
)} )}
{subtitle && ( {subtitle && (
<p className="text-muted-foreground mt-2" style={{ color: elementStyles?.subtitle?.color }}> <p
className={cn(
"mt-2",
!elementStyles?.subtitle?.fontSize && "text-muted-foreground",
subtitleStyle.classNames
)}
style={subtitleStyle.style}
>
{subtitle} {subtitle}
</p> </p>
)} )}
@@ -116,12 +162,14 @@ export function ShoppableImage({
{/* Hotspot pins */} {/* Hotspot pins */}
{displayHotspots.map((hotspot, idx) => { {displayHotspots.map((hotspot, idx) => {
const isActive = activeHotspot === idx; const isActive = activeHotspot === idx;
const xVal = parseFloat(String(hotspot.x ?? 0).replace('%', '')) || 0;
const yVal = parseFloat(String(hotspot.y ?? 0).replace('%', '')) || 0;
return ( return (
<div <div
key={idx} key={idx}
className="absolute" className="absolute"
style={{ left: `${hotspot.x}%`, top: `${hotspot.y}%`, transform: 'translate(-50%, -50%)' }} style={{ left: `${xVal}%`, top: `${yVal}%`, transform: 'translate(-50%, -50%)' }}
> >
{/* Pulsing pin */} {/* Pulsing pin */}
<button <button
@@ -143,8 +191,8 @@ export function ShoppableImage({
<div <div
className={cn( className={cn(
'absolute z-20 w-56 bg-white rounded-xl shadow-2xl border p-3', 'absolute z-20 w-56 bg-white rounded-xl shadow-2xl border p-3',
hotspot.x > 60 ? 'right-full mr-3' : 'left-full ml-3', xVal > 60 ? 'right-full mr-3' : 'left-full ml-3',
hotspot.y > 60 ? 'bottom-0' : 'top-0', yVal > 60 ? 'bottom-0' : 'top-0',
)} )}
> >
{/* Close */} {/* Close */}

View File

@@ -40,6 +40,8 @@ interface OrderDetailsResponse extends BaseResponse {
start_date: string; start_date: string;
next_payment_date: string | null; next_payment_date: string | null;
end_date: string | null; end_date: string | null;
payment_method?: string;
gateway_supports_auto_renew?: boolean;
}; };
} }
@@ -130,6 +132,35 @@ const OrderPay: React.FC = () => {
} }
}; };
// C1: Compute the projected next billing date for an early renewal.
// The server-side logic in SubscriptionManager.php copies the stored next_payment_date as
// the base when it is still in the future; otherwise it falls back to `now`. We mirror
// that here so the customer sees the same date the system will set after payment.
const computeProjectedNextPaymentDate = (sub: NonNullable<OrderDetailsResponse['subscription']>): Date => {
const now = new Date();
const storedNext = sub.next_payment_date ? new Date(sub.next_payment_date) : null;
const baseDate = storedNext && storedNext.getTime() > now.getTime() ? storedNext : now;
const interval = Math.max(1, sub.billing_interval || 1);
const projected = new Date(baseDate);
switch (sub.billing_period) {
case 'day':
projected.setDate(projected.getDate() + interval);
break;
case 'week':
projected.setDate(projected.getDate() + interval * 7);
break;
case 'month':
projected.setMonth(projected.getMonth() + interval);
break;
case 'year':
projected.setFullYear(projected.getFullYear() + interval);
break;
default:
projected.setMonth(projected.getMonth() + interval);
}
return projected;
};
if (loading) return <div className="p-8 text-center">Loading order details...</div>; if (loading) return <div className="p-8 text-center">Loading order details...</div>;
if (!order) return <div className="p-8 text-center text-red-500">Order not found</div>; if (!order) return <div className="p-8 text-center text-red-500">Order not found</div>;
@@ -143,23 +174,48 @@ const OrderPay: React.FC = () => {
<SubscriptionTimeline subscription={order.subscription} /> <SubscriptionTimeline subscription={order.subscription} />
)} )}
{isRenewal && !order.subscription && ( {isRenewal && !order.subscription && (() => {
<div className="bg-blue-50 border-l-4 border-blue-500 p-4 mb-6"> // C1: When the order is a renewal, the customer is paying for the *upcoming*
<div className="flex"> // period. After payment, SubscriptionManager will shift next_payment_date forward
<div className="flex-shrink-0"> // by the billing interval (using the stored next_payment_date as the base if it
<svg className="h-5 w-5 text-blue-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor"> // is still in the future, otherwise `now`). We surface that projected date here
<path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clipRule="evenodd" /> // so the customer is not surprised when their next charge lands sooner than the
</svg> // original cycle.
</div> const projected = order.subscription
<div className="ml-3"> ? computeProjectedNextPaymentDate(order.subscription)
<p className="text-sm text-blue-700"> : null;
This is a payment for your <span className="font-bold">subscription renewal</span>. const projectedLabel = projected
Completing this payment will extend your subscription period. ? projected.toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric' })
</p> : null;
// §9 — Manual vs auto copy. If the gateway is manual, frame the renewal
// as "complete the payment to continue" rather than "will renew automatically".
const isAuto = false;
return (
<div className={`border-l-4 p-4 mb-6 ${isAuto ? 'bg-blue-50 border-blue-500' : 'bg-amber-50 border-amber-500'}`}>
<div className="flex">
<div className="flex-shrink-0">
<svg className={`h-5 w-5 ${isAuto ? 'text-blue-400' : 'text-amber-400'}`} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
<path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clipRule="evenodd" />
</svg>
</div>
<div className="ml-3">
<p className={`text-sm ${isAuto ? 'text-blue-700' : 'text-amber-800'}`}>
{isAuto ? (
<>This is a payment for your <span className="font-bold">subscription renewal</span>. After this payment, your subscription will renew automatically on the date shown below.</>
) : (
<>This is a <span className="font-bold">manual subscription renewal</span>. Your saved payment method cannot be charged automatically for this gateway, so please complete the payment to continue your subscription.</>
)}
</p>
{projectedLabel && (
<p className={`text-sm mt-1 ${isAuto ? 'text-blue-700' : 'text-amber-800'}`}>
Your next billing date will be <span className="font-bold">{projectedLabel}</span>.
</p>
)}
</div>
</div> </div>
</div> </div>
</div> );
)} })()}
<div className="bg-white rounded-lg shadow p-6 mb-6"> <div className="bg-white rounded-lg shadow p-6 mb-6">
<h2 className="text-xl font-semibold mb-4">Order Summary <span className="text-gray-400 font-normal">#{order.number}</span></h2> <h2 className="text-xl font-semibold mb-4">Order Summary <span className="text-gray-400 font-normal">#{order.number}</span></h2>

View File

@@ -0,0 +1,74 @@
import React from 'react';
import { useParams } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api/client';
import { ProductCard } from '@/components/ProductCard';
interface CollectionData {
id: number;
title: string;
description: string;
products: any[];
}
export default function CollectionPage() {
const { slug } = useParams<{ slug: string }>();
const { data: collection, isLoading, error } = useQuery<CollectionData>({
queryKey: ['affiliate-collection', slug],
queryFn: async () => {
return api.get(`/shop/collections/${slug || ''}`);
},
enabled: !!slug
});
if (isLoading) {
return (
<div className="max-w-6xl mx-auto px-4 py-8">
<div className="animate-pulse space-y-8">
<div className="h-12 bg-muted rounded w-1/3"></div>
<div className="h-4 bg-muted rounded w-1/2"></div>
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
{[...Array(4)].map((_, i) => (
<div key={i} className="h-64 bg-muted rounded"></div>
))}
</div>
</div>
</div>
);
}
if (error || !collection) {
return (
<div className="max-w-6xl mx-auto px-4 py-16 text-center">
<h1 className="text-2xl font-bold mb-2">Collection Not Found</h1>
<p className="text-muted-foreground">The collection you are looking for does not exist or has been removed.</p>
</div>
);
}
return (
<div className="max-w-6xl mx-auto px-4 py-8">
<div className="mb-10 text-center">
<h1 className="text-3xl font-bold tracking-tight mb-3">{collection.title}</h1>
{collection.description && (
<p className="text-muted-foreground max-w-2xl mx-auto">
{collection.description}
</p>
)}
</div>
{collection.products.length > 0 ? (
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
{collection.products.map(product => (
<ProductCard key={product.id} product={product} />
))}
</div>
) : (
<div className="text-center py-12 bg-muted/20 rounded-lg">
<p className="text-muted-foreground">There are no products in this collection.</p>
</div>
)}
</div>
);
}

View File

@@ -1,6 +1,6 @@
import React, { useState } from 'react'; import React, { useState } from 'react';
import { useQuery } from '@tanstack/react-query'; import { useQuery } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom'; import { useNavigate, useSearchParams } from 'react-router-dom';
import { Search, Filter, X } from 'lucide-react'; import { Search, Filter, X } from 'lucide-react';
import { apiClient } from '@/lib/api/client'; import { apiClient } from '@/lib/api/client';
import { useCartStore } from '@/lib/cart/store'; import { useCartStore } from '@/lib/cart/store';
@@ -8,16 +8,38 @@ import { Button } from '@/components/ui/button';
import Container from '@/components/Layout/Container'; import Container from '@/components/Layout/Container';
import { ProductCard } from '@/components/ProductCard'; import { ProductCard } from '@/components/ProductCard';
import { toast } from 'sonner'; import { toast } from 'sonner';
import { Input } from '@/components/ui/input';
import { useShopSettings } from '@/hooks/useAppearanceSettings'; import { useShopSettings } from '@/hooks/useAppearanceSettings';
import SEOHead from '@/components/SEOHead'; import SEOHead from '@/components/SEOHead';
import { useDebounce } from '@/hooks/useDebounce';
import type { ProductsResponse, ProductCategory } from '@/types/product'; import type { ProductsResponse, ProductCategory } from '@/types/product';
function useBreakpoint() {
const [breakpoint, setBreakpoint] = React.useState<'mobile' | 'tablet' | 'desktop'>('desktop');
React.useEffect(() => {
const check = () => {
if (window.innerWidth < 768) setBreakpoint('mobile');
else if (window.innerWidth < 1024) setBreakpoint('tablet');
else setBreakpoint('desktop');
};
check();
window.addEventListener('resize', check);
return () => window.removeEventListener('resize', check);
}, []);
return breakpoint;
}
export default function Shop() { export default function Shop() {
const navigate = useNavigate(); const navigate = useNavigate();
const [searchParams] = useSearchParams();
const { layout: shopLayout, elements } = useShopSettings(); const { layout: shopLayout, elements } = useShopSettings();
const [page, setPage] = useState(1); const [page, setPage] = useState(1);
const [search, setSearch] = useState(''); const [search, setSearch] = useState(searchParams.get('search') || '');
const [category, setCategory] = useState(''); const [category, setCategory] = useState(searchParams.get('category') || '');
const [minPriceInput, setMinPriceInput] = useState('');
const [maxPriceInput, setMaxPriceInput] = useState('');
const minPrice = useDebounce(minPriceInput, 500);
const maxPrice = useDebounce(maxPriceInput, 500);
const [sortBy, setSortBy] = useState(''); const [sortBy, setSortBy] = useState('');
const { addItem } = useCartStore(); const { addItem } = useCartStore();
@@ -73,15 +95,25 @@ export default function Shop() {
const masonryColsClass = `${masonryMobileClass} ${masonryTabletClass} ${masonryDesktopClass}`; const masonryColsClass = `${masonryMobileClass} ${masonryTabletClass} ${masonryDesktopClass}`;
const isMasonry = shopLayout.grid_style === 'masonry'; const isMasonry = shopLayout.grid_style === 'masonry';
const isRichSidebar = shopLayout.filter_layout === 'rich_sidebar';
// Automatically reset page when filters change
React.useEffect(() => {
setPage(1);
}, [search, category, minPrice, maxPrice, sortBy]);
const breakpoint = useBreakpoint();
// Fetch products // Fetch products
const { data: productsData, isLoading: productsLoading } = useQuery<ProductsResponse>({ const { data: productsData, isLoading: productsLoading } = useQuery<ProductsResponse>({
queryKey: ['products', page, search, category], queryKey: ['products', page, search, category, minPrice, maxPrice],
queryFn: () => apiClient.get(apiClient.endpoints.shop.products, { queryFn: () => apiClient.get(apiClient.endpoints.shop.products, {
page, page,
per_page: 12, per_page: 12,
search, search,
category, category,
min_price: minPrice,
max_price: maxPrice,
}), }),
}); });
@@ -135,57 +167,177 @@ export default function Shop() {
<p className="text-muted-foreground">Browse our collection of products</p> <p className="text-muted-foreground">Browse our collection of products</p>
</div> </div>
{/* Filters */} {/* Main Content Area */}
{(elements.search_bar || elements.category_filter) && ( <div className={isRichSidebar ? "flex flex-col lg:flex-row gap-8" : ""}>
<div className="flex flex-col md:flex-row gap-4 mb-8">
{/* Search */} {/* Rich Sidebar */}
{elements.search_bar && ( {isRichSidebar && (elements.search_bar || elements.category_filter) && (
<div className="flex-1 relative"> <div className="w-full lg:w-64 flex-shrink-0 space-y-6 lg:sticky lg:top-24 lg:self-start lg:max-h-[calc(100vh-6rem)] lg:overflow-y-auto no-scrollbar">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" /> <h2 className="text-lg font-semibold border-b pb-2 mb-4">Filters</h2>
<input
type="text" {/* Search */}
placeholder="Search products..." {elements.search_bar && (
value={search} <div className="relative">
onChange={(e) => setSearch(e.target.value)} <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
className="w-full !pl-10 pr-10 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-primary" <Input
/> type="text"
{search && ( placeholder="Search products..."
<button value={search}
onClick={() => setSearch('')} onChange={(e) => setSearch(e.target.value)}
className="font-[inherit] absolute right-3 top-1/2 -translate-y-1/2 p-1 hover:bg-gray-100 rounded-full transition-colors" className="!pl-10 pr-10"
> />
<X className="h-4 w-4 text-muted-foreground" /> {search && (
</button> <button
onClick={() => setSearch('')}
className="font-[inherit] absolute right-3 top-1/2 -translate-y-1/2 p-1 hover:bg-muted rounded-full transition-colors"
>
<X className="h-4 w-4 text-muted-foreground" />
</button>
)}
</div>
)}
{/* Categories */}
{elements.category_filter && categories && categories.length > 0 && (
<div className="space-y-3">
<h3 className="font-medium text-sm text-muted-foreground uppercase tracking-wider">Categories</h3>
<div className="flex flex-col gap-2">
<button
className={`text-left text-sm hover:text-primary transition-colors ${!category ? 'font-semibold text-primary' : 'text-foreground'}`}
onClick={() => setCategory('')}
>
All Categories
</button>
{categories.map((cat: any) => (
<button
key={cat.id}
className={`text-left text-sm hover:text-primary transition-colors flex justify-between items-center ${category === cat.slug ? 'font-semibold text-primary' : 'text-foreground'}`}
onClick={() => setCategory(cat.slug)}
>
<span>{cat.name}</span>
<span className="text-xs bg-muted px-2 py-0.5 rounded-full text-muted-foreground">{cat.count}</span>
</button>
))}
</div>
</div>
)}
{/* Price Filter */}
{isRichSidebar && (
<div className="space-y-3">
<h3 className="font-medium text-sm text-muted-foreground uppercase tracking-wider">Price Range</h3>
<div className="flex items-center gap-2">
<Input
type="number"
placeholder="Min"
value={minPriceInput}
onChange={(e) => setMinPriceInput(e.target.value)}
className="focus-visible:ring-0 focus-visible:ring-offset-0 focus-visible:shadow-none"
/>
<span className="text-muted-foreground">-</span>
<Input
type="number"
placeholder="Max"
value={maxPriceInput}
onChange={(e) => setMaxPriceInput(e.target.value)}
className="focus-visible:ring-0 focus-visible:ring-offset-0 focus-visible:shadow-none"
/>
</div>
</div>
)}
{/* Clear Filters */}
{(search || category || minPrice || maxPrice) && (
<Button
variant="outline"
className="w-full mt-4"
onClick={() => {
setSearch('');
setCategory('');
setMinPriceInput('');
setMaxPriceInput('');
setSortBy('');
}}
>
Clear All Filters
</Button>
)}
</div>
)}
{/* Product Grid Area */}
<div className="flex-1">
{/* Top Bar Filters (Basic Layout) */}
{!isRichSidebar && (elements.search_bar || elements.category_filter || elements.sort_dropdown) && (
<div className="flex flex-col md:flex-row gap-4 mb-8">
{/* Search */}
{elements.search_bar && (
<div className="flex-1 relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
type="text"
placeholder="Search products..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="!pl-10 pr-10"
/>
{search && (
<button
onClick={() => setSearch('')}
className="font-[inherit] absolute right-3 top-1/2 -translate-y-1/2 p-1 hover:bg-muted rounded-full transition-colors"
>
<X className="h-4 w-4 text-muted-foreground" />
</button>
)}
</div>
)}
{/* Category Filter */}
{elements.category_filter && categories && categories.length > 0 && (
<div className="flex items-center gap-2">
<Filter className="h-4 w-4 text-muted-foreground" />
<select
value={category}
onChange={(e) => setCategory(e.target.value)}
className="px-4 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
>
<option value="">All Categories</option>
{categories.map((cat: any) => (
<option key={cat.id} value={cat.slug}>
{cat.name} ({cat.count})
</option>
))}
</select>
</div>
)}
{/* Sort Dropdown */}
{elements.sort_dropdown && (
<div className="flex items-center gap-2">
<select
value={sortBy}
onChange={(e) => setSortBy(e.target.value)}
className="px-4 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
>
<option value="">Default sorting</option>
<option value="popularity">Sort by popularity</option>
<option value="rating">Sort by average rating</option>
<option value="date">Sort by latest</option>
<option value="price">Sort by price: low to high</option>
<option value="price-desc">Sort by price: high to low</option>
</select>
</div>
)} )}
</div> </div>
)} )}
{/* Category Filter */} {/* Sort Dropdown (Rich Layout) */}
{elements.category_filter && categories && categories.length > 0 && ( {isRichSidebar && elements.sort_dropdown && (
<div className="flex items-center gap-2"> <div className="flex justify-end mb-6">
<Filter className="h-4 w-4 text-muted-foreground" />
<select
value={category}
onChange={(e) => setCategory(e.target.value)}
className="px-4 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
>
<option value="">All Categories</option>
{categories.map((cat: any) => (
<option key={cat.id} value={cat.slug}>
{cat.name} ({cat.count})
</option>
))}
</select>
</div>
)}
{/* Sort Dropdown */}
{elements.sort_dropdown && (
<div className="flex items-center gap-2">
<select <select
value={sortBy} value={sortBy}
onChange={(e) => setSortBy(e.target.value)} onChange={(e) => setSortBy(e.target.value)}
className="px-4 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-primary" className="px-4 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-primary text-sm"
> >
<option value="">Default sorting</option> <option value="">Default sorting</option>
<option value="popularity">Sort by popularity</option> <option value="popularity">Sort by popularity</option>
@@ -196,73 +348,94 @@ export default function Shop() {
</select> </select>
</div> </div>
)} )}
</div>
)}
{/* Products Grid */} {/* Products Grid */}
{productsLoading ? ( {productsLoading ? (
<div className={`grid ${gridColsClass} gap-6`}> <div className={`grid ${gridColsClass} gap-6`}>
{[...Array(8)].map((_, i) => ( {[...Array(8)].map((_, i) => (
<div key={i} className="animate-pulse"> <div key={i} className="animate-pulse">
<div className="bg-gray-200 aspect-square rounded-lg mb-4" /> <div className="bg-muted aspect-square rounded-lg mb-4" />
<div className="h-4 bg-gray-200 rounded mb-2" /> <div className="h-4 bg-muted rounded mb-2" />
<div className="h-4 bg-gray-200 rounded w-2/3" /> <div className="h-4 bg-muted rounded w-2/3" />
</div>
))}
</div> </div>
))} ) : productsData?.products && productsData.products.length > 0 ? (
</div> <>
) : productsData?.products && productsData.products.length > 0 ? ( {isMasonry ? (
<> <div className={`grid grid-cols-1 md:grid-cols-${gridCols.tablet || '3'} lg:grid-cols-${gridCols.desktop || '4'} gap-6`}>
<div className={isMasonry ? `${masonryColsClass} gap-6` : `grid ${gridColsClass} gap-6`}> {(() => {
{productsData.products.map((product: any) => ( const currentCols = parseInt(gridCols[breakpoint] || (breakpoint === 'mobile' ? '2' : breakpoint === 'tablet' ? '3' : '4'));
<div key={product.id} className={isMasonry ? 'mb-6 break-inside-avoid' : ''}> // Use a safe column count fallback (e.g. at least 1)
<ProductCard const cols = Math.max(1, currentCols);
product={product} const masonryColumns: any[][] = Array.from({ length: cols }, () => []);
onAddToCart={handleAddToCart} productsData.products.forEach((p: any, i: number) => {
/> masonryColumns[i % cols].push(p);
</div> });
))} return masonryColumns.map((col, colIndex) => (
</div> <div key={colIndex} className="flex flex-col gap-6">
{col.map((product) => (
<ProductCard key={product.id} product={product} onAddToCart={handleAddToCart} />
))}
</div>
));
})()}
</div>
) : (
<div className={`grid ${productsData.products.length < parseInt(gridCols.desktop || '4') ? `grid-cols-1 sm:grid-cols-2 lg:grid-cols-${productsData.products.length}` : gridColsClass} gap-6`}>
{productsData.products.map((product: any) => (
<div key={product.id}>
<ProductCard product={product} onAddToCart={handleAddToCart} />
</div>
))}
</div>
)}
{/* Pagination */} {/* Pagination */}
{productsData.total_pages > 1 && ( {productsData.total_pages > 1 && (
<div className="flex justify-center gap-2 mt-8"> <div className="flex justify-center gap-2 mt-8">
<Button <Button
variant="outline" variant="outline"
onClick={() => setPage(p => Math.max(1, p - 1))} onClick={() => setPage(p => Math.max(1, p - 1))}
disabled={page === 1} disabled={page === 1}
> >
Previous Previous
</Button> </Button>
<span className="flex items-center px-4"> <span className="flex items-center px-4">
Page {page} of {productsData.total_pages} Page {page} of {productsData.total_pages}
</span> </span>
<Button <Button
variant="outline" variant="outline"
onClick={() => setPage(p => Math.min(productsData.total_pages, p + 1))} onClick={() => setPage(p => Math.min(productsData.total_pages, p + 1))}
disabled={page === productsData.total_pages} disabled={page === productsData.total_pages}
> >
Next Next
</Button> </Button>
</div>
)}
</>
) : (
<div className="text-center py-12">
<p className="text-muted-foreground text-lg">No products found</p>
{!isRichSidebar && (search || category || minPrice || maxPrice) && (
<Button
variant="outline"
onClick={() => {
setSearch('');
setCategory('');
setMinPriceInput('');
setMaxPriceInput('');
setSortBy('');
}}
className="mt-4"
>
Clear Filters
</Button>
)}
</div> </div>
)} )}
</>
) : (
<div className="text-center py-12">
<p className="text-muted-foreground text-lg">No products found</p>
{(search || category) && (
<Button
variant="outline"
onClick={() => {
setSearch('');
setCategory('');
}}
className="mt-4"
>
Clear Filters
</Button>
)}
</div> </div>
)} </div>
</Container> </Container>
); );
} }

View File

@@ -2,6 +2,11 @@
module.exports = { module.exports = {
darkMode: ["class"], darkMode: ["class"],
content: ["./src/**/*.{ts,tsx,css}", "./components/**/*.{ts,tsx,css}"], content: ["./src/**/*.{ts,tsx,css}", "./components/**/*.{ts,tsx,css}"],
safelist: [
// Dynamic typography classes selected via Inspector Panel
'text-xs', 'text-sm', 'text-base', 'text-lg', 'text-xl', 'text-2xl', 'text-3xl', 'text-4xl', 'text-5xl', 'text-6xl',
'font-light', 'font-normal', 'font-medium', 'font-semibold', 'font-bold', 'font-extrabold'
],
theme: { theme: {
container: { center: true, padding: "1rem" }, container: { center: true, padding: "1rem" },
extend: { extend: {

View File

@@ -15,7 +15,7 @@
"types": [], "types": [],
"baseUrl": ".", "baseUrl": ".",
"paths": { "@/*": ["./src/*"] }, "paths": { "@/*": ["./src/*"] },
"ignoreDeprecations": "6.0" "ignoreDeprecations": "5.0"
}, },
"include": ["src"] "include": ["src"]
} }

View File

@@ -0,0 +1,166 @@
# Subscription Gateway Capabilities
> How WooNooW decides which payment gateways can auto-debit subscription
> renewals, and how merchants can override that decision.
## Why this exists
Before this system, a subscription renewal would attempt to call
`$gateway->process_subscription_renewal_payment($order, $subscription)` if
the gateway *happened* to implement that method. That had three problems:
1. **Capability was invisible** — the merchant had no way to see, declare,
or override which gateways supported subscription auto-renew.
2. **The default was unsafe** — a gateway without the method silently fell
through to manual payment. The system "worked," but the merchant
believed auto-debit was happening and customers were surprised when
they had to log in and pay manually.
3. **No override was possible** — a merchant running a custom Stripe
wrapper that *does* support auto-debit could not declare it, and a
merchant using stock Stripe could not opt out.
## What it is now
A **per-gateway capability table** that the merchant (or a WooNooW
defaults policy) controls explicitly. The system consults the table at
renewal time and decides whether to attempt auto-debit or fall through
to manual. PHP method existence alone is no longer authoritative.
### Storage
```
wp_option('woonoow_gateway_subscription_capabilities', [
'<gateway_id>' => [ 'subscription_auto_renew' => bool ],
...
])
```
### Decision flow
For a renewal where the subscription's stored `payment_method` is
`<gateway_id>`:
1. If the site-level `force_manual_renewal` setting is on, fall through
to manual. (Kill switch — see below.)
2. Look up `<gateway_id>` in the merged capability map (defaults <
stored overrides < `woonoow_gateway_subscription_capabilities` filter).
3. If the lookup returns `subscription_auto_renew = true`, attempt
auto-debit via the gateway's `process_subscription_renewal_payment`
method. On success, run `handle_renewal_success`. On failure, fall
through to manual and notify the customer.
4. If the lookup is missing or false, skip auto-debit entirely, create a
manual renewal order, and send the `renewal_payment_due` email.
The decision is made by
`WooNooW\Modules\Subscription\GatewayCapabilities::should_attempt_auto_renew($gateway_id)`.
## Built-in defaults
| Gateway ID | Default auto-renew | Why |
|---------------------|--------------------|-----|
| `paypal` | true | PayPal Reference Transactions supports recurring |
| `stripe` | true | With a WooNooW Stripe adapter implementing the contract |
| `stripe_cc` | true | Alias for stripe credit card |
| `stripe_sepa` | true | SEPA Direct Debit supports recurring |
| `dodo` | true | Dodo Payments supports recurring subscriptions |
| `tripay` | false | VA/QRIS/e-wallet — no recurring |
| `midtrans` | false | VA/QRIS/e-wallet — no recurring |
| `xendit` | false | Indonesian credit card requires customer re-auth (BI/PCI-DSS) |
| `doku` | false | Indonesian manual-only |
| `duitku` | false | Indonesian manual-only |
| `cheque`, `bacs`, `cod` | false | Offline / no auto-debit |
| **any unknown** | false | Safe default |
The default for any unknown gateway is `false`. A merchant who has a
custom adapter for an unknown gateway can flip the toggle in the admin
UI (Settings → Modules → Subscription → Gateway Auto-Renew Capabilities).
## Why per-gateway, not site-level "billing mode"
A site-level "manual vs auto" toggle asks the merchant to understand a
concept that does not exist in their head. The merchant thinks in
**payment gateways**. A checkbox next to each gateway in the admin is
data the merchant already knows.
Additionally:
- Different merchants use different gateways. A site-level toggle forces
a single behavior even when the merchant runs two gateways (one
auto-capable, one not) for different products.
- The capability is a property of the **integration**, not of the
**store**. The merchant did not choose "manual mode" — they chose
Tripay, and Tripay is a manual gateway.
- The capability can change as WooNooW ships new adapters. A
per-gateway table updates as adapters ship.
## Site-level kill switch
There is one site-level override:
- `force_manual_renewal` (default **off**) — when on, all renewals are
manual regardless of the per-gateway capability table. Useful as a
kill switch during an incident or regulatory change.
This lives in the standard module settings form (Settings → Modules →
Subscription) and is not on the gateway capability matrix screen.
## Admin UI
`Settings → Modules → Subscription` now has two sections:
1. **Configuration** — the standard 12-field schema (button text,
pause/cancel permissions, retry policy, kill switch, etc.). Driven
by the existing `SubscriptionSettings` schema.
2. **Gateway Auto-Renew Capabilities** — one row per WooCommerce
payment gateway with a per-gateway toggle. Built dynamically from
`WC()->payment_gateways()`. The merchant can flip a gateway on or
off, and the change is persisted via
`POST /woonoow/v1/subscriptions/gateway-capabilities`.
When the kill switch is on, every row shows a "Forced manual" badge and
the per-gateway toggles are disabled.
## Customer messaging
The order-pay response (`/checkout/order/{id}`) and the subscription
detail response both include `gateway_supports_auto_renew`. The
customer-spa OrderPay page renders a different callout for manual
gateways (amber) versus auto-renew gateways (blue):
- **Auto-renew:** "Your subscription will renew automatically on the
date shown below."
- **Manual:** "Your saved payment method cannot be charged
automatically for this gateway, so please complete the payment to
continue your subscription."
This ensures the customer is never promised auto-debit that the system
will not deliver.
## Extending the table (for gateway adapter authors)
A gateway adapter or third-party plugin can extend the capability
table at boot time via the
`woonoow_gateway_subscription_capabilities` filter:
```php
add_filter('woonoow_gateway_subscription_capabilities', function ($caps) {
$caps['my_custom_stripe'] = ['subscription_auto_renew' => true];
return $caps;
});
```
The adapter is then responsible for implementing
`process_subscription_renewal_payment(WC_Order $order, $subscription)`
on its gateway class. If the method does not exist, the capability
declaration is meaningless — the renewal will fall through to manual.
## Migration / no migration
This is a behavioral improvement, not a schema change. Existing
subscriptions keep their `payment_method` value. The capability table
is consulted at renewal time, not retroactively.
If a merchant upgrades WooNooW and previously relied on PHP method
existence alone, the renewal will continue to work — but the merchant
will now see the capability matrix and can confirm or override each
gateway.

View File

@@ -356,6 +356,7 @@ class AppearanceController
'card_style' => sanitize_text_field($data['layout']['card_style'] ?? 'card'), 'card_style' => sanitize_text_field($data['layout']['card_style'] ?? 'card'),
'aspect_ratio' => sanitize_text_field($data['layout']['aspect_ratio'] ?? 'square'), 'aspect_ratio' => sanitize_text_field($data['layout']['aspect_ratio'] ?? 'square'),
'card_text_align' => sanitize_text_field($data['layout']['card_text_align'] ?? 'left'), 'card_text_align' => sanitize_text_field($data['layout']['card_text_align'] ?? 'left'),
'filter_layout' => sanitize_text_field($data['layout']['filter_layout'] ?? 'basic'),
], ],
'elements' => [ 'elements' => [
'category_filter' => (bool) ($data['elements']['category_filter'] ?? true), 'category_filter' => (bool) ($data['elements']['category_filter'] ?? true),
@@ -588,6 +589,7 @@ class AppearanceController
'grid_columns' => '3', 'grid_columns' => '3',
'card_style' => 'card', 'card_style' => 'card',
'aspect_ratio' => 'square', 'aspect_ratio' => 'square',
'filter_layout' => 'basic',
], ],
'elements' => [ 'elements' => [
'category_filter' => true, 'category_filter' => true,

View File

@@ -288,6 +288,12 @@ class CheckoutController
'next_payment_date' => $sub->next_payment_date, 'next_payment_date' => $sub->next_payment_date,
'end_date' => $sub->end_date, 'end_date' => $sub->end_date,
'recurring_amount' => (float) $sub->recurring_amount, 'recurring_amount' => (float) $sub->recurring_amount,
// §9 — Renewal messaging. The order-pay page can choose between
// "auto-renew enabled" and "manual renewal only" copy.
'payment_method' => $sub->payment_method,
'gateway_supports_auto_renew' => !empty($sub->payment_method)
? \WooNooW\Modules\Subscription\GatewayCapabilities::should_attempt_auto_renew($sub->payment_method)
: false,
]; ];
} }
@@ -324,7 +330,9 @@ class CheckoutController
} }
// Create order // Create order
$order = wc_create_order(); $order = wc_create_order([
'created_via' => 'checkout'
]);
if (is_wp_error($order)) { if (is_wp_error($order)) {
return ['error' => $order->get_error_message()]; return ['error' => $order->get_error_message()];
} }
@@ -530,6 +538,9 @@ class CheckoutController
header('Server-Timing: app;dur=' . round((microtime(true) - $__t0) * 1000, 1)); header('Server-Timing: app;dur=' . round((microtime(true) - $__t0) * 1000, 1));
} }
// Auto-save checkout addresses to user account
$this->auto_save_checkout_addresses($order, $payload);
// Clear WooCommerce cart after successful order placement // Clear WooCommerce cart after successful order placement
// This ensures the cart page won't re-populate from server session // This ensures the cart page won't re-populate from server session
if (function_exists('WC') && WC()->cart) { if (function_exists('WC') && WC()->cart) {
@@ -1133,4 +1144,105 @@ class CheckoutController
} }
return $results; return $results;
} }
/**
* Auto-save checkout addresses to the user's address book if they are new.
*/
private function auto_save_checkout_addresses(\WC_Order $order, array $payload): void
{
$user_id = $order->get_customer_id();
if (!$user_id) {
return;
}
$addresses = get_user_meta($user_id, 'woonoow_addresses', true);
if (!is_array($addresses)) {
$addresses = [];
}
// Helper to check if address matches existing
$is_duplicate = function ($new_addr, $type) use ($addresses) {
foreach ($addresses as $addr) {
if ($addr['type'] !== $type && $addr['type'] !== 'both') {
continue;
}
// Compare essential fields
$match = true;
$check_fields = ['first_name', 'last_name', 'address_1', 'city', 'country'];
foreach ($check_fields as $f) {
$v1 = trim(strtolower((string)($addr[$f] ?? '')));
$v2 = trim(strtolower((string)($new_addr[$f] ?? '')));
if ($v1 !== $v2) {
$match = false;
break;
}
}
if ($match) return true;
}
return false;
};
// Helper to build address array
$build_address = function ($type, $data, $custom_fields, $addresses) {
$new_id = empty($addresses) ? 1 : max(array_column($addresses, 'id')) + 1;
$addr = [
'id' => $new_id,
'label' => ucfirst($type) . ' ' . $new_id,
'type' => $type,
'is_default' => empty($addresses), // default if it's the first one
];
$standard_fields = ['first_name', 'last_name', 'company', 'address_1', 'address_2', 'city', 'state', 'postcode', 'country', 'email', 'phone'];
foreach ($standard_fields as $f) {
if (isset($data[$f])) {
$addr[$f] = sanitize_text_field($data[$f]);
}
}
// Add custom fields matching prefix
if (is_array($custom_fields)) {
foreach ($custom_fields as $k => $v) {
if (strpos($k, $type . '_') === 0) {
$addr[$k] = sanitize_text_field($v);
} elseif (!isset($addr[$type . '_' . $k]) && !isset($addr[$k])) {
// Some custom fields might not have the prefix if they apply to both
// Or they are sent without prefix by frontend in payload[type]
}
}
}
// Also, payload[type] can contain custom fields directly because frontend sends them without prefix!
foreach ($data as $k => $v) {
if (!in_array($k, $standard_fields) && !in_array($k, ['ship_to_different'])) {
$addr[$type . '_' . $k] = sanitize_text_field($v);
}
}
return $addr;
};
$changed = false;
// Check billing
if (!empty($payload['billing'])) {
if (!$is_duplicate($payload['billing'], 'billing')) {
$billing_addr = $build_address('billing', $payload['billing'], $payload['custom_fields'] ?? [], $addresses);
$addresses[] = $billing_addr;
$changed = true;
}
}
// Check shipping
$ship_to_different = !empty($payload['shipping']['ship_to_different']);
if ($ship_to_different && !empty($payload['shipping'])) {
if (!$is_duplicate($payload['shipping'], 'shipping')) {
$shipping_addr = $build_address('shipping', $payload['shipping'], $payload['custom_fields'] ?? [], $addresses);
$addresses[] = $shipping_addr;
$changed = true;
}
}
if ($changed) {
update_user_meta($user_id, 'woonoow_addresses', array_values($addresses));
}
}
} }

View File

@@ -5,6 +5,7 @@ namespace WooNooW\Api\Controllers;
use WP_REST_Request; use WP_REST_Request;
use WP_REST_Response; use WP_REST_Response;
use WP_REST_Server; use WP_REST_Server;
use WooNooW\Modules\Affiliate\AffiliateSettings;
class AffiliateCustomerController class AffiliateCustomerController
{ {
@@ -47,6 +48,33 @@ class AffiliateCustomerController
'callback' => [$this, 'update_payment_details'], 'callback' => [$this, 'update_payment_details'],
'permission_callback' => [$this, 'check_permission'], 'permission_callback' => [$this, 'check_permission'],
]); ]);
// Affiliate Collections
register_rest_route($this->namespace, '/account/affiliate/collections', [
[
'methods' => WP_REST_Server::READABLE,
'callback' => [$this, 'get_collections'],
'permission_callback' => [$this, 'check_permission'],
],
[
'methods' => WP_REST_Server::CREATABLE,
'callback' => [$this, 'create_collection'],
'permission_callback' => [$this, 'check_permission'],
]
]);
register_rest_route($this->namespace, '/account/affiliate/collections/(?P<id>\d+)', [
[
'methods' => WP_REST_Server::EDITABLE,
'callback' => [$this, 'update_collection'],
'permission_callback' => [$this, 'check_permission'],
],
[
'methods' => WP_REST_Server::DELETABLE,
'callback' => [$this, 'delete_collection'],
'permission_callback' => [$this, 'check_permission'],
]
]);
} }
public function check_permission() public function check_permission()
@@ -74,8 +102,26 @@ class AffiliateCustomerController
? (float) $affiliate['custom_commission_rate'] ? (float) $affiliate['custom_commission_rate']
: $global_rate; : $global_rate;
$referrals_table = $wpdb->prefix . 'woonoow_referrals';
$earnings = $wpdb->get_row($wpdb->prepare(
"SELECT
SUM(CASE WHEN status = 'approved' THEN commission_amount ELSE 0 END) as total_earnings,
SUM(CASE WHEN status = 'pending' THEN commission_amount ELSE 0 END) as pending_earnings
FROM $referrals_table
WHERE affiliate_id = %d",
$affiliate['id']
));
$affiliate['global_commission_rate'] = $global_rate; $affiliate['global_commission_rate'] = $global_rate;
$affiliate['commission_rate'] = $effective_rate; $affiliate['commission_rate'] = $effective_rate;
$affiliate['total_earnings'] = $earnings->total_earnings ?: 0;
$affiliate['pending_earnings'] = $earnings->pending_earnings ?: 0;
if (class_exists('\WooNooW\Modules\Affiliate\AffiliateSettings')) {
$affiliate['collections_enabled'] = \WooNooW\Modules\Affiliate\AffiliateSettings::get_setting('woonoow_affiliate_enable_curated_collections', true);
} else {
$affiliate['collections_enabled'] = true;
}
return rest_ensure_response($affiliate); return rest_ensure_response($affiliate);
} }
@@ -136,16 +182,51 @@ class AffiliateCustomerController
return rest_ensure_response([]); return rest_ensure_response([]);
} }
$referrals = $wpdb->get_results($wpdb->prepare( $limit = (int) $request->get_param('limit');
"SELECT r.*, $page = max(1, (int) $request->get_param('page'));
$order_id = $request->get_param('order_id') ? (int) $request->get_param('order_id') : null;
$where = $wpdb->prepare("WHERE r.affiliate_id = %d", $affiliate->id);
if ($order_id) {
$where .= $wpdb->prepare(" AND r.order_id = %d", $order_id);
}
$sql = "SELECT r.*,
COALESCE(NULLIF(r.cancelled_reason, ''), NULL) as cancelled_reason, COALESCE(NULLIF(r.cancelled_reason, ''), NULL) as cancelled_reason,
COALESCE(r.approved_at, r.created_at) as approved_at COALESCE(r.approved_at, r.created_at) as approved_at
FROM $referrals_table r FROM $referrals_table r
WHERE r.affiliate_id = %d $where
ORDER BY r.created_at DESC", ORDER BY r.created_at DESC";
$affiliate->id
), ARRAY_A); if ($limit > 0) {
return rest_ensure_response($referrals); $offset = ($page - 1) * $limit;
$sql .= $wpdb->prepare(" LIMIT %d OFFSET %d", $limit, $offset);
}
$referrals = $wpdb->get_results($sql, ARRAY_A);
$total = $wpdb->get_var("SELECT COUNT(r.id) FROM $referrals_table r $where");
// Attach customer data if enabled
if (!empty($referrals) && AffiliateSettings::get_setting('woonoow_affiliate_share_customer_data', false)) {
foreach ($referrals as &$ref) {
if (!empty($ref['order_id'])) {
$order = wc_get_order($ref['order_id']);
if ($order) {
$ref['customer_name'] = trim($order->get_billing_first_name() . ' ' . $order->get_billing_last_name());
$ref['customer_email'] = $order->get_billing_email();
}
}
}
}
return rest_ensure_response([
'referrals' => $referrals,
'total' => (int) $total,
'page' => $page,
'limit' => $limit > 0 ? $limit : (int) $total,
'total_pages' => $limit > 0 ? ceil($total / $limit) : 1
]);
} }
public function get_payouts(WP_REST_Request $request) public function get_payouts(WP_REST_Request $request)
@@ -270,4 +351,125 @@ class AffiliateCustomerController
return $sanitized; return $sanitized;
} }
// --- Collections ---
public function get_collections(WP_REST_Request $request)
{
if (class_exists('\WooNooW\Modules\Affiliate\AffiliateSettings') && !\WooNooW\Modules\Affiliate\AffiliateSettings::get_setting('woonoow_affiliate_enable_curated_collections', true)) {
return new \WP_Error('rest_forbidden', 'Curated collections are disabled.', ['status' => 403]);
}
global $wpdb;
$user_id = get_current_user_id();
$affiliate_table = $wpdb->prefix . 'woonoow_affiliates';
$collections_table = $wpdb->prefix . 'woonoow_affiliate_collections';
$affiliate = $wpdb->get_row($wpdb->prepare("SELECT id, referral_code FROM $affiliate_table WHERE user_id = %d", $user_id));
if (!$affiliate) {
return rest_ensure_response([]);
}
$collections = $wpdb->get_results($wpdb->prepare("SELECT * FROM $collections_table WHERE affiliate_id = %d ORDER BY created_at DESC", $affiliate->id), ARRAY_A);
foreach ($collections as &$collection) {
$collection['product_ids'] = $collection['product_ids'] ? json_decode($collection['product_ids'], true) : [];
$collection['link'] = site_url("/collection/{$collection['slug']}");
}
return rest_ensure_response($collections);
}
public function create_collection(WP_REST_Request $request)
{
global $wpdb;
$user_id = get_current_user_id();
$affiliate_table = $wpdb->prefix . 'woonoow_affiliates';
$collections_table = $wpdb->prefix . 'woonoow_affiliate_collections';
$affiliate = $wpdb->get_row($wpdb->prepare("SELECT id FROM $affiliate_table WHERE user_id = %d", $user_id));
if (!$affiliate) {
return new \WP_Error('not_found', 'Affiliate profile not found', ['status' => 404]);
}
$title = sanitize_text_field($request->get_param('title'));
$description = sanitize_textarea_field($request->get_param('description'));
$product_ids = $request->get_param('product_ids');
if (!is_array($product_ids)) $product_ids = [];
$product_ids = array_map('intval', $product_ids);
if (count($product_ids) > 20) {
return new \WP_Error('too_many_products', 'A collection can have a maximum of 20 products.', ['status' => 400]);
}
$slug = sanitize_title($title);
// Check unique slug for this affiliate
$existing = $wpdb->get_var($wpdb->prepare("SELECT id FROM $collections_table WHERE affiliate_id = %d AND slug = %s", $affiliate->id, $slug));
if ($existing) {
$slug .= '-' . wp_generate_password(4, false);
}
$data = [
'affiliate_id' => $affiliate->id,
'title' => $title,
'slug' => $slug,
'description' => $description,
'product_ids' => json_encode($product_ids)
];
$wpdb->insert($collections_table, $data);
$data['id'] = $wpdb->insert_id;
$data['product_ids'] = $product_ids;
return rest_ensure_response($data);
}
public function update_collection(WP_REST_Request $request)
{
global $wpdb;
$user_id = get_current_user_id();
$id = (int) $request->get_param('id');
$affiliate_table = $wpdb->prefix . 'woonoow_affiliates';
$collections_table = $wpdb->prefix . 'woonoow_affiliate_collections';
$affiliate = $wpdb->get_row($wpdb->prepare("SELECT id FROM $affiliate_table WHERE user_id = %d", $user_id));
if (!$affiliate) return new \WP_Error('unauthorized', 'Unauthorized', ['status' => 401]);
$collection = $wpdb->get_row($wpdb->prepare("SELECT id FROM $collections_table WHERE id = %d AND affiliate_id = %d", $id, $affiliate->id));
if (!$collection) return new \WP_Error('not_found', 'Collection not found', ['status' => 404]);
$title = sanitize_text_field($request->get_param('title'));
$description = sanitize_textarea_field($request->get_param('description'));
$product_ids = $request->get_param('product_ids');
if (!is_array($product_ids)) $product_ids = [];
$product_ids = array_map('intval', $product_ids);
if (count($product_ids) > 20) {
return new \WP_Error('too_many_products', 'A collection can have a maximum of 20 products.', ['status' => 400]);
}
$wpdb->update($collections_table, [
'title' => $title,
'description' => $description,
'product_ids' => json_encode($product_ids)
], ['id' => $id]);
return rest_ensure_response(['success' => true]);
}
public function delete_collection(WP_REST_Request $request)
{
global $wpdb;
$user_id = get_current_user_id();
$id = (int) $request->get_param('id');
$affiliate_table = $wpdb->prefix . 'woonoow_affiliates';
$collections_table = $wpdb->prefix . 'woonoow_affiliate_collections';
$affiliate = $wpdb->get_row($wpdb->prepare("SELECT id FROM $affiliate_table WHERE user_id = %d", $user_id));
if (!$affiliate) return new \WP_Error('unauthorized', 'Unauthorized', ['status' => 401]);
$wpdb->delete($collections_table, ['id' => $id, 'affiliate_id' => $affiliate->id]);
return rest_ensure_response(['success' => true]);
}
} }

View File

@@ -38,6 +38,13 @@ class PagesController
'permission_callback' => '__return_true', 'permission_callback' => '__return_true',
]); ]);
// Proxy section form submission (e.g. Contact Form webhooks) (Must be before generic slug route)
register_rest_route($namespace, '/pages/submit-section-form', [
'methods' => 'POST',
'callback' => [__CLASS__, 'submit_section_form'],
'permission_callback' => '__return_true', // Public endpoint
]);
// Get/Save page structure (structural pages) // Get/Save page structure (structural pages)
register_rest_route($namespace, '/pages/(?P<slug>[a-zA-Z0-9_-]+)', [ register_rest_route($namespace, '/pages/(?P<slug>[a-zA-Z0-9_-]+)', [
[ [
@@ -446,11 +453,15 @@ class PagesController
$rendered_sections = self::resolve_sections_for_post($template['sections'], $post, $type); $rendered_sections = self::resolve_sections_for_post($template['sections'], $post, $type);
} }
// Get SPA settings
$settings = get_option('woonoow_appearance_settings', []);
return new WP_REST_Response([ return new WP_REST_Response([
'type' => 'content', 'type' => 'content',
'cpt' => $type, 'cpt' => $type,
'post' => $post_data, 'post' => $post_data,
'seo' => $seo, 'seo' => $seo,
'effective_container_width' => ($settings['general']['container_width'] ?? 'boxed') ?: 'boxed',
'template' => $template ?: ['sections' => []], 'template' => $template ?: ['sections' => []],
'rendered' => [ 'rendered' => [
'sections' => $rendered_sections, 'sections' => $rendered_sections,
@@ -662,6 +673,80 @@ class PagesController
], 200); ], 200);
} }
/**
* Proxy form submission for a specific section (e.g. Contact Form to Webhook)
*/
public static function submit_section_form(WP_REST_Request $request)
{
$body = $request->get_json_params();
$source_type = sanitize_text_field($body['source_type'] ?? 'page');
$source_id = sanitize_text_field($body['source_id'] ?? '');
$section_id = sanitize_text_field($body['section_id'] ?? '');
$form_data = $body['form_data'] ?? [];
if (empty($source_id) || empty($section_id)) {
return new WP_Error('invalid_params', 'Missing required parameters', ['status' => 400]);
}
$structure = null;
if ($source_type === 'template') {
$template = get_option("wn_template_{$source_id}", null);
if ($template) {
$structure = $template;
}
} else {
// It's a page
$page = get_post($source_id);
if ($page) {
$structure = get_post_meta($page->ID, '_wn_page_structure', true);
}
}
if (empty($structure) || empty($structure['sections'])) {
return new WP_Error('not_found', 'Structure not found', ['status' => 404]);
}
// Find the section
$section = null;
foreach ($structure['sections'] as $s) {
if ($s['id'] === $section_id) {
$section = $s;
break;
}
}
if (!$section) {
return new WP_Error('not_found', 'Section not found', ['status' => 404]);
}
$webhook_url = $section['props']['webhook_url']['value'] ?? null;
if (empty($webhook_url)) {
return new WP_Error('invalid_config', 'Webhook URL not configured', ['status' => 400]);
}
// Send to webhook
$response = wp_remote_post($webhook_url, [
'body' => wp_json_encode($form_data),
'headers' => [
'Content-Type' => 'application/json',
],
'timeout' => 15,
'data_format' => 'body'
]);
if (is_wp_error($response)) {
return new WP_Error('webhook_failed', 'Failed to contact webhook: ' . $response->get_error_message(), ['status' => 502]);
}
$code = wp_remote_retrieve_response_code($response);
if ($code >= 400) {
return new WP_Error('webhook_error', 'Webhook returned error code: ' . $code, ['status' => 502]);
}
return new WP_REST_Response(['success' => true], 200);
}
// ======================================== // ========================================
// Helper Methods // Helper Methods
// ======================================== // ========================================

View File

@@ -220,6 +220,7 @@ class ProductsController
$category = $request->get_param('category'); $category = $request->get_param('category');
$type = $request->get_param('type'); $type = $request->get_param('type');
$stock_status = $request->get_param('stock_status'); $stock_status = $request->get_param('stock_status');
$software_enabled = $request->get_param('software_enabled');
$orderby = $request->get_param('orderby') ?: 'date'; $orderby = $request->get_param('orderby') ?: 'date';
$order = $request->get_param('order') ?: 'DESC'; $order = $request->get_param('order') ?: 'DESC';
@@ -266,11 +267,19 @@ class ProductsController
// Stock status filter // Stock status filter
if ($stock_status) { if ($stock_status) {
$args['meta_query'] = [ $args['meta_query'] = $args['meta_query'] ?? [];
[ $args['meta_query'][] = [
'key' => '_stock_status', 'key' => '_stock_status',
'value' => $stock_status, 'value' => $stock_status,
], ];
}
// Software enabled filter
if ($software_enabled === 'true' || $software_enabled === '1') {
$args['meta_query'] = $args['meta_query'] ?? [];
$args['meta_query'][] = [
'key' => '_woonoow_software_enabled',
'value' => 'yes',
]; ];
} }
@@ -660,6 +669,26 @@ class ProductsController
update_post_meta($product->get_id(), '_woonoow_affiliate_commission_rate', self::sanitize_number($data['affiliate_commission_rate'])); update_post_meta($product->get_id(), '_woonoow_affiliate_commission_rate', self::sanitize_number($data['affiliate_commission_rate']));
} }
// Software meta
if (isset($data['software_enabled'])) {
update_post_meta($product->get_id(), '_woonoow_software_enabled', $data['software_enabled'] ? 'yes' : 'no');
}
if (isset($data['software_slug'])) {
update_post_meta($product->get_id(), '_woonoow_software_slug', sanitize_title($data['software_slug']));
}
if (isset($data['software_wp_enabled'])) {
update_post_meta($product->get_id(), '_woonoow_software_wp_enabled', $data['software_wp_enabled'] ? 'yes' : 'no');
}
if (isset($data['software_requires_wp'])) {
update_post_meta($product->get_id(), '_woonoow_software_requires_wp', sanitize_text_field($data['software_requires_wp']));
}
if (isset($data['software_tested_wp'])) {
update_post_meta($product->get_id(), '_woonoow_software_tested_wp', sanitize_text_field($data['software_tested_wp']));
}
if (isset($data['software_requires_php'])) {
update_post_meta($product->get_id(), '_woonoow_software_requires_php', sanitize_text_field($data['software_requires_php']));
}
// Allow plugins to perform additional updates (Level 1 compatibility) // Allow plugins to perform additional updates (Level 1 compatibility)
do_action('woonoow/product_updated', $product, $data, $request); do_action('woonoow/product_updated', $product, $data, $request);
@@ -819,6 +848,10 @@ class ProductsController
'permalink' => get_permalink($product->get_id()), 'permalink' => get_permalink($product->get_id()),
'date_created' => $product->get_date_created() ? $product->get_date_created()->date('Y-m-d H:i:s') : '', 'date_created' => $product->get_date_created() ? $product->get_date_created()->date('Y-m-d H:i:s') : '',
'date_modified' => $product->get_date_modified() ? $product->get_date_modified()->date('Y-m-d H:i:s') : '', 'date_modified' => $product->get_date_modified() ? $product->get_date_modified()->date('Y-m-d H:i:s') : '',
'software_enabled' => get_post_meta($product->get_id(), '_woonoow_software_enabled', true) === 'yes',
'software_slug' => get_post_meta($product->get_id(), '_woonoow_software_slug', true),
'software_current_version' => get_post_meta($product->get_id(), '_woonoow_software_current_version', true),
'software_wp_enabled' => get_post_meta($product->get_id(), '_woonoow_software_wp_enabled', true) === 'yes',
]; ];
} }
@@ -877,6 +910,14 @@ class ProductsController
$data['affiliate_enabled'] = get_post_meta($product->get_id(), '_woonoow_affiliate_enabled', true) === 'yes'; $data['affiliate_enabled'] = get_post_meta($product->get_id(), '_woonoow_affiliate_enabled', true) === 'yes';
$data['affiliate_commission_rate'] = get_post_meta($product->get_id(), '_woonoow_affiliate_commission_rate', true) ?: ''; $data['affiliate_commission_rate'] = get_post_meta($product->get_id(), '_woonoow_affiliate_commission_rate', true) ?: '';
// Software fields
$data['software_enabled'] = get_post_meta($product->get_id(), '_woonoow_software_enabled', true) === 'yes';
$data['software_slug'] = get_post_meta($product->get_id(), '_woonoow_software_slug', true) ?: '';
$data['software_wp_enabled'] = get_post_meta($product->get_id(), '_woonoow_software_wp_enabled', true) === 'yes';
$data['software_requires_wp'] = get_post_meta($product->get_id(), '_woonoow_software_requires_wp', true) ?: '';
$data['software_tested_wp'] = get_post_meta($product->get_id(), '_woonoow_software_tested_wp', true) ?: '';
$data['software_requires_php'] = get_post_meta($product->get_id(), '_woonoow_software_requires_php', true) ?: '';
// Images array (URLs) for frontend - featured + gallery // Images array (URLs) for frontend - featured + gallery
$images = []; $images = [];
$featured_image_id = $product->get_image_id(); $featured_image_id = $product->get_image_id();
@@ -1078,6 +1119,10 @@ class ProductsController
'image_url' => $image_url, 'image_url' => $image_url,
'image' => $image_url, // For form compatibility 'image' => $image_url, // For form compatibility
'license_duration_days' => get_post_meta($variation->get_id(), '_license_duration_days', true) ?: '', 'license_duration_days' => get_post_meta($variation->get_id(), '_license_duration_days', true) ?: '',
'subscription_signup_fee' => get_post_meta($variation->get_id(), '_woonoow_subscription_signup_fee', true) ?: '',
'subscription_trial_days' => get_post_meta($variation->get_id(), '_woonoow_subscription_trial_days', true) ?: '',
'subscription_period' => get_post_meta($variation->get_id(), '_woonoow_subscription_period', true) ?: '',
'subscription_interval' => get_post_meta($variation->get_id(), '_woonoow_subscription_interval', true) ?: '',
]; ];
} }
} }
@@ -1214,6 +1259,20 @@ class ProductsController
update_post_meta($saved_id, '_license_duration_days', self::sanitize_number($var_data['license_duration_days'])); update_post_meta($saved_id, '_license_duration_days', self::sanitize_number($var_data['license_duration_days']));
} }
// Save variation-level subscription fields
if (isset($var_data['subscription_signup_fee'])) {
update_post_meta($saved_id, '_woonoow_subscription_signup_fee', self::sanitize_number($var_data['subscription_signup_fee']));
}
if (isset($var_data['subscription_trial_days'])) {
update_post_meta($saved_id, '_woonoow_subscription_trial_days', absint($var_data['subscription_trial_days']));
}
if (isset($var_data['subscription_period'])) {
update_post_meta($saved_id, '_woonoow_subscription_period', sanitize_key($var_data['subscription_period']));
}
if (isset($var_data['subscription_interval'])) {
update_post_meta($saved_id, '_woonoow_subscription_interval', absint($var_data['subscription_interval']));
}
// Manually save attributes using direct database insert // Manually save attributes using direct database insert
if (!empty($wc_attributes)) { if (!empty($wc_attributes)) {
global $wpdb; global $wpdb;

View File

@@ -90,6 +90,15 @@ class SoftwareController
return current_user_can('manage_woocommerce'); return current_user_can('manage_woocommerce');
}, },
]); ]);
// Edit version
register_rest_route($namespace, '/software/products/(?P<product_id>\d+)/versions/(?P<version_id>\d+)', [
'methods' => 'PUT',
'callback' => [__CLASS__, 'edit_version'],
'permission_callback' => function () {
return current_user_can('manage_woocommerce');
},
]);
} }
/** /**
@@ -127,7 +136,7 @@ class SoftwareController
// Log the check (optional - for analytics) // Log the check (optional - for analytics)
do_action('woonoow/software/update_check', $slug, $current_version, $site_url, $license_key); do_action('woonoow/software/update_check', $slug, $current_version, $site_url, $license_key);
$result = SoftwareManager::check_update($license_key, $slug, $current_version); $result = SoftwareManager::check_update($license_key, $slug, $current_version, $site_url);
$status_code = isset($result['success']) && $result['success'] === false ? 400 : 200; $status_code = isset($result['success']) && $result['success'] === false ? 400 : 200;
@@ -242,7 +251,7 @@ class SoftwareController
return [ return [
'version' => $v['version'], 'version' => $v['version'],
'release_date' => $v['release_date'], 'release_date' => $v['release_date'],
'changelog' => $v['changelog'], 'changelog' => is_string($v['changelog']) && strpos(trim($v['changelog']), '{') === 0 ? json_decode($v['changelog'], true) : $v['changelog'],
'download_count' => (int) $v['download_count'], 'download_count' => (int) $v['download_count'],
]; ];
}, $versions), }, $versions),
@@ -283,8 +292,29 @@ class SoftwareController
$params = $request->get_json_params(); $params = $request->get_json_params();
$version = sanitize_text_field($params['version'] ?? ''); $version = sanitize_text_field($params['version'] ?? '');
$changelog = wp_kses_post($params['changelog'] ?? '');
$set_current = (bool) ($params['set_current'] ?? true); $set_current = (bool) ($params['set_current'] ?? true);
$raw_changelog = $params['changelog'] ?? [];
$changelog_data = [];
if (is_array($raw_changelog)) {
$changelog_data = [
'narrative' => wp_kses_post($raw_changelog['narrative'] ?? ''),
'points' => []
];
if (isset($raw_changelog['points']) && is_array($raw_changelog['points'])) {
foreach ($raw_changelog['points'] as $pt) {
if (isset($pt['type']) && isset($pt['text'])) {
$changelog_data['points'][] = [
'type' => sanitize_text_field($pt['type']),
'text' => sanitize_text_field($pt['text']),
];
}
}
}
} else {
$changelog_data = ['narrative' => sanitize_textarea_field($raw_changelog), 'points' => []];
}
$changelog = wp_json_encode($changelog_data);
if (empty($version)) { if (empty($version)) {
return new WP_REST_Response([ return new WP_REST_Response([
@@ -318,4 +348,62 @@ class SoftwareController
'message' => __('Version added successfully', 'woonoow'), 'message' => __('Version added successfully', 'woonoow'),
], 201); ], 201);
} }
/**
* Edit an existing version
*/
public static function edit_version(WP_REST_Request $request)
{
$product_id = $request->get_param('product_id');
$version_id = $request->get_param('version_id');
$version = sanitize_text_field($request->get_param('version'));
$changelog = $request->get_param('changelog');
$set_current = filter_var($request->get_param('set_current'), FILTER_VALIDATE_BOOLEAN);
// If changelog is an array/object, encode it to JSON
if (is_array($changelog) || is_object($changelog)) {
if (isset($changelog['narrative'])) {
$changelog['narrative'] = sanitize_textarea_field($changelog['narrative']);
}
if (isset($changelog['points']) && is_array($changelog['points'])) {
foreach ($changelog['points'] as &$point) {
$point['type'] = sanitize_text_field($point['type'] ?? '');
$point['text'] = sanitize_text_field($point['text'] ?? '');
}
}
$changelog = wp_json_encode($changelog);
} else {
$changelog = wp_kses_post($changelog);
}
if (empty($version)) {
return new WP_REST_Response([
'success' => false,
'error' => 'missing_version',
'message' => __('Version number is required', 'woonoow'),
], 400);
}
$product = wc_get_product($product_id);
if (!$product) {
return new WP_REST_Response([
'success' => false,
'error' => 'product_not_found',
], 404);
}
$result = SoftwareManager::update_version($version_id, $product_id, $version, $changelog, $set_current);
if (is_wp_error($result)) {
return new WP_REST_Response([
'success' => false,
'error' => $result->get_error_code(),
'message' => $result->get_error_message(),
], 400);
}
return new WP_REST_Response([
'success' => true,
'message' => __('Version updated successfully', 'woonoow'),
], 200);
}
} }

View File

@@ -17,6 +17,7 @@ use WP_REST_Response;
use WP_Error; use WP_Error;
use WooNooW\Core\ModuleRegistry; use WooNooW\Core\ModuleRegistry;
use WooNooW\Modules\Subscription\SubscriptionManager; use WooNooW\Modules\Subscription\SubscriptionManager;
use WooNooW\Modules\Subscription\GatewayCapabilities;
class SubscriptionsController class SubscriptionsController
{ {
@@ -40,6 +41,17 @@ class SubscriptionsController
}, },
]); ]);
// M3 — Bulk operations. Body shape: { action: 'cancel' | 'export_csv', ids: number[] }.
// For 'cancel' we return { ok: int, failed: [{id, error}] }. For 'export_csv' the
// response is a text/csv body with Content-Disposition.
register_rest_route('woonoow/v1', '/subscriptions/bulk', [
'methods' => 'POST',
'callback' => [__CLASS__, 'bulk_action'],
'permission_callback' => function () {
return current_user_can('manage_woocommerce');
},
]);
register_rest_route('woonoow/v1', '/subscriptions/(?P<id>\d+)', [ register_rest_route('woonoow/v1', '/subscriptions/(?P<id>\d+)', [
'methods' => 'GET', 'methods' => 'GET',
'callback' => [__CLASS__, 'get_subscription'], 'callback' => [__CLASS__, 'get_subscription'],
@@ -136,6 +148,23 @@ class SubscriptionsController
return is_user_logged_in(); return is_user_logged_in();
}, },
]); ]);
// §9 — Gateway capability matrix (admin)
register_rest_route('woonoow/v1', '/subscriptions/gateway-capabilities', [
'methods' => 'GET',
'callback' => [__CLASS__, 'get_gateway_capabilities'],
'permission_callback' => function () {
return current_user_can('manage_woocommerce');
},
]);
register_rest_route('woonoow/v1', '/subscriptions/gateway-capabilities', [
'methods' => 'POST',
'callback' => [__CLASS__, 'update_gateway_capabilities'],
'permission_callback' => function () {
return current_user_can('manage_woocommerce');
},
]);
} }
/** /**
@@ -147,12 +176,16 @@ class SubscriptionsController
'status' => $request->get_param('status'), 'status' => $request->get_param('status'),
'product_id' => $request->get_param('product_id'), 'product_id' => $request->get_param('product_id'),
'user_id' => $request->get_param('user_id'), 'user_id' => $request->get_param('user_id'),
'search' => $request->get_param('search'),
'limit' => $request->get_param('per_page') ?: 20, 'limit' => $request->get_param('per_page') ?: 20,
'offset' => (($request->get_param('page') ?: 1) - 1) * ($request->get_param('per_page') ?: 20), 'offset' => (($request->get_param('page') ?: 1) - 1) * ($request->get_param('per_page') ?: 20),
]; ];
$subscriptions = SubscriptionManager::get_all($args); $subscriptions = SubscriptionManager::get_all($args);
$total = SubscriptionManager::count(['status' => $args['status']]); $total = SubscriptionManager::count([
'status' => $args['status'],
'search' => $args['search'],
]);
// Enrich with product and user info // Enrich with product and user info
$enriched = []; $enriched = [];
@@ -244,16 +277,27 @@ class SubscriptionsController
/** /**
* Renew subscription (admin - force immediate renewal) * Renew subscription (admin - force immediate renewal)
*
* M2 — supports `?charge_now=true` to bypass the per-gateway capability
* gate. With the flag, the auto-debit path is attempted even on gateways
* that are normally manual-only; on failure the order is marked failed
* (no manual fallback) so the admin can see the charge couldn't go
* through.
*/ */
public static function renew_subscription(WP_REST_Request $request) public static function renew_subscription(WP_REST_Request $request)
{ {
$result = SubscriptionManager::renew($request->get_param('id')); $charge_now = filter_var($request->get_param('charge_now'), FILTER_VALIDATE_BOOLEAN);
$result = SubscriptionManager::renew($request->get_param('id'), $charge_now);
if (!$result) { if (!$result) {
return new WP_Error('renew_failed', __('Failed to process renewal', 'woonoow'), ['status' => 500]); return new WP_Error('renew_failed', __('Failed to process renewal', 'woonoow'), ['status' => 500]);
} }
return new WP_REST_Response(['success' => true, 'order_id' => $result['order_id']]); return new WP_REST_Response([
'success' => true,
'order_id' => $result['order_id'],
'status' => $result['status'] ?? 'complete',
]);
} }
/** /**
@@ -284,6 +328,98 @@ class SubscriptionsController
return new WP_REST_Response(['success' => true]); return new WP_REST_Response(['success' => true]);
} }
/**
* M3 — Bulk action endpoint.
*
* Body: { action: 'cancel' | 'export_csv', ids: number[] }
*
* - 'cancel' returns JSON `{ ok: int, failed: [{id, error}] }`. Per-subscription
* errors do not abort the batch — the admin sees the per-row outcome.
* - 'export_csv' streams a CSV download. We don't use WP_REST_Response's
* download flag because we want to set a custom filename.
*
* Hard cap of 500 ids per call to avoid runaway batches. A real implementation
* would dispatch this via Action Scheduler; for now we run inline because
* 500 cancels is <1s of DB writes.
*/
public static function bulk_action(WP_REST_Request $request)
{
$action = (string) $request->get_param('action');
$ids = $request->get_param('ids');
if (!is_array($ids) || empty($ids)) {
return new WP_Error('bad_request', __('ids must be a non-empty array', 'woonoow'), ['status' => 400]);
}
// Coerce to ints, drop non-numeric junk, dedupe.
$ids = array_values(array_unique(array_filter(array_map('intval', $ids), function ($i) { return $i > 0; })));
if (empty($ids)) {
return new WP_Error('bad_request', __('ids must contain at least one positive integer', 'woonoow'), ['status' => 400]);
}
if (count($ids) > 500) {
return new WP_Error('batch_too_large', __('Maximum 500 ids per bulk request', 'woonoow'), ['status' => 400]);
}
if ($action === 'cancel') {
$ok = 0;
$failed = [];
foreach ($ids as $id) {
$result = SubscriptionManager::cancel($id);
if ($result === false || $result === null) {
$failed[] = ['id' => $id, 'error' => __('Cancel returned false', 'woonoow')];
} else {
$ok++;
}
}
return new WP_REST_Response(['ok' => $ok, 'failed' => $failed]);
}
if ($action === 'export_csv') {
$rows = [];
foreach ($ids as $id) {
$sub = SubscriptionManager::get($id);
if (!$sub) {
$rows[] = [
'id' => $id, 'status' => 'missing', 'user_name' => '', 'user_email' => '',
'product_name' => '', 'billing_period' => '', 'billing_interval' => '',
'recurring_amount' => '', 'next_payment_date' => '', 'start_date' => '',
'end_date' => '', 'payment_method' => '',
];
continue;
}
$rows[] = [
'id' => (int) $sub->id,
'status' => (string) $sub->status,
'user_name' => (string) ($sub->user_name ?? ''),
'user_email' => (string) ($sub->user_email ?? ''),
'product_name' => (string) ($sub->product_name ?? ''),
'billing_period' => (string) $sub->billing_period,
'billing_interval' => (int) $sub->billing_interval,
'recurring_amount' => (string) $sub->recurring_amount,
'next_payment_date' => (string) ($sub->next_payment_date ?? ''),
'start_date' => (string) $sub->start_date,
'end_date' => (string) ($sub->end_date ?? ''),
'payment_method' => (string) ($sub->payment_method ?? ''),
];
}
$filename = 'woonoow-subscriptions-' . gmdate('Ymd-His') . '.csv';
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
$out = fopen('php://output', 'w');
if (!empty($rows)) {
fputcsv($out, array_keys($rows[0]));
foreach ($rows as $r) {
fputcsv($out, $r);
}
}
fclose($out);
exit;
}
return new WP_Error('unknown_action', __('Unknown bulk action', 'woonoow'), ['status' => 400]);
}
/** /**
* Get customer's subscriptions * Get customer's subscriptions
*/ */
@@ -453,10 +589,31 @@ class SubscriptionsController
// Add computed fields // Add computed fields
$enriched['is_active'] = $subscription->status === 'active'; $enriched['is_active'] = $subscription->status === 'active';
$enriched['can_pause'] = $subscription->status === 'active';
$enriched['can_resume'] = $subscription->status === 'on-hold'; // Surface pause-limit context to the client (H2). The server-side pause handler in
// SubscriptionManager::pause() already enforces the limit; this just tells the UI how
// many pauses remain so the button can be disabled with a tooltip before the customer
// hits the wall and gets a generic 500.
$settings = \WooNooW\Core\ModuleRegistry::get_settings('subscription');
$max_pause_count = isset($settings['max_pause_count']) ? (int) $settings['max_pause_count'] : 3;
$enriched['max_pause_count'] = $max_pause_count;
$enriched['pauses_remaining'] = $max_pause_count > 0
? max(0, $max_pause_count - (int) $subscription->pause_count)
: null; // null = unlimited
// Whether this customer is actually allowed to pause, incorporating:
// - feature toggle (allow_customer_pause setting)
// - subscription status
// - lifetime pause limit
$allow_pause_feature = !empty($settings['allow_customer_pause']);
$pause_limit_ok = ($max_pause_count <= 0) || ($subscription->pause_count < $max_pause_count);
$enriched['can_pause'] = $subscription->status === 'active' && $allow_pause_feature && $pause_limit_ok;
$enriched['can_resume'] = in_array($subscription->status, ['on-hold', 'pending-cancel']);
$enriched['can_cancel'] = in_array($subscription->status, ['active', 'on-hold', 'pending']); $enriched['can_cancel'] = in_array($subscription->status, ['active', 'on-hold', 'pending']);
// Expose paused_at so the UI can show when the subscription was paused
$enriched['paused_at'] = $subscription->paused_at ?? null;
// Format billing info // Format billing info
$period_labels = [ $period_labels = [
'day' => __('day', 'woonoow'), 'day' => __('day', 'woonoow'),
@@ -496,6 +653,110 @@ class SubscriptionsController
$enriched['payment_method_title'] = $payment_title; $enriched['payment_method_title'] = $payment_title;
// §9 — Tell the client whether the stored gateway is declared to support
// subscription auto-renew. The renewal flow uses this for messaging and the
// admin uses it for at-a-glance status.
$enriched['gateway_supports_auto_renew'] = !empty($subscription->payment_method)
? GatewayCapabilities::should_attempt_auto_renew($subscription->payment_method)
: false;
$enriched['gateway_force_manual'] = GatewayCapabilities::force_manual();
return $enriched; return $enriched;
} }
/**
* §9 — List the merged gateway capability matrix for the admin UI.
*
* Returns a row per available WC payment gateway with:
* id, title, description, enabled (site-enabled),
* auto_renew (effective — capability table + kill switch),
* override (the merchant-set override, or null if using default),
* default (the built-in default for this gateway ID)
*/
public static function get_gateway_capabilities(WP_REST_Request $request)
{
if (!function_exists('WC')) {
return new WP_Error('wc_missing', __('WooCommerce is not active.', 'woonoow'), ['status' => 500]);
}
$gateways = WC()->payment_gateways()->payment_gateways();
$stored = get_option(GatewayCapabilities::OPTION_KEY, []);
if (!is_array($stored)) {
$stored = [];
}
$defaults = GatewayCapabilities::default_capabilities();
$kill_switch = GatewayCapabilities::force_manual();
$rows = [];
foreach ($gateways as $id => $gateway) {
$default = isset($defaults[$id]) ? (bool) $defaults[$id]['subscription_auto_renew'] : false;
$override = array_key_exists($id, $stored) ? (bool) $stored[$id]['subscription_auto_renew'] : null;
$effective = GatewayCapabilities::should_attempt_auto_renew($id);
$rows[] = [
'id' => $id,
'title' => $gateway->get_title() ?: $gateway->method_title ?: $id,
'description' => $gateway->get_description(),
'enabled' => $gateway->enabled === 'yes',
'default' => $default,
'override' => $override,
'auto_renew' => $effective,
'forced_manual' => $kill_switch,
];
}
return new WP_REST_Response([
'gateways' => array_values($rows),
'kill_switch' => $kill_switch,
]);
}
/**
* §9 — Persist merchant overrides for the per-gateway capability table.
*
* Body shape: { overrides: { '<gateway_id>': bool | null, ... } }
* - bool => explicit override (true = auto-renew, false = manual)
* - null => clear override, fall back to default
*
* The kill switch is NOT set here — it lives in the standard module
* settings under `force_manual_renewal` (use the generic settings endpoint).
*/
public static function update_gateway_capabilities(WP_REST_Request $request)
{
$body = $request->get_json_params();
if (!is_array($body) || !isset($body['overrides']) || !is_array($body['overrides'])) {
return new WP_Error('bad_request', __('overrides map is required.', 'woonoow'), ['status' => 400]);
}
$stored = get_option(GatewayCapabilities::OPTION_KEY, []);
if (!is_array($stored)) {
$stored = [];
}
$defaults = GatewayCapabilities::default_capabilities();
$valid_ids = $defaults;
if (function_exists('WC')) {
foreach (WC()->payment_gateways()->payment_gateways() as $id => $gw) {
$valid_ids[$id] = ['subscription_auto_renew' => false];
}
}
foreach ($body['overrides'] as $id => $value) {
$id = sanitize_key((string) $id);
if ($id === '' || !array_key_exists($id, $valid_ids)) {
continue; // unknown gateway — ignore
}
if ($value === null) {
unset($stored[$id]);
} else {
$stored[$id] = ['subscription_auto_renew' => (bool) $value];
}
}
update_option(GatewayCapabilities::OPTION_KEY, $stored);
return new WP_REST_Response([
'success' => true,
'overrides' => $stored,
]);
}
} }

View File

@@ -28,6 +28,7 @@ use WooNooW\Branding;
use WooNooW\Frontend\Assets as FrontendAssets; use WooNooW\Frontend\Assets as FrontendAssets;
use WooNooW\Frontend\Shortcodes; use WooNooW\Frontend\Shortcodes;
use WooNooW\Frontend\TemplateOverride; use WooNooW\Frontend\TemplateOverride;
use WooNooW\Frontend\SmartRotator;
use WooNooW\Frontend\PageAppearance; use WooNooW\Frontend\PageAppearance;
class Bootstrap { class Bootstrap {
@@ -47,6 +48,7 @@ class Bootstrap {
FrontendAssets::init(); FrontendAssets::init();
// Note: Shortcodes removed - WC pages now redirect to SPA routes via TemplateOverride // Note: Shortcodes removed - WC pages now redirect to SPA routes via TemplateOverride
TemplateOverride::init(); TemplateOverride::init();
SmartRotator::init();
new PageAppearance(); new PageAppearance();
// Activity Log // Activity Log
@@ -75,6 +77,13 @@ class Bootstrap {
// Load custom variation attributes for WooCommerce admin // Load custom variation attributes for WooCommerce admin
add_action('woocommerce_product_variation_object_read', [self::class, 'load_variation_attributes']); add_action('woocommerce_product_variation_object_read', [self::class, 'load_variation_attributes']);
} }
public static function init_frontend() {
Shortcodes::init();
TemplateOverride::init();
SmartRotator::init();
PageAppearance::init();
}
/** /**
* Properly initialize WooCommerce cart for REST API requests * Properly initialize WooCommerce cart for REST API requests

View File

@@ -352,6 +352,21 @@ class EmailRenderer
'payment_link' => $data['payment_link'] ?? '', 'payment_link' => $data['payment_link'] ?? '',
]; ];
// O1 — Derive `billing_schedule` (e.g. "Every 3 Months") and
// `payment_method_title` (e.g. "Stripe" rather than the raw
// gateway id "stripe"). The data is on the subscription row but
// isn't pre-formatted. We rebuild both so email templates can
// show the merchant-friendly string without duplicating the
// pluralization + lookup logic.
$sub_variables['billing_schedule'] = self::format_billing_schedule(
isset($sub->billing_period) ? (string) $sub->billing_period : '',
isset($sub->billing_interval) ? (int) $sub->billing_interval : 1
);
$sub_variables['payment_method_title'] = self::resolve_payment_method_title(
isset($sub->payment_method) ? (string) $sub->payment_method : '',
$data['order'] ?? null
);
// Get product name if not already set // Get product name if not already set
if (!isset($variables['product_name']) && isset($data['product']) && $data['product'] instanceof \WC_Product) { if (!isset($variables['product_name']) && isset($data['product']) && $data['product'] instanceof \WC_Product) {
$sub_variables['product_name'] = $data['product']->get_name(); $sub_variables['product_name'] = $data['product']->get_name();
@@ -381,6 +396,57 @@ class EmailRenderer
return apply_filters('woonoow_email_variables', $variables, $event_id, $data); return apply_filters('woonoow_email_variables', $variables, $event_id, $data);
} }
/**
* O1 — Format a billing schedule string like "Every 3 Months" from raw
* period and interval columns. Mirrors the controller's
* `enrich_subscription()` math so email templates show the same string
* the customer sees in the SPA. Falls back to the period string itself
* if the period is unknown.
*/
public static function format_billing_schedule($period, $interval)
{
$period_labels = [
'day' => __('day', 'woonoow'),
'week' => __('week', 'woonoow'),
'month' => __('month', 'woonoow'),
'year' => __('year', 'woonoow'),
];
$interval = max(1, (int) $interval);
$period_label = $period_labels[$period] ?? $period;
if ($interval > 1) {
$period_label .= 's';
}
return sprintf(__('Every %s%s', 'woonoow'), $interval, $period_label);
}
/**
* O1 — Resolve a human-friendly payment method title from a stored gateway
* id. Order of preference:
* 1. The order's `payment_method_title` (most accurate; set by gateway
* at checkout — e.g. "PayPal — Visa ending in 1234")
* 2. The registered WC gateway's `get_title()` (e.g. "Stripe")
* 3. The raw id
*/
public static function resolve_payment_method_title($gateway_id, $order = null)
{
if ($order instanceof \WC_Order) {
$title = $order->get_payment_method_title();
if (!empty($title)) {
return $title;
}
}
if ($gateway_id !== '' && function_exists('WC') && WC()->payment_gateways()) {
$gateways = WC()->payment_gateways()->payment_gateways();
if (isset($gateways[$gateway_id]) && method_exists($gateways[$gateway_id], 'get_title')) {
$title = $gateways[$gateway_id]->get_title();
if (!empty($title)) {
return $title;
}
}
}
return $gateway_id;
}
/** /**
* Parse [card] tags and convert to HTML * Parse [card] tags and convert to HTML
* *

View File

@@ -1,375 +0,0 @@
<?php
/**
* Notification Template Provider
*
* Manages notification templates for all channels.
*
* @package WooNooW\Core\Notifications
*/
namespace WooNooW\Core\Notifications;
use WooNooW\Email\DefaultTemplates as EmailDefaultTemplates;
class TemplateProvider {
/**
* Option key for storing templates
*/
const OPTION_KEY = 'woonoow_notification_templates';
/**
* Get all templates
*
* @return array
*/
public static function get_templates() {
$templates = get_option(self::OPTION_KEY, []);
// Merge with defaults
$defaults = self::get_default_templates();
return array_merge($defaults, $templates);
}
/**
* Get template for specific event and channel
*
* @param string $event_id Event ID
* @param string $channel_id Channel ID
* @param string $recipient_type Recipient type ('customer' or 'staff')
* @return array|null
*/
public static function get_template($event_id, $channel_id, $recipient_type = 'customer') {
$templates = self::get_templates();
$key = "{$recipient_type}_{$event_id}_{$channel_id}";
if (isset($templates[$key])) {
return $templates[$key];
}
// Return default if exists
$defaults = self::get_default_templates();
if (isset($defaults[$key])) {
return $defaults[$key];
}
return null;
}
/**
* Save template
*
* @param string $event_id Event ID
* @param string $channel_id Channel ID
* @param array $template Template data
* @param string $recipient_type Recipient type ('customer' or 'staff')
* @return bool
*/
public static function save_template($event_id, $channel_id, $template, $recipient_type = 'customer') {
$templates = get_option(self::OPTION_KEY, []);
$key = "{$recipient_type}_{$event_id}_{$channel_id}";
$templates[$key] = [
'event_id' => $event_id,
'channel_id' => $channel_id,
'recipient_type' => $recipient_type,
'subject' => $template['subject'] ?? '',
'body' => $template['body'] ?? '',
'variables' => $template['variables'] ?? [],
'updated_at' => current_time('mysql'),
];
return update_option(self::OPTION_KEY, $templates);
}
/**
* Delete template (revert to default)
*
* @param string $event_id Event ID
* @param string $channel_id Channel ID
* @param string $recipient_type Recipient type ('customer' or 'staff')
* @return bool
*/
public static function delete_template($event_id, $channel_id, $recipient_type = 'customer') {
$templates = get_option(self::OPTION_KEY, []);
$key = "{$recipient_type}_{$event_id}_{$channel_id}";
if (isset($templates[$key])) {
unset($templates[$key]);
return update_option(self::OPTION_KEY, $templates);
}
return false;
}
/**
* Get WooCommerce email template content
*
* @param string $email_id WooCommerce email ID
* @return array|null
*/
private static function get_wc_email_template($email_id) {
if (!function_exists('WC')) {
return null;
}
$mailer = \WC()->mailer();
$emails = $mailer->get_emails();
if (isset($emails[$email_id])) {
$email = $emails[$email_id];
return [
'subject' => $email->get_subject(),
'heading' => $email->get_heading(),
'enabled' => $email->is_enabled(),
];
}
return null;
}
/**
* Get default templates
*
* @return array
*/
public static function get_default_templates() {
$templates = [];
// Get all events from EventRegistry (single source of truth)
$all_events = EventRegistry::get_all_events();
// Get email templates from DefaultTemplates
$allEmailTemplates = EmailDefaultTemplates::get_all_templates();
foreach ($all_events as $event) {
$event_id = $event['id'];
$recipient_type = $event['recipient_type'];
// Get template body from the new clean markdown source
$body = $allEmailTemplates[$recipient_type][$event_id] ?? '';
$subject = EmailDefaultTemplates::get_default_subject($recipient_type, $event_id);
// If template doesn't exist, create a simple fallback
if (empty($body)) {
$body = "[card]\n\n## Notification\n\nYou have a new notification about {$event_id}.\n\n[/card]";
$subject = __('Notification from {store_name}', 'woonoow');
}
$templates["{$recipient_type}_{$event_id}_email"] = [
'event_id' => $event_id,
'channel_id' => 'email',
'recipient_type' => $recipient_type,
'subject' => $subject,
'body' => $body,
'variables' => self::get_variables_for_event($event_id),
];
}
// Add push notification templates
$templates['staff_order_placed_push'] = [
'event_id' => 'order_placed',
'channel_id' => 'push',
'recipient_type' => 'staff',
'subject' => __('New Order #{order_number}', 'woonoow'),
'body' => __('New order from {customer_name} - {order_total}', 'woonoow'),
'variables' => self::get_order_variables(),
];
$templates['customer_order_processing_push'] = [
'event_id' => 'order_processing',
'channel_id' => 'push',
'recipient_type' => 'customer',
'subject' => __('Order Processing', 'woonoow'),
'body' => __('Your order #{order_number} is being processed', 'woonoow'),
'variables' => self::get_order_variables(),
];
$templates['customer_order_completed_push'] = [
'event_id' => 'order_completed',
'channel_id' => 'push',
'recipient_type' => 'customer',
'subject' => __('Order Completed', 'woonoow'),
'body' => __('Your order #{order_number} has been completed!', 'woonoow'),
'variables' => self::get_order_variables(),
];
$templates['staff_order_cancelled_push'] = [
'event_id' => 'order_cancelled',
'channel_id' => 'push',
'recipient_type' => 'staff',
'subject' => __('Order Cancelled', 'woonoow'),
'body' => __('Order #{order_number} has been cancelled', 'woonoow'),
'variables' => self::get_order_variables(),
];
$templates['customer_order_refunded_push'] = [
'event_id' => 'order_refunded',
'channel_id' => 'push',
'recipient_type' => 'customer',
'subject' => __('Order Refunded', 'woonoow'),
'body' => __('Your order #{order_number} has been refunded', 'woonoow'),
'variables' => self::get_order_variables(),
];
$templates['staff_low_stock_push'] = [
'event_id' => 'low_stock',
'channel_id' => 'push',
'recipient_type' => 'staff',
'subject' => __('Low Stock Alert', 'woonoow'),
'body' => __('{product_name} is running low on stock', 'woonoow'),
'variables' => self::get_product_variables(),
];
$templates['staff_out_of_stock_push'] = [
'event_id' => 'out_of_stock',
'channel_id' => 'push',
'recipient_type' => 'staff',
'subject' => __('Out of Stock Alert', 'woonoow'),
'body' => __('{product_name} is now out of stock', 'woonoow'),
'variables' => self::get_product_variables(),
];
$templates['customer_new_customer_push'] = [
'event_id' => 'new_customer',
'channel_id' => 'push',
'recipient_type' => 'customer',
'subject' => __('Welcome!', 'woonoow'),
'body' => __('Welcome to {store_name}, {customer_name}!', 'woonoow'),
'variables' => self::get_customer_variables(),
];
$templates['customer_customer_note_push'] = [
'event_id' => 'customer_note',
'channel_id' => 'push',
'recipient_type' => 'customer',
'subject' => __('Order Note Added', 'woonoow'),
'body' => __('A note has been added to order #{order_number}', 'woonoow'),
'variables' => self::get_order_variables(),
];
return $templates;
}
/**
* Get variables for a specific event
*
* @param string $event_id Event ID
* @return array
*/
private static function get_variables_for_event($event_id) {
// Product events
if (in_array($event_id, ['low_stock', 'out_of_stock'])) {
return self::get_product_variables();
}
// Customer events (but not order-related)
if ($event_id === 'new_customer') {
return self::get_customer_variables();
}
// Subscription events
if (strpos($event_id, 'subscription_') === 0) {
return self::get_subscription_variables();
}
// All other events are order-related
return self::get_order_variables();
}
/**
* Get available order variables
*
* @return array
*/
public static function get_order_variables() {
return [
'order_number' => __('Order Number', 'woonoow'),
'order_total' => __('Order Total', 'woonoow'),
'order_status' => __('Order Status', 'woonoow'),
'order_date' => __('Order Date', 'woonoow'),
'order_url' => __('Order URL', 'woonoow'),
'order_items_list' => __('Order Items (formatted list)', 'woonoow'),
'order_items_table' => __('Order Items (formatted table)', 'woonoow'),
'payment_method' => __('Payment Method', 'woonoow'),
'payment_url' => __('Payment URL (for pending payments)', 'woonoow'),
'shipping_method' => __('Shipping Method', 'woonoow'),
'tracking_number' => __('Tracking Number', 'woonoow'),
'refund_amount' => __('Refund Amount', 'woonoow'),
'customer_name' => __('Customer Name', 'woonoow'),
'customer_email' => __('Customer Email', 'woonoow'),
'customer_phone' => __('Customer Phone', 'woonoow'),
'billing_address' => __('Billing Address', 'woonoow'),
'shipping_address' => __('Shipping Address', 'woonoow'),
'store_name' => __('Store Name', 'woonoow'),
'store_url' => __('Store URL', 'woonoow'),
'store_email' => __('Store Email', 'woonoow'),
];
}
/**
* Get available product variables
*
* @return array
*/
public static function get_product_variables() {
return [
'product_name' => __('Product Name', 'woonoow'),
'product_sku' => __('Product SKU', 'woonoow'),
'product_url' => __('Product URL', 'woonoow'),
'stock_quantity' => __('Stock Quantity', 'woonoow'),
'store_name' => __('Store Name', 'woonoow'),
'store_url' => __('Store URL', 'woonoow'),
];
}
/**
* Get available customer variables
*
* @return array
*/
public static function get_customer_variables() {
return [
'customer_name' => __('Customer Name', 'woonoow'),
'customer_email' => __('Customer Email', 'woonoow'),
'customer_phone' => __('Customer Phone', 'woonoow'),
'store_name' => __('Store Name', 'woonoow'),
'store_url' => __('Store URL', 'woonoow'),
'store_email' => __('Store Email', 'woonoow'),
];
}
/**
* Get available subscription variables
*
* @return array
*/
public static function get_subscription_variables() {
return [
'subscription_id' => __('Subscription ID', 'woonoow'),
'subscription_status' => __('Subscription Status', 'woonoow'),
'product_name' => __('Product Name', 'woonoow'),
'billing_period' => __('Billing Period (e.g., Monthly)', 'woonoow'),
'recurring_amount' => __('Recurring Amount', 'woonoow'),
'next_payment_date' => __('Next Payment Date', 'woonoow'),
'end_date' => __('Subscription End Date', 'woonoow'),
'cancel_reason' => __('Cancellation Reason', 'woonoow'),
'customer_name' => __('Customer Name', 'woonoow'),
'customer_email' => __('Customer Email', 'woonoow'),
'store_name' => __('Store Name', 'woonoow'),
'store_url' => __('Store URL', 'woonoow'),
'my_account_url' => __('My Account URL', 'woonoow'),
];
}
/**
* Replace variables in template
*
* @param string $content Content with variables
* @param array $data Data to replace variables
* @return string
*/
public static function replace_variables($content, $data) {
foreach ($data as $key => $value) {
$content = str_replace('{' . $key . '}', $value, $content);
}
return $content;
}
}

View File

@@ -69,6 +69,10 @@ class AddressController {
$addresses = array_values($addresses); $addresses = array_values($addresses);
foreach ($addresses as &$address) {
$address['formatted_address'] = apply_filters('woonoow_format_address', '', $address);
}
return new WP_REST_Response($addresses, 200); return new WP_REST_Response($addresses, 200);
} }

View File

@@ -243,6 +243,19 @@ class Assets
$base_path = ''; $base_path = '';
} }
// Also force empty base path for /collection/ routes since they are global
$spa_path_var = get_query_var('woonoow_spa_path');
if (!empty($spa_path_var) && strpos($spa_path_var, 'collection/') === 0) {
$base_path = '';
}
// Handle serve_spa_for_frontpage_routes which bypasses WP queries
$request_uri = $_SERVER['REQUEST_URI'] ?? '/';
$path = parse_url($request_uri, PHP_URL_PATH);
if (strpos($path, '/collection/') === 0) {
$base_path = '';
}
// Check if BrowserRouter is enabled (default: true for SEO) // Check if BrowserRouter is enabled (default: true for SEO)
$use_browser_router = $appearance_settings['general']['use_browser_router'] ?? true; $use_browser_router = $appearance_settings['general']['use_browser_router'] ?? true;
@@ -263,6 +276,9 @@ class Assets
'useBrowserRouter' => $use_browser_router, 'useBrowserRouter' => $use_browser_router,
'frontPageSlug' => $front_page_slug, 'frontPageSlug' => $front_page_slug,
'spaMode' => $appearance_settings['general']['spa_mode'] ?? 'full', 'spaMode' => $appearance_settings['general']['spa_mode'] ?? 'full',
'affiliateSettings' => [
'enableCuratedCollections' => class_exists('\WooNooW\Modules\Affiliate\AffiliateSettings') ? \WooNooW\Modules\Affiliate\AffiliateSettings::get_setting('woonoow_affiliate_enable_curated_collections', true) : false,
],
'security' => \WooNooW\Compat\SecuritySettingsProvider::get_public_settings(), 'security' => \WooNooW\Compat\SecuritySettingsProvider::get_public_settings(),
]; ];
@@ -460,7 +476,7 @@ class Assets
} }
// Check path prefixes // Check path prefixes
$prefix_routes = ['/shop/', '/my-account/', '/product/']; $prefix_routes = ['/shop/', '/my-account/', '/product/', '/collection/'];
foreach ($prefix_routes as $prefix) { foreach ($prefix_routes as $prefix) {
if (strpos($path, $prefix) === 0) { if (strpos($path, $prefix) === 0) {
return true; return true;

View File

@@ -54,6 +54,14 @@ class ShopController
'default' => '', 'default' => '',
'sanitize_callback' => 'sanitize_text_field', 'sanitize_callback' => 'sanitize_text_field',
], ],
'min_price' => [
'default' => '',
'sanitize_callback' => 'sanitize_text_field',
],
'max_price' => [
'default' => '',
'sanitize_callback' => 'sanitize_text_field',
],
], ],
]); ]);
@@ -90,6 +98,13 @@ class ShopController
], ],
], ],
]); ]);
// Get affiliate collection (public)
register_rest_route($namespace, '/shop/collections/(?P<slug>[a-zA-Z0-9-]+)', [
'methods' => 'GET',
'callback' => [__CLASS__, 'get_collection'],
'permission_callback' => '__return_true',
]);
} }
/** /**
@@ -106,6 +121,8 @@ class ShopController
$slug = $request->get_param('slug'); $slug = $request->get_param('slug');
$include = $request->get_param('include'); $include = $request->get_param('include');
$exclude = $request->get_param('exclude'); $exclude = $request->get_param('exclude');
$min_price = $request->get_param('min_price');
$max_price = $request->get_param('max_price');
$args = [ $args = [
'post_type' => 'product', 'post_type' => 'product',
@@ -152,6 +169,30 @@ class ShopController
$args['s'] = $search; $args['s'] = $search;
} }
// Add price filter
if ($min_price !== '' || $max_price !== '') {
$price_query = [
'key' => '_price',
'type' => 'NUMERIC',
];
if ($min_price !== '' && $max_price !== '') {
$price_query['compare'] = 'BETWEEN';
$price_query['value'] = [(float)$min_price, (float)$max_price];
} elseif ($min_price !== '') {
$price_query['compare'] = '>=';
$price_query['value'] = (float)$min_price;
} else {
$price_query['compare'] = '<=';
$price_query['value'] = (float)$max_price;
}
if (!isset($args['meta_query'])) {
$args['meta_query'] = [];
}
$args['meta_query'][] = $price_query;
}
$query = new \WP_Query($args); $query = new \WP_Query($args);
// Check if this is a single product request (by slug) // Check if this is a single product request (by slug)
@@ -256,6 +297,57 @@ class ShopController
return new WP_REST_Response($products, 200); return new WP_REST_Response($products, 200);
} }
/**
* Get affiliate collection by slug
*/
public static function get_collection(WP_REST_Request $request)
{
global $wpdb;
$slug = sanitize_title($request->get_param('slug'));
$collections_table = $wpdb->prefix . 'woonoow_affiliate_collections';
$collection = $wpdb->get_row($wpdb->prepare("SELECT * FROM $collections_table WHERE slug = %s", $slug));
if (!$collection) {
return new WP_Error('not_found', 'Collection not found', ['status' => 404]);
}
$product_ids = $collection->product_ids ? json_decode($collection->product_ids, true) : [];
if (!is_array($product_ids)) $product_ids = [];
$products = [];
if (!empty($product_ids)) {
$args = [
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => -1,
'post__in' => $product_ids,
'orderby' => 'post__in',
];
$query = new \WP_Query($args);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
$product = wc_get_product(get_the_ID());
if ($product) {
$products[] = self::format_product($product);
}
}
wp_reset_postdata();
}
}
$data = [
'id' => $collection->id,
'title' => $collection->title,
'description' => $collection->description,
'products' => $products
];
return new WP_REST_Response($data, 200);
}
/** /**
* Format product data for API response * Format product data for API response
*/ */

View File

@@ -0,0 +1,83 @@
<?php
namespace WooNooW\Frontend;
if (!defined('ABSPATH')) exit;
class SmartRotator
{
public static function init()
{
add_action('init', [__CLASS__, 'register_rewrite_rules']);
add_filter('query_vars', [__CLASS__, 'register_query_vars']);
add_action('template_redirect', [__CLASS__, 'handle_redirect']);
}
public static function register_rewrite_rules()
{
// Match /go/collection-slug
add_rewrite_rule(
'^go/([^/]+)/?$',
'index.php?woonoow_go_slug=$matches[1]',
'top'
);
}
public static function register_query_vars($vars)
{
$vars[] = 'woonoow_go_slug';
return $vars;
}
public static function handle_redirect()
{
$slug = get_query_var('woonoow_go_slug');
if (empty($slug)) {
return;
}
global $wpdb;
$collections_table = $wpdb->prefix . 'woonoow_affiliate_collections';
$affiliates_table = $wpdb->prefix . 'woonoow_affiliates';
// Lookup collection and affiliate in one query
$query = $wpdb->prepare(
"SELECT c.product_ids, a.referral_code
FROM {$collections_table} c
JOIN {$affiliates_table} a ON c.affiliate_id = a.id
WHERE c.slug = %s LIMIT 1",
$slug
);
$result = $wpdb->get_row($query);
if (!$result || empty($result->product_ids)) {
// Fallback: 404 or redirect to shop
wp_safe_redirect(site_url('/shop/'));
exit;
}
$product_ids = json_decode($result->product_ids, true);
if (!is_array($product_ids) || empty($product_ids)) {
wp_safe_redirect(site_url('/shop/'));
exit;
}
// Randomly pick a product
$random_product_id = $product_ids[array_rand($product_ids)];
// Get the permalink for the product
$target_url = get_permalink($random_product_id);
if (!$target_url) {
wp_safe_redirect(site_url('/shop/'));
exit;
}
// Append the affiliate referral code
$target_url = add_query_arg('ref', $result->referral_code, $target_url);
// Redirect to the product page
wp_redirect($target_url, 302);
exit;
}
}

View File

@@ -211,6 +211,13 @@ class TemplateOverride
); );
} }
// /collection/* → SPA page (global, independent of frontpage setting)
add_rewrite_rule(
'^collection/(.*)$',
'index.php?page_id=' . $spa_page_id . '&woonoow_spa_path=collection/$matches[1]',
'top'
);
// Register query var for the SPA path // Register query var for the SPA path
add_filter('query_vars', function ($vars) { add_filter('query_vars', function ($vars) {
$vars[] = 'woonoow_spa_path'; $vars[] = 'woonoow_spa_path';
@@ -338,7 +345,7 @@ class TemplateOverride
if (is_wc_endpoint_url('order-pay')) { if (is_wc_endpoint_url('order-pay')) {
global $wp; global $wp;
$order_id = $wp->query_vars['order-pay']; $order_id = $wp->query_vars['order-pay'];
wp_redirect($build_route('order-pay/' . $order_id), 302); wp_redirect($build_route('checkout/pay/' . $order_id), 302);
exit; exit;
} }
@@ -430,7 +437,7 @@ class TemplateOverride
} }
// Check path prefixes (for sub-routes) // Check path prefixes (for sub-routes)
$prefix_routes = ['/shop/', '/my-account/', '/product/', '/checkout/']; $prefix_routes = ['/shop/', '/my-account/', '/product/', '/checkout/', '/collection/'];
foreach ($prefix_routes as $prefix) { foreach ($prefix_routes as $prefix) {
if (strpos($path, $prefix) === 0) { if (strpos($path, $prefix) === 0) {
$should_serve_spa = true; $should_serve_spa = true;
@@ -500,7 +507,7 @@ class TemplateOverride
// Check if this is a SPA route // Check if this is a SPA route
// We include /product/ and standard endpoints // We include /product/ and standard endpoints
$spa_routes = ['/product/', '/cart', '/checkout', '/my-account']; $spa_routes = ['/product/', '/cart', '/checkout', '/my-account', '/go/'];
foreach ($spa_routes as $route) { foreach ($spa_routes as $route) {
if (strpos($requested_url, $route) !== false) { if (strpos($requested_url, $route) !== false) {

View File

@@ -107,11 +107,13 @@ class AffiliateLifecycle
if (!$referral) return; if (!$referral) return;
// Check if holding period is 0 (immediate approval on completion) // Check if holding period is 0 (immediate approval on completion)
$holding_period = (int) get_option('woonoow_affiliate_holding_period', 14); $holding_period = (int) AffiliateSettings::get_setting('woonoow_affiliate_holding_period', 14);
$handled_now = false;
if ($holding_period === 0) { if ($holding_period === 0) {
// Immediate approval // Immediate approval
self::auto_approve_referral($referral->id); self::auto_approve_referral($referral->id);
$handled_now = true;
} else { } else {
// If order was completed BEFORE the scheduled action time, approve now // If order was completed BEFORE the scheduled action time, approve now
// Otherwise, the scheduled action will approve later // Otherwise, the scheduled action will approve later
@@ -120,12 +122,13 @@ class AffiliateLifecycle
if (time() >= $approval_time) { if (time() >= $approval_time) {
self::auto_approve_referral($referral->id); self::auto_approve_referral($referral->id);
$handled_now = true;
} }
// If not, the scheduled Action Scheduler job will handle it // If not, the scheduled Action Scheduler job will handle it
} }
// Cancel the scheduled auto-approval since we're handling it now // Only unschedule if we actually approved now.
if (function_exists('as_unschedule_all_actions')) { if ($handled_now && function_exists('as_unschedule_all_actions')) {
as_unschedule_all_actions('woonoow_approve_referral', ['referral_id' => $referral->id], 'woonoow_affiliate'); as_unschedule_all_actions('woonoow_approve_referral', ['referral_id' => $referral->id], 'woonoow_affiliate');
} }
} }
@@ -222,13 +225,23 @@ class AffiliateLifecycle
if (!$referral) return; // Already processed or deleted if (!$referral) return; // Already processed or deleted
// Double check order status // Double check order status.
// Referrals must never be approved before the order is completed.
$order = wc_get_order($referral->order_id); $order = wc_get_order($referral->order_id);
if (!$order || in_array($order->get_status(), ['refunded', 'cancelled', 'failed'])) { if (!$order) {
return;
}
$order_status = $order->get_status();
if (in_array($order_status, ['refunded', 'cancelled', 'failed'])) {
self::handle_order_cancelled($referral->order_id); self::handle_order_cancelled($referral->order_id);
return; return;
} }
if ($order_status !== 'completed') {
return;
}
// Approve referral // Approve referral
$wpdb->update( $wpdb->update(
$referrals_table, $referrals_table,

View File

@@ -17,6 +17,7 @@ class AffiliateManager
private static $affiliates_table = 'woonoow_affiliates'; private static $affiliates_table = 'woonoow_affiliates';
private static $referrals_table = 'woonoow_referrals'; private static $referrals_table = 'woonoow_referrals';
private static $payouts_table = 'woonoow_affiliate_payouts'; private static $payouts_table = 'woonoow_affiliate_payouts';
private static $collections_table = 'woonoow_affiliate_collections';
/** /**
* Initialize * Initialize
@@ -37,6 +38,7 @@ class AffiliateManager
$affiliates_table = $wpdb->prefix . self::$affiliates_table; $affiliates_table = $wpdb->prefix . self::$affiliates_table;
$referrals_table = $wpdb->prefix . self::$referrals_table; $referrals_table = $wpdb->prefix . self::$referrals_table;
$payouts_table = $wpdb->prefix . self::$payouts_table; $payouts_table = $wpdb->prefix . self::$payouts_table;
$collections_table = $wpdb->prefix . self::$collections_table;
require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
@@ -135,6 +137,23 @@ class AffiliateManager
} }
} }
// Collections Table
$sql_collections = "CREATE TABLE $collections_table (
id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
affiliate_id bigint(20) UNSIGNED NOT NULL,
title varchar(255) NOT NULL,
slug varchar(255) NOT NULL,
description text DEFAULT NULL,
product_ids longtext 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 affiliate_slug (affiliate_id, slug),
KEY affiliate_id (affiliate_id)
) $charset_collate;";
dbDelta($sql_collections);
// Payouts Table // Payouts Table
$sql_payouts = "CREATE TABLE $payouts_table ( $sql_payouts = "CREATE TABLE $payouts_table (
id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,

View File

@@ -108,6 +108,12 @@ class AffiliateModule
} }
} }
} }
// Create collections table if it doesn't exist
$collections_table = $wpdb->prefix . 'woonoow_affiliate_collections';
if ($wpdb->get_var("SHOW TABLES LIKE '$collections_table'") !== $collections_table) {
AffiliateManager::create_tables();
}
} }
/** /**

View File

@@ -58,14 +58,44 @@ class AffiliateSettings {
'description' => __('Automatically approve new affiliate applications.', 'woonoow'), 'description' => __('Automatically approve new affiliate applications.', 'woonoow'),
'default' => false, 'default' => false,
], ],
'woonoow_affiliate_enable_curated_collections' => [
'type' => 'toggle',
'label' => __('Enable Curated Collections', 'woonoow'),
'description' => __('Allow affiliates to create and share custom curated product collections.', 'woonoow'),
'default' => true,
],
'woonoow_affiliate_allow_self_referral' => [ 'woonoow_affiliate_allow_self_referral' => [
'type' => 'toggle', 'type' => 'toggle',
'label' => __('Allow Self-Referrals', 'woonoow'), 'label' => __('Allow Self-Referrals', 'woonoow'),
'description' => __('Allow affiliates to earn commission when their own user account places an order.', 'woonoow'), 'description' => __('Allow affiliates to earn commission when their own user account places an order.', 'woonoow'),
'default' => false, 'default' => false,
], ],
'woonoow_affiliate_share_customer_data' => [
'type' => 'toggle',
'label' => __('Share Customer Data with Affiliates', 'woonoow'),
'description' => __('Allow affiliates to see the name and email of the customers they refer.', 'woonoow'),
'default' => false,
],
]; ];
return $schemas; return $schemas;
} }
/**
* Read Affiliate module setting from module settings storage with legacy fallback.
*
* @param string $key
* @param mixed $default
* @return mixed
*/
public static function get_setting($key, $default = null)
{
$module_settings = get_option('woonoow_module_affiliate_settings', []);
if (is_array($module_settings) && array_key_exists($key, $module_settings)) {
return $module_settings[$key];
}
// Legacy fallback for older installs that may store direct option keys.
return get_option($key, $default);
}
} }

View File

@@ -102,9 +102,37 @@ class AffiliateTracker
'samesite' => 'Lax' 'samesite' => 'Lax'
]; ];
// Capture referral code $referral_code = '';
// 1. Capture from ?ref= parameter
if (isset($_GET['ref']) && !empty($_GET['ref'])) { if (isset($_GET['ref']) && !empty($_GET['ref'])) {
$referral_code = sanitize_text_field($_GET['ref']); $referral_code = sanitize_text_field($_GET['ref']);
}
// 2. Or capture from collection slug in URL (e.g., /collection/my-slug)
if (empty($referral_code)) {
$request_uri = $_SERVER['REQUEST_URI'] ?? '/';
$path = parse_url($request_uri, PHP_URL_PATH);
// Extract collection slug, accounting for possible subdirectories (e.g. /store/collection/slug)
if (preg_match('#/collection/([^/]+)#', $path, $matches)) {
$collection_slug = sanitize_text_field($matches[1]);
global $wpdb;
$collections_table = $wpdb->prefix . 'woonoow_affiliate_collections';
$affiliates_table = $wpdb->prefix . 'woonoow_affiliates';
$referral_code = $wpdb->get_var($wpdb->prepare("
SELECT a.referral_code
FROM $collections_table c
JOIN $affiliates_table a ON c.affiliate_id = a.id
WHERE c.slug = %s
", $collection_slug));
}
}
// Set the cookie if we found a referral code
if (!empty($referral_code)) {
$result = setcookie(self::COOKIE_NAME, $referral_code, $options); $result = setcookie(self::COOKIE_NAME, $referral_code, $options);
$_COOKIE[self::COOKIE_NAME] = $referral_code; $_COOKIE[self::COOKIE_NAME] = $referral_code;
error_log('[AffiliateTracker] Set woonoow_ref cookie: ' . $referral_code . ', result=' . ($result ? 'true' : 'false')); error_log('[AffiliateTracker] Set woonoow_ref cookie: ' . $referral_code . ', result=' . ($result ? 'true' : 'false'));
@@ -363,7 +391,7 @@ class AffiliateTracker
// Schedule auto-approval (e.g., 14 days) via Action Scheduler // Schedule auto-approval (e.g., 14 days) via Action Scheduler
if (function_exists('as_schedule_single_action')) { if (function_exists('as_schedule_single_action')) {
$approval_days = get_option('woonoow_affiliate_holding_period', 14); $approval_days = (int) AffiliateSettings::get_setting('woonoow_affiliate_holding_period', 14);
$timestamp = time() + ($approval_days * DAY_IN_SECONDS); $timestamp = time() + ($approval_days * DAY_IN_SECONDS);
as_schedule_single_action($timestamp, 'woonoow_approve_referral', ['referral_id' => $referral_id], 'woonoow_affiliate'); as_schedule_single_action($timestamp, 'woonoow_approve_referral', ['referral_id' => $referral_id], 'woonoow_affiliate');
} }

View File

@@ -608,7 +608,7 @@ class LicenseManager
/** /**
* Validate license (check if valid without activating) * Validate license (check if valid without activating)
*/ */
public static function validate($license_key) public static function validate($license_key, $domain = null)
{ {
$license = self::get_license_by_key($license_key); $license = self::get_license_by_key($license_key);
@@ -626,8 +626,31 @@ class LicenseManager
$subscription_status = self::get_order_subscription_status($license['order_id']); $subscription_status = self::get_order_subscription_status($license['order_id']);
$is_subscription_valid = $subscription_status === null || in_array($subscription_status, ['active', 'pending-cancel']); $is_subscription_valid = $subscription_status === null || in_array($subscription_status, ['active', 'pending-cancel']);
// Check domain activation if domain is provided
$is_domain_active = true;
if ($domain) {
global $wpdb;
$table = $wpdb->prefix . self::$activations_table;
$activation = $wpdb->get_var($wpdb->prepare(
"SELECT id FROM $table WHERE license_id = %d AND domain = %s AND status = 'active' LIMIT 1",
$license['id'],
$domain
));
if (!$activation) {
$is_domain_active = false;
}
}
if ($domain && !$is_domain_active) {
return [
'valid' => false,
'error' => 'domain_not_activated',
'message' => __('License is not activated for this domain', 'woonoow'),
];
}
return [ return [
'valid' => $license['status'] === 'active' && !$is_expired && $is_subscription_valid, 'valid' => $license['status'] === 'active' && !$is_expired && $is_subscription_valid && $is_domain_active,
'license_key' => $license['license_key'], 'license_key' => $license['license_key'],
'status' => $license['status'], 'status' => $license['status'],
'activation_limit' => (int) $license['activation_limit'], 'activation_limit' => (int) $license['activation_limit'],
@@ -639,6 +662,7 @@ class LicenseManager
'is_expired' => $is_expired, 'is_expired' => $is_expired,
'subscription_status' => $subscription_status, 'subscription_status' => $subscription_status,
'subscription_active' => $is_subscription_valid, 'subscription_active' => $is_subscription_valid,
'domain_active' => $is_domain_active,
]; ];
} }

View File

@@ -127,10 +127,10 @@ class SoftwareManager
/** /**
* Check for updates * Check for updates
*/ */
public static function check_update($license_key, $slug, $current_version) public static function check_update($license_key, $slug, $current_version, $site_url = null)
{ {
// Validate license // Validate license
$license_validation = LicenseManager::validate($license_key); $license_validation = LicenseManager::validate($license_key, $site_url);
if (!$license_validation['valid']) { if (!$license_validation['valid']) {
return [ return [
@@ -255,10 +255,21 @@ class SoftwareManager
global $wpdb; global $wpdb;
$table = $wpdb->prefix . self::$versions_table; $table = $wpdb->prefix . self::$versions_table;
return $wpdb->get_results($wpdb->prepare( $results = $wpdb->get_results($wpdb->prepare(
"SELECT * FROM $table WHERE product_id = %d ORDER BY release_date DESC", "SELECT * FROM $table WHERE product_id = %d ORDER BY release_date DESC",
$product_id $product_id
), ARRAY_A); ), ARRAY_A);
if ($results) {
foreach ($results as &$row) {
$decoded_changelog = json_decode($row['changelog'], true);
if (json_last_error() === JSON_ERROR_NONE) {
$row['changelog'] = $decoded_changelog;
}
}
}
return $results;
} }
/** /**
@@ -308,6 +319,39 @@ class SoftwareManager
return $wpdb->insert_id; return $wpdb->insert_id;
} }
/**
* Update a version
*/
public static function update_version($version_id, $product_id, $version, $changelog = '', $set_current = false)
{
global $wpdb;
$table = $wpdb->prefix . self::$versions_table;
// Reset other current versions if this one is set to current
if ($set_current) {
$wpdb->update($table, ['is_current' => 0], ['product_id' => $product_id]);
}
// Update version
$wpdb->update($table, [
'version' => $version,
'changelog' => $changelog,
'is_current' => $set_current ? 1 : 0,
], [
'id' => $version_id,
'product_id' => $product_id
]);
// Update product meta
if ($set_current) {
update_post_meta($product_id, '_woonoow_software_current_version', $version);
}
do_action('woonoow/software/version_updated', $version_id, $product_id, $version);
return true;
}
/** /**
* Generate secure download token * Generate secure download token
*/ */

View File

@@ -0,0 +1,123 @@
<?php
/**
* Gateway Capabilities — Subscription auto-renew declaration
*
* Single source of truth for "can this payment gateway auto-debit a
* subscription renewal, or does it fall through to manual?"
*
* Storage:
* wp_option('woonoow_gateway_subscription_capabilities')
* shape: [ '<gateway_id>' => [ 'subscription_auto_renew' => bool, ... ], ... ]
*
* Defaults are explicit per gateway ID so the merchant sees a meaningful
* matrix out of the box. The defaults reflect the regulatory reality
* discussed in SUBSCRIPTION_MODULE_AUDIT.md §9.5:
* - Indonesian VA/QRIS/e-wallet gateways: false (no recurring)
* - Indonesian credit-card gateways: false (BI/PCI-DSS re-auth)
* - PayPal/Stripe/Dodo: true ONLY when the merchant has a working
* adapter that implements process_subscription_renewal_payment;
* we still default to true because the integration is the common
* case in WooNooW's target market.
*
* The default for any *unknown* gateway is `false` — the safe side.
*
* @package WooNooW\Modules\Subscription
*/
namespace WooNooW\Modules\Subscription;
if (!defined('ABSPATH')) exit;
class GatewayCapabilities
{
const OPTION_KEY = 'woonoow_gateway_subscription_capabilities';
/**
* Built-in safe defaults. Keyed by WooCommerce payment-gateway ID.
*
* Filter 'woonoow_gateway_subscription_capabilities' lets adapters
* and third-party code extend this list at boot time.
*/
public static function default_capabilities(): array
{
return [
// Global auto-debit-capable gateways
'paypal' => ['subscription_auto_renew' => true],
'stripe' => ['subscription_auto_renew' => true],
'stripe_cc' => ['subscription_auto_renew' => true],
'stripe_sepa' => ['subscription_auto_renew' => true],
'dodo' => ['subscription_auto_renew' => true],
// Indonesian manual-only gateways (VA/QRIS/e-wallet/CC re-auth)
'tripay' => ['subscription_auto_renew' => false],
'midtrans' => ['subscription_auto_renew' => false],
'xendit' => ['subscription_auto_renew' => false],
'doku' => ['subscription_auto_renew' => false],
'duitku' => ['subscription_auto_renew' => false],
// Cheques / offline / no auto-debit
'cheque' => ['subscription_auto_renew' => false],
'bacs' => ['subscription_auto_renew' => false],
'cod' => ['subscription_auto_renew' => false],
];
}
/**
* Read the merged capability map: defaults < stored < filter.
* Always returns a fully-populated array (missing keys default to false).
*/
public static function all(): array
{
$stored = get_option(self::OPTION_KEY, []);
if (!is_array($stored)) {
$stored = [];
}
$merged = array_merge(self::default_capabilities(), $stored);
$merged = (array) apply_filters('woonoow_gateway_subscription_capabilities', $merged);
return $merged;
}
/**
* Single-gateway capability lookup.
* Returns true ONLY if explicitly declared true. Anything else is false.
*/
public static function supports_auto_renew(string $gateway_id): bool
{
$gateway_id = sanitize_key($gateway_id);
if ($gateway_id === '') {
return false;
}
$caps = self::all();
if (!isset($caps[$gateway_id])) {
return false; // unknown gateway: safe default
}
return !empty($caps[$gateway_id]['subscription_auto_renew']);
}
/**
* Site-level kill switch. When true, EVERY gateway is treated as
* manual regardless of per-gateway capability.
*/
public static function force_manual(): bool
{
$settings = \WooNooW\Core\ModuleRegistry::get_settings('subscription');
return !empty($settings['force_manual_renewal']);
}
/**
* The single decision function the renewal flow should call.
* Combines: kill switch > gateway capability.
*/
public static function should_attempt_auto_renew(string $gateway_id): bool
{
if (self::force_manual()) {
return false;
}
return self::supports_auto_renew($gateway_id);
}
}

View File

@@ -63,6 +63,7 @@ class SubscriptionManager
payment_meta LONGTEXT, payment_meta LONGTEXT,
cancel_reason TEXT DEFAULT NULL, cancel_reason TEXT DEFAULT NULL,
pause_count INT UNSIGNED DEFAULT 0, pause_count INT UNSIGNED DEFAULT 0,
paused_at DATETIME DEFAULT NULL,
failed_payment_count INT UNSIGNED DEFAULT 0, failed_payment_count INT UNSIGNED DEFAULT 0,
reminder_sent_at DATETIME DEFAULT NULL, reminder_sent_at DATETIME DEFAULT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP, created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
@@ -87,11 +88,50 @@ class SubscriptionManager
require_once ABSPATH . 'wp-admin/includes/upgrade.php'; require_once ABSPATH . 'wp-admin/includes/upgrade.php';
dbDelta($sql_subscriptions); dbDelta($sql_subscriptions);
dbDelta($sql_orders); dbDelta($sql_orders);
// Runtime migration: add paused_at to existing installations.
// dbDelta does not add new columns to existing tables.
if ($wpdb->get_var("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = '$table_subscriptions' AND COLUMN_NAME = 'paused_at'") == 0) {
$wpdb->query("ALTER TABLE $table_subscriptions ADD COLUMN paused_at DATETIME DEFAULT NULL AFTER pause_count");
}
}
/**
* Read a subscription meta key with variation-first, parent-fallback resolution.
*
* M1 — A variable product can have a "License 1-year" variation (period=year,
* length=1) and a "License 5-year" variation (period=year, length=5) living
* as siblings on the same parent product. The merchant authors those values
* per-variation. We must read the variation value first, then fall back to
* the parent if the variation didn't set it.
*
* An empty string and the literal `false` (post-meta "missing") are both
* treated as "not set". Only a real value returns.
*
* @param string $key Post meta key, e.g. '_woonoow_subscription_period'.
* @param int $variation_id Variation ID, or 0 if no variation.
* @param int $product_id Parent product ID.
* @param mixed $default Returned if neither variation nor parent has a value.
* @return mixed
*/
public static function get_subscription_meta($key, $variation_id, $product_id, $default = null)
{
if ($variation_id) {
$v = get_post_meta($variation_id, $key, true);
if ($v !== '' && $v !== false && $v !== null) {
return $v;
}
}
$p = get_post_meta($product_id, $key, true);
if ($p !== '' && $p !== false && $p !== null) {
return $p;
}
return $default;
} }
/** /**
* Create subscription from order item * Create subscription from order item
* *
* @param \WC_Order $order * @param \WC_Order $order
* @param \WC_Order_Item_Product $item * @param \WC_Order_Item_Product $item
* @return int|false Subscription ID or false on failure * @return int|false Subscription ID or false on failure
@@ -109,11 +149,13 @@ class SubscriptionManager
return false; return false;
} }
// Get subscription settings from product // M1 — Read subscription meta variation-first, then fall back to parent.
$billing_period = get_post_meta($product_id, '_woonoow_subscription_period', true) ?: 'month'; // Variation-level overrides let a merchant sell e.g. "License 1-year" and
$billing_interval = absint(get_post_meta($product_id, '_woonoow_subscription_interval', true)) ?: 1; // "License 5-year" as variations of one variable product.
$trial_days = absint(get_post_meta($product_id, '_woonoow_subscription_trial_days', true)); $billing_period = self::get_subscription_meta('_woonoow_subscription_period', $variation_id, $product_id, 'month');
$subscription_length = absint(get_post_meta($product_id, '_woonoow_subscription_length', true)); $billing_interval = absint(self::get_subscription_meta('_woonoow_subscription_interval', $variation_id, $product_id, 1));
$trial_days = absint(self::get_subscription_meta('_woonoow_subscription_trial_days', $variation_id, $product_id, 0));
$subscription_length = absint(self::get_subscription_meta('_woonoow_subscription_length', $variation_id, $product_id, 0));
// Calculate dates // Calculate dates
$now = current_time('mysql'); $now = current_time('mysql');
@@ -285,26 +327,52 @@ class SubscriptionManager
$where = "WHERE 1=1"; $where = "WHERE 1=1";
$params = []; $params = [];
$joins = "";
if ($args['status']) { if ($args['status']) {
$where .= " AND status = %s"; $where .= " AND s.status = %s";
$params[] = $args['status']; $params[] = $args['status'];
} }
if ($args['product_id']) { if ($args['product_id']) {
$where .= " AND product_id = %d"; $where .= " AND s.product_id = %d";
$params[] = $args['product_id']; $params[] = $args['product_id'];
} }
if ($args['user_id']) { if ($args['user_id']) {
$where .= " AND user_id = %d"; $where .= " AND s.user_id = %d";
$params[] = $args['user_id']; $params[] = $args['user_id'];
} }
$order = "ORDER BY created_at DESC"; // M4 — Free-text search. The user types something; we match on:
// - numeric input → subscriptions.id exactly
// - any input → user_email / display_name / user_login LIKE
// The customer-facing word "search" maps to a JOIN on wp_users. We don't
// attempt to LIKE-match product name here because that would require a
// second JOIN on wp_posts and product name relevance is rarely what the
// admin types into this box — they want to find a specific customer's
// subscription.
$search = is_string($args['search']) ? trim($args['search']) : '';
if ($search !== '') {
$joins .= " LEFT JOIN {$wpdb->users} u ON u.ID = s.user_id";
if (ctype_digit($search)) {
$where .= " AND (s.id = %d OR u.user_email LIKE %s OR u.display_name LIKE %s)";
$params[] = (int) $search;
$params[] = '%' . $wpdb->esc_like($search) . '%';
$params[] = '%' . $wpdb->esc_like($search) . '%';
} else {
$where .= " AND (u.user_email LIKE %s OR u.display_name LIKE %s OR u.user_login LIKE %s)";
$like = '%' . $wpdb->esc_like($search) . '%';
$params[] = $like;
$params[] = $like;
$params[] = $like;
}
}
$order = "ORDER BY s.created_at DESC";
$limit = "LIMIT " . intval($args['limit']) . " OFFSET " . intval($args['offset']); $limit = "LIMIT " . intval($args['limit']) . " OFFSET " . intval($args['offset']);
$sql = "SELECT * FROM " . self::$table_subscriptions . " $where $order $limit"; $sql = "SELECT s.* FROM " . self::$table_subscriptions . " s $joins $where $order $limit";
if (!empty($params)) { if (!empty($params)) {
$sql = $wpdb->prepare($sql, $params); $sql = $wpdb->prepare($sql, $params);
@@ -315,7 +383,10 @@ class SubscriptionManager
/** /**
* Count subscriptions * Count subscriptions
* *
* M4 — supports the same `search` semantics as `get_all` so the pagination
* total matches the filtered result set.
*
* @param array $args * @param array $args
* @return int * @return int
*/ */
@@ -325,13 +396,31 @@ class SubscriptionManager
$where = "WHERE 1=1"; $where = "WHERE 1=1";
$params = []; $params = [];
$joins = "";
if (!empty($args['status'])) { if (!empty($args['status'])) {
$where .= " AND status = %s"; $where .= " AND s.status = %s";
$params[] = $args['status']; $params[] = $args['status'];
} }
$sql = "SELECT COUNT(*) FROM " . self::$table_subscriptions . " $where"; $search = is_string($args['search']) ? trim($args['search']) : '';
if ($search !== '') {
$joins .= " LEFT JOIN {$wpdb->users} u ON u.ID = s.user_id";
if (ctype_digit($search)) {
$where .= " AND (s.id = %d OR u.user_email LIKE %s OR u.display_name LIKE %s)";
$params[] = (int) $search;
$params[] = '%' . $wpdb->esc_like($search) . '%';
$params[] = '%' . $wpdb->esc_like($search) . '%';
} else {
$where .= " AND (u.user_email LIKE %s OR u.display_name LIKE %s OR u.user_login LIKE %s)";
$like = '%' . $wpdb->esc_like($search) . '%';
$params[] = $like;
$params[] = $like;
$params[] = $like;
}
}
$sql = "SELECT COUNT(*) FROM " . self::$table_subscriptions . " s $joins $where";
if (!empty($params)) { if (!empty($params)) {
$sql = $wpdb->prepare($sql, $params); $sql = $wpdb->prepare($sql, $params);
@@ -437,11 +526,12 @@ class SubscriptionManager
$updated = $wpdb->update( $updated = $wpdb->update(
self::$table_subscriptions, self::$table_subscriptions,
[ [
'status' => 'on-hold', 'status' => 'on-hold',
'pause_count' => $subscription->pause_count + 1, 'pause_count' => $subscription->pause_count + 1,
'paused_at' => current_time('mysql'),
], ],
['id' => $subscription_id], ['id' => $subscription_id],
['%s', '%d'], ['%s', '%d', '%s'],
['%d'] ['%d']
); );
@@ -479,6 +569,8 @@ class SubscriptionManager
$subscription->billing_interval $subscription->billing_interval
); );
$update_data['next_payment_date'] = $next_payment; $update_data['next_payment_date'] = $next_payment;
$update_data['paused_at'] = null;
$format[] = '%s';
$format[] = '%s'; $format[] = '%s';
} }
@@ -505,11 +597,17 @@ class SubscriptionManager
*/ */
/** /**
* Process renewal for a subscription * Process renewal for a subscription
* *
* @param int $subscription_id * M2 — `$charge_now = true` is the admin "charge immediately" flag. It
* @return bool * bypasses the per-gateway capability gate so the auto-debit attempt is
* made even on normally-manual gateways. Use this for the ad-hoc admin
* "charge now" button, not for cron-driven renewals.
*
* @param int $subscription_id
* @param bool $charge_now M2: bypass capability gate, never fall through to manual.
* @return bool|array
*/ */
public static function renew($subscription_id) public static function renew($subscription_id, $charge_now = false)
{ {
global $wpdb; global $wpdb;
@@ -518,13 +616,15 @@ class SubscriptionManager
return false; return false;
} }
// Check for existing pending renewal order to prevent duplicates // Check for existing pending/awaiting/failed renewal order to prevent duplicates.
// A previously failed renewal must also short-circuit so the customer retries the same
// order instead of accumulating duplicate renewal orders on the subscription.
$existing_pending = $wpdb->get_row($wpdb->prepare( $existing_pending = $wpdb->get_row($wpdb->prepare(
"SELECT so.order_id FROM " . self::$table_subscription_orders . " so "SELECT so.order_id FROM " . self::$table_subscription_orders . " so
JOIN {$wpdb->posts} p ON so.order_id = p.ID JOIN {$wpdb->posts} p ON so.order_id = p.ID
WHERE so.subscription_id = %d WHERE so.subscription_id = %d
AND so.order_type = 'renewal' AND so.order_type = 'renewal'
AND p.post_status IN ('wc-pending', 'pending', 'wc-on-hold', 'on-hold')", AND p.post_status IN ('wc-pending', 'pending', 'wc-on-hold', 'on-hold', 'wc-failed', 'failed')",
$subscription_id $subscription_id
)); ));
@@ -542,7 +642,7 @@ class SubscriptionManager
// Process payment // Process payment
// Result can be: true (paid), false (failed), or 'manual' (waiting for payment) // Result can be: true (paid), false (failed), or 'manual' (waiting for payment)
$payment_result = self::process_renewal_payment($subscription, $renewal_order); $payment_result = self::process_renewal_payment($subscription, $renewal_order, $charge_now);
if ($payment_result === true) { if ($payment_result === true) {
self::handle_renewal_success($subscription_id, $renewal_order); self::handle_renewal_success($subscription_id, $renewal_order);
@@ -596,12 +696,20 @@ class SubscriptionManager
return false; return false;
} }
// Add product // Add product. H4 — price-sync policy: by default we honor the customer's
// stored recurring_amount (grandfather them at the original price). The merchant
// can flip `price_sync_on_renewal` to 'use_current_product_price' to always bill
// the latest price on every renewal.
$product = wc_get_product($subscription->variation_id ?: $subscription->product_id); $product = wc_get_product($subscription->variation_id ?: $subscription->product_id);
if ($product) { if ($product) {
$settings = ModuleRegistry::get_settings('subscription');
$price_mode = $settings['price_sync_on_renewal'] ?? 'use_stored';
$line_total = ($price_mode === 'use_current_product_price' && $product->get_price() !== '')
? (float) $product->get_price()
: (float) $subscription->recurring_amount;
$renewal_order->add_product($product, 1, [ $renewal_order->add_product($product, 1, [
'total' => $subscription->recurring_amount, 'total' => $line_total,
'subtotal' => $subscription->recurring_amount, 'subtotal' => $line_total,
]); ]);
} }
@@ -630,19 +738,22 @@ class SubscriptionManager
/** /**
* Process payment for renewal order * Process payment for renewal order
* *
* @param object $subscription * M2 — `$force = true` is used by the admin "charge now" button. It
* @param \WC_Order $order * bypasses the GatewayCapabilities gate: the admin has explicitly
* @return bool * declared intent to charge, so we attempt the auto-debit path even on
*/ * gateways that are normally manual-only. If the gateway does not
/** * implement `process_subscription_renewal_payment` and no external
* Process payment for renewal order * handler picks it up via filter, we fail loudly (return `false`) rather
* * than silently creating a manual order — the admin expects an immediate
* @param object $subscription * charge, not a payment-link email.
*
* @param object $subscription
* @param \WC_Order $order * @param \WC_Order $order
* @param bool $force M2: bypass capability gate; never fall through to manual.
* @return bool|string True if paid, false if failed, 'manual' if waiting * @return bool|string True if paid, false if failed, 'manual' if waiting
*/ */
private static function process_renewal_payment($subscription, $order) private static function process_renewal_payment($subscription, $order, $force = false)
{ {
// Allow plugins to override payment processing completely // Allow plugins to override payment processing completely
// Return true/false/'manual' to bypass default logic // Return true/false/'manual' to bypass default logic
@@ -663,14 +774,26 @@ class SubscriptionManager
$gateway = $gateways[$gateway_id]; $gateway = $gateways[$gateway_id];
// 1. Try Auto-Debit if supported // 0. Per-gateway capability gate (§9 of the audit).
if (method_exists($gateway, 'process_subscription_renewal_payment')) { // If the gateway is not declared to support subscription auto-renew (or the kill
$result = $gateway->process_subscription_renewal_payment($order, $subscription); // switch is on), we skip the auto-debit attempt entirely and fall through to
if (!is_wp_error($result) && $result) { // manual. The capability table is the merchant-visible source of truth — PHP
return true; // introspection alone is no longer authoritative.
//
// M2 — `force` skips this gate. Admin has explicitly opted in to attempting the
// charge, so we ignore the capability declaration.
$capability_ok = $force || GatewayCapabilities::should_attempt_auto_renew($gateway_id);
if ($capability_ok) {
// 1. Try Auto-Debit if supported by the gateway implementation
if (method_exists($gateway, 'process_subscription_renewal_payment')) {
$result = $gateway->process_subscription_renewal_payment($order, $subscription);
if (!is_wp_error($result) && $result) {
return true;
}
// If explicit failure from auto-debit, return false (will trigger retry logic)
return false;
} }
// If explicit failure from auto-debit, return false (will trigger retry logic)
return false;
} }
// 2. Allow other plugins to handle auto-debit via filter (e.g. Stripe/PayPal adapters) // 2. Allow other plugins to handle auto-debit via filter (e.g. Stripe/PayPal adapters)
@@ -680,6 +803,15 @@ class SubscriptionManager
} }
// 3. Fallback: Manual Payment // 3. Fallback: Manual Payment
// M2 — In force mode, the admin said "charge now". If we got here, the gateway
// does not implement auto-debit and no external handler picked it up. Creating
// a manual order would silently contradict the admin's intent. Fail loudly so
// the admin sees the charge could not be processed.
if ($force) {
$order->update_status('failed', __('Admin "charge now" requested, but gateway does not support auto-debit', 'woonoow'));
return false;
}
// Set order to pending-payment // Set order to pending-payment
$order->update_status('pending', __('Awaiting manual renewal payment', 'woonoow')); $order->update_status('pending', __('Awaiting manual renewal payment', 'woonoow'));

View File

@@ -38,8 +38,18 @@ class SubscriptionModule
add_action('woocommerce_order_status_completed', [__CLASS__, 'maybe_create_subscription'], 10, 1); add_action('woocommerce_order_status_completed', [__CLASS__, 'maybe_create_subscription'], 10, 1);
add_action('woocommerce_order_status_processing', [__CLASS__, 'maybe_create_subscription'], 10, 1); add_action('woocommerce_order_status_processing', [__CLASS__, 'maybe_create_subscription'], 10, 1);
// Hook into order status change to handle manual renewal payments // Hook into order status change to handle manual renewal payments and status sync
add_action('woocommerce_order_status_changed', [__CLASS__, 'on_order_status_changed'], 10, 3); add_action('woocommerce_order_status_changed', [__CLASS__, 'on_order_status_changed'], 10, 3);
// Hook into entity deletions for cleanup and state sync
add_action('woocommerce_trash_order', [__CLASS__, 'on_order_deleted']);
add_action('woocommerce_delete_order', [__CLASS__, 'on_order_deleted']);
add_action('trashed_post', [__CLASS__, 'on_post_deleted']);
add_action('deleted_post', [__CLASS__, 'on_post_deleted']);
add_action('delete_user', [__CLASS__, 'on_user_deleted']);
// Prevent guest checkout for subscriptions
add_filter('woocommerce_add_to_cart_validation', [__CLASS__, 'validate_subscription_add_to_cart'], 10, 3);
// Modify add to cart button text for subscription products // Modify add to cart button text for subscription products
add_filter('woocommerce_product_single_add_to_cart_text', [__CLASS__, 'subscription_add_to_cart_text'], 10, 2); add_filter('woocommerce_product_single_add_to_cart_text', [__CLASS__, 'subscription_add_to_cart_text'], 10, 2);
@@ -264,6 +274,24 @@ class SubscriptionModule
$order->save(); $order->save();
} }
/**
* Prevent guest checkout for subscriptions
*/
public static function validate_subscription_add_to_cart($passed, $product_id, $quantity) {
if (!ModuleRegistry::is_enabled('subscription')) {
return $passed;
}
if (get_post_meta($product_id, '_woonoow_subscription_enabled', true) === 'yes') {
if (!is_user_logged_in()) {
wc_add_notice(__('You must be logged in to purchase a subscription.', 'woonoow'), 'error');
return false;
}
}
return $passed;
}
/** /**
* Modify add to cart button text for subscription products * Modify add to cart button text for subscription products
*/ */
@@ -275,6 +303,14 @@ class SubscriptionModule
$product_id = $product->get_id(); $product_id = $product->get_id();
if (get_post_meta($product_id, '_woonoow_subscription_enabled', true) === 'yes') { if (get_post_meta($product_id, '_woonoow_subscription_enabled', true) === 'yes') {
// Guests cannot have subscriptions — create_from_order() rejects guest orders silently
// (H6). Show the standard add-to-cart text and let the regular checkout flow handle
// guest sign-up. The subscription will only be created if/when the customer converts
// to a user. We do NOT advertise a subscription capability the system cannot honor.
if (!is_user_logged_in()) {
return $text;
}
$settings = ModuleRegistry::get_settings('subscription'); $settings = ModuleRegistry::get_settings('subscription');
return $settings['button_text_subscribe'] ?? __('Subscribe Now', 'woonoow'); return $settings['button_text_subscribe'] ?? __('Subscribe Now', 'woonoow');
} }
@@ -532,7 +568,7 @@ class SubscriptionModule
} }
/** /**
* Handle manual renewal payment completion * Handle order status changes for both parent and renewal orders
*/ */
public static function on_order_status_changed($order_id, $old_status, $new_status) public static function on_order_status_changed($order_id, $old_status, $new_status)
{ {
@@ -540,24 +576,108 @@ class SubscriptionModule
return; return;
} }
if (!in_array($new_status, ['processing', 'completed'])) {
return;
}
// Check if this is a subscription renewal order
global $wpdb; global $wpdb;
$table_orders = $wpdb->prefix . 'woonoow_subscription_orders'; $table_orders = $wpdb->prefix . 'woonoow_subscription_orders';
$link = $wpdb->get_row($wpdb->prepare( // Find if this order is linked to any subscription
$links = $wpdb->get_results($wpdb->prepare(
"SELECT subscription_id, order_type FROM $table_orders WHERE order_id = %d", "SELECT subscription_id, order_type FROM $table_orders WHERE order_id = %d",
$order_id $order_id
)); ));
if ($link && $link->order_type === 'renewal') { if (empty($links)) {
$order = wc_get_order($order_id); return;
if ($order) { }
SubscriptionManager::handle_renewal_success($link->subscription_id, $order);
foreach ($links as $link) {
$subscription = SubscriptionManager::get($link->subscription_id);
if (!$subscription) continue;
if ($link->order_type === 'renewal') {
if (in_array($new_status, ['processing', 'completed'])) {
$order = wc_get_order($order_id);
if ($order) {
SubscriptionManager::handle_renewal_success($link->subscription_id, $order);
}
} elseif ($new_status === 'failed') {
SubscriptionManager::handle_renewal_failure($link->subscription_id);
} elseif ($new_status === 'cancelled') {
SubscriptionManager::update_status($link->subscription_id, 'cancelled', 'renewal_order_cancelled');
} elseif ($new_status === 'refunded') {
SubscriptionManager::update_status($link->subscription_id, 'on-hold', 'renewal_order_refunded');
}
} elseif ($link->order_type === 'parent') {
if (in_array($new_status, ['refunded', 'cancelled'])) {
SubscriptionManager::update_status($link->subscription_id, 'cancelled', 'parent_order_' . $new_status);
} elseif ($new_status === 'on-hold') {
SubscriptionManager::update_status($link->subscription_id, 'on-hold', 'parent_order_on_hold');
}
} }
} }
} }
/**
* Handle order trashing/deletion
*/
public static function on_order_deleted($order_id)
{
global $wpdb;
$table_orders = $wpdb->prefix . 'woonoow_subscription_orders';
$links = $wpdb->get_results($wpdb->prepare(
"SELECT subscription_id, order_type FROM $table_orders WHERE order_id = %d",
$order_id
));
foreach ($links as $link) {
if ($link->order_type === 'parent') {
SubscriptionManager::update_status($link->subscription_id, 'cancelled', 'parent_order_deleted');
} elseif ($link->order_type === 'renewal') {
SubscriptionManager::update_status($link->subscription_id, 'on-hold', 'renewal_order_deleted');
}
}
}
/**
* Handle product trashing/deletion
*/
public static function on_post_deleted($post_id)
{
if (get_post_type($post_id) !== 'product') {
return;
}
global $wpdb;
$table_subs = $wpdb->prefix . 'woonoow_subscriptions';
// Find active/on-hold subscriptions for this product
$affected = $wpdb->get_col($wpdb->prepare(
"SELECT id FROM $table_subs WHERE product_id = %d AND status IN ('active', 'on-hold', 'pending')",
$post_id
));
foreach ($affected as $sub_id) {
SubscriptionManager::update_status($sub_id, 'on-hold', 'product_deleted');
// Fire an action so merchants can hook in and get alerted
do_action('woonoow/subscription/product_deleted_alert', $sub_id, $post_id);
}
}
/**
* Handle user deletion
*/
public static function on_user_deleted($user_id)
{
global $wpdb;
$table_subs = $wpdb->prefix . 'woonoow_subscriptions';
$affected = $wpdb->get_col($wpdb->prepare(
"SELECT id FROM $table_subs WHERE user_id = %d AND status != 'cancelled'",
$user_id
));
foreach ($affected as $sub_id) {
SubscriptionManager::update_status($sub_id, 'cancelled', 'user_deleted');
}
}
} }

View File

@@ -32,6 +32,16 @@ class SubscriptionScheduler
*/ */
const REMINDER_HOOK = 'woonoow_send_renewal_reminders'; const REMINDER_HOOK = 'woonoow_send_renewal_reminders';
/**
* Cron hook for retrying unpaid manual renewals (H5).
*/
const UNPAID_RETRY_HOOK = 'woonoow_retry_unpaid_renewals';
/**
* Cron hook for auto-resuming subscriptions paused beyond the allowed duration.
*/
const PAUSE_EXPIRY_HOOK = 'woonoow_check_pause_expirations';
/** /**
* Initialize the scheduler * Initialize the scheduler
*/ */
@@ -41,6 +51,8 @@ class SubscriptionScheduler
add_action(self::RENEWAL_HOOK, [__CLASS__, 'process_renewals']); add_action(self::RENEWAL_HOOK, [__CLASS__, 'process_renewals']);
add_action(self::EXPIRY_HOOK, [__CLASS__, 'check_expirations']); add_action(self::EXPIRY_HOOK, [__CLASS__, 'check_expirations']);
add_action(self::REMINDER_HOOK, [__CLASS__, 'send_reminders']); add_action(self::REMINDER_HOOK, [__CLASS__, 'send_reminders']);
add_action(self::UNPAID_RETRY_HOOK, [__CLASS__, 'retry_unpaid_renewals']);
add_action(self::PAUSE_EXPIRY_HOOK, [__CLASS__, 'check_pause_expirations']);
// Schedule cron events if not already scheduled // Schedule cron events if not already scheduled
self::schedule_events(); self::schedule_events();
@@ -65,6 +77,14 @@ class SubscriptionScheduler
if (!wp_next_scheduled(self::REMINDER_HOOK)) { if (!wp_next_scheduled(self::REMINDER_HOOK)) {
wp_schedule_event(time(), 'daily', self::REMINDER_HOOK); wp_schedule_event(time(), 'daily', self::REMINDER_HOOK);
} }
if (!wp_next_scheduled(self::UNPAID_RETRY_HOOK)) {
wp_schedule_event(time(), 'twicedaily', self::UNPAID_RETRY_HOOK);
}
if (!wp_next_scheduled(self::PAUSE_EXPIRY_HOOK)) {
wp_schedule_event(time(), 'daily', self::PAUSE_EXPIRY_HOOK);
}
} }
/** /**
@@ -75,6 +95,8 @@ class SubscriptionScheduler
wp_clear_scheduled_hook(self::RENEWAL_HOOK); wp_clear_scheduled_hook(self::RENEWAL_HOOK);
wp_clear_scheduled_hook(self::EXPIRY_HOOK); wp_clear_scheduled_hook(self::EXPIRY_HOOK);
wp_clear_scheduled_hook(self::REMINDER_HOOK); wp_clear_scheduled_hook(self::REMINDER_HOOK);
wp_clear_scheduled_hook(self::UNPAID_RETRY_HOOK);
wp_clear_scheduled_hook(self::PAUSE_EXPIRY_HOOK);
} }
/** /**
@@ -240,7 +262,7 @@ class SubscriptionScheduler
/** /**
* Schedule a retry for failed payment * Schedule a retry for failed payment
* *
* @param int $subscription_id * @param int $subscription_id
*/ */
public static function schedule_retry($subscription_id) public static function schedule_retry($subscription_id)
@@ -260,4 +282,132 @@ class SubscriptionScheduler
); );
} }
} }
/**
* H5 — Find subscriptions that are on-hold because a manual renewal order
* was created and never paid. Send a re-notification once per 24h. After
* `unpaid_renewal_max_age_days` (default 7), auto-cancel to prevent
* indefinite on-hold state. Auto-cancel is the last-resort safety net;
* the admin can resume manually at any time.
*/
public static function retry_unpaid_renewals()
{
global $wpdb;
if (!ModuleRegistry::is_enabled('subscription')) {
return;
}
$settings = ModuleRegistry::get_settings('subscription');
$max_age_days = isset($settings['unpaid_renewal_max_age_days'])
? max(1, (int) $settings['unpaid_renewal_max_age_days'])
: 7;
$table_subs = $wpdb->prefix . 'woonoow_subscriptions';
$table_orders = $wpdb->prefix . 'woonoow_subscription_orders';
$posts = $wpdb->posts;
$now = current_time('mysql');
$min_age = date('Y-m-d H:i:s', strtotime('-24 hours', strtotime($now)));
$max_age_cutoff = date('Y-m-d H:i:s', strtotime("-{$max_age_days} days", strtotime($now)));
$reminder_threshold = date('Y-m-d H:i:s', strtotime('-24 hours', strtotime($now)));
// Find (subscription, order) pairs where the renewal order is still unpaid
// and the order was created at least 24h ago. We rate-limit per-order by
// storing the last-notice timestamp in order meta.
$candidates = $wpdb->get_results($wpdb->prepare(
"SELECT s.id AS subscription_id, o.order_id
FROM $table_subs s
JOIN $table_orders o ON o.subscription_id = s.id AND o.order_type = 'renewal'
JOIN $posts p ON p.ID = o.order_id
WHERE s.status = 'on-hold'
AND p.post_status IN ('wc-pending', 'pending', 'wc-failed', 'failed')
AND p.post_date <= %s
AND p.post_date >= %s",
$min_age,
$max_age_cutoff
));
foreach ($candidates as $row) {
$order = wc_get_order($row->order_id);
if (!$order) {
continue;
}
// Per-order rate limit: don't re-notify more than once per 24h.
$last_notice = (string) $order->get_meta('_woonoow_unpaid_notice_at', true);
if ($last_notice !== '' && strtotime($last_notice) > strtotime($reminder_threshold)) {
continue;
}
$subscription = SubscriptionManager::get($row->subscription_id);
if (!$subscription) {
continue;
}
// Re-fire the same notification that fired at first renewal. Email
// templates registered for `renewal_payment_due` will be sent.
do_action('woonoow/subscription/renewal_payment_due', $subscription->id, $order);
$order->update_meta_data('_woonoow_unpaid_notice_at', $now);
$order->save();
}
// Auto-cancel: anything older than the cutoff that is still on-hold gets
// cancelled outright. The admin can override by resuming manually.
$auto_cancel = $wpdb->get_results($wpdb->prepare(
"SELECT id FROM $table_subs
WHERE status = 'on-hold'
AND next_payment_date IS NOT NULL
AND next_payment_date <= %s",
$max_age_cutoff
));
foreach ($auto_cancel as $row) {
SubscriptionManager::update_status($row->id, 'cancelled', 'unpaid_renewal_timeout');
do_action('woonoow/subscription/cancelled', $row->id, 'unpaid_renewal_timeout');
}
}
/**
* Auto-resume subscriptions that have been paused beyond the merchant-configured
* maximum pause duration. Runs daily.
*
* Setting: `max_pause_duration_days` (int, 0 = disabled/unlimited).
* When a subscription hits the limit it is automatically resumed, giving the
* customer a fresh billing cycle from now.
*/
public static function check_pause_expirations()
{
global $wpdb;
if (!ModuleRegistry::is_enabled('subscription')) {
return;
}
$settings = ModuleRegistry::get_settings('subscription');
$max_days = isset($settings['max_pause_duration_days']) ? (int) $settings['max_pause_duration_days'] : 0;
// 0 means unlimited — feature is disabled.
if ($max_days <= 0) {
return;
}
$table = $wpdb->prefix . 'woonoow_subscriptions';
$cutoff = date('Y-m-d H:i:s', strtotime("-{$max_days} days"));
// Find on-hold subscriptions paused longer than the allowed duration.
$expired_pauses = $wpdb->get_results($wpdb->prepare(
"SELECT id FROM $table
WHERE status = 'on-hold'
AND paused_at IS NOT NULL
AND paused_at <= %s",
$cutoff
));
foreach ($expired_pauses as $row) {
$resumed = SubscriptionManager::resume($row->id);
if ($resumed) {
do_action('woonoow/subscription/auto_resumed', $row->id, 'max_pause_duration_exceeded');
}
}
}
} }

Some files were not shown because too many files have changed in this diff Show More