fluentcart-developer 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/.gitattributes +2 -0
  2. package/CLAUDE.md +22 -0
  3. package/CONTRIBUTING.md +73 -0
  4. package/LICENSE +21 -0
  5. package/README.md +127 -0
  6. package/SKILL.md +127 -0
  7. package/bin/index.js +281 -0
  8. package/copy-skills.js +43 -0
  9. package/package.json +38 -0
  10. package/skills/fluentcart-developer/SKILL.md +172 -0
  11. package/skills/fluentcart-developer/examples/README.md +25 -0
  12. package/skills/fluentcart-developer/examples/fluentcart-starter-child-theme/fluent-cart/checkout.php +32 -0
  13. package/skills/fluentcart-developer/examples/fluentcart-starter-child-theme/functions.php +40 -0
  14. package/skills/fluentcart-developer/examples/sample-custom-addon/fluentcart-custom-addon.php +114 -0
  15. package/skills/fluentcart-developer/examples/sample-custom-payment-gateway/fluentcart-custom-gateway-example.php +149 -0
  16. package/skills/fluentcart-developer/examples/sample-fee-surcharge-plugin/fluentcart-fee-surcharge.php +38 -0
  17. package/skills/fluentcart-developer/examples/sample-shipping-carrier/fluentcart-custom-shipping-carrier.php +62 -0
  18. package/skills/fluentcart-developer/references/action-hooks-admin-templates.md +787 -0
  19. package/skills/fluentcart-developer/references/action-hooks-cart-checkout.md +1355 -0
  20. package/skills/fluentcart-developer/references/action-hooks-customers-users.md +266 -0
  21. package/skills/fluentcart-developer/references/action-hooks-licenses.md +855 -0
  22. package/skills/fluentcart-developer/references/action-hooks-orders.md +631 -0
  23. package/skills/fluentcart-developer/references/action-hooks-payments-integrations.md +963 -0
  24. package/skills/fluentcart-developer/references/action-hooks-products-coupons.md +585 -0
  25. package/skills/fluentcart-developer/references/action-hooks-subscriptions.md +661 -0
  26. package/skills/fluentcart-developer/references/database-models-query-builder.md +194 -0
  27. package/skills/fluentcart-developer/references/database-models-reference.md +604 -0
  28. package/skills/fluentcart-developer/references/database-schema-reference.md +940 -0
  29. package/skills/fluentcart-developer/references/engineering-notes.md +154 -0
  30. package/skills/fluentcart-developer/references/fee-system-guide.md +449 -0
  31. package/skills/fluentcart-developer/references/filter-hooks-cart-checkout.md +1202 -0
  32. package/skills/fluentcart-developer/references/filter-hooks-customers-subscriptions.md +902 -0
  33. package/skills/fluentcart-developer/references/filter-hooks-integrations-advanced.md +1598 -0
  34. package/skills/fluentcart-developer/references/filter-hooks-orders-payments.md +1319 -0
  35. package/skills/fluentcart-developer/references/filter-hooks-products-pricing.md +628 -0
  36. package/skills/fluentcart-developer/references/filter-hooks-settings-configuration.md +1177 -0
  37. package/skills/fluentcart-developer/references/fluentcart-developer-guide.md +154 -0
  38. package/skills/fluentcart-developer/references/ghost-product-selling.md +458 -0
  39. package/skills/fluentcart-developer/references/modules-and-extensions-reference.md +224 -0
  40. package/skills/fluentcart-developer/references/paddle-gateway-case-study.md +1925 -0
  41. package/skills/fluentcart-developer/references/payment-gateway-integration.md +761 -0
  42. package/skills/fluentcart-developer/references/rest-api-checkout.md +286 -0
  43. package/skills/fluentcart-developer/references/rest-api-coupons.md +794 -0
  44. package/skills/fluentcart-developer/references/rest-api-customer-profile.md +190 -0
  45. package/skills/fluentcart-developer/references/rest-api-customers.md +1121 -0
  46. package/skills/fluentcart-developer/references/rest-api-dashboard-utilities.md +219 -0
  47. package/skills/fluentcart-developer/references/rest-api-email-notifications.md +619 -0
  48. package/skills/fluentcart-developer/references/rest-api-files.md +290 -0
  49. package/skills/fluentcart-developer/references/rest-api-integrations.md +324 -0
  50. package/skills/fluentcart-developer/references/rest-api-labels-attributes.md +321 -0
  51. package/skills/fluentcart-developer/references/rest-api-licensing.md +171 -0
  52. package/skills/fluentcart-developer/references/rest-api-order-bumps.md +200 -0
  53. package/skills/fluentcart-developer/references/rest-api-orders.md +1241 -0
  54. package/skills/fluentcart-developer/references/rest-api-overview.md +131 -0
  55. package/skills/fluentcart-developer/references/rest-api-products.md +2563 -0
  56. package/skills/fluentcart-developer/references/rest-api-public-shop.md +172 -0
  57. package/skills/fluentcart-developer/references/rest-api-reference.md +552 -0
  58. package/skills/fluentcart-developer/references/rest-api-reports.md +377 -0
  59. package/skills/fluentcart-developer/references/rest-api-roles-permissions.md +147 -0
  60. package/skills/fluentcart-developer/references/rest-api-settings.md +528 -0
  61. package/skills/fluentcart-developer/references/rest-api-shipping.md +800 -0
  62. package/skills/fluentcart-developer/references/rest-api-subscriptions.md +606 -0
  63. package/skills/fluentcart-developer/references/rest-api-tax.md +356 -0
  64. package/skills/fluentcart-developer/references/subscription-customization.md +197 -0
  65. package/skills/fluentcart-developer/scripts/cli.js +1 -0
  66. package/skills.sh.json +13 -0
