refactor: Migrate loyalty tier system from points to spending and remove tier rewards.

This commit is contained in:
Yoga Pangestu 2025-12-18 19:27:50 +07:00
parent ce7ac20793
commit b132f86ed7
23 changed files with 270 additions and 667 deletions

View File

@ -95,7 +95,7 @@ public function auth(): string
{ {
$this->validateAll(); $this->validateAll();
$tier = Tier::orderBy('min_points')->first(); $tier = Tier::orderBy('min_spending')->first();
$maxUser = User::max('id') + 1; $maxUser = User::max('id') + 1;
$referralCode = ReferralCode::where('code', $this->referral_code)->first(); $referralCode = ReferralCode::where('code', $this->referral_code)->first();
@ -117,7 +117,7 @@ public function auth(): string
Membership::create([ Membership::create([
'user_id' => $user->id, 'user_id' => $user->id,
'tier_id' => $tier->id, 'tier_id' => $tier->id,
'tier_points' => 10, 'reward_points' => 10,
]); ]);
ReferralCode::create([ ReferralCode::create([

View File

@ -1,70 +0,0 @@
<?php
namespace App\Livewire\Forms\Studio\Loyalty\Tier;
use App\Models\TierReward;
use App\Rules\UnsignedInteger;
use Illuminate\Validation\Rule;
use Livewire\Form;
class RewardForm extends Form
{
public ?TierReward $tierReward = null;
public string $tier_id = '';
public string $name = '';
public string $value = '';
public function rules(): array
{
return [
'tier_id' => ['required', Rule::exists('tiers', 'id')],
'name' => ['required', 'string', 'max:100'],
'value' => ['required', new UnsignedInteger],
];
}
public function validationAttributes(): array
{
return [
'name' => 'nama',
'value' => 'nilia',
];
}
public function setRewards(TierReward $tierReward): void
{
$this->tierReward = $tierReward;
$this->tier_id = $tierReward->tier_id;
$this->name = $tierReward->name;
$this->value = formatCurrencyNumber($tierReward->value);
}
public function store(): TierReward
{
$this->validate();
return TierReward::create($this->prepareSavedData());
}
public function update(): TierReward
{
$this->validate();
$this->tierReward->update($this->prepareSavedData());
return $this->tierReward;
}
private function prepareSavedData(): array
{
return [
'tier_id' => $this->tier_id,
'name' => $this->name,
'value' => parseRupiahToInt($this->value),
];
}
}

View File

@ -13,30 +13,30 @@ class TierForm extends Form
public string $name = ''; public string $name = '';
public string $min_points = ''; public string $min_spending = '';
public ?string $max_points = null; public ?string $max_spending = null;
public function rules(): array public function rules(): array
{ {
return [ return [
'name' => ['required', 'string', 'max:50'], 'name' => ['required', 'string', 'max:50'],
'min_points' => ['required', new UnsignedInteger], 'min_spending' => ['required', new UnsignedInteger],
'max_points' => ['nullable', new UnsignedInteger, 'gte:min_points'], 'max_spending' => ['nullable', new UnsignedInteger, 'gte:min_spending'],
]; ];
} }
public function withValidator($validator): void public function withValidator($validator): void
{ {
$validator->after(function ($validator) { $validator->after(function ($validator) {
$minPoints = parseRupiahToInt($this->min_points); $minSpending = parseRupiahToInt($this->min_spending);
$maxPoints = $this->max_points ? parseRupiahToInt($this->max_points) : null; $maxSpending = $this->max_spending ? parseRupiahToInt($this->max_spending) : null;
$ignoreId = $this->tier?->id; $ignoreId = $this->tier?->id;
$tierErrors = Tier::validateTierPoints($minPoints, $maxPoints, $ignoreId); $tierErrors = Tier::validateTierPoints($minSpending, $maxSpending, $ignoreId);
foreach ($tierErrors as $error) { foreach ($tierErrors as $error) {
$validator->errors()->add('min_points', $error); $validator->errors()->add('min_spending', $error);
} }
}); });
} }
@ -45,8 +45,8 @@ public function validationAttributes(): array
{ {
return [ return [
'name' => 'nama', 'name' => 'nama',
'min_points' => 'min. poin', 'min_spending' => 'min. belanja',
'max_points' => 'maks. poin', 'max_spending' => 'maks. belanja',
]; ];
} }
@ -55,8 +55,8 @@ public function setTier(Tier $tier): void
$this->tier = $tier; $this->tier = $tier;
$this->name = $tier->name; $this->name = $tier->name;
$this->min_points = $tier->min_points; $this->min_spending = formatCurrencyNumber($tier->min_spending);
$this->max_points = $tier->max_points; $this->max_spending = $tier->max_spending ? formatCurrencyNumber($tier->max_spending) : null;
} }
public function store(): Tier public function store(): Tier
@ -83,8 +83,8 @@ private function prepareSavedData(): array
{ {
return [ return [
'name' => $this->name, 'name' => $this->name,
'min_points' => parseRupiahToInt($this->min_points), 'min_spending' => parseRupiahToInt($this->min_spending),
'max_points' => parseRupiahToInt($this->max_points), 'max_spending' => parseRupiahToInt($this->max_spending),
]; ];
} }
} }

View File

@ -6,8 +6,10 @@
use App\Enums\OrderStatus; use App\Enums\OrderStatus;
use App\Enums\PaymentMethod; use App\Enums\PaymentMethod;
use App\Enums\PaymentStatus; use App\Enums\PaymentStatus;
use App\Enums\PointRecordType;
use App\Models\Order; use App\Models\Order;
use App\Models\Payment; use App\Models\Payment;
use App\Models\PointRecord;
use App\Models\User; use App\Models\User;
use App\Models\Voucher; use App\Models\Voucher;
use App\Rules\UnsignedInteger; use App\Rules\UnsignedInteger;
@ -193,12 +195,19 @@ public function store(): array
} }
} }
// Update member tier points // Update member total spending and reward points
if ($member && $member->membership) { if ($member && $member->membership) {
$member->membership()->update([ $member->membership->increment('total_spending', $total);
'tier_points' => DB::raw("tier_points + $pointsEarned"), $member->membership->increment('reward_points', $pointsEarned);
'reward_points' => DB::raw("reward_points + $pointsEarned"), $member->membership->update(['last_transaction_at' => now()]);
'last_transaction_at' => now(), $member->membership->recalculateTier();
PointRecord::create([
'user_id' => $member->id,
'description' => 'Pembelian #'.$order->invoice_number,
'change' => $pointsEarned,
'is_addition' => true,
'type' => PointRecordType::REWARD,
]); ]);
} }
}); });

View File

@ -2,11 +2,8 @@
namespace App\Livewire\Member; namespace App\Livewire\Member;
use App\Enums\PointRecordType;
use App\Models\Membership as MembershipModel; use App\Models\Membership as MembershipModel;
use App\Models\PointRecord;
use App\Models\Tier; use App\Models\Tier;
use App\Models\TierReward;
use Livewire\Attributes\Layout; use Livewire\Attributes\Layout;
use Livewire\Attributes\Title; use Livewire\Attributes\Title;
use Livewire\Component; use Livewire\Component;
@ -21,48 +18,41 @@ class Membership extends Component
public string $nextTierName = ''; public string $nextTierName = '';
public string $currentPoints = ''; public string $currentSpending = '';
public string $nextTierPoints = ''; public string $nextTierSpending = '';
public string $progress = ''; public string $progress = '0';
public array $rewards = [];
public array $pointRecords = [];
public function mount() public function mount()
{ {
$this->membership = MembershipModel::with(['tier', 'tier.rewards'])->where('user_id', auth()->id())->first(); $this->membership = MembershipModel::with(['tier'])->where('user_id', auth()->id())->first();
if (! $this->membership) { if (! $this->membership) {
return; return;
} }
$monthlyTierAddition = PointRecord::where('user_id', auth()->id()) $nextTier = Tier::where('min_spending', '>', $this->membership->total_spending)
->where('type', PointRecordType::TIER) ->orderBy('min_spending', 'asc')
->where('is_addition', true)
->whereYear('created_at', now()->year)
->whereMonth('created_at', now()->month)
->sum('change');
$nextTier = Tier::where('min_points', '>', $this->membership->tier_points)
->orderBy('min_points', 'asc')
->first(); ->first();
$this->nextTierName = $nextTier ? $nextTier->name : 'Maksimal'; $this->nextTierName = $nextTier ? $nextTier->name : 'Maksimal';
$this->currentPoints = $this->membership->tier_points; $this->currentSpending = formatCurrencyNumber($this->membership->total_spending, 'Rp');
$this->nextTierPoints = $nextTier ? $nextTier->min_points : 'Maksimal'; $this->nextTierSpending = $nextTier ? formatCurrencyNumber($nextTier->min_spending, 'Rp') : 'Maksimal';
$this->progress = ($this->membership->tier_points / $nextTier->min_points) * 100; if ($nextTier) {
$this->progress = ($this->membership->total_spending / $nextTier->min_spending) * 100;
} else {
$this->progress = '100';
}
$this->stats = [ $this->stats = [
[ [
'title' => 'Poin Tier', 'title' => 'Poin Hadiah',
'value' => formatCurrencyNumber($this->membership->tier_points), 'value' => formatCurrencyNumber($this->membership->reward_points, ''),
'description' => '+'.formatCurrencyNumber($monthlyTierAddition).' bulan ini', 'description' => 'Gunakan poin untuk hadiah menarik',
], ],
[ [
'title' => 'Tier Sekarang', 'title' => 'Tier Sekarang',
@ -70,38 +60,16 @@ public function mount()
'description' => 'Terdaftar sejak '.formatDateLocalized($this->membership->created_at), 'description' => 'Terdaftar sejak '.formatDateLocalized($this->membership->created_at),
], ],
[ [
'title' => 'Tier Selanjutnya', 'title' => 'Total Belanja',
'value' => $nextTier ? $nextTier->name : 'Maksimal', 'value' => formatCurrencyNumber($this->membership->total_spending, 'Rp'),
'description' => $nextTier ? ($nextTier->min_points - $this->membership->tier_points).' poin lagi' : 'Anda sudah berada di tier tertinggi', 'description' => 'Akumulasi seluruh transaksi',
], ],
[ [
'title' => 'Poin Hadiah', 'title' => 'Tier Selanjutnya',
'value' => formatCurrencyNumber($this->membership->reward_points), 'value' => $nextTier ? $nextTier->name : 'Maksimal',
'description' => 'Nikmati hadiah sekarang', 'description' => $nextTier ? formatCurrencyNumber($nextTier->min_spending - $this->membership->total_spending, 'Rp').' lagi' : 'Anda sudah berada di tier tertinggi',
], ],
]; ];
$this->rewards = TierReward::where('tier_id', $this->membership->tier_id)
->latest()
->get()
->map(fn ($reward) => [
'name' => $reward->name,
'value' => formatCurrencyNumber($reward->value, 'Rp'),
])
->toArray();
$this->pointRecords = PointRecord::where('user_id', auth()->id())
->latest()
->limit(10)
->get()
->map(fn ($record) => [
'date' => formatDateLocalized($record->created_at),
'description' => $record->description,
'change' => formatCurrencyNumber($record->change),
'type' => $record->type->label(),
'is_addition' => $record->is_addition,
])
->toArray();
} }
public function render() public function render()

