| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentCart\App\Modules\MCP\Tools; |
| 4 |
|
| 5 |
use FluentCart\App\Models\Order; |
| 6 |
use FluentCart\App\Models\Customer; |
| 7 |
use FluentCart\App\Models\Subscription; |
| 8 |
use FluentCart\App\Modules\MCP\AbilitiesRegistrar; |
| 9 |
use FluentCart\App\Modules\MCP\Support\MCPHelper; |
| 10 |
use FluentCart\App\Modules\MCP\Support\PermissionGate; |
| 11 |
use FluentCart\App\Services\DateTime\DateTime; |
| 12 |
use FluentCart\App\Services\Permission\PermissionManager; |
| 13 |
|
| 14 |
/** |
| 15 |
* Discovery tools — the agent's entry point into a FluentCart store. |
| 16 |
* |
| 17 |
* `get-store-context` is the documented "call this first" tool. One call tells |
| 18 |
* the agent who it is, what it's allowed to do, the store's money/time |
| 19 |
* conventions, headline numbers, and every valid enum value — so it never has |
| 20 |
* to guess a status string or invent a currency format. It's cached (60s) and |
| 21 |
* invalidated when reference data changes, because it's called every session. |
| 22 |
* |
| 23 |
* `list-reference-data` is the on-demand lookup for the heavier reference lists |
| 24 |
* (coupons, labels, tax/shipping config) the agent only sometimes needs — kept |
| 25 |
* OUT of the context payload so the first call stays lean. |
| 26 |
* |
| 27 |
* Parameter philosophy: get-store-context takes nothing (zero friction, it's |
| 28 |
* discovery). list-reference-data takes only `kinds[]` — the agent asks for |
| 29 |
* exactly the lists it needs, and we return only the kinds its role can see. |
| 30 |
*/ |
| 31 |
class ContextTools |
| 32 |
{ |
| 33 |
const CACHE_TTL = 60; |
| 34 |
|
| 35 |
const CACHE_PREFIX = 'fluent_cart_mcp_context_'; |
| 36 |
|
| 37 |
// The verified FluentCart domain enums. Hardcoded (with a filter override) |
| 38 |
// rather than scraped, so the agent always gets the complete valid set even |
| 39 |
// if a status currently has zero rows. |
| 40 |
const ENUMS = [ |
| 41 |
'order_statuses' => ['draft', 'pending', 'on-hold', 'processing', 'completed', 'canceled', 'failed', 'refunded', 'partial-refund'], |
| 42 |
// Kept in sync with Status::getPaymentStatuses(); 'authorized' is a valid |
| 43 |
// persisted status (card authorized, not yet captured) and must be listed |
| 44 |
// so clients can filter authorized orders through list-orders. |
| 45 |
'payment_statuses' => ['paid', 'pending', 'failed', 'refunded', 'partially_refunded', 'partially_paid', 'authorized'], |
| 46 |
// 'none' = no shipping required (e.g. digital orders); reported when the |
| 47 |
// stored value is empty. It is read-only — change-order-status won't set it. |
| 48 |
'shipping_statuses' => ['none', 'unshipped', 'shipped', 'delivered', 'unshippable'], |
| 49 |
'order_types' => ['payment', 'renewal', 'subscription'], |
| 50 |
'subscription_statuses' => ['active', 'trialing', 'paused', 'canceled', 'failing', 'expired', 'expiring', 'past_due', 'intended', 'pending', 'completed'], |
| 51 |
// installment = fixed-term split-pay plan (a lifetime license paid off in |
| 52 |
// a finite number of charges, bill_times > 0); recurring = open-ended |
| 53 |
// subscription (bill_times = 0). Derived from bill_times, never the title. |
| 54 |
'plan_types' => ['installment', 'recurring'], |
| 55 |
'billing_intervals' => ['daily', 'weekly', 'monthly', 'quarterly', 'half_yearly', 'yearly'], |
| 56 |
'fulfillment_types' => ['physical', 'digital'], |
| 57 |
'coupon_types' => ['fixed', 'percentage'], |
| 58 |
'order_modes' => ['live', 'test'], |
| 59 |
]; |
| 60 |
|
| 61 |
// Payment statuses that count as realized revenue. Centralized so every |
| 62 |
// tool (context, reports, aggregates) agrees on what "paid" means. |
| 63 |
const PAID_STATUSES = ['paid', 'partially_paid', 'partially_refunded']; |
| 64 |
|
| 65 |
/** |
| 66 |
* Ability definitions for this domain. The registrar merges every tool |
| 67 |
* class's definitions(), so a tool's schema lives next to its code. |
| 68 |
*/ |
| 69 |
public static function definitions() |
| 70 |
{ |
| 71 |
return [ |
| 72 |
'fluent-cart/get-store-context' => [ |
| 73 |
'label' => __('Get Store Context', 'fluent-cart'), |
| 74 |
'description' => __('START HERE — call once per session. Returns who you are and your permissions, the store currency/timezone conventions, headline stats, every valid enum value (order/payment/shipping/subscription statuses, intervals, types), and usage guidelines. Use this before any other tool so you never guess a status string or money format.', 'fluent-cart'), |
| 75 |
'input_schema' => [ |
| 76 |
'type' => 'object', |
| 77 |
'properties' => new \stdClass(), |
| 78 |
], |
| 79 |
'execute_callback' => [self::class, 'getContext'], |
| 80 |
'permission_callback' => function () { |
| 81 |
return PermissionGate::can('dashboard_stats/view') || PermissionGate::canAny(PermissionGate::readRoleCaps()); |
| 82 |
}, |
| 83 |
'annotations' => ['readonly' => true], |
| 84 |
], |
| 85 |
|
| 86 |
'fluent-cart/list-reference-data' => [ |
| 87 |
'label' => __('List Reference Data', 'fluent-cart'), |
| 88 |
'description' => __('On-demand lookup lists kept out of get-store-context to keep it lean: coupons, labels, gateways, tax_classes, shipping_zones, product_categories. Pass kinds[] with only what you need. Kinds your role cannot see are reported in meta.warnings, not dropped silently. The coupons kind is a capped snapshot (newest 200, each with times_used) — to filter by status/code, paginate, or find usable-now coupons, use list-coupons instead.', 'fluent-cart'), |
| 89 |
'input_schema' => [ |
| 90 |
'type' => 'object', |
| 91 |
'properties' => [ |
| 92 |
'kinds' => [ |
| 93 |
'type' => 'array', |
| 94 |
'description' => 'Which reference lists to return.', |
| 95 |
'items' => ['type' => 'string', 'enum' => ['coupons', 'labels', 'gateways', 'tax_classes', 'shipping_zones', 'product_categories']], |
| 96 |
], |
| 97 |
], |
| 98 |
'required' => ['kinds'], |
| 99 |
], |
| 100 |
'execute_callback' => [self::class, 'listReferenceData'], |
| 101 |
'permission_callback' => function () { |
| 102 |
return PermissionGate::canAny(PermissionGate::readRoleCaps()); |
| 103 |
}, |
| 104 |
'annotations' => ['readonly' => true], |
| 105 |
], |
| 106 |
]; |
| 107 |
} |
| 108 |
|
| 109 |
public static function getContext($params = []) |
| 110 |
{ |
| 111 |
$userId = get_current_user_id(); |
| 112 |
$cacheKey = self::CACHE_PREFIX . $userId; |
| 113 |
|
| 114 |
$cached = get_transient($cacheKey); |
| 115 |
if (is_array($cached)) { |
| 116 |
return $cached; |
| 117 |
} |
| 118 |
|
| 119 |
$context = self::buildContext($userId); |
| 120 |
set_transient($cacheKey, $context, self::CACHE_TTL); |
| 121 |
|
| 122 |
return $context; |
| 123 |
} |
| 124 |
|
| 125 |
private static function buildContext($userId) |
| 126 |
{ |
| 127 |
$user = get_user_by('ID', $userId); |
| 128 |
$isAdmin = $user && user_can($user, 'manage_options'); |
| 129 |
|
| 130 |
$you = [ |
| 131 |
'wp_user_id' => (int) $userId, |
| 132 |
'name' => $user ? $user->display_name : null, |
| 133 |
'email' => $user ? $user->user_email : null, |
| 134 |
'is_admin' => (bool) $isAdmin, |
| 135 |
'permissions' => array_values((array) PermissionManager::getUserPermissions()), |
| 136 |
]; |
| 137 |
|
| 138 |
$store = [ |
| 139 |
'name' => get_bloginfo('name'), |
| 140 |
'url' => site_url(), |
| 141 |
'version' => defined('FLUENTCART_VERSION') ? FLUENTCART_VERSION : null, |
| 142 |
'pro_active' => defined('FLUENT_CART_PRO') || defined('FLUENTCART_PRO_VERSION'), |
| 143 |
'currency' => MCPHelper::currencyContext(), |
| 144 |
'timezone' => wp_timezone_string(), |
| 145 |
'current_time' => MCPHelper::toIso8601(DateTime::gmtNow()), |
| 146 |
]; |
| 147 |
|
| 148 |
// Headline stats are dashboard data: gate them on dashboard_stats/view so |
| 149 |
// a narrow read role can still get context (enums, currency, permissions) |
| 150 |
// without seeing store-wide revenue/order/customer numbers. |
| 151 |
$canStats = PermissionGate::can('dashboard_stats/view'); |
| 152 |
$stats = $canStats ? self::buildStats() : null; |
| 153 |
|
| 154 |
return MCPHelper::envelope( |
| 155 |
$canStats ? self::summary($stats) : __('Store context loaded.', 'fluent-cart'), |
| 156 |
[ |
| 157 |
'you' => $you, |
| 158 |
'store' => $store, |
| 159 |
'stats' => $stats, |
| 160 |
'enums' => apply_filters('fluent_cart/mcp_enums', self::ENUMS), |
| 161 |
'reference_kinds' => self::referenceKinds(), |
| 162 |
'tool_index' => self::toolIndex(), |
| 163 |
'guidelines' => self::guidelines(), |
| 164 |
] |
| 165 |
); |
| 166 |
} |
| 167 |
|
| 168 |
/** |
| 169 |
* Headline numbers. Each metric is isolated in safeCount/safeSum so one |
| 170 |
* failing query (e.g. a model that doesn't exist on a given install) yields |
| 171 |
* null for that stat instead of breaking the whole discovery call. |
| 172 |
*/ |
| 173 |
private static function buildStats() |
| 174 |
{ |
| 175 |
$since30 = DateTime::gmtNow()->modify('-30 days')->format('Y-m-d H:i:s'); |
| 176 |
|
| 177 |
return [ |
| 178 |
'orders_total' => self::safeCount(function () { |
| 179 |
return Order::query()->count(); |
| 180 |
}), |
| 181 |
'orders_last_30d' => self::safeCount(function () use ($since30) { |
| 182 |
return Order::query()->where('created_at', '>=', $since30)->count(); |
| 183 |
}), |
| 184 |
'revenue_last_30d' => self::safeMoney(function () use ($since30) { |
| 185 |
return (int) Order::query() |
| 186 |
->whereIn('payment_status', self::PAID_STATUSES) |
| 187 |
->where('created_at', '>=', $since30) |
| 188 |
->sum('total_paid'); |
| 189 |
}), |
| 190 |
'customers_total' => self::safeCount(function () { |
| 191 |
return Customer::query()->count(); |
| 192 |
}), |
| 193 |
'active_subscriptions' => self::safeCount(function () { |
| 194 |
return Subscription::query()->where('status', 'active')->count(); |
| 195 |
}), |
| 196 |
'products_published' => self::safeCount(function () { |
| 197 |
if (!class_exists('\FluentCart\App\Models\Product')) { |
| 198 |
return null; |
| 199 |
} |
| 200 |
// post_type is pinned by the model's global scope; a literal |
| 201 |
// here (and the wrong singular one) would match nothing. |
| 202 |
return \FluentCart\App\Models\Product::query() |
| 203 |
->where('post_status', 'publish') |
| 204 |
->count(); |
| 205 |
}), |
| 206 |
]; |
| 207 |
} |
| 208 |
|
| 209 |
private static function safeCount(callable $fn) |
| 210 |
{ |
| 211 |
try { |
| 212 |
$val = $fn(); |
| 213 |
return $val === null ? null : (int) $val; |
| 214 |
} catch (\Throwable $e) { |
| 215 |
return null; |
| 216 |
} |
| 217 |
} |
| 218 |
|
| 219 |
private static function safeMoney(callable $fn) |
| 220 |
{ |
| 221 |
try { |
| 222 |
return MCPHelper::money((int) $fn()); |
| 223 |
} catch (\Throwable $e) { |
| 224 |
return null; |
| 225 |
} |
| 226 |
} |
| 227 |
|
| 228 |
/* translators: %1$s: revenue amount, %2$d: orders in 30 days, %3$d: total customers */ |
| 229 |
private static function summary($stats) |
| 230 |
{ |
| 231 |
$rev30 = isset($stats['revenue_last_30d']['display']) ? $stats['revenue_last_30d']['display'] : '—'; |
| 232 |
$orders30 = isset($stats['orders_last_30d']) ? (int) $stats['orders_last_30d'] : 0; |
| 233 |
$customers = isset($stats['customers_total']) ? (int) $stats['customers_total'] : 0; |
| 234 |
|
| 235 |
return sprintf( |
| 236 |
/* translators: %1$s: 30-day revenue, %2$d: 30-day order count, %3$d: total customers */ |
| 237 |
__('Store snapshot — last 30 days: %1$s across %2$d orders; %3$d customers total.', 'fluent-cart'), |
| 238 |
$rev30, |
| 239 |
$orders30, |
| 240 |
$customers |
| 241 |
); |
| 242 |
} |
| 243 |
|
| 244 |
/** Tells the agent what `kinds` it can pass to list-reference-data. */ |
| 245 |
private static function referenceKinds() |
| 246 |
{ |
| 247 |
return ['coupons', 'labels', 'gateways', 'tax_classes', 'shipping_zones', 'product_categories']; |
| 248 |
} |
| 249 |
|
| 250 |
/** |
| 251 |
* Task → tool routing table so an agent picks the right ability among ~30 |
| 252 |
* without trial and error, grouped by intent (discovery / find / load / |
| 253 |
* analytics / write). |
| 254 |
* |
| 255 |
* Derived from the LIVE registry so a newly registered tool can never |
| 256 |
* silently go missing — each is annotated with a curated "reach for this |
| 257 |
* when…" hint, and any tool without one still appears under its label. |
| 258 |
* Filterable so pro / add-on tools can slot themselves in. |
| 259 |
*/ |
| 260 |
private static function toolIndex() |
| 261 |
{ |
| 262 |
// [category, one-line "use this when…"], keyed by ability name. |
| 263 |
$hints = [ |
| 264 |
'fluent-cart/get-store-context' => ['discovery', 'Call first — identity, permissions, currency, enums, headline stats, and this index.'], |
| 265 |
'fluent-cart/list-reference-data' => ['discovery', 'Resolve names to ids: coupons, labels, gateways, tax classes, shipping zones, product categories.'], |
| 266 |
'fluent-cart/list-orders' => ['find', 'Find orders by status / payment / customer / product / date.'], |
| 267 |
'fluent-cart/list-customers' => ['find', 'Find customers by name / email / location / LTV.'], |
| 268 |
'fluent-cart/list-products' => ['find', 'Find products by title / category / price.'], |
| 269 |
'fluent-cart/list-subscriptions' => ['find', 'Find subscriptions by status / plan / product; summary_only for a fast aggregate.'], |
| 270 |
'fluent-cart/list-coupons' => ['find', 'Find coupons by status / code, with usage counts.'], |
| 271 |
'fluent-cart/list-transactions' => ['find', 'The payment ledger across records — refunds last week, failed charges for dunning, one customer\'s payment history.'], |
| 272 |
'fluent-cart/get-inventory' => ['find', 'Products at or below their stock threshold, or out of stock.'], |
| 273 |
'fluent-cart/get-order' => ['load', 'One order in full; include[] transactions / refunds / addresses / coupons / subscriptions.'], |
| 274 |
'fluent-cart/get-order-activity' => ['load', 'The audit timeline for one order.'], |
| 275 |
'fluent-cart/get-customer' => ['load', 'One customer profile; include[] orders / subscriptions.'], |
| 276 |
'fluent-cart/get-product' => ['load', 'One product with variations; include[] sales / downloads.'], |
| 277 |
'fluent-cart/get-subscription' => ['load', 'One subscription; include[] transactions / labels.'], |
| 278 |
'fluent-cart/get-product-financials' => ['load', 'One product\'s money: one-time + installment + recurring, MRR / ARR, payment schedule.'], |
| 279 |
'fluent-cart/get-sales-report' => ['analytics', 'The headline revenue number for a period, against the prior period.'], |
| 280 |
'fluent-cart/get-sales-trend' => ['analytics', 'Revenue / order time series by hour / day / week / month.'], |
| 281 |
'fluent-cart/get-top-products' => ['analytics', 'Best sellers by revenue or units.'], |
| 282 |
'fluent-cart/get-refund-report' => ['analytics', 'Refund count, rate and amount for a period.'], |
| 283 |
'fluent-cart/get-upcoming-payments' => ['analytics', 'Forward renewal cohort and at-risk revenue.'], |
| 284 |
'fluent-cart/query-orders' => ['analytics', 'Flexible order metrics by dimension — revenue by payment_status / order_type / month.'], |
| 285 |
'fluent-cart/query-products' => ['analytics', 'Product-line analytics — discount / margin leakage, by product / variation / order_type.'], |
| 286 |
'fluent-cart/query-customers' => ['analytics', 'Customer analytics by country / state / status / cohort.'], |
| 287 |
'fluent-cart/query-subscriptions' => ['analytics', 'Subscription analytics — contract vs recurring value, churn basis.'], |
| 288 |
'fluent-cart/query-sources' => ['analytics', 'UTM attribution — revenue by source / medium / campaign.'], |
| 289 |
'fluent-cart/change-order-status' => ['write', 'Set an order or shipping status.'], |
| 290 |
'fluent-cart/add-order-note' => ['write', 'Add an internal note to an order.'], |
| 291 |
'fluent-cart/refund-order' => ['write', 'Refund via the gateway — call dry_run first.'], |
| 292 |
'fluent-cart/upsert-customer' => ['write', 'Create or update a customer.'], |
| 293 |
'fluent-cart/change-subscription-status' => ['write', 'Cancel a subscription — call dry_run first.'], |
| 294 |
'fluent-cart/manage-coupon' => ['write', 'Create, update or deactivate a coupon.'], |
| 295 |
'fluent-cart/apply-labels' => ['write', 'Add or remove labels on an order / customer / subscription.'], |
| 296 |
]; |
| 297 |
|
| 298 |
// Preserve intent order; empty groups are dropped below. |
| 299 |
$index = ['discovery' => [], 'find' => [], 'load' => [], 'analytics' => [], 'write' => [], 'other' => []]; |
| 300 |
|
| 301 |
foreach (AbilitiesRegistrar::getDefinitions() as $name => $def) { |
| 302 |
$category = isset($hints[$name]) ? $hints[$name][0] : 'other'; |
| 303 |
$hint = isset($hints[$name]) ? $hints[$name][1] : (isset($def['label']) ? $def['label'] : $name); |
| 304 |
$short = strpos($name, 'fluent-cart/') === 0 ? substr($name, strlen('fluent-cart/')) : $name; |
| 305 |
|
| 306 |
$index[$category][$short] = $hint; |
| 307 |
} |
| 308 |
|
| 309 |
$index = array_filter($index, function ($group) { |
| 310 |
return !empty($group); |
| 311 |
}); |
| 312 |
|
| 313 |
return apply_filters('fluent_cart/mcp_tool_index', $index); |
| 314 |
} |
| 315 |
|
| 316 |
private static function guidelines() |
| 317 |
{ |
| 318 |
$default = 'Call get-store-context once per session. Consult the tool_index in this payload to pick the right tool for a task, then use list-* and query-* tools to find and aggregate records and get-* tools to load one record fully. ' |
| 319 |
. 'Money is returned as both a number (amount) and a formatted string (display) — quote display, compare amount. ' |
| 320 |
. 'Dates are ISO-8601 UTC; pass a relative range (e.g. last_30_days) or explicit start_date/end_date to report tools. ' |
| 321 |
. 'Use the exact enum values from this payload — never invent a status. ' |
| 322 |
. 'Reports never sum across currencies; filter by one currency if the store has several. ' |
| 323 |
. 'Writes (refund-order, change-subscription-status:cancel) require a dry_run preview first.'; |
| 324 |
|
| 325 |
return apply_filters('fluent_cart/mcp_guidelines', $default); |
| 326 |
} |
| 327 |
|
| 328 |
/** |
| 329 |
* `list-reference-data` — heavier lookup lists, fetched on demand. |
| 330 |
* |
| 331 |
* @param array $params { kinds: string[] } — which lists to return. Each |
| 332 |
* kind is gated by its own capability; kinds the |
| 333 |
* caller can't see are reported in `skipped`, not |
| 334 |
* silently dropped, so the agent knows why. |
| 335 |
*/ |
| 336 |
public static function listReferenceData($params = []) |
| 337 |
{ |
| 338 |
$kinds = isset($params['kinds']) ? (array) $params['kinds'] : []; |
| 339 |
if (!$kinds) { |
| 340 |
return MCPHelper::error( |
| 341 |
'missing_kinds', |
| 342 |
__('Provide one or more kinds. Valid: coupons, labels, gateways, tax_classes, shipping_zones, product_categories.', 'fluent-cart'), |
| 343 |
['valid_kinds' => self::referenceKinds()] |
| 344 |
); |
| 345 |
} |
| 346 |
|
| 347 |
$gate = [ |
| 348 |
'coupons' => 'coupons/view', |
| 349 |
'labels' => 'labels/view', |
| 350 |
'gateways' => 'dashboard_stats/view', |
| 351 |
'tax_classes' => 'store/settings', |
| 352 |
'shipping_zones' => 'store/settings', |
| 353 |
'product_categories' => 'products/view', |
| 354 |
]; |
| 355 |
|
| 356 |
$data = []; |
| 357 |
$skipped = []; |
| 358 |
|
| 359 |
foreach ($kinds as $kind) { |
| 360 |
if (!isset($gate[$kind])) { |
| 361 |
$skipped[$kind] = 'unknown_kind'; |
| 362 |
continue; |
| 363 |
} |
| 364 |
if (!PermissionGate::can($gate[$kind])) { |
| 365 |
$skipped[$kind] = 'forbidden: requires ' . $gate[$kind]; |
| 366 |
continue; |
| 367 |
} |
| 368 |
$data[$kind] = self::fetchReferenceKind($kind); |
| 369 |
} |
| 370 |
|
| 371 |
$meta = $skipped ? ['warnings' => self::skipWarnings($skipped)] : []; |
| 372 |
|
| 373 |
return MCPHelper::envelope( |
| 374 |
sprintf( |
| 375 |
/* translators: %d: number of reference lists returned */ |
| 376 |
_n('Returned %d reference list.', 'Returned %d reference lists.', count($data), 'fluent-cart'), |
| 377 |
count($data) |
| 378 |
), |
| 379 |
$data, |
| 380 |
$meta |
| 381 |
); |
| 382 |
} |
| 383 |
|
| 384 |
private static function skipWarnings($skipped) |
| 385 |
{ |
| 386 |
$out = []; |
| 387 |
foreach ($skipped as $kind => $reason) { |
| 388 |
$out[] = $kind . ': ' . $reason; |
| 389 |
} |
| 390 |
return $out; |
| 391 |
} |
| 392 |
|
| 393 |
/** |
| 394 |
* Each kind is fetched behind a class_exists guard so a model that isn't |
| 395 |
* present on a given install returns [] rather than fataling. |
| 396 |
*/ |
| 397 |
private static function fetchReferenceKind($kind) |
| 398 |
{ |
| 399 |
try { |
| 400 |
if ($kind === 'coupons' && class_exists('\FluentCart\App\Models\Coupon')) { |
| 401 |
$coupons = \FluentCart\App\Models\Coupon::query() |
| 402 |
->select(['id', 'code', 'title', 'type', 'amount', 'status', 'use_count']) |
| 403 |
->orderBy('id', 'DESC') |
| 404 |
->limit(200) |
| 405 |
->get(); |
| 406 |
$out = []; |
| 407 |
foreach ($coupons as $c) { |
| 408 |
// Match list-coupons: numeric amount; fixed coupons stored in |
| 409 |
// cents are reported in store currency, percentage as-is. |
| 410 |
$amount = ($c->type === 'fixed') |
| 411 |
? 0 + \FluentCart\App\Helpers\Helper::toDecimalWithoutComma((int) $c->amount) |
| 412 |
: (is_numeric($c->amount) ? 0 + $c->amount : $c->amount); |
| 413 |
$out[] = [ |
| 414 |
'id' => (int) $c->id, |
| 415 |
'code' => $c->code, |
| 416 |
'title' => $c->title, |
| 417 |
'type' => $c->type, |
| 418 |
'amount' => $amount, |
| 419 |
'status' => $c->status, |
| 420 |
// Usage count so "how many times was code X used" is |
| 421 |
// answerable without a second call. Alias times_used matches |
| 422 |
// list-coupons. |
| 423 |
'use_count' => (int) $c->use_count, |
| 424 |
'times_used' => (int) $c->use_count, |
| 425 |
]; |
| 426 |
} |
| 427 |
return $out; |
| 428 |
} |
| 429 |
|
| 430 |
if ($kind === 'labels' && class_exists('\FluentCart\App\Models\Label')) { |
| 431 |
// fct_label stores a single (maybe-serialized) `value` column — |
| 432 |
// it may hold a plain title string or an array {title,color,…}. |
| 433 |
// Labels are user-created and can grow large; cap like coupons |
| 434 |
// so kinds[]=labels can't trigger an unbounded read/response. |
| 435 |
$labels = \FluentCart\App\Models\Label::query()->orderBy('id', 'ASC')->limit(200)->get(); |
| 436 |
$out = []; |
| 437 |
foreach ($labels as $label) { |
| 438 |
$val = $label->value; |
| 439 |
$entry = ['id' => (int) $label->id]; |
| 440 |
if (is_array($val)) { |
| 441 |
$entry['title'] = isset($val['title']) ? $val['title'] : (isset($val['value']) ? $val['value'] : null); |
| 442 |
if (isset($val['color'])) { |
| 443 |
$entry['color'] = $val['color']; |
| 444 |
} |
| 445 |
} else { |
| 446 |
$entry['title'] = $val; |
| 447 |
} |
| 448 |
$out[] = $entry; |
| 449 |
} |
| 450 |
return $out; |
| 451 |
} |
| 452 |
|
| 453 |
if ($kind === 'tax_classes' && class_exists('\FluentCart\App\Models\TaxClass')) { |
| 454 |
// fct_tax_classes labels its name column `title`, not `name`. |
| 455 |
return \FluentCart\App\Models\TaxClass::query() |
| 456 |
->select(['id', 'title']) |
| 457 |
->get() |
| 458 |
->toArray(); |
| 459 |
} |
| 460 |
|
| 461 |
if ($kind === 'shipping_zones' && class_exists('\FluentCart\App\Models\ShippingZone')) { |
| 462 |
// fct_shipping_zones labels its name column `name`, not `title`. |
| 463 |
return \FluentCart\App\Models\ShippingZone::query() |
| 464 |
->select(['id', 'name', 'region']) |
| 465 |
->get() |
| 466 |
->toArray(); |
| 467 |
} |
| 468 |
|
| 469 |
if ($kind === 'gateways') { |
| 470 |
return self::enabledGateways(); |
| 471 |
} |
| 472 |
|
| 473 |
if ($kind === 'product_categories') { |
| 474 |
return self::productCategories(); |
| 475 |
} |
| 476 |
} catch (\Throwable $e) { |
| 477 |
return []; |
| 478 |
} |
| 479 |
|
| 480 |
return []; |
| 481 |
} |
| 482 |
|
| 483 |
/** |
| 484 |
* Active payment gateways. Each gateway stores its own settings (there is no |
| 485 |
* single payment_settings option), so we read the registered gateway |
| 486 |
* instances from the GatewayManager and keep the ones with is_active=yes. |
| 487 |
*/ |
| 488 |
private static function enabledGateways() |
| 489 |
{ |
| 490 |
$managerClass = '\FluentCart\App\Modules\PaymentMethods\Core\GatewayManager'; |
| 491 |
if (!class_exists($managerClass) || !method_exists($managerClass, 'getInstance')) { |
| 492 |
return []; |
| 493 |
} |
| 494 |
|
| 495 |
try { |
| 496 |
$gateways = $managerClass::getInstance()->all(); |
| 497 |
} catch (\Throwable $e) { |
| 498 |
return []; |
| 499 |
} |
| 500 |
|
| 501 |
$out = []; |
| 502 |
foreach ((array) $gateways as $gateway) { |
| 503 |
if (!is_object($gateway) || !method_exists($gateway, 'getMeta')) { |
| 504 |
continue; |
| 505 |
} |
| 506 |
|
| 507 |
$settings = (isset($gateway->settings) && is_object($gateway->settings) && method_exists($gateway->settings, 'get')) |
| 508 |
? (array) $gateway->settings->get() |
| 509 |
: []; |
| 510 |
|
| 511 |
$isActive = isset($settings['is_active']) |
| 512 |
? ($settings['is_active'] === 'yes') |
| 513 |
: !empty($gateway->getMeta('status')); |
| 514 |
if (!$isActive) { |
| 515 |
continue; |
| 516 |
} |
| 517 |
|
| 518 |
$meta = (array) $gateway->getMeta(); |
| 519 |
$route = isset($meta['route']) ? $meta['route'] : null; |
| 520 |
$out[] = [ |
| 521 |
'key' => $route, |
| 522 |
'title' => isset($meta['title']) ? $meta['title'] : $route, |
| 523 |
'mode' => isset($settings['payment_mode']) |
| 524 |
? $settings['payment_mode'] |
| 525 |
: (isset($settings['checkout_mode']) ? $settings['checkout_mode'] : null), |
| 526 |
]; |
| 527 |
} |
| 528 |
return $out; |
| 529 |
} |
| 530 |
|
| 531 |
/** Product categories from the WP taxonomy (best-effort across naming). */ |
| 532 |
private static function productCategories() |
| 533 |
{ |
| 534 |
foreach (['fluent-cart-category', 'product_cat', 'fluent_cart_category'] as $taxonomy) { |
| 535 |
if (!taxonomy_exists($taxonomy)) { |
| 536 |
continue; |
| 537 |
} |
| 538 |
$terms = get_terms(['taxonomy' => $taxonomy, 'hide_empty' => false, 'number' => 200]); |
| 539 |
if (is_wp_error($terms)) { |
| 540 |
continue; |
| 541 |
} |
| 542 |
$out = []; |
| 543 |
foreach ($terms as $term) { |
| 544 |
$out[] = ['id' => (int) $term->term_id, 'name' => $term->name, 'slug' => $term->slug, 'count' => (int) $term->count]; |
| 545 |
} |
| 546 |
return $out; |
| 547 |
} |
| 548 |
return []; |
| 549 |
} |
| 550 |
|
| 551 |
/** |
| 552 |
* Clear the cached context for all users. Hooked from MCPInit onto the |
| 553 |
* events that change anything the context payload reports. |
| 554 |
*/ |
| 555 |
public static function invalidateCache() |
| 556 |
{ |
| 557 |
global $wpdb; |
| 558 |
|
| 559 |
$like = $wpdb->esc_like('_transient_' . self::CACHE_PREFIX) . '%'; |
| 560 |
$wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->options} WHERE option_name LIKE %s", $like)); |
| 561 |
|
| 562 |
$like = $wpdb->esc_like('_transient_timeout_' . self::CACHE_PREFIX) . '%'; |
| 563 |
$wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->options} WHERE option_name LIKE %s", $like)); |
| 564 |
} |
| 565 |
} |
| 566 |
|