lib/app/period-services.go

82 lines
2.7 KiB
Go
Raw Normal View History

2021-02-02 04:19:16 +00:00
package app
import (
"fmt"
"time"
"code.tnxs.net/taxnexus/lib/api/ledger/ledger_client/period"
2021-02-02 05:51:33 +00:00
"code.tnxs.net/taxnexus/lib/api/ledger/ledger_models"
2021-02-02 04:19:16 +00:00
)
2021-02-02 05:51:33 +00:00
// GetPeriodByID is a first class object retrieval method
func GetPeriodByID(recordID *string, principal *User) (*ledger_models.Period, error) {
ledgerParams := period.NewGetPeriodsParams()
ledgerParams.PeriodID = recordID
periodResponse, restErr := ledgerClient.Period.GetPeriods(ledgerParams, principal.Auth)
if restErr != nil {
return nil, fmt.Errorf("devops.getPeriodByID: 💣 ⛔ getPeriod error: %w", restErr)
}
return periodResponse.Payload.Data[0], nil
}
// GetPeriodByDate is a first class object retrieval method
func GetPeriodByDate(accountID *string, theDate time.Time, principal *User) (*ledger_models.Period, error) {
ledgerParams := period.NewGetPeriodsParams()
ledgerParams.AccountID = accountID
dateString := theDate.Format(dateFormat)
ledgerParams.Date = &dateString
periodResponse, restErr := ledgerClient.Period.GetPeriods(ledgerParams, principal.Auth)
if restErr != nil {
return nil, fmt.Errorf("devops.getPeriodByDate: 💣 ⛔ getPeriod error: %w", restErr)
}
return periodResponse.Payload.Data[0], nil
}
2021-02-02 04:19:16 +00:00
// CalendarPeriod is a parameter type
type CalendarPeriod struct {
ID string
Name string
StartDate time.Time
EndDate time.Time
}
// GetPeriodParams is a parameter type
type GetPeriodParams struct {
Date time.Time
AccountID string
Principal *User
}
// GetPeriodIDByDate is a period helper function
func GetPeriodIDByDate(params GetPeriodParams) (string, error) {
sugar.Debug("ops.getPeriodIDByDate: 📥")
obj, ok := periodCache.get(params.AccountID, params.Date.Format(dateFormat))
if ok {
sugar.Debugf("ops.getPeriodIDByDate: 👍 📤 🎯")
return obj.ID, nil
}
ledgerDate := params.Date.Format(dateFormat)
ledgerParams := period.NewGetPeriodsParamsWithTimeout(getTimeout)
ledgerParams.AccountID = &params.AccountID
ledgerParams.Date = &ledgerDate
response, restErr := ledgerClient.Period.GetPeriods(ledgerParams, params.Principal.Auth)
if restErr != nil {
return "", fmt.Errorf("ops.getPeriodIDByDate: 💣 ⛔ dateStr = %s (%w)", params.Date, restErr)
}
// this loop should iterate just once
thePeriod := &CalendarPeriod{}
for _, itm := range response.Payload.Data {
startDate, _ := time.Parse(dateTimeFormat, itm.StartDate)
endDate, _ := time.Parse(dateTimeFormat, itm.EndDate)
thePeriod = &CalendarPeriod{
ID: itm.ID,
EndDate: endDate,
Name: itm.Name,
StartDate: startDate,
}
}
periodCache.put(params.AccountID, params.Date.Format(dateFormat), thePeriod)
sugar.Debugf("ops.getPeriodIDByDate: 👍 📤 %s", thePeriod.Name)
return thePeriod.ID, nil
}