@@ -0,0 +1,154 @@
1
+ # Engineering Notes
2
+
3
+ Notes from the engineers building FluentCart — architecture decisions, performance work, and lessons from production.
4
+
5
+ ---
6
+
7
+ ## Giving AI Agents the Full Power of Advanced Search — Without Bloating the Context Window
8
+
9
+ **July 14, 2026 · 7 min read**
10
+
11
+ **Shahjahan Jewel** — Founder & Lead Developer
12
+
13
+ Tags: `mcp` · `ai-agents` · `architecture`
14
+
15
+ ---
16
+
17
+ Every tool you hand an MCP agent is a tax. Its schema — every parameter, every enum, every description — is loaded into the model's context on every single request, whether the agent uses that tool or not. So when we set out to give AI agents the same advanced search our admin UI has, we hit an uncomfortable wall: the honest version of that feature is enormous, and the naive way to ship it would have made every unrelated question — "how many orders today?" — drag a few thousand tokens of filter grammar along for the ride.
18
+
19
+ This is the story of how we gave agents the entire advanced-search surface for roughly one sentence of standing context per tool.
20
+
21
+ ### The surface we were trying to expose
22
+
23
+ FluentCart's admin has a real filter engine. On the orders list alone it exposes 28 filterable properties — order status, payment status, totals, dates, customer email and lifetime value, the products and variations an order contains, transaction card metadata, UTM attribution, labels, license keys — and each property carries its own set of legal operators (`in`, `not_in`, `>`, `contains`, `days_within`, `before`…), its own value format, and sometimes a list of enum options. Multiply that across five entities — orders, customers, products, subscriptions, licenses — and you have hundreds of property definitions.
24
+
25
+ That catalog is the feature. An agent that can't see it can't build `(completed orders over $100 in the last 90 days) OR (customers whose email contains "@acme.")`. But a catalog that large, inlined into tool schemas, is a context disaster.
26
+
27
+ ### The decision: describe the door, not the building
28
+
29
+ The core move was **progressive disclosure**. Instead of teaching every agent everything up front, we teach it where to look and let it fetch the detail only when it actually needs it.
30
+
31
+ Concretely, that became two pieces:
32
+
33
+ 1. **One discovery tool, `get-search-schema`.** It takes a single `entity` argument and returns the full reference for that one entity on demand — every filterable property, its operators, its value format, its enum options, and a worked example the agent can copy.
34
+ 2. **One lean parameter, `advanced_filters`,** added to each list tool. Its schema is a single sentence: *"condition groups {property, operator, value} — call get-search-schema first."*
35
+
36
+ The always-loaded cost of the whole feature is now that one parameter and one sentence, per tool. The 28-property orders catalog only enters the context when an agent is genuinely about to search orders — and even then, only the orders catalog, not all five. We rejected the two obvious alternatives on the way here: inlining the catalogs (the context bomb) and minting a dozen `search-orders-by-x` tools (a different context bomb, plus a maintenance one).
37
+
38
+ ### The decision that made it trustworthy: derive the schema live
39
+
40
+ A discovery endpoint is only useful if it tells the truth. The trap would have been to hand-write the schema `get-search-schema` returns — a second description of the filters that drifts out of sync with the engine the moment someone adds a property.
41
+
42
+ So we don't hand-write it. The schema is built from the same source the engine executes: each filter class's `advanceFilterOptions()`, read through the `fluent_cart/{name}_filter_options` filter hook — the exact hook the admin list runs. When the attributes module registers a new `attribute_term` filter through that hook, it shows up in the agent's schema automatically, because the agent's schema and the running query are reading the same catalog. Schema and behavior cannot drift, because they are the same thing viewed from two angles.
43
+
44
+ ### The decision to reuse, not reimplement
45
+
46
+ The advanced-search grammar — OR groups of AND conditions, relation filters, cent conversion, relative dates — already lives in `BaseFilter`, the admin filter engine. We could have reimplemented a "lite" version for the MCP layer. We didn't. The bridge normalizes the agent's payload and hands it straight to `BaseFilter::make(...)->buildQuery()`, the same entry point the admin list uses, then layers the tool's own eager-loads, sorting, and pagination on top.
47
+
48
+ The payoff is a guarantee we could put in one sentence: **MCP search power equals web-UI search power**, because it *is* the web UI's search, with no second implementation to fall behind. And it all lives in the MCP module — the engine in `app/Services` was never touched, only consumed through its public surface.
49
+
50
+ ### What the agent actually sends
51
+
52
+ The agent sends a lean triple and nothing more:
53
+
54
+ ```json
55
+ {
56
+ "advanced_filters": [
57
+ [
58
+ { "property": "order.status", "operator": "in", "value": ["completed", "processing"] },
59
+ { "property": "order.total_amount", "operator": ">", "value": 100 },
60
+ { "property": "order.created_at", "operator": "days_within", "value": 90 }
61
+ ],
62
+ [
63
+ { "property": "customer.customer_email", "operator": "=", "value": "jane@acme.com" }
64
+ ]
65
+ ]
66
+ }
67
+ ```
68
+
69
+ The outer array is OR; each inner array is AND. What the agent does *not* send is just as important: the engine-internal fields — which relation to join, which column, which dispatch path — are never trusted from input. The bridge looks each property up in the trusted catalog and fills those in itself. The agent controls *what* to match; the catalog controls *how* it's matched. That single rule is what keeps agent-authored strings from ever reaching a raw column name or SQL operator.
70
+
71
+ ### The decision to fail loud
72
+
73
+ Here's the subtle part, and the one most transferable to anyone building agent-facing tools. The filter engine was built for a UI, where a human notices a weird result and adjusts. It has two behaviors that are perfectly reasonable there and quietly dangerous for an agent:
74
+
75
+ 1. it silently skips a malformed condition, and
76
+ 2. it silently returns everything when a required capability is inactive.
77
+
78
+ For a person, a filter that didn't apply is a visible non-event. For an agent, it is a **confidently wrong answer**: it asked for "refunded orders over $9 quintillion," the condition silently overflowed and vanished, and it received all 5,140 orders formatted as if they were the filtered set. The agent has no way to know. It will summarize that number to a user as fact.
79
+
80
+ So the bridge validates everything before the engine ever runs. An unknown property returns an error listing the valid ones. A bad operator returns the operators that are allowed for that property. An out-of-range money value, a malformed date, an empty relation value — each becomes a specific, structured error the agent can read and correct from, instead of a silently mangled query. Values that are merely unusual (an enum option we don't recognize) run, but carry a warning back in the response. The guiding principle is one we now apply across the whole MCP surface, including plain parameter handling: **an agent should never be able to receive a wrong answer that looks right.** If we can't honor the request, we say so; we don't guess.
81
+
82
+ ### The three doors, and the self-correcting one
83
+
84
+ Put together, an agent meets the feature at three widening levels of detail:
85
+
86
+ 1. **The tool list it already has:** the `advanced_filters` sentence tells it the capability exists and where the manual is.
87
+ 2. **`get-store-context`**, the orientation call agents make first anyway, lists `get-search-schema` under discovery and says when to reach for it.
88
+ 3. **`get-search-schema {entity}`** — the second call — delivers the full catalog for exactly one entity, on demand.
89
+
90
+ And if an agent skips the manual and guesses a property name wrong? The validation error hands back the list of valid properties — an inline, just-in-time mini-schema, delivered only in the failure case that needs it. The context is spent precisely where a mistake was made, and nowhere else.
91
+
92
+ ### The lesson
93
+
94
+ Context is a budget, and the instinct to "just expose everything so the agent is capable" spends it in the worst possible place — uniformly, on every request, mostly on tools the agent won't touch this turn. The alternative isn't giving the agent less power. It's deferring the description of that power until the moment it's used, deriving that description from the code that already exists so it can't lie, and making every failure mode loud enough that the agent can recover.
95
+
96
+ We added the full admin filter engine to our AI tools and the standing context cost barely moved. If you're building MCP tools over a large existing surface, that's the pattern worth stealing: **a thin, honest pointer in the always-loaded schema, a live-derived manual one call away, and a validation layer that turns the engine's convenient silences into errors an agent can actually learn from.**
97
+
98
+ ---
99
+
100
+ ## Why FluentCart Uses a Custom Database Schema, Not WooCommerce's
101
+
102
+ **July 10, 2026 · 4 min read**
103
+
104
+ **Shahjahan Jewel** — Founder & Lead Developer
105
+
106
+ Tags: `architecture` · `database` · `performance`
107
+
108
+ ---
109
+
110
+ The most consequential decision we made in FluentCart wasn't a feature. It was refusing to store orders in `wp_posts`. Every architectural property people notice about FluentCart — fast admin lists, honest reports, subscriptions that don't fall over — traces back to that one call.
111
+
112
+ ### The postmeta tax
113
+
114
+ Classic WordPress e-commerce modeling stores an order as a post of type `shop_order` and everything about it — totals, customer, addresses, statuses, gateway references — as rows in `wp_postmeta`. It's the entity–attribute–value pattern: one table, three columns, infinite flexibility.
115
+
116
+ The flexibility is real. So is the bill:
117
+
118
+ - **Every attribute is a LONGTEXT.** Order totals are strings. Dates are strings. Compare, sum, or sort them and MySQL casts row by row, index-free.
119
+ - **Every attribute is a join.** "Orders over $100 from Germany last month" means three self-joins on a table with tens of millions of rows before your store is even big.
120
+ - **Nothing is enforced.** No types, no foreign keys, no `NOT NULL`. Data quality becomes a convention maintained by whichever plugin wrote last.
121
+
122
+ WooCommerce itself acknowledged this — HPOS (custom order tables) is the largest migration project in its history, and it has to maintain compatibility with a decade of extensions reading `wp_postmeta` directly. That is not a criticism; it's the strongest evidence available that the schema matters and that retrofitting one is brutally expensive. We had the luxury of starting clean, so we did.
123
+
124
+ ### What we built instead
125
+
126
+ FluentCart ships its own tables, created by real migrations: `fct_orders`, `fct_order_items`, `fct_order_transactions`, `fct_customers`, `fct_subscriptions`, `fct_carts`, and friends — typed columns, proper indexes, managed by an Eloquent-style ORM from the WPFluent framework. The full map is in the [database schema docs](database-schema-reference.md).
127
+
128
+ A few decisions inside that schema do a lot of the heavy lifting:
129
+
130
+ **Money is a BIGINT, in cents.** Not a float, not a decimal string in a meta row. Floating-point money leaks pennies at scale, and string money can't use an index. Every amount passes through `Helper::toCent()` on the way in and `Helper::toDecimal()` on the way out. Summing a year of revenue is `SUM()` on an indexed integer column.
131
+
132
+ **Timestamps are UTC, always.** Everything is stored via `DateTime::gmtNow()` and converted at the display edge. Server timezone changes, DST, a store owner moving from Dhaka to Denver — none of it silently shifts your revenue-by-day report.
133
+
134
+ **Customers are first-class, decoupled from `wp_users`.** A customer row carries purchase count, lifetime value, and addresses, and only optionally links to a WordPress user. Guest checkout doesn't require conjuring user accounts, and LTV is a column you can sort by, not a nightly aggregation job.
135
+
136
+ **Subscriptions are rows, not order metadata.** A subscription has its own lifecycle, its own table, and its own transactions trail. When a renewal payment lands, we update a typed row and dispatch a domain event — we don't append another meta blob to a post.
137
+
138
+ ### What it costs
139
+
140
+ Honesty requires the other column. Walking away from `wp_posts` means walking away from the ecosystem that assumes it:
141
+
142
+ - **No WooCommerce plugin compatibility.** The thousands of Woo extensions don't work with FluentCart. Integrations get built against our REST API and hooks instead — deliberately, one at a time.
143
+ - **We own every migration.** Schema changes ship as versioned migrations we write and test. There's no "it's just postmeta, add a key" escape hatch.
144
+ - **Tooling assumptions break.** Generic WP export/backup/search plugins that only understand posts see nothing. We have to provide our own answers.
145
+
146
+ We think it's a good trade because the costs are one-time and ours, while the postmeta tax compounds forever and lands on every store owner.
147
+
148
+ ### Where it pays off
149
+
150
+ Open the FluentCart reports screen on a store with a few hundred thousand orders. Revenue by period, new-versus-returning customers, subscription cohorts, refund rates — each of those is a straightforward indexed query against typed columns. That's the whole story. There is no caching layer heroically hiding an EAV swamp, because there's no swamp.
151
+
152
+ The same schema is what makes the REST API resources clean: an order serializes from a row and its relations, not from a bag of meta keys with three naming conventions.
153
+
154
+ If you're building on FluentCart, start with the [schema documentation](database-schema-reference.md) and the [model reference](database-models-reference.md) — the database is the real API contract, and unlike a postmeta store, this one is written down.
@@ -0,0 +1,449 @@
1
+ # Fee System (Surcharges & Additional Charges)
2
+
3
+ FluentCart provides a built-in fee system that allows developers to attach additional charges to a cart during checkout. This is useful for processing fees, handling fees, small-order surcharges, payment gateway surcharges, environmental levies, and more.
4
+
5
+ ---
6
+
7
+ ## Overview
8
+
9
+ Fees are stored as order items with `payment_type = 'fee'` and a cached `fee_total` column on the order for fast aggregation. The system provides two ways to register fees:
10
+
11
+ - **Dynamic fees** via the `fluent_cart/cart/fees` filter — recalculated on every checkout update
12
+ - **Persistent fees** via `$cart->addFee()` — stored directly on the cart and persisted to the database
13
+
14
+ Fees automatically integrate with:
15
+
16
+ - Checkout summary display
17
+ - Order totals calculation
18
+ - Email templates and PDF receipts
19
+ - Admin order view and customer portal
20
+ - Refund distribution (proportional)
21
+ - REST API responses
22
+
23
+ ---
24
+
25
+ ## Fee Data Structure
26
+
27
+ Every fee follows this structure:
28
+
29
+ ```php
30
+ [
31
+ 'key' => 'processing_fee', // Unique slug (required)
32
+ 'label' => 'Processing Fee', // Customer-facing name (required)
33
+ 'amount' => 450, // Amount in cents, must be positive (required)
34
+ 'taxable' => false, // Whether tax should be calculated (default: false)
35
+ 'source' => 'my-addon', // Addon identifier (default: 'custom')
36
+ 'meta' => ['rule_id' => 42], // Optional extra data stored in order item
37
+ ]
38
+ ```
39
+
40
+ ### Rules:
41
+
42
+ - `amount` must be a positive integer (in cents). Negative values are rejected.
43
+ - `key` is sanitized with `sanitize_key()`. Combined with `source`, it forms a composite dedup key (`source:key`).
44
+ - Duplicate `source:key` entries are deduplicated — the last one wins.
45
+
46
+ ---
47
+
48
+ ## Method 1: Dynamic Fees via Filter
49
+
50
+ Use the `fluent_cart/cart/fees` filter to add fees that are recalculated on every checkout update (quantity change, coupon applied, payment method changed, etc.).
51
+
52
+ ### Hook: `fluent_cart/cart/fees`
53
+
54
+ **Parameters:**
55
+
56
+ | Parameter | Type | Description |
57
+ |-----------|------|-------------|
58
+ | `$fees` | `array` | Current fees array (may contain fees from other addons or stored fees) |
59
+ | `$context` | `array` | Cart context for condition evaluation |
60
+
61
+ **Returns:** Modified fees array
62
+
63
+ ### Context array contents:
64
+
65
+ | Key | Type | Description |
66
+ |-----|------|-------------|
67
+ | `cart` | `Cart` | The Cart model instance |
68
+ | `cart_items` | `array` | Current cart item data |
69
+ | `cart_subtotal` | `int` | Cart subtotal in cents (before discounts) |
70
+ | `shipping_total` | `int` | Shipping total in cents |
71
+ | `customer_id` | `int` | Customer ID |
72
+ | `payment_method` | `string` | Selected payment method key |
73
+ | `checkout_data` | `array` | Full checkout data |
74
+
75
+ ### Example: Small Order Surcharge
76
+
77
+ Add a $5 fee when the cart subtotal is under $25:
78
+
79
+ ```php
80
+ add_filter('fluent_cart/cart/fees', function (array $fees, array $context) {
81
+ // Get cart subtotal in cents
82
+ $subtotal = $context['cart_subtotal'];
83
+
84
+ // Apply $5 fee only when subtotal is between $0.01 and $24.99
85
+ if ($subtotal > 0 && $subtotal < 2500) {
86
+ $fees[] = [
87
+ 'key' => 'small_order_fee',
88
+ 'label' => __('Small Order Fee', 'my-addon'),
89
+ 'amount' => 500,
90
+ 'taxable' => false,
91
+ 'source' => 'my-addon',
92
+ 'meta' => ['reason' => 'subtotal_below_threshold'],
93
+ ];
94
+ }
95
+
96
+ return $fees;
97
+ }, 10, 2);
98
+ ```
99
+
100
+ ### Example: Payment Method Processing Fee
101
+
102
+ Add a 2.9% processing fee for Stripe payments:
103
+
104
+ ```php
105
+ add_filter('fluent_cart/cart/fees', function (array $fees, array $context) {
106
+ // Only apply fee for Stripe payment method
107
+ if ($context['payment_method'] !== 'stripe') {
108
+ return $fees;
109
+ }
110
+
111
+ $subtotal = $context['cart_subtotal'];
112
+ if ($subtotal <= 0) {
113
+ return $fees;
114
+ }
115
+
116
+ // Calculate 2.9% of subtotal, rounded to nearest cent
117
+ $feeAmount = (int) round($subtotal * 0.029);
118
+
119
+ $fees[] = [
120
+ 'key' => 'stripe_processing',
121
+ 'label' => __('Processing Fee (2.9%)', 'my-addon'),
122
+ 'amount' => $feeAmount,
123
+ 'taxable' => true,
124
+ 'source' => 'my-addon',
125
+ 'meta' => ['rate' => '2.9%'],
126
+ ];
127
+
128
+ return $fees;
129
+ }, 10, 2);
130
+ ```
131
+
132
+ ### Example: Location-Based Fee
133
+
134
+ Add a handling fee for orders shipping to remote areas:
135
+
136
+ ```php
137
+ add_filter('fluent_cart/cart/fees', function (array $fees, array $context) {
138
+ // Extract shipping address from checkout data
139
+ $checkoutData = $context['checkout_data'];
140
+ $country = $checkoutData['form_data']['shipping_country'] ?? '';
141
+ $state = $checkoutData['form_data']['shipping_state'] ?? '';
142
+
143
+ // Define remote US territories
144
+ $remoteAreas = ['AK', 'HI', 'PR']; // Alaska, Hawaii, Puerto Rico
145
+
146
+ // Apply $15 handling fee for remote US areas
147
+ if ($country === 'US' && in_array($state, $remoteAreas, true)) {
148
+ $fees[] = [
149
+ 'key' => 'remote_handling',
150
+ 'label' => __('Remote Area Handling Fee', 'my-addon'),
151
+ 'amount' => 1500,
152
+ 'taxable' => false,
153
+ 'source' => 'my-addon',
154
+ ];
155
+ }
156
+
157
+ return $fees;
158
+ }, 10, 2);
159
+ ```
160
+
161
+ ---
162
+
163
+ ## Method 2: Persistent Fees via Cart Methods
164
+
165
+ Use these methods to programmatically add or remove fees that are stored on the cart. Persistent fees survive page reloads and are included alongside dynamic fees.
166
+
167
+ ### `$cart->addFee(array $fee): bool`
168
+
169
+ Adds a fee to the cart and saves immediately. If a fee with the same `source:key` already exists, it will be updated.
170
+
171
+ ```php
172
+ // Find the cart by ID
173
+ $cart = \FluentCart\App\Models\Cart::find($cartId);
174
+
175
+ // Add a $2 handling fee to the cart
176
+ $cart->addFee([
177
+ 'key' => 'handling_fee',
178
+ 'label' => 'Handling Fee',
179
+ 'amount' => 200,
180
+ 'source' => 'my-addon',
181
+ 'taxable' => false,
182
+ 'meta' => ['applied_by' => 'admin'],
183
+ ]);
184
+ ```
185
+
186
+ ### `$cart->removeFee(string $key, ?string $source = null): bool`
187
+
188
+ Removes a fee by key. Optionally filter by source to avoid removing another addon's fee with the same key.
189
+
190
+ ```php
191
+ // Remove a specific fee by key and source
192
+ $cart->removeFee('handling_fee', 'my-addon');
193
+
194
+ // Remove all fees with this key (regardless of source)
195
+ $cart->removeFee('handling_fee');
196
+ ```
197
+
198
+ ### `$cart->removeFeesBySource(string $source): void`
199
+
200
+ Removes all fees from a specific source. Useful for clearing all your addon's fees before recalculating.
201
+
202
+ ```php
203
+ // Clear all fees from your addon
204
+ $cart->removeFeesBySource('my-addon');
205
+ ```
206
+
207
+ ### `$cart->getFees(): array`
208
+
209
+ Returns all validated fees (stored + dynamic from filter).
210
+
211
+ ### `$cart->getFeeTotal(): int`
212
+
213
+ Returns the total of all fees in cents.
214
+
215
+ ```php
216
+ // Retrieve all fees and the total
217
+ $fees = $cart->getFees();
218
+ $total = $cart->getFeeTotal(); // e.g., 700 (= $7.00)
219
+ ```
220
+
221
+ ---
222
+
223
+ ## How Fees Flow Through the System
224
+
225
+ ```
226
+ 1. REGISTRATION
227
+ Addon registers fees via filter or $cart->addFee()
228
+
229
+ 2. CHECKOUT SUMMARY
230
+ WebCheckoutHandler recalculates on every cart change
231
+ CartSummaryRender::renderFees() displays fee lines
232
+ Fee total included in estimated total
233
+
234
+ 3. ORDER CREATION
235
+ CheckoutProcessor reads fees from cart
236
+ Each fee becomes an OrderItem (payment_type = 'fee')
237
+ fee_total cached on the Order record
238
+ total_amount formula includes fee_total
239
+
240
+ 4. POST-ORDER
241
+ Admin view: fee rows in payment table
242
+ Customer portal: fee rows in totals
243
+ Emails: fee rows in items table
244
+ PDF receipts: fee rows in summary
245
+ Refunds: fees participate in proportional distribution
246
+ ```
247
+
248
+ ### Total Amount Formula
249
+
250
+ ```
251
+ total_amount = subtotal
252
+ - coupon_discount_total
253
+ - manual_discount_total
254
+ + fee_total
255
+ + shipping_total
256
+ + tax_total (if exclusive)
257
+ + shipping_tax (if exclusive)
258
+ ```
259
+
260
+ ---
261
+
262
+ ## Fee Display Order
263
+
264
+ Fees appear in the checkout summary and all post-order displays in this order:
265
+
266
+ ```
267
+ 1. Subtotal
268
+ 2. Shipping
269
+ 3. Fees ← your fees appear here
270
+ 4. Coupons / Discounts
271
+ 5. Tax
272
+ 6. Total
273
+ ```
274
+
275
+ This ordering is intentional — fees are additions (like shipping), shown before subtractions (discounts).
276
+
277
+ ---
278
+
279
+ ## Reading Fees from Orders
280
+
281
+ After an order is placed, fees are stored as order items. Use these methods to access them:
282
+
283
+ ### `$order->feeItems()`
284
+
285
+ Returns a `HasMany` relationship query for fee order items.
286
+
287
+ ```php
288
+ $order = \FluentCart\App\Models\Order::find($orderId);
289
+
290
+ // Iterate over fee items attached to this order
291
+ $feeItems = $order->feeItems()->get();
292
+
293
+ foreach ($feeItems as $item) {
294
+ echo $item->title; // "Processing Fee"
295
+ echo $item->subtotal; // 450 (cents)
296
+ echo $item->tax_amount; // 36 (cents, if taxable)
297
+ }
298
+ ```
299
+
300
+ ### `$order->getAppliedFees()`
301
+
302
+ Returns a simplified array of applied fees.
303
+
304
+ ```php
305
+ $fees = $order->getAppliedFees();
306
+ // [
307
+ // [
308
+ // 'key' => 'processing_fee',
309
+ // 'label' => 'Processing Fee',
310
+ // 'amount' => 450,
311
+ // 'source' => 'my-addon',
312
+ // 'item_id' => 42,
313
+ // ],
314
+ // ]
315
+ ```
316
+
317
+ ### `$order->getProductItems()`
318
+
319
+ Returns order items excluding fees and signup fees. Use this whenever displaying product line items to avoid showing fee rows in the product list.
320
+
321
+ ```php
322
+ // Correct: excludes fee and signup_fee items
323
+ $products = $order->getProductItems();
324
+
325
+ // Also available on the order: the cached total
326
+ $feeTotal = $order->fee_total; // e.g., 650
327
+ ```
328
+
329
+ ---
330
+
331
+ ## Fee Item Structure in Order Items
332
+
333
+ When a fee becomes an order item, it has this structure in `fct_order_items`:
334
+
335
+ | Column | Value | Notes |
336
+ |--------|-------|-------|
337
+ | `post_id` | `0` | No product |
338
+ | `object_id` | `0` | No variation |
339
+ | `title` | `"Processing Fee"` | The fee label |
340
+ | `quantity` | `1` | Always 1 |
341
+ | `unit_price` | `450` | Amount in cents |
342
+ | `subtotal` | `450` | Same as unit_price |
343
+ | `line_total` | `450` | Same as subtotal |
344
+ | `payment_type` | `'fee'` | Identifies as a fee |
345
+ | `other_info` | JSON | Contains `fee_key`, `source`, `taxable`, `meta` |
346
+
347
+ ---
348
+
349
+ ## Actions
350
+
351
+ ### `fluent_cart/cart/fees_calculated`
352
+
353
+ Fired after fees are collected and stored on the cart during checkout summary recalculation.
354
+
355
+ ```php
356
+ add_action('fluent_cart/cart/fees_calculated', function (array $fees, $cart) {
357
+ // Log or track fee activity
358
+ if (!empty($fees)) {
359
+ error_log('Fees applied: ' . count($fees) . ' for cart #' . $cart->id);
360
+ }
361
+ }, 10, 2);
362
+ ```
363
+
364
+ ### `fluent_cart/order/fee_items_created`
365
+
366
+ Fired after fee order items are created during order placement.
367
+
368
+ ```php
369
+ add_action('fluent_cart/order/fee_items_created', function (array $feeOrderItems, $order) {
370
+ // Post-creation processing
371
+ }, 10, 2);
372
+ ```
373
+
374
+ ---
375
+
376
+ ## Important Behavior Notes
377
+
378
+ - **Fees are recalculated on every checkout update.** Dynamic fees (via filter) run whenever the checkout summary refreshes — item changes, coupon application, payment method change, address change, etc.
379
+
380
+ - **Fees are not applied to subscription renewals.** The filter is skipped when `checkout_data.renew_data.is_renewal` is `yes`.
381
+
382
+ - **Fees are not applied to locked carts.** Custom/manual checkout carts that are locked return only stored fees without running the filter.
383
+
384
+ - **Deduplication uses `source:key`.** Two addons can both register a fee with `key = 'processing_fee'` as long as they use different `source` values.
385
+
386
+ - **Fees are read-only after order creation.** Once an order is placed, fee items cannot be edited from the admin panel.
387
+
388
+ - **Fees participate in proportional refunds.** When an order is refunded, fee items are included in the proportional distribution automatically.
389
+
390
+ - **Per-request caching.** `getFees()` caches results within a single request. Call `$cart->clearFeeCache()` if you modify fees and need to re-read within the same request.
391
+
392
+ - **Recursion guard.** If your filter callback calls `$cart->getFees()`, it returns only stored fees (not the filter result) to prevent infinite loops.
393
+
394
+ ---
395
+
396
+ ## Complete Example: Tiered Handling Fee Addon
397
+
398
+ A full working example that applies tiered handling fees based on cart subtotal:
399
+
400
+ ```php
401
+ <?php
402
+ /**
403
+ * Plugin Name: FluentCart Handling Fee
404
+ * Description: Adds tiered handling fees based on cart subtotal.
405
+ */
406
+
407
+ add_filter('fluent_cart/cart/fees', function (array $fees, array $context) {
408
+ $subtotal = $context['cart_subtotal'];
409
+
410
+ // Skip if cart is empty
411
+ if ($subtotal <= 0) {
412
+ return $fees;
413
+ }
414
+
415
+ // Tiered handling fee based on cart subtotal
416
+ $feeAmount = match (true) {
417
+ $subtotal < 2000 => 500, // Under $20: $5.00 fee
418
+ $subtotal < 5000 => 300, // $20-$49.99: $3.00 fee
419
+ $subtotal < 10000 => 100, // $50-$99.99: $1.00 fee
420
+ default => 0, // $100+: no fee
421
+ };
422
+
423
+ // Only add fee if amount is non-zero
424
+ if ($feeAmount > 0) {
425
+ $fees[] = [
426
+ 'key' => 'handling_fee',
427
+ 'label' => __('Handling Fee', 'my-handling-fee'),
428
+ 'amount' => $feeAmount,
429
+ 'taxable' => false,
430
+ 'source' => 'handling-fee-addon',
431
+ 'meta' => [
432
+ 'tier' => $subtotal < 2000 ? 'small' : ($subtotal < 5000 ? 'medium' : 'large'),
433
+ 'subtotal' => $subtotal,
434
+ ],
435
+ ];
436
+ }
437
+
438
+ return $fees;
439
+ }, 10, 2);
440
+ ```
441
+
442
+ ---
443
+
444
+ ## Related Documentation
445
+
446
+ - [Developer Hooks](action-hooks-orders.md) - Complete hooks and filters reference
447
+ - [Orders API](rest-api-reference.md) - Order management API
448
+ - [Database Models](database-models-reference.md) - Data model documentation
449
+ - [Ghost Product Selling](ghost-product-selling.md) - Custom product selling guide