Documentation
¶
Overview ¶
godoo/client.go
godoo/errors.go
godoo/methods.go
Index ¶
- Variables
- type Data
- type Domain
- type DomainCondition
- type Fields
- type LoggerEnv
- type Model
- type OdooClient
- func (c *OdooClient) CallMethod(ctx context.Context, model, method string, args ...interface{}) (interface{}, error)
- func (c *OdooClient) CallOdoo(ctx context.Context, model Model, method string, args []interface{}, ...) (interface{}, error)
- func (c *OdooClient) Create(ctx context.Context, model Model, data []Data, options ...*Options) ([]int64, error)
- func (c *OdooClient) CreateOne(ctx context.Context, model Model, data Data, options ...*Options) (int64, error)
- func (c *OdooClient) Delete(ctx context.Context, model Model, ids []int64, options ...*Options) (bool, error)
- func (c *OdooClient) Read(ctx context.Context, model Model, ids []int64, fields Fields, ...) ([]map[string]interface{}, error)
- func (c *OdooClient) ReadOne(ctx context.Context, model Model, id int64, fields Fields, options ...*Options) (map[string]interface{}, error)
- func (c *OdooClient) ReadWithLimit(ctx context.Context, model Model, ids []int64, fields Fields, options *Options) ([]map[string]interface{}, error)
- func (c *OdooClient) Search(ctx context.Context, model Model, domain Domain, options ...*Options) ([]int64, error)
- func (c *OdooClient) SearchOne(ctx context.Context, model Model, domain Domain, options ...*Options) (int64, error)
- func (c *OdooClient) Update(ctx context.Context, model Model, ids []int64, data Data, options ...*Options) (bool, error)
- func (c *OdooClient) UpdateMultiple(ctx context.Context, model Model, idDataMap map[int64]Data, ...) (map[int64]error, error)
- type OdooContext
- type OdooRPCError
- type Option
- type Options
Constants ¶
This section is empty.
Variables ¶
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.
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.
type LoggerEnv ¶
type LoggerEnv string
LoggerEnv define los tipos de entorno para la configuración del logger.
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 ¶
WithAuthTimeout establece el tiempo de espera de autenticación para OdooClient.
func WithHTTPClient ¶
WithHTTPClient establece un *http.Client personalizado para OdooClient.
func WithLogger ¶
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 ¶
WithLoggerEnv establece la configuración del logger de Zap basada en el entorno. Si WithLogger se usa también, WithLogger tendrá prioridad.
func WithSkipTLSVerify ¶
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.