All files / components/finance TransactionList.jsx

71.42% Statements 35/49
61.11% Branches 22/36
61.9% Functions 13/21
79.06% Lines 34/43

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168      6x   1x 6x 6x       7x 7x 7x 7x 7x 7x   7x 4x 4x                 3x 3x     3x     7x 6x 6x 6x   6x     7x 6x 6x 6x     7x           7x 4x     16x               3x                             9x                                                   3x                                         6x           6x                                                              
import { useState, useEffect } from "react"
import { financeApi } from "../../api/finance"
 
const fmt = (n) => Number(n).toLocaleString("ru-RU") + " ₽"
 
const formatDate = (d) => {
  const dt = new Date(d)
  return dt.toLocaleDateString("ru-RU", { day: "numeric", month: "long" })
}
 
export default function TransactionList({ onAdd, month, year }) {
  const [transactions, setTransactions] = useState([])
  const [categories, setCategories] = useState([])
  const [loading, setLoading] = useState(true)
  const [filter, setFilter] = useState("all")
  const [catFilter, setCatFilter] = useState(null)
  const [search, setSearch] = useState("")
 
  useEffect(() => {
    setLoading(true)
    Promise.all([
      financeApi.listCategories(),
      financeApi.listTransactions({
        month,
        year,
        limit: 100,
      }),
    ])
      .then(([cats, txs]) => {
        setCategories(cats || [])
        setTransactions(txs || [])
      })
      .catch(console.error)
      .finally(() => setLoading(false))
  }, [month, year])
 
  const filtered = transactions.filter((t) => {
    Iif (filter !== "all" && t.type !== filter) return false
    Iif (catFilter && t.category_id !== catFilter) return false
    Iif (search && !t.description.toLowerCase().includes(search.toLowerCase()))
      return false
    return true
  })
 
  const grouped = filtered.reduce((acc, t) => {
    const d = t.date.slice(0, 10)
    ;(acc[d] = acc[d] || []).push(t)
    return acc
  }, {})
 
  const handleDelete = async (id) => {
    if (!confirm("Удалить транзакцию?")) return
    await financeApi.deleteTransaction(id)
    setTransactions((txs) => txs.filter((t) => t.id !== id))
  }
 
  if (loading) {
    return (
      <div className="space-y-3">
        {[1, 2, 3, 4].map((i) => (
          <div key={i} className="card p-4 animate-pulse">
            <div className="h-5 bg-gray-200 dark:bg-gray-800 rounded w-3/4" />
          </div>
        ))}
      </div>
    )
  }
 
  return (
    <div className="space-y-4">
      <input
        className="w-full px-4 py-2.5 rounded-xl bg-gray-100 dark:bg-gray-800 text-sm text-gray-900 dark:text-white placeholder-gray-400 outline-none"
        placeholder="Поиск по описанию..."
        value={search}
        onChange={(e) => setSearch(e.target.value)}
      />
 
      <div className="flex gap-2">
        {[
          ["all", "Все"],
          ["income", "Доходы"],
          ["expense", "Расходы"],
        ].map(([k, l]) => (
          <button
            key={k}
            onClick={() => setFilter(k)}
            className={`px-3 py-1.5 rounded-lg text-sm font-medium transition ${
              filter === k
                ? "bg-primary-500 text-white"
                : "bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400"
            }`}
          >
            {l}
          </button>
        ))}
      </div>
 
      <div className="flex gap-2 overflow-x-auto pb-1">
        <button
          onClick={() => setCatFilter(null)}
          className={`px-3 py-1 rounded-lg text-xs font-medium whitespace-nowrap transition ${
            !catFilter
              ? "bg-accent-500 text-white"
              : "bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400"
          }`}
        >
          Все
        </button>
        {categories.map((c) => (
          <button
            key={c.id}
            onClick={() => setCatFilter(c.id)}
            className={`px-3 py-1 rounded-lg text-xs font-medium whitespace-nowrap transition ${
              catFilter === c.id
                ? "bg-accent-500 text-white"
                : "bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400"
            }`}
          >
            {c.emoji} {c.name}
          </button>
        ))}
      </div>
 
      {Object.keys(grouped).length === 0 ? (
        <div className="card p-12 text-center">
          <span className="text-4xl block mb-3">🔍</span>
          <p className="text-gray-500 dark:text-gray-400">Ничего не найдено</p>
        </div>
      ) : (
        Object.entries(grouped).map(([date, txs]) => (
          <div key={date}>
            <p className="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase mb-2">
              {formatDate(date)}
            </p>
            <div className="card divide-y divide-gray-100 dark:divide-gray-800">
              {txs.map((t) => (
                <div
                  key={t.id}
                  className="px-4 py-3 flex items-center gap-3"
                  onClick={() => handleDelete(t.id)}
                >
                  <span className="text-xl">{t.category_emoji}</span>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium text-gray-900 dark:text-white truncate">
                      {t.description || t.category_name}
                    </p>
                    <p className="text-xs text-gray-500 dark:text-gray-400">
                      {t.category_emoji} {t.category_name}
                    </p>
                  </div>
                  <span
                    className={`text-sm font-bold ${
                      t.type === "income" ? "text-green-500" : "text-red-500"
                    }`}
                  >
                    {t.type === "income" ? "+" : "-"}
                    {fmt(t.amount)}
                  </span>
                </div>
              ))}
            </div>
          </div>
        ))
      )}
    </div>
  )
}