moving handlers into service. adding website

This commit is contained in:
samantha42
2026-04-29 08:38:41 +02:00
parent 57ae3cfb06
commit 22c6a22373
18 changed files with 752 additions and 586 deletions

View File

@@ -3,12 +3,51 @@ package service
import (
"Portifolio/internal/model"
"database/sql"
"encoding/json"
"net/http"
_ "github.com/mattn/go-sqlite3"
)
func InsertCurrency(db *sql.DB, input model.CurrencyInput) (int, error) {
res, err := db.Exec(
type Service struct {
db *sql.DB
}
func (s *Service) AddCurrencyHandler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var input model.CurrencyInput
if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
http.Error(w, "invalid json", http.StatusBadRequest)
return
}
id, err := s.InsertCurrency(input)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(map[string]any{"status": "created", "id": id})
}
}
func (s *Service) GetCurrenciesHandler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
currencies, err := s.GetAllCurrencies()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(currencies)
}
}
func (s *Service) InsertCurrency(input model.CurrencyInput) (int, error) {
res, err := s.db.Exec(
`INSERT INTO currencies (code, name) VALUES (?, ?)`,
input.Code, input.Name,
)
@@ -19,9 +58,9 @@ func InsertCurrency(db *sql.DB, input model.CurrencyInput) (int, error) {
return int(id), err
}
func GetCurrencyByCode(db *sql.DB, code string) (*model.Currency, error) {
func (s *Service) GetCurrencyByCode(code string) (*model.Currency, error) {
c := &model.Currency{}
err := db.QueryRow(
err := s.db.QueryRow(
`SELECT id, code, name FROM currencies WHERE code = ?`, code,
).Scan(&c.ID, &c.Code, &c.Name)
if err == sql.ErrNoRows {
@@ -30,8 +69,8 @@ func GetCurrencyByCode(db *sql.DB, code string) (*model.Currency, error) {
return c, err
}
func GetAllCurrencies(db *sql.DB) ([]model.Currency, error) {
rows, err := db.Query(`SELECT id, code, name FROM currencies ORDER BY code`)
func (s *Service) GetAllCurrencies() ([]model.Currency, error) {
rows, err := s.db.Query(`SELECT id, code, name FROM currencies ORDER BY code`)
if err != nil {
return nil, err
}

114
internal/service/main.go Normal file
View File

@@ -0,0 +1,114 @@
package service
import (
"Portifolio/internal/database"
"Portifolio/internal/model"
"database/sql"
"encoding/json"
"net/http"
"runtime"
"time"
_ "github.com/mattn/go-sqlite3"
)
var startTime = time.Now()
func New(db *sql.DB) *Service {
return &Service{db: db}
}
func (s *Service) HealthHandler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
health := s.CheckHealth()
if health["status"] != "ok" {
w.WriteHeader(http.StatusServiceUnavailable)
}
json.NewEncoder(w).Encode(health)
}
}
func (s *Service) CheckHealth() map[string]any {
dbStatus := "ok"
dbLatency := ""
t := time.Now()
if err := s.db.Ping(); err != nil {
dbStatus = "error: " + err.Error()
} else {
dbLatency = time.Since(t).String()
}
stats := s.db.Stats()
status := "ok"
if dbStatus != "ok" {
status = "degraded"
}
var mem runtime.MemStats
runtime.ReadMemStats(&mem)
return map[string]any{
"status": status,
"uptime": time.Since(startTime).String(),
"database": map[string]any{
"status": dbStatus,
"latency": dbLatency,
"open_connections": stats.OpenConnections,
"in_use": stats.InUse,
"idle": stats.Idle,
},
"memory": map[string]any{
"alloc_mb": bToMb(mem.Alloc),
"sys_mb": bToMb(mem.Sys),
"num_gc": mem.NumGC,
},
"go_version": runtime.Version(),
"goroutines": runtime.NumGoroutine(),
}
}
func bToMb(b uint64) float64 {
return float64(b) / 1024 / 1024
}
func (s *Service) AddCompanyHandler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var input model.CompanyInput
if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
http.Error(w, "invalid request body", http.StatusBadRequest)
return
}
id, err := database.AddCompany(s.db, input)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(map[string]int{"id": id})
}
}
func (s *Service) GetAllCompanies() ([]model.Company, error) {
companies, err := database.GetAllCompanies(s.db)
return companies, err
}
func (s *Service) GetCompaniesHandler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
companies, err := database.GetAllCompanies(s.db)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(companies)
}
}

View File

