first commit

This commit is contained in:
Akhil Gupta
2021-05-29 15:20:50 +05:30
commit d25c30a7b2
194 changed files with 49873 additions and 0 deletions

179
server/controllers/auth.go Normal file
View File

@@ -0,0 +1,179 @@
package controllers
import (
"errors"
"fmt"
"net/http"
"os"
"github.com/akhilrex/hammond/common"
"github.com/akhilrex/hammond/db"
"github.com/akhilrex/hammond/models"
"github.com/akhilrex/hammond/service"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
)
func RegisterAnonController(router *gin.RouterGroup) {
router.POST("/login", userLogin)
router.POST("/auth/initialize", initializeSystem)
}
func RegisterAuthController(router *gin.RouterGroup) {
router.POST("/refresh", refresh)
router.GET("/me", me)
router.POST("/register", ShouldBeAdmin(), userRegister)
router.POST("/changePassword", changePassword)
}
func ShouldBeAdmin() gin.HandlerFunc {
return func(c *gin.Context) {
model := c.MustGet("userModel").(db.User)
if model.Role != db.ADMIN {
c.JSON(http.StatusUnauthorized, gin.H{})
} else {
c.Next()
}
}
}
func me(c *gin.Context) {
user, err := service.GetUserById(c.MustGet("userId").(string))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{})
}
c.JSON(http.StatusOK, user)
}
func userRegister(c *gin.Context) {
var registerRequest models.RegisterRequest
if err := c.ShouldBind(&registerRequest); err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewValidatorError(err))
return
}
if err := service.CreateUser(&registerRequest, *registerRequest.Role); err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewError("database", err))
return
}
c.JSON(http.StatusCreated, gin.H{"success": true})
}
func initializeSystem(c *gin.Context) {
canInitialize, err := service.CanInitializeSystem()
if !canInitialize {
c.JSON(http.StatusUnprocessableEntity, err)
}
var registerRequest models.RegisterRequest
if err := c.ShouldBind(&registerRequest); err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewValidatorError(err))
return
}
if err := service.CreateUser(&registerRequest, db.ADMIN); err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewError("initializeSystem", err))
return
}
service.UpdateSettings(registerRequest.Currency, *registerRequest.DistanceUnit)
c.JSON(http.StatusCreated, gin.H{"success": true})
}
func userLogin(c *gin.Context) {
var loginRequest models.LoginRequest
if err := c.ShouldBind(&loginRequest); err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewValidatorError(err))
return
}
user, err := db.FindOneUser(&db.User{Email: loginRequest.Email})
if err != nil {
c.JSON(http.StatusForbidden, common.NewError("login", errors.New("Not Registered email or invalid password")))
return
}
if user.CheckPassword(loginRequest.Password) != nil {
c.JSON(http.StatusForbidden, common.NewError("login", errors.New("Not Registered email or invalid password")))
return
}
UpdateContextUserModel(c, user.ID)
token, refreshToken := common.GenToken(user.ID, user.Role)
response := models.LoginResponse{
Name: user.Name,
Email: user.Email,
Token: token,
RefreshToken: refreshToken,
Role: user.RoleDetail().Long,
}
c.JSON(http.StatusOK, response)
}
func refresh(c *gin.Context) {
type tokenReqBody struct {
RefreshToken string `json:"refreshToken"`
}
tokenReq := tokenReqBody{}
c.Bind(&tokenReq)
token, _ := jwt.Parse(tokenReq.RefreshToken, func(token *jwt.Token) (interface{}, error) {
// Don't forget to validate the alg is what you expect:
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
// hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
return []byte(os.Getenv("JWT_SECRET")), nil
})
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
// Get the user record from database or
// run through your business logic to verify if the user can log in
user, err := service.GetUserById(claims["id"].(string))
if err == nil {
token, refreshToken := common.GenToken(user.ID, user.Role)
response := models.LoginResponse{
Name: user.Name,
Email: user.Email,
Token: token,
RefreshToken: refreshToken,
Role: user.RoleDetail().Long,
}
c.JSON(http.StatusOK, response)
} else {
c.JSON(http.StatusUnauthorized, gin.H{})
}
} else {
c.JSON(http.StatusUnauthorized, gin.H{})
}
}
func changePassword(c *gin.Context) {
var request models.ChangePasswordRequest
if err := c.ShouldBind(&request); err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewValidatorError(err))
return
}
user, err := service.GetUserById(c.GetString("userId"))
if err != nil {
c.JSON(http.StatusForbidden, common.NewError("changePassword", errors.New("Not Registered email or invalid password")))
return
}
if user.CheckPassword(request.OldPassword) != nil {
c.JSON(http.StatusForbidden, common.NewError("changePassword", errors.New("Not Registered email or invalid password")))
return
}
user.SetPassword(request.NewPassword)
success, err := service.UpdatePassword(user.ID, request.NewPassword)
c.JSON(http.StatusOK, success)
}

157
server/controllers/files.go Normal file
View File

@@ -0,0 +1,157 @@
package controllers
import (
"net/http"
"os"
"github.com/akhilrex/hammond/common"
"github.com/akhilrex/hammond/db"
"github.com/akhilrex/hammond/models"
"github.com/akhilrex/hammond/service"
"github.com/gin-gonic/gin"
)
func RegisterFilesController(router *gin.RouterGroup) {
router.POST("/upload", uploadFile)
router.POST("/quickEntries", createQuickEntry)
router.GET("/quickEntries", getAllQuickEntries)
router.GET("/me/quickEntries", getMyQuickEntries)
router.GET("/quickEntries/:id", getQuickEntryById)
router.POST("/quickEntries/:id/process", setQuickEntryAsProcessed)
router.GET("/attachments/:id/file", getAttachmentFile)
}
func createQuickEntry(c *gin.Context) {
var request models.CreateQuickEntryModel
if err := c.ShouldBind(&request); err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewValidatorError(err))
return
}
attachment, err := saveUploadedFile(c, "file")
if err != nil {
c.JSON(http.StatusUnprocessableEntity, err)
return
}
if err := c.ShouldBind(&request); err != nil {
c.JSON(http.StatusUnprocessableEntity, err)
return
}
quickEntry, err := service.CreateQuickEntry(request, attachment.ID, c.MustGet("userId").(string))
if err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewError("createQuickEntry", err))
return
}
c.JSON(http.StatusCreated, quickEntry)
}
func getAllQuickEntries(c *gin.Context) {
quickEntries, err := service.GetAllQuickEntries("")
if err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewError("getAllQuickEntries", err))
return
}
c.JSON(http.StatusOK, quickEntries)
}
func getMyQuickEntries(c *gin.Context) {
quickEntries, err := service.GetQuickEntriesForUser(c.MustGet("userId").(string), "")
if err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewError("getMyQuickEntries", err))
return
}
c.JSON(http.StatusOK, quickEntries)
}
func getQuickEntryById(c *gin.Context) {
var searchByIdQuery models.SearchByIdQuery
if c.ShouldBindUri(&searchByIdQuery) == nil {
quickEntry, err := service.GetQuickEntryById(searchByIdQuery.Id)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewError("getVehicleById", err))
return
}
c.JSON(http.StatusOK, quickEntry)
} else {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
}
}
func setQuickEntryAsProcessed(c *gin.Context) {
var searchByIdQuery models.SearchByIdQuery
if c.ShouldBindUri(&searchByIdQuery) == nil {
err := service.SetQuickEntryAsProcessed(searchByIdQuery.Id)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewError("getVehicleById", err))
return
}
c.JSON(http.StatusOK, gin.H{})
} else {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
}
}
func uploadFile(c *gin.Context) {
attachment, err := saveMultipleUploadedFile(c, "file")
if err != nil {
c.JSON(http.StatusBadRequest, err)
} else {
c.JSON(http.StatusOK, attachment)
}
}
func getAttachmentFile(c *gin.Context) {
var searchByIdQuery models.SearchByIdQuery
if c.ShouldBindUri(&searchByIdQuery) == nil {
attachment, err := db.GetAttachmentById(searchByIdQuery.Id)
if err == nil {
if _, err = os.Stat(attachment.Path); os.IsNotExist(err) {
c.Status(404)
} else {
c.File(attachment.Path)
}
}
} else {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
}
}
func saveUploadedFile(c *gin.Context, fileVariable string) (*db.Attachment, error) {
if fileVariable == "" {
fileVariable = "file"
}
file, err := c.FormFile(fileVariable)
if err != nil {
return nil, err
}
filePath := service.GetFilePath(file.Filename)
if err := c.SaveUploadedFile(file, filePath); err != nil {
return nil, err
}
return service.CreateAttachment(filePath, file.Filename, file.Size, file.Header.Get("Content-Type"), c.MustGet("userId").(string))
}
func saveMultipleUploadedFile(c *gin.Context, fileVariable string) ([]*db.Attachment, error) {
if fileVariable == "" {
fileVariable = "files"
}
form, err := c.MultipartForm()
if err != nil {
return nil, err
}
files := form.File[fileVariable]
var toReturn []*db.Attachment
for _, file := range files {
filePath := service.GetFilePath(file.Filename)
if err := c.SaveUploadedFile(file, filePath); err != nil {
return nil, err
}
attachment, err := service.CreateAttachment(filePath, file.Filename, file.Size, file.Header.Get("Content-Type"), c.MustGet("userId").(string))
if err != nil {
return nil, err
}
toReturn = append(toReturn, attachment)
}
return toReturn, nil
}

