This commit is contained in:
36
internal/api/requests/module.go
Normal file
36
internal/api/requests/module.go
Normal file
@@ -0,0 +1,36 @@
|
||||
package views_api
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"clintonambulance.com/calculate_negative_points/internal/api/middleware"
|
||||
"clintonambulance.com/calculate_negative_points/internal/api/requests/negative_points_processor"
|
||||
"clintonambulance.com/calculate_negative_points/internal/api/requests/users"
|
||||
"clintonambulance.com/calculate_negative_points/internal/config"
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-chi/cors"
|
||||
"github.com/swaggest/rest/nethttp"
|
||||
"github.com/swaggest/rest/web"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
func MountInternalApiEndpoints(e *web.Service, config *config.ApplicationConfig, logger *zap.Logger) {
|
||||
e.Route("/api", func(r chi.Router) {
|
||||
r.Use(cors.Handler(cors.Options{
|
||||
AllowedOrigins: []string{"http://localhost:3000"},
|
||||
AllowedMethods: []string{"GET", "POST", "OPTIONS"},
|
||||
AllowedHeaders: []string{"*"},
|
||||
AllowCredentials: true,
|
||||
}))
|
||||
currentUserMiddlware, err := middleware.CurrentUserMiddleware(config)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
r.Use(currentUserMiddlware)
|
||||
|
||||
r.Method(http.MethodGet, "/users/current", nethttp.NewHandler(users.GetCurrentUser()))
|
||||
r.Method(http.MethodPost, "/process", nethttp.NewHandler(negative_points_processor.NegativePointsProcessor(config, logger)))
|
||||
r.With(middleware.Logout(config)).Method(http.MethodDelete, "/users/current", nethttp.NewHandler(users.Logout()))
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package negative_points_processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"clintonambulance.com/calculate_negative_points/internal/api/middleware"
|
||||
"clintonambulance.com/calculate_negative_points/internal/config"
|
||||
"clintonambulance.com/calculate_negative_points/internal/nocodb"
|
||||
"clintonambulance.com/calculate_negative_points/internal/utils"
|
||||
"github.com/samber/lo"
|
||||
"github.com/swaggest/usecase"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
type negativePointsProcessorInput struct {
|
||||
File *multipart.FileHeader `formData:"file" description:"XLS schedule file to process"`
|
||||
}
|
||||
|
||||
type negativePointsProcessorOutput struct {
|
||||
Employees []string `json:"employees" description:"List of employees who had negative points" nullable:"false" required:"true"`
|
||||
}
|
||||
|
||||
func hasMatch(record nocodb.NocoDBRecord, candidates []string, threshold int) bool {
|
||||
normalizedName := utils.NormalizeName(utils.ToTitleCase(record.Name))
|
||||
bestDistance := threshold + 1
|
||||
|
||||
for _, candidate := range candidates {
|
||||
normalizedCandidate := utils.NormalizeName(candidate)
|
||||
distance := utils.LevenshteinDistance(normalizedName, normalizedCandidate)
|
||||
|
||||
if distance < bestDistance {
|
||||
bestDistance = distance
|
||||
}
|
||||
}
|
||||
|
||||
if bestDistance <= threshold {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func NegativePointsProcessor(config *config.ApplicationConfig, logger *zap.Logger) usecase.Interactor {
|
||||
u := usecase.NewInteractor(func(ctx context.Context, input negativePointsProcessorInput, output *negativePointsProcessorOutput) error {
|
||||
ctxUser := ctx.Value("claims").(middleware.Claims)
|
||||
|
||||
file, err := input.File.Open()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
employees, err := utils.ParseUploadedXLSFile(input.File)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
records, err := nocodb.Fetch(config)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
employees = lo.Filter(employees, func(e utils.Employee, _ int) bool { return e.Worked() })
|
||||
|
||||
names := lo.Map(employees, func(e utils.Employee, _ int) string { return e.Name })
|
||||
|
||||
// Convert XLS names to same format as API names (FirstName LastName) and normalize casing
|
||||
xlsNamesConverted := lo.Map(names, func(name string, _ int) string {
|
||||
return utils.ToTitleCase(utils.ConvertNameFormat(name))
|
||||
})
|
||||
|
||||
overlaps := lo.Filter(records, func(r nocodb.NocoDBRecord, _ int) bool {
|
||||
return hasMatch(r, xlsNamesConverted, config.MatchThreshold)
|
||||
})
|
||||
|
||||
currentNocodbUser, found := lo.Find(records, func(r nocodb.NocoDBRecord) bool { return hasMatch(r, []string{ctxUser.Name}, config.MatchThreshold) })
|
||||
|
||||
if !found {
|
||||
return errors.New("Unable to match API user to NocoDB user")
|
||||
}
|
||||
|
||||
requestObjects := lo.Map(overlaps, func(r nocodb.NocoDBRecord, _ int) nocodb.NocoDBRequest {
|
||||
return nocodb.NocoDBRequest{
|
||||
EmployeeId: r.ID,
|
||||
ReportedBy: currentNocodbUser.ID,
|
||||
InfractionId: config.NocoDBConfig.NegativeInfractionId,
|
||||
Date: utils.FirstDayOfMonth(),
|
||||
}
|
||||
})
|
||||
|
||||
// Marshal request objects to JSON
|
||||
jsonData, err := json.Marshal(requestObjects)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Create POST request
|
||||
req, err := http.NewRequest("POST", nocodb.AddInfractionsUrl(config), strings.NewReader(string(jsonData)))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Add authorization header
|
||||
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", config.NocoDBConfig.ApiToken.Value()))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
// Make the request
|
||||
client := &http.Client{}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Check response status
|
||||
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
fmt.Printf("Request failed with status %d: %s\n", resp.StatusCode, string(body))
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
output.Employees = lo.Map(overlaps, func(r nocodb.NocoDBRecord, _ int) string { return r.Name })
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
u.SetDescription("Process Negative Points")
|
||||
u.SetTags("Negative Points Processor")
|
||||
|
||||
return u
|
||||
}
|
||||
31
internal/api/requests/users/current.go
Normal file
31
internal/api/requests/users/current.go
Normal file
@@ -0,0 +1,31 @@
|
||||
package users
|
||||
|
||||
import (
|
||||
"context"
|
||||
"go/types"
|
||||
|
||||
"clintonambulance.com/calculate_negative_points/internal/api/middleware"
|
||||
internal_types "clintonambulance.com/calculate_negative_points/internal/types"
|
||||
"github.com/coreos/go-oidc/v3/oidc"
|
||||
"github.com/samber/lo"
|
||||
"github.com/swaggest/usecase"
|
||||
)
|
||||
|
||||
func GetCurrentUser() usecase.Interactor {
|
||||
u := usecase.NewInteractor(func(ctx context.Context, input types.Nil, output *internal_types.UiUserResponse) error {
|
||||
ctxId := ctx.Value("user").(*oidc.IDToken)
|
||||
ctxUser := ctx.Value("claims").(middleware.Claims)
|
||||
|
||||
if lo.IsNotEmpty(ctxId.Issuer) {
|
||||
output.Item = internal_types.UiUser{
|
||||
Name: ctxUser.Name,
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
u.SetDescription("Retrieve the current user")
|
||||
u.SetTags("Users")
|
||||
return u
|
||||
}
|
||||
17
internal/api/requests/users/logout.go
Normal file
17
internal/api/requests/users/logout.go
Normal file
@@ -0,0 +1,17 @@
|
||||
package users
|
||||
|
||||
import (
|
||||
"context"
|
||||
"go/types"
|
||||
|
||||
"github.com/swaggest/usecase"
|
||||
)
|
||||
|
||||
func Logout() usecase.Interactor {
|
||||
u := usecase.NewInteractor(func(ctx context.Context, input types.Nil, output *map[string]interface{}) error {
|
||||
return nil
|
||||
})
|
||||
u.SetDescription("Logout current user")
|
||||
u.SetTags("Users")
|
||||
return u
|
||||
}
|
||||
Reference in New Issue
Block a user