@@ -3,15 +3,16 @@ package service
import (
"Portifolio/internal/database"
"Portifolio/internal/model"
"database/sql"
"encoding/json"
"fmt"
"net/http"
_ "github.com/mattn/go-sqlite3"
)
func UpdatePositionByTradeList(db *sql.DB) error {
func (s *Service) UpdatePositionByTradeList() error {
trades, err := database.GetTrades(db)
trades, err := database.GetTrades(s.db)
if err != nil {
fmt.Printf("Failed to get the trades from db: %s", err)
}
@@ -42,10 +43,115 @@ func UpdatePositionByTradeList(db *sql.DB) error {
NewPositinos = append(NewPositinos, pos)
}
err = database.UpdatePositions(db, NewPositinos)
err = database.UpdatePositions(s.db, NewPositinos)
if err != nil {
return fmt.Errorf("Failed to insert the new postions number into db: %s", err)
}
return nil
}
func (s *Service) AddTradeHandler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req model.AddTradeRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "invalid json", http.StatusBadRequest)
return
}
if err := req.Validate(); err != nil {
http.Error(w, fmt.Sprintf("failed to validate trade: %s", err), http.StatusBadRequest)
return
}
currency, err := database.GetCurrencyByCode(s.db, req.CurrencyCode)
if err != nil {
http.Error(w, fmt.Sprintf("failed to find currency: %s", err), http.StatusInternalServerError)
return
}
switch model.TradeType(req.Type) {
case model.DividendType:
dividend, err := req.ToDividend()
if err != nil {
http.Error(w, fmt.Sprintf("failed to build dividend: %s", err), http.StatusBadRequest)
return
}
dividend.CurrencyCode = currency.Code
if err := database.InsertDividend(s.db, dividend); err != nil {
http.Error(w, fmt.Sprintf("failed to insert dividend: %s", err), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]any{"success": true})
case model.BuyType, model.SellType:
trade, err := req.ToTrade()
if err != nil {
http.Error(w, fmt.Sprintf("failed to build trade: %s", err), http.StatusBadRequest)
return
}
trade.CurrencyCode = currency.Code
if err := database.InsertTrade(s.db, trade); err != nil {
http.Error(w, fmt.Sprintf("failed to insert trade: %s", err), http.StatusInternalServerError)
return
}
update := true
if err := s.UpdatePositionByTradeList(); err != nil {
update = false
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]any{"success": true, "position_update": update})
default:
http.Error(w, fmt.Sprintf("unknown trade type: %d", req.Type), http.StatusBadRequest)
}
}
}
func (s *Service) GetTrades() ([]model.Trade, error) {
TradeList, err := database.GetTrades(s.db)
return TradeList, err
}
func (s *Service) GetTradeListHandler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
tradeList, err := database.GetTrades(s.db)
if err != nil {
http.Error(w, fmt.Sprintf("failed to fetch trades: %s", err), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(tradeList); err != nil {
http.Error(w, fmt.Sprintf("failed to encode trades: %s", err), http.StatusInternalServerError)
return
}
}
}
func (s *Service) GetPositions() ([]model.Position, error) {
posList, err := database.GetPositions(s.db)
return posList, err
}
func (s *Service) GetPositionListHandler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
posList, err := database.GetPositions(s.db)
if err != nil {
http.Error(w, fmt.Sprintf("failed to fetch postiton: %s", err), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(posList); err != nil {
http.Error(w, fmt.Sprintf("failed to encode positions: %s", err), http.StatusInternalServerError)
return
}
}
}

View File

@@ -0,0 +1,82 @@
package service
import (
"Portifolio/internal/database"
"Portifolio/internal/model"
"encoding/json"
"fmt"
"net/http"
_ "github.com/mattn/go-sqlite3"
)
func (s *Service) AddRevenueEntryHandler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var input struct {
CompanyID int `json:"company_id"`
CurrencyID int `json:"currency_id"`
PeriodType string `json:"period_type"`
Year int `json:"year"`
Index int `json:"index"`
Category string `json:"category"`
Value float64 `json:"value"`
}
if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
http.Error(w, "invalid json", http.StatusBadRequest)
return
}
var period model.Period
switch input.PeriodType {
case "Q":
period = model.QuarterPeriod(input.Year, input.Index)
case "H":
period = model.HalfYearPeriod(input.Year, input.Index)
case "Y":
period = model.FullYearPeriod(input.Year)
default:
http.Error(w, "invalid period_type", http.StatusBadRequest)
return
}
rev := model.RevenueInsert{
CompanyID: input.CompanyID,
CurrencyID: input.CurrencyID,
CategoryName: input.Category,
Period: period,
Value: input.Value,
}
err := database.InsertRevenue(s.db, rev)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(map[string]string{"status": "created"})
}
}
func (s *Service) GetCompanyRevenueCategories() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var input struct {
CompanyID int `json:"company_id"`
}
if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
http.Error(w, "invalid json", http.StatusBadRequest)
return
}
catlist, err := database.GetCategoriesByCompanyID(s.db, input.CompanyID)
if err != nil {
http.Error(w, fmt.Sprintf("Could not find categories by that id:%s", err), http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(map[string][]string{"list": catlist})
}
}