Skip to content

Commit

Permalink
Update display of estimated pending rewards
Browse files Browse the repository at this point in the history
  • Loading branch information
zenparsing committed May 19, 2021
1 parent 1cdc053 commit 3124613
Show file tree
Hide file tree
Showing 27 changed files with 305 additions and 90 deletions.
4 changes: 1 addition & 3 deletions browser/extensions/api/brave_rewards_api.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1143,9 +1143,7 @@ void BraveRewardsGetAdsAccountStatementFunction::OnGetAdsAccountStatement(
base::Value statement(base::Value::Type::DICTIONARY);
statement.SetDoubleKey("estimatedPendingRewards",
estimated_pending_rewards);
const std::string next_payment_date_as_string =
base::NumberToString(next_payment_date);
statement.SetStringKey("nextPaymentDate", next_payment_date_as_string);
statement.SetDoubleKey("nextPaymentDate", next_payment_date * 1000);
statement.SetIntKey("adsReceivedThisMonth", ads_received_this_month);
statement.SetDoubleKey("earningsThisMonth", earnings_this_month);
statement.SetDoubleKey("earningsLastMonth", earnings_last_month);
Expand Down
14 changes: 3 additions & 11 deletions browser/ui/webui/brave_rewards_page_ui.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1416,18 +1416,10 @@ void RewardsDOMHandler::OnGetStatement(const bool success,

base::DictionaryValue history;

history.SetDouble("adsEstimatedPendingRewards",
estimated_pending_rewards);

if (next_payment_date == 0) {
history.SetString("adsNextPaymentDate", "");
} else {
base::Time time = base::Time::FromDoubleT(next_payment_date);
history.SetString("adsNextPaymentDate",
base::TimeFormatWithPattern(time, "MMMd"));
}

history.SetDouble("adsEstimatedPendingRewards", estimated_pending_rewards);
history.SetDouble("adsNextPaymentDate", next_payment_date * 1000);
history.SetInteger("adsReceivedThisMonth", ads_received_this_month);
history.SetDouble("adsEarningsThisMonth", earnings_this_month);

CallJavascriptFunction("brave_rewards.statement", history);
}
Expand Down
2 changes: 2 additions & 0 deletions browser/ui/webui/brave_webui_source.cc
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,7 @@ void CustomizeWebUIHTMLSource(const std::string &name,
{ "editCardsTitle", IDS_EDIT_CARDS_TITLE },
{ "tosAndPp", IDS_REWARDS_WIDGET_TOS_AND_PP}, // NOLINT
{ "rewardsWidgetStartUsing", IDS_REWARDS_WIDGET_START_USING}, // NOLINT
{ "pendingRewardsMessage", IDS_BRAVE_REWARDS_PENDING_REWARDS_MESSAGE },
// Rewards BAP Deprecation Alert
{ "bapDeprecationAlertText", IDS_REWARDS_BAP_DEPRECATION_ALERT_TEXT },
{ "bapDeprecationHeader", IDS_REWARDS_BAP_DEPRECATION_HEADER },
Expand Down Expand Up @@ -725,6 +726,7 @@ void CustomizeWebUIHTMLSource(const std::string &name,
{ "optOutTooltip", IDS_BRAVE_UI_ADS_OPT_OUT_TOOLTIP },
{ "payment", IDS_BRAVE_UI_PAYMENT },
{ "paymentNotMade", IDS_BRAVE_UI_PAYMENT_NOT_MADE },
{ "pendingRewardsMessage", IDS_BRAVE_REWARDS_PENDING_REWARDS_MESSAGE },
{ "pendingContributions", IDS_BRAVE_UI_PENDING_CONTRIBUTIONS },
{ "pendingContributionEmpty", IDS_BRAVE_UI_PENDING_CONTRIBUTION_EMPTY },
{ "pendingContributionRemoveAll", IDS_BRAVE_UI_PENDING_CONTRIBUTION_REMOVE_ALL }, // NOLINT
Expand Down
2 changes: 1 addition & 1 deletion common/extensions/api/brave_rewards.json
Original file line number Diff line number Diff line change
Expand Up @@ -1153,7 +1153,7 @@
"type": "number"
},
"nextPaymentDate": {
"type": "string"
"type": "number"
},
"adsReceivedThisMonth": {
"type": "integer"
Expand Down
44 changes: 37 additions & 7 deletions components/brave_new_tab_ui/components/default/rewards/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { convertBalance } from '../../../../brave_rewards/resources/page/utils'
import { getLocale, splitStringForTag } from '../../../../common/locale'

import {
ArrivingSoon,
WidgetWrapper,
WidgetLayer,
NotificationsList,
Expand All @@ -34,6 +35,9 @@ import Notification from './notification'
import BrandedWallpaperNotification from './brandedWallpaperNotification'
import { BatColorIcon, CloseStrokeIcon } from 'brave-ui/components/icons'

import { formatMessage } from '../../../../../components/brave_rewards/resources/shared/lib/locale_context'
import { getDaysUntilRewardsPayment } from '../../../../../components/brave_rewards/resources/shared/lib/pending_rewards'

export interface RewardsProps {
enabledAds: boolean
balance: NewTab.RewardsBalance
Expand Down Expand Up @@ -68,12 +72,13 @@ class Rewards extends React.PureComponent<RewardsProps, {}> {

const rate = parameters.rate || 0.0
const showEnableAds = !enabledAds && adsSupported
const amount = adsAccountStatement ? adsAccountStatement.estimatedPendingRewards : 0
const amount = adsAccountStatement ? adsAccountStatement.earningsThisMonth : 0
const converted = convertBalance(amount, rate)
const batFormatString = onlyAnonWallet ? getLocale('rewardsWidgetBap') : getLocale('rewardsWidgetBat')

return (
<AmountItem isActionPrompt={!!showEnableAds} isLast={false}>
{this.renderPendingRewardsNotice()}
{
adsSupported
? <div data-test-id={`widget-amount-total-ads`}>
Expand All @@ -82,14 +87,10 @@ class Rewards extends React.PureComponent<RewardsProps, {}> {
{batFormatString}<AmountUSD>{converted} USD</AmountUSD>
</ConvertedAmount>
</div>
: null
}
{
!adsSupported
? <UnsupportedMessage>
:
<UnsupportedMessage>
{getLocale('rewardsWidgetAdsNotSupported')}
</UnsupportedMessage>
: null
}
<AmountDescription>
{getLocale('rewardsWidgetEstimatedEarnings')}
Expand Down Expand Up @@ -152,6 +153,35 @@ class Rewards extends React.PureComponent<RewardsProps, {}> {
)
}

renderPendingRewardsNotice = () => {
const {
nextPaymentDate,
estimatedPendingRewards
} = this.props.adsAccountStatement

if (estimatedPendingRewards <= 0) {
return null
}

const days = getDaysUntilRewardsPayment(nextPaymentDate)
if (!days) {
return null
}

return (
<ArrivingSoon>
{
formatMessage(getLocale('pendingRewardsMessage'), [
<span className='amount' key='amount'>
<strong>+{estimatedPendingRewards}</strong> BAT
</span>,
days
])
}
</ArrivingSoon>
)
}

renderRewardsInfo = () => {
const {
adsSupported,
Expand Down
10 changes: 10 additions & 0 deletions components/brave_new_tab_ui/components/default/rewards/style.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -282,3 +282,13 @@ export const StyledTOS = styled(TOSAndPP as React.ComponentType<TOSProps>)`
export const StyleCenter = styled('div')<{}>`
text-align: center;
`

export const ArrivingSoon = styled.div`
background: ${p => p.theme.palette.white};
border-radius: 6px;
padding: 0 10px;
color: ${p => p.theme.palette.neutral900};
font-size: 14px;
line-height: 22px;
margin-bottom: 8px;
`
23 changes: 14 additions & 9 deletions components/brave_new_tab_ui/storage/new_tab_storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export const defaultState: NewTab.State = {
rewardsState: {
adsAccountStatement: {
estimatedPendingRewards: 0,
nextPaymentDate: '',
nextPaymentDate: 0,
adsReceivedThisMonth: 0,
earningsThisMonth: 0,
earningsLastMonth: 0
Expand Down Expand Up @@ -238,16 +238,21 @@ export const replaceStackWidgets = (state: NewTab.State) => {
}

const cleanData = (state: NewTab.State) => {
// We need to disable linter as we defined in d.ts that this values are number,
// but we need this check to covert from old version to a new one
/* tslint:disable */
if (typeof state.rewardsState.totalContribution === 'string') {
state.rewardsState.totalContribution = 0.0
const { rewardsState } = state

if (typeof (rewardsState.totalContribution as any) === 'string') {
rewardsState.totalContribution = 0
}

// nextPaymentDate updated from seconds-since-epoch-string to ms-since-epoch
const { adsAccountStatement } = rewardsState
if (typeof (adsAccountStatement.nextPaymentDate as any) === 'string') {
adsAccountStatement.nextPaymentDate =
Number(adsAccountStatement.nextPaymentDate) * 1000 || 0
}
/* tslint:enable */

if (!state.rewardsState.parameters) {
state.rewardsState.parameters = defaultState.rewardsState.parameters
if (!rewardsState.parameters) {
rewardsState.parameters = defaultState.rewardsState.parameters
}

return state
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ export const onPendingContributions = (list: Rewards.PendingContribution[]) =>
list
})

export const onStatement = (data: {adsEstimatedPendingRewards: number, adsNextPaymentDate: string, adsReceivedThisMonth: number}) =>
export const onStatement = (data: {adsEstimatedPendingRewards: number, adsNextPaymentDate: number, adsReceivedThisMonth: number}) =>
action(types.ON_STATEMENT, {
data
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import App from './components/app'
require('../../../../ui/webui/resources/fonts/muli.css')
require('../../../../ui/webui/resources/fonts/poppins.css')

import { WithThemeVariables } from '../shared/components/with_theme_variables'

// Utils
import store from './store'
import { ThemeProvider } from 'styled-components'
Expand All @@ -33,7 +35,9 @@ window.cr.define('brave_rewards', function () {
render(
<Provider store={store}>
<ThemeProvider theme={Theme}>
<App />
<WithThemeVariables>
<App />
</WithThemeVariables>
</ThemeProvider>
</Provider>,
document.getElementById('root'))
Expand Down Expand Up @@ -103,7 +107,7 @@ window.cr.define('brave_rewards', function () {
}
}

function statement (data: {adsEstimatedPendingRewards: number, adsNextPaymentDate: string, adsReceivedThisMonth: number}) {
function statement (data: {adsEstimatedPendingRewards: number, adsNextPaymentDate: number, adsReceivedThisMonth: number}) {
getActions().onStatement(data)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,25 @@ import { List, NextContribution, Tokens } from '../../ui/components'
import { Grid, Column, Select, ControlWrapper } from 'brave-ui/components'
import AdsOnboarding from './adsOnboarding'
import {
StyledArrivingSoon,
StyledListContent,
StyledTotalContent
} from './style'

import { MoneyBagIcon } from '../../shared/components/icons/money_bag'
import { formatMessage } from '../../shared/lib/locale_context'
import { getDaysUntilRewardsPayment } from '../../shared/lib/pending_rewards'

// Utils
import { getLocale } from '../../../../common/locale'
import * as rewardsActions from '../actions/rewards_actions'
import * as utils from '../utils'

const nextPaymentDateFormatter = new Intl.DateTimeFormat(undefined, {
month: 'short',
day: 'numeric'
})

interface Props extends Rewards.ComponentProps {
}

Expand Down Expand Up @@ -180,8 +190,10 @@ class AdsBox extends React.Component<Props, {}> {
let adsUIEnabled = false
let adsIsSupported = false
let estimatedPendingRewards = 0
let nextPaymentDate = ''
let nextPaymentDate = 0
let adsReceivedThisMonth = 0
let earningsThisMonth = 0

const {
adsData,
safetyNetFailed,
Expand All @@ -196,6 +208,7 @@ class AdsBox extends React.Component<Props, {}> {
estimatedPendingRewards = adsData.adsEstimatedPendingRewards || 0
nextPaymentDate = adsData.adsNextPaymentDate
adsReceivedThisMonth = adsData.adsReceivedThisMonth || 0
earningsThisMonth = adsData.adsEarningsThisMonth || 0
}

// disabled / alert state
Expand Down Expand Up @@ -223,6 +236,7 @@ class AdsBox extends React.Component<Props, {}> {
}

const tokenString = getLocale(onlyAnonWallet ? 'points' : 'tokens')
const estimatedPendingDays = getDaysUntilRewardsPayment(nextPaymentDate)

return (
<BoxMobile
Expand All @@ -232,19 +246,33 @@ class AdsBox extends React.Component<Props, {}> {
settingsChild={this.adsSettings(adsEnabled)}
{...boxPropsExtra}
>
{
estimatedPendingRewards > 0 && estimatedPendingDays &&
<StyledArrivingSoon>
<MoneyBagIcon />
{
formatMessage(getLocale('pendingRewardsMessage'), [
<span className='amount' key='amount'>
+{estimatedPendingRewards} BAT
</span>,
estimatedPendingDays
])
}
</StyledArrivingSoon>
}
<List title={<StyledListContent>{getLocale('adsCurrentEarnings')}</StyledListContent>}>
<StyledTotalContent>
<Tokens
onlyAnonWallet={onlyAnonWallet}
value={estimatedPendingRewards.toFixed(3)}
converted={utils.convertBalance(estimatedPendingRewards, parameters.rate)}
value={earningsThisMonth.toFixed(3)}
converted={utils.convertBalance(earningsThisMonth, parameters.rate)}
/>
</StyledTotalContent>
</List>
<List title={<StyledListContent>{getLocale('adsPaymentDate')}</StyledListContent>}>
<StyledListContent>
<NextContribution>
{nextPaymentDate}
{nextPaymentDateFormatter.format(new Date(nextPaymentDate))}
</NextContribution>
</StyledListContent>
</List>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,3 +84,29 @@ export const StyledWalletClose = styled('div')<{}>`
color: ${p => p.theme.color.subtleExclude};
width: 25px;
`

export const StyledArrivingSoon = styled.div`
background: rgba(93, 181, 252, 0.2);
margin-bottom: 8px;
padding: 4px;
color: var(--brave-palette-neutral700);
text-align: center;
font-size: 12px;
line-height: 22px;
span.amount {
color: var(--brave-palette-neutral900);
font-weight: 600;
font-size: 14px;
line-height: 24px;
}
.icon {
height: 16px;
width: auto;
fill: var(--brave-palette-blue500);
vertical-align: middle;
margin-bottom: 3px;
margin-right: 8px;
}
`
14 changes: 10 additions & 4 deletions components/brave_rewards/resources/android_page/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,9 @@ export const defaultState: Rewards.State = {
adsUIEnabled: false,
adsIsSupported: false,
adsEstimatedPendingRewards: 0,
adsNextPaymentDate: '',
adsReceivedThisMonth: 0
adsNextPaymentDate: 0,
adsReceivedThisMonth: 0,
adsEarningsThisMonth: 0
},
adsHistory: [],
pendingContributionTotal: 0,
Expand Down Expand Up @@ -88,6 +89,11 @@ const cleanData = (state: Rewards.State) => {
state.parameters = defaultState.parameters
}

// Data type change: adsNextPaymentDate (string -> number)
if (typeof (state.adsData.adsNextPaymentDate as any) !== 'number') {
throw new Error('Invalid adsNextPaymentDate')
}

return state
}

Expand All @@ -96,13 +102,13 @@ export const load = (): Rewards.State => {
let state: Rewards.State = defaultState
if (data) {
try {
state = JSON.parse(data)
state = cleanData(JSON.parse(data))
state.initializing = true
} catch (e) {
console.error('Could not parse local storage data: ', e)
}
}
return cleanData(state)
return state
}

export const debouncedSave = debounce((data: Rewards.State) => {
Expand Down
Loading

0 comments on commit 3124613

Please sign in to comment.