### Get Analytics Overview API Source: https://context7.com/sjperalta/fintera-api-go/llms.txt Retrieves comprehensive analytics data, including statistics and revenue trends for a given project and date range. Requires a GET request to /api/v1/analytics/overview with project ID, start date, end date, and revenue timeframe. ```bash curl -X GET "http://localhost:8081/api/v1/analytics/overview?project_id=3&start_date=2024-01-01&end_date=2024-12-31&revenue_timeframe=12M" \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." ``` -------------------------------- ### Go Application Integration with Background Worker Source: https://github.com/sjperalta/fintera-api-go/blob/main/docs/go_migration_plan.md Demonstrates how to integrate the native Go background worker into an application's main entry point. It initializes services, creates a worker with a specified number of goroutines, schedules recurring jobs, and starts the HTTP server. Includes graceful shutdown handling for the worker. ```go // cmd/api/main.go package main import ( "context" "log" "time" "fintera-api/internal/jobs" "fintera-api/internal/services" ) func main() { // Initialize services db := database.Connect() paymentService := services.NewPaymentService(db) creditService := services.NewCreditScoreService(db) statsService := services.NewStatisticsService(db) // Create worker with 5 concurrent goroutines worker := jobs.NewWorker(5) // Schedule recurring jobs (replaces Solid Queue recurring tasks) worker.ScheduleEvery(1*time.Hour, func(ctx context.Context) error { log.Println("Checking overdue payments...") return paymentService.CheckOverduePayments(ctx) }) worker.ScheduleEvery(6*time.Hour, func(ctx context.Context) error { log.Println("Updating credit scores...") return creditService.UpdateAllScores(ctx) }) worker.ScheduleEvery(24*time.Hour, func(ctx context.Context) error { log.Println("Generating daily statistics...") return statsService.GenerateDaily(ctx) }) // Start HTTP server... router := setupRouter(worker) router.Run(":8080") // Graceful shutdown worker.Shutdown() } ``` -------------------------------- ### Background Job Examples Source: https://github.com/sjperalta/fintera-api-go/blob/main/docs/go_migration_plan.md Illustrates common background jobs handled by the application. These include overdue payment interest calculation, credit score updates, revenue/statistics generation, email notifications, and reservation release. ```Go package jobs import ( "fmt" "time" ) // StartBackgroundJobs initializes and runs various background jobs. func StartBackgroundJobs() { go runOverdueInterestJob() go runCreditScoreUpdateJob() go runRevenueGenerationJob() go runEmailNotificationJob() go runReservationReleaseJob() } func runOverdueInterestJob() { // Example: Run every day at midnight tticker := time.NewTicker(24 * time.Hour) defer ticker.Stop() for range ticker.C { fmt.Println("Running overdue interest calculation...") // Implement overdue interest logic here } } func runCreditScoreUpdateJob() { // Example: Run every hour ticker := time.NewTicker(1 * time.Hour) defer ticker.Stop() for range ticker.C { fmt.Println("Running credit score updates...") // Implement credit score update logic here } } func runRevenueGenerationJob() { // Example: Run weekly ticker := time.NewTicker(7 * 24 * time.Hour) defer ticker.Stop() for range ticker.C { fmt.Println("Generating revenue and statistics...") // Implement revenue/statistics generation logic here } } func runEmailNotificationJob() { // Example: Run every 15 minutes ticker := time.NewTicker(15 * time.Minute) defer ticker.Stop() for range ticker.C { fmt.Println("Sending email notifications...") // Implement email notification logic here } } func runReservationReleaseJob() { // Example: Run every 30 minutes ticker := time.NewTicker(30 * time.Minute) defer ticker.Stop() for range ticker.C { fmt.Println("Releasing unpaid reservations...") // Implement reservation release logic here } } ``` -------------------------------- ### List Contracts Handler Example in Go Source: https://github.com/sjperalta/fintera-api-go/blob/main/docs/go_migration_plan.md This Go code defines a handler for listing contracts. It retrieves user information and query parameters from the request, then calls the contract service to fetch contract data. It handles potential errors and returns a JSON response with contract details and pagination information. ```go // internal/handlers/contract_handler.go package handlers import ( "net/http" "github.com/gin-gonic/gin" "fintera-api/internal/services" ) type ContractHandler struct { contractService services.ContractService } func NewContractHandler(cs services.ContractService) *ContractHandler { return &ContractHandler{contractService: cs} } // @Summary List all contracts // @Tags Contracts // @Security BearerAuth // @Produce json // @Param page query int false "Page number" // @Param per_page query int false "Items per page" // @Param search_term query string false "Search term" // @Param sort query string false "Sort field and direction (e.g., created_at-desc)" // @Success 200 {object} ContractListResponse // @Router /api/v1/contracts [get] func (h *ContractHandler) Index(c *gin.Context) { user := c.MustGet("currentUser").(*models.User) query := &services.ContractQuery{ Page: c.DefaultQuery("page", "1"), PerPage: c.DefaultQuery("per_page", "20"), SearchTerm: c.Query("search_term"), Sort: c.Query("sort"), UserID: user.ID, IsAdmin: user.IsAdmin(), } result, err := h.contractService.List(c.Request.Context(), query) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } c.JSON(http.StatusOK, gin.H{ "contracts": result.Items, "pagination": result.Pagination, }) } ``` -------------------------------- ### GET /api/v1/analytics/performance Source: https://context7.com/sjperalta/fintera-api-go/llms.txt Retrieves project performance metrics. ```APIDOC ## GET /api/v1/analytics/performance ### Description Retrieves project performance metrics. ### Method GET ### Endpoint `/api/v1/analytics/performance` ### Parameters (No parameters specified) ### Request Example ```bash curl -X GET http://localhost:8081/api/v1/analytics/performance \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." ``` ### Response #### Success Response (200) (No specific response body details provided in the source text) #### Response Example (No specific response example provided in the source text) ``` -------------------------------- ### List and Get Projects (API) Source: https://context7.com/sjperalta/fintera-api-go/llms.txt Retrieves a list of all projects with pagination or fetches details for a specific project by its ID. Supports filtering and sorting through query parameters. Requires authorization. ```bash # List all projects curl -X GET "http://localhost:8081/api/v1/projects?page=1&per_page=10" \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." # Get specific project by ID curl -X GET http://localhost:8081/api/v1/projects/3 \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." ``` -------------------------------- ### GET /api/v1/projects Source: https://context7.com/sjperalta/fintera-api-go/llms.txt Retrieves a list of projects with lot availability statistics and detailed information. Supports pagination. ```APIDOC ## GET /api/v1/projects ### Description Retrieves a list of projects with lot availability statistics and detailed information. Supports pagination. ### Method GET ### Endpoint /api/v1/projects ### Parameters #### Query Parameters - **page** (integer) - Optional - The page number for pagination. - **per_page** (integer) - Optional - The number of items per page. ### Response #### Success Response (200) - **id** (integer) - The unique identifier of the project. - **name** (string) - The name of the project. - **address** (string) - The address of the project. - **description** (string) - A description of the project. - **project_type** (string) - The type of project. - **measurement_unit** (string) - The unit of measurement for lots. - **price_per_square_unit** (number) - The base price per unit of measurement. - **interest_rate** (number) - The annual interest rate. - **commission_rate** (number) - The commission rate. - **lot_count** (integer) - The total number of lots. - **available_lots** (integer) - The number of available lots. - **reserved_lots** (integer) - The number of reserved lots. - **sold_lots** (integer) - The number of sold lots. - **delivery_date** (string) - The expected delivery date. #### Response Example ```json { "id": 3, "name": "Residencial Las Palmas", "address": "Km 15 Carretera Norte", "description": "Premium residential lots with ocean views", "project_type": "residential", "measurement_unit": "m2", "price_per_square_unit": 150.00, "interest_rate": 12.5, "commission_rate": 5.0, "lot_count": 50, "available_lots": 45, "reserved_lots": 3, "sold_lots": 2, "delivery_date": "2025-12-31T00:00:00Z" } ``` ``` -------------------------------- ### GET /api/v1/contracts Source: https://github.com/sjperalta/fintera-api-go/blob/main/docs/go_migration_plan.md Retrieves a list of contracts with optional pagination, search, and sorting parameters. ```APIDOC ## GET /api/v1/contracts ### Description Retrieves a list of contracts with optional pagination, search, and sorting parameters. Requires user authentication. ### Method GET ### Endpoint /api/v1/contracts ### Parameters #### Query Parameters - **page** (int) - Optional - Page number for pagination. - **per_page** (int) - Optional - Number of items per page. - **search_term** (string) - Optional - Term to search contracts by. - **sort** (string) - Optional - Field and direction for sorting (e.g., `created_at-desc`). ### Request Example ```json { "example": "No request body for GET request" } ``` ### Response #### Success Response (200) - **contracts** (array) - List of contract objects. - **pagination** (object) - Pagination details. #### Response Example ```json { "contracts": [ { "id": "123", "name": "Sample Contract", "created_at": "2023-10-27T10:00:00Z" } ], "pagination": { "total": 100, "page": 1, "per_page": 20 } } ``` ``` -------------------------------- ### GET /api/v1/projects/{id} Source: https://context7.com/sjperalta/fintera-api-go/llms.txt Retrieves detailed information for a specific project by its ID. ```APIDOC ## GET /api/v1/projects/{id} ### Description Retrieves detailed information for a specific project by its ID. ### Method GET ### Endpoint /api/v1/projects/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the project. ### Response #### Success Response (200) - **id** (integer) - The unique identifier of the project. - **name** (string) - The name of the project. - **address** (string) - The address of the project. - **description** (string) - A description of the project. - **project_type** (string) - The type of project. - **measurement_unit** (string) - The unit of measurement for lots. - **price_per_square_unit** (number) - The base price per unit of measurement. - **interest_rate** (number) - The annual interest rate. - **commission_rate** (number) - The commission rate. - **lot_count** (integer) - The total number of lots. - **available_lots** (integer) - The number of available lots. - **reserved_lots** (integer) - The number of reserved lots. - **sold_lots** (integer) - The number of sold lots. - **delivery_date** (string) - The expected delivery date. #### Response Example ```json { "id": 3, "name": "Residencial Las Palmas", "address": "Km 15 Carretera Norte", "description": "Premium residential lots with ocean views", "project_type": "residential", "measurement_unit": "m2", "price_per_square_unit": 150.00, "interest_rate": 12.5, "commission_rate": 5.0, "lot_count": 50, "available_lots": 45, "reserved_lots": 3, "sold_lots": 2, "delivery_date": "2025-12-31T00:00:00Z" } ``` ``` -------------------------------- ### Approve Contract Handler Example in Go Source: https://github.com/sjperalta/fintera-api-go/blob/main/docs/go_migration_plan.md This Go code implements a handler for approving a contract. It extracts the contract ID from the URL parameters and the current user from the request context. It then calls the contract service's Approve method and returns a success message or an error. ```go // internal/handlers/contract_handler.go package handlers import ( "net/http" "github.com/gin-gonic/gin" "fintera-api/internal/services" ) // ... (previous code for ContractHandler and NewContractHandler) // @Summary Approve a contract // @Tags Contracts // @Security BearerAuth // @Produce json // @Param project_id path int true "Project ID" // @Param lot_id path int true "Lot ID" // @Param id path int true "Contract ID" // @Success 200 {object} ContractResponse // @Router /api/v1/projects/{project_id}/lots/{lot_id}/contracts/{id}/approve [post] func (h *ContractHandler) Approve(c *gin.Context) { contractID := c.Param("id") user := c.MustGet("currentUser").(*models.User) result, err := h.contractService.Approve(c.Request.Context(), contractID, user) if err != nil { c.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()}) return } c.JSON(http.StatusOK, gin.H{ "message": "Contrato aprobado exitosamente", "contract": result, }) } ``` -------------------------------- ### Casbin Authorization Middleware Example in Go Source: https://github.com/sjperalta/fintera-api-go/blob/main/docs/go_migration_plan.md This Go code defines an authorization middleware using Casbin. It checks if the current user is authenticated and then uses the Casbin enforcer to verify if the user's role has permission to access the requested path and method. It aborts the request with an appropriate status code if authorization fails. ```go // internal/middleware/authorization.go package middleware import ( "net/http" "github.com/casbin/casbin/v2" "github.com/gin-gonic/gin" ) func Authorization(enforcer *casbin.Enforcer) gin.HandlerFunc { return func(c *gin.Context) { user, exists := c.Get("currentUser") if !exists { c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"}) return } role := user.(*models.User).Role path := c.Request.URL.Path method := c.Request.Method allowed, err := enforcer.Enforce(role, path, method) if err != nil || !allowed { c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "No tienes acceso a esta sección"}) return } c.Next() } } ``` -------------------------------- ### Download Customer Record PDF API Source: https://context7.com/sjperalta/fintera-api-go/llms.txt Generates and downloads a PDF of a customer record (Hoja de Cliente). This requires a GET request to /api/v1/reports/customer_record_pdf with a contract ID and authorization. ```bash curl -X GET "http://localhost:8081/api/v1/reports/customer_record_pdf?contract_id=50" \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \ -o customer_record.pdf ``` -------------------------------- ### Download User Information Sheet PDF API Source: https://context7.com/sjperalta/fintera-api-go/llms.txt Generates and downloads a PDF containing user information. Uses a GET request to /api/v1/reports/user_information_pdf with a user ID and authorization. ```bash curl -X GET "http://localhost:8081/api/v1/reports/user_information_pdf?user_id=5" \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \ -o user_info.pdf ``` -------------------------------- ### Download Contract Promise PDF API Source: https://context7.com/sjperalta/fintera-api-go/llms.txt Generates and downloads a PDF for a contract promise. This endpoint requires a GET request to /api/v1/reports/user_promise_contract_pdf with a contract ID and authorization. ```bash curl -X GET "http://localhost:8081/api/v1/reports/user_promise_contract_pdf?contract_id=50" \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \ -o contract_promise.pdf ``` -------------------------------- ### Download User Balance Statement PDF API Source: https://context7.com/sjperalta/fintera-api-go/llms.txt Generates and downloads a PDF of a user's balance statement. Requires a GET request to /api/v1/reports/user_balance_pdf with a user ID and authorization. ```bash curl -X GET "http://localhost:8081/api/v1/reports/user_balance_pdf?user_id=5" \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \ -o user_balance.pdf ``` -------------------------------- ### Go Project Structure Overview Source: https://github.com/sjperalta/fintera-api-go/blob/main/docs/go_migration_plan.md Provides a high-level overview of the Go project's directory structure. It highlights key directories like 'cmd' for entry points, 'internal' for application-specific code, and 'pkg' for reusable libraries. ```Go // This is a conceptual representation of the project structure. // Actual code would reside within these directories. // cmd/api/main.go // package main // func main() { // // Application entry point // } // internal/config/config.go // package config // func LoadConfig() error { // // Load configuration from files or environment variables // return nil // } // internal/database/database.go // package database // func Connect() error { // // Establish database connection // return nil // } // internal/models/contract.go // package models // type Contract struct { // // Contract fields // } // internal/repository/contract_repository.go // package repository // func GetContractByID(id string) (*models.Contract, error) { // // Database query for contract // return nil, nil // } // internal/services/contract_service.go // package services // func CreateContract(data interface{}) error { // // Business logic for creating a contract // return nil // } // internal/handlers/contract_handler.go // package handlers // func HandleGetContract(c *gin.Context) { // // HTTP request handling for contracts // } // internal/middleware/auth.go // package middleware // func AuthMiddleware() gin.HandlerFunc { // // JWT authentication middleware // return nil // } // internal/jobs/worker.go // package jobs // func StartWorker() { // // Job processing logic // } // internal/mailers/resend.go // package mailers // func SendEmail(to, subject, body string) error { // // Email sending logic using Resend SDK // return nil // } // internal/reports/pdf_generator.go // package reports // func GeneratePDFReport() ([]byte, error) { // // PDF generation logic // return nil, nil // } // pkg/statemachine/contract_state.go // package statemachine // // Contract state machine definitions // api/openapi/spec.yaml // OpenAPI specification file // go.mod // Module definition file // Dockerfile // Docker build instructions ``` -------------------------------- ### Export Analytics Data API Source: https://context7.com/sjperalta/fintera-api-go/llms.txt Exports analytics data in a specified format (e.g., CSV) for a given project and date range. Uses a GET request to /api/v1/analytics/export, requiring format, project ID, start date, and end date. ```bash curl -X GET "http://localhost:8081/api/v1/analytics/export?format=csv&project_id=3&start_date=2024-01-01&end_date=2024-12-31" \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \ -o analytics_report.csv ``` -------------------------------- ### Local Storage Usage in Gin Handlers (Go) Source: https://github.com/sjperalta/fintera-api-go/blob/main/docs/go_migration_plan.md Demonstrates how to integrate the local storage service within Gin web handlers for managing file uploads and downloads. It includes functions for uploading receipts, validating file types, and serving downloaded files. Dependencies include 'net/http' and the 'gin-gonic/gin' framework. It handles request parameters, file form data, and JSON responses for success and error scenarios. ```go package handlers import ( "net/http" "github.com/gin-gonic/gin" ) func (h *PaymentHandler) UploadReceipt(c *gin.Context) { paymentID := c.Param("id") // Get uploaded file file, header, err := c.Request.FormFile("receipt") if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "No file uploaded"}) return } defer file.Close() // Validate file type if !isValidFileType(header.Header.Get("Content-Type")) { c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid file type. Only PDF, JPG, PNG allowed"}) return } // Upload to local storage path, err := h.storage.Upload(file, header, "receipts") if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save file"}) return } // Update payment record with file path h.paymentService.UpdateReceiptPath(c.Request.Context(), paymentID, path) c.JSON(http.StatusOK, gin.H{"message": "Receipt uploaded successfully", "path": path}) } func (h *PaymentHandler) DownloadReceipt(c *gin.Context) { paymentID := c.Param("id") payment, _ := h.paymentService.FindByID(c.Request.Context(), paymentID) if payment.ReceiptPath == "" { c.JSON(http.StatusNotFound, gin.H{"error": "No receipt found"}) return } // Serve file directly filePath := h.storage.GetFullPath(payment.ReceiptPath) c.File(filePath) } func isValidFileType(contentType string) bool { validTypes := map[string]bool{ "application/pdf": true, "image/jpeg": true, "image/png": true, } return validTypes[contentType] } ``` -------------------------------- ### Get Project Performance Metrics API Source: https://context7.com/sjperalta/fintera-api-go/llms.txt Retrieves performance metrics for projects. This endpoint is accessed via a GET request to /api/v1/analytics/performance and requires authorization. ```bash curl -X GET http://localhost:8081/api/v1/analytics/performance \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." ``` -------------------------------- ### Get Lot Distribution Statistics API Source: https://context7.com/sjperalta/fintera-api-go/llms.txt Fetches lot distribution statistics for a specified project. This is an authenticated GET request to the /api/v1/analytics/distribution endpoint, requiring a project ID. ```bash curl -X GET "http://localhost:8081/api/v1/analytics/distribution?project_id=3" \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." ``` -------------------------------- ### Get Monthly Payment Statistics API Source: https://context7.com/sjperalta/fintera-api-go/llms.txt Retrieves payment statistics for a specific month and year. Uses a GET request to /api/v1/payments/statistics with month and year query parameters. Requires authorization. ```bash curl -X GET "http://localhost:8081/api/v1/payments/statistics?month=7&year=2024" \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." ``` -------------------------------- ### Local File Storage Implementation in Go Source: https://github.com/sjperalta/fintera-api-go/blob/main/docs/go_migration_plan.md Implements a local file storage system in Go, allowing for file uploads, downloads, and deletions. It creates directories based on subdirectories and timestamps, generates unique filenames using UUIDs, and handles file copying. Dependencies include standard Go libraries like 'os', 'io', 'path/filepath', 'time', and 'github.com/google/uuid'. It returns relative paths for storage and absolute paths for serving. ```go package storage import ( "fmt" "io" "mime/multipart" "os" "path/filepath" "time" "github.com/google/uuid" ) type LocalStorage struct { basePath string } // NewLocalStorage creates a storage with the given base directory func NewLocalStorage(basePath string) (*LocalStorage, error) { // Ensure the base directory exists if err := os.MkdirAll(basePath, 0755); err != nil { return nil, fmt.Errorf("failed to create storage directory: %w", err) } return &LocalStorage{basePath: basePath}, nil } // Upload saves a file and returns its path func (s *LocalStorage) Upload(file multipart.File, header *multipart.FileHeader, subDir string) (string, error) { // Create subdirectory (e.g., "contracts", "receipts") dir := filepath.Join(s.basePath, subDir, time.Now().Format("2006/01")) if err := os.MkdirAll(dir, 0755); err != nil { return "", fmt.Errorf("failed to create directory: %w", err) } // Generate unique filename ext := filepath.Ext(header.Filename) filename := fmt.Sprintf("%s%s", uuid.New().String(), ext) filePath := filepath.Join(dir, filename) // Create destination file dst, err := os.Create(filePath) if err != nil { return "", fmt.Errorf("failed to create file: %w", err) } defer dst.Close() // Copy content if _, err := io.Copy(dst, file); err != nil { return "", fmt.Errorf("failed to save file: %w", err) } // Return relative path for database storage relPath, _ := filepath.Rel(s.basePath, filePath) return relPath, nil } // Download returns a file reader func (s *LocalStorage) Download(relativePath string) (*os.File, error) { filePath := filepath.Join(s.basePath, relativePath) return os.Open(filePath) } // Delete removes a file func (s *LocalStorage) Delete(relativePath string) error { filePath := filepath.Join(s.basePath, relativePath) return os.Remove(filePath) } // GetFullPath returns the absolute path for serving files func (s *LocalStorage) GetFullPath(relativePath string) string { return filepath.Join(s.basePath, relativePath) } ``` -------------------------------- ### Get Payment Stats Summary API Source: https://context7.com/sjperalta/fintera-api-go/llms.txt Fetches a summary of payment statistics, including pending and collected amounts this month, and total overdue payments. Accessed via a GET request to /api/v1/payments/stats with authentication. ```bash curl -X GET http://localhost:8081/api/v1/payments/stats \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." ``` -------------------------------- ### GET /api/v1/notifications Source: https://context7.com/sjperalta/fintera-api-go/llms.txt Lists user notifications with pagination. ```APIDOC ## GET /api/v1/notifications ### Description Lists user notifications with pagination. ### Method GET ### Endpoint `/api/v1/notifications` ### Parameters #### Query Parameters - **page** (integer) - Optional - The page number for pagination (default: 1). - **per_page** (integer) - Optional - The number of notifications per page (default: 20). ### Request Example ```bash curl -X GET "http://localhost:8081/api/v1/notifications?page=1&per_page=20" \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." ``` ### Response #### Success Response (200) - **notifications** (array) - A list of notification objects. - **id** (integer) - The ID of the notification. - **title** (string) - The title of the notification. - **message** (string) - The message content of the notification. - **notification_type** (string) - The type of notification. - **read** (boolean) - Indicates if the notification has been read. - **created_at** (string) - The timestamp when the notification was created. - **pagination** (object) - Pagination details. - **page** (integer) - Current page number. - **per_page** (integer) - Number of items per page. - **total** (integer) - Total number of items. - **total_pages** (integer) - Total number of pages. #### Response Example ```json { "notifications": [ { "id": 1, "title": "Pago Aprobado", "message": "Su pago de $1,287.92 ha sido aprobado", "notification_type": "payment_approved", "read": false, "created_at": "2024-07-20T14:30:00Z" } ], "pagination": { "page": 1, "per_page": 20, "total": 5, "total_pages": 1 } } ``` ``` -------------------------------- ### Implement Repository Pattern for Contracts in Go Source: https://github.com/sjperalta/fintera-api-go/blob/main/docs/go_migration_plan.md Provides a repository implementation for managing contract data using GORM. It defines an interface for CRUD operations and includes methods for finding contracts by ID, by lot, creating, updating, and listing contracts with pagination and filtering. ```go package repository import ( "context" "gorm.io/gorm" "fintera-api/internal/models" ) type ContractRepository interface { FindByID(ctx context.Context, id uint) (*models.Contract, error) FindByLot(ctx context.Context, lotID uint) ([]*models.Contract, error) Create(ctx context.Context, contract *models.Contract) error Update(ctx context.Context, contract *models.Contract) error ListWithPagination(ctx context.Context, query *ContractQuery) (*PaginatedResult[models.Contract], error) } type contractRepository struct { db *gorm.DB } func NewContractRepository(db *gorm.DB) ContractRepository { return &contractRepository{db: db} } func (r *contractRepository) FindByID(ctx context.Context, id uint) (*models.Contract, error) { var contract models.Contract err := r.db.WithContext(ctx). Preload("Lot.Project"). Preload("ApplicantUser"). Preload("Creator"). Preload("Payments"). First(&contract, id).Error if err != nil { return nil, err } return &contract, nil } func (r *contractRepository) ListWithPagination(ctx context.Context, query *ContractQuery) (*PaginatedResult[models.Contract], error) { var contracts []models.Contract var total int64 db := r.db.WithContext(ctx).Model(&models.Contract{}) // Apply filters if query.UserID != 0 { db = db.Where("creator_id = ?", query.UserID) } if query.SearchTerm != "" { db = db.Where("... search conditions ...") } // Count total db.Count(&total) // Apply sorting and pagination db = db.Order(query.SortField + " " + query.SortDirection). Offset((query.Page - 1) * query.PerPage). Limit(query.PerPage). Find(&contracts) return &PaginatedResult[models.Contract]{ Items: contracts, Total: total, Page: query.Page, PerPage: query.PerPage, TotalPages: (int(total) + query.PerPage - 1) / query.PerPage, }, db.Error } ``` -------------------------------- ### Create User (Bash) Source: https://context7.com/sjperalta/fintera-api-go/llms.txt Creates a new user account with specified details including email, password, name, and role. Requires an Authorization header and Content-Type set to application/json. The response includes the newly created user's ID and basic information. ```bash curl -X POST http://localhost:8081/api/v1/users \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \ -H "Content-Type: application/json" \ -d '{ "email": "newcustomer@example.com", "password": "securepassword123", "full_name": "Jane Smith", "phone": "+1987654321", "identity": "0801199567890", "address": "123 Main Street, City", "role": "customer", "rtn": "08011995678901" }' ``` -------------------------------- ### GET /api/v1/reports/commissions_csv Source: https://context7.com/sjperalta/fintera-api-go/llms.txt Exports a CSV report of commissions. ```APIDOC ## GET /api/v1/reports/commissions_csv ### Description Exports a CSV report of commissions. ### Method GET ### Endpoint `/api/v1/reports/commissions_csv` ### Parameters (No parameters specified) ### Request Example ```bash curl -X GET http://localhost:8081/api/v1/reports/commissions_csv \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \ -o commissions_report.csv ``` ### Response #### Success Response (200) (The response will be a CSV file containing the commissions data.) #### Response Example (The response is a file, not a JSON object. Example filename: `commissions_report.csv`) ``` -------------------------------- ### Implement Contract State Machine in Go Source: https://github.com/sjperalta/fintera-api-go/blob/main/docs/go_migration_plan.md Defines a state machine for contract lifecycle management using the 'looplab/fsm' library. It includes states like pending, submitted, approved, rejected, cancelled, and closed, along with transitions and callback hooks for custom logic. ```go package statemachine import ( "github.com/looplab/fsm" ) const ( ContractStatePending = "pending" ContractStateSubmitted = "submitted" ContractStateApproved = "approved" ContractStateRejected = "rejected" ContractStateCancelled = "cancelled" ContractStateClosed = "closed" ) type ContractFSM struct { FSM *fsm.FSM } func NewContractFSM(initialState string) *ContractFSM { return &ContractFSM{ FSM: fsm.NewFSM( initialState, fsm.Events{ {Name: "submit", Src: []string{ContractStatePending, ContractStateRejected}, Dst: ContractStateSubmitted}, {Name: "approve", Src: []string{ContractStatePending, ContractStateSubmitted, ContractStateRejected}, Dst: ContractStateApproved}, {Name: "reject", Src: []string{ContractStatePending, ContractStateSubmitted}, Dst: ContractStateRejected}, {Name: "cancel", Src: []string{ContractStatePending, ContractStateSubmitted, ContractStateRejected}, Dst: ContractStateCancelled}, {Name: "close", Src: []string{ContractStateApproved}, Dst: ContractStateClosed}, {Name: "reopen", Src: []string{ContractStateClosed}, Dst: ContractStateApproved}, }, fsm.Callbacks{ "before_approve": func(e *fsm.Event) { // Guard: validate contract is ready for approval }, "after_approve": func(e *fsm.Event) { // Callback: create payment schedule, notify user }, "after_close": func(e *fsm.Event) { // Callback: mark lot as sold }, }, ), } } ``` -------------------------------- ### GET /api/v1/reports/overdue_payments_csv Source: https://context7.com/sjperalta/fintera-api-go/llms.txt Exports a CSV report of overdue payments. ```APIDOC ## GET /api/v1/reports/overdue_payments_csv ### Description Exports a CSV report of overdue payments. ### Method GET ### Endpoint `/api/v1/reports/overdue_payments_csv` ### Parameters (No parameters specified) ### Request Example ```bash curl -X GET http://localhost:8081/api/v1/reports/overdue_payments_csv \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \ -o overdue_payments.csv ``` ### Response #### Success Response (200) (The response will be a CSV file containing the overdue payments data.) #### Response Example (The response is a file, not a JSON object. Example filename: `overdue_payments.csv`) ``` -------------------------------- ### Create Real Estate Project (API) Source: https://context7.com/sjperalta/fintera-api-go/llms.txt Creates a new real estate project with essential configuration details. Requires project name, address, type, pricing, interest rates, and delivery date. Returns the created project object with an ID. ```bash # Create a new real estate project curl -X POST http://localhost:8081/api/v1/projects \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \ -H "Content-Type: application/json" \ -d '{ "name": "Residencial Las Palmas", "address": "Km 15 Carretera Norte", "description": "Premium residential lots with ocean views", "project_type": "residential", "measurement_unit": "m2", "price_per_square_unit": 150.00, "interest_rate": 12.5, "commission_rate": 5.0, "delivery_date": "2025-12-31", "lot_count": 50 }' ``` -------------------------------- ### GET /api/v1/reports/total_revenue_csv Source: https://context7.com/sjperalta/fintera-api-go/llms.txt Exports a CSV report of total revenue. ```APIDOC ## GET /api/v1/reports/total_revenue_csv ### Description Exports a CSV report of total revenue. ### Method GET ### Endpoint `/api/v1/reports/total_revenue_csv` ### Parameters (No parameters specified) ### Request Example ```bash curl -X GET http://localhost:8081/api/v1/reports/total_revenue_csv \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \ -o revenue_report.csv ``` ### Response #### Success Response (200) (The response will be a CSV file containing the total revenue data.) #### Response Example (The response is a file, not a JSON object. Example filename: `revenue_report.csv`) ``` -------------------------------- ### POST /api/v1/projects Source: https://context7.com/sjperalta/fintera-api-go/llms.txt Creates a new real estate project with configuration for pricing, interest rates, and lot management. ```APIDOC ## POST /api/v1/projects ### Description Creates a new real estate project with configuration for pricing, interest rates, and lot management. ### Method POST ### Endpoint /api/v1/projects ### Parameters #### Request Body - **name** (string) - Required - The name of the project. - **address** (string) - Required - The address of the project. - **description** (string) - Optional - A description of the project. - **project_type** (string) - Required - The type of project (e.g., "residential"). - **measurement_unit** (string) - Required - The unit of measurement for lots (e.g., "m2"). - **price_per_square_unit** (number) - Required - The base price per unit of measurement. - **interest_rate** (number) - Required - The annual interest rate. - **commission_rate** (number) - Required - The commission rate. - **delivery_date** (string) - Required - The expected delivery date in YYYY-MM-DD format. - **lot_count** (integer) - Required - The total number of lots in the project. ### Request Example ```json { "name": "Residencial Las Palmas", "address": "Km 15 Carretera Norte", "description": "Premium residential lots with ocean views", "project_type": "residential", "measurement_unit": "m2", "price_per_square_unit": 150.00, "interest_rate": 12.5, "commission_rate": 5.0, "delivery_date": "2025-12-31", "lot_count": 50 } ``` ### Response #### Success Response (200) - **id** (integer) - The unique identifier of the created project. - **name** (string) - The name of the project. - **address** (string) - The address of the project. - **project_type** (string) - The type of project. - **price_per_square_unit** (number) - The price per square unit. - **interest_rate** (number) - The interest rate. - **commission_rate** (number) - The commission rate. - **lot_count** (integer) - The total number of lots. - **available_lots** (integer) - The number of available lots. - **reserved_lots** (integer) - The number of reserved lots. - **sold_lots** (integer) - The number of sold lots. #### Response Example ```json { "id": 3, "name": "Residencial Las Palmas", "address": "Km 15 Carretera Norte", "project_type": "residential", "price_per_square_unit": 150.00, "interest_rate": 12.5, "commission_rate": 5.0, "lot_count": 50, "available_lots": 50, "reserved_lots": 0, "sold_lots": 0 } ``` ``` -------------------------------- ### GET /api/v1/analytics/distribution Source: https://context7.com/sjperalta/fintera-api-go/llms.txt Retrieves lot distribution statistics for a given project. ```APIDOC ## GET /api/v1/analytics/distribution ### Description Retrieves lot distribution statistics for a given project. ### Method GET ### Endpoint `/api/v1/analytics/distribution` ### Parameters #### Query Parameters - **project_id** (integer) - Required - The ID of the project. ### Request Example ```bash curl -X GET "http://localhost:8081/api/v1/analytics/distribution?project_id=3" \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." ``` ### Response #### Success Response (200) (No specific response body details provided in the source text) #### Response Example (No specific response example provided in the source text) ``` -------------------------------- ### GET /api/v1/reports/user_information_pdf Source: https://context7.com/sjperalta/fintera-api-go/llms.txt Downloads a PDF report of a user's information sheet. ```APIDOC ## GET /api/v1/reports/user_information_pdf ### Description Downloads a PDF report of a user's information sheet. ### Method GET ### Endpoint `/api/v1/reports/user_information_pdf` ### Parameters #### Query Parameters - **user_id** (integer) - Required - The ID of the user. ### Request Example ```bash curl -X GET "http://localhost:8081/api/v1/reports/user_information_pdf?user_id=5" \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \ -o user_info.pdf ``` ### Response #### Success Response (200) (The response will be a PDF file containing the user's information sheet.) #### Response Example (The response is a file, not a JSON object. Example filename: `user_info.pdf`) ``` -------------------------------- ### GET /api/v1/reports/user_rescission_contract_pdf Source: https://context7.com/sjperalta/fintera-api-go/llms.txt Downloads a PDF report of a user's contract rescission. ```APIDOC ## GET /api/v1/reports/user_rescission_contract_pdf ### Description Downloads a PDF report of a user's contract rescission. ### Method GET ### Endpoint `/api/v1/reports/user_rescission_contract_pdf` ### Parameters #### Query Parameters - **contract_id** (integer) - Required - The ID of the contract. ### Request Example ```bash curl -X GET "http://localhost:8081/api/v1/reports/user_rescission_contract_pdf?contract_id=50" \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \ -o contract_rescission.pdf ``` ### Response #### Success Response (200) (The response will be a PDF file containing the contract rescission details.) #### Response Example (The response is a file, not a JSON object. Example filename: `contract_rescission.pdf`) ```