Splitting a Drupal Commerce order fee across items for Salesforce
To push an order-level fee from Drupal Commerce to Salesforce when your mappings push orders, order items and webform submissions to different objects, subscribe to Salesforce Suite's push params event, resolve the related order from whatever entity is being pushed, and set the fee only on objects that have the field. When the record is one item of a multi-item order, send that item's share of the fee in proportion to its price, and decide where the leftover cent goes, because rounding each share on its own can make them add up to a different total.
Where an order-level fee lives in Drupal Commerce
The setup was a group of nonprofit membership sites on one Drupal distribution. Members pay for things through Drupal Commerce, some of them directly and some through Webform submissions paid with Commerce Webform Order. Card payments carry a processing fee, which the sites add to the order as an adjustment. There are several adjustment types for it, one per kind of application, so the fee is the sum of all of them.
That is the natural place for a fee in Commerce: it belongs to the order, not to any single item. Salesforce didn't see it that way. Salesforce Suite mappings push the order to one object, each order item to another, and the webform submissions to a third, and the team wanted the fee recorded on whichever of those records should carry it.
Why one subscriber has to handle three entity types
Salesforce Suite dispatches SalesforceEvents::PUSH_PARAMS with a SalesforcePushParamsEvent just before it sends a record. The event gives you the Drupal entity, the mapping and the parameters about to be sent, and you can add, change or remove parameters there. A teammate wrote one subscriber for every mapping rather than one per mapping. It does three things in turn.
First, it finds the order. An order is itself. An order item knows its order through getOrder(). A webform submission doesn't know about orders at all, but Commerce Webform Order keeps that link and has a repository service that returns the last order item created for a submission, and from that you reach the order.
Second, it checks that the target Salesforce object actually has the fee field, using an object describe call through Salesforce Suite's REST client. If there is no order or no field, it removes the parameter instead of sending an empty value. That one subscriber can then run on every mapping without breaking the ones whose object has no fee field.
Third, it works out the value. For an order or a submission, that is the whole fee. For an order item on an order with several items, it is a share.
How to split the fee in proportion to item price
The team's rule is the simple one: an item's share is the fee multiplied by the item's total price over the order subtotal, rounded to two decimals because the Salesforce field is Currency(16,2). They also guard against a zero subtotal, so a fully discounted order doesn't divide by zero. Here is the same idea as a small, standalone function:
<?php
/**
* Returns the item's share of an order-level fee, in proportion to price.
*/
function item_fee_share(float $fee, float $item_total, float $subtotal, int $item_count): float {
if ($item_count > 1 && $subtotal > 0) {
$fee *= $item_total / $subtotal;
}
return round($fee, 2);
}
// A 3.00 fee on an order of 50.00 + 30.00 + 20.00.
echo item_fee_share(3.00, 50.00, 100.00, 3), PHP_EOL; // 1.5
echo item_fee_share(3.00, 30.00, 100.00, 3), PHP_EOL; // 0.9
echo item_fee_share(3.00, 20.00, 100.00, 3), PHP_EOL; // 0.6
Those shares add up to the fee. Plenty of others won't.
Why rounded shares can miss the total by a cent
Each share is rounded on its own, so the rounding errors add up. A 1.00 fee on three items of the same price gives 0.33 three times, which is 0.99. A 0.10 fee on two equal items gives 0.05 twice, which is fine, but on three it gives 0.03 three times, which is 0.09. When someone in Salesforce totals the item records and compares them with the order record, they find a cent missing and no reason for it.
The fix is to allocate in whole cents and hand out the remainder on purpose. The largest remainder method does that: give each item the floor of its exact share in cents, then give the leftover cents, one each, to the items whose exact share lost the most to rounding down.
<?php
/**
* Splits a fee across items by price so the shares always sum to the fee.
*
* @param int $fee_cents
* The fee in cents.
* @param int[] $item_cents
* Item totals in cents, keyed by item id.
*
* @return int[]
* Each item's share in cents, keyed by item id.
*/
function split_fee(int $fee_cents, array $item_cents): array {
$subtotal = array_sum($item_cents);
if ($subtotal <= 0) {
return array_map(fn () => 0, $item_cents);
}
$shares = [];
$remainders = [];
foreach ($item_cents as $id => $cents) {
$exact = $fee_cents * $cents / $subtotal;
$shares[$id] = (int) floor($exact);
$remainders[$id] = $exact - $shares[$id];
}
// Largest remainder first; ties go to the lower id, so reruns agree.
$ids = array_keys($remainders);
usort($ids, fn ($x, $y) => [$remainders[$y], $x] <=> [$remainders[$x], $y]);
$left = $fee_cents - array_sum($shares);
foreach ($ids as $id) {
if ($left-- <= 0) {
break;
}
$shares[$id]++;
}
return $shares;
}
print_r(split_fee(100, ['a' => 1000, 'b' => 1000, 'c' => 1000]));
// a => 34, b => 33, c => 33
Two details matter when you move this into a push params subscriber. The split has to be computed for the whole order every time, then the current item's share picked out by id, because the subscriber sees one item per push. And the order of items with equal remainders must be stable, or two pushes of the same order could put the extra cent on different items. Sorting on remainder and then on item id fixes that. Drupal Commerce also has a price splitter service that it uses to spread order-level promotions across items, and I'd check whether it fits before maintaining your own.
What I'd watch for in this pattern
What I like about doing it in the push params event is that the fee stays where Commerce puts it, on the order, and the Salesforce shape is decided at the edge. Nothing in Drupal has to store a per-item fee that could drift from the adjustment.
The describe call is worth a look. It runs on every push, so make sure the result is cached for each object type rather than fetched each time. And removing the parameter when the field doesn't exist is better than sending a null, because a null can clear a value someone set by hand in Salesforce.
Key takeaways
- One Salesforce Suite push params subscriber can serve order, order item and webform submission mappings when it resolves the related order from whichever entity is being pushed.
- Check that the target Salesforce object has the field and remove the parameter when it doesn't, so the subscriber is safe on every mapping.
- Splitting an order-level fee by item price is easy, but rounding each share on its own can leave the shares a cent away from the fee.
- Allocate in whole cents with the largest remainder method and a stable tie-break, so the item shares always add up to the order total.