Skip to content

Commit

Permalink
Выносит формирование таблицы с накоплениями в отдельную функцию savin…
Browse files Browse the repository at this point in the history
…gsTable
  • Loading branch information
Alexey Khan committed Jan 26, 2021
1 parent f59a2a1 commit 68c5aaa
Show file tree
Hide file tree
Showing 5 changed files with 61 additions and 112 deletions.
4 changes: 2 additions & 2 deletions cmd/console/calculate.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ var calculateCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) { _ = cmd.Help() },
Example: commandOverview(
"Финансовые расчеты",
"Используйте команду `calculate`, чтобы посмотреть, каких результатов можно достигнуть " +
"за указанный период, если соблюдать определенные условия, например, размер ежемесячных " +
"Используйте команду `calculate`, чтобы посмотреть, каких результатов можно достигнуть "+
"за указанный период, если соблюдать определенные условия, например, размер ежемесячных "+
"инвестиций, средняя доходность портфеля и уровень инфляции.\n\n"+
"Пример: узнайте, сколько денег вы сможете накопить, если на протяжении следующих 20 лет "+
"будете ежемесячно откладывать по 10,000 рублей с доходностью портфеля 10% годовых и ежемесячной "+
Expand Down
2 changes: 1 addition & 1 deletion cmd/console/calculate_inflation.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ var calculateInflationConfig = struct {
overview: "Задача: рассчитать изменение покупательской способности по прошествии %s " +
"при заданном уровне инфляции %.2f%% в год на примере изменения денежной суммы, " +
"по сегодняшним меркам равной %.2f рублям.",
results: " > Эквивалент исходной суммы в будущем: %.2f\n\n",
results: " > Эквивалент исходной суммы в будущем: %.2f\n\n",
detailed: "\n > Эквивалент исходной суммы в будущем: %.2f\n" +
" > Ценность исходной суммы в будущем: %.2f\n\n",
examples: []string{
Expand Down
57 changes: 4 additions & 53 deletions cmd/console/calculate_savings.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ package main
import (
"fmt"

"github.com/jedib0t/go-pretty/v6/table"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
Expand All @@ -48,7 +47,7 @@ var calculateSavingsConfig = struct {
" > Сумма собственных вложений за период: %.2f\n" +
" > Сумма начисленных процентов за период: %.2f\n\n",
examples: []string{
"./bin/assist calculate savings --goal=10000 --years=10 --interest=6.5 --detailed=M",
"./bin/assist calculate savings --payment=10000 --years=10 --interest=6.5 --detailed=M",
"./bin/assist calculate savings -p=10000 -y=10 -i=6.5 -d=M",
"./bin/assist calculate savings --help",
},
Expand Down Expand Up @@ -106,59 +105,11 @@ var calculateSavings = &cobra.Command{
return
}

firstColumn := tableColumnYear
detailedMonthly := detailed == commandOptionDetailedMonthly
if detailedMonthly {
firstColumn = tableColumnMonth
}

t := getTableWriter(
firstColumn,
tableColumnInvestments,
tableColumnInterestIncome,
tableColumnTotalSavings)

var (
next int
index interface{}

totalSavings, interestIncome, personalInvestments float64
)

periods := 12 * int(years)
periodRate := interest * 0.01 / 12
for i := 0; i <= periods; i++ {
interest := totalSavings * periodRate
interestIncome += interest
if i == periods {
totalSavings += interest
t.AppendSeparator()
} else {
totalSavings += interest + payment
personalInvestments += payment
}

next = i + 1
index = next

if !detailedMonthly {
index = next / 12
}
if i == periods {
index = tableFooterTotal
}
if detailedMonthly || (next >= 12 && next%12 == 0 || i == periods) {
t.AppendRow(table.Row{
index,
fmt.Sprintf("%.2f", personalInvestments),
fmt.Sprintf("%.2f", interestIncome),
fmt.Sprintf("%.2f", totalSavings),
})
}
}
rendered, personalInvestments, interestIncome, totalSavings := savingsTable(
payment, interest, years, detailed == commandOptionDetailedMonthly)

fmt.Println(taskOverview)
fmt.Println(t.Render())
fmt.Println(rendered)
fmt.Printf(calculateSavingsConfig.detailed, totalSavings, personalInvestments, interestIncome)
return
},
Expand Down
55 changes: 51 additions & 4 deletions cmd/console/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,9 @@ const (
commandOptions = " Параметры и опции команды:"
commandUsageExamples = "\n Примеры использования:\n"

tableColumnYear = "Год"
tableColumnMonth = "Месяц"
tableColumnExpenses = "Расходы"
tableColumnYear = "Год"
tableColumnMonth = "Месяц"
tableColumnExpenses = "Расходы"

tableColumnInflationInitial = "Исходная ценность"
tableColumnInflationEquivalent = "Эквивалент ценности"
Expand All @@ -70,7 +70,6 @@ var logo = [...]string{
`$$/ $$/ $$$$$$/ $$$$$$/ $$$$$$/ $$$$$$/ $$/ `,
}


func yearsDuration(years uint8) string {
info := "лет"
if years != 11 && years%10 == 1 {
Expand All @@ -79,6 +78,54 @@ func yearsDuration(years uint8) string {
return fmt.Sprintf("%d %s", years, info)
}

func savingsTable(payment, interest float64, years uint8, detailed bool) (rendered string, personalInvestments, interestIncome, totalSavings float64) {
firstColumn := tableColumnYear
if detailed {
firstColumn = tableColumnMonth
}

t := getTableWriter(
firstColumn,
tableColumnInvestments,
tableColumnInterestIncome,
tableColumnTotalSavings)

var index interface{}
periods := 12 * int(years)
periodRate := interest * 0.01 / 12
for i := 0; i <= periods; i++ {
interest := totalSavings * periodRate
interestIncome += interest
if i == periods {
totalSavings += interest
t.AppendSeparator()
} else {
totalSavings += interest + payment
personalInvestments += payment
}

index = i + 1
if !detailed {
index = (i + 1) / 12
}

if i == periods {
index = tableFooterTotal
}

if detailed || (i+1 >= 12 && (i+1)%12 == 0 || i == periods) {
t.AppendRow(table.Row{
index,
fmt.Sprintf("%.2f", personalInvestments),
fmt.Sprintf("%.2f", interestIncome),
fmt.Sprintf("%.2f", totalSavings),
})
}
}

return t.Render(), personalInvestments, interestIncome, totalSavings
}

func commandOverview(title, about string, examples []string) string {
boldWhiteText := text.Colors{text.Bold, text.FgHiWhite}
normalWhiteText := text.Colors{text.FgHiWhite}
Expand Down
55 changes: 3 additions & 52 deletions cmd/console/decompose_savings.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ package main
import (
"fmt"

"github.com/jedib0t/go-pretty/v6/table"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
Expand Down Expand Up @@ -106,59 +105,11 @@ var decomposeSavings = &cobra.Command{
return
}

firstColumn := tableColumnYear
detailedMonthly := detailed == commandOptionDetailedMonthly
if detailedMonthly {
firstColumn = tableColumnMonth
}

t := getTableWriter(
firstColumn,
tableColumnInvestments,
tableColumnInterestIncome,
tableColumnTotalSavings)

var (
next int
index interface{}

totalSavings, interestIncome, personalInvestments float64
)

periods := 12 * int(years)
periodRate := interest * 0.01 / 12
for i := 0; i <= periods; i++ {
interest := totalSavings * periodRate
interestIncome += interest
if i == periods {
totalSavings += interest
t.AppendSeparator()
} else {
totalSavings += interest + payment
personalInvestments += payment
}

next = i + 1
index = next

if !detailedMonthly {
index = next / 12
}
if i == periods {
index = tableFooterTotal
}
if detailedMonthly || (next >= 12 && next%12 == 0 || i == periods) {
t.AppendRow(table.Row{
index,
fmt.Sprintf("%.2f", personalInvestments),
fmt.Sprintf("%.2f", interestIncome),
fmt.Sprintf("%.2f", totalSavings),
})
}
}
rendered, personalInvestments, interestIncome, _ := savingsTable(
payment, interest, years, detailed == commandOptionDetailedMonthly)

fmt.Println(taskOverview)
fmt.Println(t.Render())
fmt.Println(rendered)
fmt.Printf(decomposeSavingsConfig.detailed, payment, personalInvestments, interestIncome)

return nil
Expand Down

0 comments on commit 68c5aaa

Please sign in to comment.