- 获取订单下的所有的 trackings
- 获取每个tracking 的运费跟真实运费
// 还原 cost 的 markup
// 9开头的运单都是usps,没有加 markup
if(preg_match('/^9|^42/', $item->tracking_number)){
$markup = 1;
} else {
// 2023-11-10把markup从1.2改为1.26,假设第二天这些单开始被发货时应用新的markup,取11月11日中间的一个order作为分界点
// 2024-01-19改回1.2,air改为1.1
if($item->order_id > 5619000 && $item->order_id <= 5830547) {
$factor1 = 1.15;
$factor2 = 1.26;
} else {
$factor1 = 1.1;
$factor2 = 1.2;
}
$markup = in_array($item->service, ['FIRST_OVERNIGHT', 'PRIORITY_OVERNIGHT'])? $factor1 : $factor2;
}
// 计算预估运费
$item->cost = round($item->cost / $markup, 2);
- 获取 tracking 跟 job 之间的关系, 分摊每个 tracking,按照 op 的 shipping_cost 进行加权
// 判断订单的所有运费是否已经获取到 invoice,如果不是就使用预估运费
$costType = $ordersTrackingsNotInvoiced[strval($orderId)] ?? false ? 'cost' : 'net';
$ops->groupBy('shipping_group')->each(function ($sgops, $shippingGroupId) use ($costType, &$trackings, &$opIds, $orderId) {
// 不存在 Combine shipping 不需要分摊
if (! $shippingGroupId ) {
$sgops->each(function ($op) use ($costType) {
$op->shipping_cost = $op->{$costType};
});
} else {
$total = 0;
$weight = [];
foreach ($sgops as $op) {
// 每个运费只计算一次,join 表的时候数据会多出来
if (!isset($trackings[$op->tracking_number])) {
$total += $op->{$costType};
$trackings[$op->tracking_number] = true;
}
if (!isset($opIds[strval($op->orders_products_id)])) {
// 按照 shipping_fee 进行分摊
$weight[] = $op->shipping_fee;
$opIds[strval($op->orders_products_id)] = true;
} else {
$weight[] = 0;
}
}
$shippCosts = divide_by_weights($total, $weight);
foreach ($sgops as $i => $op) {
$op->shipping_cost = $shippCosts[$i] ?? 0;
}
if ($orderId == $this->orderId) {
\dump($sgops, $total, $weight);
}
}
});