Small build updates (#3546)
* Sites API * Extract Revenue react api helpers * !fixup * Extract JS Money module to /extra * Extract Revenue full build extras (tests pass for full) * Update MIX_ENV=small mix test * Remove dead code * Add moduledocs * Add credo config * Trick dialyzer * DRY revenue metrics * Use more concise version of on_full_build macro * Disable credo checkpull/3547/head
parent
af0b97e68a
commit
88e1d9dc28
@ -0,0 +1,205 @@
|
||||
# This file contains the configuration for Credo and you are probably reading
|
||||
# this after creating it with `mix credo.gen.config`.
|
||||
#
|
||||
# If you find anything wrong or unclear in this file, please report an
|
||||
# issue on GitHub: https://github.com/rrrene/credo/issues
|
||||
#
|
||||
%{
|
||||
#
|
||||
# You can have as many configs as you like in the `configs:` field.
|
||||
configs: [
|
||||
%{
|
||||
#
|
||||
# Run any config using `mix credo -C <name>`. If no config name is given
|
||||
# "default" is used.
|
||||
#
|
||||
name: "default",
|
||||
#
|
||||
# These are the files included in the analysis:
|
||||
files: %{
|
||||
#
|
||||
# You can give explicit globs or simply directories.
|
||||
# In the latter case `**/*.{ex,exs}` will be used.
|
||||
#
|
||||
included: [
|
||||
"lib/",
|
||||
"test/",
|
||||
"extra/"
|
||||
],
|
||||
excluded: [~r"/_build/", ~r"/deps/", ~r"/node_modules/"]
|
||||
},
|
||||
#
|
||||
# Load and configure plugins here:
|
||||
#
|
||||
plugins: [],
|
||||
#
|
||||
# If you create your own checks, you must specify the source files for
|
||||
# them here, so they can be loaded by Credo before running the analysis.
|
||||
#
|
||||
requires: [],
|
||||
#
|
||||
# If you want to enforce a style guide and need a more traditional linting
|
||||
# experience, you can change `strict` to `true` below:
|
||||
#
|
||||
strict: false,
|
||||
#
|
||||
# To modify the timeout for parsing files, change this value:
|
||||
#
|
||||
parse_timeout: 5000,
|
||||
#
|
||||
# If you want to use uncolored output by default, you can change `color`
|
||||
# to `false` below:
|
||||
#
|
||||
color: true,
|
||||
#
|
||||
# You can customize the parameters of any check by adding a second element
|
||||
# to the tuple.
|
||||
#
|
||||
# To disable a check put `false` as second element:
|
||||
#
|
||||
# {Credo.Check.Design.DuplicatedCode, false}
|
||||
#
|
||||
checks: %{
|
||||
enabled: [
|
||||
#
|
||||
## Consistency Checks
|
||||
#
|
||||
{Credo.Check.Consistency.ExceptionNames, []},
|
||||
{Credo.Check.Consistency.LineEndings, []},
|
||||
{Credo.Check.Consistency.ParameterPatternMatching, []},
|
||||
{Credo.Check.Consistency.SpaceAroundOperators, []},
|
||||
{Credo.Check.Consistency.SpaceInParentheses, []},
|
||||
{Credo.Check.Consistency.TabsOrSpaces, []},
|
||||
|
||||
#
|
||||
## Design Checks
|
||||
#
|
||||
# You can customize the priority of any check
|
||||
# Priority values are: `low, normal, high, higher`
|
||||
#
|
||||
{Credo.Check.Design.AliasUsage,
|
||||
[priority: :low, if_nested_deeper_than: 2, if_called_more_often_than: 0]},
|
||||
# You can also customize the exit_status of each check.
|
||||
# If you don't want TODO comments to cause `mix credo` to fail, just
|
||||
# set this value to 0 (zero).
|
||||
#
|
||||
{Credo.Check.Design.TagTODO, [exit_status: 2]},
|
||||
{Credo.Check.Design.TagFIXME, []},
|
||||
|
||||
#
|
||||
## Readability Checks
|
||||
#
|
||||
{Credo.Check.Readability.AliasOrder, []},
|
||||
{Credo.Check.Readability.FunctionNames, []},
|
||||
{Credo.Check.Readability.LargeNumbers, []},
|
||||
{Credo.Check.Readability.MaxLineLength, [priority: :low, max_length: 120]},
|
||||
{Credo.Check.Readability.ModuleAttributeNames, []},
|
||||
{Credo.Check.Readability.ModuleDoc, []},
|
||||
{Credo.Check.Readability.ModuleNames, []},
|
||||
{Credo.Check.Readability.ParenthesesInCondition, []},
|
||||
{Credo.Check.Readability.ParenthesesOnZeroArityDefs, []},
|
||||
{Credo.Check.Readability.PipeIntoAnonymousFunctions, []},
|
||||
{Credo.Check.Readability.PredicateFunctionNames, []},
|
||||
{Credo.Check.Readability.PreferImplicitTry, []},
|
||||
{Credo.Check.Readability.RedundantBlankLines, []},
|
||||
{Credo.Check.Readability.Semicolons, []},
|
||||
{Credo.Check.Readability.SpaceAfterCommas, []},
|
||||
{Credo.Check.Readability.StringSigils, []},
|
||||
{Credo.Check.Readability.TrailingBlankLine, []},
|
||||
{Credo.Check.Readability.TrailingWhiteSpace, []},
|
||||
{Credo.Check.Readability.UnnecessaryAliasExpansion, []},
|
||||
{Credo.Check.Readability.VariableNames, []},
|
||||
{Credo.Check.Readability.WithSingleClause, []},
|
||||
|
||||
#
|
||||
## Refactoring Opportunities
|
||||
#
|
||||
{Credo.Check.Refactor.Apply, []},
|
||||
{Credo.Check.Refactor.CondStatements, []},
|
||||
{Credo.Check.Refactor.CyclomaticComplexity, []},
|
||||
{Credo.Check.Refactor.FunctionArity, []},
|
||||
{Credo.Check.Refactor.LongQuoteBlocks, []},
|
||||
{Credo.Check.Refactor.MatchInCondition, []},
|
||||
{Credo.Check.Refactor.MapJoin, []},
|
||||
{Credo.Check.Refactor.NegatedConditionsInUnless, []},
|
||||
{Credo.Check.Refactor.NegatedConditionsWithElse, false},
|
||||
{Credo.Check.Refactor.Nesting, []},
|
||||
{Credo.Check.Refactor.UnlessWithElse, []},
|
||||
{Credo.Check.Refactor.WithClauses, []},
|
||||
{Credo.Check.Refactor.FilterFilter, []},
|
||||
{Credo.Check.Refactor.RejectReject, []},
|
||||
{Credo.Check.Refactor.RedundantWithClauseResult, []},
|
||||
|
||||
#
|
||||
## Warnings
|
||||
#
|
||||
{Credo.Check.Warning.ApplicationConfigInModuleAttribute, []},
|
||||
{Credo.Check.Warning.BoolOperationOnSameValues, []},
|
||||
{Credo.Check.Warning.ExpensiveEmptyEnumCheck, []},
|
||||
{Credo.Check.Warning.IExPry, []},
|
||||
{Credo.Check.Warning.IoInspect, []},
|
||||
{Credo.Check.Warning.OperationOnSameValues, []},
|
||||
{Credo.Check.Warning.OperationWithConstantResult, []},
|
||||
{Credo.Check.Warning.RaiseInsideRescue, []},
|
||||
{Credo.Check.Warning.SpecWithStruct, []},
|
||||
{Credo.Check.Warning.WrongTestFileExtension, []},
|
||||
{Credo.Check.Warning.UnusedEnumOperation, []},
|
||||
{Credo.Check.Warning.UnusedFileOperation, []},
|
||||
{Credo.Check.Warning.UnusedKeywordOperation, []},
|
||||
{Credo.Check.Warning.UnusedListOperation, []},
|
||||
{Credo.Check.Warning.UnusedPathOperation, []},
|
||||
{Credo.Check.Warning.UnusedRegexOperation, []},
|
||||
{Credo.Check.Warning.UnusedStringOperation, []},
|
||||
{Credo.Check.Warning.UnusedTupleOperation, []},
|
||||
{Credo.Check.Warning.UnsafeExec, []}
|
||||
],
|
||||
disabled: [
|
||||
#
|
||||
# Checks scheduled for next check update (opt-in for now, just replace `false` with `[]`)
|
||||
|
||||
#
|
||||
# Controversial and experimental checks (opt-in, just move the check to `:enabled`
|
||||
# and be sure to use `mix credo --strict` to see low priority checks)
|
||||
#
|
||||
{Credo.Check.Consistency.MultiAliasImportRequireUse, []},
|
||||
{Credo.Check.Consistency.UnusedVariableNames, []},
|
||||
{Credo.Check.Design.DuplicatedCode, []},
|
||||
{Credo.Check.Design.SkipTestWithoutComment, []},
|
||||
{Credo.Check.Readability.AliasAs, []},
|
||||
{Credo.Check.Readability.BlockPipe, []},
|
||||
{Credo.Check.Readability.ImplTrue, []},
|
||||
{Credo.Check.Readability.MultiAlias, []},
|
||||
{Credo.Check.Readability.NestedFunctionCalls, []},
|
||||
{Credo.Check.Readability.SeparateAliasRequire, []},
|
||||
{Credo.Check.Readability.SingleFunctionToBlockPipe, []},
|
||||
{Credo.Check.Readability.SinglePipe, []},
|
||||
{Credo.Check.Readability.Specs, []},
|
||||
{Credo.Check.Readability.StrictModuleLayout, []},
|
||||
{Credo.Check.Readability.WithCustomTaggedTuple, []},
|
||||
{Credo.Check.Refactor.ABCSize, []},
|
||||
{Credo.Check.Refactor.AppendSingleItem, []},
|
||||
{Credo.Check.Refactor.DoubleBooleanNegation, []},
|
||||
{Credo.Check.Refactor.FilterReject, []},
|
||||
{Credo.Check.Refactor.IoPuts, []},
|
||||
{Credo.Check.Refactor.MapMap, []},
|
||||
{Credo.Check.Refactor.ModuleDependencies, []},
|
||||
{Credo.Check.Refactor.NegatedIsNil, []},
|
||||
{Credo.Check.Refactor.PipeChainStart, []},
|
||||
{Credo.Check.Refactor.RejectFilter, []},
|
||||
{Credo.Check.Refactor.VariableRebinding, []},
|
||||
{Credo.Check.Warning.LazyLogging, []},
|
||||
{Credo.Check.Warning.LeakyEnvironment, []},
|
||||
{Credo.Check.Warning.MapGetUnsafePass, []},
|
||||
{Credo.Check.Warning.MixEnv, []},
|
||||
{Credo.Check.Warning.UnsafeToAtom, []}
|
||||
|
||||
# {Credo.Check.Refactor.MapInto, []},
|
||||
|
||||
#
|
||||
# Custom checks can be created using `mix credo.gen.check`.
|
||||
#
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@ -1,199 +0,0 @@
|
||||
import React from 'react';
|
||||
import { Link } from 'react-router-dom'
|
||||
|
||||
import * as storage from '../../util/storage'
|
||||
import Bar from '../bar'
|
||||
import numberFormatter from '../../util/number-formatter'
|
||||
import * as api from '../../api'
|
||||
import Money from './money'
|
||||
import { isValidHttpUrl, trimURL } from '../../util/url'
|
||||
|
||||
const MOBILE_UPPER_WIDTH = 767
|
||||
const DEFAULT_WIDTH = 1080
|
||||
const BREAKDOWN_LIMIT = 100
|
||||
|
||||
export default class PropertyBreakdown extends React.Component {
|
||||
constructor(props) {
|
||||
super(props)
|
||||
let propKey = props.goal.prop_names[0]
|
||||
this.storageKey = 'goalPropTab__' + props.site.domain + props.goal.name
|
||||
const storedKey = storage.getItem(this.storageKey)
|
||||
if (props.goal.prop_names.includes(storedKey)) {
|
||||
propKey = storedKey
|
||||
}
|
||||
if (props.query.filters['props']) {
|
||||
propKey = Object.keys(props.query.filters['props'])[0]
|
||||
}
|
||||
|
||||
this.state = {
|
||||
loading: true,
|
||||
propKey: propKey,
|
||||
viewport: DEFAULT_WIDTH,
|
||||
breakdown: [],
|
||||
page: 1,
|
||||
moreResultsAvailable: false
|
||||
}
|
||||
|
||||
this.handleResize = this.handleResize.bind(this);
|
||||
this.fetch = this.fetch.bind(this)
|
||||
this.fetchAndReplace = this.fetchAndReplace.bind(this)
|
||||
this.fetchAndConcat = this.fetchAndConcat.bind(this)
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
window.addEventListener('resize', this.handleResize, false);
|
||||
|
||||
this.handleResize();
|
||||
this.fetchAndReplace()
|
||||
|
||||
if (this.props.query.period === 'realtime') {
|
||||
document.addEventListener('tick', this.fetchAndReplace)
|
||||
}
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
window.removeEventListener('resize', this.handleResize, false);
|
||||
document.removeEventListener('tick', this.fetchAndReplace)
|
||||
}
|
||||
|
||||
handleResize() {
|
||||
this.setState({ viewport: window.innerWidth });
|
||||
}
|
||||
|
||||
fetch({ concat }) {
|
||||
if (!this.props.query.filters['goal']) return
|
||||
|
||||
api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/property/${encodeURIComponent(this.state.propKey)}`, this.props.query, { limit: BREAKDOWN_LIMIT, page: this.state.page })
|
||||
.then((res) => {
|
||||
let breakdown = concat ? this.state.breakdown.concat(res) : res
|
||||
|
||||
this.setState(() => ({
|
||||
loading: false,
|
||||
breakdown: breakdown,
|
||||
moreResultsAvailable: res.length >= BREAKDOWN_LIMIT
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
fetchAndReplace() {
|
||||
this.fetch({ concat: false })
|
||||
}
|
||||
|
||||
fetchAndConcat() {
|
||||
this.fetch({ concat: true })
|
||||
}
|
||||
|
||||
loadMore() {
|
||||
this.setState({ loading: true, page: this.state.page + 1 }, this.fetchAndConcat.bind(this))
|
||||
}
|
||||
|
||||
renderUrl(value) {
|
||||
if (isValidHttpUrl(value.name)) {
|
||||
return (
|
||||
<a target="_blank" href={value.name} rel="noreferrer" className="hidden group-hover:block">
|
||||
<svg className="inline h-4 w-4 ml-1 -mt-1 text-gray-600 dark:text-gray-400" fill="currentColor" viewBox="0 0 20 20"><path d="M11 3a1 1 0 100 2h2.586l-6.293 6.293a1 1 0 101.414 1.414L15 6.414V9a1 1 0 102 0V4a1 1 0 00-1-1h-5z"></path><path d="M5 5a2 2 0 00-2 2v8a2 2 0 002 2h8a2 2 0 002-2v-3a1 1 0 10-2 0v3H5V7h3a1 1 0 000-2H5z"></path></svg>
|
||||
</a>
|
||||
)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
renderPropContent(value, query) {
|
||||
return (
|
||||
<span className="flex px-2 py-1.5 group dark:text-gray-300 relative z-9 break-all">
|
||||
<Link
|
||||
to={{ pathname: window.location.pathname, search: query.toString() }}
|
||||
className="md:truncate hover:underline block"
|
||||
>
|
||||
{trimURL(value.name, 100)}
|
||||
</Link>
|
||||
{this.renderUrl(value)}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
renderPropValue(value) {
|
||||
const query = new URLSearchParams(window.location.search)
|
||||
query.set('props', JSON.stringify({ [this.state.propKey]: value.name }))
|
||||
const { viewport } = this.state;
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-between my-2" key={value.name}>
|
||||
<div className="flex-1 truncate">
|
||||
<Bar
|
||||
count={value.unique_conversions}
|
||||
plot="unique_conversions"
|
||||
all={this.state.breakdown}
|
||||
bg="bg-red-50 dark:bg-gray-500 dark:bg-opacity-15"
|
||||
>
|
||||
{this.renderPropContent(value, query)}
|
||||
</Bar>
|
||||
</div>
|
||||
<div className="flex dark:text-gray-200">
|
||||
<span className="font-medium inline-block w-20 text-right">{numberFormatter(value.unique_conversions)}</span>
|
||||
{
|
||||
viewport > MOBILE_UPPER_WIDTH ?
|
||||
(
|
||||
<span
|
||||
className="font-medium inline-block w-20 text-right"
|
||||
>{numberFormatter(value.total_conversions)}
|
||||
</span>
|
||||
)
|
||||
: null
|
||||
}
|
||||
<span className="font-medium inline-block w-20 text-right">{numberFormatter(value.conversion_rate)}%</span>
|
||||
{this.props.renderRevenueColumn && <span className="hidden md:inline-block md:w-20 font-medium text-right"><Money formatted={value.total_revenue} /></span>}
|
||||
{this.props.renderRevenueColumn && <span className="hidden md:inline-block md:w-20 font-medium text-right"><Money formatted={value.average_revenue} /></span>}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
changePropKey(newKey) {
|
||||
storage.setItem(this.storageKey, newKey)
|
||||
this.setState({ propKey: newKey, loading: true, breakdown: [], page: 1, moreResultsAvailable: false }, this.fetchAndReplace)
|
||||
}
|
||||
|
||||
renderLoading() {
|
||||
if (this.state.loading) {
|
||||
return <div className="px-4 py-2"><div className="loading sm mx-auto"><div></div></div></div>
|
||||
} else if (this.state.moreResultsAvailable && this.props.query.period !== 'realtime') {
|
||||
return (
|
||||
<div className="w-full text-center my-4">
|
||||
<button onClick={this.loadMore.bind(this)} type="button" className="button">
|
||||
Load more
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
renderBody() {
|
||||
return this.state.breakdown.map((propValue) => this.renderPropValue(propValue))
|
||||
}
|
||||
|
||||
renderPill(key) {
|
||||
const isActive = this.state.propKey === key
|
||||
|
||||
if (isActive) {
|
||||
return <li key={key} className="inline-block h-5 text-indigo-700 dark:text-indigo-500 font-bold mr-2 active-prop-heading">{key}</li>
|
||||
} else {
|
||||
return <li key={key} className="hover:text-indigo-600 cursor-pointer mr-2" onClick={this.changePropKey.bind(this, key)}>{key}</li>
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<div className="w-full pl-3 sm:pl-6 mt-4">
|
||||
<div className="flex-col sm:flex-row flex items-center pb-1">
|
||||
<span className="text-xs font-bold text-gray-600 dark:text-gray-300 self-start sm:self-auto mb-1 sm:mb-0">Breakdown by:</span>
|
||||
<ul className="flex flex-wrap font-medium text-xs text-gray-500 dark:text-gray-400 leading-5 pl-1 sm:pl-2">
|
||||
{this.props.goal.prop_names.map(this.renderPill.bind(this))}
|
||||
</ul>
|
||||
</div>
|
||||
{this.renderBody()}
|
||||
{this.renderLoading()}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,22 @@
|
||||
defmodule Plausible.Goal.Revenue do
|
||||
@moduledoc """
|
||||
Currency specific functions for revenue goals
|
||||
"""
|
||||
|
||||
def revenue?(%Plausible.Goal{currency: currency}) do
|
||||
!!currency
|
||||
end
|
||||
|
||||
def valid_currencies() do
|
||||
Ecto.Enum.dump_values(Plausible.Goal, :currency)
|
||||
end
|
||||
|
||||
def currency_options() do
|
||||
options =
|
||||
for code <- valid_currencies() do
|
||||
{code, "#{code} - #{Cldr.Currency.display_name!(code)}"}
|
||||
end
|
||||
|
||||
options
|
||||
end
|
||||
end
|
||||
@ -0,0 +1,37 @@
|
||||
defmodule Plausible.Ingestion.Event.Revenue do
|
||||
@moduledoc """
|
||||
Revenue specific functions for the ingestion scope
|
||||
"""
|
||||
|
||||
def get_revenue_attrs(
|
||||
%Plausible.Ingestion.Event{request: %{revenue_source: %Money{} = revenue_source}} = event
|
||||
) do
|
||||
matching_goal =
|
||||
Enum.find(event.site.revenue_goals, &(&1.event_name == event.clickhouse_event_attrs.name))
|
||||
|
||||
cond do
|
||||
is_nil(matching_goal) ->
|
||||
%{}
|
||||
|
||||
matching_goal.currency == revenue_source.currency ->
|
||||
%{
|
||||
revenue_source_amount: Money.to_decimal(revenue_source),
|
||||
revenue_source_currency: to_string(revenue_source.currency),
|
||||
revenue_reporting_amount: Money.to_decimal(revenue_source),
|
||||
revenue_reporting_currency: to_string(revenue_source.currency)
|
||||
}
|
||||
|
||||
matching_goal.currency != revenue_source.currency ->
|
||||
converted = Money.to_currency!(revenue_source, matching_goal.currency)
|
||||
|
||||
%{
|
||||
revenue_source_amount: Money.to_decimal(revenue_source),
|
||||
revenue_source_currency: to_string(revenue_source.currency),
|
||||
revenue_reporting_amount: Money.to_decimal(converted),
|
||||
revenue_reporting_currency: to_string(converted.currency)
|
||||
}
|
||||
end
|
||||
end
|
||||
|
||||
def get_revenue_attrs(_event), do: %{}
|
||||
end
|
||||
@ -0,0 +1,35 @@
|
||||
defmodule Plausible.Ingestion.Request.Revenue do
|
||||
@moduledoc """
|
||||
Revenue specific functions for the ingestion scope
|
||||
"""
|
||||
|
||||
def put_revenue_source(%Ecto.Changeset{} = changeset, %{} = request_body) do
|
||||
with revenue_source <- request_body["revenue"] || request_body["$"],
|
||||
%{"amount" => _, "currency" => _} = revenue_source <-
|
||||
Plausible.Helpers.JSON.decode_or_fallback(revenue_source) do
|
||||
parse_revenue_source(changeset, revenue_source)
|
||||
else
|
||||
_any -> changeset
|
||||
end
|
||||
end
|
||||
|
||||
@valid_currencies Plausible.Goal.Revenue.valid_currencies()
|
||||
defp parse_revenue_source(changeset, %{"amount" => amount, "currency" => currency}) do
|
||||
with true <- currency in @valid_currencies,
|
||||
{%Decimal{} = amount, _rest} <- parse_decimal(amount),
|
||||
%Money{} = amount <- Money.new(currency, amount) do
|
||||
Ecto.Changeset.put_change(changeset, :revenue_source, amount)
|
||||
else
|
||||
_any -> changeset
|
||||
end
|
||||
end
|
||||
|
||||
defp parse_decimal(value) do
|
||||
case value do
|
||||
value when is_binary(value) -> Decimal.parse(value)
|
||||
value when is_float(value) -> {Decimal.from_float(value), nil}
|
||||
value when is_integer(value) -> {Decimal.new(value), nil}
|
||||
_any -> :error
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -0,0 +1,97 @@
|
||||
defmodule Plausible.Stats.Goal.Revenue do
|
||||
@moduledoc """
|
||||
Revenue specific functions for the stats scope
|
||||
"""
|
||||
import Ecto.Query
|
||||
|
||||
@revenue_metrics [:average_revenue, :total_revenue]
|
||||
|
||||
def revenue_metrics() do
|
||||
@revenue_metrics
|
||||
end
|
||||
|
||||
def total_revenue_query(query) do
|
||||
from(e in query,
|
||||
select_merge: %{
|
||||
total_revenue:
|
||||
fragment("toDecimal64(sum(?) * any(_sample_factor), 3)", e.revenue_reporting_amount)
|
||||
}
|
||||
)
|
||||
end
|
||||
|
||||
def average_revenue_query(query) do
|
||||
from(e in query,
|
||||
select_merge: %{
|
||||
average_revenue:
|
||||
fragment("toDecimal64(avg(?) * any(_sample_factor), 3)", e.revenue_reporting_amount)
|
||||
}
|
||||
)
|
||||
end
|
||||
|
||||
@spec get_revenue_tracking_currency(Plausible.Site.t(), Plausible.Stats.Query.t(), [atom()]) ::
|
||||
{atom() | nil, [atom()]}
|
||||
@doc """
|
||||
Returns the common currency for the goal filters in a query. If there are no
|
||||
goal filters, multiple currencies or the site owner does not have access to
|
||||
revenue goals, `nil` is returned and revenue metrics are dropped.
|
||||
|
||||
Aggregating revenue data works only for same currency goals. If the query is
|
||||
filtered by goals with different currencies, for example, one USD and other
|
||||
EUR, revenue metrics are dropped.
|
||||
"""
|
||||
def get_revenue_tracking_currency(site, query, metrics) do
|
||||
goal_filters =
|
||||
case query.filters do
|
||||
%{"event:goal" => {:is, {_, goal_name}}} -> [goal_name]
|
||||
%{"event:goal" => {:member, list}} -> Enum.map(list, fn {_, goal_name} -> goal_name end)
|
||||
_any -> []
|
||||
end
|
||||
|
||||
requested_revenue_metrics? = Enum.any?(metrics, &(&1 in @revenue_metrics))
|
||||
filtering_by_goal? = Enum.any?(goal_filters)
|
||||
|
||||
revenue_goals_available? = fn ->
|
||||
site = Plausible.Repo.preload(site, :owner)
|
||||
Plausible.Billing.Feature.RevenueGoals.check_availability(site.owner) == :ok
|
||||
end
|
||||
|
||||
if requested_revenue_metrics? && filtering_by_goal? && revenue_goals_available?.() do
|
||||
revenue_goals_currencies =
|
||||
Plausible.Repo.all(
|
||||
from rg in Ecto.assoc(site, :revenue_goals),
|
||||
where: rg.event_name in ^goal_filters,
|
||||
select: rg.currency,
|
||||
distinct: true
|
||||
)
|
||||
|
||||
if length(revenue_goals_currencies) == 1,
|
||||
do: {List.first(revenue_goals_currencies), metrics},
|
||||
else: {nil, metrics -- @revenue_metrics}
|
||||
else
|
||||
{nil, metrics -- @revenue_metrics}
|
||||
end
|
||||
end
|
||||
|
||||
def cast_revenue_metrics_to_money([%{goal: _goal} | _rest] = results, revenue_goals)
|
||||
when is_list(revenue_goals) do
|
||||
for result <- results do
|
||||
if matching_goal = Enum.find(revenue_goals, &(&1.event_name == result.goal)) do
|
||||
cast_revenue_metrics_to_money(result, matching_goal.currency)
|
||||
else
|
||||
result
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def cast_revenue_metrics_to_money(results, currency) when is_map(results) do
|
||||
for {metric, value} <- results, into: %{} do
|
||||
if metric in @revenue_metrics && currency do
|
||||
{metric, Money.new!(value || 0, currency)}
|
||||
else
|
||||
{metric, value}
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def cast_revenue_metrics_to_money(results, _), do: results
|
||||
end
|
||||
@ -0,0 +1,27 @@
|
||||
defmodule PlausibleWeb.Controllers.API.Revenue do
|
||||
@moduledoc """
|
||||
Revenue specific functions for the API scope
|
||||
"""
|
||||
|
||||
@revenue_metrics Plausible.Stats.Goal.Revenue.revenue_metrics()
|
||||
def format_revenue_metric({metric, value}) do
|
||||
if metric in @revenue_metrics do
|
||||
{metric, format_money(value)}
|
||||
else
|
||||
{metric, value}
|
||||
end
|
||||
end
|
||||
|
||||
def format_money(value) do
|
||||
case value do
|
||||
%Money{} ->
|
||||
%{
|
||||
short: Money.to_string!(value, format: :short, fractional_digits: 1),
|
||||
long: Money.to_string!(value)
|
||||
}
|
||||
|
||||
_any ->
|
||||
value
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -0,0 +1,15 @@
|
||||
defmodule Plausible.Helpers.JSON do
|
||||
@moduledoc """
|
||||
Common helpers for JSON handling
|
||||
"""
|
||||
|
||||
def decode_or_fallback(raw) do
|
||||
with raw when is_binary(raw) <- raw,
|
||||
{:ok, %{} = decoded} <- Jason.decode(raw) do
|
||||
decoded
|
||||
else
|
||||
already_a_map when is_map(already_a_map) -> already_a_map
|
||||
_any -> %{}
|
||||
end
|
||||
end
|
||||
end
|
||||
File diff suppressed because it is too large
Load Diff
Loading…
Reference in New Issue