Hello from MCP server

List Files | Just Commands | Repo | Logs

← back |
import { defineStore } from "pinia";

import { Preferences } from "@capacitor/preferences";
import { storeCurrency, type CurrencyPrefs } from "@/framework/currencies";
import { getDb } from "@/dataAccess/getDb";

export const usePreferencesStore = defineStore("preferences", {
  state: () => ({
    darkMode: false,
    currency: "usd",
    role: "tech",
    darkModeToggleCount: 0,
    currencyPrefs: null as CurrencyPrefs | null,
  }),
  actions: {
    async getPreferences() {
      const dark = (await Preferences.get({ key: "darkMode" })).value;
      this.darkMode = dark === "true";
      const currency = (await Preferences.get({ key: "currency" })).value;
      this.currency = currency || "usd";
      const role = (await Preferences.get({ key: "role" })).value;
      this.role = role || "tech";
    },

    async getPreference(key: string): Promise<string | null> {
      const result = await Preferences.get({ key });
      return result.value;
    },

    async setPreference(key: string, value: string) {
      await Preferences.set({ key, value });
      await this.getPreferences();
      // Track dark mode toggles
      if (key === "darkMode") {
        this.darkModeToggleCount++;
      }

      // When setting currency, also persist full currency prefs to userPrefs table
      if (key === "currency") {
        await this.syncCurrencyPrefs(value);
      }
    },

    // Helper to build and store full currency prefs
    async syncCurrencyPrefs(targetCurrency: string) {
      const db = await getDb();

      // Load currencies and rates from database
      const currencies = (await db.currencies.getAll()) || [];
      const exchangeRates = (await db.currencies.getRates()) || [];

      // Find the currency record to get the symbol
      const currencyRecord = currencies.find(
        (c: any) => c.refId?.toLowerCase() === targetCurrency.toLowerCase()
      );

      // Find the exchange rate for the target currency
      const rate = exchangeRates.find(
        (r: any) => r.quoteCurrency?.toLowerCase() === targetCurrency.toLowerCase()
      );

      const prefs: CurrencyPrefs = {
        baseCurrency: rate?.baseCurrency || "XAG",
        targetCurrency: targetCurrency.toUpperCase(),
        exchangeRate: rate?.rate ? parseFloat(rate.rate) : 1,
        symbol: currencyRecord?.symbol || "$",
      };

      this.currencyPrefs = prefs;
      await storeCurrency(prefs);
    },

    resetDarkModeToggleCount() {
      this.darkModeToggleCount = 0;
    },
  },
});