godoo

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 19, 2025 License: MIT Imports: 15 Imported by: 0

README

godoo - Odoo XML-RPC Client for Go

godoo is a Go library providing a simple and flexible client for interacting with Odoo instances via its XML-RPC API (Odoo 12+). It offers a clean and idiomatic Go interface for common Odoo operations such as search, read, create, update, delete, and custom method calls.


Table of Contents


Features

  • XML-RPC Communication: Connects to Odoo's common and object endpoints.
  • Authentication Management: Handles Odoo user authentication and session validity.
  • CRUD Operations:
    • Search: Search records by domain.
    • SearchOne: Search for a single record.
    • Read: Read multiple records by ID and fields.
    • ReadOne: Read a single record by ID and fields.
    • ReadWithLimit: Read records with a specified limit.
    • Create: Create new records.
    • Update: Update existing records.
    • Delete: Delete records.
  • Custom Method Calls: CallMethod for invoking any custom Odoo method.
  • Context Support (context.Context): All operations accept context.Context for cancellation and timeouts, enabling robust and controllable network interactions.
  • Flexible Logging with Zap:
    • Uses go.uber.org/zap for high-performance, structured logging.
    • Provides a default production-ready logger (JSON output).
    • Allows configuration for development (human-readable) or production logging via functional options.
    • Supports injecting a completely custom *zap.Logger instance.
  • Configurable Options: Utilize functional options (godoo.With...) for easy setup of authentication timeouts, TLS verification skipping (for development/testing), and custom HTTP clients.

Installation

To install godoo, use go get:

go get github.com/ilcreatore32/godoo

To fetch a specific version (recommended for production applications), use:

go get github.com/ilcreatore32/godoo@vX.Y.Z

(Replace vX.Y.Z with a release tag like v0.1.0).


Usage

Quick Start

Here's a basic example of how to initialize godoo and perform a simple search operation:

package main

import (
 "context"
 "fmt"
 "log"
 "os"
 "time"

 "github.com/ilcreatore32/godoo"
 "go.uber.org/zap"
)

func main() {
 // 1. Load Odoo connection details from environment variables.
 //    DO NOT hardcode credentials in production.
 odooURL := os.Getenv("ODOO_URL")
 odooDB := os.Getenv("ODOO_DB")
 odooUsername := os.Getenv("ODOO_USERNAME")
 odooPassword := os.Getenv("ODOO_PASSWORD")
 
 if odooURL == "" || odooDB == "" || odooUsername == "" || odooPassword == "" {
  log.Fatalf("Error: Odoo environment variables are not set. See README for details.")
 }

 // 2. Configure your application's logger (optional, but good practice)
 appLogger, _ := zap.NewDevelopment()
 defer func() { _ = appLogger.Sync() }()

 // 3. Initialize the godoo client
 client, err := godoo.New(
  odooURL,
  odooDB,
  odooUsername,
  odooPassword,
  godoo.WithLoggerEnv(godoo.EnvDevelopment), // Use development logger for godoo
  godoo.WithAuthTimeout(3*time.Hour),
  // godoo.WithSkipTLSVerify(true), // DANGER: Do not use in production!
 )
 if err != nil {
  appLogger.Fatal("Failed to initialize Odoo client", zap.Error(err))
 }

 // 4. Create a context with a timeout for your operations
 ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
 defer cancel()

 // 5. Perform an Odoo operation: Search for companies
 fmt.Println("\n--- Searching for Companies ---")
 companyIDs, err := client.Search(ctx, "res.partner", [][]interface{}{{"is_company", "=", true}})
 if err != nil {
  appLogger.Error("Error searching for companies", zap.Error(err))
  return
 }
 fmt.Printf("Found %d company IDs.\n", len(companyIDs))

 if len(companyIDs) > 0 {
  // 6. Read details of the first company found
  fmt.Println("\n--- Reading details of the first company ---")
  company, err := client.ReadOne(ctx, "res.partner", companyIDs[0], []string{"name", "email", "phone"})
  if err != nil {
   appLogger.Error("Error reading company details", zap.Error(err))
   return
  }
  fmt.Printf("Company details: %+v\n", company)
 }

 fmt.Println("\nExample completed.")
}

For more detailed examples, including demonstration of context timeouts and different error types, please refer to the example/ directory:

Handling Errors

godoo returns standard Go error types. For specific Odoo-related errors, godoo provides custom error types that can be checked using errors.Is:

  • godoo.ErrAuthenticationFailed: Returned when Odoo authentication fails (e.g., wrong username/password).
  • godoo.ErrRecordNotFound: Returned by SearchOne or ReadOne if no record matches the criteria.
  • godoo.ErrOdooRPC: A general wrapper for errors returned directly by the Odoo XML-RPC server (e.g., "Access Denied"). You can check if an error is an Odoo RPC error using errors.Is(err, godoo.ErrOdooRPC). The underlying Odoo error message will be embedded.

Example of Error Checking:

import (
    "errors"
    "github.com/ilcreatore32/godoo"
)

// ... inside a function ...
_, err := client.SearchOne(ctx, "res.partner", [][]interface{}{{"name", "=", "NonExistentCompany"}})
if err != nil {
    if errors.Is(err, godoo.ErrRecordNotFound) {
        fmt.Println("Record not found as expected.")
    } else if errors.Is(err, godoo.ErrAuthenticationFailed) {
        fmt.Println("Authentication failed! Check credentials.")
    } else {
        fmt.Printf("An unexpected error occurred: %v\n", err)
    }
}
Custom Method Calls

You can call any custom Odoo method using client.CallMethod. This is useful for invoking server actions, wizard methods, or any method not covered by the standard CRUD functions.

package main

import (
 "context"
 "fmt"
 "log"
 "os"
 "time"

 "github.com/ilcreatore32/godoo"
 "go.uber.org/zap"
)

func main() {
 // ... (client initialization as above) ...

 odooURL := os.Getenv("ODOO_URL")
 odooDB := os.Getenv("ODOO_DB")
 odooUsername := os.Getenv("ODOO_USERNAME")
 odooPassword := os.Getenv("ODOO_PASSWORD")
 
 if odooURL == "" || odooDB == "" || odooUsername == "" || odooPassword == "" {
  log.Fatalf("Error: Odoo environment variables are not set. See README for details.")
 }

 appLogger, _ := zap.NewDevelopment()
 defer func() { _ = appLogger.Sync() }()

 client, err := godoo.New(
  odooURL,
  odooDB,
  odooUsername,
  odooPassword,
  godoo.WithLoggerEnv(godoo.EnvDevelopment),
 )
 if err != nil {
  appLogger.Fatal("Failed to initialize Odoo client", zap.Error(err))
 }

 ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
 defer cancel()

 fmt.Println("\n--- Calling a Custom Odoo Method (e.g., 'check_access_rights') ---")
 var result bool // The type of `result` depends on what your Odoo method returns
 
 // Example: Call `check_access_rights` on `res.partner` model
 // Parameters: model, method_name, args (list), kwargs (map)
 err = client.CallMethod(ctx, "res.partner", "check_access_rights", []interface{}{"read", false}, map[string]interface{}{}, &result)
 if err != nil {
  appLogger.Error("Error calling custom method", zap.Error(err))
  return
 }
 fmt.Printf("Result of 'check_access_rights' for 'res.partner' (read): %t\n", result)

 fmt.Println("\nCustom method call example completed.")
}

Configuration Options

When creating a new godoo.OdooClient using godoo.New(), you can provide several functional options:

  • godoo.WithAuthTimeout(d time.Duration): Sets the duration after which the Odoo authentication session is considered expired and a re-authentication attempt will be made.

  • godoo.WithSkipTLSVerify(skip bool): WARNING: DO NOT USE IN PRODUCTION. If true, TLS certificate verification will be skipped. Useful for development or testing with self-signed certificates.

  • godoo.WithHTTPClient(httpClient *http.Client): Allows you to provide a custom *http.Client instance. This is useful for advanced scenarios like custom Transport implementations, proxy configurations, or fine-grained control over HTTP timeouts.

  • godoo.WithLogger(logger *zap.Logger): Injects a pre-configured *zap.Logger instance directly into the OdooClient. This overrides any settings from WithLoggerEnv.

  • godoo.WithLoggerEnv(env godoo.LoggerEnv): Configures godoo's internal Zap logger based on a predefined environment type:

    • godoo.EnvDevelopment: Configures a human-readable logger (similar to zap.NewDevelopment()) suitable for console output during development. Disables caller info and most stacktraces for cleaner logs.

    • godoo.EnvProduction: Configures a high-performance, structured (JSON) logger (similar to zap.NewProduction()) suitable for production environments and log aggregation systems. Includes caller info and stacktraces for errors.

      If WithLoggerEnv is not provided, the OdooClient defaults to godoo.EnvProduction for its internal logging.


Compatibility

godoo is designed to work with Odoo 12 and newer versions, utilizing their XML-RPC API. Compatibility with older versions is not guaranteed.


Contributing

Contributions are welcome! If you find a bug, have a feature request, or want to contribute code, please feel free to:

  1. Open an issue.
  2. Submit a pull request.

License

godoo is licensed under the MIT License.


Documentation

Overview

godoo/client.go

godoo/errors.go

godoo/methods.go

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrAuthenticationFailed indica que la autenticación con Odoo falló.
	ErrAuthenticationFailed = errors.New("godoo: authentication failed")

	// ErrRecordNotFound indica que no se encontró ningún registro para los criterios dados
	// en operaciones como SearchOne o ReadOne.
	ErrRecordNotFound = errors.New("godoo: no record found for the given criteria")

	// ErrInvalidModel indica que el modelo de Odoo especificado no existe o es inválido.
	ErrInvalidModel = errors.New("godoo: invalid Odoo model")

	// ErrInvalidMethod indica que el método especificado no existe para el modelo de Odoo dado.
	ErrInvalidMethod = errors.New("godoo: invalid Odoo method for the model")

	// ErrOdooRPC es un error genérico para cualquier fallo en la llamada XML-RPC a Odoo,
	// cuando no se puede clasificar más específicamente. El error subyacente de la librería XML-RPC
	// estará envuelto.
	ErrOdooRPC = errors.New("godoo: Odoo XML-RPC call failed")

	// ErrInvalidResponse is returned when the Odoo RPC response is
	// malformed or not in the expected format.
	ErrInvalidResponse = errors.New("invalid Odoo RPC response")
)

Common Odoo client specific errors.

Functions

This section is empty.

Types

type Data added in v1.0.0

type Data map[string]interface{}

Data is a custom type designed to facilitate the declaration of data for Odoo records. It's essentially a map where keys are field names (strings) and values can be of any type (interface{}).

This allows you to define record fields and their values in a structured, readable way, similar to a JSON object or a Python dictionary.

func (Data) ToRPC added in v1.0.0

func (d Data) ToRPC() map[string]interface{}

ToRPC converts the Data type to a map[string]interface{} suitable for Odoo RPC calls. This method is provided for consistency with other ToRPC methods, though a direct type assertion is often sufficient.

type Domain added in v1.0.0

type Domain []DomainCondition

Domain represents a collection of DomainCondition elements. This type is used to build complex filter expressions for Odoo RPC calls.

func (Domain) ToRPC added in v1.0.0

func (d Domain) ToRPC() []interface{}

ToRPC converts the Go-native Domain type into the []interface{} format expected by Odoo's RPC (Remote Procedure Call) for domain filters. This method is crucial for transforming type-safe Go structs into the generic list structure required by the Odoo RPC client.

It specifically handles the transformation of logical operators (like "|" or "&") from a single-element slice (e.g., {"|"}) into a direct string element within the final RPC array (e.g., "|"), aligning with Odoo's expected domain structure.

type DomainCondition added in v1.0.0

type DomainCondition []interface{}

DomainCondition represents a single element within an Odoo domain filter. It can be either a 3-element tuple [field, operator, value] for a condition, or a single string element for a logical operator like "|" or "&".

Examples:

{"name", "=", "John Doe"} // A standard condition
{"|"}                    // A logical OR operator

type Fields added in v1.0.0

type Fields []string

Fields represents a slice of field names to retrieve from Odoo. This type alias adds semantic meaning to a []string when used for Odoo fields.

func (Fields) ToRPC added in v1.0.0

func (f Fields) ToRPC() []string

ToRPC converts the Fields type to a []string suitable for Odoo RPC calls.

type LoggerEnv

type LoggerEnv string

LoggerEnv define los tipos de entorno para la configuración del logger.

const (
	// EnvDevelopment configura el logger para un entorno de desarrollo (salida legible y con colores básicos).
	EnvDevelopment LoggerEnv = "development"
	// EnvProduction configura el logger para un entorno de producción (salida JSON estructurada).
	EnvProduction LoggerEnv = "production"
)

type Model added in v1.0.0

type Model string

Model represents an Odoo model name. This type provides compile-time safety and enables autocompletion in IDEs when using predefined model constants.

const (
	// Product & Inventory Models
	ModelProductProduct  Model = "product.product"  // Product Variants
	ModelProductTemplate Model = "product.template" // Product Templates
	ModelProductCategory Model = "product.category" // Internal Product Categories
	ModelStockPicking    Model = "stock.picking"    // Delivery Orders, Receipts, Internal Transfers
	ModelStockMove       Model = "stock.move"       // Individual Stock Movements
	ModelStockQuant      Model = "stock.quant"      // Inventory Quantities (on hand by location, lot, etc.)
	ModelStockLocation   Model = "stock.location"   // Warehouse Locations

	// Sales & CRM Models
	ModelSaleOrder     Model = "sale.order"      // Sales Orders
	ModelSaleOrderLine Model = "sale.order.line" // Lines within a Sales Order
	ModelCrmLead       Model = "crm.lead"        // CRM Leads/Opportunities
	ModelCrmStage      Model = "crm.stage"       // Stages for CRM Leads/Opportunities
	ModelResPartner    Model = "res.partner"     // Contacts (Customers, Vendors, Addresses)

	// Accounting & Finance Models
	ModelAccountMove     Model = "account.move"      // Journal Entries, Invoices, Vendor Bills, Refunds
	ModelAccountMoveLine Model = "account.move.line" // Lines within an Account Move
	ModelAccountPayment  Model = "account.payment"   // Customer Payments, Vendor Payments
	ModelAccountJournal  Model = "account.journal"   // Accounting Journals (e.g., Sales, Purchase, Bank)
	ModelAccountTax      Model = "account.tax"       // Taxes

	// Purchase Models
	ModelPurchaseOrder     Model = "purchase.order"      // Purchase Orders
	ModelPurchaseOrderLine Model = "purchase.order.line" // Lines within a Purchase Order

	// Human Resources & Payroll Models
	ModelHrEmployee   Model = "hr.employee"   // Employees
	ModelHrDepartment Model = "hr.department" // Departments
	ModelHrJob        Model = "hr.job"        // Job Positions
	ModelHrExpense    Model = "hr.expense"    // Employee Expenses

	// Project & Timesheet Models
	ModelProjectProject      Model = "project.project"       // Projects
	ModelProjectTask         Model = "project.task"          // Project Tasks
	ModelAccountAnalyticLine Model = "account.analytic.line" // Timesheets / Analytic Entries

	// User & System Models
	ModelResUsers           Model = "res.users"             // Users of the Odoo system
	ModelResCompany         Model = "res.company"           // Companies (for multi-company setups)
	ModelResCurrency        Model = "res.currency"          // Currencies
	ModelResCountry         Model = "res.country"           // Countries
	ModelIrModel            Model = "ir.model"              // Odoo Models Metadata (used for introspection)
	ModelIrAttachment       Model = "ir.attachment"         // File Attachments linked to records
	ModelIrActionsActWindow Model = "ir.actions.act_window" // Window Actions (how views are opened)
	ModelIrSequence         Model = "ir.sequence"           // Document Sequencing (e.g., for invoice numbers)

	// Messaging & Activity Models
	ModelMailActivity Model = "mail.activity" // Scheduled Activities (tasks, calls, meetings)
	ModelMailMessage  Model = "mail.message"  // Messages in the chatter (discussions, notes)
	ModelMailThread   Model = "mail.thread"   // Base model for models with chatter functionality
)

Predefined constants for commonly used Odoo models. Expand this list as needed for your application.

type OdooClient

type OdooClient struct {
	// contains filtered or unexported fields
}

OdooClient represents the Odoo XML-RPC client. It holds all connection parameters and session state.

func New

func New(urlStr, db, username, password string, opts ...Option) (*OdooClient, error)

New creates a new OdooClient instance with functional options.

func (*OdooClient) CallMethod

func (c *OdooClient) CallMethod(ctx context.Context, model, method string, args ...interface{}) (interface{}, error)

CallMethod calls a custom method on the specified Odoo model.

func (*OdooClient) CallOdoo added in v1.0.0

func (c *OdooClient) CallOdoo(ctx context.Context, model Model, method string, args []interface{}, options map[string]interface{}) (interface{}, error)

CallOdoo executes a custom Odoo RPC method call using 'execute_kw'. This function provides maximum flexibility for calling any Odoo model method with custom arguments and options, including the Odoo context.

Parameters:

  • ctx: The Go context for the request, enabling cancellation and timeouts.
  • model: The Odoo model name (e.g., ModelResPartner, ModelProductTemplate).
  • method: The name of the Odoo model method to call (e.g., "search", "read", "create", "write", "unlink", or a custom method like "my_custom_action").
  • args: A slice of interfaces representing the positional arguments for the Odoo method. This corresponds to the third argument of Odoo's `execute_kw` call, which is a list of arguments for the method being called. Example for `read`: `[]interface{}{[]int64{1, 2, 3}, []string{"name", "display_name"}}` When using `Domain`, `Fields`, or `Data` types, remember to call their `.ToRPC()` method or cast to their underlying types.
  • options: A map of string to interface{} representing keyword arguments for the Odoo method. This corresponds to the fourth argument of Odoo's `execute_kw` call, which is a dictionary of options. This is where Odoo's `context` (e.g., `{"context": {"lang": "es_ES"}}`), `limit`, `offset`, `order`, etc., are passed. If using `godoo.Options`, call `myOptions.ToRPC()`.

Returns:

  • interface{}: The raw result from the Odoo RPC call. The caller is responsible for type asserting this value to the expected Go type (e.g., `int64`, `[]int64`, `map[string]interface{}`, `[]map[string]interface{}`, `bool`, etc.).
  • error: An error if the operation fails due to connection issues, Odoo RPC errors, or context cancellation/timeout.

func (*OdooClient) Create

func (c *OdooClient) Create(ctx context.Context, model Model, data []Data, options ...*Options) ([]int64, error)

Create creates one or more new records in the specified Odoo model.

Parameters:

  • ctx: The context for the request.
  • model: The Odoo model name where the records will be created.
  • data: A slice of Data types, where each Data map represents the field-value pairs for a new record. Example: `[]godoo.Data{{"name": "Prod 1"}, {"name": "Prod 2"}}`.
  • options: Optional pointer to an Options struct to include additional context.

Returns:

  • []int64: A slice of IDs of the newly created records. Returns an empty slice if no records are created.
  • error: An error if the creation fails, or if the response type is unexpected. Note: Odoo's RPC usually returns `[]int64` for multiple creations.

func (*OdooClient) CreateOne added in v1.0.0

func (c *OdooClient) CreateOne(ctx context.Context, model Model, data Data, options ...*Options) (int64, error)

CreateOne creates a single new record in the specified Odoo model. It returns the ID (int64) of the newly created record.

Parameters:

  • ctx: The context for the request.
  • model: The Odoo model name where the record will be created.
  • data: A Data type representing the field-value pairs for the new record. Example: `godoo.Data{"name": "Single Product", "price": 25.0}`.
  • options: Optional pointer to an Options struct to include additional context.

Returns:

  • int64: The ID of the newly created record.
  • error: An error if the creation fails, or if the response type is unexpected.

func (*OdooClient) Delete

func (c *OdooClient) Delete(ctx context.Context, model Model, ids []int64, options ...*Options) (bool, error)

Delete deletes records from the specified Odoo model.

Parameters:

  • ctx: The context for the request.
  • model: The Odoo model name from which records will be deleted.
  • ids: A slice of int64 representing the IDs of the records to delete.
  • options: Optional pointer to an Options struct to include additional context.

Returns:

  • bool: `true` if the deletion operation was successful, `false` otherwise.
  • error: An error if the deletion fails, or if the response type is unexpected.

func (*OdooClient) Read

func (c *OdooClient) Read(ctx context.Context, model Model, ids []int64, fields Fields, options ...*Options) ([]map[string]interface{}, error)

Read performs a read operation on the specified Odoo model, retrieving records by their IDs. It fetches specific fields for the given records.

Parameters:

  • ctx: The context for the request.
  • model: The Odoo model name.
  • ids: A slice of int64 representing the IDs of the records to read.
  • fields: A Fields type representing the names of the fields to retrieve. If `fields` is empty or nil, Odoo will typically return a default set of fields.
  • options: Optional pointer to an Options struct to include additional context or override default behavior.

Returns:

  • []map[string]interface{}: A slice of maps, where each map represents a record and contains field-value pairs.
  • error: An error if the operation fails, or if parsing the response fails.

func (*OdooClient) ReadOne

func (c *OdooClient) ReadOne(ctx context.Context, model Model, id int64, fields Fields, options ...*Options) (map[string]interface{}, error)

ReadOne performs a read operation for a single record on the specified Odoo model. It retrieves specific fields for the given record ID.

Parameters:

  • ctx: The context for the request.
  • model: The Odoo model name.
  • id: The int64 ID of the single record to read.
  • fields: A Fields type representing the names of the fields to retrieve. If `fields` is empty or nil, Odoo will return a default set of fields.
  • options: Optional pointer to an Options struct to include additional context or override default behavior.

Returns:

  • map[string]interface{}: A map representing the single record, containing field-value pairs.
  • error: An error if the operation fails, or `ErrRecordNotFound` if no record is found for the given ID.

func (*OdooClient) ReadWithLimit

func (c *OdooClient) ReadWithLimit(ctx context.Context, model Model, ids []int64, fields Fields, options *Options) ([]map[string]interface{}, error)

ReadWithLimit performs a read operation on the specified Odoo model with IDs, fields, and options. This is useful for fetching a subset of records when dealing with a large set of IDs, and applying specific Odoo context or ordering. Note that this method does not perform an internal 'search' prior to 'read'; it expects the IDs to be provided directly. Use `Search` followed by `Read` if filtering is needed.

Parameters:

  • ctx: The context for the request.
  • model: The Odoo model name.
  • ids: A slice of int64 representing the IDs of the records to read.
  • fields: A Fields type representing the names of the fields to retrieve.
  • options: A pointer to an Options struct, allowing specification of limit, offset, order, and context. This argument is not optional and should always be provided, even if empty, to configure the read behavior.

Returns:

  • []map[string]interface{}: A slice of maps, where each map represents a record.
  • error: An error if the operation fails.

func (*OdooClient) Search

func (c *OdooClient) Search(ctx context.Context, model Model, domain Domain, options ...*Options) ([]int64, error)

Search performs a search operation on the specified Odoo model. It returns a slice of integer IDs (int64) that match the given domain.

Parameters:

  • ctx: The context for the request, enabling cancellation and timeouts.
  • model: The Odoo model name (e.g., ModelResPartner, ModelProductTemplate).
  • domain: A Domain type representing the Odoo domain filter. Example: `godoo.Domain{{"name", "=", "John Doe"}, {"active", "=", true}}` For complex logical operations like OR/AND, proper nesting is required: `godoo.Domain{"&", {"is_company", "=", true}, {"|", {"email", "ilike", "%example.com"}, {"active", "=", false}}}`
  • options: Optional pointer to an Options struct to control search parameters like limit, offset, order, and context.

Returns:

  • []int64: A slice of IDs of the records that match the search criteria.
  • error: An error if the operation fails, including network issues, Odoo RPC errors, or context cancellation/timeout. Returns `ErrRecordNotFound` if no records match the domain (though Odoo search usually returns empty list, not error).

func (*OdooClient) SearchOne

func (c *OdooClient) SearchOne(ctx context.Context, model Model, domain Domain, options ...*Options) (int64, error)

SearchOne performs a search operation on the specified Odoo model, but limits the result to at most one record. This is useful when you expect a unique record based on the domain.

Parameters:

  • ctx: The context for the request.
  • model: The Odoo model name.
  • domain: The Domain type representing the Odoo domain filter.
  • options: Optional pointer to an Options struct to include additional context or override default behavior. Note: The `Limit` option will be internally set to 1 for this method.

Returns:

  • int64: The ID of the single record found.
  • error: An error if the operation fails, or `ErrRecordNotFound` if no record is found. If multiple records are found (which should not happen with limit 1, but as a safeguard), it logs a warning and returns the first ID.

func (*OdooClient) Update

func (c *OdooClient) Update(ctx context.Context, model Model, ids []int64, data Data, options ...*Options) (bool, error)

Update updates existing records in the specified Odoo model.

Parameters:

  • ctx: The context for the request.
  • model: The Odoo model name where records will be updated.
  • ids: A slice of int64 representing the IDs of the records to update.
  • data: A Data type where keys are field names (string) and values are the new data for those fields. Only the fields specified in `data` will be updated. Example: `godoo.Data{"name": "Updated Product Name", "price": 12.0}`.
  • options: Optional pointer to an Options struct to include additional context.

Returns:

  • bool: `true` if the update operation was successful, `false` otherwise.
  • error: An error if the update fails, or if the response type is unexpected.

func (*OdooClient) UpdateMultiple added in v1.0.0

func (c *OdooClient) UpdateMultiple(ctx context.Context, model Model, idDataMap map[int64]Data, options ...*Options) (map[int64]error, error)

UpdateMultiple updates multiple existing records in the specified Odoo model, allowing different data to be applied to each record.

This function iterates through the provided map of IDs and their respective data, making an individual Odoo RPC call for each record concurrently using goroutines. This can improve performance for a large number of independent record updates.

Parameters:

  • ctx: The context for the request, enabling cancellation and timeouts for each individual update.
  • model: The Odoo model name where records will be updated.
  • idDataMap: A map where keys are the int64 IDs of the records to update, and values are Data maps containing the specific field-value pairs for each corresponding record. Example: map[int64]godoo.Data{ 1: {"name": "Updated Item 1", "active": true}, 2: {"description": "New description for item 2"}, }

Returns:

  • map[int64]error: A map indicating the success or failure for each ID. If an ID was updated successfully, its value in the map will be nil. If an error occurred for a specific ID, the error will be present. This map will be empty if idDataMap is empty or nil.
  • error: An error if there's a fundamental issue before starting updates (e.g., connection failure), or if the main context is cancelled. Individual record errors are captured in the returned map.

type OdooContext added in v1.0.0

type OdooContext map[string]interface{}

OdooContext represents the 'context' dictionary passed as an option in Odoo RPC calls. It allows custom key-value pairs that influence Odoo's server-side logic (e.g., language, timezone, active_test).

type OdooRPCError

type OdooRPCError struct {
	OriginalError error  // El error subyacente de la librería xmlrpc
	Code          int    // Código de error de Odoo (si se puede parsear, a menudo 0 o -32xxx)
	Message       string // Mensaje de error de Odoo
}

OdooRPCError representa un error más estructurado devuelto por el servidor Odoo XML-RPC. Envuelve el error original del cliente XML-RPC.

func (*OdooRPCError) Error

func (e *OdooRPCError) Error() string

Error implementa la interfaz error para OdooRPCError.

func (*OdooRPCError) Unwrap

func (e *OdooRPCError) Unwrap() error

Unwrap permite el uso de errors.Is y errors.As con OdooRPCError.

type Option

type Option func(*OdooClient)

Option es una función que configura un OdooClient.

func WithAuthTimeout

func WithAuthTimeout(d time.Duration) Option

WithAuthTimeout establece el tiempo de espera de autenticación para OdooClient.

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) Option

WithHTTPClient establece un *http.Client personalizado para OdooClient.

func WithLogger

func WithLogger(logger *zap.Logger) Option

WithLogger establece un logger de Zap personalizado para OdooClient. Si se usa esta opción, anula la configuración automática de entorno.

func WithLoggerEnv

func WithLoggerEnv(env LoggerEnv) Option

WithLoggerEnv establece la configuración del logger de Zap basada en el entorno. Si WithLogger se usa también, WithLogger tendrá prioridad.

func WithSkipTLSVerify

func WithSkipTLSVerify(skip bool) Option

WithSkipTLSVerify establece si se debe omitir la verificación de certificados TLS. ADVERTENCIA: No usar en producción.

type Options added in v1.0.0

type Options struct {
	Context OdooContext            `json:"context,omitempty"` // Odoo's context dictionary
	Limit   int                    `json:"limit,omitempty"`   // Maximum number of records to return
	Offset  int                    `json:"offset,omitempty"`  // Number of records to skip
	Order   string                 `json:"order,omitempty"`   // Field(s) to sort by (e.g., "name asc", "date desc,id asc")
	Extra   map[string]interface{} `json:"extra,omitempty"`   // For any other less common Odoo options
}

Options represents common keyword arguments for Odoo RPC methods. This struct simplifies specifying common options like limit, offset, order, and the Odoo-specific 'context'. For less common options, the 'Extra' map can be used.

func (*Options) ToRPC added in v1.0.0

func (o *Options) ToRPC() map[string]interface{}

ToRPC converts the Options struct into the map[string]interface{} format expected by Odoo's RPC.

Directories

Path Synopsis
godoo/example/main.go
godoo/example/main.go

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL