From 3d90d3a178eab768d57885194a18cf362afca584 Mon Sep 17 00:00:00 2001 From: Simon Michael Date: Wed, 28 Oct 2026 12:50:22 -1000 Subject: [PATCH 1/4] dev: web: Param, one description of each multiple-choice URL parameter; calc uses it A multiple-choice URL parameter such as calc was described in several places that nothing kept in agreement: its parser, its encoder, its row of links, the options summary's names for it, and its name as a string literal across the handlers (#2798). Now a Param value holds its name, its modes in display order, each mode's URL word, and its labels, and the parser (parseParam, readParam, lookupParam), the row of links (paramLinks), the URL settings (paramSetting, paramSettings) and the options summary's names (paramPhrase) are made from it. The new Hledger.Web.Param module also takes the generic links row renderer (linksRow, linksRowClass, linksRowGroups) from Widget.Common, which now imports it, avoiding an import cycle. calc is the first parameter converted, replacing parseCalc, calcWord and calcLinks. Its labels and translator comments are unchanged, so its translations are too. The journal and register pages now carry only a valid calc value on their links, rather than any value given. Supersedes #2807 and #2821, following the design discussed in #2807. AI usage: Claude Fable 5.1/Opus 5.5, ~51k output tokens --- hledger-lib/locale/hledger.pot | 21 ++- hledger-web/Hledger/Web/App.hs | 7 +- hledger-web/Hledger/Web/Handler/BalanceR.hs | 7 +- hledger-web/Hledger/Web/Handler/JournalR.hs | 12 +- hledger-web/Hledger/Web/Handler/RegisterR.hs | 12 +- .../Hledger/Web/Handler/StatementsR.hs | 7 +- hledger-web/Hledger/Web/Param.hs | 144 ++++++++++++++++++ hledger-web/Hledger/Web/ReportPage.hs | 33 ++-- hledger-web/Hledger/Web/Test.hs | 13 ++ hledger-web/Hledger/Web/Widget/Common.hs | 52 +------ hledger-web/hledger-web.cabal | 1 + 11 files changed, 204 insertions(+), 105 deletions(-) create mode 100644 hledger-web/Hledger/Web/Param.hs diff --git a/hledger-lib/locale/hledger.pot b/hledger-lib/locale/hledger.pot index db191690095..82646f5b268 100644 --- a/hledger-lib/locale/hledger.pot +++ b/hledger-lib/locale/hledger.pot @@ -293,9 +293,8 @@ msgstr "" msgid "Historical gain" msgstr "" -#. the depth limit, in the list of options in effect. #. the label before a report's calculation links, and the links' text and tooltips. -#: hledger/Hledger/Cli/Commands/Balance.hs hledger-web/Hledger/Web/Widget/Common.hs +#: hledger/Hledger/Cli/Commands/Balance.hs hledger-web/Hledger/Web/Param.hs msgid "Posting counts" msgstr "" @@ -1646,35 +1645,33 @@ msgid "Show each amount as a percentage of its column's total (-%)" msgstr "" #. the label before a report's calculation links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Widget/Common.hs +#: hledger-web/Hledger/Web/Param.hs msgid "Calculate:" msgstr "" #. the label before a report's calculation links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Widget/Common.hs +#: hledger-web/Hledger/Web/Param.hs msgid "Show sums of postings" msgstr "" #. the label before a report's calculation links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Widget/Common.hs +#: hledger-web/Hledger/Web/Param.hs msgctxt "calculation" msgid "Sums" msgstr "" -#. the depth limit, in the list of options in effect. #. the label before a report's calculation links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Widget/Common.hs +#: hledger-web/Hledger/Web/Param.hs msgid "Value change" msgstr "" #. the label before a report's calculation links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Widget/Common.hs +#: hledger-web/Hledger/Web/Param.hs msgid "Show how period-end market values changed (--valuechange)" msgstr "" -#. the depth limit, in the list of options in effect. #. the label before a report's calculation links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Widget/Common.hs +#: hledger-web/Hledger/Web/Param.hs msgid "Unrealized gain" msgstr "" @@ -1736,12 +1733,12 @@ msgid "{title} in {dates}, filtered" msgstr "" #. the label before a report's calculation links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Widget/Common.hs +#: hledger-web/Hledger/Web/Param.hs msgid "Show unrealized capital gains: market value minus cost (--gain)" msgstr "" #. the label before a report's calculation links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Widget/Common.hs +#: hledger-web/Hledger/Web/Param.hs msgid "Count the postings instead of summing them (--count)" msgstr "" diff --git a/hledger-web/Hledger/Web/App.hs b/hledger-web/Hledger/Web/App.hs index efbfcb5a696..d9d3c5de534 100644 --- a/hledger-web/Hledger/Web/App.hs +++ b/hledger-web/Hledger/Web/App.hs @@ -60,7 +60,8 @@ import Hledger.Cli.Commands.Balancesheet (balancesheetSpec) import Hledger.Cli.Commands.Cashflow (cashflowSpec) import Hledger.Cli.Commands.Incomestatement (incomestatementSpec) import Hledger.Cli.CompoundBalanceCommand (CompoundBalanceCommandSpec(..)) -import Hledger.Web.ReportPage (AmountMode(..), accumWord, amountModeOf, intervalPeriodExpr, parseCalc, parseListMode, parseValue, reportLinks, setAmountMode) +import Hledger.Web.Param (calcParam, lookupParam, paramName) +import Hledger.Web.ReportPage (AmountMode(..), accumWord, amountModeOf, intervalPeriodExpr, parseListMode, parseValue, reportLinks, setAmountMode) import Hledger.Web.Settings (Extra(..), webmanualurl, widgetFile) import Hledger.Web.Settings.StaticFiles import Hledger.Web.WebOptions @@ -453,7 +454,7 @@ getViewData = do -- parameters, see startupUrlState). lotsShown <- (== Just "1") <$> lookupGetParam "lots" mvalue <- either (const Nothing) id . parseValue <$> lookupGetParam "value" - gain <- either (const False) (== CalcGain) . parseCalc <$> lookupGetParam "calc" + gain <- (== Just CalcGain) <$> lookupParam calcParam let jHasLots = jsHasLots js jfull = jsFull js atCost = conversionop_ (maybe id setAmountMode mvalue _rsReportOpts) == Just ToCost @@ -610,7 +611,7 @@ keptParamNames route -- only the control it names. date2 has no control, being deprecated, -- but is preserved like the rest. stickyParamNames :: [Text] -stickyParamNames = ["interval", "depth", "value", "list", "total", "avg", "sort", "pct", "calc", "infer", "date2", "empty", "lots"] +stickyParamNames = ["interval", "depth", "value", "list", "total", "avg", "sort", "pct", paramName calcParam, "infer", "date2", "empty", "lots"] -- | Are zero-balance accounts hidden ? The empty parameter says (1 -- shows them, 0 hides them, the direction of the command line's diff --git a/hledger-web/Hledger/Web/Handler/BalanceR.hs b/hledger-web/Hledger/Web/Handler/BalanceR.hs index c9a823d9493..15de60a33d8 100644 --- a/hledger-web/Hledger/Web/Handler/BalanceR.hs +++ b/hledger-web/Hledger/Web/Handler/BalanceR.hs @@ -18,11 +18,12 @@ import Hledger.Utils.I18n (tr, trc, trf) import Hledger.Web.Import import Hledger.Web.Widget.AddForm (addModal) import Hledger.Web.Paging (yearsRow) +import Hledger.Web.Param (calcParam, paramLinks, paramSettings) import Hledger.Web.ReportPage import Hledger.Web.WebOptions import Hledger.Web.Widget.Chart (reportChart) import Hledger.Web.Widget.Common - (amountLinks, calcLinks, columnsLinks, commodityLinks, controlsHint, controlsToggle, optionsSummary, + (amountLinks, columnsLinks, commodityLinks, controlsHint, controlsToggle, optionsSummary, depthLinks, listModeLinks, lotsLinks, percentLinks, pricesLinks, realLinks, sortLinks, statusLinks, typeLinks, zeroBalanceLinks) @@ -88,7 +89,7 @@ getBalanceR = do avgParams = [("avg", "1") | average_ ropts] sortParams = [("sort", "amount") | sort_amount_ ropts] pctParams = [("pct", "1") | percent_ ropts] - calcParams = [("calc", w) | Just w <- [calcWord $ balancecalc_ ropts]] + calcParams = paramSettings calcParam CalcChange (balancecalc_ ropts) inferParams = [("infer", "1") | infer_prices_ ropts, not (infer_prices_ roptsOrig)] date2Params = [("date2", "1") | date2_ ropts, not (date2_ roptsOrig)] emptyParams = [("empty", if hideEmpty then "0" else "1") | hideEmpty /= empty_ roptsOrig] @@ -162,7 +163,7 @@ getBalanceR = do | rpInterval /= NoInterval ] ++ [ sortLinks trs BalanceR (qParams ++ removeAttributes ["sort"] pageParams) (sort_amount_ ropts) , percentLinks trs BalanceR (qParams ++ removeAttributes ["pct"] pageParams) (percent_ ropts) - , calcLinks trs BalanceR (qParams ++ removeAttributes ["calc"] pageParams) (balancecalc_ ropts) ] + , paramLinks calcParam trs BalanceR (qParams ++ pageParams) CalcChange (balancecalc_ ropts) ] Yesod.toWidget controlRows Yesod.toWidget $ H.h2 $ H.toHtml $ withFilter title for_ pctErr $ Yesod.toWidget . pctError trs diff --git a/hledger-web/Hledger/Web/Handler/JournalR.hs b/hledger-web/Hledger/Web/Handler/JournalR.hs index 81df164cba3..01f769a9cb7 100644 --- a/hledger-web/Hledger/Web/Handler/JournalR.hs +++ b/hledger-web/Hledger/Web/Handler/JournalR.hs @@ -15,9 +15,10 @@ import Hledger.Web.Import import Hledger.Web.Paging import Hledger.Web.WebOptions import Hledger.Web.Widget.AddForm (addModal) -import Hledger.Web.ReportPage (amountModeOf, deepestDepth, depthParams, intervalLinks, listWord, parseCalc, parseInterval, parseListMode, parseValue, removeAttributes, setAmountMode, valueParams) +import Hledger.Web.Param (calcParam, lookupParam, paramLinks, paramSettings) +import Hledger.Web.ReportPage (amountModeOf, deepestDepth, depthParams, intervalLinks, listWord, parseInterval, parseListMode, parseValue, removeAttributes, setAmountMode, valueParams) import Hledger.Web.Widget.Common - (accountParams, amountLinks, calcLinks, columnsLinks, commodityLinks, + (accountParams, amountLinks, columnsLinks, commodityLinks, controlsHint, controlsToggle, optionsSummary, searchHeading, depthLinks, inertControls, listModeLinks, lotsLinks, mixedAmountAsHtml, percentLinks, pricesLinks, realLinks, sortLinks, @@ -38,7 +39,7 @@ getJournalR = do avgOn <- (== Just "1") <$> lookupGetParam "avg" sortAmt <- (== Just "amount") <$> lookupGetParam "sort" pctOn <- (== Just "1") <$> lookupGetParam "pct" - mcalc <- lookupGetParam "calc" + calcCur <- fromMaybe CalcChange <$> lookupParam calcParam date2On <- (== Just "1") <$> lookupGetParam "date2" pagereq <- pageRequest let title = case account of @@ -80,7 +81,7 @@ getJournalR = do [("avg", "1") | avgOn] ++ [("sort", "amount") | sortAmt] ++ [("pct", "1") | pctOn] ++ - [("calc", c) | Just c <- [mcalc], not (T.null c)] ++ + paramSettings calcParam CalcChange calcCur ++ [("date2", "1") | date2On] lotsParams = [("lots", "1") | lotsShown] carried = dbg1 "journal carried params" $ stickyParams ++ valParams ++ listParams ++ inferParams ++ emptyParams ++ lotsParams ++ depthParams q @@ -117,7 +118,6 @@ getJournalR = do -- The report-shaping controls, operative on the report pages, -- shown dimmed with the url's state marked. rpInterval = maybe NoInterval (either (const NoInterval) id . parseInterval) minterval - calcCur = either (const CalcChange) id $ parseCalc mcalc -- The years row; its links rewrite the search's date narrowing themselves. yearsNav = yearsRow trs JournalR qparam today carried years intervalRow = inertControls trs $ @@ -126,7 +126,7 @@ getJournalR = do [ columnsLinks trs JournalR (qps ++ removeAttributes ["total", "avg"] carried) totalOn avgOn , sortLinks trs JournalR (qps ++ removeAttributes ["sort"] carried) sortAmt , percentLinks trs JournalR (qps ++ removeAttributes ["pct"] carried) pctOn - , calcLinks trs JournalR (qps ++ removeAttributes ["calc"] carried) calcCur + , paramLinks calcParam trs JournalR (qps ++ carried) CalcChange calcCur ] -- All of them behind the controls disclosure, closed by default, -- in the same order as on the report pages. diff --git a/hledger-web/Hledger/Web/Handler/RegisterR.hs b/hledger-web/Hledger/Web/Handler/RegisterR.hs index 78faae113a3..abef9369b90 100644 --- a/hledger-web/Hledger/Web/Handler/RegisterR.hs +++ b/hledger-web/Hledger/Web/Handler/RegisterR.hs @@ -27,11 +27,12 @@ import Hledger.Write.Chart.Svg (SvgOptions(..), chartSvgMarkupWith, defaultSvgOp import Hledger.Web.Import import Hledger.Web.Paging import Hledger.Web.Widget.Chart (chartLegend, chartWidth) -import Hledger.Web.ReportPage (amountModeOf, deepestDepth, depthParams, removeAttributes, intervalLinks, listWord, parseCalc, parseInterval, parseListMode, parseValue, setAmountMode, valueParams) +import Hledger.Web.Param (calcParam, lookupParam, paramLinks, paramSettings) +import Hledger.Web.ReportPage (amountModeOf, deepestDepth, depthParams, removeAttributes, intervalLinks, listWord, parseInterval, parseListMode, parseValue, setAmountMode, valueParams) import Hledger.Web.WebOptions import Hledger.Web.Widget.AddForm (addModal) import Hledger.Web.Widget.Common - (accountParams, accountRegisterQuery, amountLinks, calcLinks, columnsLinks, + (accountParams, accountRegisterQuery, amountLinks, columnsLinks, commodityLinks, controlsHint, controlsToggle, optionsSummary, searchHeading, costsLinks, depthLinks, inertControls, listModeLinks, lotsLinks, mixedAmountAsHtmlElided, mixedAmountAsHtmlWith, moreCommodities, percentLinks, pricesLinks, realLinks, @@ -64,7 +65,7 @@ getRegisterR = do avgOn <- (== Just "1") <$> lookupGetParam "avg" sortAmt <- (== Just "amount") <$> lookupGetParam "sort" pctOn <- (== Just "1") <$> lookupGetParam "pct" - mcalc <- lookupGetParam "calc" + calcCur <- fromMaybe CalcChange <$> lookupParam calcParam urlrender <- getUrlRenderParams pagereq <- pageRequest -- How wide to draw the chart: as wide as the page's main column. @@ -104,7 +105,7 @@ getRegisterR = do [("avg", "1") | avgOn] ++ [("sort", "amount") | sortAmt] ++ [("pct", "1") | pctOn] ++ - [("calc", c) | Just c <- [mcalc], not (T.null c)] + paramSettings calcParam CalcChange calcCur lotsParams = [("lots", "1") | lotsShown] -- The account this register is for, which its own links keep. acctParams = maybe [] (\(a, subs) -> accountParams subs a) account @@ -147,7 +148,6 @@ getRegisterR = do -- The report-shaping controls, operative on the report pages, -- shown dimmed with the url's state marked. rpInterval = maybe NoInterval (either (const NoInterval) id . parseInterval) minterval - calcCur = either (const CalcChange) id $ parseCalc mcalc -- The years row; its links rewrite the search's date narrowing themselves. yearsNav = yearsRow trs RegisterR qparam today modeParams years intervalRow = inertControls trs $ @@ -156,7 +156,7 @@ getRegisterR = do [ columnsLinks trs RegisterR (qParams qparam ++ removeAttributes ["total", "avg"] modeParams) totalOn avgOn , sortLinks trs RegisterR (qParams qparam ++ removeAttributes ["sort"] modeParams) sortAmt , percentLinks trs RegisterR (qParams qparam ++ removeAttributes ["pct"] modeParams) pctOn - , calcLinks trs RegisterR (qParams qparam ++ removeAttributes ["calc"] modeParams) calcCur + , paramLinks calcParam trs RegisterR (qParams qparam ++ modeParams) CalcChange calcCur ] -- All of them behind the controls disclosure, closed by default, -- in the same order as on the report pages. diff --git a/hledger-web/Hledger/Web/Handler/StatementsR.hs b/hledger-web/Hledger/Web/Handler/StatementsR.hs index d79c877ce8a..e0e11b26c2d 100644 --- a/hledger-web/Hledger/Web/Handler/StatementsR.hs +++ b/hledger-web/Hledger/Web/Handler/StatementsR.hs @@ -33,11 +33,12 @@ import Hledger.Write.Spreadsheet qualified as Spr import Hledger.Web.Import import Hledger.Web.Widget.AddForm (addModal) import Hledger.Web.Paging (yearsRow) +import Hledger.Web.Param (calcParam, paramLinks, paramSettings) import Hledger.Web.ReportPage import Hledger.Web.WebOptions import Hledger.Web.Widget.Chart (reportChart) import Hledger.Web.Widget.Common - (amountLinks, calcLinks, columnsLinks, commodityLinks, controlsToggle, optionsSummary, + (amountLinks, columnsLinks, commodityLinks, controlsToggle, optionsSummary, depthLinks, equityLinks, helplink, listModeLinks, lotsLinks, percentLinks, pricesLinks, realLinks, sortLinks, statusLinks, zeroBalanceLinks) @@ -127,7 +128,7 @@ statementPage here tabtitle spec mequity = do avgParams = [("avg", "1") | average_ ropts] sortParams = [("sort", "amount") | sort_amount_ ropts] pctParams = [("pct", "1") | percent_ ropts] - calcParams = [("calc", w) | Just w <- [calcWord $ balancecalc_ ropts]] + calcParams = paramSettings calcParam CalcChange (balancecalc_ ropts) inferParams = [("infer", "1") | infer_prices_ ropts, not (infer_prices_ roptsOrig)] date2Params = [("date2", "1") | date2_ ropts, not (date2_ roptsOrig)] emptyParams = [("empty", if hideEmpty then "0" else "1") | hideEmpty /= empty_ roptsOrig] @@ -204,7 +205,7 @@ statementPage here tabtitle spec mequity = do | rpInterval /= NoInterval ] ++ [ sortLinks trs here (qParams ++ removeAttributes ["sort"] pageParams) (sort_amount_ ropts) , percentLinks trs here (qParams ++ removeAttributes ["pct"] pageParams) (percent_ ropts) - , calcLinks trs here (qParams ++ removeAttributes ["calc"] pageParams) (balancecalc_ ropts) ] + , paramLinks calcParam trs here (qParams ++ pageParams) CalcChange (balancecalc_ ropts) ] Yesod.toWidget controlRows Yesod.toWidget $ H.h2 $ H.toHtml $ withFilter $ cbrTitle cbr for_ pctErr $ Yesod.toWidget . pctError trs diff --git a/hledger-web/Hledger/Web/Param.hs b/hledger-web/Hledger/Web/Param.hs new file mode 100644 index 00000000000..2af4a67d160 --- /dev/null +++ b/hledger-web/Hledger/Web/Param.hs @@ -0,0 +1,144 @@ +{-| +The report pages' rows of links, and their multiple-choice URL +parameters, such as calc: each one's name, modes, URL words, and labels, +written once, from which its parser, its row of links, the parameters +that carry it, and its name in the options summary are made. +-} + +{-# LANGUAGE LambdaCase #-} +{-# LANGUAGE OverloadedStrings #-} + +module Hledger.Web.Param + ( linksRow + , linksRowClass + , linksRowGroups + , Param(..) + , parseParam + , lookupParam + , paramSetting + , paramSettings + , paramLinks + , paramPhrase + , calcParam + ) where + +import Control.Monad (unless) +import Data.Foldable (find, for_) +import Data.Text (Text) +import Data.Text qualified as T +import Text.Blaze ((!), (!?)) +import Text.Blaze.Html5 qualified as H +import Text.Blaze.Html5.Attributes qualified as A +import Yesod (HtmlUrl, MonadHandler, lookupGetParam) + +import Hledger +import Hledger.Utils.I18n (Translations, tr, trc) + +-- | A row of links above a report: a label, then each link's label, +-- title, target, and whether it is the one being shown. +-- Each label and title is a whole phrase, not a word slotted into a +-- sentence: an adjective that fits one language's sentence does not fit +-- another's, so a translation cannot be assembled from parts. +linksRow :: Text -> [(Text, Text, (r, [(Text, Text)]), Bool)] -> HtmlUrl r +linksRow = linksRowClass "" + +-- | 'linksRow' with an extra class on the row: a hook for hledger.js's +-- keyboard shortcuts. +linksRowClass :: Text -> Text -> [(Text, Text, (r, [(Text, Text)]), Bool)] -> HtmlUrl r +linksRowClass cls rowlabel items = linksRowGroups cls rowlabel [items] + +-- | 'linksRowClass' with the links in groups, shown a little apart. +linksRowGroups :: Text -> Text -> [[(Text, Text, (r, [(Text, Text)]), Bool)]] -> HtmlUrl r +linksRowGroups cls rowlabel groups renderUrl = + H.p ! A.class_ (H.toValue $ T.unwords $ "report-links" : [cls | not (T.null cls)]) $ do + unless (T.null rowlabel) $ H.span ! A.class_ "row-label" $ H.toHtml rowlabel + for_ (zip [0 :: Int ..] groups) $ \(g, items) -> + for_ (zip [0 :: Int ..] items) $ \(i, (label, title, link, current)) -> + let classes = ["current" | current] ++ ["group-start" | g > 0, i == 0] + in H.a !? (not (null classes), A.class_ (H.toValue $ T.unwords classes)) + ! A.href (H.toValue $ uncurry renderUrl link) + ! A.title (H.toValue title) $ + H.toHtml label + +-- | A multiple-choice URL parameter, and its row of links. +-- Where the parameter offers every constructor of its type, write +-- 'paramWord' and 'paramLabel' as case expressions naming every +-- constructor, with no catch-all case: then a constructor added to the +-- type gives a missing-case warning until it has a word and a label. +data Param a = Param + { paramName :: Text + -- ^ The URL parameter's name, eg "calc". Also the class of its row + -- of links, which hledger.js's keyboard shortcuts look for. + , paramModes :: [a] + -- ^ The modes the page offers, in the order of the row's links. + -- Can be a subset of the type's constructors. + , paramWord :: a -> Text + -- ^ The URL word naming a mode, eg "gain". Each mode's must differ. + , paramRowLabel :: Translations -> Text + -- ^ The label before the row of links, eg "Calculate:". + , paramLabel :: Translations -> a -> (Text, Text) + -- ^ A mode's link text and tooltip. The link text is also how the + -- closed options disclosure names the mode. + } + +-- | Read a parameter's value: one of its modes' words, or, when it is +-- empty or absent, Nothing, for the page's default. An unknown word is +-- returned on the Left. +parseParam :: Param a -> Maybe Text -> Either Text (Maybe a) +parseParam p = \case + Nothing -> Right Nothing + Just "" -> Right Nothing + Just w -> maybe (Left w) (Right . Just) $ find ((== w) . paramWord p) (paramModes p) + +-- | A parameter's value in the request, if it names one of its modes. +-- For pages that ignore an unknown value rather than report it. +lookupParam :: MonadHandler m => Param a -> m (Maybe a) +lookupParam p = either (const Nothing) id . parseParam p <$> lookupGetParam (paramName p) + +-- | The URL parameter selecting a mode. +paramSetting :: Param a -> a -> (Text, Text) +paramSetting p a = (paramName p, paramWord p a) + +-- | The URL parameter selecting a mode, if needed: not for the page's +-- default mode, or a mode the parameter does not offer. +paramSettings :: Eq a => Param a -> a -> a -> [(Text, Text)] +paramSettings p dflt a = [paramSetting p a | a /= dflt, a `elem` paramModes p] + +-- | A parameter's row of links, one per mode, each replacing the +-- parameter among the given ones; the page's default mode needs none. +-- The mode being shown is marked. The row's class is the parameter's +-- name, a hook for hledger.js's keyboard shortcuts. +paramLinks :: Eq a => Param a -> Translations -> r -> [(Text, Text)] -> a -> a -> HtmlUrl r +paramLinks p trs route kept dflt current = + linksRowClass (paramName p) (paramRowLabel p trs) + [ (label, title, (route, kept' ++ paramSettings p dflt a), a == current) + | a <- paramModes p, let (label, title) = paramLabel p trs a ] + where kept' = filter ((/= paramName p) . fst) kept + +-- | The link text of the mode a URL word names, if it names one: how +-- the closed options disclosure lists it. +paramPhrase :: Param a -> Translations -> Text -> Maybe Text +paramPhrase p trs w = fst . paramLabel p trs <$> find ((== w) . paramWord p) (paramModes p) + +-- | The calc parameter: what a report's cells calculate, as the balance +-- commands' --valuechange, --gain, and --count flags choose. +calcParam :: Param BalanceCalculation +calcParam = Param + { paramName = "calc" + , paramModes = [CalcChange, CalcValueChange, CalcGain, CalcPostingsCount] + , paramWord = \case + CalcChange -> "change" + CalcValueChange -> "valuechange" + CalcGain -> "gain" + CalcPostingsCount -> "count" + -- Not offered (not in paramModes), so never in a url. + _ -> "" + -- TRANSLATORS: the label before a report's calculation links, and the links' text and tooltips. + , paramRowLabel = \trs -> tr trs "Calculate:" + , paramLabel = \trs -> \case + CalcChange -> (trc trs "calculation" "Sums", tr trs "Show sums of postings") + CalcValueChange -> (tr trs "Value change", tr trs "Show how period-end market values changed (--valuechange)") + CalcGain -> (tr trs "Unrealized gain", tr trs "Show unrealized capital gains: market value minus cost (--gain)") + CalcPostingsCount -> (tr trs "Posting counts", tr trs "Count the postings instead of summing them (--count)") + _ -> ("", "") + } diff --git a/hledger-web/Hledger/Web/ReportPage.hs b/hledger-web/Hledger/Web/ReportPage.hs index 80a2ffb3bca..8adea864bd7 100644 --- a/hledger-web/Hledger/Web/ReportPage.hs +++ b/hledger-web/Hledger/Web/ReportPage.hs @@ -21,7 +21,7 @@ module Hledger.Web.ReportPage ( AmountMode(..), parseValue, parseListMode, - parseCalc, + readParam, listWord, valueWord, amountModeOf, @@ -33,7 +33,6 @@ module Hledger.Web.ReportPage ( parseInterval, depthParams, accumWord, - calcWord, columnHeading, headingParams, removeAttributes, @@ -67,7 +66,8 @@ import Yesod (HtmlUrl) import Hledger.Utils.I18n (Translations, tr, trc, trf) import Hledger import Hledger.Cli.Anchor (dateTerm, renderPeriodHeading) -import Hledger.Web.Widget.Common (AmountMode(..), accumWord, linksRowClass, listWord, removeDates, valueWord) +import Hledger.Web.Param (Param(..), calcParam, linksRowClass, paramSettings, parseParam) +import Hledger.Web.Widget.Common (AmountMode(..), accumWord, listWord, removeDates, valueWord) import Hledger.Query qualified as Query import Hledger.Write.Html (Html, formatCell, nl) import Hledger.Write.Spreadsheet (Cell(..), Class(..), NumLines, textFromClass) @@ -119,7 +119,7 @@ reportParams rspecOrig qparam q qopts hideEmpty params = do avg <- parseFlag "avg" (param "avg") sortAmt <- parseSort (param "sort") pct <- parseFlag "pct" (param "pct") - calc <- parseCalc (param "calc") + calc <- fromMaybe CalcChange <$> readParam calcParam (param $ paramName calcParam) infer <- parseFlag "infer" (param "infer") dat2 <- parseFlag "date2" (param "date2") let rpInterval = fromMaybe ivl $ intervalFromQueryOpts qopts @@ -201,7 +201,7 @@ startupUrlState rspec@ReportSpec{_rsReportOpts = ropts} = (params, rspec') [("avg", "1") | average_ ropts] ++ [("sort", "amount") | sort_amount_ ropts] ++ [("pct", "1") | percent_ ropts] ++ - [("calc", c) | Just c <- [calcWord $ balancecalc_ ropts]] ++ + paramSettings calcParam CalcChange (balancecalc_ ropts) ++ [("costs", "1") | show_costs_ ropts] ++ [("infer", "1") | infer_prices_ ropts] ++ [("date2", "1") | date2_ ropts] ++ @@ -368,25 +368,10 @@ parseSort = \case Just "amount" -> Right True Just other -> Left $ BadParamValue "sort" other --- | The calc parameter: what a report's cells calculate, as the balance --- commands' --valuechange, --gain, and --count flags choose. -parseCalc :: Maybe Text -> Either ReportParamError BalanceCalculation -parseCalc = \case - Nothing -> Right CalcChange - Just "" -> Right CalcChange - Just "change" -> Right CalcChange - Just "valuechange" -> Right CalcValueChange - Just "gain" -> Right CalcGain - Just "count" -> Right CalcPostingsCount - Just other -> Left $ BadParamValue "calc" other - --- | The calc parameter value naming a calculation, for those that have one. -calcWord :: BalanceCalculation -> Maybe Text -calcWord = \case - CalcValueChange -> Just "valuechange" - CalcGain -> Just "gain" - CalcPostingsCount -> Just "count" - _ -> Nothing +-- | Read a multiple-choice parameter's value (see 'parseParam'), +-- naming the parameter if the value is unknown. +readParam :: Param a -> Maybe Text -> Either ReportParamError (Maybe a) +readParam p = either (Left . BadParamValue (paramName p)) Right . parseParam p -- | The value parameter, mirroring --value's WHEN[,COMM] syntax: -- "none", "cost", or a valuation "end", "then", "now", or a date, each diff --git a/hledger-web/Hledger/Web/Test.hs b/hledger-web/Hledger/Web/Test.hs index 64c15bfdb9f..5ca7803491e 100644 --- a/hledger-web/Hledger/Web/Test.hs +++ b/hledger-web/Hledger/Web/Test.hs @@ -44,6 +44,7 @@ import Data.Aeson (encode) import Data.ByteString qualified as BS import Data.String (fromString) import Data.Function ((&)) +import Data.List (nub) import Data.Text qualified as T import Data.Text.Encoding qualified as TE import Data.Text.IO qualified as TIO @@ -64,6 +65,7 @@ import Web.Cookie (defaultSetCookie, setCookieName, setCookieValue) import Hledger.Web.Application ( makeAppWith ) import Hledger.Utils.I18n (noTranslations) import Hledger.Web.Paging (pageNumbers) +import Hledger.Web.Param (Param(..), calcParam, parseParam) import Hledger.Web.ReportPage (intervalPeriodExpr, startupUrlState) import Hledger.Web.WebOptions -- ( WebOpts(..), defwebopts, prognameandversion ) import Hledger.Web.Import hiding (get, j) @@ -271,6 +273,17 @@ hledgerWebTest = do splitPeriodExpr refday "2025" `shouldBe` Nothing splitPeriodExpr refday "monthly bogus" `shouldBe` Nothing + -- The multiple-choice parameters, whose parsers are made from their words. + hspec $ describe "Param" $ do + it "gives each mode its own word" $ do + let distinctWords p = let ws = map (paramWord p) (paramModes p) in length (nub ws) == length ws + distinctWords calcParam `shouldBe` True + it "reads a mode's word, an empty or absent value as the default, and returns an unknown word" $ do + parseParam calcParam (Just "gain") `shouldBe` Right (Just CalcGain) + parseParam calcParam (Just "") `shouldBe` Right Nothing + parseParam calcParam Nothing `shouldBe` Right Nothing + parseParam calcParam (Just "budget") `shouldBe` Left "budget" + -- The options in effect, listed on the closed Options disclosure. hspec $ describe "optionsSummary" $ do it "lists the options in the controls' order, in their words, skipping other parameters" $ diff --git a/hledger-web/Hledger/Web/Widget/Common.hs b/hledger-web/Hledger/Web/Widget/Common.hs index c0536a3f076..13a0df3aab4 100644 --- a/hledger-web/Hledger/Web/Widget/Common.hs +++ b/hledger-web/Hledger/Web/Widget/Common.hs @@ -13,9 +13,6 @@ module Hledger.Web.Widget.Common , optionsSummary , searchHeading , inertControls - , linksRow - , linksRowClass - , linksRowGroups , pricesLinks , commodityLinks , depthLinks @@ -28,7 +25,6 @@ module Hledger.Web.Widget.Common , columnsLinks , sortLinks , percentLinks - , calcLinks , costsLinks , lotsLinks , closedLinks @@ -57,7 +53,7 @@ module Hledger.Web.Widget.Common ) where import Control.Applicative ((<|>)) -import Control.Monad (guard, unless, when) +import Control.Monad (guard, when) import Control.Monad.Except (ExceptT, mapExceptT) import Data.Char (isDigit) import Data.Foldable (find, for_) @@ -82,6 +78,7 @@ import Hledger.Utils.I18n (Translations, tr, trc, trf) import Hledger import Hledger.Cli.Anchor qualified as Anchor import Hledger.Cli.Utils (writeFileWithBackupIfChanged) +import Hledger.Web.Param (calcParam, linksRow, linksRowClass, paramName, paramPhrase) import Hledger.Web.Settings (manualurl) import Hledger.Query qualified as Query @@ -162,32 +159,6 @@ balanceReportAsHtml registerR here reports reportParams hideEmpty totlabel totti -- form's clear button is the way out of a search. totallink = (registerR, qps ++ kept) --- | A row of links above a report: a label, then each link's label, --- title, target, and whether it is the one being shown. --- Each label and title is a whole phrase, not a word slotted into a --- sentence: an adjective that fits one language's sentence does not fit --- another's, so a translation cannot be assembled from parts. -linksRow :: Text -> [(Text, Text, (r, [(Text, Text)]), Bool)] -> HtmlUrl r -linksRow = linksRowClass "" - --- | 'linksRow' with an extra class on the row: a hook for hledger.js's --- keyboard shortcuts. -linksRowClass :: Text -> Text -> [(Text, Text, (r, [(Text, Text)]), Bool)] -> HtmlUrl r -linksRowClass cls rowlabel items = linksRowGroups cls rowlabel [items] - --- | 'linksRowClass' with the links in groups, shown a little apart. -linksRowGroups :: Text -> Text -> [[(Text, Text, (r, [(Text, Text)]), Bool)]] -> HtmlUrl r -linksRowGroups cls rowlabel groups renderUrl = - H.p ! A.class_ (H.toValue $ T.unwords $ "report-links" : [cls | not (T.null cls)]) $ do - unless (T.null rowlabel) $ H.span ! A.class_ "row-label" $ H.toHtml rowlabel - for_ (zip [0 :: Int ..] groups) $ \(g, items) -> - for_ (zip [0 :: Int ..] items) $ \(i, (label, title, link, current)) -> - let classes = ["current" | current] ++ ["group-start" | g > 0, i == 0] - in H.a !? (not (null classes), A.class_ (H.toValue $ T.unwords classes)) - ! A.href (H.toValue $ uncurry renderUrl link) - ! A.title (H.toValue title) $ - H.toHtml label - -- | A page's rows of report controls behind a disclosure, closed by -- default so the page stays uncluttered. Opening it is remembered per -- browser in the showcontrols cookie (hledger.js), which the server @@ -220,7 +191,7 @@ optionsSummary trs deepest = mapMaybe phrase . sortOn (rowOrder . fst) where rowOrder k = fromMaybe maxBound $ elemIndex k ["equity", "interval", "accum", "depth", "list", "value", "infer", "empty", "lots", "closed", - "total", "avg", "costs", "sort", "pct", "calc", "date2"] + "total", "avg", "costs", "sort", "pct", paramName calcParam, "date2"] phrase = \case ("interval", w) -> Just $ fromMaybe w $ lookup w [ ("yearly", tr trs "Yearly"), ("quarterly", tr trs "Quarterly"), ("monthly", tr trs "Monthly") @@ -240,9 +211,7 @@ optionsSummary trs deepest = mapMaybe phrase . sortOn (rowOrder . fst) ("list", "flat") -> Just $ trc trs "accounts" "List" ("sort", "amount") -> Just $ tr trs "By amount" ("pct", "1") -> Just $ tr trs "Percentages" - ("calc", c) -> lookup c - [ ("valuechange", tr trs "Value change"), ("gain", tr trs "Unrealized gain") - , ("count", tr trs "Posting counts") ] + (k, w) | k == paramName calcParam -> paramPhrase calcParam trs w -- TRANSLATORS: options in effect, listed on the closed options disclosure. ("total", "1") -> Just $ trc trs "column" "Total" ("avg", "1") -> Just $ trc trs "column" "Average" @@ -491,19 +460,6 @@ percentLinks trs route kept pct = , (tr trs "Percentages", tr trs "Show each amount as a percentage of its column's total (-%)", (route, kept ++ [("pct", "1")]), pct) ] --- | Links choosing what the report's cells calculate, as the balance --- commands' --valuechange, --gain, and --count flags do. -calcLinks :: Translations -> r -> [(Text, Text)] -> BalanceCalculation -> HtmlUrl r -calcLinks trs route kept calc = - -- TRANSLATORS: the label before a report's calculation links, and the links' text and tooltips. - linksRow (tr trs "Calculate:") - [ (trc trs "calculation" "Sums", tr trs "Show sums of postings", (route, kept), calc == CalcChange) - , (tr trs "Value change", tr trs "Show how period-end market values changed (--valuechange)", link "valuechange", calc == CalcValueChange) - , (tr trs "Unrealized gain", tr trs "Show unrealized capital gains: market value minus cost (--gain)", link "gain", calc == CalcGain) - , (tr trs "Posting counts", tr trs "Count the postings instead of summing them (--count)", link "count", calc == CalcPostingsCount) - ] - where link w = (route, kept ++ [("calc", w)]) - -- | Links showing or hiding the costs recorded with a register's -- amounts (10 AAPL @ $95), keeping the given parameters. costsLinks :: Translations -> r -> [(Text, Text)] -> Bool -> HtmlUrl r diff --git a/hledger-web/hledger-web.cabal b/hledger-web/hledger-web.cabal index a3e23876644..b59b2e45685 100644 --- a/hledger-web/hledger-web.cabal +++ b/hledger-web/hledger-web.cabal @@ -102,6 +102,7 @@ library Hledger.Web.Import Hledger.Web.Main Hledger.Web.Paging + Hledger.Web.Param Hledger.Web.ReportPage Hledger.Web.Settings Hledger.Web.Settings.StaticFiles From f75d43f4fbcdb272aed40a7a02510eb3101600a2 Mon Sep 17 00:00:00 2001 From: Simon Michael Date: Thu, 12 Nov 2026 21:40:39 -1000 Subject: [PATCH 2/4] dev: web: accum uses Param A bad accum value in a url now shows the same message as other bad parameter values ("The accum parameter has a value this page does not know"), instead of its own. accumParam replaces parseAccum, accumWord, accumulationLinks and the BadAccum error, and the accum literals in the handlers, App.hs's kept parameters, startupUrlState and the options summary. Its modes keep the links' order, so the H key still toggles Ending balances. AI usage: Claude Opus 5.5, ~8k output tokens --- hledger-lib/locale/hledger.pot | 21 +++------ hledger-web/Hledger/Web/App.hs | 14 +++--- hledger-web/Hledger/Web/Handler/BalanceR.hs | 8 ++-- hledger-web/Hledger/Web/Handler/RegisterR.hs | 12 ++--- .../Hledger/Web/Handler/StatementsR.hs | 8 ++-- hledger-web/Hledger/Web/Param.hs | 20 ++++++++ hledger-web/Hledger/Web/ReportPage.hs | 46 ++----------------- hledger-web/Hledger/Web/Test.hs | 7 +-- hledger-web/Hledger/Web/Widget/Common.hs | 16 ++----- 9 files changed, 60 insertions(+), 92 deletions(-) diff --git a/hledger-lib/locale/hledger.pot b/hledger-lib/locale/hledger.pot index 82646f5b268..34956c7e835 100644 --- a/hledger-lib/locale/hledger.pot +++ b/hledger-lib/locale/hledger.pot @@ -312,8 +312,7 @@ msgstr "" #. Key term #. the label before a report's accumulation mode links, and the links' text and tooltips. -#. the depth limit, in the list of options in effect. -#: hledger/Hledger/Cli/Commands/Balance.hs hledger-web/Hledger/Web/ReportPage.hs hledger-web/Hledger/Web/Widget/Common.hs +#: hledger/Hledger/Cli/Commands/Balance.hs hledger-web/Hledger/Web/Param.hs msgid "Balance changes" msgstr "" @@ -650,7 +649,7 @@ msgid "Register" msgstr "" #. the label before a report's accumulation mode links, and the links' text and tooltips. -#: hledger/Hledger/Cli/Commands/Run.hs hledger-web/Hledger/Web/ReportPage.hs hledger-web/templates/default-layout.hamlet +#: hledger/Hledger/Cli/Commands/Run.hs hledger-web/Hledger/Web/Param.hs hledger-web/templates/default-layout.hamlet msgid "Show:" msgstr "" @@ -912,30 +911,28 @@ msgid "Show a column per day" msgstr "" #. the label before a report's accumulation mode links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/ReportPage.hs +#: hledger-web/Hledger/Web/Param.hs msgid "Show how much each balance changed in each period" msgstr "" #. Key term #. the label before a report's accumulation mode links, and the links' text and tooltips. -#. the depth limit, in the list of options in effect. -#: hledger-web/Hledger/Web/ReportPage.hs hledger-web/Hledger/Web/Widget/Common.hs +#: hledger-web/Hledger/Web/Param.hs msgid "Ending balances" msgstr "" #. the label before a report's accumulation mode links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/ReportPage.hs +#: hledger-web/Hledger/Web/Param.hs msgid "Show each balance at the end of each period, including everything before it" msgstr "" #. the label before a report's accumulation mode links, and the links' text and tooltips. -#. the depth limit, in the list of options in effect. -#: hledger-web/Hledger/Web/ReportPage.hs hledger-web/Hledger/Web/Widget/Common.hs +#: hledger-web/Hledger/Web/Param.hs msgid "Cumulative totals" msgstr "" #. the label before a report's accumulation mode links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/ReportPage.hs +#: hledger-web/Hledger/Web/Param.hs msgid "Show each balance's change since the start of the report (--cumulative)" msgstr "" @@ -947,10 +944,6 @@ msgstr "" msgid "Could not parse the reporting interval:" msgstr "" -#: hledger-web/Hledger/Web/ReportPage.hs -msgid "Unknown balance accumulation mode:" -msgstr "" - #: hledger-web/Hledger/Web/ReportPage.hs msgid "Unknown amount conversion:" msgstr "" diff --git a/hledger-web/Hledger/Web/App.hs b/hledger-web/Hledger/Web/App.hs index d9d3c5de534..a5a5b69a170 100644 --- a/hledger-web/Hledger/Web/App.hs +++ b/hledger-web/Hledger/Web/App.hs @@ -60,8 +60,8 @@ import Hledger.Cli.Commands.Balancesheet (balancesheetSpec) import Hledger.Cli.Commands.Cashflow (cashflowSpec) import Hledger.Cli.Commands.Incomestatement (incomestatementSpec) import Hledger.Cli.CompoundBalanceCommand (CompoundBalanceCommandSpec(..)) -import Hledger.Web.Param (calcParam, lookupParam, paramName) -import Hledger.Web.ReportPage (AmountMode(..), accumWord, amountModeOf, intervalPeriodExpr, parseListMode, parseValue, reportLinks, setAmountMode) +import Hledger.Web.Param (Param(..), accumParam, calcParam, lookupParam) +import Hledger.Web.ReportPage (AmountMode(..), amountModeOf, intervalPeriodExpr, parseListMode, parseValue, reportLinks, setAmountMode) import Hledger.Web.Settings (Extra(..), webmanualurl, widgetFile) import Hledger.Web.Settings.StaticFiles import Hledger.Web.WebOptions @@ -235,8 +235,8 @@ instance Yesod App where -- The accumulation mode is kept only when it is not the default, as -- the pages' own links carry it. let keepable :: Text -> Text -> Bool - keepable "accum" v = v `elem` keptAccums here - keepable _ v = not (T.null v) + keepable k v | k == paramName accumParam = v `elem` keptAccums here + | otherwise = not (T.null v) keptParams <- fmap catMaybes . for (keptParamNames here) $ \name -> fmap (name,) . mfilter (keepable name) <$> lookupGetParam name @@ -589,7 +589,7 @@ reportRoutes = [rmRoute i | i <- reportMenu, isJust (rmAccum i)] keptAccums :: Route App -> [Text] keptAccums route = case [dflt | i <- reportMenu, rmRoute i == route, Just dflt <- [rmAccum i]] of - [dflt] -> [accumWord a | a <- [PerPeriod, Historical, Cumulative], a /= dflt] + [dflt] -> [paramWord accumParam a | a <- paramModes accumParam, a /= dflt] _ | route == RegisterR -> ["historical"] _ -> [] @@ -602,8 +602,8 @@ keptAccums route = keptParamNames :: Route App -> [Text] keptParamNames route | route == HoldingsR = "closed" : stickyParamNames - | route `elem` reportRoutes = "accum" : stickyParamNames - | route == RegisterR = "account" : "subs" : "accum" : "costs" : stickyParamNames + | route `elem` reportRoutes = paramName accumParam : stickyParamNames + | route == RegisterR = "account" : "subs" : paramName accumParam : "costs" : stickyParamNames | route == JournalR = stickyParamNames | otherwise = [] diff --git a/hledger-web/Hledger/Web/Handler/BalanceR.hs b/hledger-web/Hledger/Web/Handler/BalanceR.hs index 15de60a33d8..b6cc9b92688 100644 --- a/hledger-web/Hledger/Web/Handler/BalanceR.hs +++ b/hledger-web/Hledger/Web/Handler/BalanceR.hs @@ -18,7 +18,7 @@ import Hledger.Utils.I18n (tr, trc, trf) import Hledger.Web.Import import Hledger.Web.Widget.AddForm (addModal) import Hledger.Web.Paging (yearsRow) -import Hledger.Web.Param (calcParam, paramLinks, paramSettings) +import Hledger.Web.Param (Param(..), accumParam, calcParam, paramLinks, paramSettings) import Hledger.Web.ReportPage import Hledger.Web.WebOptions import Hledger.Web.Widget.Chart (reportChart) @@ -82,7 +82,7 @@ getBalanceR = do -- What links staying on this page keep: the period as given, and each -- report-shaping parameter that is not at its default. intervalParams = [("interval", w) | Just w <- [intervalPeriodExpr rpInterval]] - accumParams = [("accum", accumWord accum) | accum /= PerPeriod] + accumParams = paramSettings accumParam PerPeriod accum valParams = valueParams roptsOrig rpValue listParams = [("list", listWord (accountlistmode_ ropts)) | accountlistmode_ ropts /= accountlistmode_ roptsOrig] totalParams = [("total", "1") | row_total_ ropts] @@ -107,7 +107,7 @@ getBalanceR = do -- search's dates. registerParams = [("value", "none") | amountModeOf ropts == Just AsRecorded, amountModeOf roptsOrig /= Just AsRecorded] ++ - removeAttributes ["accum", "value"] pageParams + removeAttributes [paramName accumParam, "value"] pageParams -- TRANSLATORS: the name of a depth 0 report's one row, all accounts in one. relink = map (map (labelAllAccounts (trc trs "accounts" "All") . addLinkParams registerParams)) headinglink = urlrender BalanceR . headingParams rpInterval qparam params @@ -142,7 +142,7 @@ getBalanceR = do entriesReport rspecOrig{_rsQuery = filterQuery (\x -> not (queryIsDateOrDate2 x || queryIsDepth x)) q} j yearsNav = yearsRow trs BalanceR qparam today pageParams yearsDays controlRows = controlsToggle trs controlsOpen (optionsSummary trs deepest pageParams) $ \render -> foldMap ($ render) $ - [ accumulationLinks trs BalanceR (qParams ++ removeAttributes ["accum"] pageParams) PerPeriod accum + [ paramLinks accumParam trs BalanceR (qParams ++ pageParams) PerPeriod accum , intervalLinks trs BalanceR (removeAttributes ["interval"] pageParams) qparam rpInterval , yearsNav , statusLinks trs BalanceR pageParams qparam diff --git a/hledger-web/Hledger/Web/Handler/RegisterR.hs b/hledger-web/Hledger/Web/Handler/RegisterR.hs index abef9369b90..bf70e31a9d4 100644 --- a/hledger-web/Hledger/Web/Handler/RegisterR.hs +++ b/hledger-web/Hledger/Web/Handler/RegisterR.hs @@ -27,7 +27,7 @@ import Hledger.Write.Chart.Svg (SvgOptions(..), chartSvgMarkupWith, defaultSvgOp import Hledger.Web.Import import Hledger.Web.Paging import Hledger.Web.Widget.Chart (chartLegend, chartWidth) -import Hledger.Web.Param (calcParam, lookupParam, paramLinks, paramSettings) +import Hledger.Web.Param (Param(..), accumParam, calcParam, lookupParam, paramLinks, paramSetting, paramSettings) import Hledger.Web.ReportPage (amountModeOf, deepestDepth, depthParams, removeAttributes, intervalLinks, listWord, parseInterval, parseListMode, parseValue, setAmountMode, valueParams) import Hledger.Web.WebOptions import Hledger.Web.Widget.AddForm (addModal) @@ -49,7 +49,7 @@ getRegisterR = do -- starting from before the query's start date, rather than a total of -- the transactions shown; a report's ending balance links here that way, -- so that the balance ends on the figure clicked. - historical <- (== Just "historical") <$> lookupGetParam "accum" + historical <- (== Just Historical) <$> lookupParam accumParam -- With a value parameter amounts are converted as a report page's -- figures were (see Hledger.Web.ReportPage.parseValue), so that its -- figures' registers end on them. One it does not know is ignored. @@ -89,7 +89,7 @@ getRegisterR = do rspec = rspec0{_rsReportOpts = ropts} -- links staying on this register keep its modes valParams = valueParams (_rsReportOpts rspec0) mmode - accumParams = [("accum", "historical") | historical] + accumParams = [paramSetting accumParam Historical | historical] costsParams = [("costs", "1") | costsOn] inferParams = [("infer", "1") | inferOn] date2Params = [("date2", "1") | date2On] @@ -114,7 +114,7 @@ getRegisterR = do acctParams ++ stickyParams ++ accumParams ++ valParams ++ costsParams ++ inferParams ++ date2Params ++ emptyParams ++ listParams ++ lotsParams ++ depthParams q -- Links to the journal carry the sticky state; the account, the -- accumulation mode and the costs toggle are this page's own. - journalCarry = removeAttributes ["account", "subs", "accum", "costs"] modeParams + journalCarry = removeAttributes ["account", "subs", paramName accumParam, "costs"] modeParams -- An entry's date link: the journal on that date, same modes. dayParams t = ("q", journalDayQuery qparam (tdate t)) : journalCarry -- the rows of links above the chart: the filters (status, @@ -217,7 +217,7 @@ getRegisterR = do | otherwise = trc trs "column heading" "Total" -- The balance column's heading switches the mode, keeping the -- register's other modes. - accumToggle = (RegisterR, qParams qparam ++ removeAttributes ["accum"] modeParams ++ [("accum", "historical") | not historical]) + accumToggle = (RegisterR, qParams qparam ++ removeAttributes [paramName accumParam] modeParams ++ [paramSetting accumParam Historical | not historical]) accumToggleTitle | historical = tr trs "Click to show the running balance from the start of this period" | otherwise = tr trs "Click to show the running balance including everything before this period" @@ -231,7 +231,7 @@ getRegisterR = do broughtForwardLink (secondary, start) = (RegisterR, [("q", T.unwords $ ((if secondary then "date2:.." else "date:..") <> showDate start) : removeDates qparam)] ++ - removeAttributes ["accum"] modeParams) + removeAttributes [paramName accumParam] modeParams) transactionFrag = transactionFragment j defaultLayout $ do -- TRANSLATORS: the browser tab title of this page. diff --git a/hledger-web/Hledger/Web/Handler/StatementsR.hs b/hledger-web/Hledger/Web/Handler/StatementsR.hs index e0e11b26c2d..16cca6e2425 100644 --- a/hledger-web/Hledger/Web/Handler/StatementsR.hs +++ b/hledger-web/Hledger/Web/Handler/StatementsR.hs @@ -33,7 +33,7 @@ import Hledger.Write.Spreadsheet qualified as Spr import Hledger.Web.Import import Hledger.Web.Widget.AddForm (addModal) import Hledger.Web.Paging (yearsRow) -import Hledger.Web.Param (calcParam, paramLinks, paramSettings) +import Hledger.Web.Param (Param(..), accumParam, calcParam, paramLinks, paramSettings) import Hledger.Web.ReportPage import Hledger.Web.WebOptions import Hledger.Web.Widget.Chart (reportChart) @@ -121,7 +121,7 @@ statementPage here tabtitle spec mequity = do -- accumulation mode when it is not the report's own, and each -- report-shaping parameter that is not at its default. intervalParams = [("interval", w) | Just w <- [intervalPeriodExpr rpInterval]] - accumParams = [("accum", accumWord accum) | accum /= cbcaccum spec] + accumParams = paramSettings accumParam (cbcaccum spec) accum valParams = valueParams roptsOrig rpValue listParams = [("list", listWord (accountlistmode_ ropts)) | accountlistmode_ ropts /= accountlistmode_ roptsOrig] totalParams = [("total", "1") | row_total_ ropts] @@ -145,7 +145,7 @@ statementPage here tabtitle spec mequity = do -- default, the startup options', converts them. registerParams = [("value", "none") | amountModeOf ropts == Just AsRecorded, amountModeOf roptsOrig /= Just AsRecorded] ++ - removeAttributes ["accum", "value", "equity"] pageParams + removeAttributes [paramName accumParam, "value", "equity"] pageParams -- TRANSLATORS: the name of a depth 0 report's one row, all accounts in one. relink = map (map (labelAllAccounts (trc trs "accounts" "All") . addLinkParams registerParams)) headinglink = urlrender here . headingParams rpInterval qparam params @@ -187,7 +187,7 @@ statementPage here tabtitle spec mequity = do yearsNav = yearsRow trs here qparam today pageParams yearsDays controlRows = controlsToggle trs controlsOpen (optionsSummary trs deepest pageParams) $ \render -> foldMap ($ render) $ [ equityLinks trs here (qParams ++ removeAttributes ["equity"] pageParams) shown | Just shown <- [mequity] ] ++ - [ accumulationLinks trs here (qParams ++ removeAttributes ["accum"] pageParams) (cbcaccum spec) accum + [ paramLinks accumParam trs here (qParams ++ pageParams) (cbcaccum spec) accum , intervalLinks trs here (removeAttributes ["interval"] pageParams) qparam rpInterval , yearsNav , statusLinks trs here pageParams qparam diff --git a/hledger-web/Hledger/Web/Param.hs b/hledger-web/Hledger/Web/Param.hs index 2af4a67d160..0e39dc00be8 100644 --- a/hledger-web/Hledger/Web/Param.hs +++ b/hledger-web/Hledger/Web/Param.hs @@ -19,6 +19,7 @@ module Hledger.Web.Param , paramSettings , paramLinks , paramPhrase + , accumParam , calcParam ) where @@ -120,6 +121,25 @@ paramLinks p trs route kept dflt current = paramPhrase :: Param a -> Translations -> Text -> Maybe Text paramPhrase p trs w = fst . paramLabel p trs <$> find ((== w) . paramWord p) (paramModes p) +-- | The accum parameter: whether a report shows balance changes, ending +-- balances, or cumulative totals; absent for the page's own default. +-- The H key toggles Ending balances, the second link (hledger.js). +accumParam :: Param BalanceAccumulation +accumParam = Param + { paramName = "accum" + , paramModes = [PerPeriod, Historical, Cumulative] + , paramWord = \case + PerPeriod -> "change" + Historical -> "historical" + Cumulative -> "cumulative" + -- TRANSLATORS: the label before a report's accumulation mode links, and the links' text and tooltips. + , paramRowLabel = \trs -> tr trs "Show:" + , paramLabel = \trs -> \case + PerPeriod -> (tr trs "Balance changes", tr trs "Show how much each balance changed in each period") + Historical -> (tr trs "Ending balances", tr trs "Show each balance at the end of each period, including everything before it") + Cumulative -> (tr trs "Cumulative totals", tr trs "Show each balance's change since the start of the report (--cumulative)") + } + -- | The calc parameter: what a report's cells calculate, as the balance -- commands' --valuechange, --gain, and --count flags choose. calcParam :: Param BalanceCalculation diff --git a/hledger-web/Hledger/Web/ReportPage.hs b/hledger-web/Hledger/Web/ReportPage.hs index 8adea864bd7..b4e56328e12 100644 --- a/hledger-web/Hledger/Web/ReportPage.hs +++ b/hledger-web/Hledger/Web/ReportPage.hs @@ -32,14 +32,12 @@ module Hledger.Web.ReportPage ( deepestDepth, parseInterval, depthParams, - accumWord, columnHeading, headingParams, removeAttributes, relinkDateHeaders, reportLinks, intervalLinks, - accumulationLinks, reportTable, chartReportSpec, splitAccountNames, @@ -66,8 +64,8 @@ import Yesod (HtmlUrl) import Hledger.Utils.I18n (Translations, tr, trc, trf) import Hledger import Hledger.Cli.Anchor (dateTerm, renderPeriodHeading) -import Hledger.Web.Param (Param(..), calcParam, linksRowClass, paramSettings, parseParam) -import Hledger.Web.Widget.Common (AmountMode(..), accumWord, listWord, removeDates, valueWord) +import Hledger.Web.Param (Param(..), accumParam, calcParam, linksRowClass, paramSettings, parseParam) +import Hledger.Web.Widget.Common (AmountMode(..), listWord, removeDates, valueWord) import Hledger.Query qualified as Query import Hledger.Write.Html (Html, formatCell, nl) import Hledger.Write.Spreadsheet (Cell(..), Class(..), NumLines, textFromClass) @@ -92,7 +90,7 @@ data ReportParams = ReportParams { -- | A parameter the page cannot use, with what was given; or a -- combination of parameters that contradict each other. data ReportParamError - = BadInterval String | BadAccum Text | BadValue Text | BadParamValue Text Text + = BadInterval String | BadValue Text | BadParamValue Text Text | ValuechangeNeedsEnd | GainNotCost | ValueThenUnsupported -- | Resolve a report page's parameters: the startup report spec, the search parameter and its parsed query and options, whether @@ -112,7 +110,7 @@ reportParams rspecOrig qparam q qopts hideEmpty params = do ivl <- case mfilter (not . T.null) (param "interval") of Nothing -> Right (interval_ roptsOrig) Just t -> either (Left . BadInterval . errorBundlePretty) Right $ parseInterval t - rpAccum <- parseAccum (param "accum") + rpAccum <- readParam accumParam (param $ paramName accumParam) rpValue <- parseValue (param "value") mlist <- parseListMode (param "list") total <- parseFlag "total" (param "total") @@ -194,7 +192,7 @@ startupUrlState rspec@ReportSpec{_rsReportOpts = ropts} = (params, rspec') params = [("interval", p) | Just p <- [intervalPeriodExpr $ interval_ ropts]] ++ [("depth", T.pack (show n)) | Just n <- [dsFlatDepth $ depth_ ropts]] ++ - [("accum", accumWord a) | let a = balanceaccum_ ropts, a /= PerPeriod] ++ + paramSettings accumParam PerPeriod (balanceaccum_ ropts) ++ [("value", valueWord m) | Just m <- [amountModeOf ropts], m /= AsRecorded] ++ [("list", "tree") | accountlistmode_ ropts == ALTree] ++ [("total", "1") | row_total_ ropts] ++ @@ -310,36 +308,6 @@ intervalLinks trs route kept qparam current = link mword = (route, [("q", qparam) | not (T.null qparam)] ++ kept ++ [("interval", w) | Just w <- [mword]]) --- | Links to the same report page for each accumulation mode: balance --- changes, ending balances, or cumulative totals. They keep the given --- parameters; the page's own default mode needs none. The mode being --- shown is marked. -accumulationLinks :: Translations -> r -> [(Text, Text)] -> BalanceAccumulation -> BalanceAccumulation -> HtmlUrl r -accumulationLinks trs route kept dflt current = - -- The H key toggles Ending balances, the second link (hledger.js). - -- TRANSLATORS: the label before a report's accumulation mode links, and the links' text and tooltips. - linksRowClass "accum" (tr trs "Show:") - [ (tr trs "Balance changes", tr trs "Show how much each balance changed in each period", - link PerPeriod, current == PerPeriod) - , (tr trs "Ending balances", tr trs "Show each balance at the end of each period, including everything before it", - link Historical, current == Historical) - , (tr trs "Cumulative totals", tr trs "Show each balance's change since the start of the report (--cumulative)", - link Cumulative, current == Cumulative) - ] - where link m = (route, kept ++ [("accum", accumWord m) | m /= dflt]) - --- | The accum parameter: "historical" for ending balances, "change" for --- balance changes, "cumulative" for totals since the report's start, or --- none for the page's default. -parseAccum :: Maybe Text -> Either ReportParamError (Maybe BalanceAccumulation) -parseAccum = \case - Nothing -> Right Nothing - Just "" -> Right Nothing - Just "historical" -> Right $ Just Historical - Just "change" -> Right $ Just PerPeriod - Just "cumulative" -> Right $ Just Cumulative - Just other -> Left $ BadAccum other - -- | The list parameter: show accounts as a "tree" or a "flat" list. parseListMode :: Maybe Text -> Either ReportParamError (Maybe AccountListMode) parseListMode = \case @@ -465,10 +433,6 @@ paramError trs = \case H.div ! A.class_ "alert alert-danger" $ do H.toHtml $ tr trs "Could not parse the reporting interval:" H.pre $ H.toHtml err - BadAccum v -> - H.div ! A.class_ "alert alert-danger" $ do - H.toHtml $ tr trs "Unknown balance accumulation mode:" - H.pre $ H.toHtml v BadValue v -> H.div ! A.class_ "alert alert-danger" $ do H.toHtml $ tr trs "Unknown amount conversion:" diff --git a/hledger-web/Hledger/Web/Test.hs b/hledger-web/Hledger/Web/Test.hs index 5ca7803491e..943b5487c42 100644 --- a/hledger-web/Hledger/Web/Test.hs +++ b/hledger-web/Hledger/Web/Test.hs @@ -65,7 +65,7 @@ import Web.Cookie (defaultSetCookie, setCookieName, setCookieValue) import Hledger.Web.Application ( makeAppWith ) import Hledger.Utils.I18n (noTranslations) import Hledger.Web.Paging (pageNumbers) -import Hledger.Web.Param (Param(..), calcParam, parseParam) +import Hledger.Web.Param (Param(..), accumParam, calcParam, parseParam) import Hledger.Web.ReportPage (intervalPeriodExpr, startupUrlState) import Hledger.Web.WebOptions -- ( WebOpts(..), defwebopts, prognameandversion ) import Hledger.Web.Import hiding (get, j) @@ -277,6 +277,7 @@ hledgerWebTest = do hspec $ describe "Param" $ do it "gives each mode its own word" $ do let distinctWords p = let ws = map (paramWord p) (paramModes p) in length (nub ws) == length ws + distinctWords accumParam `shouldBe` True distinctWords calcParam `shouldBe` True it "reads a mode's word, an empty or absent value as the default, and returns an unknown word" $ do parseParam calcParam (Just "gain") `shouldBe` Right (Just CalcGain) @@ -1284,7 +1285,7 @@ hledgerWebTest = do setUrl BalanceR addGetParam "accum" "bogus" statusIs 200 - bodyContains "Unknown balance accumulation mode" + bodyContains "The accum parameter has a value this page does not know" bodyNotContains "" yit "keeps the accumulation mode off the journal page's search form" $ do @@ -1654,7 +1655,7 @@ hledgerWebTest = do addGetParam "accum" "bogus" statusIs 200 bodyContains "

