github.com/shoshinnikita/budget-manager@v0.7.1-0.20220131195411-8c46ff1c6778/internal/web/pages/utils.go (about)

     1  package pages
     2  
     3  import (
     4  	"context"
     5  	"net/http"
     6  	"strconv"
     7  	"time"
     8  
     9  	"github.com/ShoshinNikita/budget-manager/internal/db"
    10  	"github.com/ShoshinNikita/budget-manager/internal/logger"
    11  	"github.com/ShoshinNikita/budget-manager/internal/pkg/money"
    12  	"github.com/ShoshinNikita/budget-manager/internal/pkg/reqid"
    13  	"github.com/ShoshinNikita/budget-manager/internal/web/utils"
    14  )
    15  
    16  // processErrorWithPage is similar to 'utils.ProcessError' but shows the error page instead of returning json
    17  func (h Handlers) processErrorWithPage(ctx context.Context, log logger.Logger, w http.ResponseWriter,
    18  	respMsg string, code int) {
    19  
    20  	data := struct {
    21  		Code      int
    22  		RequestID reqid.RequestID
    23  		Message   string
    24  		//
    25  		Footer FooterTemplateData
    26  	}{
    27  		Code:      code,
    28  		RequestID: reqid.FromContext(ctx),
    29  		Message:   respMsg,
    30  		//
    31  		Footer: FooterTemplateData{
    32  			Version: h.version,
    33  			GitHash: h.gitHash,
    34  		},
    35  	}
    36  	if err := h.tplExecutor.Execute(ctx, w, errorPageTemplateName, data); err != nil {
    37  		utils.EncodeInternalError(ctx, w, log, executeErrorMessage, err)
    38  	}
    39  }
    40  
    41  // processInternalErrorWithPage is similar to 'utils.ProcessInternalError' but shows the error page
    42  // instead of returning json
    43  func (h Handlers) processInternalErrorWithPage(ctx context.Context, log logger.Logger, w http.ResponseWriter,
    44  	respMsg string, err error) {
    45  
    46  	utils.LogInternalError(log, respMsg, err)
    47  
    48  	h.processErrorWithPage(ctx, log, w, respMsg, http.StatusInternalServerError)
    49  }
    50  
    51  func toShortMonth(m time.Month) string {
    52  	month := m.String()
    53  	// Don't trim June and July
    54  	if len(month) > 4 {
    55  		month = m.String()[:3]
    56  	}
    57  	return month
    58  }
    59  
    60  func sumSpendCosts(spends []db.Spend) money.Money {
    61  	var m money.Money
    62  	for i := range spends {
    63  		m = m.Sub(spends[i].Cost)
    64  	}
    65  	return m
    66  }
    67  
    68  func getYearAndMonth(r *http.Request) (y int, month time.Month, ok bool) {
    69  	year, err := strconv.Atoi(r.FormValue("year"))
    70  	if err != nil {
    71  		return 0, 0, false
    72  	}
    73  
    74  	m, err := strconv.Atoi(r.FormValue("month"))
    75  	if err != nil {
    76  		return 0, 0, false
    77  	}
    78  	month = time.Month(m)
    79  	if !(time.January <= month && month <= time.December) {
    80  		return 0, 0, false
    81  	}
    82  
    83  	return year, month, true
    84  }