Skip to content

Commit

Permalink
Fix tax breakdown on save (#887)
Browse files Browse the repository at this point in the history
* Tax breakdown fix - if total is a price then save its value

* Implement `SerializesCastableAttributes`

* Add full param list

* Update test coverage

* Use toJson()

---------

Co-authored-by: Alec Ritson <hello@itsalec.co.uk>
  • Loading branch information
ryanmitchell and alecritson authored Mar 10, 2023
1 parent 86a509c commit e799ab1
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 3 deletions.
35 changes: 32 additions & 3 deletions packages/core/src/Base/Casts/TaxBreakdown.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@
namespace Lunar\Base\Casts;

use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Contracts\Database\Eloquent\SerializesCastableAttributes;
use Lunar\DataTypes\Price;
use Lunar\Models\Currency;

class TaxBreakdown implements CastsAttributes
class TaxBreakdown implements CastsAttributes, SerializesCastableAttributes
{
/**
* Cast the given value.
Expand All @@ -25,7 +26,6 @@ public function get($model, $key, $value, $attributes)
json_decode($value, false)
)->map(function ($rate) use ($currency) {
$rate->total = new Price($rate->total, $currency, 1);

return $rate;
});
}
Expand All @@ -42,7 +42,36 @@ public function get($model, $key, $value, $attributes)
public function set($model, $key, $value, $attributes)
{
return [
$key => json_encode($value),
$key => json_encode(collect($value)->map(function ($rate) {
if (! is_array($rate)) {
if ($rate->total instanceof Price) {
$rate->total = $rate->total->value;
}
}
return $rate;
})->values()),
];
}

/**
* Get the serialized representation of the value.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @param \Illuminate\Support\Collection $value
* @param array<string, mixed> $attributes
*/
public function serialize($model, $key, $value, $attributes)
{
return $value->map(function ($rate) {
if ($rate->total instanceof Price) {
$rate->total = (object) [
'value' => $rate->total->value,
'formatted' => $rate->total->formatted,
'currency' => $rate->total->currency->toArray(),
];
}
return $rate;
})->toJson();
}
}
4 changes: 4 additions & 0 deletions packages/core/tests/Unit/Actions/Carts/CreateOrderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,10 @@ public function can_create_order()
$this->assertDatabaseHas((new OrderLine())->getTable(), [
'identifier' => $shippingOption->getIdentifier(),
]);

$order->save();
$containsCurrency = str_contains($order->fresh()->getRawOriginal('tax_breakdown'), '"currency"');
$this->assertFalse($containsCurrency);
}

/** @test */
Expand Down

0 comments on commit e799ab1

Please sign in to comment.