Skip to content

fix: apply code review fixes across all modules#4

Merged
hansipie merged 13 commits into
mainfrom
fix/code-review
Apr 18, 2026
Merged

fix: apply code review fixes across all modules#4
hansipie merged 13 commits into
mainfrom
fix/code-review

Conversation

@hansipie

Copy link
Copy Markdown
Owner

Summary

  • Remplacement de tous les traceback.print_exc() par logger.exception() et suppression des imports traceback
  • Fix du format de logging f-string → %s dans tous les modules
  • Correction de bugs Streamlit/Plotly (use_container_width, date filtering, hash_funcs)
  • Ajout migration v7 : colonnes amount_from/amount_to de la table Swaps convertis de TEXT en REAL
  • ratesdb_url configurable via settings/config/Market (fallback fiat rates)
  • Fix du bypass de cache fiat dans _get_api_fiat_rate (utilise maintenant get_fiat_latest_rate_cached)
  • Robustesse de update_currencies : déduplication des dates, retry sur erreurs transitoires, insertion batch
  • Fix de la préservation des sous-répertoires dans configuration.py (os.path.basenameos.path.relpath)
  • Suppression du rapport de code review code-review-report.md

Test plan

  • Vérifier que la mise à jour des prix fonctionne (bouton Update)
  • Vérifier que les graphiques s'affichent correctement (page Graphs)
  • Vérifier la migration v7 s'applique sans erreur sur une DB existante
  • Vérifier que le champ RatesDB URL apparaît dans Settings et est sauvegardé
  • Vérifier que la suppression d'un portfolio ne laisse pas d'orphelins dans Portfolios_Tokens

- tokensdb.py: parameterize all queries in get_token_counts,
  get_token_balances, get_last_timestamp_by_token; add empty
  guards; unify Value alias casing
- market.py: whitelist table names in drop_duplicate; replace
  N+1 loop in get_last_market with single JOIN query; fix %f→%d
- tools.py: guard zero division in convert_price_to_target_currency,
  convert_dataframe_prices_historical, calculate_crypto_rate
- 3_Operations.py: fix swapped Streamlit keys swap_amount_from/to;
  guard rows_selected()[0] against None; protect all rate
  divisions with replace(0, pd.NA); guard swap_perf rate_now==0
- Fix inverted keys in swap_edit_dialog (swap_edit_amount_from/to)
- Guard calc_perf and build_buy_avg_table against zero buy rates (airdrops)
- Guard Timeframe Low/High metrics in Graphs against zero prices
- Guard fiat rate inversion in batch_convert_historical_api
- Use module logger instead of root logging in market.py
- Replace f-string table interpolation in drop_duplicate() with a
  hardcoded query dict (_TABLE_QUERIES), making injection structurally
  impossible regardless of validation
- Remove f-strings from get_token_counts() and get_token_balances()
  where conditions were interpolated; user data was already
  parameterized but the pattern was unsafe
- Fix TypeError in swap_edit() when rows_selected() returns None:
  check for None before calling len()
- Unify usd_to_eur_rate zero-guard in convert_price_to_target_currency()
  to cover both USD→EUR and EUR→USD branches, with explicit warning log
- Extend usd_to_eur_rate guard to also reject negative rates
- Move _DROP_DUPLICATE_QUERIES to module-level constant in market.py
- Add clarifying comments in tokensdb.py that conditions strings
  contain only SQL structure, not user data
- 1_Portfolios: remove unused get_portfolio_history() and TokensDatabase import
- 2_Graphs: fix if/elif chain, remove unused apimarket instance, simplify redundant elif
- 3_Operations: rename COL_TOken→col_token, merge draw_swap/draw_swap_arch into _draw_swap_table, add ttl=3600 to build_swap_dataframe cache
- 4_Import: fix log typo, replace traceback.print_exc() with logger.exception(), remove traceback import
- 6_Settings: remove redundant st.session_state.fiat_currency double source of truth
- market.py: wrap response.json() in try/except ValueError
- token_metadata.py: remove hardcoded __main__ block
- tools.py: move sqlite3/requests imports to module level, narrow except Exception
apimarket.py:
- Wrap all requests.get() calls in try/except RequestException
- Add _MAX_PAGES=1000 guard on pagination loops with warning log
- Rename variable `request` → `response` (requests convention)
- Replace all inplace=True with explicit df = df.method() assignments
- Extract _SOURCE_CURRENCY constant, replace hardcoded "USD"

migrations.py:
- Add try/except sqlite3.Error in _ensure_customdata, _get_db_version,
  _set_db_version with re-raise for clear failure messages
- Handle ValueError in _get_db_version for corrupted db_version values
- Replace silent pass in _migrate_v2/_migrate_v5 with logger.debug()
- Extract _V2_COLUMNS dict to make f-string SQL intent explicit
Instead of resolving token_symbol → coinid via /api/v1/coins
(which picks the first result and can return wrong token data),
now use the mraccoon_id stored in TokenMetadata when available.
Falls back to token_symbol if no mraccoon_id is configured.
- Replace remaining traceback.print_exc() with logger.exception()
- Fix f-string logging to use %s format throughout
- Add migration v7: convert Swaps amount columns from TEXT to REAL
- Wire configurable ratesdb_url through settings, config, and Market
- Fix fiat rate caching bypass in _get_api_fiat_rate
- Harden currency update: dedup dates, retry on transient errors, batch insert
- Fix plotly use_container_width, path preservation in save_config, and misc bugs
@hansipie
hansipie merged commit 19dca89 into main Apr 18, 2026
1 check passed
@hansipie
hansipie deleted the fix/code-review branch April 18, 2026 10:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant