### Go Complete CRUD Component Setup Example Source: https://github.com/iota-uz/iota-sdk/blob/main/docs/crud-package.md A comprehensive example demonstrating the end-to-end setup of CRUD components in Go. This includes defining entity fields with various constraints (e.g., required, searchable, min/max length, precision, initial values), creating a schema, building the CRUD components with a mapper and validator, and finally registering the generated service and controller with the application. ```go // Define fields fields := crud.NewFields([]crud.Field{ crud.NewUUIDField("id", crud.WithKey(), crud.WithReadonly()), crud.NewStringField("name", crud.WithRequired(), crud.WithSearchable(), crud.WithMinLen(3), crud.WithMaxLen(100), ), crud.NewDecimalField("price", crud.WithPrecision(10), crud.WithScale(2), crud.WithDecimalMin("0.00"), ), crud.NewBoolField("active", crud.WithInitialValue(func() any { return true }), ), crud.NewDateTimeField("created_at", crud.WithReadonly(), crud.WithInitialValue(func() any { return time.Now() }), ), }) // Create schema schema := crud.NewSchema( "products", fields, NewProductMapper(fields), crud.WithValidator(validateProduct), ) // Build CRUD components builder := crud.NewBuilder(schema, eventBus) // Register in module app.RegisterServices(builder.Service()) app.RegisterControllers( controllers.NewCrudController("/products", app, builder), ) ``` -------------------------------- ### Comprehensive Localization Setup Example Source: https://github.com/iota-uz/iota-sdk/blob/main/docs/crud-package.md A combined example demonstrating both the Go schema definition for 'products' and the corresponding English locale JSON file. This snippet shows how to integrate schema creation with the required localization data for field labels. ```go // Schema definition schema := crud.NewSchema("products", fields, mapper) ``` ```json { "products": { "Fields": { "id": "Product ID", "name": "Product Name", "description": "Description", "price": "Price ($)", "active": "Status", "created_at": "Created Date" } } } ``` -------------------------------- ### Quick Start: Test HTTP Controller in Go Source: https://github.com/iota-uz/iota-sdk/blob/main/docs/controller-test-suite.md Demonstrates how to set up and run a basic HTTP controller test using the `controllertest` package in Go. It initializes a test suite, registers a controller, and performs a GET request with a status assertion. ```Go package mymodule_test import ( "testing" "github.com/iota-uz/iota-sdk/pkg/testutils/controllertest" ) func TestMyController(t *testing.T) { suite := controllertest.New(t, myModule) suite.Register(myController) suite.GET("/users").Expect(t).Status(200) } ``` -------------------------------- ### Install fp-go library Source: https://github.com/iota-uz/iota-sdk/blob/main/pkg/fp/README.md Instructions to install the fp-go library using the Go package manager. Requires Go version 1.18 or higher. ```Shell go get github.com/repeale/fp-go ``` -------------------------------- ### Install Go Excel Export Package Source: https://github.com/iota-uz/iota-sdk/blob/main/pkg/excel/README.md Instructions to install the `iota-sdk/pkg/excel` package using Go's package manager. ```bash go get github.com/iota-uz/iota-sdk/pkg/excel ``` -------------------------------- ### Install @iotauz/ai-chat Component Source: https://github.com/iota-uz/iota-sdk/blob/main/ai-chat/README.md Instructions for installing the @iotauz/ai-chat React component using npm, yarn, or pnpm package managers. ```bash npm install @iotauz/ai-chat yarn add @iotauz/ai-chat pnpm add @iotauz/ai-chat ``` -------------------------------- ### Perform HTTP Requests with Controller Test Suite in Go Source: https://github.com/iota-uz/iota-sdk/blob/main/docs/controller-test-suite.md Examples of various HTTP methods (GET, POST, PUT, DELETE) available on the test suite, all returning a `*Request` for chaining. ```Go suite.GET("/path") suite.POST("/path") suite.PUT("/path") suite.DELETE("/path") ``` -------------------------------- ### Basic CRUD Testing in Go Controllers Source: https://github.com/iota-uz/iota-sdk/blob/main/docs/controller-test-suite.md Provides a comprehensive example of testing Create, Read, Update, and Delete (CRUD) operations for a user resource in a Go controller. It covers GET for listing, POST for creation, PUT for updating, and DELETE for removal, demonstrating common HTTP methods and status code assertions. ```go func TestUserCRUD(t *testing.T) { suite := controllertest.New(t, userModule) suite.Register(userController) // List users suite.GET("/users"). Expect(t). Status(200). Contains("Users List") // Create user userData := map[string]string{ "name": "John Doe", "email": "john@example.com", } suite.POST("/users"). JSON(userData). Expect(t). Status(201) // Update user updateData := map[string]string{"name": "Jane Doe"} suite.PUT("/users/1"). JSON(updateData). Expect(t). Status(200) // Delete user suite.DELETE("/users/1"). Expect(t). Status(204) } ``` -------------------------------- ### Go Database Operations with jmoiron/sqlx Source: https://github.com/iota-uz/iota-sdk/blob/main/AGENTS.md Advises following existing patterns for database operations using the `jmoiron/sqlx` library for SQL interactions. ```Go jmoiron/sqlx ``` -------------------------------- ### Run Development Server Source: https://github.com/iota-uz/iota-sdk/blob/main/ai-chat/README.md Commands to start the development server for the @iotauz/ai-chat project using npm, yarn, or pnpm. ```bash npm run dev # or yarn dev # or pnpm dev ``` -------------------------------- ### Create New Controller Test Suite in Go Source: https://github.com/iota-uz/iota-sdk/blob/main/docs/controller-test-suite.md Example of initializing a new test suite with multiple application modules using `controllertest.New`. ```Go suite := controllertest.New(t, userModule, authModule) ``` -------------------------------- ### Go HTTP CRUD Controller Initialization Source: https://github.com/iota-uz/iota-sdk/blob/main/docs/crud-package.md Shows how to initialize a `NewCrudController` in Go, which automatically generates a complete set of RESTful web endpoints for CRUD operations. It also demonstrates how to selectively disable specific operations like delete, create, or edit during controller setup. The generated endpoints include GET for listing and details, POST for creation and updates, and DELETE for removal. ```go controller := controllers.NewCrudController( "/products", app, builder, controllers.WithoutDelete(), // Disable delete controllers.WithoutCreate(), // Disable create controllers.WithoutEdit(), // Disable edit ) ``` -------------------------------- ### Go-Money: Install Package Source: https://github.com/iota-uz/iota-sdk/blob/main/pkg/money/README.md This snippet provides the command to quickly install the Go-Money library using the Go package manager. It is the first step required to integrate and use the library in a Go project. ```bash $ go get github.com/Rhymond/go-money ``` -------------------------------- ### IOTA SDK Development Commands Source: https://github.com/iota-uz/iota-sdk/blob/main/CLAUDE.md Essential commands for building, linting, testing, and managing templates and migrations within the IOTA SDK project. ```shell templ generate && make css ``` ```shell go vet ./... ``` ```shell make test ``` ```shell go test -v ./... ``` ```shell go test -v ./path/to/package -run TestName ``` ```shell go test -v ./path/to/package -run TestName/SubtestName ``` ```shell make check-tr ``` ```shell make migrate up ``` -------------------------------- ### Go Custom Repository Implementation Example Source: https://github.com/iota-uz/iota-sdk/blob/main/docs/crud-package.md Illustrates how to provide a custom implementation for the repository interface in Go. This allows developers to override default data access logic, integrate with different storage solutions, or add specific behaviors for certain entities. The example shows defining a custom struct, a constructor, and implementing a `Create` method, with guidance on implementing other repository methods. ```go type customProductRepo struct { schema crud.Schema[Product] // Add any additional fields needed } func NewCustomProductRepo(schema crud.Schema[Product]) crud.Repository[Product] { return &customProductRepo{ schema: schema, } } // Implement all Repository interface methods func (r *customProductRepo) Create(ctx context.Context, values []crud.FieldValue) (Product, error) { // Custom creation logic // You can use crud.DefaultRepository as a reference implementation return Product{}, nil } // ... implement other methods ... // Use with builder builder := crud.NewBuilder( schema, eventPublisher, crud.WithRepository(NewCustomProductRepo(schema)), ) ``` -------------------------------- ### Export Data Using Go FunctionDataSource Source: https://github.com/iota-uz/iota-sdk/blob/main/docs/excel-exporter-service.md This Go example demonstrates how to use `excel.NewFunctionDataSource` to dynamically generate data for an Excel export. It defines a function that fetches employee data, calculates bonuses, and formats rows, then configures export options like filename, headers, and auto-filters before performing the export and returning the download URL. ```go func (c *MyController) ExportComputedReport(w http.ResponseWriter, r *http.Request) { ctx := r.Context() // Define headers headers := []string{"Employee", "Department", "Base Salary", "Bonus", "Total Compensation"} // Create a function that generates data dynamically dataFunc := func(ctx context.Context) ([][]interface{}, error) { // Fetch base data from multiple sources employees, err := c.employeeService.GetActiveEmployees(ctx) if err != nil { return nil, err } var rows [][]interface{} for _, emp := range employees { // Calculate bonus based on business logic bonus := c.calculateBonus(emp.Performance, emp.Department) total := emp.BaseSalary + bonus row := []interface{}{ emp.Name, emp.Department, emp.BaseSalary, bonus, total, } rows = append(rows, row) } return rows, nil } // Create data source with custom sheet name datasource := excel.NewFunctionDataSource(headers, dataFunc). WithSheetName("Compensation Report") // Configure export options config := exportconfig.New( exportconfig.WithFilename("compensation_report"), exportconfig.WithExportOptions(&excel.ExportOptions{ IncludeHeaders: true, AutoFilter: true, FreezeHeader: true, }), ) // Export using the data source upload, err := c.excelService.ExportFromDataSource(ctx, datasource, config) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // Return download URL json.NewEncoder(w).Encode(map[string]interface{}{ "downloadUrl": upload.URL().String(), "filename": upload.Name() }) } ``` -------------------------------- ### Go-Money: Basic Usage and Splitting Example Source: https://github.com/iota-uz/iota-sdk/blob/main/pkg/money/README.md This example demonstrates the basic initialization of a Money object, adding two Money objects, and then splitting the total amount among multiple parties. It highlights how leftover pennies are distributed in a round-robin fashion to ensure no value is lost. ```go package main import ( "log" "github.com/Rhymond/go-money" ) func main() { pound := money.New(100, money.GBP) twoPounds, err := pound.Add(pound) if err != nil { log.Fatal(err) } parties, err := twoPounds.Split(3) if err != nil { log.Fatal(err) } parties[0].Display() // £0.67 parties[1].Display() // £0.67 parties[2].Display() // £0.66 } ``` -------------------------------- ### Go Testing with testify Assertions Source: https://github.com/iota-uz/iota-sdk/blob/main/AGENTS.md Recommends implementing table-driven tests with descriptive names, utilizing `require` and `assert` packages from `github.com/stretchr/testify` for robust assertions. ```Go github.com/stretchr/testify ``` ```Go require ``` ```Go assert ``` ```Go TestFunctionName_Scenario ``` -------------------------------- ### Go UI Components with templ/htmx Source: https://github.com/iota-uz/iota-sdk/blob/main/AGENTS.md Directs developers to follow existing patterns for UI components built with the `templ` templating engine and `htmx` for dynamic interfaces. ```Go templ/htmx ``` -------------------------------- ### IOTA SDK Build, Lint, and Test Commands Source: https://github.com/iota-uz/iota-sdk/blob/main/GEMINI.md Provides a list of common shell commands used for building, linting, and testing the IOTA SDK project, including commands for Go code compilation, template generation, CSS compilation, and database migrations. ```Shell templ generate && make css go vet ./... go test -v ./... go test -v ./path/to/package -run TestName go test -v ./path/to/package -run TestName/SubtestName make check-tr make migrate up ``` -------------------------------- ### Export Large Dataset with Batching and Options in Go Source: https://github.com/iota-uz/iota-sdk/blob/main/docs/excel-exporter-service.md Provides an example of exporting a large dataset to Excel using `excelService.ExportFromQueryWithOptions`. It configures export options like `MaxRows` to handle pagination internally, preventing memory overload and ensuring efficient processing of extensive data, then returns the file URL and size. ```Go func (c *MyController) ExportLargeDataset(w http.ResponseWriter, r *http.Request) { ctx := r.Context() // Configure for large dataset exportOpts := &excel.ExportOptions{ IncludeHeaders: true, MaxRows: 50000, // Limit to 50k rows per file } // Export with pagination handled internally upload, err := c.excelService.ExportFromQueryWithOptions( ctx, "SELECT * FROM large_table ORDER BY id", "large_dataset", exportOpts, nil, ) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // Return result json.NewEncoder(w).Encode(map[string]interface{}{ "fileUrl": upload.URL().String(), "fileSize": upload.Size().String(), }) } ``` -------------------------------- ### Go Code Formatting Source: https://github.com/iota-uz/iota-sdk/blob/main/AGENTS.md Specifies the use of the standard Go formatting tool to maintain consistent code style across the project. ```Go go fmt ``` -------------------------------- ### Implement Robust Error Handling for Excel Exports in Go Source: https://github.com/iota-uz/iota-sdk/blob/main/docs/excel-exporter-service.md Provides a comprehensive example of error handling for Excel export operations. It demonstrates how to differentiate and respond to various error types, such as context cancellation, database errors, and file saving issues, ensuring graceful degradation and informative feedback. ```Go upload, err := excelService.ExportFromQuery(ctx, query, filename, args...) if err != nil { switch { case errors.Is(err, context.Canceled): // Handle cancellation http.Error(w, "Export cancelled", http.StatusRequestTimeout) case strings.Contains(err.Error(), "failed to execute query"): // Database error http.Error(w, "Database error", http.StatusInternalServerError) case strings.Contains(err.Error(), "failed to save"): // Upload service error http.Error(w, "Failed to save file", http.StatusInternalServerError) default: // Generic error http.Error(w, "Export failed", http.StatusInternalServerError) } return } ``` -------------------------------- ### Go: Code Formatting with go fmt Source: https://github.com/iota-uz/iota-sdk/blob/main/CLAUDE.md This guideline specifies the use of `go fmt` for automatic code formatting in Go projects, ensuring consistent code style and eliminating manual indentation. ```Go go fmt ``` -------------------------------- ### Go: Testing with testify and Table-Driven Tests Source: https://github.com/iota-uz/iota-sdk/blob/main/CLAUDE.md Guidelines for writing tests in Go, emphasizing table-driven tests with descriptive naming conventions (e.g., `TestFunctionName_Scenario`). It also mandates the use of `require` and `assert` packages from `github.com/stretchr/testify` for assertions. ```Go TestFunctionName_Scenario require assert ``` -------------------------------- ### Execute Request and Get Response for Assertions in Go Source: https://github.com/iota-uz/iota-sdk/blob/main/docs/controller-test-suite.md How to execute an HTTP request and obtain a `*Response` object for subsequent assertions using the `Expect` method. ```Go response := suite.GET("/users").Expect(t) ``` -------------------------------- ### IOTA SDK Module Architecture Overview Source: https://github.com/iota-uz/iota-sdk/blob/main/CLAUDE.md Illustrates the Domain-Driven Design (DDD) based module structure within the IOTA SDK, showing the separation of domain, infrastructure, services, and presentation layers. ```directory-structure modules/{module}/ ├── domain/ # Pure business logic │ ├── aggregates/{entity}/ # Complex business entities │ │ ├── {entity}.go # Entity interface │ │ ├── {entity}_impl.go # Entity implementation │ │ ├── {entity}_events.go # Domain events │ │ └── {entity}_repository.go # Repository interface │ ├── entities/{entity}/ # Simpler domain entities │ └── value_objects/ # Immutable domain concepts ├── infrastructure/ # External concerns │ └── persistence/ │ ├── models/models.go # Database models │ ├── {entity}_repository.go # Repository implementations │ ├── {module}_mappers.go # Domain-to-DB mapping │ ├── schema/{module}-schema.sql # SQL schema │ └── setup_test.go # Test utilities ├── services/ # Business logic orchestration │ ├── {entity}_service.go # Service implementation │ ├── {entity}_service_test.go # Service tests │ └── setup_test.go # Test setup ├── presentation/ # UI and API layer │ ├── controllers/ │ │ ├── {entity}_controller.go # HTTP handlers │ │ ├── {entity}_controller_test.go # Controller tests │ │ ├── dtos/{entity}_dto.go # Data transfer objects │ │ └── setup_test.go # Test utilities │ ├── templates/ │ │ ├── pages/{entity}/ # Entity-specific pages │ │ │ ├── list.templ # List view │ │ │ ├── edit.templ # Edit form │ │ │ └── new.templ # Create form │ │ └── components/ # Reusable UI components │ ├── viewmodels/ # Presentation models │ ├── mappers/mappers.go # Domain-to-presentation mapping │ └── locales/ # Internationalization │ ├── en.json # English translations │ ├── ru.json # Russian translations │ └── uz.json # Uzbek translations ├── module.go # Module registration ├── links.go # Navigation items └── permissions/constants.go # RBAC permissions ``` -------------------------------- ### Go: Standard Error Handling with pkg/serrors Source: https://github.com/iota-uz/iota-sdk/blob/main/CLAUDE.md This guideline dictates the use of `pkg/serrors` for managing standard error types within the Go project, promoting consistent error handling practices. ```Go pkg/serrors ``` -------------------------------- ### Go Standard Error Handling Source: https://github.com/iota-uz/iota-sdk/blob/main/AGENTS.md Defines the use of `pkg/serrors` for standard error types to ensure consistent error management throughout the application. ```Go pkg/serrors ``` -------------------------------- ### Go Field-Level Validation Rule Example Source: https://github.com/iota-uz/iota-sdk/blob/main/docs/crud-package.md Illustrates how to apply specific validation rules directly to individual fields when defining them. This example shows how to enforce an email format and mark a field as required using `crud.WithRule` and `crud.WithRequired`. ```go crud.NewStringField("email", crud.WithRule(crud.EmailRule()), crud.WithRequired(), ) ``` -------------------------------- ### IOTA SDK Module Registration Calls in Go Source: https://github.com/iota-uz/iota-sdk/blob/main/AGENTS.md Illustrates the Go code snippets used within `modules/{module}/module.go` to register services, controllers, and quick navigation links for a new module in the IOTA SDK application. These calls ensure that the module's components are properly integrated into the application's lifecycle and accessible. ```Go app.RegisterServices() ``` ```Go app.RegisterControllers() ``` ```Go app.QuickLinks().Add() ``` -------------------------------- ### IOTA SDK Development Build, Lint, and Test Commands Source: https://github.com/iota-uz/iota-sdk/blob/main/AGENTS.md Provides essential shell commands for building, linting, testing, and managing templates and migrations within the IOTA SDK development workflow. These commands are crucial for verifying code quality, ensuring proper compilation, and running automated tests. ```Shell templ generate && make css ``` ```Shell go vet ./... ``` ```Shell make test ``` ```Shell go test -v ./... ``` ```Shell go test -v ./path/to/package -run TestName ``` ```Shell go test -v ./path/to/package -run TestName/SubtestName ``` ```Shell make check-tr ``` ```Shell make migrate up ``` -------------------------------- ### Define Integer Field with Options in Go Source: https://github.com/iota-uz/iota-sdk/blob/main/docs/crud-package.md Example of creating an integer field, specifying minimum and maximum allowed values, marking it as required, and providing an initial value using a function. ```Go crud.NewIntField("age", crud.WithMin(0), crud.WithMax(150), crud.WithRequired(), crud.WithInitialValue(func() any { return 18 }), ) ``` -------------------------------- ### Go Entity-Level Validation Function Example Source: https://github.com/iota-uz/iota-sdk/blob/main/docs/crud-package.md Provides an example of a custom Go function designed for entity-level validation. This function allows for complex business logic checks that might involve multiple fields of an entity, such as ensuring a product's price is greater than its cost. ```go func validateProduct(product Product) error { if product.Price < product.Cost { return errors.New("price must be greater than cost") } return nil } ``` -------------------------------- ### IOTA SDK Module Architecture Directory Structure Source: https://github.com/iota-uz/iota-sdk/blob/main/GEMINI.md Illustrates the Domain-Driven Design (DDD) based module architecture of the IOTA SDK, showing the separation of layers (domain, infrastructure, services, presentation) and their respective subdirectories and file types. ```Directory Structure modules/{module}/ ├── domain/ # Pure business logic │ ├── aggregates/{entity}/ # Complex business entities │ │ ├── {entity}.go # Entity interface │ │ ├── {entity}_impl.go # Entity implementation │ │ ├── {entity}_events.go # Domain events │ │ └── {entity}_repository.go # Repository interface │ ├── entities/{entity}/ # Simpler domain entities │ └── value_objects/ # Immutable domain concepts ├── infrastructure/ # External concerns │ └── persistence/ │ ├── models/models.go # Database models │ ├── {entity}_repository.go # Repository implementations │ ├── {module}_mappers.go # Domain-to-DB mapping │ ├── schema/{module}-schema.sql # SQL schema │ └── setup_test.go # Test utilities ├── services/ # Business logic orchestration │ ├── {entity}_service.go # Service implementation │ ├── {entity}_service_test.go # Service tests │ └── setup_test.go # Test setup ├── presentation/ # UI and API layer │ ├── controllers/ │ │ ├── {entity}_controller.go # HTTP handlers │ │ ├── {entity}_controller_test.go # Controller tests │ │ ├── dtos/{entity}_dto.go # Data transfer objects │ │ └── setup_test.go # Test utilities │ ├── templates/ │ │ ├── pages/{entity}/ # Entity-specific pages │ │ │ ├── list.templ # List view │ │ │ ├── edit.templ # Edit form │ │ │ └── new.templ # Create form │ │ └── components/ # Reusable UI components │ ├── viewmodels/ # Presentation models │ ├── mappers/mappers.go # Domain-to-presentation mapping │ └── locales/ # Internationalization │ ├── en.json # English translations │ ├── ru.json # Russian translations │ └── uz.json # Uzbek translations ├── module.go # Module registration ├── links.go # Navigation items └── permissions/constants.go # RBAC permissions ``` -------------------------------- ### Define Boolean Field with Options in Go Source: https://github.com/iota-uz/iota-sdk/blob/main/docs/crud-package.md Example of creating a boolean field, customizing the labels for true and false states, and setting an initial default value. ```Go crud.NewBoolField("active", crud.WithTrueLabel("Active"), crud.WithFalseLabel("Inactive"), crud.WithInitialValue(func() any { return true }), ) ``` -------------------------------- ### Warning: Do Not Read Generated Templ Files Source: https://github.com/iota-uz/iota-sdk/blob/main/AGENTS.md Warns against manually reading `*_templ.go` files, as they are automatically generated by the `templ generate` command from `.templ` source files and contain no useful information for direct inspection. ```Go *_templ.go ``` ```Go templ generate (make generate) ``` ```Go .templ ``` -------------------------------- ### Avoid Problematic Excel Data Source (Load All Data) in Go Source: https://github.com/iota-uz/iota-sdk/blob/main/docs/excel-exporter-service.md Illustrates a problematic approach to creating an `excel.DataSource` where all data is loaded into memory at once without limits. This anti-pattern can lead to out-of-memory errors for large datasets and should be avoided. ```Go // ❌ Avoid loading all data at once without limits func createProblematicDataSource() excel.DataSource { headers := []string{"ID", "Name"} dataFunc := func(ctx context.Context) ([][]interface{}, error) { // Don't do this - could load millions of rows allData, err := fetchAllDataFromDatabase(ctx) if err != nil { return nil, err } var rows [][]interface{} for _, item := range allData { row := []interface{}{item.ID, item.Name} rows = append(rows, row) } return rows, nil } return excel.NewFunctionDataSource(headers, dataFunc) } ``` -------------------------------- ### Get Response Body as String in Go Source: https://github.com/iota-uz/iota-sdk/blob/main/docs/controller-test-suite.md How to retrieve the entire response body as a string using the `Body` method for parsing or inspection. ```Go body := suite.GET("/api/data").Expect(t).Body() // Parse or inspect body content ``` -------------------------------- ### Inject ExcelExportService into Go Controller Source: https://github.com/iota-uz/iota-sdk/blob/main/docs/excel-exporter-service.md Demonstrates how to inject the `ExcelExportService` into a Go controller or service. This snippet shows the struct definition for `MyController` and a constructor function `NewMyController` that accepts the service as a dependency, facilitating dependency injection. ```go type MyController struct { excelService *services.ExcelExportService } func NewMyController(excelService *services.ExcelExportService) *MyController { return &MyController{ excelService: excelService, } } ``` -------------------------------- ### Define String Field with Options in Go Source: https://github.com/iota-uz/iota-sdk/blob/main/docs/crud-package.md Example of creating a string field with various options, including enabling text search, setting minimum and maximum lengths, applying a regular expression pattern, and marking it as a multiline text area for forms. ```Go crud.NewStringField("name", crud.WithSearchable(), // Enable text search crud.WithMinLen(3), // Minimum length crud.WithMaxLen(100), // Maximum length crud.WithPattern("^[A-Z]"), // Regex pattern crud.WithMultiline(), // Textarea in forms ) ``` -------------------------------- ### Export Data to Excel from SQL Query in Go Source: https://github.com/iota-uz/iota-sdk/blob/main/docs/excel-exporter-service.md Illustrates the simplest way to export data to an Excel file directly from a SQL query using the `ExportFromQuery` method of the `ExcelExportService`. It takes a SQL query, a filename, and query parameters, handles potential errors, and redirects the client to the generated download URL. ```go func (c *MyController) ExportUsers(w http.ResponseWriter, r *http.Request) { ctx := r.Context() // Export active users to Excel upload, err := c.excelService.ExportFromQuery( ctx, "SELECT id, name, email, created_at FROM users WHERE active = $1", "active_users", // filename (without .xlsx) true, // query parameter ) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // Redirect to download URL http.Redirect(w, r, upload.URL().String(), http.StatusSeeOther) } ``` -------------------------------- ### Export Data to Multiple Excel Sheets in Go Source: https://github.com/iota-uz/iota-sdk/blob/main/docs/excel-exporter-service.md Demonstrates how to export data from multiple database queries into separate Excel files, which can then be combined or provided as individual download links. It defines custom data structures for multi-sheet support and shows a handler function for an HTTP request. ```Go // Custom data source supporting multiple sheets type MultiSheetDataSource struct { sheets []SheetData currentSheet int currentRow int } type SheetData struct { Name string Headers []string Rows [][]interface{} } // Implement DataSource interface for each sheet... // Then use multiple exports and combine: func (c *MyController) ExportMultiSheetReport(w http.ResponseWriter, r *http.Request) { // Note: Current implementation exports single sheets // For multi-sheet, export multiple files or extend the Excel package sheets := []struct{ query string name string }{ {"SELECT * FROM sales", "sales"}, {"SELECT * FROM inventory", "inventory"}, {"SELECT * FROM customers", "customers"}, } var uploads []upload.Upload for _, sheet := range sheets { upload, err := c.excelService.ExportFromQuery( r.Context(), sheet.query, sheet.name, ) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } uploads = append(uploads, upload) } // Return all download links var urls []string for _, u := range uploads { urls = append(urls, u.URL().String()) } json.NewEncoder(w).Encode(map[string]interface{}{ "files": urls, }) } ``` -------------------------------- ### Create Optimized Excel Data Source in Go Source: https://github.com/iota-uz/iota-sdk/blob/main/docs/excel-exporter-service.md Demonstrates a best practice for creating an `excel.DataSource` function that processes data in batches to prevent memory issues when dealing with large datasets. It includes context cancellation handling and a total row limit to ensure efficient memory usage. ```Go // ✅ Good practices func createOptimizedDataSource() excel.DataSource { headers := []string{"ID", "Name", "Value"} dataFunc := func(ctx context.Context) ([][]interface{}, error) { const batchSize = 1000 // Process in batches to avoid memory issues var allRows [][]interface{} offset := 0 for { select { case <-ctx.Done(): return nil, ctx.Err() default: } // Fetch batch batch, err := fetchBatch(ctx, offset, batchSize) if err != nil { return nil, err } if len(batch) == 0 { break // No more data } // Convert batch to rows for _, item := range batch { row := []interface{}{item.ID, item.Name, item.Value} allRows = append(allRows, row) } offset += batchSize // Limit total rows to prevent memory issues if len(allRows) >= 50000 { break } } return allRows, nil } return excel.NewFunctionDataSource(headers, dataFunc). WithSheetName("Optimized Data") } ``` -------------------------------- ### Go-Money: Initialize Monetary Values Source: https://github.com/iota-uz/iota-sdk/blob/main/pkg/money/README.md These examples show two primary ways to initialize a Money object: using the smallest currency unit (e.g., 100 for 1 pound) with `money.New`, or directly from a float value with `money.NewFromFloat`. It emphasizes the use of ISO 4217 Currency Codes for setting the currency. ```go pound := money.New(100, money.GBP) quarterEuro := money.NewFromFloat(0.25, money.EUR) ``` -------------------------------- ### Currying functions with fp-go in Go Source: https://github.com/iota-uz/iota-sdk/blob/main/pkg/fp/README.md Demonstrates how fp-go enables currying by default, allowing data-last function application. The example shows filtering positive numbers from a slice by first currying the filter function. ```Go func isPositive(x int) bool { return x > 0 } func main() { filterPositive := fp.Filter(isPositive) numbers := []int{1, 2, 3, 4, 5} positives := filterPositive(numbers) } ``` -------------------------------- ### Export Data to Excel with Custom Options and Styling in Go Source: https://github.com/iota-uz/iota-sdk/blob/main/docs/excel-exporter-service.md Shows how to export data from a SQL query to Excel with advanced customization using `ExportOptions` and `StyleOptions`. `ExportOptions` allows configuring headers, autofilter, date format, and row limits, while `StyleOptions` enables detailed styling for headers and alternate rows. The function returns the generated download URL and filename as a JSON response. ```go func (c *MyController) ExportSalesReport(w http.ResponseWriter, r *http.Request) { ctx := r.Context() // Configure export options exportOpts := &excel.ExportOptions{ IncludeHeaders: true, AutoFilter: true, FreezeHeader: true, DateFormat: "2006-01-02", MaxRows: 10000, // Limit to 10k rows } // Configure styling styleOpts := &excel.StyleOptions{ HeaderStyle: &excel.CellStyle{ Font: &excel.FontStyle{ Bold: true, Size: 12, }, Fill: &excel.FillStyle{ Type: "pattern", Pattern: 1, Color: "#4CAF50", }, }, AlternateRow: true, } // Export with options upload, err := c.excelService.ExportFromQueryWithOptions( ctx, `SELECT order_id, customer_name, product_name, quantity, unit_price, total_amount, order_date FROM sales_orders WHERE order_date BETWEEN $1 AND $2 ORDER BY order_date DESC`, "sales_report", exportOpts, styleOpts, startDate, endDate, ) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // Return download URL as JSON response := map[string]string{ "downloadUrl": upload.URL().String(), "filename": upload.Name(), } json.NewEncoder(w).Encode(response) } ``` -------------------------------- ### Integrate ChatbotInterface Component in React Source: https://github.com/iota-uz/iota-sdk/blob/main/ai-chat/README.md Example demonstrating how to import and use the ChatbotInterface component in a React application, including setting up the API endpoint, custom title, icon, sound options, and a message submission callback. ```jsx import { ChatbotInterface } from '@iotauz/ai-chat'; // Import the pre-compiled CSS styles import '@iotauz/ai-chat/dist/styles.css'; import { MessagesSquare } from 'lucide-react'; // or any other icon library function App() { return ( } soundOptions={{ // Optional: customize sound effects submitSoundPath: "/sounds/custom-submit.mp3", operatorSoundPath: "/sounds/custom-operator.mp3", volume: 0.4, enabled: true }} onMessageSubmit={(message) => { console.log("User submitted message:", message); // Perform actions when a user submits a message }} /> ); } ``` -------------------------------- ### Integrate Excel Export with HTMX in Go Source: https://github.com/iota-uz/iota-sdk/blob/main/docs/excel-exporter-service.md Shows how to handle Excel exports in an HTTP handler, specifically integrating with HTMX requests. It triggers HTMX events for download readiness or error messages, providing a seamless user experience for asynchronous operations. ```Go func (c *MyController) ExportWithHTMX(w http.ResponseWriter, r *http.Request) { ctx := r.Context() // Export data upload, err := c.excelService.ExportFromQuery( ctx, "SELECT * FROM orders WHERE status = $1", "pending_orders", "pending", ) if err != nil { if htmx.IsHxRequest(r) { htmx.SetTrigger(w, "export-error", `{"message": "`+err.Error()+`"}`) } http.Error(w, err.Error(), http.StatusInternalServerError) return } // For HTMX requests, trigger download if htmx.IsHxRequest(r) { htmx.SetTrigger(w, "download-ready", `{"url": "`+upload.URL().String()+`", "filename": "`+upload.Name()+`"}`) w.WriteHeader(http.StatusNoContent) return } // For regular requests, redirect http.Redirect(w, r, upload.URL().String(), http.StatusSeeOther) } ``` -------------------------------- ### Define Decimal Field with Options in Go Source: https://github.com/iota-uz/iota-sdk/blob/main/docs/crud-package.md Example of creating a high-precision decimal field, specifying total digits (precision) and decimal places (scale), setting minimum and maximum decimal values, and marking it as required. ```Go crud.NewDecimalField("price", crud.WithPrecision(10), // Total digits crud.WithScale(2), // Decimal places crud.WithDecimalMin("0.00"), crud.WithDecimalMax("999999.99"), crud.WithRequired(), ) ``` -------------------------------- ### Go HTTP Controller for Exporting User and Sales Data to Excel Source: https://github.com/iota-uz/iota-sdk/blob/main/docs/excel-exporter-service.md This Go code defines a `ReportController` that integrates with an `excelService` to provide API endpoints for generating Excel reports. It includes methods to register HTTP routes (`/api/reports/export/users`, `/api/reports/export/sales`), parse query parameters (e.g., 'status', 'start_date', 'end_date'), execute SQL queries to fetch data, and return JSON responses containing download URLs for the generated Excel files. The `ExportSales` method also demonstrates applying custom styling to the Excel output. ```go package controllers type ReportController struct { excelService *services.ExcelExportService } func NewReportController(excelService *services.ExcelExportService) *ReportController { return &ReportController{ excelService: excelService, } } func (c *ReportController) RegisterRoutes(router *http.ServeMux) { router.HandleFunc("/api/reports/export/users", c.ExportUsers) router.HandleFunc("/api/reports/export/sales", c.ExportSales) } func (c *ReportController) ExportUsers(w http.ResponseWriter, r *http.Request) { ctx := r.Context() // Parse filters status := r.URL.Query().Get("status") if status == "" { status = "active" } // Export with filters upload, err := c.excelService.ExportFromQuery( ctx, `SELECT id, username, email, status, created_at, last_login_at FROM users WHERE status = $1 ORDER BY created_at DESC`, "users_" + status, status, ) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // Return JSON response w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]interface{}{ "success": true, "download_url": upload.URL().String(), "filename": upload.Name(), "size": upload.Size(), }) } func (c *ReportController) ExportSales(w http.ResponseWriter, r *http.Request) { ctx := r.Context() // Parse date range startDate := r.URL.Query().Get("start_date") endDate := r.URL.Query().Get("end_date") if startDate == "" || endDate == "" { http.Error(w, "start_date and end_date are required", http.StatusBadRequest) return } // Configure styling for financial data styleOpts := &excel.StyleOptions{ HeaderStyle: &excel.CellStyle{ Font: &excel.FontStyle{Bold: true}, Fill: &excel.FillStyle{ Type: "pattern", Pattern: 1, Color: "#E3F2FD", }, }, AlternateRow: true, } // Export sales data upload, err := c.excelService.ExportFromQueryWithOptions( ctx, `SELECT order_id, order_date, customer_name, product_name, quantity, unit_price, quantity * unit_price as total FROM sales_orders so JOIN customers c ON so.customer_id = c.id JOIN products p ON so.product_id = p.id WHERE order_date BETWEEN $1 AND $2 ORDER BY order_date DESC`, fmt.Sprintf("sales_%s_to_%s", startDate, endDate), nil, styleOpts, startDate, endDate, ) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // Return response w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]interface{}{ "url": upload.URL().String(), "generated_at": time.Now().Format(time.RFC3339), }) } ``` -------------------------------- ### Export Custom Report with Dynamic Column Selection in Go Source: https://github.com/iota-uz/iota-sdk/blob/main/docs/excel-exporter-service.md Demonstrates how to export a custom report to Excel where the columns are dynamically selected based on user input from an HTTP request. It constructs a dynamic SQL query and uses an `excelService` to generate the report, returning a download URL. ```Go func (c *MyController) ExportCustomReport(w http.ResponseWriter, r *http.Request) { ctx := r.Context() // Parse selected columns from request selectedColumns := r.Form["columns[]"] // Build dynamic query columns := strings.Join(selectedColumns, ", ") query := fmt.Sprintf("SELECT %s FROM products WHERE category = $1", columns) upload, err := c.excelService.ExportFromQuery( ctx, query, "custom_product_report", r.URL.Query().Get("category"), ) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // Return download link w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]string{ "downloadUrl": upload.URL().String(), "message": "Download your report", }) } ``` -------------------------------- ### IOTA SDK Module Architecture Directory Structure Source: https://github.com/iota-uz/iota-sdk/blob/main/AGENTS.md Illustrates the Domain-Driven Design (DDD) based directory structure for modules within the IOTA SDK, showing clear separation of domain, infrastructure, services, and presentation layers. This structure promotes maintainability and scalability by organizing code based on business capabilities and concerns. ```Shell modules/{module}/ ├── domain/ # Pure business logic │ ├── aggregates/{entity}/ # Complex business entities │ │ ├── {entity}.go # Entity interface │ │ ├── {entity}_impl.go # Entity implementation │ │ ├── {entity}_events.go # Domain events │ │ └── {entity}_repository.go # Repository interface │ ├── entities/{entity}/ # Simpler domain entities │ └── value_objects/ # Immutable domain concepts ├── infrastructure/ # External concerns │ └── persistence/ │ ├── models/models.go # Database models │ ├── {entity}_repository.go # Repository implementations │ ├── {module}_mappers.go # Domain-to-DB mapping │ ├── schema/{module}-schema.sql # SQL schema │ └── setup_test.go # Test utilities ├── services/ # Business logic orchestration │ ├── {entity}_service.go # Service implementation │ ├── {entity}_service_test.go # Service tests │ └── setup_test.go # Test setup ├── presentation/ # UI and API layer │ ├── controllers/ │ │ ├── {entity}_controller.go # HTTP handlers │ │ ├── {entity}_controller_test.go # Controller tests │ │ ├── dtos/{entity}_dto.go # Data transfer objects │ │ └── setup_test.go # Test utilities │ ├── templates/ │ │ ├── pages/{entity}/ # Entity-specific pages │ │ │ ├── list.templ # List view │ │ │ ├── edit.templ # Edit form │ │ │ └── new.templ # Create form │ │ └── components/ # Reusable UI components │ ├── viewmodels/ # Presentation models │ ├── mappers/mappers.go # Domain-to-presentation mapping │ └── locales/ # Internationalization │ ├── en.json # English translations │ ├── ru.json # Russian translations │ └── uz.json # Uzbek translations ├── module.go # Module registration ├── links.go # Navigation items └── permissions/constants.go # RBAC permissions ``` -------------------------------- ### Go-Money: Assert Money Value State Source: https://github.com/iota-uz/iota-sdk/blob/main/pkg/money/README.md These examples demonstrate how to use assertion methods like `IsZero()`, `IsPositive()`, and `IsNegative()` to check the state of a Money object. These methods are useful for validating monetary values and implementing conditional logic. ```go pound := money.New(100, money.GBP) result := pound.IsZero() // false pound.IsPositive() // true pound.IsNegative() // false ```