This repository has been archived on 2026-01-02. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
cover-letter-templater/backend/controllers/cover/cover.go
T
2025-07-12 15:44:49 +03:00

95 lines
2.1 KiB
Go

package cover
import (
"backend/models/cover"
"backend/models/template"
"backend/utils"
"backend/utils/chatgpt"
"backend/utils/jwt"
res "backend/utils/responses"
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
)
var validate = validator.New()
func Get(c *gin.Context) {
}
type CoverPost struct {
TemplateId string `json:"templateId" validate:"required,number,min=1"`
Application string `json:"application" validate:"required,min=50"`
}
func Post(c *gin.Context) {
// Receive data from frontend, check if data is okay, hash password, call model
var data CoverPost
if err := utils.BindAndValidate(&data, c); err != nil {
res.Error(c, err.Error(), http.StatusBadRequest)
return
}
// Get user data from the token
user, err := jwt.GetUser(c)
if err != nil {
res.NeedsToLogin(c)
return
}
// Get tempalte
templates, err := template.Get("user_id = $1 AND id = $2", user.Id, data.TemplateId)
if err != nil {
res.Error(c, err.Error(), http.StatusInternalServerError)
return
}
// Check if template exists
if len(templates) == 0 {
res.Error(c, "Template not found", http.StatusNotFound)
return
}
// Call chat and ask for cover letter nicely
generatedCover, err := chatgpt.GenerateCoverLetter(templates[0].Template, data.Application)
if err != nil {
res.Error(c, err.Error(), http.StatusInternalServerError)
return
}
// Find cover name that doesnt exist
coverName := generatedCover.Name
for i := 1; true; i++ {
// Try to find cover with same name
covers, err := cover.Get("name = $1 AND user_id = $2", coverName, user.Id)
if err != nil {
res.Error(c, err.Error(), http.StatusInternalServerError)
return
}
// Found non existent name
if len(covers) == 0 {
break
}
// Change number on name
coverName = fmt.Sprintf("%s (%d)", generatedCover.Name, i)
}
// Save name in database
if err := cover.Create(coverName, generatedCover.Cover, user.Id); err != nil {
res.Error(c, err.Error(), http.StatusInternalServerError)
return
}
res.Success(c, gin.H{"message": "Successfully created " + coverName})
}
func Put(c *gin.Context) {
}
func Delete(c *gin.Context) {
}