View File

@@ -0,0 +1,64 @@
package controllers
import (
"net/http"
"github.com/akhilrex/hammond/common"
"github.com/akhilrex/hammond/db"
"github.com/akhilrex/hammond/models"
"github.com/akhilrex/hammond/service"
"github.com/gin-gonic/gin"
)
func RegisterAnonMasterConroller(router *gin.RouterGroup) {
router.GET("/masters", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"fuelUnits": db.FuelUnitDetails,
"fuelTypes": db.FuelTypeDetails,
"distanceUnits": db.DistanceUnitDetails,
"roles": db.RoleDetails,
"currencies": models.GetCurrencyMasterList(),
})
})
}
func RegisterMastersController(router *gin.RouterGroup) {
router.GET("/settings", getSettings)
router.POST("/settings", udpateSettings)
router.POST("/me/settings", udpateMySettings)
}
func getSettings(c *gin.Context) {
c.JSON(http.StatusOK, service.GetSettings())
}
func udpateSettings(c *gin.Context) {
var model models.UpdateSettingModel
if err := c.ShouldBind(&model); err == nil {
err := service.UpdateSettings(model.Currency, *model.DistanceUnit)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewError("udpateSettings", err))
return
}
c.JSON(http.StatusOK, gin.H{})
} else {
c.JSON(http.StatusUnprocessableEntity, common.NewValidatorError(err))
}
}
func udpateMySettings(c *gin.Context) {
var model models.UpdateSettingModel
if err := c.ShouldBind(&model); err == nil {
err := service.UpdateUserSettings(c.MustGet("userId").(string), model.Currency, *model.DistanceUnit)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewError("udpateMySettings", err))
return
}
c.JSON(http.StatusOK, gin.H{})
} else {
c.JSON(http.StatusUnprocessableEntity, common.NewValidatorError(err))
}
}

View File