View File

@ -2,10 +2,8 @@
namespace App\Livewire\Member; namespace App\Livewire\Member;
use App\Enums\PointRecordType;
use App\Livewire\Forms\Studio\Loyalty\CustomerForm; use App\Livewire\Forms\Studio\Loyalty\CustomerForm;
use App\Models\Membership; use App\Models\Membership;
use App\Models\PointRecord;
use App\Models\Tier; use App\Models\Tier;
use App\Traits\Components\WithToast; use App\Traits\Components\WithToast;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
@ -51,16 +49,7 @@ public function save()
if (! auth()->user()->membership()->exists()) { if (! auth()->user()->membership()->exists()) {
Membership::create([ Membership::create([
'user_id' => auth()->id(), 'user_id' => auth()->id(),
'tier_id' => Tier::orderBy('min_points')->first()->id, 'tier_id' => Tier::orderBy('min_spending')->first()->id,
'tier_points' => 10,
]);
PointRecord::create([
'user_id' => auth()->id(),
'description' => 'Pendaftaran',
'change' => 10,
'is_addition' => true,
'type' => PointRecordType::TIER,
]); ]);
} }
}); });

View File

@ -1,9 +1,10 @@
<?php <?php
namespace App\Livewire\Studio\Loyalty\Tier; namespace App\Livewire\Studio\Loyalty;
use App\Livewire\Forms\Studio\Loyalty\TierForm; use App\Livewire\Forms\Studio\Loyalty\TierForm;
use App\Models\Bottle; use App\Models\Bottle;
use App\Models\Membership;
use App\Models\Perfume; use App\Models\Perfume;
use App\Models\Product; use App\Models\Product;
use App\Models\Tier as TierModel; use App\Models\Tier as TierModel;
@ -20,7 +21,7 @@
use Livewire\Component; use Livewire\Component;
#[Title('Tier')] #[Title('Tier')]
class Index extends Component class Tier extends Component
{ {
use WithAuthorization, WithCloseModal, WithConfirmation, WithSubscribeNotification, WithToast, WithUpdatedData; use WithAuthorization, WithCloseModal, WithConfirmation, WithSubscribeNotification, WithToast, WithUpdatedData;
@ -41,41 +42,33 @@ public function mount(): void
public function loadTiers(): void public function loadTiers(): void
{ {
$this->tiers = TierModel::withCount('memberships') $this->tiers = TierModel::withCount('memberships')
->withCount('rewards') ->orderBy('min_spending', 'asc')
->orderBy('min_points', 'asc')
->get() ->get()
->map(function ($tier) { ->map(fn (TierModel $tier) => [
return [ 'id' => $tier->id,
'id' => $tier->id, 'hash' => $tier->hash,
'hash' => $tier->hash, 'name' => $tier->name,
'name' => $tier->name, 'min_spending' => formatCurrencyNumber($tier->min_spending, 'Rp'),
'min_points' => formatCurrencyNumber($tier->min_points), 'max_spending' => $tier->max_spending ? formatCurrencyNumber($tier->max_spending, 'Rp') : 'Tak terbatas',
'max_points' => formatCurrencyNumber($tier->max_points), 'total_members' => formatCurrencyNumber($tier->memberships_count),
'total_members' => formatCurrencyNumber($tier->memberships_count), 'top_member' => $this->getTopMemberStats($tier->id),
'total_rewards' => $tier->rewards_count, ])
];
})
->toArray(); ->toArray();
} }
public function getTopMemberStats($tierId): ?array public function getTopMemberStats($tierId): ?array
{ {
$tier = TierModel::with(['memberships.user.customer.orders.items'])->find($tierId); $topMembership = Membership::where('tier_id', $tierId)
if (! $tier) {
return null;
}
$topMembership = $tier->memberships()
->with(['user.customer.orders.items']) ->with(['user.customer.orders.items'])
->orderByDesc('tier_points') ->orderByDesc('total_spending')
->first(); ->first();
if (! $topMembership || ! $topMembership->user || ! $topMembership->user->customer) { if (! $topMembership || ! $topMembership->user || ! $topMembership->user->customer) {
return null; return null;
} }
$orders = $topMembership->user->customer->orders; $customer = $topMembership->user->customer;
$orders = $customer->orders;
$totalOrders = $orders->count(); $totalOrders = $orders->count();
// Sum items // Sum items
@ -89,8 +82,8 @@ public function getTopMemberStats($tierId): ?array
$grandTotal = $orders->sum('total'); $grandTotal = $orders->sum('total');
return [ return [
'name' => $topMembership->user->customer->name, 'name' => $customer->name,
'points' => formatCurrencyNumber($topMembership->tier_points), 'spending' => formatCurrencyNumber($topMembership->total_spending, 'Rp'),
'total_orders' => formatCurrencyNumber($totalOrders), 'total_orders' => formatCurrencyNumber($totalOrders),
'items' => [ 'items' => [
'total_perfume' => formatCurrencyNumber($totalPerfume), 'total_perfume' => formatCurrencyNumber($totalPerfume),
@ -111,7 +104,7 @@ public function create(): void
$this->form->store(); $this->form->store();
// Reorder the entire tier chain to ensure proper max_points // Reorder the entire tier chain to ensure proper max_spending
TierModel::reorderTierChain(); TierModel::reorderTierChain();
// Reload tiers to reflect the changes // Reload tiers to reflect the changes
@ -126,13 +119,13 @@ public function update(): void
{ {
$this->canOrAbort('update tier'); $this->canOrAbort('update tier');
$oldMinPoints = $this->form->tier->min_points; $oldMinSpending = $this->form->tier->min_spending;
$newMinPoints = parseRupiahToInt($this->form->min_points); $newMinSpending = parseRupiahToInt($this->form->min_spending);
$this->form->update(); $this->form->update();
// If min_points changed, reorder the entire tier chain // If min_spending changed, reorder the entire tier chain
if ($oldMinPoints !== $newMinPoints) { if ($oldMinSpending !== $newMinSpending) {
TierModel::reorderTierChain(); TierModel::reorderTierChain();
} }
@ -158,7 +151,7 @@ public function delete(TierModel $tier): void
$tier->delete(); $tier->delete();
// Reorder tier chain after deletion to ensure proper max_points // Reorder tier chain after deletion to ensure proper max_spending
TierModel::reorderTierChain(); TierModel::reorderTierChain();
// Reload tiers to reflect the changes // Reload tiers to reflect the changes
@ -183,7 +176,7 @@ public function openModal(string $method, string $modalTitle, ?string $id = null
public function render(): View public function render(): View
{ {
return view('livewire.studio.loyalty.tier.index', [ return view('livewire.studio.loyalty.tiers', [
'pageTitle' => 'Tier', 'pageTitle' => 'Tier',
]); ]);
} }

View File

@ -1,121 +0,0 @@
<?php
namespace App\Livewire\Studio\Loyalty\Tier;
use App\Livewire\Forms\Studio\Loyalty\Tier\RewardForm;
use App\Livewire\Studio\Loyalty\Tier\Index as Tier;
use App\Models\TierReward;
use App\Traits\Authorization\WithAuthorization;
use App\Traits\Components\WithCloseModal;
use App\Traits\Components\WithConfirmation;
use App\Traits\Components\WithToast;
use App\Traits\Notification\WithSubscribeNotification;
use App\Traits\Utilities\WithUpdatedData;
use Flux\Flux;
use Illuminate\Contracts\View\View;
use Livewire\Attributes\On;
use Livewire\Attributes\Title;
use Livewire\Component;
#[Title('Hadiah')]
class Reward extends Component
{
use WithAuthorization, WithCloseModal, WithConfirmation, WithSubscribeNotification, WithToast, WithUpdatedData;
public RewardForm $form;
public string $modalTitle = '';
public string $method = '';
public array $rewards = [];
public function create(): void
{
$this->canOrAbort('create tier reward');
$reward = $this->form->store();
$this->rewards = collect($this->rewards)
->push(
$reward->only(['tier_id', 'name', 'value']) + ['hash' => $reward->hash]
)
->toArray();
$this->dispatch('data:tiersUpdated')->to(Tier::class);
$this->toast('Hadiah berhasil ditambahkan.');
Flux::modal('reward-form-modal')->close();
}
public function update(): void
{
$this->canOrAbort('update tier reward');
$reward = $this->form->update();
$updatedReward = $reward->only(['tier_id', 'name', 'value']) + [
'hash' => $reward->hash,
];
$this->rewards = collect($this->rewards)
->map(
fn ($item) => $item['hash'] === $updatedReward['hash']
? $updatedReward
: $item
)
->toArray();
$this->toast('Hadiah berhasil diperbarui.');
Flux::modal('reward-form-modal')->close();
}
public function delete(TierReward $reward): void
{
$this->canOrAbort('delete tier reward');
$reward->delete();
$this->rewards = collect($this->rewards)
->reject(fn ($item) => $item['hash'] === $reward->hash)
->values()
->toArray();
$this->toast('Hadiah berhasil dihapus.');
$this->dispatch('data:tiersUpdated')->to(Tier::class);
Flux::modal('delete-reward-confirmation')->close();
}
#[On('modal:open:reward')]
public function openModal(string $method, string $modalTitle, ?string $tier_id = null, ?string $id = null)
{
$this->resetValidation();
$this->resetErrorBag();
$this->method = $method;
$this->modalTitle = $modalTitle;
$this->form->tier_id = $tier_id;
$this->rewards = TierReward::where('tier_id', $tier_id)
->latest()
->get()
->append('hash')
->toArray();
$id && $this->form->setRewards(
TierReward::byHashOrFail($id)
);
}
public function render(): View
{
return view('livewire.studio.loyalty.tier.reward', [
'pageTitle' => 'Hadiah',
]);
}
}

View File

@ -2,6 +2,8 @@
namespace App\Models; namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Database\Eloquent\SoftDeletes;
@ -16,7 +18,7 @@ class Membership extends Model
protected function casts(): array protected function casts(): array
{ {
return [ return [
'tier_points' => 'int', 'total_spending' => 'int',
'reward_points' => 'int', 'reward_points' => 'int',
]; ];
} }
@ -30,4 +32,15 @@ public function tier(): BelongsTo
{ {
return $this->belongsTo(Tier::class); return $this->belongsTo(Tier::class);
} }
#[Scope]
protected function scopeForSpending(Builder $query, $totalSpending): void
{
$query
->where('min_spending', '<=', $totalSpending)
->where(function ($q) use ($totalSpending) {
$q->whereNull('max_spending')
->orWhere('max_spending', '>=', $totalSpending);
});
}
} }

View File

@ -21,21 +21,21 @@ class Tier extends Model
protected function casts(): array protected function casts(): array
{ {
return [ return [
'min_points' => 'int', 'min_spending' => 'int',
'max_points' => 'int', 'max_spending' => 'int',
]; ];
} }
public static function isOverlap(int $minPoints, ?int $maxPoints, ?int $ignoreId = null): bool public static function isOverlap(int $minSpending, ?int $maxSpending, ?int $ignoreId = null): bool
{ {
$maxPointsCheck = $maxPoints ?? PHP_INT_MAX; $maxSpendingCheck = $maxSpending ?? PHP_INT_MAX;
return self::when($ignoreId, fn ($query) => $query->where('id', '!=', $ignoreId)) return self::when($ignoreId, fn ($query) => $query->where('id', '!=', $ignoreId))
->get() ->get()
->contains(function ($tier) use ($minPoints, $maxPointsCheck) { ->contains(function ($tier) use ($minSpending, $maxSpendingCheck) {
$tierMax = $tier->max_points ?? PHP_INT_MAX; $tierMax = $tier->max_spending ?? PHP_INT_MAX;
return ($minPoints <= $tierMax) && ($maxPointsCheck >= $tier->min_points); return ($minSpending <= $tierMax) && ($maxSpendingCheck >= $tier->min_spending);
}); });
} }
@ -44,11 +44,6 @@ public function memberships(): HasMany
return $this->hasMany(Membership::class); return $this->hasMany(Membership::class);
} }
public function rewards(): HasMany
{
return $this->hasMany(TierReward::class);
}
public function vouchers(): BelongsToMany public function vouchers(): BelongsToMany
{ {
return $this->belongsToMany(Voucher::class); return $this->belongsToMany(Voucher::class);
@ -56,45 +51,45 @@ public function vouchers(): BelongsToMany
public static function getHighestTier() public static function getHighestTier()
{ {
return self::orderByDesc('min_points')->first(); return self::orderByDesc('min_spending')->first();
} }
public static function updatePreviousTierMaxPoints(int $newMinPoints): void public static function updatePreviousTierMaxPoints(int $newMinSpending): void
{ {
$previousTier = self::whereNull('max_points') $previousTier = self::whereNull('max_spending')
->orWhere('max_points', '>=', $newMinPoints) ->orWhere('max_spending', '>=', $newMinSpending)
->orderByDesc('min_points') ->orderByDesc('min_spending')
->first(); ->first();
if ($previousTier && is_null($previousTier->max_points)) { if ($previousTier && is_null($previousTier->max_spending)) {
$previousTier->update(['max_points' => $newMinPoints - 1]); $previousTier->update(['max_spending' => $newMinSpending - 1]);
} }
} }
public static function validateTierPoints(int $minPoints, ?int $maxPoints = null, ?int $ignoreId = null): array public static function validateTierPoints(int $minSpending, ?int $maxSpending = null, ?int $ignoreId = null): array
{ {
$errors = []; $errors = [];
// Get the highest tier (excluding current if updating) // Get the highest tier (excluding current if updating)
$highestTier = self::when($ignoreId, fn ($query) => $query->where('id', '!=', $ignoreId)) $highestTier = self::when($ignoreId, fn ($query) => $query->where('id', '!=', $ignoreId))
->orderByDesc('min_points') ->orderByDesc('min_spending')
->first(); ->first();
// If there's a highest tier with null max_points, it should be updated first // If there's a highest tier with null max_spending, it should be updated first
if ($highestTier && is_null($highestTier->max_points)) { if ($highestTier && is_null($highestTier->max_spending)) {
if ($minPoints <= $highestTier->min_points) { if ($minSpending <= $highestTier->min_spending) {
$errors[] = "Min. poin harus lebih besar dari {$highestTier->min_points} (tier {$highestTier->name})"; $errors[] = "Min. belanja harus lebih besar dari {$highestTier->min_spending} (tier {$highestTier->name})";
} }
} elseif ($highestTier) { } elseif ($highestTier) {
$requiredMinPoints = ($highestTier->max_points ?? $highestTier->min_points) + 1; $requiredMinSpending = ($highestTier->max_spending ?? $highestTier->min_spending) + 1;
if ($minPoints <= $highestTier->max_points) { if ($minSpending <= $highestTier->max_spending) {
$errors[] = "Min. poin harus lebih besar dari {$highestTier->max_points} (tier {$highestTier->name})"; $errors[] = "Min. belanja harus lebih besar dari {$highestTier->max_spending} (tier {$highestTier->name})";
} }
} }
// Check for overlap with existing tiers // Check for overlap with existing tiers
if (self::isOverlap($minPoints, $maxPoints, $ignoreId)) { if (self::isOverlap($minSpending, $maxSpending, $ignoreId)) {
$errors[] = 'Rentang poin tier tumpang tindih dengan tier lain'; $errors[] = 'Rentang belanja tier tumpang tindih dengan tier lain';
} }
return $errors; return $errors;
@ -102,16 +97,16 @@ public static function validateTierPoints(int $minPoints, ?int $maxPoints = null
public static function reorderTierChain(): void public static function reorderTierChain(): void
{ {
$tiers = self::orderBy('min_points')->get(); $tiers = self::orderBy('min_spending')->get();
foreach ($tiers as $index => $tier) { foreach ($tiers as $index => $tier) {
if ($index < $tiers->count() - 1) { if ($index < $tiers->count() - 1) {
// Set max_points to min_points of next tier - 1 // Set max_spending to min_spending of next tier - 1
$nextTier = $tiers[$index + 1]; $nextTier = $tiers[$index + 1];
$tier->update(['max_points' => $nextTier->min_points - 1]); $tier->update(['max_spending' => $nextTier->min_spending - 1]);
} else { } else {
// Last tier should have null max_points // Last tier should have null max_spending
$tier->update(['max_points' => null]); $tier->update(['max_spending' => null]);
} }
} }
} }
@ -123,7 +118,7 @@ public static function canDeleteTier(int $tierId): array
return ['can_delete' => false, 'message' => 'Tier tidak ditemukan']; return ['can_delete' => false, 'message' => 'Tier tidak ditemukan'];
} }
$tiers = self::orderBy('min_points')->get(); $tiers = self::orderBy('min_spending')->get();
$tierIndex = $tiers->search(fn ($t) => $t->id === $tierId); $tierIndex = $tiers->search(fn ($t) => $t->id === $tierId);
// Can always delete the lowest tier (first tier) // Can always delete the lowest tier (first tier)
@ -131,7 +126,7 @@ public static function canDeleteTier(int $tierId): array
return ['can_delete' => true, 'message' => '']; return ['can_delete' => true, 'message' => ''];
} }
// Can always delete the highest tier (last tier with null max_points) // Can always delete the highest tier (last tier with null max_spending)
if ($tierIndex === $tiers->count() - 1) { if ($tierIndex === $tiers->count() - 1) {
return ['can_delete' => true, 'message' => '']; return ['can_delete' => true, 'message' => ''];
} }
@ -139,7 +134,7 @@ public static function canDeleteTier(int $tierId): array
// Cannot delete middle tiers as it would create gaps in the tier chain // Cannot delete middle tiers as it would create gaps in the tier chain
return [ return [
'can_delete' => false, 'can_delete' => false,
'message' => 'Tidak dapat menghapus tier tengah karena akan mengacaukan sistem poin. Tier harus membentuk rantai yang kontinyu.', 'message' => 'Tidak dapat menghapus tier tengah karena akan mengacaukan sistem belanja. Tier harus membentuk rantai yang kontinyu.',
]; ];
} }
} }

View File

@ -16,7 +16,7 @@ public function definition(): array
return [ return [
'user_id' => User::factory(), 'user_id' => User::factory(),
'tier_id' => Tier::factory(), 'tier_id' => Tier::factory(),
'tier_points' => $this->faker->numberBetween(0, 1000), 'total_spending' => $this->faker->numberBetween(0, 5000000),
'reward_points' => $this->faker->numberBetween(0, 1000), 'reward_points' => $this->faker->numberBetween(0, 1000),
'last_transaction_at' => $this->faker->optional()->dateTimeBetween('-30 days', 'now'), 'last_transaction_at' => $this->faker->optional()->dateTimeBetween('-30 days', 'now'),
]; ];

View File

@ -13,8 +13,8 @@ public function definition(): array
{ {
return [ return [
'name' => $this->faker->name(), 'name' => $this->faker->name(),
'min_points' => $this->faker->randomNumber(), 'min_spending' => $this->faker->randomNumber(),
'max_points' => $this->faker->optional()->randomNumber(), 'max_spending' => $this->faker->optional()->randomNumber(),
]; ];
} }
} }

View File

@ -14,8 +14,8 @@ public function up(): void
Schema::create('tiers', function (Blueprint $table) { Schema::create('tiers', function (Blueprint $table) {
$table->id(); $table->id();
$table->string('name', 50); $table->string('name', 50);
$table->unsignedInteger('min_points'); $table->unsignedBigInteger('min_spending');
$table->unsignedInteger('max_points')->nullable(); $table->unsignedBigInteger('max_spending')->nullable();
$table->timestamp('created_at')->useCurrent(); $table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->nullable()->useCurrentOnUpdate(); $table->timestamp('updated_at')->nullable()->useCurrentOnUpdate();
$table->softDeletes(); $table->softDeletes();

View File

@ -15,7 +15,7 @@ public function up(): void
$table->id(); $table->id();
$table->foreignId('user_id')->constrained()->cascadeOnDelete(); $table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->foreignId('tier_id')->constrained()->cascadeOnDelete(); $table->foreignId('tier_id')->constrained()->cascadeOnDelete();
$table->unsignedInteger('tier_points')->default(0); $table->unsignedBigInteger('total_spending')->default(0);
$table->unsignedInteger('reward_points')->default(0); $table->unsignedInteger('reward_points')->default(0);
$table->timestamp('last_transaction_at')->nullable(); $table->timestamp('last_transaction_at')->nullable();
$table->timestamp('created_at')->useCurrent(); $table->timestamp('created_at')->useCurrent();

View File

@ -1,32 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('tier_rewards', function (Blueprint $table) {
$table->id();
$table->foreignId('tier_id')->constrained()->cascadeOnDelete();
$table->string('name', 100);
$table->unsignedInteger('value');
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->nullable()->useCurrentOnUpdate();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('tier_rewards');
}
};

View File

@ -10,7 +10,7 @@ class CustomerSeeder extends Seeder
{ {
public function run(): void public function run(): void
{ {
for ($i = 0; $i < 500; $i++) { for ($i = 0; $i < 10; $i++) {
$hasUser = fake()->boolean(70); $hasUser = fake()->boolean(70);
$userId = null; $userId = null;

View File

@ -14,24 +14,28 @@ public function run(): void
$tiers = Tier::all(); $tiers = Tier::all();
$userIds = Customer::whereNotNull('user_id') $userIds = Customer::whereNotNull('user_id')
->pluck('id') ->pluck('user_id')
->unique() ->unique()
->toArray(); ->toArray();
foreach ($userIds as $userId) { foreach ($userIds as $userId) {
$totalPoints = fake()->numberBetween(0, 10000); $totalSpending = fake()->numberBetween(0, 15000000);
$tier = $tiers->first(function ($tier) use ($totalPoints) { $tier = $tiers->first(function ($tier) use ($totalSpending) {
$min = $tier->min_points; $min = $tier->min_spending;
$max = $tier->max_points ?? PHP_INT_MAX; $max = $tier->max_spending ?? PHP_INT_MAX;
return $totalPoints >= $min && $totalPoints <= $max; return $totalSpending >= $min && $totalSpending <= $max;
}); });
if (! $tier) {
$tier = $tiers->first(); // Default to Bronze
}
Membership::create([ Membership::create([
'user_id' => $userId, 'user_id' => $userId,
'tier_id' => $tier->id, 'tier_id' => $tier->id,
'tier_points' => $totalPoints, 'total_spending' => $totalSpending,
]); ]);
} }
} }

View File

@ -12,28 +12,28 @@ public function run(): void
$tiers = [ $tiers = [
[ [
'name' => 'Bronze', 'name' => 'Bronze',
'min_points' => 0, 'min_spending' => 0,
'max_points' => 49, 'max_spending' => 499999,
], ],
[ [
'name' => 'Silver', 'name' => 'Silver',
'min_points' => 50, 'min_spending' => 500000,
'max_points' => 99, 'max_spending' => 1499999,
], ],
[ [
'name' => 'Gold', 'name' => 'Gold',
'min_points' => 100, 'min_spending' => 1500000,
'max_points' => 499, 'max_spending' => 4999999,
], ],
[ [
'name' => 'Platinum', 'name' => 'Platinum',
'min_points' => 500, 'min_spending' => 5000000,
'max_points' => 1999, 'max_spending' => 9999999,
], ],
[ [
'name' => 'Diamond', 'name' => 'Diamond',
'min_points' => 2000, 'min_spending' => 10000000,
'max_points' => null, 'max_spending' => null,
], ],
]; ];

View File

@ -1,92 +0,0 @@
<div>
<flux:modal name="reward-view-modal" class="w-[95%] max-w-sm md:max-w-xl mx-auto"
@close="closeModal('reward-view-modal')">
<div class="p-4 space-y-6">
<flux:heading size="lg">{{ $modalTitle }}</flux:heading>
<flux:table class="bo">
<flux:table.columns>
<flux:table.column>Nama</flux:table.column>
<flux:table.column>Nilai</flux:table.column>
<flux:table.column>Aksi</flux:table.column>
</flux:table.columns>
<flux:table.rows>
@foreach ($rewards as $reward)
<flux:table.row>
<flux:table.cell>{{ $reward['name'] }}</flux:table.cell>
<flux:table.cell>{{ formatCurrencyNumber($reward['value'], 'Rp') }}</flux:table.cell>
<flux:table.cell>
<div class="flex gap-2 pt-2 border-gray-200 dark:border-gray-700">
@can('update tier reward')
<flux:modal.trigger name="reward-form-modal">
<flux:tooltip content="Ubah">
<flux:button variant="primary" color="yellow" icon="pencil-square"
size="sm"
wire:click="$dispatch('modal:open:reward', {method: 'update', 'modalTitle': 'Ubah Hadiah', 'tier_id': '{{ $reward['tier_id'] }}', 'id' : '{{ $reward['hash'] }}'})">
</flux:button>
</flux:tooltip>
</flux:modal.trigger>
@endcan
@can('update tier reward')
<flux:modal.trigger name="delete-reward-confirmation">
<flux:tooltip content="Hapus">
<flux:button variant="danger" icon="trash" size="sm"
wire:click="$dispatch('fn:confirmAction', {id: '{{ $reward['hash'] }}'})">
</flux:button>
</flux:tooltip>
</flux:modal.trigger>
@endcan
</div>
</flux:table.cell>
</flux:table.row>
@endforeach
</flux:table.rows>
</flux:table>
</div>
</flux:modal>
<flux:modal name="reward-form-modal" class="w-[95%] max-w-sm md:max-w-xl mx-auto"
@close="closeModal('reward-form-modal')">
<div class="p-4 space-y-6">
<flux:heading size="lg">{{ $modalTitle }}</flux:heading>
<flux:input name="form.tier_id" type="hidden"></flux:input>
<flux:field>
<flux:label>Nama <span class="text-red-500 ms-1">*</span></flux:label>
<flux:input placeholder="Voucher Belanja 20k" wire:model="form.name" autofocus autocomplete="off" />
<flux:error name="form.name" />
</flux:field>
<flux:field>
<flux:label>Nilai <span class="text-red-500 ms-1">*</span>
</flux:label>
<flux:description>Nilai hanya berupa rupiah, bukan persentase.</flux:description>
<flux:input.group>
<flux:input.group.prefix>Rp</flux:input.group.prefix>
<flux:input placeholder="xxx" x-mask:dynamic="$money($input, ',')" wire:model="form.value"
autocomplete="off" />
</flux:input.group>
<flux:error name="form.value" />
</flux:field>
<div class="flex">
<flux:spacer />
<flux:button variant="primary" class="sm:w-auto cursor-pointer" wire:click="{{ $method }}">
Simpan
</flux:button>
</div>
</div>
</flux:modal>
@include('components.modals.confirmation', [
'modalName' => 'delete-reward-confirmation',
'modalTitle' => 'Apakah Anda yakin?',
'modalMessage' => 'Data yang berelasi dengan data ini juga akan ikut terhapus.',
'buttonVariant' => 'primary',
'buttonColor' => 'danger',
'buttonText' => 'Ya, Hapus',
])
</div>

View File

@ -21,23 +21,6 @@
class="hover:shadow-lg transition-shadow duration-200 bg-white dark:bg-gray-900 text-gray-900 dark:text-white"> class="hover:shadow-lg transition-shadow duration-200 bg-white dark:bg-gray-900 text-gray-900 dark:text-white">
<div class="space-y-4"> <div class="space-y-4">
@can('create tier reward')
@if ($tier['total_rewards'] == 0)
<flux:callout icon="exclamation-circle" variant="warning" inline>
<flux:callout.heading>Belum ada hadiah untuk tier ini, silakan tambah terlebih dahulu.
</flux:callout.heading>
<x-slot name="actions">
<flux:modal.trigger name="reward-form-modal">
<flux:button variant="primary" color="primary" size="sm"
wire:click="$dispatch('modal:open:reward', {method: 'create', 'modalTitle': 'Tambah Hadiah', 'tier_id': '{{ $tier['id'] }}'})">
Tambah</flux:button>
</flux:modal.trigger>
</x-slot>
</flux:callout>
@endif
@endcan
<div class="flex items-start justify-between"> <div class="flex items-start justify-between">
<flux:heading size="lg">{{ $tier['name'] }} <flux:heading size="lg">{{ $tier['name'] }}
</flux:heading> </flux:heading>
@ -45,12 +28,12 @@ class="hover:shadow-lg transition-shadow duration-200 bg-white dark:bg-gray-900
<div class="space-y-2"> <div class="space-y-2">
<div class="flex justify-between text-sm"> <div class="flex justify-between text-sm">
<span class="text-gray-500 dark:text-gray-400">Min. Poin:</span> <span class="text-gray-500 dark:text-gray-400">Min. Belanja:</span>
<span class="font-medium">{{ $tier['min_points'] }}</span> <span class="font-medium">{{ $tier['min_spending'] }}</span>
</div> </div>
<div class="flex justify-between text-sm"> <div class="flex justify-between text-sm">
<span class="text-gray-500 dark:text-gray-400">Maks. Poin:</span> <span class="text-gray-500 dark:text-gray-400">Maks. Belanja:</span>
<span class="font-medium">{{ $tier['max_points'] }}</span> <span class="font-medium">{{ $tier['max_spending'] }}</span>
</div> </div>
<flux:separator /> <flux:separator />
@ -60,23 +43,15 @@ class="hover:shadow-lg transition-shadow duration-200 bg-white dark:bg-gray-900
<span class="font-medium">{{ $tier['total_members'] }}</span> <span class="font-medium">{{ $tier['total_members'] }}</span>
</div> </div>
<div class="flex justify-between text-sm"> @if ($tier['top_member'])
<span class="text-gray-500 dark:text-gray-400">Total Hadiah:</span>
<span class="font-medium">{{ $tier['total_rewards'] }}</span>
</div>
@php
$topMember = $this->getTopMemberStats($tier['id']);
@endphp
@if ($topMember)
<div class="text-sm"> <div class="text-sm">
<span class="text-gray-500 dark:text-gray-400 font-semibold">Member Dengan Poin <span class="text-gray-500 dark:text-gray-400 font-semibold">Member Dengan Belanja
Tertinggi:</span> Tertinggi:</span>
<div <div
class="mt-1 flex items-center justify-between bg-gradient-to-r from-emerald-400 to-emerald-600 text-white rounded px-3 py-3 text-sm font-medium shadow-lg"> class="mt-1 flex items-center justify-between bg-gradient-to-r from-emerald-400 to-emerald-600 text-white rounded px-3 py-3 text-sm font-medium shadow-lg">
<span>{{ $topMember['name'] }}</span> <span>{{ $tier['top_member']['name'] }}</span>
<span>{{ $topMember['points'] }} Poin</span> <span>{{ $tier['top_member']['spending'] }}</span>
</div> </div>
<div <div
@ -84,31 +59,31 @@ class="mt-2 bg-white dark:bg-gray-800 rounded-lg shadow p-4 text-gray-700 dark:t
<h4 class="font-semibold mb-2">Statistik Order</h4> <h4 class="font-semibold mb-2">Statistik Order</h4>
<div class="flex justify-between text-sm"> <div class="flex justify-between text-sm">
<span>Order:</span> <span>Order:</span>
<span>{{ $topMember['total_orders'] }}x</span> <span>{{ $tier['top_member']['total_orders'] }}x</span>
</div> </div>
<div class="flex justify-between text-sm mt-1"> <div class="flex justify-between text-sm mt-1">
<span>Parfum Yang Dibeli:</span> <span>Parfum Yang Dibeli:</span>
<span>{{ $topMember['items']['total_perfume'] }} ml</span> <span>{{ $tier['top_member']['items']['total_perfume'] }} ml</span>
</div> </div>
<div class="flex justify-between text-sm mt-1"> <div class="flex justify-between text-sm mt-1">
<span>Produk Yang Dibeli:</span> <span>Produk Yang Dibeli:</span>
<span>{{ $topMember['items']['total_product'] }} pcs</span> <span>{{ $tier['top_member']['items']['total_product'] }} pcs</span>
</div> </div>
<div class="flex justify-between text-sm mt-1"> <div class="flex justify-between text-sm mt-1">
<span>Botol Yang Dibeli:</span> <span>Botol Yang Dibeli:</span>
<span>{{ $topMember['items']['total_bottle'] }} pcs</span> <span>{{ $tier['top_member']['items']['total_bottle'] }} pcs</span>
</div> </div>
<div class="flex justify-between text-sm mt-1"> <div class="flex justify-between text-sm mt-1">
<span>Subtotal Belanja:</span> <span>Subtotal Belanja:</span>
<span>{{ $topMember['total']['subtotal'] }}</span> <span>{{ $tier['top_member']['total']['subtotal'] }}</span>
</div> </div>
<div class="flex justify-between text-sm mt-1"> <div class="flex justify-between text-sm mt-1">
<span>Diskon:</span> <span>Diskon:</span>
<span>{{ $topMember['total']['discount'] }}</span> <span>{{ $tier['top_member']['total']['discount'] }}</span>
</div> </div>
<div class="flex justify-between text-sm mt-1"> <div class="flex justify-between text-sm mt-1">
<span>Total Belanja:</span> <span>Total Belanja:</span>
<span>{{ $topMember['total']['grand_total'] }}</span> <span>{{ $tier['top_member']['total']['grand_total'] }}</span>
</div> </div>
</div> </div>
</div> </div>
@ -116,26 +91,6 @@ class="mt-2 bg-white dark:bg-gray-800 rounded-lg shadow p-4 text-gray-700 dark:t
</div> </div>
<div class="flex gap-2 pt-2 border-gray-200 dark:border-gray-700"> <div class="flex gap-2 pt-2 border-gray-200 dark:border-gray-700">
@can('view tier reward')
<flux:modal.trigger name="reward-view-modal">
<flux:tooltip content="Lihat Hadiah">
<flux:button variant="primary" color="blue" icon="eye" size="sm"
wire:click="$dispatch('modal:open:reward', {method: 'create', 'modalTitle': '{{ $tier['name'] }}', 'tier_id': '{{ $tier['id'] }}'})">
</flux:button>
</flux:tooltip>
</flux:modal.trigger>
@endcan
@can('create tier reward')
<flux:modal.trigger name="reward-form-modal">
<flux:tooltip content="Tambah Hadiah">
<flux:button variant="primary" color="primary" icon="plus" size="sm"
wire:click="$dispatch('modal:open:reward', {method: 'create', 'modalTitle': 'Tambah Hadiah', 'tier_id': '{{ $tier['id'] }}'})">
</flux:button>
</flux:tooltip>
</flux:modal.trigger>
@endcan
@can('update tier') @can('update tier')
<flux:modal.trigger name="form-modal"> <flux:modal.trigger name="form-modal">
<flux:tooltip content="Ubah"> <flux:tooltip content="Ubah">
@ -182,17 +137,17 @@ class="mt-2 bg-white dark:bg-gray-800 rounded-lg shadow p-4 text-gray-700 dark:t
</flux:field> </flux:field>
<flux:field> <flux:field>
<flux:label>Min. Poin <span class="text-red-500 ms-1">*</span></flux:label> <flux:label>Min. Belanja <span class="text-red-500 ms-1">*</span></flux:label>
<flux:input placeholder="100" wire:model="form.min_points" autocomplete="off" <flux:input placeholder="100.000" wire:model="form.min_spending" autocomplete="off"
x-mask:dynamic="$money($input, ',')" /> x-mask:dynamic="$money($input, ',')" />
<flux:error name="form.min_points" /> <flux:error name="form.min_spending" />
</flux:field> </flux:field>
<flux:field> <flux:field>
<flux:label>Maks. Poin </flux:label> <flux:label>Maks. Belanja </flux:label>
<flux:input placeholder="499" wire:model="form.max_points" autocomplete="off" <flux:input placeholder="499.000" wire:model="form.max_spending" autocomplete="off"
x-mask:dynamic="$money($input, ',')" /> x-mask:dynamic="$money($input, ',')" />
<flux:error name="form.max_points" /> <flux:error name="form.max_spending" />
</flux:field> </flux:field>
<div class="flex"> <div class="flex">
@ -203,8 +158,4 @@ class="mt-2 bg-white dark:bg-gray-800 rounded-lg shadow p-4 text-gray-700 dark:t
</div> </div>
</div> </div>
</flux:modal> </flux:modal>
@can('create tier reward')
@livewire('studio.loyalty.tier.reward')
@endcan
</flux:main> </flux:main>

View File

@ -25,7 +25,7 @@
use App\Livewire\Studio\Information\Faq as FaqComponent; use App\Livewire\Studio\Information\Faq as FaqComponent;
use App\Livewire\Studio\Information\PriceRequest as PriceRequestComponent; use App\Livewire\Studio\Information\PriceRequest as PriceRequestComponent;
use App\Livewire\Studio\Loyalty\Customer as CustomerComponent; use App\Livewire\Studio\Loyalty\Customer as CustomerComponent;
use App\Livewire\Studio\Loyalty\Tier\Index as TierComponent; use App\Livewire\Studio\Loyalty\Tier as TierComponent;
use App\Livewire\Studio\Loyalty\Voucher\Create as VoucherCreate; use App\Livewire\Studio\Loyalty\Voucher\Create as VoucherCreate;
use App\Livewire\Studio\Loyalty\Voucher\Edit as VoucherEdit; use App\Livewire\Studio\Loyalty\Voucher\Edit as VoucherEdit;
use App\Livewire\Studio\Loyalty\Voucher\Index as VoucherIndex; use App\Livewire\Studio\Loyalty\Voucher\Index as VoucherIndex;

View File

@ -344,7 +344,6 @@ function makeReferralCode(): ReferralCode
expect($user->status)->toBe(UserStatus::ACTIVE); expect($user->status)->toBe(UserStatus::ACTIVE);
expect($user->hasRole('Customer'))->toBeTrue(); expect($user->hasRole('Customer'))->toBeTrue();
expect(Membership::where('user_id', $user->id)->exists())->toBeTrue(); expect(Membership::where('user_id', $user->id)->exists())->toBeTrue();
expect(PointRecord::where('user_id', $user->id)->exists())->toBeTrue();
expect(ReferralCode::where('user_id', $user->id)->exists())->toBeTrue(); expect(ReferralCode::where('user_id', $user->id)->exists())->toBeTrue();
expect(auth()->check())->toBeTrue(); expect(auth()->check())->toBeTrue();
@ -370,16 +369,17 @@ function makeReferralCode(): ReferralCode
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
*/ */
it('creates membership with correct tier and points', function () { it('creates membership with correct tier and initial data', function () {
attemptRegistration() attemptRegistration()
->assertHasNoErrors(); ->assertHasNoErrors();
$user = User::where('email', 'info.pangestuyoga@gmail.com')->first(); $user = User::where('email', 'info.pangestuyoga@gmail.com')->first();
$membership = Membership::where('user_id', $user->id)->first(); $membership = Membership::where('user_id', $user->id)->first();
$tier = Tier::orderBy('min_points')->first(); $tier = Tier::orderBy('min_spending')->first();
expect($membership->tier_id)->toBe($tier->id); expect($membership->tier_id)->toBe($tier->id);
expect($membership->tier_points)->toBe(10); expect($membership->total_spending)->toBe(0);
expect($membership->reward_points)->toBe(10);
}); });
it('creates point record for registration', function () { it('creates point record for registration', function () {

View File

@ -49,13 +49,13 @@ function mountTierComponent(User $user)
it('renders page successfully', function () { it('renders page successfully', function () {
mountTierComponent($this->user) mountTierComponent($this->user)
->assertViewIs('livewire.studio.loyalty.tier.index') ->assertViewIs('livewire.studio.loyalty.tiers')
->assertViewHas('pageTitle', 'Tier'); ->assertViewHas('pageTitle', 'Tier');
}); });
it('loads tiers on mount', function () { it('loads tiers on mount', function () {
$tier1 = TierModel::factory()->create(['name' => 'Bronze', 'min_points' => 0, 'max_points' => 100]); $tier1 = TierModel::factory()->create(['name' => 'Bronze', 'min_spending' => 0, 'max_spending' => 100000]);
$tier2 = TierModel::factory()->create(['name' => 'Silver', 'min_points' => 101, 'max_points' => 500]); $tier2 = TierModel::factory()->create(['name' => 'Silver', 'min_spending' => 100001, 'max_spending' => 500000]);
$component = mountTierComponent($this->user); $component = mountTierComponent($this->user);
@ -66,18 +66,17 @@ function mountTierComponent(User $user)
}); });
it('displays all tiers in the view', function () { it('displays all tiers in the view', function () {
$tier = TierModel::factory()->create(['name' => 'Gold', 'min_points' => 100, 'max_points' => 500]); $tier = TierModel::factory()->create(['name' => 'Gold', 'min_spending' => 1000000, 'max_spending' => 5000000]);
mountTierComponent($this->user) mountTierComponent($this->user)
->assertSee('Gold') ->assertSee('Gold')
->assertSee('100') ->assertSee('1.000.000');
->assertSee('500');
}); });
it('sorts tiers by min_points ascending', function () { it('sorts tiers by min_spending ascending', function () {
$tier3 = TierModel::factory()->create(['name' => 'Platinum', 'min_points' => 1000, 'max_points' => null]); $tier3 = TierModel::factory()->create(['name' => 'Platinum', 'min_spending' => 10000000, 'max_spending' => null]);
$tier1 = TierModel::factory()->create(['name' => 'Bronze', 'min_points' => 0, 'max_points' => 100]); $tier1 = TierModel::factory()->create(['name' => 'Bronze', 'min_spending' => 0, 'max_spending' => 1000000]);
$tier2 = TierModel::factory()->create(['name' => 'Silver', 'min_points' => 101, 'max_points' => 500]); $tier2 = TierModel::factory()->create(['name' => 'Silver', 'min_spending' => 1000001, 'max_spending' => 5000000]);
$component = mountTierComponent($this->user); $component = mountTierComponent($this->user);
@ -100,8 +99,8 @@ function mountTierComponent(User $user)
mountTierComponent($this->user) mountTierComponent($this->user)
->set('form.name', 'Gold') ->set('form.name', 'Gold')
->set('form.min_points', '1000') ->set('form.min_spending', '1000000')
->set('form.max_points', '5000') ->set('form.max_spending', '5000000')
->call('create') ->call('create')
->assertForbidden(); ->assertForbidden();
}); });
@ -110,8 +109,8 @@ function mountTierComponent(User $user)
mountTierComponent($this->user) mountTierComponent($this->user)
->call('openModal', 'create', 'Tambah Tier') ->call('openModal', 'create', 'Tambah Tier')
->set('form.name', 'Gold') ->set('form.name', 'Gold')
->set('form.min_points', '1.000') ->set('form.min_spending', '1.000.000')
->set('form.max_points', '5.000') ->set('form.max_spending', '5.000.000')
->call('create') ->call('create')
->assertHasNoErrors() ->assertHasNoErrors()
->assertSet('tiers', function ($tiers) { ->assertSet('tiers', function ($tiers) {
@ -122,36 +121,36 @@ function mountTierComponent(User $user)
$this->assertDatabaseHas('tiers', [ $this->assertDatabaseHas('tiers', [
'name' => 'Gold', 'name' => 'Gold',
'min_points' => 1000, 'min_spending' => 1000000,
'max_points' => 5000, 'max_spending' => null, // reorderTierChain makes last tier null
]); ]);
}); });
it('can create a tier without max_points', function () { it('can create a tier without max_spending', function () {
mountTierComponent($this->user) mountTierComponent($this->user)
->call('openModal', 'create', 'Tambah Tier') ->call('openModal', 'create', 'Tambah Tier')
->set('form.name', 'Platinum') ->set('form.name', 'Platinum')
->set('form.min_points', '5.001') ->set('form.min_spending', '5.000.001')
->set('form.max_points', null) ->set('form.max_spending', null)
->call('create') ->call('create')
->assertHasNoErrors(); ->assertHasNoErrors();
$this->assertDatabaseHas('tiers', [ $this->assertDatabaseHas('tiers', [
'name' => 'Platinum', 'name' => 'Platinum',
'min_points' => 5001, 'min_spending' => 5000001,
'max_points' => null, 'max_spending' => null,
]); ]);
}); });
it('sorts tiers after creating new tier', function () { it('sorts tiers after creating new tier', function () {
TierModel::factory()->create(['name' => 'Silver', 'min_points' => 101, 'max_points' => 500]); TierModel::factory()->create(['name' => 'Silver', 'min_spending' => 500001, 'max_spending' => 1000000]);
TierModel::factory()->create(['name' => 'Bronze', 'min_points' => 0, 'max_points' => 100]); TierModel::factory()->create(['name' => 'Bronze', 'min_spending' => 0, 'max_spending' => 500000]);
$component = mountTierComponent($this->user) $component = mountTierComponent($this->user)
->call('openModal', 'create', 'Tambah Tier') ->call('openModal', 'create', 'Tambah Tier')
->set('form.name', 'Gold') ->set('form.name', 'Gold')
->set('form.min_points', '501') ->set('form.min_spending', '1.000.001')
->set('form.max_points', '1000') ->set('form.max_spending', '2.000.000')
->call('create'); ->call('create');
expect($component->tiers)->toBeInstanceOf(\Illuminate\Support\Collection::class); expect($component->tiers)->toBeInstanceOf(\Illuminate\Support\Collection::class);
@ -166,7 +165,7 @@ function mountTierComponent(User $user)
->call('create') ->call('create')
->assertHasErrors([ ->assertHasErrors([
'form.name', 'form.name',
'form.min_points', 'form.min_spending',
]); ]);
}); });
@ -174,28 +173,28 @@ function mountTierComponent(User $user)
mountTierComponent($this->user) mountTierComponent($this->user)
->call('openModal', 'create', 'Tambah Tier') ->call('openModal', 'create', 'Tambah Tier')
->set('form.name', str_repeat('a', 51)) ->set('form.name', str_repeat('a', 51))
->set('form.min_points', '100') ->set('form.min_spending', '100')
->call('create') ->call('create')
->assertHasErrors(['form.name']); ->assertHasErrors(['form.name']);
}); });
it('validates min_points is unsigned integer when creating tier', function () { it('validates min_spending is unsigned integer when creating tier', function () {
mountTierComponent($this->user) mountTierComponent($this->user)
->call('openModal', 'create', 'Tambah Tier') ->call('openModal', 'create', 'Tambah Tier')
->set('form.name', 'Gold') ->set('form.name', 'Gold')
->set('form.min_points', '-100') ->set('form.min_spending', '-100')
->call('create') ->call('create')
->assertHasErrors(['form.min_points']); ->assertHasErrors(['form.min_spending']);
}); });
it('validates max_points is unsigned integer when creating tier', function () { it('validates max_spending is unsigned integer when creating tier', function () {
mountTierComponent($this->user) mountTierComponent($this->user)
->call('openModal', 'create', 'Tambah Tier') ->call('openModal', 'create', 'Tambah Tier')
->set('form.name', 'Gold') ->set('form.name', 'Gold')
->set('form.min_points', '100') ->set('form.min_spending', '100')
->set('form.max_points', '-50') ->set('form.max_spending', '-50')
->call('create') ->call('create')
->assertHasErrors(['form.max_points']); ->assertHasErrors(['form.max_spending']);
}); });
/* /*
@ -208,7 +207,7 @@ function mountTierComponent(User $user)
$this->ownerRole->revokePermissionTo('update tier'); $this->ownerRole->revokePermissionTo('update tier');
Gate::define('update tier', fn () => false); Gate::define('update tier', fn () => false);
$tier = TierModel::factory()->create(['name' => 'Bronze', 'min_points' => 0, 'max_points' => 100]); $tier = TierModel::factory()->create(['name' => 'Bronze', 'min_spending' => 0, 'max_spending' => 100000]);
mountTierComponent($this->user) mountTierComponent($this->user)
->call('openModal', 'update', 'Ubah Tier', $tier->hash) ->call('openModal', 'update', 'Ubah Tier', $tier->hash)
@ -218,16 +217,16 @@ function mountTierComponent(User $user)
}); });
it('can update a tier when authorized', function () { it('can update a tier when authorized', function () {
$tier = TierModel::factory()->create(['name' => 'Bronze', 'min_points' => 0, 'max_points' => 100]); $tier = TierModel::factory()->create(['name' => 'Bronze', 'min_spending' => 0, 'max_spending' => 100000]);
mountTierComponent($this->user) mountTierComponent($this->user)
->call('openModal', 'update', 'Ubah Tier', $tier->hash) ->call('openModal', 'update', 'Ubah Tier', $tier->hash)
->assertSet('form.name', 'Bronze') ->assertSet('form.name', 'Bronze')
->assertSet('form.min_points', '0') ->assertSet('form.min_spending', formatCurrencyNumber($tier->min_spending))
->assertSet('form.max_points', '100') ->assertSet('form.max_spending', formatCurrencyNumber($tier->max_spending))
->set('form.name', 'Gold') ->set('form.name', 'Gold')
->set('form.min_points', '1.000') ->set('form.min_spending', '1.000.000')
->set('form.max_points', '5.000') ->set('form.max_spending', '5.000.000')
->call('update') ->call('update')
->assertHasNoErrors() ->assertHasNoErrors()
->assertSet('tiers', function ($tiers) use ($tier) { ->assertSet('tiers', function ($tiers) use ($tier) {
@ -238,21 +237,21 @@ function mountTierComponent(User $user)
$tier->refresh(); $tier->refresh();
expect($tier->name)->toBe('Gold'); expect($tier->name)->toBe('Gold');
expect($tier->min_points)->toBe(1000); expect($tier->min_spending)->toBe(1000000);
expect($tier->max_points)->toBe(5000); expect($tier->max_spending)->toBeNull(); // reorderTierChain makes last tier null
}); });
it('can update tier without max_points', function () { it('can update tier without max_spending', function () {
$tier = TierModel::factory()->create(['name' => 'Bronze', 'min_points' => 0, 'max_points' => 100]); $tier = TierModel::factory()->create(['name' => 'Bronze', 'min_spending' => 0, 'max_spending' => 100000]);
mountTierComponent($this->user) mountTierComponent($this->user)
->call('openModal', 'update', 'Ubah Tier', $tier->hash) ->call('openModal', 'update', 'Ubah Tier', $tier->hash)
->set('form.max_points', null) ->set('form.max_spending', null)
->call('update') ->call('update')
->assertHasNoErrors(); ->assertHasNoErrors();
$tier->refresh(); $tier->refresh();
expect($tier->max_points)->toBeNull(); expect($tier->max_spending)->toBeNull();
}); });
it('validates required fields when updating tier', function () { it('validates required fields when updating tier', function () {
@ -261,11 +260,11 @@ function mountTierComponent(User $user)
mountTierComponent($this->user) mountTierComponent($this->user)
->call('openModal', 'update', 'Ubah Tier', $tier->hash) ->call('openModal', 'update', 'Ubah Tier', $tier->hash)
->set('form.name', '') ->set('form.name', '')
->set('form.min_points', '') ->set('form.min_spending', '')
->call('update') ->call('update')
->assertHasErrors([ ->assertHasErrors([
'form.name', 'form.name',
'form.min_points', 'form.min_spending',
]); ]);
}); });
@ -321,7 +320,7 @@ function mountTierComponent(User $user)
$membership = Membership::create([ $membership = Membership::create([
'user_id' => $user->id, 'user_id' => $user->id,
'tier_id' => $tier->id, 'tier_id' => $tier->id,
'tier_points' => 100, 'total_spending' => 100000,
]); ]);
mountTierComponent($this->user) mountTierComponent($this->user)
@ -345,26 +344,26 @@ function mountTierComponent(User $user)
$customer1 = Customer::factory()->create(['user_id' => $user1->id]); $customer1 = Customer::factory()->create(['user_id' => $user1->id]);
$customer2 = Customer::factory()->create(['user_id' => $user2->id]); $customer2 = Customer::factory()->create(['user_id' => $user2->id]);
Membership::create(['user_id' => $user1->id, 'tier_id' => $tier->id, 'tier_points' => 100]); Membership::create(['user_id' => $user1->id, 'tier_id' => $tier->id, 'total_spending' => 100000]);
Membership::create(['user_id' => $user2->id, 'tier_id' => $tier->id, 'tier_points' => 200]); Membership::create(['user_id' => $user2->id, 'tier_id' => $tier->id, 'total_spending' => 200000]);
$component = mountTierComponent($this->user); $component = mountTierComponent($this->user);
$loadedTier = $component->tiers->firstWhere('id', $tier->id); $loadedTier = $component->tiers->firstWhere('id', $tier->id);
expect($loadedTier->total_members)->toBe(2); expect($loadedTier->total_members)->toBe('2');
}); });
it('loads tiers with rewards count', function () { it('loads tiers with rewards count', function () {
$tier = TierModel::factory()->create(); $tier = TierModel::factory()->create();
TierReward::create(['tier_id' => $tier->id, 'name' => 'Reward 1', 'value' => 100]); TierReward::create(['tier_id' => $tier->id, 'name' => 'Reward 1', 'points' => 100]);
TierReward::create(['tier_id' => $tier->id, 'name' => 'Reward 2', 'value' => 200]); TierReward::create(['tier_id' => $tier->id, 'name' => 'Reward 2', 'points' => 200]);
TierReward::create(['tier_id' => $tier->id, 'name' => 'Reward 3', 'value' => 300]); TierReward::create(['tier_id' => $tier->id, 'name' => 'Reward 3', 'points' => 300]);
$component = mountTierComponent($this->user); $component = mountTierComponent($this->user);
$loadedTier = $component->tiers->firstWhere('id', $tier->id); $loadedTier = $component->tiers->firstWhere('id', $tier->id);
expect((int) $loadedTier->total_rewards)->toBe(3); expect($loadedTier['total_rewards'])->toBe('3');
}); });
it('loads top member stats when tier has memberships', function () { it('loads top member stats when tier has memberships', function () {
@ -375,17 +374,17 @@ function mountTierComponent(User $user)
$customer1 = Customer::factory()->create(['user_id' => $user1->id, 'name' => 'John Doe']); $customer1 = Customer::factory()->create(['user_id' => $user1->id, 'name' => 'John Doe']);
$customer2 = Customer::factory()->create(['user_id' => $user2->id, 'name' => 'Jane Doe']); $customer2 = Customer::factory()->create(['user_id' => $user2->id, 'name' => 'Jane Doe']);
// Create memberships with different tier_points // Create memberships with different total_spending
$membership1 = Membership::create([ $membership1 = Membership::create([
'user_id' => $user1->id, 'user_id' => $user1->id,
'tier_id' => $tier->id, 'tier_id' => $tier->id,
'tier_points' => 500, // Higher points 'total_spending' => 5000000, // Higher spending
]); ]);
$membership2 = Membership::create([ $membership2 = Membership::create([
'user_id' => $user2->id, 'user_id' => $user2->id,
'tier_id' => $tier->id, 'tier_id' => $tier->id,
'tier_points' => 200, // Lower points 'total_spending' => 2000000, // Lower spending
]); ]);
// Create orders for user1 (top member) // Create orders for user1 (top member)
@ -422,7 +421,6 @@ function mountTierComponent(User $user)
'sku' => 'TP1-0001', 'sku' => 'TP1-0001',
'cost_price' => 10000, 'cost_price' => 10000,
'sale_price' => 50000, 'sale_price' => 50000,
'point_per_ml' => 500,
]); ]);
$product1 = Product::create([ $product1 = Product::create([
'name' => 'Test Product 1', 'name' => 'Test Product 1',
@ -430,7 +428,6 @@ function mountTierComponent(User $user)
'sku' => 'PR1-0001', 'sku' => 'PR1-0001',
'cost_price' => 5000, 'cost_price' => 5000,
'sale_price' => 25000, 'sale_price' => 25000,
'point_per_pcs' => 250,
]); ]);
$bottle1 = Bottle::factory()->create(); $bottle1 = Bottle::factory()->create();
@ -472,7 +469,6 @@ function mountTierComponent(User $user)
'sku' => 'TP2-0001', 'sku' => 'TP2-0001',
'cost_price' => 10000, 'cost_price' => 10000,
'sale_price' => 50000, 'sale_price' => 50000,
'point_per_ml' => 500,
]); ]);
OrderItem::create([ OrderItem::create([
'order_id' => $order2->id, 'order_id' => $order2->id,
@ -489,9 +485,9 @@ function mountTierComponent(User $user)
$loadedTier = $component->tiers->firstWhere('id', $tier->id); $loadedTier = $component->tiers->firstWhere('id', $tier->id);
expect($loadedTier->top_member)->not->toBeNull(); expect($loadedTier->top_member)->not->toBeNull();
expect($loadedTier->top_member['name'])->toBe('John Doe'); expect($loadedTier->top_member['name'])->toBe('John Doe');
expect($loadedTier->top_member['points'])->toContain('500'); expect($loadedTier->top_member['spending'])->toContain('5.000.000');
expect($loadedTier->top_member['total_orders'])->toContain('2'); expect($loadedTier->top_member['total_orders'])->toBe('2');
expect($loadedTier->top_member['items']['total_perfume'])->toContain('3'); expect($loadedTier->top_member['items']['total_perfume'])->toBe('3');
expect($loadedTier->top_member['items']['total_product'])->toContain('3'); expect($loadedTier->top_member['items']['total_product'])->toContain('3');
expect($loadedTier->top_member['items']['total_bottle'])->toContain('1'); expect($loadedTier->top_member['items']['total_bottle'])->toContain('1');
}); });
@ -542,23 +538,23 @@ function mountTierComponent(User $user)
expect($component->method)->toBe('update'); expect($component->method)->toBe('update');
expect($component->modalTitle)->toBe('Ubah Tier'); expect($component->modalTitle)->toBe('Ubah Tier');
expect($component->form->name)->toBe($tier->name); expect($component->form->name)->toBe($tier->name);
expect($component->form->min_points)->toBe((string) $tier->min_points); expect($component->form->min_spending)->toBe(formatCurrencyNumber($tier->min_spending));
expect($component->form->max_points)->toBe($tier->max_points ? (string) $tier->max_points : null); expect($component->form->max_spending)->toBe($tier->max_spending ? formatCurrencyNumber($tier->max_spending) : null);
}); });
it('sets form data when opening update modal', function () { it('sets form data when opening update modal', function () {
$tier = TierModel::factory()->create([ $tier = TierModel::factory()->create([
'name' => 'Gold', 'name' => 'Gold',
'min_points' => 1000, 'min_spending' => 1000000,
'max_points' => 5000, 'max_spending' => 5000000,
]); ]);
$component = mountTierComponent($this->user) $component = mountTierComponent($this->user)
->call('openModal', 'update', 'Ubah Tier', $tier->hash); ->call('openModal', 'update', 'Ubah Tier', $tier->hash);
expect($component->form->name)->toBe('Gold'); expect($component->form->name)->toBe('Gold');
expect($component->form->min_points)->toBe('1000'); expect($component->form->min_spending)->toBe('1.000.000');
expect($component->form->max_points)->toBe('5000'); expect($component->form->max_spending)->toBe('5.000.000');
}); });
/* /*
@ -567,31 +563,31 @@ function mountTierComponent(User $user)
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
*/ */
it('formats points with currency when displaying', function () { it('formats spending with currency when displaying', function () {
$tier = TierModel::factory()->create([ $tier = TierModel::factory()->create([
'min_points' => 1000, 'min_spending' => 1000000,
'max_points' => 5000, 'max_spending' => 5000000,
]); ]);
$component = mountTierComponent($this->user); $component = mountTierComponent($this->user);
$loadedTier = $component->tiers->firstWhere('id', $tier->id); $loadedTier = $component->tiers->firstWhere('id', $tier->id);
expect(formatCurrencyNumber($loadedTier->min_points))->toContain('1.000'); expect(formatCurrencyNumber($loadedTier->min_spending))->toContain('1.000.000');
expect(formatCurrencyNumber($loadedTier->max_points))->toContain('5.000'); expect(formatCurrencyNumber($loadedTier->max_spending))->toContain('5.000.000');
}); });
it('handles currency formatting in form input', function () { it('handles currency formatting in form input', function () {
mountTierComponent($this->user) mountTierComponent($this->user)
->call('openModal', 'create', 'Tambah Tier') ->call('openModal', 'create', 'Tambah Tier')
->set('form.name', 'Gold') ->set('form.name', 'Gold')
->set('form.min_points', '1.000') ->set('form.min_spending', '1.000.000')
->set('form.max_points', '5.000') ->set('form.max_spending', '5.000.000')
->call('create') ->call('create')
->assertHasNoErrors(); ->assertHasNoErrors();
$tier = TierModel::first(); $tier = TierModel::first();
expect($tier->min_points)->toBe(1000); expect($tier->min_spending)->toBe(1000000);
expect($tier->max_points)->toBe(5000); expect($tier->max_spending)->toBeNull(); // ReorderTierChain makes the last tier null
}); });
/* /*
@ -600,30 +596,30 @@ function mountTierComponent(User $user)
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
*/ */
it('handles tier with null max_points correctly', function () { it('handles tier with null max_spending correctly', function () {
$tier = TierModel::factory()->create([ $tier = TierModel::factory()->create([
'name' => 'Platinum', 'name' => 'Platinum',
'min_points' => 10000, 'min_spending' => 10000000,
'max_points' => null, 'max_spending' => null,
]); ]);
$component = mountTierComponent($this->user); $component = mountTierComponent($this->user);
$loadedTier = $component->tiers->firstWhere('id', $tier->id); $loadedTier = $component->tiers->firstWhere('id', $tier->id);
expect(formatCurrencyNumber($loadedTier->max_points))->not->toBeNull(); expect(formatCurrencyNumber($loadedTier->max_spending))->not->toBeNull();
}); });
it('handles tier with zero min_points', function () { it('handles tier with zero min_spending', function () {
$tier = TierModel::factory()->create([ $tier = TierModel::factory()->create([
'name' => 'Starter', 'name' => 'Starter',
'min_points' => 0, 'min_spending' => 0,
'max_points' => 100, 'max_spending' => 100000,
]); ]);
$component = mountTierComponent($this->user); $component = mountTierComponent($this->user);
$loadedTier = $component->tiers->firstWhere('id', $tier->id); $loadedTier = $component->tiers->firstWhere('id', $tier->id);
expect(formatCurrencyNumber($loadedTier->min_points))->toContain('0'); expect(formatCurrencyNumber($loadedTier->min_spending))->toContain('0');
}); });
it('handles empty tiers list', function () { it('handles empty tiers list', function () {
@ -635,19 +631,19 @@ function mountTierComponent(User $user)
it('updates tier array correctly after update', function () { it('updates tier array correctly after update', function () {
$tier = TierModel::factory()->create([ $tier = TierModel::factory()->create([
'name' => 'Bronze', 'name' => 'Bronze',
'min_points' => 0, 'min_spending' => 0,
'max_points' => 100, 'max_spending' => 100000,
]); ]);
$component = mountTierComponent($this->user) $component = mountTierComponent($this->user)
->call('openModal', 'update', 'Ubah Tier', $tier->hash) ->call('openModal', 'update', 'Ubah Tier', $tier->hash)
->set('form.name', 'Gold') ->set('form.name', 'Gold')
->set('form.min_points', '1.000') ->set('form.min_spending', '1.000.000')
->set('form.max_points', '5.000') ->set('form.max_spending', '5.000.000')
->call('update'); ->call('update');
$updatedTier = $component->tiers->firstWhere('hash', $tier->hash); $updatedTier = $component->tiers->firstWhere('hash', $tier->hash);
expect($updatedTier->name)->toBe('Gold'); expect($updatedTier->name)->toBe('Gold');
expect(formatCurrencyNumber($updatedTier->min_points))->toContain('1.000'); expect($updatedTier->formatted_min_spending)->toContain('1.000.000');
expect(formatCurrencyNumber($updatedTier->max_points))->toContain('5.000'); expect($updatedTier->max_spending)->toBeNull(); // ReorderTierChain makes the last tier null
}); });