Files
suivicpt/app/Livewire/Suivi/Index.php
T
jeremy bayseandClaude Sonnet 5 97dc7cdb2a Allow editing an existing transaction
Desktop reuses the add-form with a Modifier link per row; mobile gets
a "Dernières opérations" list under the quick-entry form since no
table exists there.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-01 08:37:50 +02:00

315 lines
11 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Livewire\Suivi;
use App\Enums\CategoryType;
use App\Models\BudgetLine;
use App\Models\Category;
use App\Models\Household;
use App\Models\RecurringTransaction;
use App\Models\Transaction;
use Livewire\Attributes\Layout;
use Livewire\Component;
#[Layout('layouts.app')]
class Index extends Component
{
public string $date;
public string $dateEffective;
public ?int $categoryId = null;
public string $amount = '';
public string $details = '';
public string $paidByUserId = '';
public string $filterPaidBy = '';
public ?int $editingTransactionId = null;
public function mount(): void
{
$this->date = now()->toDateString();
$this->dateEffective = now()->toDateString();
}
public function addTransaction(): void
{
$this->validate([
'date' => ['required', 'date'],
'dateEffective' => ['required', 'date'],
'categoryId' => ['required', 'exists:categories,id'],
'amount' => ['required', 'numeric'],
'details' => ['nullable', 'string', 'max:255'],
'paidByUserId' => ['nullable', 'integer'],
]);
$household = auth()->user()->currentHousehold;
$category = $household->categories()->findOrFail($this->categoryId);
$paidByUserId = $this->resolvePaidByUserId($household, $this->paidByUserId);
if ($this->editingTransactionId) {
$transaction = $household->transactions()->findOrFail($this->editingTransactionId);
$transaction->update([
'category_id' => $category->id,
'paid_by_user_id' => $paidByUserId,
'date' => $this->date,
'date_effective' => $this->dateEffective,
'amount' => $this->amount,
'details' => $this->details,
]);
} else {
$household->transactions()->create([
'category_id' => $category->id,
'user_id' => auth()->id(),
'paid_by_user_id' => $paidByUserId,
'date' => $this->date,
'date_effective' => $this->dateEffective,
'amount' => $this->amount,
'details' => $this->details,
]);
}
$wasEditing = $this->editingTransactionId !== null;
$this->reset(['categoryId', 'amount', 'details', 'paidByUserId', 'editingTransactionId']);
$this->date = now()->toDateString();
$this->dateEffective = now()->toDateString();
$this->dispatch($wasEditing ? 'transaction-updated' : 'transaction-added');
}
public function startEditTransaction(int $transactionId): void
{
$household = auth()->user()->currentHousehold;
$transaction = $household->transactions()->findOrFail($transactionId);
$this->editingTransactionId = $transaction->id;
$this->categoryId = $transaction->category_id;
$this->amount = (string) $transaction->amount;
$this->details = (string) $transaction->details;
$this->date = $transaction->date->toDateString();
$this->dateEffective = $transaction->date_effective->toDateString();
$this->paidByUserId = $transaction->paid_by_user_id ? (string) $transaction->paid_by_user_id : '';
}
public function cancelEditTransaction(): void
{
$this->reset(['categoryId', 'amount', 'details', 'paidByUserId', 'editingTransactionId']);
$this->date = now()->toDateString();
$this->dateEffective = now()->toDateString();
}
/**
* Vide ou "0" = dépense commune (aucun membre précis). Vérifie que la
* valeur, si fournie, correspond bien à un membre du foyer courant.
*/
private function resolvePaidByUserId(Household $household, string $value): ?int
{
if ($value === '' || $value === '0') {
return null;
}
$isMember = $household->members()->whereKey((int) $value)->exists();
return $isMember ? (int) $value : null;
}
public function deleteTransaction(int $transactionId): void
{
$household = auth()->user()->currentHousehold;
$transaction = $household->transactions()->findOrFail($transactionId);
$transaction->delete();
}
public function confirmRecurrence(int $recurringId, string $amount): void
{
$household = auth()->user()->currentHousehold;
$recurring = $household->recurringTransactions()->findOrFail($recurringId);
$today = now();
if ($recurring->wasGeneratedFor((int) $today->year, (int) $today->month)) {
return;
}
$household->transactions()->create([
'category_id' => $recurring->category_id,
'recurring_transaction_id' => $recurring->id,
'user_id' => auth()->id(),
'paid_by_user_id' => $recurring->paid_by_user_id,
'date' => $today->toDateString(),
'date_effective' => $today->toDateString(),
'amount' => $amount,
'details' => $recurring->name,
]);
$recurring->update([
'last_generated_year' => $today->year,
'last_generated_month' => $today->month,
]);
$this->dispatch('transaction-added');
}
public function dismissRecurrence(int $recurringId): void
{
$household = auth()->user()->currentHousehold;
$recurring = $household->recurringTransactions()->findOrFail($recurringId);
$today = now();
$recurring->update([
'last_generated_year' => $today->year,
'last_generated_month' => $today->month,
]);
}
/**
* Budget planifié pour cette catégorie sur le mois en cours, en résolvant
* l'override du mois s'il existe sinon le montant par défaut de l'année.
*/
private function budgetForCurrentMonth(Category $category, int $year, int $month): ?float
{
$lines = $category->budgetLines()->where('year', $year)->get();
$override = $lines->firstWhere('month', $month);
if ($override) {
return (float) $override->amount;
}
$default = $lines->firstWhere('month', null);
return $default ? (float) $default->amount : null;
}
private function trackedForCategoryThisMonth(Category $category, int $year, int $month): float
{
return (float) $category->transactions()
->whereYear('date_effective', $year)
->whereMonth('date_effective', $month)
->sum('amount');
}
public function render()
{
$household = auth()->user()->currentHousehold;
// Le solde cumulé porte sur l'ensemble des transactions, indépendamment
// du filtre "payé par" appliqué à la liste affichée.
$allTransactions = $household->transactions()->with('category')->get();
$chronological = $allTransactions->sortBy(['date', 'id'])->values();
$running = [];
$balance = 0.0;
foreach ($chronological as $t) {
$sign = $t->category->type === CategoryType::Revenu ? 1 : -1;
$balance += (float) $t->amount * $sign;
$running[$t->id] = $balance;
}
$transactionsQuery = $household->transactions()
->with(['category', 'paidBy']);
if ($this->filterPaidBy === 'common') {
$transactionsQuery->whereNull('paid_by_user_id');
} elseif ($this->filterPaidBy !== '') {
$transactionsQuery->where('paid_by_user_id', (int) $this->filterPaidBy);
}
$transactions = $transactionsQuery
->orderByDesc('date')
->orderByDesc('id')
->get();
$year = (int) now()->year;
$month = (int) now()->month;
$revenueCategoryIds = $household->categories()->where('type', CategoryType::Revenu)->pluck('id');
$revenueBudget = (float) BudgetLine::whereIn('category_id', $revenueCategoryIds)
->where('year', $year)
->where(fn ($q) => $q->where('month', $month)->orWhereNull('month'))
->get()
->groupBy('category_id')
->map(fn ($lines) => $lines->firstWhere('month', $month)?->amount ?? $lines->firstWhere('month', null)?->amount ?? 0)
->sum();
$revenueTracked = (float) $household->transactions()
->whereHas('category', fn ($q) => $q->where('type', CategoryType::Revenu))
->whereYear('date_effective', $year)
->whereMonth('date_effective', $month)
->sum('amount');
$unaffected = max(0, $revenueBudget - $revenueTracked);
$today = now();
$pendingRecurrences = $household->recurringTransactions()
->with('category')
->where('active', true)
->where('day_of_month', '<=', $today->day)
->get()
->reject(fn (RecurringTransaction $r) => $r->wasGeneratedFor((int) $today->year, (int) $today->month))
->sortBy('day_of_month')
->values();
$categories = $household->categories()->orderBy('type')->orderBy('position')->get();
$categoryProgress = $categories
->whereIn('type', [CategoryType::Depense, CategoryType::Epargne])
->mapWithKeys(function (Category $category) use ($year, $month) {
$budget = $this->budgetForCurrentMonth($category, $year, $month);
if ($budget === null || $budget <= 0) {
return [$category->id => null];
}
$tracked = $this->trackedForCategoryThisMonth($category, $year, $month);
return [$category->id => [
'pct' => min(100, round($tracked / $budget * 100)),
'remaining' => max(0, $budget - $tracked),
]];
});
$members = $household->members()->orderBy('name')->get();
$paidBySummary = $household->transactions()
->with(['category', 'paidBy'])
->whereHas('category', fn ($q) => $q->where('type', CategoryType::Depense))
->whereYear('date_effective', $year)
->whereMonth('date_effective', $month)
->get()
->groupBy(fn (Transaction $t) => $t->paid_by_user_id ?? 'common')
->map(fn ($group, $key) => [
'label' => $key === 'common' ? 'Commun' : $group->first()->paidBy->name,
'total' => (float) $group->sum('amount'),
])
->sortByDesc('total')
->values();
$recentTransactions = $allTransactions->sortByDesc('id')->take(5)->values();
return view('livewire.suivi.index', [
'transactions' => $transactions,
'running' => $running,
'categories' => $categories,
'categoryProgress' => $categoryProgress,
'members' => $members,
'paidBySummary' => $paidBySummary,
'recentTransactions' => $recentTransactions,
'nbrThisYear' => $allTransactions->filter(fn (Transaction $t) => $t->date->year === $year)->count(),
'nbrTotal' => $allTransactions->count(),
'lastEntry' => $allTransactions->sortByDesc('date')->first(),
'unaffected' => $unaffected,
'pendingRecurrences' => $pendingRecurrences,
]);
}
}