@@ -0,0 +1,71 @@
package controllers
import (
"net/http"
"os"
"strings"
"github.com/akhilrex/hammond/db"
"github.com/dgrijalva/jwt-go"
"github.com/dgrijalva/jwt-go/request"
"github.com/gin-gonic/gin"
)
// Strips 'BEARER ' prefix from token string
func stripBearerPrefixFromTokenString(tok string) (string, error) {
// Should be a bearer token
if len(tok) > 6 && strings.ToUpper(tok[0:6]) == "BEARER " {
return tok[7:], nil
}
return tok, nil
}
// Extract token from Authorization header
// Uses PostExtractionFilter to strip "TOKEN " prefix from header
var AuthorizationHeaderExtractor = &request.PostExtractionFilter{
request.HeaderExtractor{"Authorization"},
stripBearerPrefixFromTokenString,
}
// Extractor for OAuth2 access tokens. Looks in 'Authorization'
// header then 'access_token' argument for a token.
var MyAuth2Extractor = &request.MultiExtractor{
AuthorizationHeaderExtractor,
request.ArgumentExtractor{"access_token"},
}
// A helper to write user_id and user_model to the context
func UpdateContextUserModel(c *gin.Context, my_user_id string) {
var myUserModel db.User
if my_user_id != "" {
db.DB.First(&myUserModel, map[string]string{
"ID": my_user_id,
})
}
c.Set("userId", my_user_id)
c.Set("userModel", myUserModel)
}
// You can custom middlewares yourself as the doc: https://github.com/gin-gonic/gin#custom-middleware
// r.Use(AuthMiddleware(true))
func AuthMiddleware(auto401 bool) gin.HandlerFunc {
return func(c *gin.Context) {
UpdateContextUserModel(c, "")
token, err := request.ParseFromRequest(c.Request, MyAuth2Extractor, func(token *jwt.Token) (interface{}, error) {
b := ([]byte(os.Getenv("JWT_SECRET")))
return b, nil
})
if err != nil {
if auto401 {
c.AbortWithError(http.StatusUnauthorized, err)
}
return
}
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
my_user_id := claims["id"].(string)
//fmt.Println(my_user_id,claims["id"])
UpdateContextUserModel(c, my_user_id)
}
}
}

View File

@@ -0,0 +1,70 @@
package controllers
import (
"fmt"
"net/http"
"github.com/akhilrex/hammond/common"
"github.com/akhilrex/hammond/db"
"github.com/akhilrex/hammond/models"
"github.com/akhilrex/hammond/service"
"github.com/gin-gonic/gin"
)
func RegisterSetupController(router *gin.RouterGroup) {
router.POST("/clarkson/check", canMigrate)
router.POST("/clarkson/migrate", migrate)
router.GET("/system/status", appInitialized)
}
func appInitialized(c *gin.Context) {
canInitialize, err := service.CanInitializeSystem()
message := ""
if err != nil {
message = err.Error()
}
c.JSON(http.StatusOK, gin.H{"initialized": !canInitialize, "message": message})
}
func canMigrate(c *gin.Context) {
var request models.ClarksonMigrationModel
if err := c.ShouldBind(&request); err == nil {
canMigrate, data, errr := db.CanMigrate(request.Url)
errorMessage := ""
if errr != nil {
errorMessage = errr.Error()
}
c.JSON(http.StatusOK, gin.H{
"canMigrate": canMigrate,
"data": data,
"message": errorMessage,
})
} else {
c.JSON(http.StatusUnprocessableEntity, common.NewValidatorError(err))
}
}
func migrate(c *gin.Context) {
var request models.ClarksonMigrationModel
if err := c.ShouldBind(&request); err == nil {
canMigrate, _, _ := db.CanMigrate(request.Url)
if !canMigrate {
c.JSON(http.StatusBadRequest, fmt.Errorf("cannot migrate database. please check connection string."))
return
}
success, err := db.MigrateClarkson(request.Url)
if !success {
c.JSON(http.StatusBadRequest, err)
return
}
c.JSON(http.StatusOK, gin.H{
"success": success,
})
} else {
c.JSON(http.StatusUnprocessableEntity, common.NewValidatorError(err))
}
}

View File

@@ -0,0 +1,22 @@
package controllers
import (
"net/http"
"github.com/akhilrex/hammond/db"
"github.com/gin-gonic/gin"
)
func RegisterUserController(router *gin.RouterGroup) {
router.GET("/users", allUsers)
}
func allUsers(c *gin.Context) {
users, err := db.GetAllUsers()
if err != nil {
c.JSON(http.StatusBadRequest, err)
return
}
c.JSON(http.StatusOK, users)
}

View File

