Files
tm_back/internal/customer/handler.go
T
n.nakhostin 8c1e593686 Implement customer management domain with authorization and API enhancements
- Introduced a new customer management domain, including entities, services, handlers, and forms for customer operations.
- Added JWT-based user authorization settings in the configuration file for both user and customer management.
- Updated API endpoints to reflect the new structure, including changes to health check and user management routes.
- Enhanced Swagger documentation to include new customer-related endpoints and authorization details.
- Refactored the Makefile to include a target for generating API documentation.
- Removed obsolete documentation files to streamline the project structure.
2025-08-11 12:55:08 +03:30

742 lines
31 KiB
Go

package customer
import (
"strconv"
"tm/internal/user"
"tm/pkg/authorization"
"tm/pkg/logger"
"tm/pkg/response"
"github.com/google/uuid"
"github.com/labstack/echo/v4"
)
// Handler handles HTTP requests for customer operations
type Handler struct {
service Service
authService authorization.AuthorizationService
userHandler *user.Handler
logger logger.Logger
}
// NewHandler creates a new customer handler
func NewHandler(service Service, userHandler *user.Handler, authService authorization.AuthorizationService, logger logger.Logger) *Handler {
return &Handler{
service: service,
authService: authService,
userHandler: userHandler,
logger: logger,
}
}
// RegisterRoutes registers customer routes
func (h *Handler) RegisterRoutes(e *echo.Echo) {
adminV1 := e.Group("/admin/v1/customers")
adminV1.Use(h.userHandler.AuthMiddleware())
adminV1.POST("", h.CreateCustomer)
adminV1.GET("", h.ListCustomers)
adminV1.GET("/:id", h.GetCustomerByID)
adminV1.PUT("/:id", h.UpdateCustomer)
adminV1.DELETE("/:id", h.DeleteCustomer)
adminV1.PATCH("/:id/status", h.UpdateCustomerStatus)
adminV1.PATCH("/:id/verification", h.UpdateCustomerVerification)
adminV1.POST("/:id/verify", h.VerifyCustomer)
adminV1.POST("/:id/suspend", h.SuspendCustomer)
adminV1.POST("/:id/activate", h.ActivateCustomer)
adminV1.GET("/company/:companyId", h.GetCustomersByCompanyID)
adminV1.GET("/type/:type", h.GetCustomersByType)
adminV1.GET("/status/:status", h.GetCustomersByStatus)
// Mobile-specific endpoints
v1 := e.Group("/api/v1")
authorizationGP := v1.Group("")
authorizationGP.POST("/login", h.Login)
authorizationGP.POST("/refresh-token", h.RefreshToken)
profileGP := v1.Group("")
profileGP.Use(h.AuthMiddleware())
profileGP.GET("/profile", h.GetProfile)
profileGP.DELETE("/logout", h.Logout)
}
// CreateCustomer creates a new customer (Web Panel)
// @Summary Create a new customer
// @Description Create a new customer with comprehensive information including personal details, company information, address, and business details. This endpoint is used by the web panel for full customer registration.
// @Tags Customers-Admin
// @Accept json
// @Produce json
// @Param customer body CreateCustomerForm true "Customer information including type (individual|company|government), personal details, company info, address, and business details"
// @Success 201 {object} response.APIResponse{data=CustomerResponse} "Customer created successfully"
// @Failure 400 {object} response.APIResponse "Bad request - Invalid input data"
// @Failure 409 {object} response.APIResponse "Conflict - Customer with this email/company already exists"
// @Failure 422 {object} response.APIResponse "Validation error - Invalid request data"
// @Failure 500 {object} response.APIResponse "Internal server error"
// @Security BearerAuth
// @Router /admin/v1/customers [post]
func (h *Handler) CreateCustomer(c echo.Context) error {
form, err := response.Parse[CreateCustomerForm](c)
if err != nil {
return response.ValidationError(c, "Invalid request data", err.Error())
}
// TODO: Get user ID from JWT token
createdBy := uuid.New() // This should come from JWT token
customer, err := h.service.CreateCustomer(c.Request().Context(), form, &createdBy)
if err != nil {
if err.Error() == "customer with this email already exists" ||
err.Error() == "company with this name already exists" ||
err.Error() == "company with this registration number already exists" ||
err.Error() == "company with this tax ID already exists" {
return response.Conflict(c, err.Error())
}
return response.InternalServerError(c, "Failed to create customer")
}
return response.Created(c, customer.ToResponse(), "Customer created successfully")
}
// GetCustomerByID retrieves a customer by ID
// @Summary Get customer by ID
// @Description Retrieve detailed customer information by unique customer ID. Returns comprehensive customer data including personal details, company information, address, verification status, and audit fields.
// @Tags Customers-Admin
// @Accept json
// @Produce json
// @Param id path string true "Customer UUID" format(uuid)
// @Success 200 {object} response.APIResponse{data=CustomerResponse} "Customer retrieved successfully"
// @Failure 400 {object} response.APIResponse "Bad request - Invalid customer ID format"
// @Failure 404 {object} response.APIResponse "Not found - Customer does not exist"
// @Failure 500 {object} response.APIResponse "Internal server error"
// @Security BearerAuth
// @Router /admin/v1/customers/{id} [get]
func (h *Handler) GetCustomerByID(c echo.Context) error {
idStr := c.Param("id")
id, err := uuid.Parse(idStr)
if err != nil {
return response.BadRequest(c, "Invalid customer ID", err.Error())
}
customer, err := h.service.GetCustomerByID(c.Request().Context(), id)
if err != nil {
if err.Error() == "customer not found" {
return response.NotFound(c, "Customer not found")
}
return response.InternalServerError(c, "Failed to retrieve customer")
}
return response.Success(c, customer.ToResponse(), "Customer retrieved successfully")
}
// UpdateCustomer updates a customer (Web Panel)
// @Summary Update customer information
// @Description Update existing customer information with comprehensive details. All fields are optional and only provided fields will be updated. This endpoint is used by the web panel for full customer management.
// @Tags Customers-Admin
// @Accept json
// @Produce json
// @Param id path string true "Customer UUID" format(uuid)
// @Param customer body UpdateCustomerForm true "Customer update information - all fields are optional"
// @Success 200 {object} response.APIResponse{data=CustomerResponse} "Customer updated successfully"
// @Failure 400 {object} response.APIResponse "Bad request - Invalid customer ID or input data"
// @Failure 404 {object} response.APIResponse "Not found - Customer does not exist"
// @Failure 409 {object} response.APIResponse "Conflict - Customer with this email/company already exists"
// @Failure 422 {object} response.APIResponse "Validation error - Invalid request data"
// @Failure 500 {object} response.APIResponse "Internal server error"
// @Security BearerAuth
// @Router /admin/v1/customers/{id} [put]
func (h *Handler) UpdateCustomer(c echo.Context) error {
idStr := c.Param("id")
id, err := uuid.Parse(idStr)
if err != nil {
return response.BadRequest(c, "Invalid customer ID", err.Error())
}
form, err := response.Parse[UpdateCustomerForm](c)
if err != nil {
return response.ValidationError(c, "Invalid request data", err.Error())
}
// TODO: Get user ID from JWT token
updatedBy := uuid.New() // This should come from JWT token
customer, err := h.service.UpdateCustomer(c.Request().Context(), id, form, &updatedBy)
if err != nil {
if err.Error() == "customer not found" {
return response.NotFound(c, "Customer not found")
}
if err.Error() == "customer with this email already exists" ||
err.Error() == "company with this name already exists" ||
err.Error() == "company with this registration number already exists" ||
err.Error() == "company with this tax ID already exists" {
return response.Conflict(c, err.Error())
}
return response.InternalServerError(c, "Failed to update customer")
}
return response.Success(c, customer.ToResponse(), "Customer updated successfully")
}
// DeleteCustomer deletes a customer (soft delete)
// @Summary Delete customer
// @Description Soft delete a customer by setting status to inactive. The customer record is preserved but marked as deleted. This is a reversible operation.
// @Tags Customers-Admin
// @Accept json
// @Produce json
// @Param id path string true "Customer UUID" format(uuid)
// @Success 200 {object} response.APIResponse "Customer deleted successfully"
// @Failure 400 {object} response.APIResponse "Bad request - Invalid customer ID format"
// @Failure 404 {object} response.APIResponse "Not found - Customer does not exist"
// @Failure 500 {object} response.APIResponse "Internal server error"
// @Security BearerAuth
// @Router /admin/v1/customers/{id} [delete]
func (h *Handler) DeleteCustomer(c echo.Context) error {
idStr := c.Param("id")
id, err := uuid.Parse(idStr)
if err != nil {
return response.BadRequest(c, "Invalid customer ID", err.Error())
}
// TODO: Get user ID from JWT token
deletedBy := uuid.New() // This should come from JWT token
err = h.service.DeleteCustomer(c.Request().Context(), id, &deletedBy)
if err != nil {
if err.Error() == "customer not found" {
return response.NotFound(c, "Customer not found")
}
return response.InternalServerError(c, "Failed to delete customer")
}
return response.Success(c, nil, "Customer deleted successfully")
}
// ListCustomers lists customers with filters and pagination
// @Summary List customers with filters and pagination
// @Description Retrieve a paginated list of customers with advanced filtering options including search, type, status, company, industry, verification status, and compliance status. Supports sorting and pagination.
// @Tags Customers-Admin
// @Accept json
// @Produce json
// @Param search query string false "Search term to filter customers by name, email, or company name"
// @Param type query string false "Filter by customer type" Enums(individual, company, government)
// @Param status query string false "Filter by customer status" Enums(active, inactive, suspended, pending)
// @Param company_id query string false "Filter by company ID" format(uuid)
// @Param industry query string false "Filter by industry"
// @Param is_verified query boolean false "Filter by verification status"
// @Param is_compliant query boolean false "Filter by compliance status"
// @Param language query string false "Filter by preferred language"
// @Param currency query string false "Filter by preferred currency"
// @Param limit query integer false "Number of customers per page (1-100)" minimum(1) maximum(100) default(20)
// @Param offset query integer false "Number of customers to skip for pagination" minimum(0) default(0)
// @Param sort_by query string false "Field to sort by" Enums(email, company_name, created_at, updated_at, status) default(created_at)
// @Param sort_order query string false "Sort order" Enums(asc, desc) default(desc)
// @Success 200 {object} response.APIResponse{data=CustomerListResponse} "Customers retrieved successfully"
// @Failure 400 {object} response.APIResponse "Bad request - Invalid query parameters"
// @Failure 422 {object} response.APIResponse "Validation error - Invalid query parameters"
// @Failure 500 {object} response.APIResponse "Internal server error"
// @Security BearerAuth
// @Router /admin/v1/customers [get]
func (h *Handler) ListCustomers(c echo.Context) error {
form, err := response.Parse[ListCustomersForm](c)
if err != nil {
return response.ValidationError(c, "Invalid request data", err.Error())
}
result, err := h.service.ListCustomers(c.Request().Context(), form)
if err != nil {
return response.InternalServerError(c, "Failed to list customers")
}
return response.Success(c, result, "Customers retrieved successfully")
}
// UpdateCustomerStatus updates customer status
// @Summary Update customer status
// @Description Update the status of a customer account. Valid statuses include active, inactive, suspended, and pending. This affects the customer's ability to access the system.
// @Tags Customers-Admin
// @Accept json
// @Produce json
// @Param id path string true "Customer UUID" format(uuid)
// @Param status body UpdateCustomerStatusForm true "Status update information"
// @Success 200 {object} response.APIResponse "Customer status updated successfully"
// @Failure 400 {object} response.APIResponse "Bad request - Invalid customer ID or status"
// @Failure 404 {object} response.APIResponse "Not found - Customer does not exist"
// @Failure 422 {object} response.APIResponse "Validation error - Invalid status value"
// @Failure 500 {object} response.APIResponse "Internal server error"
// @Security BearerAuth
// @Router /admin/v1/customers/{id}/status [patch]
func (h *Handler) UpdateCustomerStatus(c echo.Context) error {
idStr := c.Param("id")
id, err := uuid.Parse(idStr)
if err != nil {
return response.BadRequest(c, "Invalid customer ID", err.Error())
}
form, err := response.Parse[UpdateCustomerStatusForm](c)
if err != nil {
return response.ValidationError(c, "Invalid request data", err.Error())
}
// TODO: Get user ID from JWT token
updatedBy := uuid.New() // This should come from JWT token
err = h.service.UpdateCustomerStatus(c.Request().Context(), id, form, &updatedBy)
if err != nil {
if err.Error() == "customer not found" {
return response.NotFound(c, "Customer not found")
}
return response.InternalServerError(c, "Failed to update customer status")
}
return response.Success(c, nil, "Customer status updated successfully")
}
// UpdateCustomerVerification updates customer verification status
// @Summary Update customer verification and compliance status
// @Description Update the verification and compliance status of a customer. This includes marking customers as verified and compliant, with optional compliance notes for audit purposes.
// @Tags Customers-Admin
// @Accept json
// @Produce json
// @Param id path string true "Customer UUID" format(uuid)
// @Param verification body UpdateCustomerVerificationForm true "Verification and compliance update information"
// @Success 200 {object} response.APIResponse "Customer verification updated successfully"
// @Failure 400 {object} response.APIResponse "Bad request - Invalid customer ID"
// @Failure 404 {object} response.APIResponse "Not found - Customer does not exist"
// @Failure 422 {object} response.APIResponse "Validation error - Invalid verification data"
// @Failure 500 {object} response.APIResponse "Internal server error"
// @Security BearerAuth
// @Router /admin/v1/customers/{id}/verification [patch]
func (h *Handler) UpdateCustomerVerification(c echo.Context) error {
idStr := c.Param("id")
id, err := uuid.Parse(idStr)
if err != nil {
return response.BadRequest(c, "Invalid customer ID", err.Error())
}
form, err := response.Parse[UpdateCustomerVerificationForm](c)
if err != nil {
return response.ValidationError(c, "Invalid request data", err.Error())
}
// TODO: Get user ID from JWT token
updatedBy := uuid.New() // This should come from JWT token
err = h.service.UpdateCustomerVerification(c.Request().Context(), id, form, &updatedBy)
if err != nil {
if err.Error() == "customer not found" {
return response.NotFound(c, "Customer not found")
}
return response.InternalServerError(c, "Failed to update customer verification")
}
return response.Success(c, nil, "Customer verification updated successfully")
}
// VerifyCustomer verifies a customer
// @Summary Verify customer
// @Description Mark a customer as verified. This is a simple verification action that sets the customer's verification status to true.
// @Tags Customers-Admin
// @Accept json
// @Produce json
// @Param id path string true "Customer UUID" format(uuid)
// @Success 200 {object} response.APIResponse "Customer verified successfully"
// @Failure 400 {object} response.APIResponse "Bad request - Invalid customer ID"
// @Failure 404 {object} response.APIResponse "Not found - Customer does not exist"
// @Failure 500 {object} response.APIResponse "Internal server error"
// @Security BearerAuth
// @Router /admin/v1/customers/{id}/verify [post]
func (h *Handler) VerifyCustomer(c echo.Context) error {
idStr := c.Param("id")
id, err := uuid.Parse(idStr)
if err != nil {
return response.BadRequest(c, "Invalid customer ID", err.Error())
}
// TODO: Get user ID from JWT token
verifiedBy := uuid.New() // This should come from JWT token
err = h.service.VerifyCustomer(c.Request().Context(), id, &verifiedBy)
if err != nil {
if err.Error() == "customer not found" {
return response.NotFound(c, "Customer not found")
}
return response.InternalServerError(c, "Failed to verify customer")
}
return response.Success(c, nil, "Customer verified successfully")
}
// SuspendCustomer suspends a customer
// @Summary Suspend customer account
// @Description Suspend a customer account by setting their status to suspended. Suspended customers cannot access the system. A reason for suspension must be provided.
// @Tags Customers-Admin
// @Accept json
// @Produce json
// @Param id path string true "Customer UUID" format(uuid)
// @Param reason body object true "Suspension reason" SchemaExample({"reason": "Violation of terms of service"})
// @Success 200 {object} response.APIResponse "Customer suspended successfully"
// @Failure 400 {object} response.APIResponse "Bad request - Invalid customer ID or missing reason"
// @Failure 404 {object} response.APIResponse "Not found - Customer does not exist"
// @Failure 500 {object} response.APIResponse "Internal server error"
// @Security BearerAuth
// @Router /admin/v1/customers/{id}/suspend [post]
func (h *Handler) SuspendCustomer(c echo.Context) error {
idStr := c.Param("id")
id, err := uuid.Parse(idStr)
if err != nil {
return response.BadRequest(c, "Invalid customer ID", err.Error())
}
var requestBody map[string]string
if err := c.Bind(&requestBody); err != nil {
return response.BadRequest(c, "Invalid request body", err.Error())
}
reason := requestBody["reason"]
if reason == "" {
return response.BadRequest(c, "Suspension reason is required", "")
}
// TODO: Get user ID from JWT token
suspendedBy := uuid.New() // This should come from JWT token
err = h.service.SuspendCustomer(c.Request().Context(), id, reason, &suspendedBy)
if err != nil {
if err.Error() == "customer not found" {
return response.NotFound(c, "Customer not found")
}
return response.InternalServerError(c, "Failed to suspend customer")
}
return response.Success(c, nil, "Customer suspended successfully")
}
// ActivateCustomer activates a customer
// @Summary Activate suspended customer account
// @Description Reactivate a suspended customer account by setting their status back to active. This reverses the suspension action.
// @Tags Customers-Admin
// @Accept json
// @Produce json
// @Param id path string true "Customer UUID" format(uuid)
// @Success 200 {object} response.APIResponse "Customer activated successfully"
// @Failure 400 {object} response.APIResponse "Bad request - Invalid customer ID"
// @Failure 404 {object} response.APIResponse "Not found - Customer does not exist"
// @Failure 500 {object} response.APIResponse "Internal server error"
// @Security BearerAuth
// @Router /admin/v1/customers/{id}/activate [post]
func (h *Handler) ActivateCustomer(c echo.Context) error {
idStr := c.Param("id")
id, err := uuid.Parse(idStr)
if err != nil {
return response.BadRequest(c, "Invalid customer ID", err.Error())
}
// TODO: Get user ID from JWT token
activatedBy := uuid.New() // This should come from JWT token
err = h.service.ActivateCustomer(c.Request().Context(), id, &activatedBy)
if err != nil {
if err.Error() == "customer not found" {
return response.NotFound(c, "Customer not found")
}
return response.InternalServerError(c, "Failed to activate customer")
}
return response.Success(c, nil, "Customer activated successfully")
}
// GetCustomersByCompanyID retrieves customers by company ID
// @Summary Get customers by company ID
// @Description Retrieve all customers associated with a specific company. This is useful for company administrators to see all users within their organization.
// @Tags Customers-Admin
// @Accept json
// @Produce json
// @Param companyId path string true "Company UUID" format(uuid)
// @Param limit query integer false "Number of customers per page (1-100)" minimum(1) maximum(100) default(20)
// @Param offset query integer false "Number of customers to skip for pagination" minimum(0) default(0)
// @Success 200 {object} response.APIResponse{data=[]CustomerResponse,meta=response.Meta} "Customers retrieved successfully"
// @Failure 400 {object} response.APIResponse "Bad request - Invalid company ID format"
// @Failure 500 {object} response.APIResponse "Internal server error"
// @Security BearerAuth
// @Router /admin/v1/customers/company/{companyId} [get]
func (h *Handler) GetCustomersByCompanyID(c echo.Context) error {
companyIDStr := c.Param("companyId")
companyID, err := uuid.Parse(companyIDStr)
if err != nil {
return response.BadRequest(c, "Invalid company ID", err.Error())
}
limit := 20
if limitStr := c.QueryParam("limit"); limitStr != "" {
if parsedLimit, err := strconv.Atoi(limitStr); err == nil && parsedLimit > 0 && parsedLimit <= 100 {
limit = parsedLimit
}
}
offset := 0
if offsetStr := c.QueryParam("offset"); offsetStr != "" {
if parsedOffset, err := strconv.Atoi(offsetStr); err == nil && parsedOffset >= 0 {
offset = parsedOffset
}
}
customers, total, err := h.service.GetCustomersByCompanyID(c.Request().Context(), companyID, limit, offset)
if err != nil {
return response.InternalServerError(c, "Failed to retrieve customers by company")
}
var customerResponses []*CustomerResponse
for _, customer := range customers {
customerResponses = append(customerResponses, customer.ToResponse())
}
meta := &response.Meta{
Total: int(total),
Limit: limit,
Offset: offset,
}
return response.SuccessWithMeta(c, customerResponses, meta, "Customers retrieved successfully")
}
// GetCustomersByType retrieves customers by type
// @Summary Get customers by type
// @Description Retrieve customers filtered by their type (individual, company, or government). Useful for administrative reporting and management.
// @Tags Customers-Admin
// @Accept json
// @Produce json
// @Param type path string true "Customer type" Enums(individual, company, government)
// @Param limit query integer false "Number of customers per page (1-100)" minimum(1) maximum(100) default(20)
// @Param offset query integer false "Number of customers to skip for pagination" minimum(0) default(0)
// @Success 200 {object} response.APIResponse{data=[]CustomerResponse,meta=response.Meta} "Customers retrieved successfully"
// @Failure 400 {object} response.APIResponse "Bad request - Invalid customer type"
// @Failure 500 {object} response.APIResponse "Internal server error"
// @Security BearerAuth
// @Router /admin/v1/customers/type/{type} [get]
func (h *Handler) GetCustomersByType(c echo.Context) error {
customerTypeStr := c.Param("type")
customerType := CustomerType(customerTypeStr)
// Validate customer type
if customerType != CustomerTypeIndividual && customerType != CustomerTypeCompany && customerType != CustomerTypeGovernment {
return response.BadRequest(c, "Invalid customer type", "Must be individual, company, or government")
}
limit := 20
if limitStr := c.QueryParam("limit"); limitStr != "" {
if parsedLimit, err := strconv.Atoi(limitStr); err == nil && parsedLimit > 0 && parsedLimit <= 100 {
limit = parsedLimit
}
}
offset := 0
if offsetStr := c.QueryParam("offset"); offsetStr != "" {
if parsedOffset, err := strconv.Atoi(offsetStr); err == nil && parsedOffset >= 0 {
offset = parsedOffset
}
}
customers, total, err := h.service.GetCustomersByType(c.Request().Context(), customerType, limit, offset)
if err != nil {
return response.InternalServerError(c, "Failed to retrieve customers by type")
}
var customerResponses []*CustomerResponse
for _, customer := range customers {
customerResponses = append(customerResponses, customer.ToResponse())
}
meta := &response.Meta{
Total: int(total),
Limit: limit,
Offset: offset,
}
return response.SuccessWithMeta(c, customerResponses, meta, "Customers retrieved successfully")
}
// GetCustomersByStatus retrieves customers by status
// @Summary Get customers by status
// @Description Retrieve customers filtered by their account status (active, inactive, suspended, or pending). Useful for administrative monitoring and management.
// @Tags Customers-Admin
// @Accept json
// @Produce json
// @Param status path string true "Customer status" Enums(active, inactive, suspended, pending)
// @Param limit query integer false "Number of customers per page (1-100)" minimum(1) maximum(100) default(20)
// @Param offset query integer false "Number of customers to skip for pagination" minimum(0) default(0)
// @Success 200 {object} response.APIResponse{data=[]CustomerResponse,meta=response.Meta} "Customers retrieved successfully"
// @Failure 400 {object} response.APIResponse "Bad request - Invalid customer status"
// @Failure 500 {object} response.APIResponse "Internal server error"
// @Security BearerAuth
// @Router /admin/v1/customers/status/{status} [get]
func (h *Handler) GetCustomersByStatus(c echo.Context) error {
statusStr := c.Param("status")
status := CustomerStatus(statusStr)
// Validate customer status
if status != CustomerStatusActive && status != CustomerStatusInactive && status != CustomerStatusSuspended && status != CustomerStatusPending {
return response.BadRequest(c, "Invalid customer status", "Must be active, inactive, suspended, or pending")
}
limit := 20
if limitStr := c.QueryParam("limit"); limitStr != "" {
if parsedLimit, err := strconv.Atoi(limitStr); err == nil && parsedLimit > 0 && parsedLimit <= 100 {
limit = parsedLimit
}
}
offset := 0
if offsetStr := c.QueryParam("offset"); offsetStr != "" {
if parsedOffset, err := strconv.Atoi(offsetStr); err == nil && parsedOffset >= 0 {
offset = parsedOffset
}
}
customers, total, err := h.service.GetCustomersByStatus(c.Request().Context(), status, limit, offset)
if err != nil {
return response.InternalServerError(c, "Failed to retrieve customers by status")
}
var customerResponses []*CustomerResponse
for _, customer := range customers {
customerResponses = append(customerResponses, customer.ToResponse())
}
meta := &response.Meta{
Total: int(total),
Limit: limit,
Offset: offset,
}
return response.SuccessWithMeta(c, customerResponses, meta, "Customers retrieved successfully")
}
// Login handles customer authentication
// @Summary Customer login
// @Description Authenticate customer with username (email) and password. Returns access token, refresh token, and customer information upon successful authentication.
// @Tags Customers-Authorization
// @Accept json
// @Produce json
// @Param login body LoginForm true "Login credentials (username/email and password)"
// @Success 200 {object} response.APIResponse{data=AuthResponse} "Login successful"
// @Failure 400 {object} response.APIResponse "Bad request - Invalid input data"
// @Failure 401 {object} response.APIResponse "Unauthorized - Invalid credentials or inactive account"
// @Failure 422 {object} response.APIResponse "Validation error - Invalid request data"
// @Failure 500 {object} response.APIResponse "Internal server error"
// @Router /api/v1/login [post]
func (h *Handler) Login(c echo.Context) error {
form, err := response.Parse[LoginForm](c)
if err != nil {
return response.ValidationError(c, "Invalid request data", err.Error())
}
// Call service
authResponse, err := h.service.Login(c.Request().Context(), form)
if err != nil {
if err.Error() == "invalid credentials" {
return response.Unauthorized(c, err.Error())
}
if err.Error() == "account is not active" {
return response.Unauthorized(c, err.Error())
}
return response.InternalServerError(c, "Failed to authenticate customer")
}
return response.Success(c, authResponse, "Login successful")
}
// RefreshToken handles customer token refresh
// @Summary Refresh customer access token
// @Description Refresh access token using a valid refresh token. This allows customers to maintain their session without re-authentication.
// @Tags Customers-Authorization
// @Accept json
// @Produce json
// @Param refresh body RefreshTokenForm true "Refresh token for generating new access token"
// @Success 200 {object} response.APIResponse{data=AuthResponse} "Token refreshed successfully"
// @Failure 400 {object} response.APIResponse "Bad request - Invalid refresh token or feature not implemented"
// @Failure 401 {object} response.APIResponse "Unauthorized - Invalid or expired refresh token"
// @Failure 422 {object} response.APIResponse "Validation error - Invalid request data"
// @Failure 500 {object} response.APIResponse "Internal server error"
// @Router /api/v1/refresh-token [post]
func (h *Handler) RefreshToken(c echo.Context) error {
form, err := response.Parse[RefreshTokenForm](c)
if err != nil {
return response.ValidationError(c, "Invalid request data", err.Error())
}
// Call service
authResponse, err := h.service.RefreshToken(c.Request().Context(), form.RefreshToken)
if err != nil {
if err.Error() == "token refresh not implemented yet" {
return response.BadRequest(c, "Token refresh not implemented yet", "")
}
return response.InternalServerError(c, "Failed to refresh token")
}
return response.Success(c, authResponse, "Token refreshed successfully")
}
// GetProfile retrieves customer profile information
// @Summary Get customer profile
// @Description Retrieve authenticated customer's profile information. This endpoint requires a valid access token and returns the customer's own profile data.
// @Tags Customers-Authorization
// @Accept json
// @Produce json
// @Security BearerAuth
// @Success 200 {object} response.APIResponse{data=CustomerResponse} "Profile retrieved successfully"
// @Failure 401 {object} response.APIResponse "Unauthorized - Invalid or missing access token"
// @Failure 404 {object} response.APIResponse "Not found - Customer profile not found"
// @Failure 500 {object} response.APIResponse "Internal server error"
// @Router /api/v1/profile [get]
func (h *Handler) GetProfile(c echo.Context) error {
// Get customer ID from context (set by AuthMiddleware)
customerID, err := GetCustomerIDFromContext(c)
if err != nil {
return response.Unauthorized(c, "Customer ID not found in context")
}
// Call service
customer, err := h.service.GetProfile(c.Request().Context(), customerID)
if err != nil {
if err.Error() == "customer not found" {
return response.NotFound(c, "Customer not found")
}
return response.InternalServerError(c, "Failed to retrieve customer profile")
}
return response.Success(c, customer.ToResponse(), "Profile retrieved successfully")
}
// Logout handles customer logout
// @Summary Customer logout
// @Description Logout customer and invalidate access token. This ensures the token cannot be used for future requests.
// @Tags Customers-Authorization
// @Accept json
// @Produce json
// @Security BearerAuth
// @Success 200 {object} response.APIResponse "Logout successful"
// @Failure 401 {object} response.APIResponse "Unauthorized - Invalid or missing access token"
// @Failure 500 {object} response.APIResponse "Internal server error"
// @Router /api/v1/logout [delete]
func (h *Handler) Logout(c echo.Context) error {
// Get customer ID from context (set by AuthMiddleware)
customerID, err := GetCustomerIDFromContext(c)
if err != nil {
return response.Unauthorized(c, "Customer ID not found in context")
}
// Get access token from context
accessToken, err := GetAccessTokenFromContext(c)
if err != nil {
return response.Unauthorized(c, "Access token not found in context")
}
// Call service
err = h.service.Logout(c.Request().Context(), customerID, accessToken)
if err != nil {
return response.InternalServerError(c, "Failed to logout customer")
}
return response.Success(c, nil, "Logout successful")
}