fix: resolve remaining merge conflicts

This commit is contained in:
Rede5 2026-02-14 17:21:10 +00:00
parent eb1276eac4
commit 948858eca0
8 changed files with 3292 additions and 3528 deletions

View file

@ -35,7 +35,6 @@ type CoreHandlers struct {
credentialsService *services.CredentialsService
}
<<<<<<< HEAD
func NewCoreHandlers(
l *auth.LoginUseCase,
reg *auth.RegisterCandidateUseCase,
@ -44,6 +43,7 @@ func NewCoreHandlers(
list *user.ListUsersUseCase,
del *user.DeleteUserUseCase,
upd *user.UpdateUserUseCase,
updatePasswordUC *user.UpdatePasswordUseCase,
lc *tenant.ListCompaniesUseCase,
fp *auth.ForgotPasswordUseCase,
rp *auth.ResetPasswordUseCase,
@ -53,9 +53,6 @@ func NewCoreHandlers(
adminService *services.AdminService,
credentialsService *services.CredentialsService,
) *CoreHandlers {
=======
func NewCoreHandlers(l *auth.LoginUseCase, reg *auth.RegisterCandidateUseCase, c *tenant.CreateCompanyUseCase, u *user.CreateUserUseCase, list *user.ListUsersUseCase, del *user.DeleteUserUseCase, upd *user.UpdateUserUseCase, updatePasswordUC *user.UpdatePasswordUseCase, lc *tenant.ListCompaniesUseCase, auditService *services.AuditService, notificationService *services.NotificationService, ticketService *services.TicketService, adminService *services.AdminService, credentialsService *services.CredentialsService) *CoreHandlers {
>>>>>>> dev
return &CoreHandlers{
loginUC: l,
registerCandidateUC: reg,
@ -119,10 +116,9 @@ func (h *CoreHandlers) Login(w http.ResponseWriter, r *http.Request) {
// Set HttpOnly Cookie
http.SetCookie(w, &http.Cookie{
Name: "jwt",
Value: resp.Token,
Path: "/",
// Domain: "localhost", // Or separate based on env
Name: "jwt",
Value: resp.Token,
Path: "/",
Expires: time.Now().Add(24 * time.Hour),
HttpOnly: true,
Secure: false, // Set to true in production with HTTPS
@ -181,7 +177,6 @@ func (h *CoreHandlers) RegisterCandidate(w http.ResponseWriter, r *http.Request)
resp, err := h.registerCandidateUC.Execute(r.Context(), req)
if err != nil {
// Log removed to fix compilation error (LogAction missing)
http.Error(w, err.Error(), http.StatusConflict)
return
}
@ -750,7 +745,7 @@ func (h *CoreHandlers) ForgotPassword(w http.ResponseWriter, r *http.Request) {
_ = h.forgotPasswordUC.Execute(r.Context(), req)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"message": "Se o email estiver cadastrado, você receberá um link de recuperação."})
json.NewEncoder(w).Encode(map[string]string{"message": "Se o email estiver cadastrado, voce recebera um link de recuperacao."})
}
// ResetPassword resets the user's password.
@ -1130,11 +1125,8 @@ func (h *CoreHandlers) UpdateMyProfile(w http.ResponseWriter, r *http.Request) {
return
}
// userID (string) passed directly as first arg
// log.Printf("[UpdateMyProfile] UserID: %s, TenantID: %s", userID, tenantID)
resp, err := h.updateUserUC.Execute(ctx, userID, tenantID, req)
if err != nil {
// log.Printf("[UpdateMyProfile] Error: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
@ -1216,20 +1208,6 @@ func (h *CoreHandlers) UploadMyAvatar(w http.ResponseWriter, r *http.Request) {
// @Failure 401 {string} string "Unauthorized"
// @Failure 500 {string} string "Internal Server Error"
// @Router /api/v1/users/me [get]
<<<<<<< HEAD
=======
// Me returns the current user profile including company info.
// @Summary Get My Profile
// @Description Returns the profile of the authenticated user.
// @Tags Users
// @Accept json
// @Produce json
// @Security BearerAuth
// @Success 200 {object} object
// @Failure 401 {string} string "Unauthorized"
// @Failure 500 {string} string "Internal Server Error"
// @Router /api/v1/users/me [get]
>>>>>>> dev
func (h *CoreHandlers) Me(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
userIDVal := ctx.Value(middleware.ContextUserID)
@ -1310,7 +1288,6 @@ func (h *CoreHandlers) SaveFCMToken(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(map[string]string{"message": "Token saved successfully"})
}
<<<<<<< HEAD
// SaveCredentials saves encrypted credentials for external services.
// @Summary Save Credentials
// @Description Saves encrypted credentials payload (e.g. Stripe key encrypted by Backoffice)
@ -1356,8 +1333,6 @@ func (h *CoreHandlers) SaveCredentials(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(map[string]string{"message": "Credentials saved successfully"})
}
=======
>>>>>>> dev
// hasAdminRole checks if roles array contains admin or superadmin
func hasAdminRole(roles []string) bool {
for _, r := range roles {

View file

@ -161,8 +161,6 @@ func TestLoginHandler_Success(t *testing.T) {
// Return entity.User
u := entity.NewUser("u1", "t1", "John", "john@example.com")
u.PasswordHash = "hashed_123456"
// Add Role if needed (mocked)
// u.Roles = ...
return u, nil
}
return nil, nil // Not found
@ -239,21 +237,13 @@ func createTestCoreHandlers(t *testing.T, db *sql.DB, loginUC *auth.LoginUseCase
(*user.UpdateUserUseCase)(nil),
(*user.UpdatePasswordUseCase)(nil),
(*tenant.ListCompaniesUseCase)(nil),
<<<<<<< HEAD
nil,
nil,
nil,
nil,
nil,
nil,
nil,
=======
nil, // forgotPasswordUC
nil, // resetPasswordUC
auditSvc,
notifSvc,
ticketSvc,
adminSvc,
credSvc,
>>>>>>> dev
)
}

View file

@ -23,28 +23,6 @@ const (
// User represents a user within a specific Tenant (Company).
type User struct {
<<<<<<< HEAD
ID string `json:"id"`
TenantID string `json:"tenant_id"` // Link to Company
Name string `json:"name"`
Email string `json:"email"`
PasswordHash string `json:"-"`
Roles []Role `json:"roles"`
Status string `json:"status"` // "ACTIVE", "INACTIVE"
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
// HML Fields
AvatarUrl string `json:"avatar_url"`
Metadata map[string]interface{} `json:"metadata"`
// HEAD Fields (Profile Profile)
Bio string `json:"bio"`
ProfilePictureURL string `json:"profile_picture_url"`
Skills []string `json:"skills"` // Stored as JSONB, mapped to slice
Experience []any `json:"experience,omitempty"` // Flexible JSON structure
Education []any `json:"education,omitempty"` // Flexible JSON structure
=======
ID string `json:"id"`
TenantID string `json:"tenant_id"` // Link to Company
Name string `json:"name"`
@ -68,7 +46,9 @@ type User struct {
Metadata map[string]interface{} `json:"metadata"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
>>>>>>> dev
// HEAD Fields (Profile)
ProfilePictureURL string `json:"profile_picture_url,omitempty"`
}
// NewUser creates a new User instance.

View file

@ -26,13 +26,12 @@ type UpdateUserRequest struct {
Name *string `json:"name,omitempty"`
Email *string `json:"email,omitempty"`
Phone *string `json:"phone,omitempty"`
Bio *string `json:"bio,omitempty"`
Active *bool `json:"active,omitempty"`
Status *string `json:"status,omitempty"`
Roles *[]string `json:"roles,omitempty"`
AvatarUrl *string `json:"avatarUrl,omitempty"`
// HEAD Fields
// Profile Fields
Bio *string `json:"bio,omitempty"`
ProfilePictureURL *string `json:"profilePictureUrl,omitempty"`
Skills []string `json:"skills,omitempty"`
@ -46,21 +45,16 @@ type UserResponse struct {
Email string `json:"email"`
Roles []string `json:"roles"`
Status string `json:"status"`
<<<<<<< HEAD
=======
AvatarUrl string `json:"avatar_url"`
AvatarUrl string `json:"avatar_url,omitempty"`
Phone *string `json:"phone,omitempty"`
Bio *string `json:"bio,omitempty"`
>>>>>>> dev
CreatedAt time.Time `json:"created_at"`
// Merged Fields
AvatarUrl string `json:"avatar_url,omitempty"` // hml
Bio string `json:"bio,omitempty"` // HEAD
ProfilePictureURL string `json:"profile_picture_url,omitempty"` // HEAD
Skills []string `json:"skills,omitempty"` // HEAD
Experience []any `json:"experience,omitempty"` // HEAD
Education []any `json:"education,omitempty"` // HEAD
// Profile Fields
ProfilePictureURL string `json:"profile_picture_url,omitempty"`
Skills []string `json:"skills,omitempty"`
Experience []any `json:"experience,omitempty"`
Education []any `json:"education,omitempty"`
}
type UpdatePasswordRequest struct {

View file

@ -34,10 +34,9 @@ func NewJobHandler(service JobServiceInterface) *JobHandler {
// @Tags Jobs
// @Accept json
// @Produce json
<<<<<<< HEAD
// @Param page query int false "Page number (default: 1)"
// @Param limit query int false "Items per page (default: 10, max: 100)"
// @Param companyId query int false "Filter by company ID"
// @Param companyId query string false "Filter by company ID"
// @Param featured query bool false "Filter by featured status"
// @Param search query string false "Full-text search query"
// @Param employmentType query string false "Filter by employment type"
@ -47,12 +46,6 @@ func NewJobHandler(service JobServiceInterface) *JobHandler {
// @Param salaryMax query number false "Maximum salary filter"
// @Param sortBy query string false "Sort by: date, salary, relevance"
// @Param sortOrder query string false "Sort order: asc, desc"
=======
// @Param page query int false "Page number (default: 1)"
// @Param limit query int false "Items per page (default: 10, max: 100)"
// @Param companyId query string false "Filter by company ID"
// @Param featured query bool false "Filter by featured status"
>>>>>>> dev
// @Success 200 {object} dto.PaginatedResponse
// @Failure 500 {string} string "Internal Server Error"
// @Router /api/v1/jobs [get]

View file

@ -3,7 +3,6 @@ package postgres
import (
"context"
"database/sql"
"encoding/json"
"time"
"github.com/lib/pq"
@ -58,9 +57,6 @@ func (r *UserRepository) Save(ctx context.Context, user *entity.User) (*entity.U
role = user.Roles[0].Name
}
// Prepare pq Array for skills
// IMPORTANT: import "github.com/lib/pq" needed at top
err = tx.QueryRowContext(ctx, query,
user.Email, // identifier = email
user.PasswordHash,
@ -111,31 +107,14 @@ func (r *UserRepository) Save(ctx context.Context, user *entity.User) (*entity.U
}
func (r *UserRepository) FindByEmail(ctx context.Context, email string) (*entity.User, error) {
<<<<<<< HEAD
query := `
SELECT
id, COALESCE(tenant_id::text, ''), COALESCE(name, full_name, ''),
COALESCE(email, identifier), password_hash, COALESCE(status, 'active'), created_at, updated_at, COALESCE(avatar_url, ''),
bio, profile_picture_url, skills, experience, education
FROM users WHERE email = $1 OR identifier = $1
`
=======
query := `SELECT id, COALESCE(tenant_id::text, ''), COALESCE(name, full_name, ''),
COALESCE(email, identifier), password_hash, COALESCE(status, 'active'), created_at, updated_at, COALESCE(avatar_url, ''),
phone, bio, address, city, state, zip_code, birth_date, education, experience, skills, objective, title
FROM users WHERE email = $1 OR identifier = $1`
>>>>>>> dev
row := r.db.QueryRowContext(ctx, query, email)
u := &entity.User{}
var dbID string
<<<<<<< HEAD
var skills, experience, education []byte // temp for Scanning
err := row.Scan(
&dbID, &u.TenantID, &u.Name, &u.Email, &u.PasswordHash, &u.Status, &u.CreatedAt, &u.UpdatedAt, &u.AvatarUrl,
&u.Bio, &u.ProfilePictureURL, &skills, &experience, &education,
=======
var phone sql.NullString
var bio sql.NullString
err := row.Scan(
@ -160,7 +139,6 @@ func (r *UserRepository) FindByEmail(ctx context.Context, email string) (*entity
pq.Array(&u.Skills),
&u.Objective,
&u.Title,
>>>>>>> dev
)
if err != nil {
if err == sql.ErrNoRows {
@ -169,53 +147,21 @@ func (r *UserRepository) FindByEmail(ctx context.Context, email string) (*entity
return nil, err
}
u.ID = dbID
<<<<<<< HEAD
// Unmarshal JSONB fields
if len(skills) > 0 {
_ = json.Unmarshal(skills, &u.Skills)
}
if len(experience) > 0 {
_ = json.Unmarshal(experience, &u.Experience)
}
if len(education) > 0 {
_ = json.Unmarshal(education, &u.Education)
}
=======
u.Phone = nullStringPtr(phone)
u.Bio = nullStringPtr(bio)
>>>>>>> dev
u.Roles, _ = r.getRoles(ctx, dbID)
return u, nil
}
func (r *UserRepository) FindByID(ctx context.Context, id string) (*entity.User, error) {
<<<<<<< HEAD
query := `
SELECT
id, COALESCE(tenant_id::text, ''), COALESCE(name, full_name, ''),
COALESCE(email, identifier), password_hash, COALESCE(status, 'active'), created_at, updated_at, COALESCE(avatar_url, ''),
bio, profile_picture_url, skills, experience, education
FROM users WHERE id = $1
`
=======
query := `SELECT id, COALESCE(tenant_id::text, ''), COALESCE(name, full_name, ''),
COALESCE(email, identifier), password_hash, COALESCE(status, 'active'), created_at, updated_at, COALESCE(avatar_url, ''),
phone, bio, address, city, state, zip_code, birth_date, education, experience, skills, objective, title
FROM users WHERE id = $1`
>>>>>>> dev
row := r.db.QueryRowContext(ctx, query, id)
u := &entity.User{}
var dbID string
<<<<<<< HEAD
var skills, experience, education []byte // temp for Scanning
err := row.Scan(
&dbID, &u.TenantID, &u.Name, &u.Email, &u.PasswordHash, &u.Status, &u.CreatedAt, &u.UpdatedAt, &u.AvatarUrl,
&u.Bio, &u.ProfilePictureURL, &skills, &experience, &education,
=======
var phone sql.NullString
var bio sql.NullString
err := row.Scan(
@ -240,29 +186,13 @@ func (r *UserRepository) FindByID(ctx context.Context, id string) (*entity.User,
pq.Array(&u.Skills),
&u.Objective,
&u.Title,
>>>>>>> dev
)
if err != nil {
return nil, err
}
u.ID = dbID
<<<<<<< HEAD
// Unmarshal JSONB fields
if len(skills) > 0 {
_ = json.Unmarshal(skills, &u.Skills)
}
if len(experience) > 0 {
_ = json.Unmarshal(experience, &u.Experience)
}
if len(education) > 0 {
_ = json.Unmarshal(education, &u.Education)
}
=======
u.Phone = nullStringPtr(phone)
u.Bio = nullStringPtr(bio)
>>>>>>> dev
u.Roles, _ = r.getRoles(ctx, dbID)
return u, nil
}
@ -336,9 +266,6 @@ func (r *UserRepository) Update(ctx context.Context, user *entity.User) (*entity
}
defer tx.Rollback()
// 1. Update basic fields + legacy role column + Profile fields
// We use the first role as the "legacy" role for compatibility
// Prepare pq Array for skills
// 1. Update basic fields + legacy role column
// We use the first role as the "legacy" role for compatibility
primaryRole := ""
@ -346,21 +273,6 @@ func (r *UserRepository) Update(ctx context.Context, user *entity.User) (*entity
primaryRole = user.Roles[0].Name
}
<<<<<<< HEAD
skillsJSON, _ := json.Marshal(user.Skills)
experienceJSON, _ := json.Marshal(user.Experience)
educationJSON, _ := json.Marshal(user.Education)
query := `
UPDATE users
SET name=$1, email=$2, status=$3, role=$4, updated_at=$5, avatar_url=$6,
bio=$7, profile_picture_url=$8, skills=$9, experience=$10, education=$11
WHERE id=$12
`
_, err = tx.ExecContext(ctx, query,
user.Name, user.Email, user.Status, primaryRole, user.UpdatedAt, user.AvatarUrl,
user.Bio, user.ProfilePictureURL, skillsJSON, experienceJSON, educationJSON,
=======
query := `
UPDATE users
SET name=$1, full_name=$2, email=$3, status=$4, role=$5, updated_at=$6, avatar_url=$7,
@ -392,7 +304,6 @@ func (r *UserRepository) Update(ctx context.Context, user *entity.User) (*entity
pq.Array(user.Skills),
user.Objective,
user.Title,
>>>>>>> dev
user.ID,
)
if err != nil {

View file

@ -34,7 +34,6 @@ func NewRouter() http.Handler {
// --- CORE ARCHITECTURE INITIALIZATION ---
// Infrastructure
// Infrastructure
userRepo := postgres.NewUserRepository(database.DB)
companyRepo := postgres.NewCompanyRepository(database.DB)
locationRepo := postgres.NewLocationRepository(database.DB)
@ -78,14 +77,11 @@ func NewRouter() http.Handler {
listUsersUC := userUC.NewListUsersUseCase(userRepo)
deleteUserUC := userUC.NewDeleteUserUseCase(userRepo)
updateUserUC := userUC.NewUpdateUserUseCase(userRepo)
<<<<<<< HEAD
updatePasswordUC := userUC.NewUpdatePasswordUseCase(userRepo, authService)
forgotPasswordUC := authUC.NewForgotPasswordUseCase(userRepo, tokenRepo, emailService, frontendURL)
resetPasswordUC := authUC.NewResetPasswordUseCase(userRepo, tokenRepo, authService)
// Admin Logic Services
=======
updatePasswordUC := userUC.NewUpdatePasswordUseCase(userRepo, authService)
>>>>>>> dev
auditService := services.NewAuditService(database.DB)
notificationService := services.NewNotificationService(database.DB, fcmService)
ticketService := services.NewTicketService(database.DB)
@ -145,7 +141,7 @@ func NewRouter() http.Handler {
}
response := map[string]interface{}{
"message": "🐴 GoHorseJobs API is running!",
"message": "GoHorseJobs API is running!",
"docs": "/docs",
"health": "/health",
"version": "1.0.0",
@ -160,12 +156,9 @@ func NewRouter() http.Handler {
// --- CORE ROUTES ---
// Public
mux.HandleFunc("POST /api/v1/auth/login", coreHandlers.Login)
<<<<<<< HEAD
mux.HandleFunc("POST /api/v1/auth/logout", coreHandlers.Logout)
mux.HandleFunc("POST /api/v1/auth/forgot-password", coreHandlers.ForgotPassword)
mux.HandleFunc("POST /api/v1/auth/reset-password", coreHandlers.ResetPassword)
=======
mux.HandleFunc("POST /api/v1/auth/logout", coreHandlers.Logout)
>>>>>>> dev
mux.HandleFunc("POST /api/v1/auth/register", coreHandlers.RegisterCandidate)
mux.HandleFunc("POST /api/v1/auth/register/candidate", coreHandlers.RegisterCandidate)
mux.HandleFunc("POST /api/v1/auth/register/company", coreHandlers.CreateCompany)
@ -201,24 +194,11 @@ func NewRouter() http.Handler {
mux.Handle("PATCH /api/v1/users/me/profile", authMiddleware.HeaderAuthGuard(http.HandlerFunc(coreHandlers.UpdateMyProfile)))
mux.Handle("PATCH /api/v1/users/me/password", authMiddleware.HeaderAuthGuard(http.HandlerFunc(coreHandlers.UpdateMyPassword)))
// /api/v1/admin/companies -> Handled by coreHandlers.ListCompanies (Smart Branching)
// Needs to be wired with Optional Auth to support both Public and Admin.
// I will create OptionalHeaderAuthGuard in middleware next.
// Company Management
mux.Handle("PATCH /api/v1/companies/{id}/status", authMiddleware.HeaderAuthGuard(adminOnly(http.HandlerFunc(adminHandlers.UpdateCompanyStatus))))
mux.Handle("PATCH /api/v1/companies/{id}", authMiddleware.HeaderAuthGuard(adminOnly(http.HandlerFunc(adminHandlers.UpdateCompany))))
mux.Handle("DELETE /api/v1/companies/{id}", authMiddleware.HeaderAuthGuard(adminOnly(http.HandlerFunc(adminHandlers.DeleteCompany))))
// /api/v1/admin/jobs -> /api/v1/jobs?mode=admin (Need Smart Handler) or just separate path /api/v1/jobs/management?
// User said "remove admin from ALL routes".
// Maybe /api/v1/management/jobs?
// Or just /api/v1/jobs (guarded)?
// JobHandler.GetJobs is Public.
// I will leave /api/v1/admin/jobs mapped to `GET /api/v1/jobs` for now (Collision).
// OK, I will map it to `GET /api/v1/jobs/moderation` for clearer distinction without "admin" prefix?
// Or simply `GET /api/v1/jobs` handle it?
// Given safe constraints, `GET /api/v1/jobs/moderation` is safer than breaking public `GET /api/v1/jobs`.
mux.Handle("GET /api/v1/jobs/moderation", authMiddleware.HeaderAuthGuard(adminOnly(http.HandlerFunc(adminHandlers.ListJobs))))
// /api/v1/admin/jobs/{id}/status
@ -275,12 +255,7 @@ func NewRouter() http.Handler {
mux.Handle("POST /api/v1/system/cloudflare/purge", authMiddleware.HeaderAuthGuard(adminOnly(http.HandlerFunc(adminHandlers.PurgeCache))))
// Seeder Routes (Dev Only)
// Guarded by Admin Roles, or you could make it Dev only via env check
mux.HandleFunc("GET /api/v1/seeder/seed/stream", seederHandlers.HandleSeedStream) // Has its own auth or unrestricted for dev? Better unrestricted for simplicity in dev if safe.
// Actually, let's keep it open for now or simple admin guard if user is logged in.
// The frontend uses EventSource which sends cookies but not custom headers easily without polyfill.
// We'll leave it public for the requested "Dev" purpose, or rely on internal network.
// If needed, we can add query param token.
mux.HandleFunc("GET /api/v1/seeder/seed/stream", seederHandlers.HandleSeedStream)
mux.HandleFunc("POST /api/v1/seeder/reset", seederHandlers.HandleReset)
// Email Templates & Settings (Admin Only)
@ -309,14 +284,9 @@ func NewRouter() http.Handler {
mux.HandleFunc("POST /api/v1/subscription/checkout", subHandler.CreateCheckoutSession)
mux.HandleFunc("POST /api/v1/subscription/webhook", subHandler.HandleWebhook)
// Application Routes
<<<<<<< HEAD
mux.HandleFunc("POST /api/v1/applications", applicationHandler.CreateApplication)
mux.Handle("GET /api/v1/applications/me", authMiddleware.HeaderAuthGuard(http.HandlerFunc(applicationHandler.ListUserApplications))) // New endpoint
=======
// Application Routes (merged: both OptionalAuth for create + both /me endpoints)
mux.Handle("POST /api/v1/applications", authMiddleware.OptionalHeaderAuthGuard(http.HandlerFunc(applicationHandler.CreateApplication)))
mux.Handle("GET /api/v1/applications/me", authMiddleware.HeaderAuthGuard(http.HandlerFunc(applicationHandler.GetMyApplications)))
>>>>>>> dev
mux.HandleFunc("GET /api/v1/applications", applicationHandler.GetApplications)
mux.HandleFunc("GET /api/v1/applications/{id}", applicationHandler.GetApplicationByID)
mux.HandleFunc("PUT /api/v1/applications/{id}/status", applicationHandler.UpdateApplicationStatus)
@ -331,12 +301,10 @@ func NewRouter() http.Handler {
// --- TICKET ROUTES ---
ticketHandler := handlers.NewTicketHandler(ticketService)
// mux.HandleFunc("GET /api/v1/tickets/stats", ticketHandler.GetTicketStats) // Removed in hml
mux.HandleFunc("GET /api/v1/tickets", ticketHandler.GetTickets)
mux.HandleFunc("POST /api/v1/tickets", ticketHandler.CreateTicket)
mux.HandleFunc("GET /api/v1/tickets/{id}", ticketHandler.GetTicketByID)
mux.HandleFunc("PUT /api/v1/tickets/{id}", ticketHandler.UpdateTicket)
// mux.HandleFunc("GET /api/v1/tickets/{id}/messages", ticketHandler.GetTicketMessages) // Merged into GetByID
mux.HandleFunc("POST /api/v1/tickets/{id}/messages", ticketHandler.AddTicketMessage)
// --- ACTIVITY LOG ROUTES ---
@ -347,13 +315,9 @@ func NewRouter() http.Handler {
// --- NOTIFICATION ROUTES ---
notificationHandler := handlers.NewNotificationHandler(notificationService)
mux.Handle("GET /api/v1/notifications", authMiddleware.HeaderAuthGuard(http.HandlerFunc(notificationHandler.GetNotifications)))
// mux.Handle("GET /api/v1/notifications/unread-count", authMiddleware.HeaderAuthGuard(http.HandlerFunc(notificationHandler.GetUnreadCount))) // Removed in hml
mux.Handle("PUT /api/v1/notifications/read-all", authMiddleware.HeaderAuthGuard(http.HandlerFunc(notificationHandler.MarkAllAsRead)))
mux.Handle("PUT /api/v1/notifications/{id}/read", authMiddleware.HeaderAuthGuard(http.HandlerFunc(notificationHandler.MarkAsRead)))
// mux.Handle("DELETE /api/v1/notifications/{id}", authMiddleware.HeaderAuthGuard(http.HandlerFunc(notificationHandler.DeleteNotification))) // Removed in hml
mux.Handle("POST /api/v1/notifications/fcm-token", authMiddleware.HeaderAuthGuard(http.HandlerFunc(notificationHandler.RegisterFCMToken)))
// mux.Handle("DELETE /api/v1/notifications/fcm-token", authMiddleware.HeaderAuthGuard(http.HandlerFunc(notificationHandler.UnregisterFCMToken))) // Removed in hml
// Swagger Route - available at /docs
mux.HandleFunc("/docs/", httpSwagger.WrapHandler)

View file

@ -76,49 +76,31 @@ func (s *JobService) CreateJob(req dto.CreateJobRequest, createdBy string) (*mod
}
func (s *JobService) GetJobs(filter dto.JobFilterQuery) ([]models.JobWithCompany, int, error) {
// Merged Query: Includes hml fields + key HEAD logic
// Merged Query: Includes both HEAD and dev fields
baseQuery := `
<<<<<<< HEAD
SELECT
j.id, j.company_id, j.title, j.description, j.salary_min, j.salary_max, j.salary_type,
j.employment_type, j.work_mode, j.working_hours, j.location, j.status, j.salary_negotiable, j.is_featured, j.created_at, j.updated_at,
COALESCE(c.name, '') as company_name, c.logo_url as company_logo_url,
CASE
WHEN c.type = 'CANDIDATE_WORKSPACE' OR c.name LIKE 'Candidate - %' THEN ''
ELSE COALESCE(c.name, '')
END as company_name, c.logo_url as company_logo_url,
r.name as region_name, ci.name as city_name,
j.view_count, j.featured_until
j.view_count, j.featured_until,
(SELECT COUNT(*) FROM applications a WHERE a.job_id = j.id) as applications_count
FROM jobs j
LEFT JOIN companies c ON j.company_id::text = c.id::text
LEFT JOIN states r ON j.region_id::text = r.id::text
LEFT JOIN cities ci ON j.city_id::text = ci.id::text
WHERE 1=1`
=======
SELECT
j.id, j.company_id, j.title, j.description, j.salary_min, j.salary_max, j.salary_type,
j.employment_type, j.work_mode, j.working_hours, j.location, j.status, j.salary_negotiable, j.is_featured, j.created_at, j.updated_at,
CASE
WHEN c.type = 'CANDIDATE_WORKSPACE' OR c.name LIKE 'Candidate - %' THEN ''
ELSE COALESCE(c.name, '')
END as company_name, c.logo_url as company_logo_url,
r.name as region_name, ci.name as city_name,
(SELECT COUNT(*) FROM applications a WHERE a.job_id = j.id) as applications_count
FROM jobs j
LEFT JOIN companies c ON j.company_id::text = c.id::text
LEFT JOIN states r ON j.region_id::text = r.id::text
LEFT JOIN cities ci ON j.city_id::text = ci.id::text
WHERE 1=1`
>>>>>>> dev
countQuery := `SELECT COUNT(*) FROM jobs j WHERE 1=1`
var args []interface{}
argId := 1
// Search (merged logic)
// Supports full text search if available, or ILIKE fallback.
// Using generic ILIKE for broad compatibility as hml did, but incorporating HEAD's concept.
if filter.Search != nil && *filter.Search != "" {
searchTerm := fmt.Sprintf("%%%s%%", *filter.Search)
// HEAD had tsvector. If DB supports it great. But to avoid "function not found" if extension missing, safe bet is ILIKE.
// hml used ILIKE.
clause := fmt.Sprintf(" AND (j.title ILIKE $%d OR j.description ILIKE $%d OR c.name ILIKE $%d)", argId, argId, argId)
baseQuery += clause
countQuery += clause
@ -174,7 +156,7 @@ func (s *JobService) GetJobs(filter dto.JobFilterQuery) ([]models.JobWithCompany
args = append(args, locTerm)
argId++
}
// Support HEAD's LocationSearch explicitly if different (mapped to same in requests.go but just in case)
// Support HEAD's LocationSearch explicitly if different
if filter.LocationSearch != nil && *filter.LocationSearch != "" && (filter.Location == nil || *filter.Location != *filter.LocationSearch) {
locTerm := fmt.Sprintf("%%%s%%", *filter.LocationSearch)
baseQuery += fmt.Sprintf(" AND j.location ILIKE $%d", argId)
@ -254,7 +236,6 @@ func (s *JobService) GetJobs(filter dto.JobFilterQuery) ([]models.JobWithCompany
case "salary_desc":
sortClause = " ORDER BY j.salary_max DESC NULLS LAST"
case "relevance":
// Simple relevance if no fulltext rank
sortClause = " ORDER BY j.is_featured DESC, j.created_at DESC"
}
}
@ -262,10 +243,7 @@ func (s *JobService) GetJobs(filter dto.JobFilterQuery) ([]models.JobWithCompany
// Override sort order if explicit
if filter.SortOrder != nil {
if *filter.SortOrder == "asc" {
// Naive replace/append. hml logic didn't support generic SortOrder param well (it embedded in SortBy).
// If SortBy was one of the above, we might just append ASC?
// But for now, rely on SortBy providing correct default or direction.
// HEAD relied on SortOrder.
// Rely on SortBy providing correct default or direction.
}
}
@ -299,12 +277,8 @@ func (s *JobService) GetJobs(filter dto.JobFilterQuery) ([]models.JobWithCompany
if err := rows.Scan(
&j.ID, &j.CompanyID, &j.Title, &j.Description, &j.SalaryMin, &j.SalaryMax, &j.SalaryType,
&j.EmploymentType, &j.WorkMode, &j.WorkingHours, &j.Location, &j.Status, &j.SalaryNegotiable, &j.IsFeatured, &j.CreatedAt, &j.UpdatedAt,
<<<<<<< HEAD
&j.CompanyName, &j.CompanyLogoURL, &j.RegionName, &j.CityName,
&j.ViewCount, &j.FeaturedUntil,
=======
&j.CompanyName, &j.CompanyLogoURL, &j.RegionName, &j.CityName, &j.ApplicationsCount,
>>>>>>> dev
&j.ViewCount, &j.FeaturedUntil, &j.ApplicationsCount,
); err != nil {
return nil, 0, err
}
@ -329,17 +303,11 @@ func (s *JobService) GetJobByID(id string) (*models.Job, error) {
salary_negotiable, currency, work_mode
FROM jobs WHERE id = $1
`
// Added extra fields to SELECT to cover both models
err := s.DB.QueryRow(query, id).Scan(
&j.ID, &j.CompanyID, &j.Title, &j.Description, &j.SalaryMin, &j.SalaryMax, &j.SalaryType,
<<<<<<< HEAD
&j.EmploymentType, &j.WorkingHours, &j.Location, &j.RegionID, &j.CityID,
&j.Requirements, &j.Benefits, &j.VisaSupport, &j.LanguageLevel, &j.Status, &j.IsFeatured, &j.FeaturedUntil, &j.ViewCount, &j.CreatedAt, &j.UpdatedAt,
&j.SalaryNegotiable, &j.Currency, &j.WorkMode,
=======
&j.EmploymentType, &j.WorkingHours, &j.Location, &j.RegionID, &j.CityID, &j.SalaryNegotiable,
&j.Requirements, &j.Benefits, &j.VisaSupport, &j.LanguageLevel, &j.Status, &j.CreatedAt, &j.UpdatedAt,
>>>>>>> dev
)
if err != nil {
return nil, err
@ -362,8 +330,6 @@ func (s *JobService) UpdateJob(id string, req dto.UpdateJobRequest) (*models.Job
args = append(args, *req.Description)
argId++
}
<<<<<<< HEAD
=======
if req.SalaryMin != nil {
setClauses = append(setClauses, fmt.Sprintf("salary_min = $%d", argId))
args = append(args, *req.SalaryMin)
@ -434,7 +400,6 @@ func (s *JobService) UpdateJob(id string, req dto.UpdateJobRequest) (*models.Job
args = append(args, *req.LanguageLevel)
argId++
}
>>>>>>> dev
if req.Status != nil {
setClauses = append(setClauses, fmt.Sprintf("status = $%d", argId))
args = append(args, *req.Status)
@ -447,13 +412,10 @@ func (s *JobService) UpdateJob(id string, req dto.UpdateJobRequest) (*models.Job
}
if req.FeaturedUntil != nil {
setClauses = append(setClauses, fmt.Sprintf("featured_until = $%d", argId))
// HEAD had string parsing. hml didn't show parsing logic but request field might be string.
// Assuming ISO8601 string from DTO.
parsedTime, err := time.Parse(time.RFC3339, *req.FeaturedUntil)
if err == nil {
args = append(args, parsedTime)
} else {
// Fallback or error? For now fallback null or skip
args = append(args, nil)
}
argId++
@ -463,11 +425,6 @@ func (s *JobService) UpdateJob(id string, req dto.UpdateJobRequest) (*models.Job
args = append(args, *req.SalaryNegotiable)
argId++
}
if req.Currency != nil {
setClauses = append(setClauses, fmt.Sprintf("currency = $%d", argId))
args = append(args, *req.Currency)
argId++
}
if len(setClauses) == 0 {
return s.GetJobByID(id)