beancount-gs/script/config.go

372 lines
8.9 KiB
Go
Raw Normal View History

2021-11-18 08:27:28 +00:00
package script
import (
"encoding/json"
"fmt"
2021-11-23 06:58:37 +00:00
"os"
"sort"
"strings"
2022-03-11 15:18:38 +00:00
"github.com/gin-gonic/gin"
2021-11-18 08:27:28 +00:00
)
2021-12-04 04:06:45 +00:00
var serverSecret string
2021-11-18 08:27:28 +00:00
var serverConfig Config
2021-11-22 14:50:10 +00:00
var ledgerConfigMap map[string]Config
var ledgerAccountsMap map[string][]Account
2021-11-23 06:58:37 +00:00
var ledgerAccountTypesMap map[string]map[string]string
2021-11-18 08:27:28 +00:00
var whiteList []string
type Config struct {
2021-12-01 09:32:15 +00:00
Id string `json:"id,omitempty"`
Mail string `json:"mail,omitempty"`
Title string `json:"title,omitempty"`
DataPath string `json:"dataPath,omitempty"`
2021-11-18 08:27:28 +00:00
OperatingCurrency string `json:"operatingCurrency"`
StartDate string `json:"startDate"`
IsBak bool `json:"isBak"`
2021-11-28 12:19:40 +00:00
OpeningBalances string `json:"openingBalances"`
2021-12-04 05:12:12 +00:00
CreateDate string `json:"createDate,omitempty"`
2021-11-18 08:27:28 +00:00
}
2021-11-22 14:50:10 +00:00
type Account struct {
2021-11-23 14:42:03 +00:00
Acc string `json:"account"`
StartDate string `json:"startDate"`
2021-11-28 12:19:40 +00:00
Currency string `json:"currency,omitempty"`
MarketNumber string `json:"marketNumber,omitempty"`
MarketCurrency string `json:"marketCurrency,omitempty"`
MarketCurrencySymbol string `json:"marketCurrencySymbol,omitempty"`
2021-11-23 14:42:03 +00:00
EndDate string `json:"endDate,omitempty"`
Type *AccountType `json:"type,omitempty"`
2021-11-22 14:50:10 +00:00
}
2021-11-23 06:58:37 +00:00
type AccountType struct {
2021-11-22 14:50:10 +00:00
Key string `json:"key"`
Name string `json:"name"`
}
2021-11-18 08:27:28 +00:00
func GetServerConfig() Config {
return serverConfig
}
2021-12-01 09:32:15 +00:00
func LoadServerConfig() error {
filePath := GetServerConfigFilePath()
if !FileIfExist(filePath) {
serverConfig = Config{
OpeningBalances: "Equity:OpeningBalances",
OperatingCurrency: "CNY",
StartDate: "1970-01-01",
IsBak: true,
}
return nil
}
fileContent, err := ReadFile(filePath)
if err != nil {
return err
}
err = json.Unmarshal(fileContent, &serverConfig)
if err != nil {
LogSystemError("Failed unmarshall config file (" + filePath + ")")
return err
}
LogSystemInfo("Success load config file (" + filePath + ")")
// load white list
whiteListFilePath := GetServerWhiteListFilePath()
2021-12-06 14:07:19 +00:00
if FileIfExist(whiteListFilePath) {
fileContent, err = ReadFile(whiteListFilePath)
if err != nil {
return err
}
err = json.Unmarshal(fileContent, &whiteList)
if err != nil {
LogSystemError("Failed unmarshal whitelist file (" + whiteListFilePath + ")")
return err
}
} else {
2021-12-07 15:19:36 +00:00
err = CreateFile(whiteListFilePath)
if err != nil {
return err
}
err = WriteFile(whiteListFilePath, "[]")
2021-12-06 14:07:19 +00:00
if err != nil {
return err
}
whiteList = make([]string, 0)
2021-12-01 09:32:15 +00:00
}
LogSystemInfo("Success load whitelist file (" + whiteListFilePath + ")")
return nil
}
func UpdateServerConfig(config Config) error {
bytes, err := json.Marshal(config)
if err != nil {
return err
}
err = WriteFile(GetServerConfigFilePath(), string(bytes))
if err != nil {
return err
}
serverConfig = config
return nil
}
2021-11-18 08:27:28 +00:00
func GetLedgerConfigMap() map[string]Config {
return ledgerConfigMap
}
2021-11-18 10:10:19 +00:00
func GetLedgerConfig(ledgerId string) *Config {
for k, v := range ledgerConfigMap {
if k == ledgerId {
return &v
}
}
return nil
2021-11-18 08:27:28 +00:00
}
func GetLedgerConfigByMail(mail string) *Config {
for _, v := range ledgerConfigMap {
if v.Mail == mail {
return &v
}
}
return nil
}
2021-11-19 09:54:02 +00:00
func GetLedgerConfigFromContext(c *gin.Context) *Config {
ledgerConfig, _ := c.Get("LedgerConfig")
t, _ := ledgerConfig.(*Config)
return t
}
2021-11-22 14:50:10 +00:00
func GetLedgerAccounts(ledgerId string) []Account {
return ledgerAccountsMap[ledgerId]
}
2021-11-28 12:19:40 +00:00
func GetLedgerAccount(ledgerId string, account string) Account {
accounts := ledgerAccountsMap[ledgerId]
for _, acc := range accounts {
if acc.Acc == account {
return acc
}
}
panic("Invalid account")
}
func UpdateLedgerAccounts(ledgerId string, accounts []Account) {
ledgerAccountsMap[ledgerId] = accounts
}
2022-03-11 15:18:38 +00:00
func ClearLedgerAccounts(ledgerId string) {
delete(ledgerAccountsMap, ledgerId)
}
2021-11-23 06:58:37 +00:00
func GetLedgerAccountTypes(ledgerId string) map[string]string {
return ledgerAccountTypesMap[ledgerId]
}
2021-11-28 12:19:40 +00:00
func UpdateLedgerAccountTypes(ledgerId string, accountTypesMap map[string]string) {
ledgerAccountTypesMap[ledgerId] = accountTypesMap
}
2022-03-11 15:18:38 +00:00
func ClearLedgerAccountTypes(ledgerId string) {
delete(ledgerAccountTypesMap, ledgerId)
}
2021-11-23 14:42:03 +00:00
func GetAccountType(ledgerId string, acc string) AccountType {
accountTypes := ledgerAccountTypesMap[ledgerId]
accNodes := strings.Split(acc, ":")
accountType := AccountType{
Key: acc,
// 默认取最后一个节点
Name: accNodes[len(accNodes)-1],
}
var matchKey string = ""
for key, name := range accountTypes {
if strings.Contains(acc, key) && len(matchKey) < len(key) {
matchKey = key
accountType = AccountType{Key: key, Name: name}
}
}
return accountType
}
2021-11-18 08:27:28 +00:00
func IsInWhiteList(ledgerId string) bool {
// ledger white list is empty, return true
2022-07-03 14:59:01 +00:00
if len(whiteList) == 0 {
2021-11-18 08:27:28 +00:00
return true
}
for i := range whiteList {
if whiteList[i] == ledgerId {
return true
}
}
return false
}
func LoadLedgerConfigMap() error {
path := GetServerLedgerConfigFilePath()
2021-12-01 09:32:15 +00:00
// 文件不存在,则创建 ledger_config.json
if !FileIfExist(path) {
err := CreateFile(path)
if err != nil {
return err
}
ledgerConfigMap = make(map[string]Config)
} else {
// 文件存在,将文件内容加载到缓存
fileContent, err := ReadFile(path)
if err != nil {
return err
}
2021-12-15 15:14:04 +00:00
if string(fileContent) != "" {
err = json.Unmarshal(fileContent, &ledgerConfigMap)
if err != nil {
LogSystemError("Failed unmarshal ledger_config file (" + path + ")")
return err
}
} else {
ledgerConfigMap = make(map[string]Config)
2021-11-28 12:19:40 +00:00
}
2021-12-01 09:32:15 +00:00
LogSystemInfo("Success load ledger_config file (" + path + ")")
2021-11-28 12:19:40 +00:00
}
2021-11-18 08:27:28 +00:00
return nil
}
2021-11-22 14:50:10 +00:00
func LoadLedgerAccountsMap() error {
2021-11-23 06:58:37 +00:00
if ledgerAccountsMap == nil {
ledgerAccountsMap = make(map[string][]Account)
}
2021-11-22 14:50:10 +00:00
for _, config := range ledgerConfigMap {
2021-12-01 09:32:15 +00:00
err := LoadLedgerAccounts(config.Id)
if err != nil {
return err
2021-11-23 06:58:37 +00:00
}
2021-12-01 09:32:15 +00:00
}
return nil
}
func LoadLedgerAccounts(ledgerId string) error {
config := ledgerConfigMap[ledgerId]
// 加载 account_type.json 到缓存(内存)
loadErr := LoadLedgerAccountTypesMap(config)
if loadErr != nil {
LogSystemError("Failed to load account types")
return loadErr
}
accountDirPath := config.DataPath + "/account"
dirs, err := os.ReadDir(accountDirPath)
if err != nil {
return err
}
accountMap := make(map[string]Account)
for _, dir := range dirs {
bytes, err := ReadFile(accountDirPath + "/" + dir.Name())
2021-11-22 14:50:10 +00:00
if err != nil {
return err
}
2021-12-01 09:32:15 +00:00
lines := strings.Split(string(bytes), "\n")
var temp Account
for _, line := range lines {
if line != "" {
words := strings.Fields(line)
if len(words) >= 3 {
key := words[2]
temp = accountMap[key]
account := Account{Acc: key, Type: nil}
// 货币单位
if len(words) >= 4 {
account.Currency = words[3]
}
if words[1] == "open" {
account.StartDate = words[0]
} else if words[1] == "close" {
account.EndDate = words[0]
}
if temp.StartDate != "" {
account.StartDate = temp.StartDate
}
if temp.EndDate != "" {
account.EndDate = temp.EndDate
2021-11-23 06:58:37 +00:00
}
2021-12-01 09:32:15 +00:00
accountMap[key] = account
2021-11-23 06:58:37 +00:00
}
}
}
2021-11-22 14:50:10 +00:00
}
2021-12-01 09:32:15 +00:00
accounts := make([]Account, 0)
for _, account := range accountMap {
accounts = append(accounts, account)
}
// 账户按字母排序
sort.Sort(AccountSort(accounts))
ledgerAccountsMap[config.Id] = accounts
LogSystemInfo(fmt.Sprintf("Success load [%s] accounts cache", config.Mail))
2021-11-22 14:50:10 +00:00
return nil
}
2021-11-23 06:58:37 +00:00
func LoadLedgerAccountTypesMap(config Config) error {
path := GetLedgerAccountTypeFilePath(config.DataPath)
fileContent, err := ReadFile(path)
if err != nil {
return err
}
accountTypes := make(map[string]string)
err = json.Unmarshal(fileContent, &accountTypes)
if err != nil {
LogSystemError("Failed unmarshal config file (" + path + ")")
return err
}
if ledgerAccountTypesMap == nil {
ledgerAccountTypesMap = make(map[string]map[string]string)
}
ledgerAccountTypesMap[config.Id] = accountTypes
LogSystemInfo(fmt.Sprintf("Success load [%s] account type cache", config.Mail))
2021-11-23 06:58:37 +00:00
return nil
}
2021-11-22 14:50:10 +00:00
func WriteLedgerConfigMap(newLedgerConfigMap map[string]Config) error {
2021-11-18 08:27:28 +00:00
path := GetServerLedgerConfigFilePath()
mapBytes, err := json.Marshal(ledgerConfigMap)
if err != nil {
2021-11-21 14:37:13 +00:00
LogSystemError("Failed marshal ConfigMap")
2021-11-18 08:27:28 +00:00
return err
}
err = WriteFile(path, string(mapBytes))
ledgerConfigMap = newLedgerConfigMap
2021-11-21 14:37:13 +00:00
LogSystemInfo("Success write ledger_config file (" + path + ")")
2021-11-18 08:27:28 +00:00
return err
}
2021-11-22 08:47:49 +00:00
2021-12-04 04:06:45 +00:00
func GenerateServerSecret(secret string) string {
if secret == "" {
serverSecret = RandChar(16)
} else {
serverSecret = secret
}
return serverSecret
}
func EqualServerSecret(secret string) bool {
return serverSecret == secret
}
2021-11-22 08:47:49 +00:00
func GetCommoditySymbol(commodity string) string {
switch commodity {
case "CNY":
return "¥"
case "USD":
return "$"
}
2021-11-24 09:32:24 +00:00
return ""
2021-11-22 08:47:49 +00:00
}
2021-11-28 12:19:40 +00:00
func GetAccountPrefix(account string) string {
nodes := strings.Split(account, ":")
return nodes[0]
}
2021-11-29 14:42:49 +00:00
func GetAccountIconName(account string) string {
nodes := strings.Split(account, ":")
2021-12-01 09:32:15 +00:00
return strings.Join(nodes, "_")
2021-11-29 14:42:49 +00:00
}