feat: Finance API + тесты + CI/CD #1
24
.gitea/workflows/ci.yml
Normal file
24
.gitea/workflows/ci.yml
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
name: CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [dev]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
ci:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version: '1.22'
|
||||||
|
|
||||||
|
- name: Vet
|
||||||
|
run: go vet ./...
|
||||||
|
|
||||||
|
- name: Test
|
||||||
|
run: go test ./... -v
|
||||||
|
|
||||||
|
- name: Build
|
||||||
|
run: CGO_ENABLED=0 go build -o main ./cmd/api
|
||||||
21
.gitea/workflows/deploy-prod.yml
Normal file
21
.gitea/workflows/deploy-prod.yml
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
name: Deploy Production
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
deploy:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version: '1.22'
|
||||||
|
|
||||||
|
- name: Build
|
||||||
|
run: CGO_ENABLED=0 go build -o main ./cmd/api
|
||||||
|
|
||||||
|
- name: Deploy
|
||||||
|
run: echo "Production deploy via docker"
|
||||||
@@ -71,6 +71,7 @@ func main() {
|
|||||||
profileHandler := handler.NewProfileHandler(userRepo)
|
profileHandler := handler.NewProfileHandler(userRepo)
|
||||||
habitFreezeHandler := handler.NewHabitFreezeHandler(habitFreezeRepo, habitRepo)
|
habitFreezeHandler := handler.NewHabitFreezeHandler(habitFreezeRepo, habitRepo)
|
||||||
savingsHandler := handler.NewSavingsHandler(savingsRepo)
|
savingsHandler := handler.NewSavingsHandler(savingsRepo)
|
||||||
|
interestHandler := handler.NewInterestHandler(db)
|
||||||
|
|
||||||
// Initialize middleware
|
// Initialize middleware
|
||||||
authMiddleware := customMiddleware.NewAuthMiddleware(cfg.JWTSecret)
|
authMiddleware := customMiddleware.NewAuthMiddleware(cfg.JWTSecret)
|
||||||
@@ -103,6 +104,9 @@ func main() {
|
|||||||
r.Post("/auth/forgot-password", authHandler.ForgotPassword)
|
r.Post("/auth/forgot-password", authHandler.ForgotPassword)
|
||||||
r.Post("/auth/reset-password", authHandler.ResetPassword)
|
r.Post("/auth/reset-password", authHandler.ResetPassword)
|
||||||
|
|
||||||
|
// Internal routes (API key protected)
|
||||||
|
interestHandler.RegisterRoutes(r)
|
||||||
|
|
||||||
// Protected routes
|
// Protected routes
|
||||||
r.Group(func(r chi.Router) {
|
r.Group(func(r chi.Router) {
|
||||||
r.Use(authMiddleware.Authenticate)
|
r.Use(authMiddleware.Authenticate)
|
||||||
|
|||||||
58
internal/handler/interest.go
Normal file
58
internal/handler/interest.go
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
package handler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
"github.com/jmoiron/sqlx"
|
||||||
|
|
||||||
|
"github.com/daniil/homelab-api/internal/service"
|
||||||
|
)
|
||||||
|
|
||||||
|
type InterestHandler struct {
|
||||||
|
service *service.InterestService
|
||||||
|
secretKey string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewInterestHandler(db *sqlx.DB) *InterestHandler {
|
||||||
|
secretKey := os.Getenv("INTERNAL_API_KEY")
|
||||||
|
if secretKey == "" {
|
||||||
|
secretKey = "pulse-internal-2026"
|
||||||
|
}
|
||||||
|
return &InterestHandler{
|
||||||
|
service: service.NewInterestService(db),
|
||||||
|
secretKey: secretKey,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// RegisterRoutes регистрирует internal routes
|
||||||
|
func (h *InterestHandler) RegisterRoutes(r chi.Router) {
|
||||||
|
r.Post("/internal/calculate-interest", h.CalculateInterest)
|
||||||
|
}
|
||||||
|
|
||||||
|
// CalculateInterest запускает расчёт процентов для всех вкладов
|
||||||
|
// POST /internal/calculate-interest
|
||||||
|
// Header: X-Internal-Key: <secret>
|
||||||
|
func (h *InterestHandler) CalculateInterest(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// Verify internal API key
|
||||||
|
key := r.Header.Get("X-Internal-Key")
|
||||||
|
if key != h.secretKey {
|
||||||
|
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
results, err := h.service.CalculateAllDepositsInterest()
|
||||||
|
if err != nil {
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||||
|
"message": "Interest calculation completed",
|
||||||
|
"results": results,
|
||||||
|
})
|
||||||
|
}
|
||||||
10
internal/health/health_test.go
Normal file
10
internal/health/health_test.go
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
package health
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestHealthCheck(t *testing.T) {
|
||||||
|
status := "ok"
|
||||||
|
if status != "ok" {
|
||||||
|
t.Errorf("expected ok, got %s", status)
|
||||||
|
}
|
||||||
|
}
|
||||||
123
internal/service/interest.go
Normal file
123
internal/service/interest.go
Normal file
@@ -0,0 +1,123 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"math"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/daniil/homelab-api/internal/model"
|
||||||
|
"github.com/jmoiron/sqlx"
|
||||||
|
)
|
||||||
|
|
||||||
|
type InterestService struct {
|
||||||
|
db *sqlx.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewInterestService(db *sqlx.DB) *InterestService {
|
||||||
|
return &InterestService{db: db}
|
||||||
|
}
|
||||||
|
|
||||||
|
// CalculateAllDepositsInterest проверяет все вклады и начисляет проценты где нужно
|
||||||
|
func (s *InterestService) CalculateAllDepositsInterest() ([]string, error) {
|
||||||
|
var results []string
|
||||||
|
|
||||||
|
// Получаем все активные вклады
|
||||||
|
var deposits []model.SavingsCategory
|
||||||
|
err := s.db.Select(&deposits, `
|
||||||
|
SELECT * FROM savings_categories
|
||||||
|
WHERE is_deposit = true AND interest_rate > 0
|
||||||
|
`)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to fetch deposits: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("Found %d deposits to check", len(deposits))
|
||||||
|
|
||||||
|
for _, deposit := range deposits {
|
||||||
|
result, err := s.CalculateInterestForDeposit(&deposit)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Error calculating interest for %s: %v", deposit.Name, err)
|
||||||
|
results = append(results, fmt.Sprintf("❌ %s: %v", deposit.Name, err))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if result != "" {
|
||||||
|
results = append(results, result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return results, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CalculateInterestForDeposit рассчитывает проценты для одного вклада
|
||||||
|
func (s *InterestService) CalculateInterestForDeposit(deposit *model.SavingsCategory) (string, error) {
|
||||||
|
if !deposit.IsDeposit || deposit.InterestRate <= 0 {
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if !deposit.DepositStartDate.Valid {
|
||||||
|
return "", fmt.Errorf("no start date")
|
||||||
|
}
|
||||||
|
|
||||||
|
now := time.Now()
|
||||||
|
startDate := deposit.DepositStartDate.Time
|
||||||
|
|
||||||
|
// Проверяем не истёк ли срок вклада
|
||||||
|
if deposit.DepositTerm > 0 {
|
||||||
|
endDate := startDate.AddDate(0, deposit.DepositTerm, 0)
|
||||||
|
if now.After(endDate) {
|
||||||
|
log.Printf("Deposit %s expired on %v", deposit.Name, endDate)
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// День начисления = день открытия вклада
|
||||||
|
interestDay := startDate.Day()
|
||||||
|
|
||||||
|
// Сегодня день начисления?
|
||||||
|
if now.Day() != interestDay {
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Проверяем не начислены ли уже проценты за этот месяц
|
||||||
|
currentMonth := fmt.Sprintf("%02d.%d", now.Month(), now.Year())
|
||||||
|
searchPattern := "%" + currentMonth + "%"
|
||||||
|
var count int
|
||||||
|
err := s.db.Get(&count, `SELECT COUNT(*) FROM savings_transactions WHERE category_id = $1 AND description LIKE $2`, deposit.ID, searchPattern)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if count > 0 {
|
||||||
|
log.Printf("Interest for %s already calculated for %s", deposit.Name, currentMonth)
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Получаем текущий баланс
|
||||||
|
var balance float64
|
||||||
|
err = s.db.Get(&balance, `SELECT COALESCE(SUM(CASE WHEN type = 'deposit' THEN amount ELSE -amount END), 0) FROM savings_transactions WHERE category_id = $1`, deposit.ID)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Рассчитываем проценты (годовая ставка / 12)
|
||||||
|
monthlyRate := deposit.InterestRate / 12 / 100
|
||||||
|
interest := balance * monthlyRate
|
||||||
|
interest = math.Round(interest*100) / 100
|
||||||
|
|
||||||
|
if interest <= 0 {
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Добавляем транзакцию
|
||||||
|
description := fmt.Sprintf("Проценты за %s (%.2f%% годовых)", currentMonth, deposit.InterestRate)
|
||||||
|
|
||||||
|
_, err = s.db.Exec(`INSERT INTO savings_transactions (user_id, category_id, type, amount, date, description) VALUES ($1, $2, 'deposit', $3, $4, $5)`, deposit.UserID, deposit.ID, interest, now.Format("2006-01-02"), description)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
result := fmt.Sprintf("✅ %s: +%.2f₽ (баланс: %.2f₽)", deposit.Name, interest, balance+interest)
|
||||||
|
log.Printf(result)
|
||||||
|
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user