66 lines
1.6 KiB
Go
66 lines
1.6 KiB
Go
package database
|
|
|
|
import (
|
|
"backend/model"
|
|
"encoding/json"
|
|
"fmt"
|
|
"os"
|
|
"strings"
|
|
)
|
|
|
|
func CreateOperation(operation *model.Operation) error {
|
|
e := Db.Where(model.Operation{
|
|
Title: operation.Title,
|
|
Amount: operation.Amount,
|
|
Note: operation.Note,
|
|
Icon: operation.Icon,
|
|
Type: operation.Type,
|
|
Date: operation.Date,
|
|
UserID: operation.UserID,
|
|
CategoryID: operation.CategoryID,
|
|
SubcategoryID: operation.SubcategoryID,
|
|
}).FirstOrCreate(&operation).Error
|
|
if e != nil {
|
|
return e
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func GetOperationsFromFile(filename string) []model.Operation {
|
|
data, e := os.ReadFile(filename)
|
|
if e != nil {
|
|
panic(e)
|
|
}
|
|
decoder := json.NewDecoder(strings.NewReader(string(data)))
|
|
var res []model.Operation
|
|
decoder.Decode(&res)
|
|
return res
|
|
}
|
|
|
|
func GetAllOperations(userid string) ([]model.Operation, error) {
|
|
var operations []model.Operation
|
|
e := Db.Where(model.Operation{UserID: userid}).Find(&operations).Error
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
for i := range operations {
|
|
if operations[i].CategoryID == "" {
|
|
continue
|
|
}
|
|
var category model.Category
|
|
e := Db.First(&category, "ID = ?", operations[i].CategoryID).Error
|
|
if e != nil {
|
|
fmt.Println(e)
|
|
return nil, e
|
|
}
|
|
operations[i].Category = category
|
|
// // var subcategories []model.Subcategory
|
|
// // e := Db.Where(model.Subcategory{CategoryID: categories[i].ID}).Find(&subcategories).Error
|
|
// // if e != nil {
|
|
// // return nil, e
|
|
// // }
|
|
// categories[i].Subcategories = subcategories
|
|
}
|
|
return operations, nil
|
|
}
|