Balance Sheet

" - bodyContains "Unknown balance accumulation mode" + bodyContains "The accum parameter has a value this page does not know" bodyNotContains "" yit "serves the income statement, with changes, revenues shown positive" $ do diff --git a/hledger-web/Hledger/Web/Widget/Common.hs b/hledger-web/Hledger/Web/Widget/Common.hs index 13a0df3aab4..4eb69b306aa 100644 --- a/hledger-web/Hledger/Web/Widget/Common.hs +++ b/hledger-web/Hledger/Web/Widget/Common.hs @@ -31,7 +31,6 @@ module Hledger.Web.Widget.Common , holdingsValueLinks , typeLinks , AmountMode(..) - , accumWord , listWord , valueWord , searchTerms @@ -78,7 +77,7 @@ import Hledger.Utils.I18n (Translations, tr, trc, trf) import Hledger import Hledger.Cli.Anchor qualified as Anchor import Hledger.Cli.Utils (writeFileWithBackupIfChanged) -import Hledger.Web.Param (calcParam, linksRow, linksRowClass, paramName, paramPhrase) +import Hledger.Web.Param (accumParam, calcParam, linksRow, linksRowClass, paramName, paramPhrase) import Hledger.Web.Settings (manualurl) import Hledger.Query qualified as Query @@ -190,7 +189,7 @@ optionsSummary :: Translations -> Int -> [(Text, Text)] -> [Text] optionsSummary trs deepest = mapMaybe phrase . sortOn (rowOrder . fst) where rowOrder k = fromMaybe maxBound $ elemIndex k - ["equity", "interval", "accum", "depth", "list", "value", "infer", "empty", "lots", "closed", + ["equity", "interval", paramName accumParam, "depth", "list", "value", "infer", "empty", "lots", "closed", "total", "avg", "costs", "sort", "pct", paramName calcParam, "date2"] phrase = \case ("interval", w) -> Just $ fromMaybe w $ lookup w @@ -201,9 +200,7 @@ optionsSummary trs deepest = mapMaybe phrase . sortOn (rowOrder . fst) d <- readMay (T.unpack n) :: Maybe Int guard (d < deepest) Just $ trf trs "Depth {depth}" [("depth", n)] - ("accum", a) -> lookup a - [ ("change", tr trs "Balance changes"), ("historical", tr trs "Ending balances") - , ("cumulative", tr trs "Cumulative totals") ] + (k, w) | k == paramName accumParam -> paramPhrase accumParam trs w ("value", "none") -> Just $ tr trs "As recorded" ("value", "cost") -> Just $ trc trs "amounts" "Cost" ("value", _) -> Just $ trc trs "amounts" "Value" @@ -269,13 +266,6 @@ pricesLinks trs route kept inferOn = , (tr trs "Inferred too", tr trs "Infer market prices from transaction costs too (--infer-market-prices)", (route, kept ++ [("infer", "1")]), inferOn) ] --- | The accum parameter value naming an accumulation mode. -accumWord :: BalanceAccumulation -> Text -accumWord = \case - PerPeriod -> "change" - Historical -> "historical" - Cumulative -> "cumulative" - -- | The list parameter value naming an accounts mode. listWord :: AccountListMode -> Text listWord ALTree = "tree" From 4cd22cbbd4d6a12bcb087f2ac2b68de4d8401151 Mon Sep 17 00:00:00 2001 From: Simon Michael Date: Thu, 12 Nov 2026 21:44:24 -1000 Subject: [PATCH 3/4] dev: web: list and sort use Param listParam and sortParam replace parseListMode, parseSort, listWord, listModeLinks and sortLinks, the journal and register pages' own checks of the sort parameter, and the list and sort literals in the handlers, App.hs's kept parameters, startupUrlState and the options summary. sort, a yes/no choice, is a Param Bool. The accounts list/tree row's class is now its parameter's name, list, and hledger.js's t key finds it by that. AI usage: Claude Opus 5.5, ~9k output tokens --- hledger-lib/locale/hledger.pot | 23 +++++----- hledger-web/Hledger/Web/App.hs | 8 ++-- hledger-web/Hledger/Web/Handler/BalanceR.hs | 14 +++--- hledger-web/Hledger/Web/Handler/HoldingsR.hs | 15 ++++--- hledger-web/Hledger/Web/Handler/JournalR.hs | 20 ++++----- hledger-web/Hledger/Web/Handler/RegisterR.hs | 20 ++++----- .../Hledger/Web/Handler/StatementsR.hs | 14 +++--- hledger-web/Hledger/Web/Param.hs | 36 +++++++++++++++ hledger-web/Hledger/Web/ReportPage.hs | 33 +++----------- hledger-web/Hledger/Web/Test.hs | 4 +- hledger-web/Hledger/Web/Widget/Common.hs | 45 +++---------------- hledger-web/static/hledger.js | 2 +- 12 files changed, 108 insertions(+), 126 deletions(-) diff --git a/hledger-lib/locale/hledger.pot b/hledger-lib/locale/hledger.pot index 34956c7e835..33e27c37eeb 100644 --- a/hledger-lib/locale/hledger.pot +++ b/hledger-lib/locale/hledger.pot @@ -1527,30 +1527,28 @@ msgid "Show only virtual postings, the parenthesized ones (real:0)" msgstr "" #. the label before a report's list/tree links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Widget/Common.hs hledger-web/templates/default-layout.hamlet +#: hledger-web/Hledger/Web/Param.hs hledger-web/templates/default-layout.hamlet msgid "Accounts:" msgstr "" #. the label before a report's list/tree links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Widget/Common.hs +#: hledger-web/Hledger/Web/Param.hs msgid "Show accounts as a flat list (--flat)" msgstr "" -#. the depth limit, in the list of options in effect. #. the label before a report's list/tree links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Widget/Common.hs +#: hledger-web/Hledger/Web/Param.hs msgctxt "accounts" msgid "List" msgstr "" #. the label before a report's list/tree links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Widget/Common.hs +#: hledger-web/Hledger/Web/Param.hs msgid "Show accounts as a tree (--tree)" msgstr "" -#. the depth limit, in the list of options in effect. #. the label before a report's list/tree links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Widget/Common.hs +#: hledger-web/Hledger/Web/Param.hs msgctxt "accounts" msgid "Tree" msgstr "" @@ -1585,28 +1583,27 @@ msgid "Average" msgstr "" #. the label before a report's sort links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Widget/Common.hs hledger-web/templates/default-layout.hamlet +#: hledger-web/Hledger/Web/Param.hs hledger-web/templates/default-layout.hamlet msgid "Sort:" msgstr "" #. the label before a report's sort links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Widget/Common.hs +#: hledger-web/Hledger/Web/Param.hs msgid "By account" msgstr "" #. the label before a report's sort links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Widget/Common.hs +#: hledger-web/Hledger/Web/Param.hs msgid "Sort rows by account display order" msgstr "" -#. the depth limit, in the list of options in effect. #. the label before a report's sort links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Widget/Common.hs +#: hledger-web/Hledger/Web/Param.hs msgid "By amount" msgstr "" #. the label before a report's sort links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Widget/Common.hs +#: hledger-web/Hledger/Web/Param.hs msgid "Sort rows by their amounts, largest first (-S)" msgstr "" diff --git a/hledger-web/Hledger/Web/App.hs b/hledger-web/Hledger/Web/App.hs index a5a5b69a170..b7872cecbfa 100644 --- a/hledger-web/Hledger/Web/App.hs +++ b/hledger-web/Hledger/Web/App.hs @@ -60,8 +60,8 @@ import Hledger.Cli.Commands.Balancesheet (balancesheetSpec) import Hledger.Cli.Commands.Cashflow (cashflowSpec) import Hledger.Cli.Commands.Incomestatement (incomestatementSpec) import Hledger.Cli.CompoundBalanceCommand (CompoundBalanceCommandSpec(..)) -import Hledger.Web.Param (Param(..), accumParam, calcParam, lookupParam) -import Hledger.Web.ReportPage (AmountMode(..), amountModeOf, intervalPeriodExpr, parseListMode, parseValue, reportLinks, setAmountMode) +import Hledger.Web.Param (Param(..), accumParam, calcParam, listParam, lookupParam, sortParam) +import Hledger.Web.ReportPage (AmountMode(..), amountModeOf, intervalPeriodExpr, parseValue, reportLinks, setAmountMode) import Hledger.Web.Settings (Extra(..), webmanualurl, widgetFile) import Hledger.Web.Settings.StaticFiles import Hledger.Web.WebOptions @@ -202,7 +202,7 @@ instance Yesod App where -- value parameter asks, with inferred market prices if asked. mvalmode <- either (const Nothing) id . parseValue <$> lookupGetParam "value" inferparam <- (== Just "1") <$> lookupGetParam "infer" - mlistmode <- either (const Nothing) id . parseListMode <$> lookupGetParam "list" + mlistmode <- lookupParam listParam let rspec = reportspec_ (cliopts_ opts) -- In the page's tree mode the sidebar gets fold carets (the -- inline script in default-layout.hamlet); its shape never changes. @@ -611,7 +611,7 @@ keptParamNames route -- only the control it names. date2 has no control, being deprecated, -- but is preserved like the rest. stickyParamNames :: [Text] -stickyParamNames = ["interval", "depth", "value", "list", "total", "avg", "sort", "pct", paramName calcParam, "infer", "date2", "empty", "lots"] +stickyParamNames = ["interval", "depth", "value", paramName listParam, "total", "avg", paramName sortParam, "pct", paramName calcParam, "infer", "date2", "empty", "lots"] -- | Are zero-balance accounts hidden ? The empty parameter says (1 -- shows them, 0 hides them, the direction of the command line's diff --git a/hledger-web/Hledger/Web/Handler/BalanceR.hs b/hledger-web/Hledger/Web/Handler/BalanceR.hs index b6cc9b92688..21b1e2e853f 100644 --- a/hledger-web/Hledger/Web/Handler/BalanceR.hs +++ b/hledger-web/Hledger/Web/Handler/BalanceR.hs @@ -18,14 +18,14 @@ import Hledger.Utils.I18n (tr, trc, trf) import Hledger.Web.Import import Hledger.Web.Widget.AddForm (addModal) import Hledger.Web.Paging (yearsRow) -import Hledger.Web.Param (Param(..), accumParam, calcParam, paramLinks, paramSettings) +import Hledger.Web.Param (Param(..), accumParam, calcParam, listParam, paramLinks, paramSettings, sortParam) import Hledger.Web.ReportPage import Hledger.Web.WebOptions import Hledger.Web.Widget.Chart (reportChart) import Hledger.Web.Widget.Common (amountLinks, columnsLinks, commodityLinks, controlsHint, controlsToggle, optionsSummary, - depthLinks, listModeLinks, lotsLinks, - percentLinks, pricesLinks, realLinks, sortLinks, + depthLinks, lotsLinks, + percentLinks, pricesLinks, realLinks, statusLinks, typeLinks, zeroBalanceLinks) @@ -84,10 +84,10 @@ getBalanceR = do intervalParams = [("interval", w) | Just w <- [intervalPeriodExpr rpInterval]] accumParams = paramSettings accumParam PerPeriod accum valParams = valueParams roptsOrig rpValue - listParams = [("list", listWord (accountlistmode_ ropts)) | accountlistmode_ ropts /= accountlistmode_ roptsOrig] + listParams = paramSettings listParam (accountlistmode_ roptsOrig) (accountlistmode_ ropts) totalParams = [("total", "1") | row_total_ ropts] avgParams = [("avg", "1") | average_ ropts] - sortParams = [("sort", "amount") | sort_amount_ ropts] + sortParams = paramSettings sortParam False (sort_amount_ ropts) pctParams = [("pct", "1") | percent_ ropts] calcParams = paramSettings calcParam CalcChange (balancecalc_ ropts) inferParams = [("infer", "1") | infer_prices_ ropts, not (infer_prices_ roptsOrig)] @@ -154,14 +154,14 @@ getBalanceR = do -- TRANSLATORS: the hint below the commodity filter row. (tr trs "Shift-click selects several commodities.") j ] ++ [ depthLinks trs BalanceR pageParams qparam deepest | deepest > 1 ] ++ - [ listModeLinks trs BalanceR (qParams ++ removeAttributes ["list"] pageParams) (accountlistmode_ roptsOrig) (accountlistmode_ ropts) + [ paramLinks listParam trs BalanceR (qParams ++ pageParams) (accountlistmode_ roptsOrig) (accountlistmode_ ropts) , amountLinks trs BalanceR (qParams ++ removeAttributes ["value"] pageParams) (amountModeOf roptsOrig) (amountModeOf ropts) , pricesLinks trs BalanceR (qParams ++ removeAttributes ["infer"] pageParams) (infer_prices_ ropts) , zeroBalanceLinks trs BalanceR (qParams ++ removeAttributes ["empty"] pageParams) (empty_ roptsOrig) hideEmpty ] ++ [ lotsLinks trs BalanceR (qParams ++ removeAttributes ["lots"] pageParams) lotsShown | jHasLots ] ++ [ columnsLinks trs BalanceR (qParams ++ removeAttributes ["total", "avg"] pageParams) (row_total_ ropts) (average_ ropts) | rpInterval /= NoInterval ] ++ - [ sortLinks trs BalanceR (qParams ++ removeAttributes ["sort"] pageParams) (sort_amount_ ropts) + [ paramLinks sortParam trs BalanceR (qParams ++ pageParams) False (sort_amount_ ropts) , percentLinks trs BalanceR (qParams ++ removeAttributes ["pct"] pageParams) (percent_ ropts) , paramLinks calcParam trs BalanceR (qParams ++ pageParams) CalcChange (balancecalc_ ropts) ] Yesod.toWidget controlRows diff --git a/hledger-web/Hledger/Web/Handler/HoldingsR.hs b/hledger-web/Hledger/Web/Handler/HoldingsR.hs index 138e7453b9a..d3939a85355 100644 --- a/hledger-web/Hledger/Web/Handler/HoldingsR.hs +++ b/hledger-web/Hledger/Web/Handler/HoldingsR.hs @@ -21,14 +21,15 @@ import Hledger.Web.Import import Hledger.Web.Widget.AddForm (addModal) import Hledger.Web.Handler.BalanceR (reportTitle) import Hledger.Web.Paging (yearsRow) +import Hledger.Web.Param (Param(..), listParam, paramLinks, paramSettings, sortParam) import Hledger.Web.ReportPage import Hledger.Web.WebOptions import Hledger.Web.Widget.Chart (reportChart) import Hledger.Web.Widget.Common (accountParams, closedLinks, commodityLinks, controlsToggle, optionsSummary, - depthLinks, holdingsValueLinks, listModeLinks, + depthLinks, holdingsValueLinks, lotsLinks, pricesLinks, realLinks, searchTerms, - sortLinks, statusLinks, zeroBalanceLinks) + statusLinks, zeroBalanceLinks) -- | The holdings view: investment holdings and their performance at the -- report end date, as the holdings command shows them. In tree mode the @@ -94,8 +95,8 @@ getHoldingsR = do -- this page does not use but passes along. intervalParams = [("interval", w) | Just w <- [intervalPeriodExpr rpInterval]] valParams = valueParams roptsOrig rpValue - listParams = [("list", listWord (accountlistmode_ ropts)) | accountlistmode_ ropts /= accountlistmode_ roptsOrig] - sortParams = [("sort", "amount") | sort_amount_ ropts] + listParams = paramSettings listParam (accountlistmode_ roptsOrig) (accountlistmode_ ropts) + sortParams = paramSettings sortParam False (sort_amount_ ropts) inferParams = [("infer", "1") | infer_prices_ ropts, not (infer_prices_ roptsOrig)] closedParams = [("closed", if closedShown then "1" else "0") | closedShown /= empty_ roptsOrig] emptyParams = [("empty", if hideEmpty then "0" else "1") | hideEmpty /= empty_ roptsOrig] @@ -107,7 +108,7 @@ getHoldingsR = do qParams = [("q", qparam) | not (T.null qparam)] -- An account cell links to the account's register, keeping -- the states that page reads. - registerKept = removeAttributes ["interval", "sort", "closed"] pageParams + registerKept = removeAttributes ["interval", paramName sortParam, "closed"] pageParams acctlink acct = urlrender RegisterR $ qParams ++ accountParams True acct ++ registerKept -- A position's cell links to that register filtered to the @@ -285,13 +286,13 @@ getHoldingsR = do -- TRANSLATORS: the hint below the commodity filter row. (tr trs "Shift-click selects several commodities.") jfull ] ++ [ depthLinks trs HoldingsR pageParams qparam deepest | deepest > 1 ] ++ - [ listModeLinks trs HoldingsR (qParams ++ removeAttributes ["list"] pageParams) (accountlistmode_ roptsOrig) (accountlistmode_ ropts) + [ paramLinks listParam trs HoldingsR (qParams ++ pageParams) (accountlistmode_ roptsOrig) (accountlistmode_ ropts) , holdingsValueLinks trs HoldingsR (qParams ++ removeAttributes ["value"] pageParams) (isJust $ value_ ropts) , pricesLinks trs HoldingsR (qParams ++ removeAttributes ["infer"] pageParams) (infer_prices_ ropts) , zeroBalanceLinks trs HoldingsR (qParams ++ removeAttributes ["empty"] pageParams) (empty_ roptsOrig) hideEmpty , lotsLinks trs HoldingsR (qParams ++ removeAttributes ["lots"] pageParams) lotsShown , closedLinks trs HoldingsR (qParams ++ removeAttributes ["closed"] pageParams) (not $ empty_ roptsOrig) (not closedShown) - , sortLinks trs HoldingsR (qParams ++ removeAttributes ["sort"] pageParams) (sort_amount_ ropts) ] + , paramLinks sortParam trs HoldingsR (qParams ++ pageParams) False (sort_amount_ ropts) ] Yesod.toWidget controlRows Yesod.toWidget $ H.h2 $ H.toHtml $ withFilter title -- the chart, as holdings --chart draws it: a bar per holding, or per lot diff --git a/hledger-web/Hledger/Web/Handler/JournalR.hs b/hledger-web/Hledger/Web/Handler/JournalR.hs index 01f769a9cb7..b08a5b50ae1 100644 --- a/hledger-web/Hledger/Web/Handler/JournalR.hs +++ b/hledger-web/Hledger/Web/Handler/JournalR.hs @@ -15,13 +15,13 @@ import Hledger.Web.Import import Hledger.Web.Paging import Hledger.Web.WebOptions import Hledger.Web.Widget.AddForm (addModal) -import Hledger.Web.Param (calcParam, lookupParam, paramLinks, paramSettings) -import Hledger.Web.ReportPage (amountModeOf, deepestDepth, depthParams, intervalLinks, listWord, parseInterval, parseListMode, parseValue, removeAttributes, setAmountMode, valueParams) +import Hledger.Web.Param (calcParam, listParam, lookupParam, paramLinks, paramSettings, sortParam) +import Hledger.Web.ReportPage (amountModeOf, deepestDepth, depthParams, intervalLinks, parseInterval, parseValue, removeAttributes, setAmountMode, valueParams) import Hledger.Web.Widget.Common (accountParams, amountLinks, columnsLinks, commodityLinks, controlsHint, controlsToggle, optionsSummary, searchHeading, - depthLinks, inertControls, listModeLinks, lotsLinks, - mixedAmountAsHtml, percentLinks, pricesLinks, realLinks, sortLinks, + depthLinks, inertControls, lotsLinks, + mixedAmountAsHtml, percentLinks, pricesLinks, realLinks, statusLinks, typeLinks, transactionFragment, journalDayQuery, zeroBalanceLinks) @@ -32,12 +32,12 @@ getJournalR = do VD{perms, j, jHasLots, lotsShown, q, opts, qparam, account, today, trs, hideEmpty, controlsOpen, commoditiesOpen} <- getViewData require ViewPermission mmode <- either (const Nothing) id . parseValue <$> lookupGetParam "value" - mlist <- either (const Nothing) id . parseListMode <$> lookupGetParam "list" + mlist <- lookupParam listParam inferOn <- (== Just "1") <$> lookupGetParam "infer" minterval <- lookupGetParam "interval" totalOn <- (== Just "1") <$> lookupGetParam "total" avgOn <- (== Just "1") <$> lookupGetParam "avg" - sortAmt <- (== Just "amount") <$> lookupGetParam "sort" + sortAmt <- fromMaybe False <$> lookupParam sortParam pctOn <- (== Just "1") <$> lookupGetParam "pct" calcCur <- fromMaybe CalcChange <$> lookupParam calcParam date2On <- (== Just "1") <$> lookupGetParam "date2" @@ -69,7 +69,7 @@ getJournalR = do emptyParams = [("empty", if hideEmpty then "0" else "1") | hideEmpty /= dfltHidden] valParams = valueParams roptsStartup mmode elist = fromMaybe (accountlistmode_ roptsStartup) mlist - listParams = [("list", listWord elist) | elist /= accountlistmode_ roptsStartup] + listParams = paramSettings listParam (accountlistmode_ roptsStartup) elist inferParams = [("infer", "1") | inferOn] -- The report-shaping state shapes nothing here, but it is passed -- along and shown dimmed below, so the startup options' url @@ -79,7 +79,7 @@ getJournalR = do [("interval", w) | Just w <- [mfilter (not . T.null) minterval]] ++ [("total", "1") | totalOn] ++ [("avg", "1") | avgOn] ++ - [("sort", "amount") | sortAmt] ++ + paramSettings sortParam False sortAmt ++ [("pct", "1") | pctOn] ++ paramSettings calcParam CalcChange calcCur ++ [("date2", "1") | date2On] @@ -105,7 +105,7 @@ getJournalR = do depthRow = depthLinks trs JournalR carried qparam deepest -- The amounts mode converts the sidebar's amounts, and tree mode -- adds its fold carets; the journal's entries always show as written. - listRow = listModeLinks trs JournalR (qps ++ removeAttributes ["list"] carried) (accountlistmode_ roptsStartup) elist + listRow = paramLinks listParam trs JournalR (qps ++ carried) (accountlistmode_ roptsStartup) elist amountsRow = amountLinks trs JournalR (qps ++ removeAttributes ["value"] carried) (amountModeOf roptsStartup) (amountModeOf $ maybe id setAmountMode mmode roptsStartup) pricesRow = pricesLinks trs JournalR (qps ++ removeAttributes ["infer"] carried) inferOn @@ -124,7 +124,7 @@ getJournalR = do intervalLinks trs JournalR (removeAttributes ["interval"] carried) qparam rpInterval inertRows = inertControls trs $ mconcat [ columnsLinks trs JournalR (qps ++ removeAttributes ["total", "avg"] carried) totalOn avgOn - , sortLinks trs JournalR (qps ++ removeAttributes ["sort"] carried) sortAmt + , paramLinks sortParam trs JournalR (qps ++ carried) False sortAmt , percentLinks trs JournalR (qps ++ removeAttributes ["pct"] carried) pctOn , paramLinks calcParam trs JournalR (qps ++ carried) CalcChange calcCur ] diff --git a/hledger-web/Hledger/Web/Handler/RegisterR.hs b/hledger-web/Hledger/Web/Handler/RegisterR.hs index bf70e31a9d4..0945b8e302d 100644 --- a/hledger-web/Hledger/Web/Handler/RegisterR.hs +++ b/hledger-web/Hledger/Web/Handler/RegisterR.hs @@ -27,16 +27,16 @@ import Hledger.Write.Chart.Svg (SvgOptions(..), chartSvgMarkupWith, defaultSvgOp import Hledger.Web.Import import Hledger.Web.Paging import Hledger.Web.Widget.Chart (chartLegend, chartWidth) -import Hledger.Web.Param (Param(..), accumParam, calcParam, lookupParam, paramLinks, paramSetting, paramSettings) -import Hledger.Web.ReportPage (amountModeOf, deepestDepth, depthParams, removeAttributes, intervalLinks, listWord, parseInterval, parseListMode, parseValue, setAmountMode, valueParams) +import Hledger.Web.Param (Param(..), accumParam, calcParam, listParam, lookupParam, paramLinks, paramSetting, paramSettings, sortParam) +import Hledger.Web.ReportPage (amountModeOf, deepestDepth, depthParams, removeAttributes, intervalLinks, parseInterval, parseValue, setAmountMode, valueParams) import Hledger.Web.WebOptions import Hledger.Web.Widget.AddForm (addModal) import Hledger.Web.Widget.Common (accountParams, accountRegisterQuery, amountLinks, columnsLinks, commodityLinks, controlsHint, controlsToggle, optionsSummary, searchHeading, costsLinks, depthLinks, - inertControls, listModeLinks, lotsLinks, mixedAmountAsHtmlElided, + inertControls, lotsLinks, mixedAmountAsHtmlElided, mixedAmountAsHtmlWith, moreCommodities, percentLinks, pricesLinks, realLinks, - runningBalanceAsHtml, sortLinks, statusLinks, typeLinks, + runningBalanceAsHtml, statusLinks, typeLinks, zeroBalanceLinks, transactionFragment, removeDates, journalDayQuery) -- | The main journal/account register view, with accounts sidebar. @@ -54,7 +54,7 @@ getRegisterR = do -- figures were (see Hledger.Web.ReportPage.parseValue), so that its -- figures' registers end on them. One it does not know is ignored. mmode <- either (const Nothing) id . parseValue <$> lookupGetParam "value" - mlist <- either (const Nothing) id . parseListMode <$> lookupGetParam "list" + mlist <- lookupParam listParam -- With costs=1 amounts keep the costs recorded with them (10 AAPL @ $95), -- which are stripped by default. costsOn <- (== Just "1") <$> lookupGetParam "costs" @@ -63,7 +63,7 @@ getRegisterR = do minterval <- lookupGetParam "interval" totalOn <- (== Just "1") <$> lookupGetParam "total" avgOn <- (== Just "1") <$> lookupGetParam "avg" - sortAmt <- (== Just "amount") <$> lookupGetParam "sort" + sortAmt <- fromMaybe False <$> lookupParam sortParam pctOn <- (== Just "1") <$> lookupGetParam "pct" calcCur <- fromMaybe CalcChange <$> lookupParam calcParam urlrender <- getUrlRenderParams @@ -96,14 +96,14 @@ getRegisterR = do dfltHidden = empty_ $ _rsReportOpts rspec0 emptyParams = [("empty", if hideEmpty then "0" else "1") | hideEmpty /= dfltHidden] elist = fromMaybe (accountlistmode_ $ _rsReportOpts rspec0) mlist - listParams = [("list", listWord elist) | elist /= accountlistmode_ (_rsReportOpts rspec0)] + listParams = paramSettings listParam (accountlistmode_ (_rsReportOpts rspec0)) elist -- The report-shaping state shapes nothing here, but it is passed -- along and shown dimmed below, so it survives visiting a register. stickyParams = [("interval", w) | Just w <- [mfilter (not . T.null) minterval]] ++ [("total", "1") | totalOn] ++ [("avg", "1") | avgOn] ++ - [("sort", "amount") | sortAmt] ++ + paramSettings sortParam False sortAmt ++ [("pct", "1") | pctOn] ++ paramSettings calcParam CalcChange calcCur lotsParams = [("lots", "1") | lotsShown] @@ -134,7 +134,7 @@ getRegisterR = do deepest = deepestDepth j depthRow = depthLinks trs RegisterR modeParams qparam deepest -- Tree mode adds the sidebar's fold carets. - listRow = listModeLinks trs RegisterR (qParams qparam ++ removeAttributes ["list"] modeParams) (accountlistmode_ $ _rsReportOpts rspec0) elist + listRow = paramLinks listParam trs RegisterR (qParams qparam ++ modeParams) (accountlistmode_ $ _rsReportOpts rspec0) elist amountsRow = amountLinks trs RegisterR (qParams qparam ++ removeAttributes ["value"] modeParams) (amountModeOf $ _rsReportOpts rspec0) (amountModeOf ropts) costsRow = costsLinks trs RegisterR (qParams qparam ++ removeAttributes ["costs"] modeParams) costsOn @@ -154,7 +154,7 @@ getRegisterR = do intervalLinks trs RegisterR (removeAttributes ["interval"] modeParams) qparam rpInterval inertRows = inertControls trs $ mconcat [ columnsLinks trs RegisterR (qParams qparam ++ removeAttributes ["total", "avg"] modeParams) totalOn avgOn - , sortLinks trs RegisterR (qParams qparam ++ removeAttributes ["sort"] modeParams) sortAmt + , paramLinks sortParam trs RegisterR (qParams qparam ++ modeParams) False sortAmt , percentLinks trs RegisterR (qParams qparam ++ removeAttributes ["pct"] modeParams) pctOn , paramLinks calcParam trs RegisterR (qParams qparam ++ modeParams) CalcChange calcCur ] diff --git a/hledger-web/Hledger/Web/Handler/StatementsR.hs b/hledger-web/Hledger/Web/Handler/StatementsR.hs index 16cca6e2425..dc112d22380 100644 --- a/hledger-web/Hledger/Web/Handler/StatementsR.hs +++ b/hledger-web/Hledger/Web/Handler/StatementsR.hs @@ -33,15 +33,15 @@ import Hledger.Write.Spreadsheet qualified as Spr import Hledger.Web.Import import Hledger.Web.Widget.AddForm (addModal) import Hledger.Web.Paging (yearsRow) -import Hledger.Web.Param (Param(..), accumParam, calcParam, paramLinks, paramSettings) +import Hledger.Web.Param (Param(..), accumParam, calcParam, listParam, paramLinks, paramSettings, sortParam) import Hledger.Web.ReportPage import Hledger.Web.WebOptions import Hledger.Web.Widget.Chart (reportChart) import Hledger.Web.Widget.Common (amountLinks, columnsLinks, commodityLinks, controlsToggle, optionsSummary, depthLinks, equityLinks, helplink, - listModeLinks, lotsLinks, percentLinks, pricesLinks, realLinks, - sortLinks, statusLinks, zeroBalanceLinks) + lotsLinks, percentLinks, pricesLinks, realLinks, + statusLinks, zeroBalanceLinks) getBalancesheetR, getBalancesheetequityR, getIncomestatementR, getCashflowR :: Handler Html -- The balance sheet's equity choice is remembered: an equity parameter @@ -123,10 +123,10 @@ statementPage here tabtitle spec mequity = do intervalParams = [("interval", w) | Just w <- [intervalPeriodExpr rpInterval]] accumParams = paramSettings accumParam (cbcaccum spec) accum valParams = valueParams roptsOrig rpValue - listParams = [("list", listWord (accountlistmode_ ropts)) | accountlistmode_ ropts /= accountlistmode_ roptsOrig] + listParams = paramSettings listParam (accountlistmode_ roptsOrig) (accountlistmode_ ropts) totalParams = [("total", "1") | row_total_ ropts] avgParams = [("avg", "1") | average_ ropts] - sortParams = [("sort", "amount") | sort_amount_ ropts] + sortParams = paramSettings sortParam False (sort_amount_ ropts) pctParams = [("pct", "1") | percent_ ropts] calcParams = paramSettings calcParam CalcChange (balancecalc_ ropts) inferParams = [("infer", "1") | infer_prices_ ropts, not (infer_prices_ roptsOrig)] @@ -196,14 +196,14 @@ statementPage here tabtitle spec mequity = do -- TRANSLATORS: the hint below the commodity filter row. (tr trs "Shift-click selects several commodities.") j ] ++ [ depthLinks trs here pageParams qparam deepest | deepest > 1 ] ++ - [ listModeLinks trs here (qParams ++ removeAttributes ["list"] pageParams) (accountlistmode_ roptsOrig) (accountlistmode_ ropts) + [ paramLinks listParam trs here (qParams ++ pageParams) (accountlistmode_ roptsOrig) (accountlistmode_ ropts) , amountLinks trs here (qParams ++ removeAttributes ["value"] pageParams) (amountModeOf roptsOrig) (amountModeOf ropts) , pricesLinks trs here (qParams ++ removeAttributes ["infer"] pageParams) (infer_prices_ ropts) , zeroBalanceLinks trs here (qParams ++ removeAttributes ["empty"] pageParams) (empty_ roptsOrig) hideEmpty ] ++ [ lotsLinks trs here (qParams ++ removeAttributes ["lots"] pageParams) lotsShown | jHasLots ] ++ [ columnsLinks trs here (qParams ++ removeAttributes ["total", "avg"] pageParams) (row_total_ ropts) (average_ ropts) | rpInterval /= NoInterval ] ++ - [ sortLinks trs here (qParams ++ removeAttributes ["sort"] pageParams) (sort_amount_ ropts) + [ paramLinks sortParam trs here (qParams ++ pageParams) False (sort_amount_ ropts) , percentLinks trs here (qParams ++ removeAttributes ["pct"] pageParams) (percent_ ropts) , paramLinks calcParam trs here (qParams ++ pageParams) CalcChange (balancecalc_ ropts) ] Yesod.toWidget controlRows diff --git a/hledger-web/Hledger/Web/Param.hs b/hledger-web/Hledger/Web/Param.hs index 0e39dc00be8..cb70a7f1c91 100644 --- a/hledger-web/Hledger/Web/Param.hs +++ b/hledger-web/Hledger/Web/Param.hs @@ -21,6 +21,8 @@ module Hledger.Web.Param , paramPhrase , accumParam , calcParam + , listParam + , sortParam ) where import Control.Monad (unless) @@ -162,3 +164,37 @@ calcParam = Param CalcPostingsCount -> (tr trs "Posting counts", tr trs "Count the postings instead of summing them (--count)") _ -> ("", "") } + +-- | The list parameter: show accounts as a flat list or a tree; absent +-- for the page's default, the startup one. The t key toggles them +-- (hledger.js). +listParam :: Param AccountListMode +listParam = Param + { paramName = "list" + , paramModes = [ALFlat, ALTree] + , paramWord = \case + ALFlat -> "flat" + ALTree -> "tree" + -- TRANSLATORS: the label before a report's list/tree links, and the links' text and tooltips. + , paramRowLabel = \trs -> tr trs "Accounts:" + , paramLabel = \trs -> \case + ALFlat -> (trc trs "accounts" "List", tr trs "Show accounts as a flat list (--flat)") + ALTree -> (trc trs "accounts" "Tree", tr trs "Show accounts as a tree (--tree)") + } + +-- | The sort parameter: whether rows are sorted by amount, rather than +-- by account display order (declaration order, otherwise name). +-- The S key toggles By amount, the second link (hledger.js). +sortParam :: Param Bool +sortParam = Param + { paramName = "sort" + , paramModes = [False, True] + , paramWord = \case + False -> "account" + True -> "amount" + -- TRANSLATORS: the label before a report's sort links, and the links' text and tooltips. + , paramRowLabel = \trs -> tr trs "Sort:" + , paramLabel = \trs -> \case + False -> (tr trs "By account", tr trs "Sort rows by account display order") + True -> (tr trs "By amount", tr trs "Sort rows by their amounts, largest first (-S)") + } diff --git a/hledger-web/Hledger/Web/ReportPage.hs b/hledger-web/Hledger/Web/ReportPage.hs index b4e56328e12..a82f2535d1a 100644 --- a/hledger-web/Hledger/Web/ReportPage.hs +++ b/hledger-web/Hledger/Web/ReportPage.hs @@ -20,9 +20,7 @@ module Hledger.Web.ReportPage ( pctError, AmountMode(..), parseValue, - parseListMode, readParam, - listWord, valueWord, amountModeOf, setAmountMode, @@ -64,8 +62,8 @@ import Yesod (HtmlUrl) import Hledger.Utils.I18n (Translations, tr, trc, trf) import Hledger import Hledger.Cli.Anchor (dateTerm, renderPeriodHeading) -import Hledger.Web.Param (Param(..), accumParam, calcParam, linksRowClass, paramSettings, parseParam) -import Hledger.Web.Widget.Common (AmountMode(..), listWord, removeDates, valueWord) +import Hledger.Web.Param (Param(..), accumParam, calcParam, listParam, sortParam, linksRowClass, paramSettings, parseParam) +import Hledger.Web.Widget.Common (AmountMode(..), removeDates, valueWord) import Hledger.Query qualified as Query import Hledger.Write.Html (Html, formatCell, nl) import Hledger.Write.Spreadsheet (Cell(..), Class(..), NumLines, textFromClass) @@ -112,10 +110,10 @@ reportParams rspecOrig qparam q qopts hideEmpty params = do Just t -> either (Left . BadInterval . errorBundlePretty) Right $ parseInterval t rpAccum <- readParam accumParam (param $ paramName accumParam) rpValue <- parseValue (param "value") - mlist <- parseListMode (param "list") + mlist <- readParam listParam (param $ paramName listParam) total <- parseFlag "total" (param "total") avg <- parseFlag "avg" (param "avg") - sortAmt <- parseSort (param "sort") + sortAmt <- fromMaybe False <$> readParam sortParam (param $ paramName sortParam) pct <- parseFlag "pct" (param "pct") calc <- fromMaybe CalcChange <$> readParam calcParam (param $ paramName calcParam) infer <- parseFlag "infer" (param "infer") @@ -194,10 +192,10 @@ startupUrlState rspec@ReportSpec{_rsReportOpts = ropts} = (params, rspec') [("depth", T.pack (show n)) | Just n <- [dsFlatDepth $ depth_ ropts]] ++ paramSettings accumParam PerPeriod (balanceaccum_ ropts) ++ [("value", valueWord m) | Just m <- [amountModeOf ropts], m /= AsRecorded] ++ - [("list", "tree") | accountlistmode_ ropts == ALTree] ++ + paramSettings listParam ALFlat (accountlistmode_ ropts) ++ [("total", "1") | row_total_ ropts] ++ [("avg", "1") | average_ ropts] ++ - [("sort", "amount") | sort_amount_ ropts] ++ + paramSettings sortParam False (sort_amount_ ropts) ++ [("pct", "1") | percent_ ropts] ++ paramSettings calcParam CalcChange (balancecalc_ ropts) ++ [("costs", "1") | show_costs_ ropts] ++ @@ -308,15 +306,6 @@ intervalLinks trs route kept qparam current = link mword = (route, [("q", qparam) | not (T.null qparam)] ++ kept ++ [("interval", w) | Just w <- [mword]]) --- | The list parameter: show accounts as a "tree" or a "flat" list. -parseListMode :: Maybe Text -> Either ReportParamError (Maybe AccountListMode) -parseListMode = \case - Nothing -> Right Nothing - Just "" -> Right Nothing - Just "tree" -> Right $ Just ALTree - Just "flat" -> Right $ Just ALFlat - Just other -> Left $ BadParamValue "list" other - -- | A parameter that turns something on: "1", or "0" or nothing for off. parseFlag :: Text -> Maybe Text -> Either ReportParamError Bool parseFlag name = \case @@ -326,16 +315,6 @@ parseFlag name = \case Just "1" -> Right True Just other -> Left $ BadParamValue name other --- | The sort parameter: rows in "amount" order, or "account" order (the --- default). -parseSort :: Maybe Text -> Either ReportParamError Bool -parseSort = \case - Nothing -> Right False - Just "" -> Right False - Just "account" -> Right False - Just "amount" -> Right True - Just other -> Left $ BadParamValue "sort" other - -- | Read a multiple-choice parameter's value (see 'parseParam'), -- naming the parameter if the value is unknown. readParam :: Param a -> Maybe Text -> Either ReportParamError (Maybe a) diff --git a/hledger-web/Hledger/Web/Test.hs b/hledger-web/Hledger/Web/Test.hs index 943b5487c42..2ef391fd5bd 100644 --- a/hledger-web/Hledger/Web/Test.hs +++ b/hledger-web/Hledger/Web/Test.hs @@ -65,7 +65,7 @@ import Web.Cookie (defaultSetCookie, setCookieName, setCookieValue) import Hledger.Web.Application ( makeAppWith ) import Hledger.Utils.I18n (noTranslations) import Hledger.Web.Paging (pageNumbers) -import Hledger.Web.Param (Param(..), accumParam, calcParam, parseParam) +import Hledger.Web.Param (Param(..), accumParam, calcParam, listParam, parseParam, sortParam) import Hledger.Web.ReportPage (intervalPeriodExpr, startupUrlState) import Hledger.Web.WebOptions -- ( WebOpts(..), defwebopts, prognameandversion ) import Hledger.Web.Import hiding (get, j) @@ -279,6 +279,8 @@ hledgerWebTest = do let distinctWords p = let ws = map (paramWord p) (paramModes p) in length (nub ws) == length ws distinctWords accumParam `shouldBe` True distinctWords calcParam `shouldBe` True + distinctWords listParam `shouldBe` True + distinctWords sortParam `shouldBe` True it "reads a mode's word, an empty or absent value as the default, and returns an unknown word" $ do parseParam calcParam (Just "gain") `shouldBe` Right (Just CalcGain) parseParam calcParam (Just "") `shouldBe` Right Nothing diff --git a/hledger-web/Hledger/Web/Widget/Common.hs b/hledger-web/Hledger/Web/Widget/Common.hs index 4eb69b306aa..af5445eac33 100644 --- a/hledger-web/Hledger/Web/Widget/Common.hs +++ b/hledger-web/Hledger/Web/Widget/Common.hs @@ -21,9 +21,7 @@ module Hledger.Web.Widget.Common , zeroBalanceLinks , statusLinks , realLinks - , listModeLinks , columnsLinks - , sortLinks , percentLinks , costsLinks , lotsLinks @@ -31,7 +29,6 @@ module Hledger.Web.Widget.Common , holdingsValueLinks , typeLinks , AmountMode(..) - , listWord , valueWord , searchTerms , MovedOptions(..) @@ -77,7 +74,7 @@ import Hledger.Utils.I18n (Translations, tr, trc, trf) import Hledger import Hledger.Cli.Anchor qualified as Anchor import Hledger.Cli.Utils (writeFileWithBackupIfChanged) -import Hledger.Web.Param (accumParam, calcParam, linksRow, linksRowClass, paramName, paramPhrase) +import Hledger.Web.Param (accumParam, calcParam, listParam, sortParam, linksRow, linksRowClass, paramName, paramPhrase) import Hledger.Web.Settings (manualurl) import Hledger.Query qualified as Query @@ -125,7 +122,7 @@ helplink topic label _ = H.a ! A.href u ! A.target "hledgerhelp" $ toHtml label -- prices, zero balances, and lot detail. Each such link rewrites the -- search itself. registerKeptParams :: [(Text, Text)] -> [(Text, Text)] -registerKeptParams ps = [p | p@(k, _) <- ps, k `elem` ["depth", "value", "list", "infer", "empty", "lots"]] +registerKeptParams ps = [p | p@(k, _) <- ps, k `elem` ["depth", "value", paramName listParam, "infer", "empty", "lots"]] -- | Render a "BalanceReport" as the sidebar: the page links (each page's -- route, label, and title, with the parameters their links carry), then @@ -189,8 +186,8 @@ optionsSummary :: Translations -> Int -> [(Text, Text)] -> [Text] optionsSummary trs deepest = mapMaybe phrase . sortOn (rowOrder . fst) where rowOrder k = fromMaybe maxBound $ elemIndex k - ["equity", "interval", paramName accumParam, "depth", "list", "value", "infer", "empty", "lots", "closed", - "total", "avg", "costs", "sort", "pct", paramName calcParam, "date2"] + ["equity", "interval", paramName accumParam, "depth", paramName listParam, "value", "infer", "empty", "lots", "closed", + "total", "avg", "costs", paramName sortParam, "pct", paramName calcParam, "date2"] phrase = \case ("interval", w) -> Just $ fromMaybe w $ lookup w [ ("yearly", tr trs "Yearly"), ("quarterly", tr trs "Quarterly"), ("monthly", tr trs "Monthly") @@ -204,9 +201,8 @@ optionsSummary trs deepest = mapMaybe phrase . sortOn (rowOrder . fst) ("value", "none") -> Just $ tr trs "As recorded" ("value", "cost") -> Just $ trc trs "amounts" "Cost" ("value", _) -> Just $ trc trs "amounts" "Value" - ("list", "tree") -> Just $ trc trs "accounts" "Tree" - ("list", "flat") -> Just $ trc trs "accounts" "List" - ("sort", "amount") -> Just $ tr trs "By amount" + (k, w) | k == paramName listParam -> paramPhrase listParam trs w + (k, w) | k == paramName sortParam -> paramPhrase sortParam trs w ("pct", "1") -> Just $ tr trs "Percentages" (k, w) | k == paramName calcParam -> paramPhrase calcParam trs w -- TRANSLATORS: options in effect, listed on the closed options disclosure. @@ -266,11 +262,6 @@ pricesLinks trs route kept inferOn = , (tr trs "Inferred too", tr trs "Infer market prices from transaction costs too (--infer-market-prices)", (route, kept ++ [("infer", "1")]), inferOn) ] --- | The list parameter value naming an accounts mode. -listWord :: AccountListMode -> Text -listWord ALTree = "tree" -listWord ALFlat = "flat" - -- | How a page shows amounts: in the commodities they were recorded in, -- converted to cost (as with -B), or converted with one of the market -- valuations (as with -V, -X, and --value). @@ -403,19 +394,6 @@ realLinks trs route kept qparam = , (tr trs "Virtual", tr trs "Show only virtual postings, the parenthesized ones (real:0)", Just "real:0") ] --- | Links showing the report's accounts as a flat list or a tree, --- keeping the given parameters; the mode being shown is marked, and --- the page's default mode, the startup one, needs no parameter. The t --- key toggles them (hledger.js). -listModeLinks :: Translations -> r -> [(Text, Text)] -> AccountListMode -> AccountListMode -> HtmlUrl r -listModeLinks trs route kept dflt mode = - -- TRANSLATORS: the label before a report's list/tree links, and the links' text and tooltips. - linksRowClass "accounts" (tr trs "Accounts:") - [ (trc trs "accounts" "List", tr trs "Show accounts as a flat list (--flat)", link ALFlat, mode == ALFlat) - , (trc trs "accounts" "Tree", tr trs "Show accounts as a tree (--tree)", link ALTree, mode == ALTree) - ] - where link m = (route, kept ++ [("list", listWord m) | m /= dflt]) - -- | Toggles adding a row-total and a row-average column to a -- multi-period report, as -T and -A do; the columns shown are marked. -- The T and A keys follow these links, by their order here (hledger.js). @@ -429,17 +407,6 @@ columnsLinks trs route kept total avg = (route, kept ++ [("total", "1") | total] ++ [("avg", "1") | not avg]), avg) ] --- | Links sorting the report's rows by account display order (declaration order, otherwise name) --- or by amount, keeping the given parameters; the order being shown is marked. --- The S key toggles By amount, the second link (hledger.js). -sortLinks :: Translations -> r -> [(Text, Text)] -> Bool -> HtmlUrl r -sortLinks trs route kept byAmount = - -- TRANSLATORS: the label before a report's sort links, and the links' text and tooltips. - linksRowClass "sort" (tr trs "Sort:") - [ (tr trs "By account", tr trs "Sort rows by account display order", (route, kept), not byAmount) - , (tr trs "By amount", tr trs "Sort rows by their amounts, largest first (-S)", (route, kept ++ [("sort", "amount")]), byAmount) - ] - -- | Links showing the report's numbers as amounts or as percentages of -- their column's total, keeping the given parameters. percentLinks :: Translations -> r -> [(Text, Text)] -> Bool -> HtmlUrl r diff --git a/hledger-web/static/hledger.js b/hledger-web/static/hledger.js index 3db9cee7e59..a58eeaa6b81 100644 --- a/hledger-web/static/hledger.js +++ b/hledger-web/static/hledger.js @@ -196,7 +196,7 @@ var keymap = [ { keys: ['[', ']'], at: '#main-content .with-legend', run: commodityStep }, { keys: ['/'], run: function() { fullWindowLeave(); focusSearch(); } }, { keys: ['z'], at: '.zero-balances a:not(.current)', run: linkFollow }, - { keys: ['t'], at: rowLink('accounts', -1), run: linkToggle }, + { keys: ['t'], at: rowLink('list', -1), run: linkToggle }, { keys: ['H'], at: rowLink('accum', 1), run: linkToggle }, { keys: ['L'], at: rowLink('lots', 1), run: linkToggle }, { keys: ['V'], at: rowLink('amounts', -1), run: linkToggle }, From 1e062458af5ae8e6fa319075500e1924eabf2bc7 Mon Sep 17 00:00:00 2001 From: Simon Michael Date: Sat, 14 Nov 2026 08:10:13 -1000 Subject: [PATCH 4/4] dev: web: the parameters themselves are in ReportPage, Param keeps the generic part Following review: Hledger.Web.Param now holds only the generic definitions (the Param type, its functions, and the links row renderer), and the four parameters, accumParam, calcParam, listParam and sortParam, are in Hledger.Web.ReportPage with the rest of the report pages' parameter handling. optionsSummary and registerKeptParams, which use them, move from Widget.Common to ReportPage too, avoiding an import cycle; the sidebar (balanceReportAsHtml) now takes the parameters its register links keep. AI usage: Claude Opus 5.5, ~15k output tokens --- hledger-lib/locale/hledger.pot | 94 ++++++------ hledger-web/Hledger/Web/App.hs | 6 +- hledger-web/Hledger/Web/Handler/BalanceR.hs | 4 +- hledger-web/Hledger/Web/Handler/HoldingsR.hs | 4 +- hledger-web/Hledger/Web/Handler/JournalR.hs | 6 +- hledger-web/Hledger/Web/Handler/RegisterR.hs | 6 +- .../Hledger/Web/Handler/StatementsR.hs | 4 +- hledger-web/Hledger/Web/Param.hs | 92 +---------- hledger-web/Hledger/Web/ReportPage.hs | 144 +++++++++++++++++- hledger-web/Hledger/Web/Test.hs | 6 +- hledger-web/Hledger/Web/Widget/Common.hs | 71 ++------- 11 files changed, 220 insertions(+), 217 deletions(-) diff --git a/hledger-lib/locale/hledger.pot b/hledger-lib/locale/hledger.pot index 33e27c37eeb..28aa4ba70c2 100644 --- a/hledger-lib/locale/hledger.pot +++ b/hledger-lib/locale/hledger.pot @@ -294,7 +294,7 @@ msgid "Historical gain" msgstr "" #. the label before a report's calculation links, and the links' text and tooltips. -#: hledger/Hledger/Cli/Commands/Balance.hs hledger-web/Hledger/Web/Param.hs +#: hledger/Hledger/Cli/Commands/Balance.hs hledger-web/Hledger/Web/ReportPage.hs msgid "Posting counts" msgstr "" @@ -312,7 +312,7 @@ msgstr "" #. Key term #. the label before a report's accumulation mode links, and the links' text and tooltips. -#: hledger/Hledger/Cli/Commands/Balance.hs hledger-web/Hledger/Web/Param.hs +#: hledger/Hledger/Cli/Commands/Balance.hs hledger-web/Hledger/Web/ReportPage.hs msgid "Balance changes" msgstr "" @@ -649,7 +649,7 @@ msgid "Register" msgstr "" #. the label before a report's accumulation mode links, and the links' text and tooltips. -#: hledger/Hledger/Cli/Commands/Run.hs hledger-web/Hledger/Web/Param.hs hledger-web/templates/default-layout.hamlet +#: hledger/Hledger/Cli/Commands/Run.hs hledger-web/Hledger/Web/ReportPage.hs hledger-web/templates/default-layout.hamlet msgid "Show:" msgstr "" @@ -861,7 +861,7 @@ msgid "None" msgstr "" #. the interval links above a report: each link's text, and its tooltip. -#: hledger-web/Hledger/Web/ReportPage.hs hledger-web/Hledger/Web/Widget/Common.hs +#: hledger-web/Hledger/Web/ReportPage.hs msgid "Yearly" msgstr "" @@ -871,7 +871,7 @@ msgid "Show a column per year" msgstr "" #. the interval links above a report: each link's text, and its tooltip. -#: hledger-web/Hledger/Web/ReportPage.hs hledger-web/Hledger/Web/Widget/Common.hs +#: hledger-web/Hledger/Web/ReportPage.hs msgid "Quarterly" msgstr "" @@ -881,7 +881,7 @@ msgid "Show a column per quarter" msgstr "" #. the interval links above a report: each link's text, and its tooltip. -#: hledger-web/Hledger/Web/ReportPage.hs hledger-web/Hledger/Web/Widget/Common.hs +#: hledger-web/Hledger/Web/ReportPage.hs msgid "Monthly" msgstr "" @@ -891,7 +891,7 @@ msgid "Show a column per month" msgstr "" #. the interval links above a report: each link's text, and its tooltip. -#: hledger-web/Hledger/Web/ReportPage.hs hledger-web/Hledger/Web/Widget/Common.hs +#: hledger-web/Hledger/Web/ReportPage.hs msgid "Weekly" msgstr "" @@ -901,7 +901,7 @@ msgid "Show a column per week" msgstr "" #. the interval links above a report: each link's text, and its tooltip. -#: hledger-web/Hledger/Web/ReportPage.hs hledger-web/Hledger/Web/Widget/Common.hs +#: hledger-web/Hledger/Web/ReportPage.hs msgid "Daily" msgstr "" @@ -911,28 +911,28 @@ msgid "Show a column per day" msgstr "" #. the label before a report's accumulation mode links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Param.hs +#: hledger-web/Hledger/Web/ReportPage.hs msgid "Show how much each balance changed in each period" msgstr "" #. Key term #. the label before a report's accumulation mode links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Param.hs +#: hledger-web/Hledger/Web/ReportPage.hs msgid "Ending balances" msgstr "" #. the label before a report's accumulation mode links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Param.hs +#: hledger-web/Hledger/Web/ReportPage.hs msgid "Show each balance at the end of each period, including everything before it" msgstr "" #. the label before a report's accumulation mode links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Param.hs +#: hledger-web/Hledger/Web/ReportPage.hs msgid "Cumulative totals" msgstr "" #. the label before a report's accumulation mode links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Param.hs +#: hledger-web/Hledger/Web/ReportPage.hs msgid "Show each balance's change since the start of the report (--cumulative)" msgstr "" @@ -1290,7 +1290,7 @@ msgid "Options" msgstr "" #. the depth limit, in the list of options in effect. -#: hledger-web/Hledger/Web/Widget/Common.hs +#: hledger-web/Hledger/Web/ReportPage.hs #, python-brace-format msgid "Depth {depth}" msgstr "" @@ -1353,18 +1353,18 @@ msgstr "" #. the depth limit, in the list of options in effect. #. the label before a report's amount conversion links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Widget/Common.hs +#: hledger-web/Hledger/Web/ReportPage.hs hledger-web/Hledger/Web/Widget/Common.hs msgid "As recorded" msgstr "" #. the depth limit, in the list of options in effect. -#: hledger-web/Hledger/Web/Widget/Common.hs +#: hledger-web/Hledger/Web/ReportPage.hs msgctxt "amounts" msgid "Cost" msgstr "" #. the depth limit, in the list of options in effect. -#: hledger-web/Hledger/Web/Widget/Common.hs +#: hledger-web/Hledger/Web/ReportPage.hs msgctxt "amounts" msgid "Value" msgstr "" @@ -1527,28 +1527,28 @@ msgid "Show only virtual postings, the parenthesized ones (real:0)" msgstr "" #. the label before a report's list/tree links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Param.hs hledger-web/templates/default-layout.hamlet +#: hledger-web/Hledger/Web/ReportPage.hs hledger-web/templates/default-layout.hamlet msgid "Accounts:" msgstr "" #. the label before a report's list/tree links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Param.hs +#: hledger-web/Hledger/Web/ReportPage.hs msgid "Show accounts as a flat list (--flat)" msgstr "" #. the label before a report's list/tree links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Param.hs +#: hledger-web/Hledger/Web/ReportPage.hs msgctxt "accounts" msgid "List" msgstr "" #. the label before a report's list/tree links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Param.hs +#: hledger-web/Hledger/Web/ReportPage.hs msgid "Show accounts as a tree (--tree)" msgstr "" #. the label before a report's list/tree links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Param.hs +#: hledger-web/Hledger/Web/ReportPage.hs msgctxt "accounts" msgid "Tree" msgstr "" @@ -1565,7 +1565,7 @@ msgstr "" #. options in effect, listed on the closed options disclosure. #. the label before a report's extra-column toggles, and the toggles' text and tooltips. -#: hledger-web/Hledger/Web/Widget/Common.hs +#: hledger-web/Hledger/Web/ReportPage.hs hledger-web/Hledger/Web/Widget/Common.hs msgctxt "column" msgid "Total" msgstr "" @@ -1577,33 +1577,33 @@ msgstr "" #. options in effect, listed on the closed options disclosure. #. the label before a report's extra-column toggles, and the toggles' text and tooltips. -#: hledger-web/Hledger/Web/Widget/Common.hs +#: hledger-web/Hledger/Web/ReportPage.hs hledger-web/Hledger/Web/Widget/Common.hs msgctxt "column" msgid "Average" msgstr "" #. the label before a report's sort links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Param.hs hledger-web/templates/default-layout.hamlet +#: hledger-web/Hledger/Web/ReportPage.hs hledger-web/templates/default-layout.hamlet msgid "Sort:" msgstr "" #. the label before a report's sort links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Param.hs +#: hledger-web/Hledger/Web/ReportPage.hs msgid "By account" msgstr "" #. the label before a report's sort links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Param.hs +#: hledger-web/Hledger/Web/ReportPage.hs msgid "Sort rows by account display order" msgstr "" #. the label before a report's sort links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Param.hs +#: hledger-web/Hledger/Web/ReportPage.hs msgid "By amount" msgstr "" #. the label before a report's sort links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Param.hs +#: hledger-web/Hledger/Web/ReportPage.hs msgid "Sort rows by their amounts, largest first (-S)" msgstr "" @@ -1625,7 +1625,7 @@ msgstr "" #. the depth limit, in the list of options in effect. #. the label before a report's amounts/percentages links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Widget/Common.hs +#: hledger-web/Hledger/Web/ReportPage.hs hledger-web/Hledger/Web/Widget/Common.hs msgid "Percentages" msgstr "" @@ -1635,78 +1635,78 @@ msgid "Show each amount as a percentage of its column's total (-%)" msgstr "" #. the label before a report's calculation links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Param.hs +#: hledger-web/Hledger/Web/ReportPage.hs msgid "Calculate:" msgstr "" #. the label before a report's calculation links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Param.hs +#: hledger-web/Hledger/Web/ReportPage.hs msgid "Show sums of postings" msgstr "" #. the label before a report's calculation links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Param.hs +#: hledger-web/Hledger/Web/ReportPage.hs msgctxt "calculation" msgid "Sums" msgstr "" #. the label before a report's calculation links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Param.hs +#: hledger-web/Hledger/Web/ReportPage.hs msgid "Value change" msgstr "" #. the label before a report's calculation links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Param.hs +#: hledger-web/Hledger/Web/ReportPage.hs msgid "Show how period-end market values changed (--valuechange)" msgstr "" #. the label before a report's calculation links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Param.hs +#: hledger-web/Hledger/Web/ReportPage.hs msgid "Unrealized gain" msgstr "" #. options in effect, listed on the closed options disclosure. -#: hledger-web/Hledger/Web/Widget/Common.hs +#: hledger-web/Hledger/Web/ReportPage.hs msgid "Inferred prices" msgstr "" #. options in effect, listed on the closed options disclosure. -#: hledger-web/Hledger/Web/Widget/Common.hs +#: hledger-web/Hledger/Web/ReportPage.hs msgid "Zero balances hidden" msgstr "" #. options in effect, listed on the closed options disclosure. -#: hledger-web/Hledger/Web/Widget/Common.hs +#: hledger-web/Hledger/Web/ReportPage.hs msgid "Zero balances shown" msgstr "" #. options in effect, listed on the closed options disclosure. -#: hledger-web/Hledger/Web/Widget/Common.hs +#: hledger-web/Hledger/Web/ReportPage.hs msgid "Lots shown" msgstr "" #. options in effect, listed on the closed options disclosure. -#: hledger-web/Hledger/Web/Widget/Common.hs +#: hledger-web/Hledger/Web/ReportPage.hs msgid "Costs shown" msgstr "" #. options in effect, listed on the closed options disclosure. -#: hledger-web/Hledger/Web/Widget/Common.hs +#: hledger-web/Hledger/Web/ReportPage.hs msgid "Closed positions shown" msgstr "" #. options in effect, listed on the closed options disclosure. -#: hledger-web/Hledger/Web/Widget/Common.hs +#: hledger-web/Hledger/Web/ReportPage.hs msgid "Closed positions hidden" msgstr "" #. options in effect, listed on the closed options disclosure. -#: hledger-web/Hledger/Web/Widget/Common.hs +#: hledger-web/Hledger/Web/ReportPage.hs msgid "Secondary dates" msgstr "" #. options in effect, listed on the closed options disclosure. -#: hledger-web/Hledger/Web/Widget/Common.hs +#: hledger-web/Hledger/Web/ReportPage.hs msgid "Equity shown" msgstr "" @@ -1723,12 +1723,12 @@ msgid "{title} in {dates}, filtered" msgstr "" #. the label before a report's calculation links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Param.hs +#: hledger-web/Hledger/Web/ReportPage.hs msgid "Show unrealized capital gains: market value minus cost (--gain)" msgstr "" #. the label before a report's calculation links, and the links' text and tooltips. -#: hledger-web/Hledger/Web/Param.hs +#: hledger-web/Hledger/Web/ReportPage.hs msgid "Count the postings instead of summing them (--count)" msgstr "" diff --git a/hledger-web/Hledger/Web/App.hs b/hledger-web/Hledger/Web/App.hs index b7872cecbfa..9879ca5ebc4 100644 --- a/hledger-web/Hledger/Web/App.hs +++ b/hledger-web/Hledger/Web/App.hs @@ -60,8 +60,8 @@ import Hledger.Cli.Commands.Balancesheet (balancesheetSpec) import Hledger.Cli.Commands.Cashflow (cashflowSpec) import Hledger.Cli.Commands.Incomestatement (incomestatementSpec) import Hledger.Cli.CompoundBalanceCommand (CompoundBalanceCommandSpec(..)) -import Hledger.Web.Param (Param(..), accumParam, calcParam, listParam, lookupParam, sortParam) -import Hledger.Web.ReportPage (AmountMode(..), amountModeOf, intervalPeriodExpr, parseValue, reportLinks, setAmountMode) +import Hledger.Web.Param (Param(..), lookupParam) +import Hledger.Web.ReportPage (AmountMode(..), accumParam, amountModeOf, calcParam, intervalPeriodExpr, listParam, parseValue, registerKeptParams, reportLinks, setAmountMode, sortParam) import Hledger.Web.Settings (Extra(..), webmanualurl, widgetFile) import Hledger.Web.Settings.StaticFiles import Hledger.Web.WebOptions @@ -285,7 +285,7 @@ instance Yesod App where (tr trs "Net flows:", tr trs "The sum of every account: open positions in each commodity, and the cash that paid for them. Zero when nothing crosses commodities.") accounts = - balanceReportAsHtml RegisterR here sidebarReports sidebarParams hideEmptyAccts totlabel tottitle trs j qparam account $ + balanceReportAsHtml RegisterR here sidebarReports sidebarParams (registerKeptParams sidebarParams) hideEmptyAccts totlabel tottitle trs j qparam account $ styleAmounts (journalCommodityStylesWith HardRounding j) $ balanceReport rspec' j diff --git a/hledger-web/Hledger/Web/Handler/BalanceR.hs b/hledger-web/Hledger/Web/Handler/BalanceR.hs index 21b1e2e853f..ba493d7ea19 100644 --- a/hledger-web/Hledger/Web/Handler/BalanceR.hs +++ b/hledger-web/Hledger/Web/Handler/BalanceR.hs @@ -18,12 +18,12 @@ import Hledger.Utils.I18n (tr, trc, trf) import Hledger.Web.Import import Hledger.Web.Widget.AddForm (addModal) import Hledger.Web.Paging (yearsRow) -import Hledger.Web.Param (Param(..), accumParam, calcParam, listParam, paramLinks, paramSettings, sortParam) +import Hledger.Web.Param (Param(..), paramLinks, paramSettings) import Hledger.Web.ReportPage import Hledger.Web.WebOptions import Hledger.Web.Widget.Chart (reportChart) import Hledger.Web.Widget.Common - (amountLinks, columnsLinks, commodityLinks, controlsHint, controlsToggle, optionsSummary, + (amountLinks, columnsLinks, commodityLinks, controlsHint, controlsToggle, depthLinks, lotsLinks, percentLinks, pricesLinks, realLinks, statusLinks, typeLinks, zeroBalanceLinks) diff --git a/hledger-web/Hledger/Web/Handler/HoldingsR.hs b/hledger-web/Hledger/Web/Handler/HoldingsR.hs index d3939a85355..fb3fe4de26d 100644 --- a/hledger-web/Hledger/Web/Handler/HoldingsR.hs +++ b/hledger-web/Hledger/Web/Handler/HoldingsR.hs @@ -21,12 +21,12 @@ import Hledger.Web.Import import Hledger.Web.Widget.AddForm (addModal) import Hledger.Web.Handler.BalanceR (reportTitle) import Hledger.Web.Paging (yearsRow) -import Hledger.Web.Param (Param(..), listParam, paramLinks, paramSettings, sortParam) +import Hledger.Web.Param (Param(..), paramLinks, paramSettings) import Hledger.Web.ReportPage import Hledger.Web.WebOptions import Hledger.Web.Widget.Chart (reportChart) import Hledger.Web.Widget.Common - (accountParams, closedLinks, commodityLinks, controlsToggle, optionsSummary, + (accountParams, closedLinks, commodityLinks, controlsToggle, depthLinks, holdingsValueLinks, lotsLinks, pricesLinks, realLinks, searchTerms, statusLinks, zeroBalanceLinks) diff --git a/hledger-web/Hledger/Web/Handler/JournalR.hs b/hledger-web/Hledger/Web/Handler/JournalR.hs index b08a5b50ae1..ebe46511d9e 100644 --- a/hledger-web/Hledger/Web/Handler/JournalR.hs +++ b/hledger-web/Hledger/Web/Handler/JournalR.hs @@ -15,11 +15,11 @@ import Hledger.Web.Import import Hledger.Web.Paging import Hledger.Web.WebOptions import Hledger.Web.Widget.AddForm (addModal) -import Hledger.Web.Param (calcParam, listParam, lookupParam, paramLinks, paramSettings, sortParam) -import Hledger.Web.ReportPage (amountModeOf, deepestDepth, depthParams, intervalLinks, parseInterval, parseValue, removeAttributes, setAmountMode, valueParams) +import Hledger.Web.Param (lookupParam, paramLinks, paramSettings) +import Hledger.Web.ReportPage (amountModeOf, calcParam, deepestDepth, depthParams, intervalLinks, listParam, optionsSummary, parseInterval, parseValue, removeAttributes, setAmountMode, sortParam, valueParams) import Hledger.Web.Widget.Common (accountParams, amountLinks, columnsLinks, commodityLinks, - controlsHint, controlsToggle, optionsSummary, searchHeading, + controlsHint, controlsToggle, searchHeading, depthLinks, inertControls, lotsLinks, mixedAmountAsHtml, percentLinks, pricesLinks, realLinks, statusLinks, typeLinks, diff --git a/hledger-web/Hledger/Web/Handler/RegisterR.hs b/hledger-web/Hledger/Web/Handler/RegisterR.hs index 0945b8e302d..4913042f4a2 100644 --- a/hledger-web/Hledger/Web/Handler/RegisterR.hs +++ b/hledger-web/Hledger/Web/Handler/RegisterR.hs @@ -27,13 +27,13 @@ import Hledger.Write.Chart.Svg (SvgOptions(..), chartSvgMarkupWith, defaultSvgOp import Hledger.Web.Import import Hledger.Web.Paging import Hledger.Web.Widget.Chart (chartLegend, chartWidth) -import Hledger.Web.Param (Param(..), accumParam, calcParam, listParam, lookupParam, paramLinks, paramSetting, paramSettings, sortParam) -import Hledger.Web.ReportPage (amountModeOf, deepestDepth, depthParams, removeAttributes, intervalLinks, parseInterval, parseValue, setAmountMode, valueParams) +import Hledger.Web.Param (Param(..), lookupParam, paramLinks, paramSetting, paramSettings) +import Hledger.Web.ReportPage (accumParam, amountModeOf, calcParam, deepestDepth, depthParams, intervalLinks, listParam, optionsSummary, parseInterval, parseValue, removeAttributes, setAmountMode, sortParam, valueParams) import Hledger.Web.WebOptions import Hledger.Web.Widget.AddForm (addModal) import Hledger.Web.Widget.Common (accountParams, accountRegisterQuery, amountLinks, columnsLinks, - commodityLinks, controlsHint, controlsToggle, optionsSummary, searchHeading, costsLinks, depthLinks, + commodityLinks, controlsHint, controlsToggle, searchHeading, costsLinks, depthLinks, inertControls, lotsLinks, mixedAmountAsHtmlElided, mixedAmountAsHtmlWith, moreCommodities, percentLinks, pricesLinks, realLinks, runningBalanceAsHtml, statusLinks, typeLinks, diff --git a/hledger-web/Hledger/Web/Handler/StatementsR.hs b/hledger-web/Hledger/Web/Handler/StatementsR.hs index dc112d22380..e7c756c9d60 100644 --- a/hledger-web/Hledger/Web/Handler/StatementsR.hs +++ b/hledger-web/Hledger/Web/Handler/StatementsR.hs @@ -33,12 +33,12 @@ import Hledger.Write.Spreadsheet qualified as Spr import Hledger.Web.Import import Hledger.Web.Widget.AddForm (addModal) import Hledger.Web.Paging (yearsRow) -import Hledger.Web.Param (Param(..), accumParam, calcParam, listParam, paramLinks, paramSettings, sortParam) +import Hledger.Web.Param (Param(..), paramLinks, paramSettings) import Hledger.Web.ReportPage import Hledger.Web.WebOptions import Hledger.Web.Widget.Chart (reportChart) import Hledger.Web.Widget.Common - (amountLinks, columnsLinks, commodityLinks, controlsToggle, optionsSummary, + (amountLinks, columnsLinks, commodityLinks, controlsToggle, depthLinks, equityLinks, helplink, lotsLinks, percentLinks, pricesLinks, realLinks, statusLinks, zeroBalanceLinks) diff --git a/hledger-web/Hledger/Web/Param.hs b/hledger-web/Hledger/Web/Param.hs index cb70a7f1c91..ef0a4be964c 100644 --- a/hledger-web/Hledger/Web/Param.hs +++ b/hledger-web/Hledger/Web/Param.hs @@ -1,8 +1,9 @@ {-| -The report pages' rows of links, and their multiple-choice URL -parameters, such as calc: each one's name, modes, URL words, and labels, -written once, from which its parser, its row of links, the parameters -that carry it, and its name in the options summary are made. +The report pages' rows of links, and the generic part of their +multiple-choice URL parameters: a parameter's name, modes, URL words, +and labels, written once (the parameters themselves are in +"Hledger.Web.ReportPage"), from which its parser, its row of links, the +parameters that carry it, and its name in the options summary are made. -} {-# LANGUAGE LambdaCase #-} @@ -19,10 +20,6 @@ module Hledger.Web.Param , paramSettings , paramLinks , paramPhrase - , accumParam - , calcParam - , listParam - , sortParam ) where import Control.Monad (unless) @@ -34,8 +31,7 @@ import Text.Blaze.Html5 qualified as H import Text.Blaze.Html5.Attributes qualified as A import Yesod (HtmlUrl, MonadHandler, lookupGetParam) -import Hledger -import Hledger.Utils.I18n (Translations, tr, trc) +import Hledger.Utils.I18n (Translations) -- | A row of links above a report: a label, then each link's label, -- title, target, and whether it is the one being shown. @@ -122,79 +118,3 @@ paramLinks p trs route kept dflt current = -- the closed options disclosure lists it. paramPhrase :: Param a -> Translations -> Text -> Maybe Text paramPhrase p trs w = fst . paramLabel p trs <$> find ((== w) . paramWord p) (paramModes p) - --- | The accum parameter: whether a report shows balance changes, ending --- balances, or cumulative totals; absent for the page's own default. --- The H key toggles Ending balances, the second link (hledger.js). -accumParam :: Param BalanceAccumulation -accumParam = Param - { paramName = "accum" - , paramModes = [PerPeriod, Historical, Cumulative] - , paramWord = \case - PerPeriod -> "change" - Historical -> "historical" - Cumulative -> "cumulative" - -- TRANSLATORS: the label before a report's accumulation mode links, and the links' text and tooltips. - , paramRowLabel = \trs -> tr trs "Show:" - , paramLabel = \trs -> \case - PerPeriod -> (tr trs "Balance changes", tr trs "Show how much each balance changed in each period") - Historical -> (tr trs "Ending balances", tr trs "Show each balance at the end of each period, including everything before it") - Cumulative -> (tr trs "Cumulative totals", tr trs "Show each balance's change since the start of the report (--cumulative)") - } - --- | The calc parameter: what a report's cells calculate, as the balance --- commands' --valuechange, --gain, and --count flags choose. -calcParam :: Param BalanceCalculation -calcParam = Param - { paramName = "calc" - , paramModes = [CalcChange, CalcValueChange, CalcGain, CalcPostingsCount] - , paramWord = \case - CalcChange -> "change" - CalcValueChange -> "valuechange" - CalcGain -> "gain" - CalcPostingsCount -> "count" - -- Not offered (not in paramModes), so never in a url. - _ -> "" - -- TRANSLATORS: the label before a report's calculation links, and the links' text and tooltips. - , paramRowLabel = \trs -> tr trs "Calculate:" - , paramLabel = \trs -> \case - CalcChange -> (trc trs "calculation" "Sums", tr trs "Show sums of postings") - CalcValueChange -> (tr trs "Value change", tr trs "Show how period-end market values changed (--valuechange)") - CalcGain -> (tr trs "Unrealized gain", tr trs "Show unrealized capital gains: market value minus cost (--gain)") - CalcPostingsCount -> (tr trs "Posting counts", tr trs "Count the postings instead of summing them (--count)") - _ -> ("", "") - } - --- | The list parameter: show accounts as a flat list or a tree; absent --- for the page's default, the startup one. The t key toggles them --- (hledger.js). -listParam :: Param AccountListMode -listParam = Param - { paramName = "list" - , paramModes = [ALFlat, ALTree] - , paramWord = \case - ALFlat -> "flat" - ALTree -> "tree" - -- TRANSLATORS: the label before a report's list/tree links, and the links' text and tooltips. - , paramRowLabel = \trs -> tr trs "Accounts:" - , paramLabel = \trs -> \case - ALFlat -> (trc trs "accounts" "List", tr trs "Show accounts as a flat list (--flat)") - ALTree -> (trc trs "accounts" "Tree", tr trs "Show accounts as a tree (--tree)") - } - --- | The sort parameter: whether rows are sorted by amount, rather than --- by account display order (declaration order, otherwise name). --- The S key toggles By amount, the second link (hledger.js). -sortParam :: Param Bool -sortParam = Param - { paramName = "sort" - , paramModes = [False, True] - , paramWord = \case - False -> "account" - True -> "amount" - -- TRANSLATORS: the label before a report's sort links, and the links' text and tooltips. - , paramRowLabel = \trs -> tr trs "Sort:" - , paramLabel = \trs -> \case - False -> (tr trs "By account", tr trs "Sort rows by account display order") - True -> (tr trs "By amount", tr trs "Sort rows by their amounts, largest first (-S)") - } diff --git a/hledger-web/Hledger/Web/ReportPage.hs b/hledger-web/Hledger/Web/ReportPage.hs index a82f2535d1a..05a872aec2a 100644 --- a/hledger-web/Hledger/Web/ReportPage.hs +++ b/hledger-web/Hledger/Web/ReportPage.hs @@ -21,6 +21,12 @@ module Hledger.Web.ReportPage ( AmountMode(..), parseValue, readParam, + accumParam, + calcParam, + listParam, + sortParam, + optionsSummary, + registerKeptParams, valueWord, amountModeOf, setAmountMode, @@ -42,12 +48,13 @@ module Hledger.Web.ReportPage ( ) where import Control.Exception qualified as E -import Control.Monad (mfilter, unless) +import Control.Monad (guard, mfilter, unless) import Data.Foldable (find, for_, traverse_) -import Data.List (mapAccumL, stripPrefix) -import Data.Maybe (fromMaybe, listToMaybe) +import Data.List (elemIndex, mapAccumL, sortOn, stripPrefix) +import Data.Maybe (fromMaybe, listToMaybe, mapMaybe) import Data.Text.Encoding qualified as TE import Network.HTTP.Types.URI (urlEncode) +import Safe (readMay) import Data.Text (Text) import Data.Text qualified as T import Data.Set qualified as Set @@ -62,7 +69,7 @@ import Yesod (HtmlUrl) import Hledger.Utils.I18n (Translations, tr, trc, trf) import Hledger import Hledger.Cli.Anchor (dateTerm, renderPeriodHeading) -import Hledger.Web.Param (Param(..), accumParam, calcParam, listParam, sortParam, linksRowClass, paramSettings, parseParam) +import Hledger.Web.Param (Param(..), linksRowClass, paramPhrase, paramSettings, parseParam) import Hledger.Web.Widget.Common (AmountMode(..), removeDates, valueWord) import Hledger.Query qualified as Query import Hledger.Write.Html (Html, formatCell, nl) @@ -320,6 +327,135 @@ parseFlag name = \case readParam :: Param a -> Maybe Text -> Either ReportParamError (Maybe a) readParam p = either (Left . BadParamValue (paramName p)) Right . parseParam p +-- | The accum parameter: whether a report shows balance changes, ending +-- balances, or cumulative totals; absent for the page's own default. +-- The H key toggles Ending balances, the second link (hledger.js). +accumParam :: Param BalanceAccumulation +accumParam = Param + { paramName = "accum" + , paramModes = [PerPeriod, Historical, Cumulative] + , paramWord = \case + PerPeriod -> "change" + Historical -> "historical" + Cumulative -> "cumulative" + -- TRANSLATORS: the label before a report's accumulation mode links, and the links' text and tooltips. + , paramRowLabel = \trs -> tr trs "Show:" + , paramLabel = \trs -> \case + PerPeriod -> (tr trs "Balance changes", tr trs "Show how much each balance changed in each period") + Historical -> (tr trs "Ending balances", tr trs "Show each balance at the end of each period, including everything before it") + Cumulative -> (tr trs "Cumulative totals", tr trs "Show each balance's change since the start of the report (--cumulative)") + } + +-- | The calc parameter: what a report's cells calculate, as the balance +-- commands' --valuechange, --gain, and --count flags choose. +calcParam :: Param BalanceCalculation +calcParam = Param + { paramName = "calc" + , paramModes = [CalcChange, CalcValueChange, CalcGain, CalcPostingsCount] + , paramWord = \case + CalcChange -> "change" + CalcValueChange -> "valuechange" + CalcGain -> "gain" + CalcPostingsCount -> "count" + -- Not offered (not in paramModes), so never in a url. + _ -> "" + -- TRANSLATORS: the label before a report's calculation links, and the links' text and tooltips. + , paramRowLabel = \trs -> tr trs "Calculate:" + , paramLabel = \trs -> \case + CalcChange -> (trc trs "calculation" "Sums", tr trs "Show sums of postings") + CalcValueChange -> (tr trs "Value change", tr trs "Show how period-end market values changed (--valuechange)") + CalcGain -> (tr trs "Unrealized gain", tr trs "Show unrealized capital gains: market value minus cost (--gain)") + CalcPostingsCount -> (tr trs "Posting counts", tr trs "Count the postings instead of summing them (--count)") + _ -> ("", "") + } + +-- | The list parameter: show accounts as a flat list or a tree; absent +-- for the page's default, the startup one. The t key toggles them +-- (hledger.js). +listParam :: Param AccountListMode +listParam = Param + { paramName = "list" + , paramModes = [ALFlat, ALTree] + , paramWord = \case + ALFlat -> "flat" + ALTree -> "tree" + -- TRANSLATORS: the label before a report's list/tree links, and the links' text and tooltips. + , paramRowLabel = \trs -> tr trs "Accounts:" + , paramLabel = \trs -> \case + ALFlat -> (trc trs "accounts" "List", tr trs "Show accounts as a flat list (--flat)") + ALTree -> (trc trs "accounts" "Tree", tr trs "Show accounts as a tree (--tree)") + } + +-- | The sort parameter: whether rows are sorted by amount, rather than +-- by account display order (declaration order, otherwise name). +-- The S key toggles By amount, the second link (hledger.js). +sortParam :: Param Bool +sortParam = Param + { paramName = "sort" + , paramModes = [False, True] + , paramWord = \case + False -> "account" + True -> "amount" + -- TRANSLATORS: the label before a report's sort links, and the links' text and tooltips. + , paramRowLabel = \trs -> tr trs "Sort:" + , paramLabel = \trs -> \case + False -> (tr trs "By account", tr trs "Sort rows by account display order") + True -> (tr trs "By amount", tr trs "Sort rows by their amounts, largest first (-S)") + } + +-- | Of the parameters the page links keep, those the sidebar's register +-- links keep: the states the register reads, ie the depth limit (which +-- clips its sidebar), the amounts mode, the accounts mode, inferred +-- prices, zero balances, and lot detail. Each such link rewrites the +-- search itself. +registerKeptParams :: [(Text, Text)] -> [(Text, Text)] +registerKeptParams ps = [p | p@(k, _) <- ps, k `elem` ["depth", "value", paramName listParam, "infer", "empty", "lots"]] + +-- | The report options a page's parameters set, as short phrases for the +-- closed controls disclosure: the controls' own words where those stand +-- alone ("Monthly", "Tree"), a phrase where a control's word would not +-- ("Shown"). The pages' links carry only the options not at their +-- defaults, so these are the options in effect, listed in the order of +-- the controls' rows. The filters are not here: they are search terms, +-- shown in the search box. A depth limit at or beyond the given +-- deepest account's depth is not one: the Depth links show it as none. +optionsSummary :: Translations -> Int -> [(Text, Text)] -> [Text] +optionsSummary trs deepest = mapMaybe phrase . sortOn (rowOrder . fst) + where + rowOrder k = fromMaybe maxBound $ elemIndex k + ["equity", "interval", paramName accumParam, "depth", paramName listParam, "value", "infer", "empty", "lots", "closed", + "total", "avg", "costs", paramName sortParam, "pct", paramName calcParam, "date2"] + phrase = \case + ("interval", w) -> Just $ fromMaybe w $ lookup w + [ ("yearly", tr trs "Yearly"), ("quarterly", tr trs "Quarterly"), ("monthly", tr trs "Monthly") + , ("weekly", tr trs "Weekly"), ("daily", tr trs "Daily") ] + -- TRANSLATORS: the depth limit, in the list of options in effect. + ("depth", n) -> do + d <- readMay (T.unpack n) :: Maybe Int + guard (d < deepest) + Just $ trf trs "Depth {depth}" [("depth", n)] + (k, w) | k == paramName accumParam -> paramPhrase accumParam trs w + ("value", "none") -> Just $ tr trs "As recorded" + ("value", "cost") -> Just $ trc trs "amounts" "Cost" + ("value", _) -> Just $ trc trs "amounts" "Value" + (k, w) | k == paramName listParam -> paramPhrase listParam trs w + (k, w) | k == paramName sortParam -> paramPhrase sortParam trs w + ("pct", "1") -> Just $ tr trs "Percentages" + (k, w) | k == paramName calcParam -> paramPhrase calcParam trs w + -- TRANSLATORS: options in effect, listed on the closed options disclosure. + ("total", "1") -> Just $ trc trs "column" "Total" + ("avg", "1") -> Just $ trc trs "column" "Average" + ("infer", "1") -> Just $ tr trs "Inferred prices" + ("empty", "0") -> Just $ tr trs "Zero balances hidden" + ("empty", "1") -> Just $ tr trs "Zero balances shown" + ("lots", "1") -> Just $ tr trs "Lots shown" + ("costs", "1") -> Just $ tr trs "Costs shown" + ("closed", "1") -> Just $ tr trs "Closed positions shown" + ("closed", "0") -> Just $ tr trs "Closed positions hidden" + ("date2", "1") -> Just $ tr trs "Secondary dates" + ("equity", "1") -> Just $ tr trs "Equity shown" + _ -> Nothing + -- | The value parameter, mirroring --value's WHEN[,COMM] syntax: -- "none", "cost", or a valuation "end", "then", "now", or a date, each -- optionally with a commodity to convert to (end,EUR = -X EUR). None diff --git a/hledger-web/Hledger/Web/Test.hs b/hledger-web/Hledger/Web/Test.hs index 2ef391fd5bd..fcf9db0ddba 100644 --- a/hledger-web/Hledger/Web/Test.hs +++ b/hledger-web/Hledger/Web/Test.hs @@ -65,11 +65,11 @@ import Web.Cookie (defaultSetCookie, setCookieName, setCookieValue) import Hledger.Web.Application ( makeAppWith ) import Hledger.Utils.I18n (noTranslations) import Hledger.Web.Paging (pageNumbers) -import Hledger.Web.Param (Param(..), accumParam, calcParam, listParam, parseParam, sortParam) -import Hledger.Web.ReportPage (intervalPeriodExpr, startupUrlState) +import Hledger.Web.Param (Param(..), parseParam) +import Hledger.Web.ReportPage (accumParam, calcParam, intervalPeriodExpr, listParam, optionsSummary, sortParam, startupUrlState) import Hledger.Web.WebOptions -- ( WebOpts(..), defwebopts, prognameandversion ) import Hledger.Web.Import hiding (get, j) -import Hledger.Web.Widget.Common (MovedOptions(..), normalisedSearch, optionsSummary, splitPeriodExpr, transactionFragment) +import Hledger.Web.Widget.Common (MovedOptions(..), normalisedSearch, splitPeriodExpr, transactionFragment) import Hledger.Cli hiding (prognameandversion) diff --git a/hledger-web/Hledger/Web/Widget/Common.hs b/hledger-web/Hledger/Web/Widget/Common.hs index af5445eac33..55244c0eaae 100644 --- a/hledger-web/Hledger/Web/Widget/Common.hs +++ b/hledger-web/Hledger/Web/Widget/Common.hs @@ -10,7 +10,6 @@ module Hledger.Web.Widget.Common , balanceReportAsHtml , controlsHint , controlsToggle - , optionsSummary , searchHeading , inertControls , pricesLinks @@ -49,13 +48,13 @@ module Hledger.Web.Widget.Common ) where import Control.Applicative ((<|>)) -import Control.Monad (guard, when) +import Control.Monad (when) import Control.Monad.Except (ExceptT, mapExceptT) import Data.Char (isDigit) import Data.Foldable (find, for_) -import Data.List (elemIndex, sortOn) +import Data.List (elemIndex) import Data.Set qualified as Set -import Data.Maybe (fromMaybe, isJust, isNothing, listToMaybe, mapMaybe, maybeToList) +import Data.Maybe (isJust, isNothing, listToMaybe, mapMaybe, maybeToList) import Data.Text (Text) import Data.Text qualified as T import Data.Time.Calendar (Day) @@ -74,7 +73,7 @@ import Hledger.Utils.I18n (Translations, tr, trc, trf) import Hledger import Hledger.Cli.Anchor qualified as Anchor import Hledger.Cli.Utils (writeFileWithBackupIfChanged) -import Hledger.Web.Param (accumParam, calcParam, listParam, sortParam, linksRow, linksRowClass, paramName, paramPhrase) +import Hledger.Web.Param (linksRow, linksRowClass) import Hledger.Web.Settings (manualurl) import Hledger.Query qualified as Query @@ -116,20 +115,14 @@ helplink :: Text -> Text -> HtmlUrl r helplink topic label _ = H.a ! A.href u ! A.target "hledgerhelp" $ toHtml label where u = textValue $ manualurl <> if T.null topic then "" else T.cons '#' topic --- | Of the parameters the page links keep, those the sidebar's register --- links keep: the states the register reads, ie the depth limit (which --- clips its sidebar), the amounts mode, the accounts mode, inferred --- prices, zero balances, and lot detail. Each such link rewrites the --- search itself. -registerKeptParams :: [(Text, Text)] -> [(Text, Text)] -registerKeptParams ps = [p | p@(k, _) <- ps, k `elem` ["depth", "value", paramName listParam, "infer", "empty", "lots"]] - -- | Render a "BalanceReport" as the sidebar: the page links (each page's -- route, label, and title, with the parameters their links carry), then --- the accounts, linking to their registers. The current page's row is marked. +-- the accounts, linking to their registers with the given parameters +-- (see 'Hledger.Web.ReportPage.registerKeptParams'). The current page's +-- row is marked. balanceReportAsHtml :: - Eq r => r -> r -> [(r, Text, Text)] -> [(Text, Text)] -> Bool -> Text -> Text -> Translations -> Journal -> Text -> Maybe (AccountName, Bool) -> BalanceReport -> HtmlUrl r -balanceReportAsHtml registerR here reports reportParams hideEmpty totlabel tottitle trs j qparam maccount (items, total) = + Eq r => r -> r -> [(r, Text, Text)] -> [(Text, Text)] -> [(Text, Text)] -> Bool -> Text -> Text -> Translations -> Journal -> Text -> Maybe (AccountName, Bool) -> BalanceReport -> HtmlUrl r +balanceReportAsHtml registerR here reports reportParams kept hideEmpty totlabel tottitle trs j qparam maccount (items, total) = $(hamletFile "templates/balance-report.hamlet") where l = ledgerFromJournal Any j @@ -147,7 +140,6 @@ balanceReportAsHtml registerR here reports reportParams hideEmpty totlabel totti -- displays such balances as zero. where isInteresting a = not (all (mixedAmountLooksZero . mixedAmountStripCosts . bdexcludingsubs) . pdperiods $ adata a) || any isInteresting (asubs a) matchesAcctSelector acct = maybe False ((`matchesAccount` acct) . accountRegisterQuery) maccount - kept = registerKeptParams reportParams qps = [("q", qparam) | not (T.null qparam)] acctlink acct = (registerR, qps ++ accountParams True acct ++ kept) acctonlylink acct = (registerR, qps ++ accountParams False acct ++ kept) @@ -174,51 +166,6 @@ controlsToggle trs open summary rows = ^{rows} |] --- | The report options a page's parameters set, as short phrases for the --- closed controls disclosure: the controls' own words where those stand --- alone ("Monthly", "Tree"), a phrase where a control's word would not --- ("Shown"). The pages' links carry only the options not at their --- defaults, so these are the options in effect, listed in the order of --- the controls' rows. The filters are not here: they are search terms, --- shown in the search box. A depth limit at or beyond the given --- deepest account's depth is not one: the Depth links show it as none. -optionsSummary :: Translations -> Int -> [(Text, Text)] -> [Text] -optionsSummary trs deepest = mapMaybe phrase . sortOn (rowOrder . fst) - where - rowOrder k = fromMaybe maxBound $ elemIndex k - ["equity", "interval", paramName accumParam, "depth", paramName listParam, "value", "infer", "empty", "lots", "closed", - "total", "avg", "costs", paramName sortParam, "pct", paramName calcParam, "date2"] - phrase = \case - ("interval", w) -> Just $ fromMaybe w $ lookup w - [ ("yearly", tr trs "Yearly"), ("quarterly", tr trs "Quarterly"), ("monthly", tr trs "Monthly") - , ("weekly", tr trs "Weekly"), ("daily", tr trs "Daily") ] - -- TRANSLATORS: the depth limit, in the list of options in effect. - ("depth", n) -> do - d <- readMay (T.unpack n) :: Maybe Int - guard (d < deepest) - Just $ trf trs "Depth {depth}" [("depth", n)] - (k, w) | k == paramName accumParam -> paramPhrase accumParam trs w - ("value", "none") -> Just $ tr trs "As recorded" - ("value", "cost") -> Just $ trc trs "amounts" "Cost" - ("value", _) -> Just $ trc trs "amounts" "Value" - (k, w) | k == paramName listParam -> paramPhrase listParam trs w - (k, w) | k == paramName sortParam -> paramPhrase sortParam trs w - ("pct", "1") -> Just $ tr trs "Percentages" - (k, w) | k == paramName calcParam -> paramPhrase calcParam trs w - -- TRANSLATORS: options in effect, listed on the closed options disclosure. - ("total", "1") -> Just $ trc trs "column" "Total" - ("avg", "1") -> Just $ trc trs "column" "Average" - ("infer", "1") -> Just $ tr trs "Inferred prices" - ("empty", "0") -> Just $ tr trs "Zero balances hidden" - ("empty", "1") -> Just $ tr trs "Zero balances shown" - ("lots", "1") -> Just $ tr trs "Lots shown" - ("costs", "1") -> Just $ tr trs "Costs shown" - ("closed", "1") -> Just $ tr trs "Closed positions shown" - ("closed", "0") -> Just $ tr trs "Closed positions hidden" - ("date2", "1") -> Just $ tr trs "Secondary dates" - ("equity", "1") -> Just $ tr trs "Equity shown" - _ -> Nothing - -- | A journal or register page's heading: the given title, then the -- search's dates, if it has any, shown as the balance pages show theirs -- (eg "General Journal in 2024"), then ", filtered" if it has other