@@ -0,0 +1,436 @@
package controllers
import (
"net/http"
"github.com/akhilrex/hammond/common"
"github.com/akhilrex/hammond/models"
"github.com/akhilrex/hammond/service"
"github.com/gin-gonic/gin"
)
func RegisterVehicleController(router *gin.RouterGroup) {
router.POST("/vehicles", createVehicle)
router.GET("/vehicles", getAllVehicles)
router.GET("/vehicles/:id", getVehicleById)
router.PUT("/vehicles/:id", updateVehicle)
router.GET("/vehicles/:id/stats", getVehicleStats)
router.GET("/vehicles/:id/users", getVehicleUsers)
router.POST("/vehicles/:id/users/:subId", shareVehicle)
router.DELETE("/vehicles/:id/users/:subId", unshareVehicle)
router.GET("/me/vehicles", getMyVehicles)
router.GET("/me/stats", getMystats)
router.GET("/vehicles/:id/fillups", getFillupsByVehicleId)
router.POST("/vehicles/:id/fillups", createFillup)
router.GET("/vehicles/:id/fillups/:subId", getFillupById)
router.PUT("/vehicles/:id/fillups/:subId", updateFillup)
router.DELETE("/vehicles/:id/fillups/:subId", deleteFillup)
router.GET("/vehicles/:id/expenses", getExpensesByVehicleId)
router.POST("/vehicles/:id/expenses", createExpense)
router.GET("/vehicles/:id/expenses/:subId", getExpenseById)
router.PUT("/vehicles/:id/expenses/:subId", updateExpense)
router.DELETE("/vehicles/:id/expenses/:subId", deleteExpense)
router.POST("/vehicles/:id/attachments", createVehicleAttachment)
router.GET("/vehicles/:id/attachments", getVehicleAttachments)
}
func createVehicle(c *gin.Context) {
var request models.CreateVehicleRequest
if err := c.ShouldBind(&request); err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewValidatorError(err))
return
}
vehicle, err := service.CreateVehicle(request, c.MustGet("userId").(string))
if err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewError("createVehicle", err))
return
}
c.JSON(http.StatusCreated, vehicle)
}
func getVehicleById(c *gin.Context) {
var searchByIdQuery models.SearchByIdQuery
if c.ShouldBindUri(&searchByIdQuery) == nil {
vehicle, err := service.GetVehicleById(searchByIdQuery.Id)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewError("getVehicleById", err))
return
}
c.JSON(http.StatusOK, vehicle)
} else {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
}
}
func updateVehicle(c *gin.Context) {
var searchByIdQuery models.SearchByIdQuery
var updateVehicleModel models.UpdateVehicleRequest
if err := c.ShouldBindUri(&searchByIdQuery); err == nil {
if err := c.ShouldBind(&updateVehicleModel); err == nil {
err := service.UpdateVehicle(searchByIdQuery.Id, updateVehicleModel)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewError("getVehicleById", err))
return
}
c.JSON(http.StatusOK, gin.H{})
} else {
c.JSON(http.StatusUnprocessableEntity, common.NewValidatorError(err))
}
} else {
c.JSON(http.StatusUnprocessableEntity, common.NewValidatorError(err))
}
}
func getAllVehicles(c *gin.Context) {
vehicles, err := service.GetAllVehicles()
if err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewError("getVehicleById", err))
return
}
c.JSON(200, vehicles)
}
func getMyVehicles(c *gin.Context) {
vehicles, err := service.GetUserVehicles(c.MustGet("userId").(string))
if err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewError("getMyVehicles", err))
return
}
c.JSON(200, vehicles)
}
func getFillupsByVehicleId(c *gin.Context) {
var searchByIdQuery models.SearchByIdQuery
if err := c.ShouldBindUri(&searchByIdQuery); err == nil {
fillups, err := service.GetFillupsByVehicleId(searchByIdQuery.Id)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewError("getFillupsByVehicleId", err))
return
}
c.JSON(http.StatusOK, fillups)
} else {
c.JSON(http.StatusUnprocessableEntity, common.NewValidatorError(err))
}
}
func getExpensesByVehicleId(c *gin.Context) {
var searchByIdQuery models.SearchByIdQuery
if err := c.ShouldBindUri(&searchByIdQuery); err == nil {
data, err := service.GetExpensesByVehicleId(searchByIdQuery.Id)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewError("getExpensesByVehicleId", err))
return
}
c.JSON(http.StatusOK, data)
} else {
c.JSON(http.StatusUnprocessableEntity, common.NewValidatorError(err))
}
}
func createFillup(c *gin.Context) {
var request models.CreateFillupRequest
var searchByIdQuery models.SearchByIdQuery
if err := c.ShouldBindUri(&searchByIdQuery); err == nil {
if err := c.ShouldBind(&request); err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewValidatorError(err))
return
}
fillup, err := service.CreateFillup(request)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewError("createFillup", err))
return
}
c.JSON(http.StatusCreated, fillup)
} else {
c.JSON(http.StatusUnprocessableEntity, common.NewValidatorError(err))
}
}
func createExpense(c *gin.Context) {
var request models.CreateExpenseRequest
var searchByIdQuery models.SearchByIdQuery
if err := c.ShouldBindUri(&searchByIdQuery); err == nil {
if err := c.ShouldBind(&request); err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewValidatorError(err))
return
}
expense, err := service.CreateExpense(request)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewError("createExpense", err))
return
}
c.JSON(http.StatusCreated, expense)
} else {
c.JSON(http.StatusUnprocessableEntity, common.NewValidatorError(err))
}
}
func updateExpense(c *gin.Context) {
var searchByIdQuery models.SubItemQuery
var updateExpenseModel models.UpdateExpenseRequest
if err := c.ShouldBindUri(&searchByIdQuery); err == nil {
if err := c.ShouldBind(&updateExpenseModel); err == nil {
err := service.UpdateExpense(searchByIdQuery.SubId, updateExpenseModel)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewError("getExpenseById", err))
return
}
c.JSON(http.StatusOK, gin.H{})
} else {
c.JSON(http.StatusUnprocessableEntity, common.NewValidatorError(err))
}
} else {
c.JSON(http.StatusUnprocessableEntity, common.NewValidatorError(err))
}
}
func updateFillup(c *gin.Context) {
var searchByIdQuery models.SubItemQuery
var updateFillupModel models.UpdateFillupRequest
if err := c.ShouldBindUri(&searchByIdQuery); err == nil {
if err := c.ShouldBind(&updateFillupModel); err == nil {
err := service.UpdateFillup(searchByIdQuery.SubId, updateFillupModel)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewError("getFillupById", err))
return
}
c.JSON(http.StatusOK, gin.H{})
} else {
c.JSON(http.StatusUnprocessableEntity, common.NewValidatorError(err))
}
} else {
c.JSON(http.StatusUnprocessableEntity, common.NewValidatorError(err))
}
}
func deleteExpense(c *gin.Context) {
var searchByIdQuery models.SubItemQuery
if err := c.ShouldBindUri(&searchByIdQuery); err == nil {
err := service.DeleteExpenseById(searchByIdQuery.SubId)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewError("getExpenseById", err))
return
}
c.JSON(http.StatusOK, gin.H{})
} else {
c.JSON(http.StatusUnprocessableEntity, common.NewValidatorError(err))
}
}
func deleteFillup(c *gin.Context) {
var searchByIdQuery models.SubItemQuery
if err := c.ShouldBindUri(&searchByIdQuery); err == nil {
err := service.DeleteFillupById(searchByIdQuery.SubId)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewError("getFillupById", err))
return
}
c.JSON(http.StatusOK, gin.H{})
} else {
c.JSON(http.StatusUnprocessableEntity, common.NewValidatorError(err))
}
}
func getExpenseById(c *gin.Context) {
var searchByIdQuery models.SubItemQuery
if err := c.ShouldBindUri(&searchByIdQuery); err == nil {
obj, err := service.GetExpenseById(searchByIdQuery.SubId)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewError("getExpenseById", err))
return
}
c.JSON(http.StatusOK, obj)
} else {
c.JSON(http.StatusUnprocessableEntity, common.NewValidatorError(err))
}
}
func getFillupById(c *gin.Context) {
var searchByIdQuery models.SubItemQuery
if err := c.ShouldBindUri(&searchByIdQuery); err == nil {
obj, err := service.GetFillupById(searchByIdQuery.SubId)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewError("getFillupById", err))
return
}
c.JSON(http.StatusOK, obj)
} else {
c.JSON(http.StatusUnprocessableEntity, common.NewValidatorError(err))
}
}
func createVehicleAttachment(c *gin.Context) {
var searchByIdQuery models.SearchByIdQuery
var dataModel models.CreateVehicleAttachmentModel
if err := c.ShouldBindUri(&searchByIdQuery); err == nil {
if err := c.ShouldBind(&dataModel); err == nil {
vehicle, err := service.GetVehicleById(searchByIdQuery.Id)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewError("createVehicleAttachment", err))
return
}
attachment, err := saveUploadedFile(c, "file")
if err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewError("createVehicleAttachment", err))
return
}
err = service.CreateVehicleAttachment(vehicle.ID, attachment.ID, dataModel.Title)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewError("createVehicleAttachment", err))
return
}
c.JSON(http.StatusOK, gin.H{})
} else {
c.JSON(http.StatusUnprocessableEntity, common.NewValidatorError(err))
}
} else {
c.JSON(http.StatusUnprocessableEntity, common.NewValidatorError(err))
}
}
func getVehicleAttachments(c *gin.Context) {
var searchByIdQuery models.SearchByIdQuery
if err := c.ShouldBindUri(&searchByIdQuery); err == nil {
vehicle, err := service.GetVehicleById(searchByIdQuery.Id)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewError("createVehicleAttachment", err))
return
}
attachments, err := service.GetVehicleAttachments(vehicle.ID)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewError("createVehicleAttachment", err))
return
}
c.JSON(http.StatusOK, attachments)
} else {
c.JSON(http.StatusUnprocessableEntity, common.NewValidatorError(err))
}
}
func getVehicleUsers(c *gin.Context) {
var searchByIdQuery models.SearchByIdQuery
if err := c.ShouldBindUri(&searchByIdQuery); err == nil {
vehicle, err := service.GetVehicleById(searchByIdQuery.Id)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewError("getVehicleUsers", err))
return
}
data, err := service.GetVehicleUsers(vehicle.ID)
var model []models.UserVehicleSimpleModel
for _, item := range *data {
model = append(model, models.UserVehicleSimpleModel{
ID: item.ID,
UserID: item.UserID,
VehicleID: item.VehicleID,
IsOwner: item.IsOwner,
Name: item.User.Name,
})
}
if err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewError("getVehicleUsers", err))
return
}
c.JSON(http.StatusOK, model)
} else {
c.JSON(http.StatusUnprocessableEntity, common.NewValidatorError(err))
}
}
func shareVehicle(c *gin.Context) {
var searchByIdQuery models.SubItemQuery
if err := c.ShouldBindUri(&searchByIdQuery); err == nil {
err := service.ShareVehicle(searchByIdQuery.Id, searchByIdQuery.SubId)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewError("shareVehicle", err))
return
}
c.JSON(http.StatusOK, gin.H{})
} else {
c.JSON(http.StatusUnprocessableEntity, common.NewValidatorError(err))
}
}
func unshareVehicle(c *gin.Context) {
var searchByIdQuery models.SubItemQuery
if err := c.ShouldBindUri(&searchByIdQuery); err == nil {
err := service.UnshareVehicle(searchByIdQuery.Id, searchByIdQuery.SubId)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewError("shareVehicle", err))
return
}
c.JSON(http.StatusOK, gin.H{})
} else {
c.JSON(http.StatusUnprocessableEntity, common.NewValidatorError(err))
}
}
func getVehicleStats(c *gin.Context) {
var searchByIdQuery models.SearchByIdQuery
if err := c.ShouldBindUri(&searchByIdQuery); err == nil {
vehicle, err := service.GetVehicleById(searchByIdQuery.Id)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewError("getVehicleState", err))
return
}
model := models.VehicleStatsModel{}
c.JSON(http.StatusOK, model.SetStats(&vehicle.Fillups, &vehicle.Expenses))
} else {
c.JSON(http.StatusUnprocessableEntity, common.NewValidatorError(err))
}
}
func getMystats(c *gin.Context) {
var model models.UserStatsQueryModel
if err := c.ShouldBind(&model); err == nil {
stats, err := service.GetUserStats(c.MustGet("userId").(string), model)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewError("getMyVehicles", err))
return
}
c.JSON(200, stats)
} else {
c.JSON(http.StatusUnprocessableEntity, common.NewValidatorError(err))
}
}