All connectors

Dolibarr

Official

Dolibarr

Let agents read customers, products, stock, orders, invoices, payments and bank accounts. Write access also permits record changes, stock movements, order/invoice validation and recording payments.

Guaranteed read-only access requires a non-admin Dolibarr user with read-only permissions. The user's permissions remain the final limit on the API key.

Supports Dolibarr 16+ over HTTPS, at the domain root or within up to two folders.

Connect Dolibarr.

Setup instructions

Connect Dolibarr

Requires Dolibarr 16 or later over HTTPS and an administrator to enable the API.

For Read access, use a non-admin user's key with only read permissions. Dolibarr administrators bypass most permission checks.

  1. Enable API / Web services (REST server) under Setup → Modules/Applications.
  2. Create a non-admin, non-external houston user under Users & Groups. Grant read permissions for the modules agents need. Add Extend access to all third parties AND their objects only if agents should see all third parties; otherwise access is limited to the user's assigned ones.
  3. On the user's card, choose Modify and generate Token for API (Key for API before version 23). Save and copy it.
  4. In Houston, enter Dolibarr domain without https:// or a path. Put a folder such as /dolibarr in Install path. Paste API key, choose Read for Access and save.

Official REST API guide.

Advanced

Changes

Use a separate key and a connection with Write access. Grant create/modify permissions only for the relevant modules. Stock changes require Create/modify warehouses; invoice payments require Create payments for customer invoices (version 24+) or Create/modify customer invoices on earlier versions. With advanced permissions, also grant order/invoice validation. Validation assigns final numbers and may send notifications. Agents cannot delete records.

Connection problems

The API must answer at https://<domain><install path>/api/index.php/status. Use the final HTTPS domain; redirects and install paths deeper than two folders are unsupported. Check enabled modules, user permissions and API IP restrictions. Before version 20, missing permissions can return 401. Multicompany access uses the key owner's entity.

Files

  • connector.luau
    -- Dolibarr REST API (Dolibarr 16 to 24). Arguments and results keep Dolibarr's native field names.
    type Options = {[string]: any}
    type Endpoint = {name: string, method: string?, path: string, list: {string}?, query: {string}?, required: {string}?,
    	fields: string?, returns: string?, choices: {[string]: {any}}?, paging: {string}?}
    
    local HOST = string.lower(config.host)
    local DOCS = "https://wiki.dolibarr.org/index.php/Module_Web_Services_API_REST_(developer)"
    local NONE: Options = table.freeze({})
    local EMPTY: {string} = table.freeze({})
    local MAX_ID = 9007199254740991
    
    -- The install path is the part of the address before /index.php, such as /dolibarr;
    -- the proxy allows at most two folders. A .php, .phtml or similar folder would send
    -- the key to another script through its path info. An invalid path fails each call,
    -- not help().
    local function base(raw: string?): string?
    	-- People may paste the page or the API address: drop a trailing index.php and api folder.
    	local text = "/" .. string.gsub(string.gsub(raw or "", "^[%s/]+", ""), "[%s/]+$", "")
    	text = string.gsub(string.gsub(text, "/index%.php$", ""), "/api$", "")
    	local segments: {string} = {}
    	for segment in string.gmatch(text, "[^/]+") do
    		if not string.match(segment, "^[%w%-_.~]+$") or string.match(segment, "^%.+$")
    			or string.find(string.lower(segment), ".ph", 1, true) then return nil end
    		table.insert(segments, segment)
    	end
    	if #segments > 2 then return nil end
    	return "https://" .. HOST .. (if #segments > 0 then "/" .. table.concat(segments, "/") else "") .. "/api/index.php"
    end
    local API = base(config.install_path)
    
    -- Endpoints read on every connection; list endpoints page with PAGE plus their own options.
    local PAGE = {"sortfield", "sortorder", "limit", "page", "sqlfilters", "properties"}
    -- Dolibarr ignores a status or mode it does not know, which would return an unfiltered list.
    local INVOICE_STATUSES = {"draft", "unpaid", "paid", "cancelled"}
    local READS: {Endpoint} = {
    	{name = "getStatus", path = "/status", returns = "{success: {code, dolibarr_version, ...}}"},
    	{name = "listThirdparties", path = "/thirdparties", list = {"mode", "category"}, choices = {mode = {1, 2, 3, 4}}},
    	{name = "getThirdparty", path = "/thirdparties/{id}"},
    	{name = "listContacts", path = "/contacts", list = {"thirdparty_ids", "category"}},
    	{name = "getContact", path = "/contacts/{id}"},
    	{name = "listProducts", path = "/products", list = {"mode", "category", "includestockdata"}, choices = {mode = {1, 2}}},
    	{name = "getProduct", path = "/products/{id}", query = {"includestockdata"}},
    	{name = "getProductStock", path = "/products/{id}/stock", query = {"selected_warehouse_id"},
    		returns = "{stock_warehouses: {[warehouseID]: {real, ...}}, stock_reel, stock_theorique}"},
    	{name = "listWarehouses", path = "/warehouses", list = {"category"}},
    	{name = "getWarehouse", path = "/warehouses/{id}"},
    	{name = "listStockMovements", path = "/stockmovements", list = {}},
    	{name = "listCategories", path = "/categories", list = {"type"}},
    	{name = "getCategory", path = "/categories/{id}"},
    	{name = "listOrders", path = "/orders", list = {"thirdparty_ids", "sqlfilterlines"}},
    	{name = "getOrder", path = "/orders/{id}"},
    	{name = "listInvoices", path = "/invoices", list = {"thirdparty_ids", "status"}, choices = {status = INVOICE_STATUSES}},
    	{name = "getInvoice", path = "/invoices/{id}"},
    	{name = "listInvoicePayments", path = "/invoices/{id}/payments", returns = "[{amount, date, num, ref, type, ...}]"},
    	{name = "listProposals", path = "/proposals", list = {"thirdparty_ids"}},
    	{name = "getProposal", path = "/proposals/{id}"},
    	{name = "listShipments", path = "/shipments", list = {"thirdparty_ids"}},
    	{name = "getShipment", path = "/shipments/{id}"},
    	{name = "listSupplierOrders", path = "/supplierorders", list = {"thirdparty_ids", "status"}, choices = {status = {"draft",
    		"validated", "approved", "running", "received_start", "received_end", "cancelled", "refused"}}},
    	{name = "getSupplierOrder", path = "/supplierorders/{id}"},
    	{name = "listSupplierInvoices", path = "/supplierinvoices", list = {"thirdparty_ids", "status"}, choices = {status = INVOICE_STATUSES}},
    	{name = "getSupplierInvoice", path = "/supplierinvoices/{id}"},
    	{name = "listSupplierInvoicePayments", path = "/supplierinvoices/{id}/payments", returns = "[{amount, date, num, ref, type, ...}]"},
    	{name = "listBankAccounts", path = "/bankaccounts", list = {"category"}},
    	{name = "getBankAccount", path = "/bankaccounts/{id}"},
    	{name = "listBankAccountLines", path = "/bankaccounts/{id}/lines", query = {"sqlfilters"}, required = {"sqlfilters"},
    		returns = "[line]"},
    	{name = "getBankAccountBalance", path = "/bankaccounts/{id}/balance", returns = "number"},
    	{name = "listPaymentTypes", path = "/setup/dictionary/payment_types", list = {}, paging = {"sortfield", "sortorder", "limit", "page", "sqlfilters"}},
    }
    -- Endpoints write access adds. A POST create answers with the new record's ID.
    local WRITES: {Endpoint} = {
    	{name = "createThirdparty", method = "POST", path = "/thirdparties", fields = "required", required = {"name"}, returns = "id"},
    	{name = "updateThirdparty", method = "PUT", path = "/thirdparties/{id}", fields = "required"},
    	{name = "createContact", method = "POST", path = "/contacts", fields = "required", required = {"lastname"}, returns = "id"},
    	{name = "updateContact", method = "PUT", path = "/contacts/{id}", fields = "required"},
    	{name = "createProduct", method = "POST", path = "/products", fields = "required", required = {"ref", "label"}, returns = "id"},
    	{name = "updateProduct", method = "PUT", path = "/products/{id}", fields = "required"},
    	{name = "createStockMovement", method = "POST", path = "/stockmovements", fields = "required",
    		required = {"product_id", "warehouse_id", "qty"}, returns = "id"},
    	{name = "createOrder", method = "POST", path = "/orders", fields = "required", required = {"socid", "date"}, returns = "id"},
    	{name = "addOrderLine", method = "POST", path = "/orders/{id}/lines", fields = "required", returns = "lineID"},
    	{name = "validateOrder", method = "POST", path = "/orders/{id}/validate", fields = "optional"},
    	{name = "closeOrder", method = "POST", path = "/orders/{id}/close", fields = "optional"},
    	{name = "createInvoice", method = "POST", path = "/invoices", fields = "required", required = {"socid"}, returns = "id"},
    	{name = "createInvoiceFromOrder", method = "POST", path = "/invoices/createfromorder/{id}"},
    	{name = "addInvoiceLine", method = "POST", path = "/invoices/{id}/lines", fields = "required", returns = "lineID"},
    	{name = "validateInvoice", method = "POST", path = "/invoices/{id}/validate", fields = "optional"},
    	{name = "addInvoicePayment", method = "POST", path = "/invoices/{id}/payments", fields = "required",
    		required = {"datepaye", "paymentid", "closepaidinvoices", "accountid"}, returns = "paymentID"},
    }
    
    -- Dolibarr strips the password and key fields from user records; the connector also drops
    -- them anywhere else, with a third party's key for its partner's web service. Filtering or
    -- sorting on them would reveal them a character at a time, so queries cannot name them.
    local SECRET: {[string]: boolean} = {api_key = true, pass = true, pass_crypted = true, pass_indatabase = true,
    	pass_indatabase_crypted = true, pass_temp = true, clicktodial_password = true, webservices_key = true}
    
    local function column(value: string, name: string)
    	local field = string.lower(string.match(value, "([^%.]*)$") or value)
    	assert(not SECRET[field], name .. " cannot use " .. field .. ", which the connector withholds")
    end
    
    -- Dolibarr reads a field only between a term's ( and its first :, and a value cannot
    -- contain parentheses, so words inside values stay allowed. Dolibarr 16-17 keep only the
    -- letters, digits, _ and . of that field, so the check does too.
    local function withheld(value: string, name: string): string
    	for field in string.gmatch(value, "%(([^:()]*):") do column((string.gsub(field, "[^%w_%.]", "")), name) end
    	return value
    end
    
    -- Dolibarr returns IDs as strings, so digit strings are accepted too.
    local function id(value: any, name: string): string
    	local valid = if type(value) == "number" then value >= 1 and value <= MAX_ID and value % 1 == 0
    		else type(value) == "string" and #value <= 16 and string.match(value, "^[1-9]%d*$") ~= nil and (tonumber(value) or math.huge) <= MAX_ID
    	assert(valid, name .. " must be a positive integer ID")
    	return if type(value) == "number" then string.format("%d", value) else value
    end
    
    local function integer(value: any, name: string, min: number, max: number): string
    	assert(type(value) == "number" and value % 1 == 0 and value >= min and value <= max,
    		name .. " must be an integer from " .. string.format("%d", min) .. " to " .. string.format("%d", max))
    	return string.format("%d", value)
    end
    
    local function text(value: any, name: string, pattern: string): string
    	assert(type(value) == "string" and #value <= 4000 and string.match(value, pattern), name .. " is not valid")
    	return value
    end
    
    local function array(value: any, name: string): {any}
    	assert(type(value) == "table" and #value > 0, name .. " must be a nonempty array")
    	local count = 0
    	for _ in value do count += 1 end
    	assert(count == #value, name .. " must be an array")
    	return value
    end
    
    local FIELD = "^[%a_][%w_]*$"
    -- Each option's query value. Restler reads http_method, and Dolibarr DOLAPIKEY, from any
    -- query string, so queries are only ever built from these closed option names.
    local ENCODE: {[string]: (any, string) -> string} = {
    	sortfield = function(value, name)
    		assert(type(value) == "string" and (string.match(value, FIELD) or string.match(value, "^[%a_][%w_]*%.[%a_][%w_]*$")),
    			name .. " must be a column such as t.rowid")
    		column(value, name)
    		return value
    	end,
    	sortorder = function(value, name)
    		assert(value == "ASC" or value == "DESC", name .. " must be ASC or DESC")
    		return value
    	end,
    	limit = function(value, name) return integer(value, name, 1, 200) end,
    	page = function(value, name) return integer(value, name, 0, MAX_ID) end,
    	sqlfilters = function(value, name) return withheld(text(value, name, "%S"), name) end,
    	sqlfilterlines = function(value, name) return withheld(text(value, name, "%S"), name) end,
    	properties = function(value, name)
    		local names: {string} = {}
    		for _, item in array(value, name) do table.insert(names, text(item, name, FIELD)) end
    		return table.concat(names, ",")
    	end,
    	thirdparty_ids = function(value, name)
    		local ids: {string} = {}
    		local items: {any} = if type(value) == "table" then array(value, name) else {value}
    		for _, item in items do table.insert(ids, id(item, name)) end
    		return table.concat(ids, ",")
    	end,
    	-- Each endpoint's choices already restrict mode and status.
    	mode = function(value) return string.format("%d", value) end,
    	category = id,
    	selected_warehouse_id = id,
    	status = function(value) return value end,
    	type = function(value, name) return text(value, name, FIELD) end,
    	includestockdata = function(value, name)
    		assert(type(value) == "boolean", name .. " must be a boolean")
    		return if value then "1" else "0"
    	end,
    }
    
    local function optionNames(endpoint: Endpoint): {string}
    	local names: {string} = {}
    	local groups: {{string}} = {if endpoint.list then endpoint.paging or PAGE else EMPTY, endpoint.list or EMPTY, endpoint.query or EMPTY}
    	for _, group in groups do
    		for _, name in group do table.insert(names, name) end
    	end
    	return names
    end
    
    local function query(endpoint: Endpoint, input: any): string
    	if input ~= nil then assert(type(input) == "table", "opts must be an object") end
    	local opts: Options = input or NONE
    	local allowed: {[string]: boolean} = {}
    	for _, name in optionNames(endpoint) do allowed[name] = true end
    	local keys: {string} = {}
    	for key in opts do
    		assert(type(key) == "string" and allowed[key], tostring(key) .. " is not a supported option")
    		table.insert(keys, key)
    	end
    	-- required names fields for writes and options for reads.
    	if not endpoint.fields then
    		for _, name in endpoint.required or EMPTY do assert(opts[name] ~= nil, name .. " is required") end
    	end
    	-- Dolibarr returns the whole table for limit=0, so lists always send a limit.
    	if endpoint.list then
    		if opts.limit == nil then table.insert(keys, "limit") end
    		if opts.page == nil then table.insert(keys, "page") end
    	end
    	table.sort(keys)
    	local parts: {string} = {}
    	for _, key in keys do
    		local value = opts[key]
    		if value == nil then value = if key == "limit" then 100 else 0 end
    		local choices = if endpoint.choices then endpoint.choices[key] else nil
    		if choices then assert(table.find(choices, value), key .. " must be one of " .. table.concat(choices, ", ")) end
    		table.insert(parts, key .. "=" .. url.encode(ENCODE[key](value, key)))
    	end
    	return if #parts > 0 then "?" .. table.concat(parts, "&") else ""
    end
    
    -- Fields become the JSON body unchanged, so they must be a JSON object.
    local function body(endpoint: Endpoint, input: any): string?
    	if not endpoint.fields then return nil end
    	if input == nil and endpoint.fields == "optional" then return "{}" end
    	assert(type(input) == "table" and #input == 0, "fields must be an object")
    	local count = 0
    	for key in input do
    		assert(type(key) == "string", "fields must be an object")
    		count += 1
    	end
    	assert(count > 0 or endpoint.fields == "optional", "fields must name at least one field")
    	assert(input.id == nil, "fields must not contain id")
    	for _, name in endpoint.required or EMPTY do assert(input[name] ~= nil, "fields." .. name .. " is required") end
    	return json.encode(input)
    end
    
    local function header(response: HttpResponse, name: string): string?
    	local values = response.headers[name]
    	return if values then values[1] else nil
    end
    
    -- Web servers and firewalls answer with HTML; keep their visible text.
    local function excerpt(raw: string): string
    	local value = string.gsub(raw, "<!%-%-(.-)%-%->", " %1 ")
    	for _, tag in {"script", "style"} do value = string.gsub(value, "<" .. tag .. "[%s>].-</" .. tag .. ">", " ") end
    	value = string.gsub(string.gsub(value, "<[^>]*>", " "), "%s+", " ")
    	return string.sub((string.gsub(value, "^ ", "")), 1, 300)
    end
    
    -- A write that failed late or answered unreadably may still have been applied.
    local SAVED = "; the change may have been saved: read the record before repeating it"
    
    local function envelope(raw: string): any
    	local ok, value = pcall(json.decode, raw)
    	return if ok and type(value) == "table" and type(value.error) == "table" then value.error else nil
    end
    
    local function failure(name: string, response: HttpResponse, raw: string, write: boolean): never
    	local status = response.statusCode
    	local message = "Dolibarr HTTP " .. tostring(status)
    	local err = envelope(raw)
    	if err then
    		-- Restler adds an exception's details as keys "0", "1"...; debug names source files and is dropped.
    		message ..= ": " .. string.sub(tostring(err.message), 1, 600)
    		for index = 0, 4 do
    			local detail = err[tostring(index)]
    			if type(detail) == "string" and detail ~= "" then message ..= "; " .. string.sub(detail, 1, 300) end
    		end
    	elseif string.match(raw, "%S") then
    		message ..= ": " .. excerpt(raw)
    	end
    	if status == 304 then
    		message ..= ". Dolibarr made no change: the record may already be in that state"
    	elseif status == 401 then
    		message ..= ". Check the API key and that its Dolibarr user is active; before Dolibarr 20, a missing permission also answers 401"
    	elseif status == 403 then
    		message ..= ". The Dolibarr user of this API key lacks the permission, or the module behind this request is disabled"
    	elseif status == 501 then
    		message ..= ". This Dolibarr does not offer this endpoint, or blocks it with API_ENDPOINT_RULES"
    	elseif status == 404 and not err then
    		message ..= ". Check the connection's domain and install path: the API must answer at " .. tostring(API)
    	end
    	local location = header(response, "location")
    	if status >= 300 and status < 400 and status ~= 304 and location then
    		message ..= "; redirected to " .. string.sub(location, 1, 200) .. ". Set the connection's domain and install path to the final address."
    	end
    	local retry = header(response, "retry-after")
    	if retry then message ..= "; Retry-After: " .. string.sub(retry, 1, 40) end
    	if write and status >= 500 then message ..= SAVED end
    	-- Dolibarr reports its own failures, such as an SQL error, as JSON 5xx, and an IP
    	-- restriction as 503; those fail again on retry. Other 5xx are retryable only for
    	-- reads, as a write may have been applied, and a 503 only when it asks to wait.
    	local transient = status >= 500 and status ~= 501 and (status ~= 503 or retry ~= nil)
    	return houston.fail({operation = name, layer = "upstream", upstream_status = status,
    		retryable = status == 429 or (transient and not err and not write), message = message})
    end
    
    local function withhold(value: any)
    	if type(value) ~= "table" then return end
    	for key, item in value do
    		if SECRET[key] then value[key] = nil else withhold(item) end
    	end
    end
    
    local function call(endpoint: Endpoint, recordID: any, input: any): any
    	assert(API, "The connection's install path must be empty or one or two folders, such as /dolibarr or /dolibarr/htdocs")
    	local name, method = endpoint.name, endpoint.method or "GET"
    	local path = endpoint.path
    	if string.find(path, "{id}", 1, true) then path = string.gsub(path, "{id}", id(recordID, "id")) end
    	local target = API .. path .. query(endpoint, if endpoint.fields then nil else input)
    	local payload = body(endpoint, input)
    	local headers: HttpHeaders = {Accept = {"application/json"}}
    	if payload then headers["Content-Type"] = {"application/json"} end
    	local response = await(http.request({method = method, url = target, headers = headers, body = payload}))
    	local write = method ~= "GET"
    	if response.statusCode < 200 or response.statusCode >= 300 then
    		local raw = await(response.body:readPrefix(16 * 1024))
    		-- Before Dolibarr 19 (21 for contacts, 22 for third parties), an empty list answered
    		-- 404 "Not Found: No ... found"; a bare "Not Found" is a route this Dolibarr lacks.
    		local err = envelope(raw)
    		if response.statusCode == 404 and endpoint.list and err and err.code == 404
    			and string.match(tostring(err.message), "^Not Found: .") then return json.decode("[]") end
    		failure(name, response, raw, write)
    	end
    	local raw = await(response.body:readAll())
    	local ok, value = pcall(json.decode, raw)
    	if not ok or value == nil then
    		-- With the API module disabled, Dolibarr answers HTTP 200 with a plain-text warning.
    		return houston.fail({operation = name, layer = "upstream", upstream_status = response.statusCode, retryable = false,
    			message = "Dolibarr returned a response that is not JSON; check that the API REST module is enabled and answers at "
    				.. API .. "/status" .. (if write then SAVED else "")})
    	end
    	withhold(value)
    	return value
    end
    
    local exports: {[string]: any} = {}
    local signatures: {[string]: string} = {}
    local function add(endpoint: Endpoint)
    	local names: {string} = {}
    	for _, name in optionNames(endpoint) do
    		table.insert(names, name .. (if table.find(endpoint.required or EMPTY, name) then "" else "?"))
    	end
    	local hasID = string.find(endpoint.path, "{id}", 1, true) ~= nil
    	local args: {string} = {}
    	if hasID then table.insert(args, "id") end
    	if endpoint.fields then table.insert(args, if endpoint.fields == "required" then "fields" else "fields?") end
    	if #names > 0 then table.insert(args, "{" .. table.concat(names, ", ") .. "}" .. (if endpoint.required then "" else "?")) end
    	local returns = endpoint.returns or (if endpoint.list then "[record]" else "record")
    	signatures[endpoint.name] = "(" .. table.concat(args, ", ") .. ") -> " .. returns
    	-- After the optional ID, an endpoint takes either fields or options.
    	exports[endpoint.name] = if hasID then function(recordID: any, input: any): any return call(endpoint, recordID, input) end
    		else function(input: any): any return call(endpoint, nil, input) end
    end
    for _, endpoint in READS do add(endpoint) end
    if houston.allows("data:write") then
    	for _, endpoint in WRITES do add(endpoint) end
    end
    
    exports.help = function(): string
    	local names: {string} = {}
    	for name in signatures do table.insert(names, name) end
    	table.sort(names)
    	local lines = {
    		"Dolibarr REST API for " .. HOST .. ". Results keep Dolibarr's native JSON: records are objects whose IDs and amounts are usually strings (\"id\":\"12\", \"total_ttc\":\"120.00000000\"), dates are Unix timestamps (payment lists use 'YYYY-MM-DD HH:MM:SS'), and lists are arrays, an empty list included. IDs can be passed as numbers or digit strings. Extra fields sit in array_options as options_<code>. Connector calls return completed values: use them directly, without await.",
    		"Lists fetch one page: limit (1-200, default 100) and page (from 0); fetch the next page while a page returns limit records. sortfield is a database column with its alias, such as t.rowid, t.ref, t.datec or t.tms, and sortorder ASC or DESC. properties={'id','ref','total_ttc'} returns only those fields (Dolibarr 19+). sqlfilters uses Dolibarr's syntax on database columns, not JSON names: \"(t.ref:like:'FA26%') and (t.fk_soc:=:12)\", with operators = != < > <= >= like notlike in notin is isnot, quoted strings and no parentheses inside values; for example (t.tms:>:'2026-10-01 00:00:00') finds records changed since a date. thirdparty_ids is an ID or an array of IDs. listThirdparties mode: 1 customers, 2 prospects, 3 neither, 4 suppliers; listProducts mode: 1 products, 2 services. listInvoices and listSupplierInvoices status: draft, unpaid, paid or cancelled; listSupplierOrders status: draft, validated, approved, running, received_start, received_end, cancelled or refused. listOrders sqlfilterlines (Dolibarr 18+) filters by line columns, such as (tl.fk_product:=:9). listPaymentTypes sorts and filters on code, id or libelle.",
    		"Examples: listInvoices({status='unpaid', sortfield='t.datef', sortorder='DESC', limit=20}); getInvoice(42); listOrders({sqlfilters=\"(t.ref_ext:=:'PS-1042')\"}); listThirdparties({sqlfilters=\"(t.email:=:'[email protected]')\"}); listProducts({sqlfilters=\"(t.ref:=:'MUG-01')\", properties={'id','ref','label','price'}}); getProductStock(9); listStockMovements({sqlfilters='(t.fk_product:=:9)', sortorder='DESC'}); listBankAccountLines(1, {sqlfilters=\"(dateo:>=:'2026-10-01')\"}).",
    		"Customer orders, invoices and proposals link to a third party through socid (fk_soc in sqlfilters) and carry their lines. Statuses (status, statut or fk_statut) are numeric strings: an order is 0 draft, 1 validated, 2 shipping, 3 delivered, -1 cancelled; an invoice 0 draft, 1 unpaid, 2 paid, 3 abandoned. ref_ext holds an external reference such as a shop order ID. listBankAccountLines requires sqlfilters on bare column names without t. (dateo, datev, amount, label, num_releve), as Dolibarr returns every matching line at once; getProductStock returns stock_reel and stock_theorique from Dolibarr 21, and before 19 fails with HTTP 404 \"No stock found\" for a product without stock; getBankAccountBalance needs Dolibarr 21+. The API key's Dolibarr user permissions apply: a missing permission or disabled module fails with HTTP 403 (401 before Dolibarr 20), an endpoint this Dolibarr lacks or blocks with HTTP 501, and a missing record with HTTP 404; Dolibarr reports its own errors, such as an invalid sqlfilters column, as HTTP 400 or 503. Errors carry Dolibarr's message.",
    	}
    	if houston.allows("data:write") then
    		table.insert(lines, "Writes send fields as a JSON object of Dolibarr field names (see Dolibarr's API explorer for each object); a create returns the new record's ID, so read it back with the matching get, while updates and actions return the record. Updates change only the given fields. Dates are Unix timestamps. createOrder({socid=12, date=1792540800, ref_ext='PS-1042'}) creates a draft order; add lines with addOrderLine(orderID, {fk_product=9, qty=2, subprice='12.50', tva_tx='20'}) or {desc='Shipping', qty=1, subprice='5', tva_tx='20', product_type=1}, then validateOrder(orderID) gives it its reference (pass {idwarehouse=1} when validation moves stock). createInvoiceFromOrder(orderID) returns a draft invoice copied from the order; validateInvoice(id) numbers it, which cannot be undone, and addInvoicePayment(id, {datepaye=1792540800, paymentid=<listPaymentTypes id>, accountid=<bank account id>, closepaidinvoices='yes'}) records a payment of the whole remaining amount. createStockMovement({product_id=9, warehouse_id=1, qty=-2, label='Shop order PS-1042'}) moves stock (negative qty removes it); before Dolibarr 23, pass movementlabel instead of label, batch as lot, and sellBy and eatBy as dlc and dluo. Validation and closing may run Dolibarr's workflows and notifications; they answer HTTP 304 when the record is already in that state. Only HTTP 429 is retried: after a timeout or 5xx, read the record before repeating a write.")
    	end
    	table.insert(lines, "Reference: " .. DOCS .. " and the API explorer at <your Dolibarr>/api/index.php/explorer.")
    	for _, name in names do table.insert(lines, name .. signatures[name]) end
    	return table.concat(lines, "\n")
    end
    return exports
    
  • houston.json
    {
      "schema_version": 2,
      "name": "Dolibarr",
      "files": [
        "connector.luau"
      ],
      "icon": "icon.svg",
      "access": [
        {
          "name": "data",
          "label": "Access",
          "description": "Houston sends no changes with Read access. Dolibarr has the final say: the API key acts as its Dolibarr user, so to guarantee read-only access use the key of a user who can only read.",
          "levels": [
            {
              "value": "read",
              "label": "Read"
            },
            {
              "value": "write",
              "label": "Write"
            }
          ],
          "default": "read"
        }
      ],
      "config": {
        "host": {
          "description": "The domain your Dolibarr is served from, without https:// or a path.",
          "label": "Dolibarr domain",
          "max_length": 253,
          "order": 2,
          "placeholder": "erp.example.com",
          "required": true,
          "type": "string"
        },
        "install_path": {
          "description": "Leave empty when Dolibarr opens at the root of the domain. Otherwise enter the folder before /index.php, such as /dolibarr or /dolibarr/htdocs.",
          "label": "Install path",
          "max_length": 200,
          "order": 3,
          "placeholder": "/dolibarr",
          "type": "string"
        }
      },
      "auth": {
        "key": {
          "config": {
            "token": {
              "label": "API key",
              "order": 1,
              "required": true,
              "type": "secret",
              "max_length": 128
            }
          },
          "label": "Dolibarr API key",
          "type": "manual"
        }
      },
      "proxy": [
        {
          "action": {
            "headers": {
              "remove": [
                "Authorization",
                "Cookie",
                "DOLAPIENTITY"
              ],
              "set": {
                "DOLAPIKEY": "{{auth.key.token}}"
              }
            }
          },
          "if": "{{ allows access.data \"write\" }}",
          "match": {
            "host": [
              "{{config.host}}"
            ],
            "method": [
              "POST"
            ],
            "path": [
              "/api/index.php/thirdparties",
              "/api/index.php/contacts",
              "/api/index.php/products",
              "/api/index.php/stockmovements",
              "/api/index.php/orders",
              "/api/index.php/orders/{id}/lines",
              "/api/index.php/orders/{id}/validate",
              "/api/index.php/orders/{id}/close",
              "/api/index.php/invoices",
              "/api/index.php/invoices/createfromorder/{id}",
              "/api/index.php/invoices/{id}/lines",
              "/api/index.php/invoices/{id}/validate",
              "/api/index.php/invoices/{id}/payments",
              "/{base}/api/index.php/thirdparties",
              "/{base}/api/index.php/contacts",
              "/{base}/api/index.php/products",
              "/{base}/api/index.php/stockmovements",
              "/{base}/api/index.php/orders",
              "/{base}/api/index.php/orders/{id}/lines",
              "/{base}/api/index.php/orders/{id}/validate",
              "/{base}/api/index.php/orders/{id}/close",
              "/{base}/api/index.php/invoices",
              "/{base}/api/index.php/invoices/createfromorder/{id}",
              "/{base}/api/index.php/invoices/{id}/lines",
              "/{base}/api/index.php/invoices/{id}/validate",
              "/{base}/api/index.php/invoices/{id}/payments",
              "/{base}/{sub}/api/index.php/thirdparties",
              "/{base}/{sub}/api/index.php/contacts",
              "/{base}/{sub}/api/index.php/products",
              "/{base}/{sub}/api/index.php/stockmovements",
              "/{base}/{sub}/api/index.php/orders",
              "/{base}/{sub}/api/index.php/orders/{id}/lines",
              "/{base}/{sub}/api/index.php/orders/{id}/validate",
              "/{base}/{sub}/api/index.php/orders/{id}/close",
              "/{base}/{sub}/api/index.php/invoices",
              "/{base}/{sub}/api/index.php/invoices/createfromorder/{id}",
              "/{base}/{sub}/api/index.php/invoices/{id}/lines",
              "/{base}/{sub}/api/index.php/invoices/{id}/validate",
              "/{base}/{sub}/api/index.php/invoices/{id}/payments"
            ],
            "protocol": "http"
          }
        },
        {
          "action": {
            "headers": {
              "remove": [
                "Authorization",
                "Cookie",
                "DOLAPIENTITY"
              ],
              "set": {
                "DOLAPIKEY": "{{auth.key.token}}"
              }
            }
          },
          "if": "{{ allows access.data \"write\" }}",
          "match": {
            "host": [
              "{{config.host}}"
            ],
            "method": [
              "PUT"
            ],
            "path": [
              "/api/index.php/thirdparties/{id}",
              "/api/index.php/contacts/{id}",
              "/api/index.php/products/{id}",
              "/{base}/api/index.php/thirdparties/{id}",
              "/{base}/api/index.php/contacts/{id}",
              "/{base}/api/index.php/products/{id}",
              "/{base}/{sub}/api/index.php/thirdparties/{id}",
              "/{base}/{sub}/api/index.php/contacts/{id}",
              "/{base}/{sub}/api/index.php/products/{id}"
            ],
            "protocol": "http"
          }
        },
        {
          "action": {
            "headers": {
              "remove": [
                "Authorization",
                "Cookie",
                "DOLAPIENTITY"
              ],
              "set": {
                "DOLAPIKEY": "{{auth.key.token}}"
              }
            }
          },
          "match": {
            "host": [
              "{{config.host}}"
            ],
            "method": [
              "GET"
            ],
            "path": [
              "/api/index.php/status",
              "/api/index.php/thirdparties",
              "/api/index.php/thirdparties/{id}",
              "/api/index.php/contacts",
              "/api/index.php/contacts/{id}",
              "/api/index.php/products",
              "/api/index.php/products/{id}",
              "/api/index.php/products/{id}/stock",
              "/api/index.php/warehouses",
              "/api/index.php/warehouses/{id}",
              "/api/index.php/stockmovements",
              "/api/index.php/categories",
              "/api/index.php/categories/{id}",
              "/api/index.php/orders",
              "/api/index.php/orders/{id}",
              "/api/index.php/invoices",
              "/api/index.php/invoices/{id}",
              "/api/index.php/invoices/{id}/payments",
              "/api/index.php/proposals",
              "/api/index.php/proposals/{id}",
              "/api/index.php/shipments",
              "/api/index.php/shipments/{id}",
              "/api/index.php/supplierorders",
              "/api/index.php/supplierorders/{id}",
              "/api/index.php/supplierinvoices",
              "/api/index.php/supplierinvoices/{id}",
              "/api/index.php/supplierinvoices/{id}/payments",
              "/api/index.php/bankaccounts",
              "/api/index.php/bankaccounts/{id}",
              "/api/index.php/bankaccounts/{id}/lines",
              "/api/index.php/bankaccounts/{id}/balance",
              "/api/index.php/setup/dictionary/payment_types",
              "/{base}/api/index.php/status",
              "/{base}/api/index.php/thirdparties",
              "/{base}/api/index.php/thirdparties/{id}",
              "/{base}/api/index.php/contacts",
              "/{base}/api/index.php/contacts/{id}",
              "/{base}/api/index.php/products",
              "/{base}/api/index.php/products/{id}",
              "/{base}/api/index.php/products/{id}/stock",
              "/{base}/api/index.php/warehouses",
              "/{base}/api/index.php/warehouses/{id}",
              "/{base}/api/index.php/stockmovements",
              "/{base}/api/index.php/categories",
              "/{base}/api/index.php/categories/{id}",
              "/{base}/api/index.php/orders",
              "/{base}/api/index.php/orders/{id}",
              "/{base}/api/index.php/invoices",
              "/{base}/api/index.php/invoices/{id}",
              "/{base}/api/index.php/invoices/{id}/payments",
              "/{base}/api/index.php/proposals",
              "/{base}/api/index.php/proposals/{id}",
              "/{base}/api/index.php/shipments",
              "/{base}/api/index.php/shipments/{id}",
              "/{base}/api/index.php/supplierorders",
              "/{base}/api/index.php/supplierorders/{id}",
              "/{base}/api/index.php/supplierinvoices",
              "/{base}/api/index.php/supplierinvoices/{id}",
              "/{base}/api/index.php/supplierinvoices/{id}/payments",
              "/{base}/api/index.php/bankaccounts",
              "/{base}/api/index.php/bankaccounts/{id}",
              "/{base}/api/index.php/bankaccounts/{id}/lines",
              "/{base}/api/index.php/bankaccounts/{id}/balance",
              "/{base}/api/index.php/setup/dictionary/payment_types",
              "/{base}/{sub}/api/index.php/status",
              "/{base}/{sub}/api/index.php/thirdparties",
              "/{base}/{sub}/api/index.php/thirdparties/{id}",
              "/{base}/{sub}/api/index.php/contacts",
              "/{base}/{sub}/api/index.php/contacts/{id}",
              "/{base}/{sub}/api/index.php/products",
              "/{base}/{sub}/api/index.php/products/{id}",
              "/{base}/{sub}/api/index.php/products/{id}/stock",
              "/{base}/{sub}/api/index.php/warehouses",
              "/{base}/{sub}/api/index.php/warehouses/{id}",
              "/{base}/{sub}/api/index.php/stockmovements",
              "/{base}/{sub}/api/index.php/categories",
              "/{base}/{sub}/api/index.php/categories/{id}",
              "/{base}/{sub}/api/index.php/orders",
              "/{base}/{sub}/api/index.php/orders/{id}",
              "/{base}/{sub}/api/index.php/invoices",
              "/{base}/{sub}/api/index.php/invoices/{id}",
              "/{base}/{sub}/api/index.php/invoices/{id}/payments",
              "/{base}/{sub}/api/index.php/proposals",
              "/{base}/{sub}/api/index.php/proposals/{id}",
              "/{base}/{sub}/api/index.php/shipments",
              "/{base}/{sub}/api/index.php/shipments/{id}",
              "/{base}/{sub}/api/index.php/supplierorders",
              "/{base}/{sub}/api/index.php/supplierorders/{id}",
              "/{base}/{sub}/api/index.php/supplierinvoices",
              "/{base}/{sub}/api/index.php/supplierinvoices/{id}",
              "/{base}/{sub}/api/index.php/supplierinvoices/{id}/payments",
              "/{base}/{sub}/api/index.php/bankaccounts",
              "/{base}/{sub}/api/index.php/bankaccounts/{id}",
              "/{base}/{sub}/api/index.php/bankaccounts/{id}/lines",
              "/{base}/{sub}/api/index.php/bankaccounts/{id}/balance",
              "/{base}/{sub}/api/index.php/setup/dictionary/payment_types"
            ],
            "protocol": "http"
          }
        }
      ]
    }
    
  • icon.svgicon.svg
  • README.md
    ---
    description: Look up customers, products, stock, orders, invoices, payments and bank accounts in your Dolibarr ERP and CRM, and create orders, invoices, payments and stock movements. Read-only access is guaranteed by a read-only Dolibarr user.
    ---
    
    # Dolibarr
    
    Let agents read customers, products, stock, orders, invoices, payments and bank
    accounts. **Write** access also permits record changes, stock movements,
    order/invoice validation and recording payments.
    
    > Guaranteed read-only access requires a non-admin Dolibarr user with read-only permissions.
    > The user's permissions remain the final limit on the API key.
    
    Supports Dolibarr 16+ over HTTPS, at the domain root or within up to two folders.
    
    [Connect Dolibarr](SETUP.md).
    
  • SETUP.md
    # Connect Dolibarr
    
    Requires Dolibarr 16 or later over HTTPS and an administrator to enable the API.
    
    > For **Read** access, use a non-admin user's key with only read permissions.
    > Dolibarr administrators bypass most permission checks.
    
    1. Enable **API / Web services (REST server)** under **Setup → Modules/Applications**.
    2. Create a non-admin, non-external `houston` user under **Users & Groups**.
       Grant read permissions for the modules agents need. Add **Extend access to all
       third parties AND their objects** only if agents should see all third parties;
       otherwise access is limited to the user's assigned ones.
    3. On the user's card, choose **Modify** and generate **Token for API**
       (**Key for API** before version 23). Save and copy it.
    4. In Houston, enter **Dolibarr domain** without `https://` or a path. Put a folder
       such as `/dolibarr` in **Install path**. Paste **API key**, choose **Read** for
       **Access** and save.
    
    [Official REST API guide](https://wiki.dolibarr.org/index.php/Module_Web_Services_API_REST_(developer)).
    
    ## Advanced
    
    ### Changes
    
    Use a separate key and a connection with **Write** access. Grant create/modify
    permissions only for the relevant modules. Stock changes require **Create/modify
    warehouses**; invoice payments require **Create payments for customer invoices**
    (version 24+) or **Create/modify customer invoices** on earlier versions. With
    advanced permissions, also grant order/invoice validation. Validation assigns
    final numbers and may send notifications. Agents cannot delete records.
    
    ### Connection problems
    
    The API must answer at `https://<domain><install path>/api/index.php/status`.
    Use the final HTTPS domain; redirects and install paths deeper than two folders
    are unsupported. Check enabled modules, user permissions and API IP restrictions.
    Before version 20, missing permissions can return 401. Multicompany access uses
    the key owner's entity.
    
  • tests
    • authentication.luau
      return {
      	contract = function(m)
      		m.authentication({
      			{
      				auth = { token = "synthetic-method-secret" },
      				config = { host = "erp.example.com" },
      				endpoint = { "GET", "https://erp.example.com/api/index.php/status" },
      				expected = "synthetic-method-secret",
      				header = "DOLAPIKEY",
      				method = "key",
      				publisher = {},
      			},
      		})
      	end,
      }
      
    • bad_install_path.luau
      return {
      	scenario = {publisher = {}, config = {host = "example.com", install_path = "/srv/www/dolibarr"}, auth_method = "key",
      		auth_config = {token = "Zx81Kq0PnB2vLm4TcR7wYs9dHf3jGa6E"}},
      	configure = function()
      		calls = 0
      		http = {request = function()
      			calls += 1
      			return fixture.operation({statusCode = 200, headers = {}, body = fixture.reader("{}")})
      		end}
      	end,
      	run = function(erp)
      		-- The proxy allows at most two folders; deeper or dot paths fail before any request.
      		local ok, err = pcall(function() erp.getStatus() end)
      		assert(not ok and string.find(tostring(err), "install path must be empty or one or two folders", 1, true), tostring(err))
      		assert(calls == 0, "an invalid install path reached Dolibarr")
      	end,
      }
      
    • endpoints.luau
      return {
      	contract = function(m)
      		local want, got = {}, {}
      		for line in string.gmatch(m.modules["connector.luau"], "[^\n]+") do
      			if not string.find(line, '{name = "', 1, true) then
      				continue
      			end
      			local method = string.match(line, 'method = "([^"]+)"')
      			local path = assert(string.match(line, 'path = "([^"]+)"'), "endpoint without path")
      			local gate = if method then '{{ allows access.data "write" }}' else ""
      			for _, prefix in { "", "/{base}", "/{base}/{sub}" } do
      				table.insert(
      					want,
      					(method or "GET") .. " " .. prefix .. "/api/index.php" .. path .. " " .. gate
      				)
      			end
      		end
      		for _, rule in m.raw.proxy do
      			for _, method in rule.match.method do
      				for _, path in rule.match.path do
      					table.insert(got, method .. " " .. path .. " " .. (rule["if"] or ""))
      				end
      			end
      		end
      		assert(#want >= 140, "endpoint table incomplete")
      		m.sortedEqual(want, got)
      	end,
      }
      
    • errors.luau
      return {
      	scenario = {publisher = {}, access = {data = "write"}, config = {host = "erp.example.com"}, auth_method = "key",
      		auth_config = {token = "Zx81Kq0PnB2vLm4TcR7wYs9dHf3jGa6E"}},
      	configure = function()
      		calls = 0
      		status = 200
      		payload = "{}"
      		responseHeaders = {}
      		http = {request = function(req)
      			calls += 1
      			return fixture.operation({statusCode = status, headers = responseHeaders, body = fixture.reader(payload)})
      		end}
      	end,
      	run = function(erp)
      		local function rejected(fn, expected)
      			local before = calls
      			local ok, err = pcall(fn)
      			assert(not ok and string.find(tostring(err), expected, 1, true), "wrong validation error: " .. tostring(err))
      			assert(calls == before, "invalid input reached Dolibarr")
      		end
      		rejected(function() erp.getInvoice() end, "id must be a positive integer ID")
      		for _, value in {0, -1, 1.5, "0", "07", "1e3", " 1", "../setup/conf", "9007199254740993", 2 ^ 60} do
      			rejected(function() erp.getInvoice(value) end, "id must be a positive integer ID")
      		end
      		rejected(function() erp.updateProduct("x", {price = 1}) end, "id must be a positive integer ID")
      		rejected(function() erp.listInvoices("unpaid") end, "opts must be an object")
      		-- Restler and Dolibarr read a method override, a key and error suppression from any query string.
      		for _, key in {"http_method", "DOLAPIKEY", "api_key", "suppress_response_codes", "pagination_data", "loadlinkedobjects", "withLines"} do
      			rejected(function() erp.listInvoices({[key] = "DELETE"}) end, key .. " is not a supported option")
      			rejected(function() erp.getInvoice(1, {[key] = "DELETE"}) end, key .. " is not a supported option")
      		end
      		rejected(function() erp.getStatus({limit = 1}) end, "limit is not a supported option")
      		rejected(function() erp.getProduct(1, {limit = 1}) end, "limit is not a supported option")
      		rejected(function() erp.listPaymentTypes({properties = {"id"}}) end, "properties is not a supported option")
      		rejected(function() erp.listInvoices({page = -1}) end, "page must be an integer from 0 to 9007199254740991")
      		rejected(function() erp.listInvoices({limit = 0}) end, "limit must be an integer from 1 to 200")
      		rejected(function() erp.listInvoices({limit = 201}) end, "limit must be an integer from 1 to 200")
      		rejected(function() erp.listInvoices({page = -1}) end, "page must be an integer")
      		rejected(function() erp.listInvoices({sortorder = "asc"}) end, "sortorder must be ASC or DESC")
      		for _, value in {"t.rowid;", "t.rowid desc", "a.b.c", "t.", ".rowid", ""} do
      			rejected(function() erp.listInvoices({sortfield = value}) end, "sortfield must be a column")
      		end
      		rejected(function() erp.listInvoices({sqlfilters = " "}) end, "sqlfilters is not valid")
      		rejected(function() erp.listInvoices({sqlfilters = string.rep("x", 4001)}) end, "sqlfilters is not valid")
      		rejected(function() erp.listInvoices({properties = "id,ref"}) end, "properties must be a nonempty array")
      		rejected(function() erp.listInvoices({properties = {"id", "ref&http_method=DELETE"}}) end, "properties is not valid")
      		rejected(function() erp.listInvoices({thirdparty_ids = {12, "x"}}) end, "thirdparty_ids must be a positive integer ID")
      		rejected(function() erp.listInvoices({status = "unpaid&http_method=DELETE"}) end, "status must be one of")
      		rejected(function() erp.listThirdparties({mode = 5}) end, "mode must be one of 1, 2, 3, 4")
      		rejected(function() erp.listThirdparties({mode = 0}) end, "mode must be one of 1, 2, 3, 4")
      		rejected(function() erp.listProducts({mode = 3}) end, "mode must be one of 1, 2")
      		-- Dolibarr ignores an unknown status and returns every record.
      		rejected(function() erp.listInvoices({status = "unpaid,paid"}) end, "status must be one of draft, unpaid, paid, cancelled")
      		rejected(function() erp.listInvoices({status = "validated"}) end, "status must be one of draft, unpaid, paid, cancelled")
      		rejected(function() erp.listSupplierOrders({status = "unpaid"}) end, "status must be one of draft, validated, approved")
      		rejected(function() erp.listProducts({includestockdata = 1}) end, "includestockdata must be a boolean")
      		rejected(function() erp.listBankAccountLines(1) end, "sqlfilters is required")
      		-- Filtering or sorting on a withheld field would reveal it one character at a time.
      		rejected(function() erp.listThirdparties({sqlfilters = "(t.WebServices_Key:like:'a%')"}) end, "sqlfilters cannot use webservices_key")
      		rejected(function() erp.listOrders({sqlfilterlines = "(tl.pass:=:'x')"}) end, "sqlfilterlines cannot use pass")
      		rejected(function() erp.listThirdparties({sortfield = "t.webservices_key"}) end, "sortfield cannot use webservices_key")
      		rejected(function() erp.listThirdparties({sqlfilters = "(t.name:like:'a%') or (webservices_key:like:'a%')"}) end, "sqlfilters cannot use webservices_key")
      		-- Dolibarr 16-17 keep only letters, digits, _ and . of a field, so spacing and punctuation cannot hide one.
      		for _, filter in {"( t.webservices_key :like:'a%')", "(t.`webservices_key`:like:'a%')", "(t.web-services_key:like:'a%')", "(t.webservices_key: like :'a%')"} do
      			rejected(function() erp.listThirdparties({sqlfilters = filter}) end, "sqlfilters cannot use webservices_key")
      		end
      		-- Values may contain those words: Dolibarr reads a field only at the start of a (field:operator:value) term.
      		erp.listProducts({sqlfilters = "(t.label:like:'%Ski pass%') or (t.ref:=:'PASS-2026') or (t.note_private:like:'%api_key%')"})
      		erp.listThirdparties({sqlfilters = "(t.note_private:like:'%passage%') and (t.webservices_url:!=:'')", sortfield = "t.pass_count"})
      
      		rejected(function() erp.createThirdparty("Ann") end, "fields must be an object")
      		rejected(function() erp.createThirdparty({"Ann"}) end, "fields must be an object")
      		rejected(function() erp.createThirdparty({email = "[email protected]"}) end, "fields.name is required")
      		rejected(function() erp.createProduct({ref = "MUG"}) end, "fields.label is required")
      		rejected(function() erp.createOrder({socid = 12}) end, "fields.date is required")
      		rejected(function() erp.addInvoicePayment(42, {datepaye = 1, paymentid = 6, accountid = 1}) end, "fields.closepaidinvoices is required")
      		rejected(function() erp.createInvoice({id = 5, socid = 12}) end, "fields must not contain id")
      		rejected(function() erp.updateProduct(9, {}) end, "fields must name at least one field")
      		rejected(function() erp.validateOrder(7, "now") end, "fields must be an object")
      
      		local function upstream(code, body, headers, expected, absent)
      			status, payload, responseHeaders = code, body, headers
      			local before = calls
      			local ok, err = pcall(function() erp.validateInvoice(42) end)
      			for _, text in expected do
      				assert(not ok and string.find(tostring(err), text, 1, true), "missing " .. text .. " in " .. tostring(err))
      			end
      			for _, text in absent or {} do
      				assert(not string.find(tostring(err), text, 1, true), "unexpected " .. text .. " in " .. tostring(err))
      			end
      			assert(calls == before + 1, "failed write was retried")
      		end
      		local debug = ',"debug":{"source":"api_access.class.php:339 at authenticate stage","stages":{"success":["get"]}}'
      		upstream(401, '{"error":{"code":401,"message":"Unauthorized: Error user not valid (not found or bad password or bad api key)"}' .. debug .. "}", {},
      			{"Dolibarr HTTP 401: Unauthorized: Error user not valid", "Check the API key", '"retryable":false'}, {"api_access.class.php"})
      		upstream(403, '{"error":{"code":403,"message":"Forbidden"}}', {}, {"HTTP 403: Forbidden. The Dolibarr user of this API key lacks the permission, or the module behind this request is disabled"})
      		upstream(304, "", {}, {"HTTP 304. Dolibarr made no change", '"retryable":false'})
      		upstream(404, '{"error":{"code":404,"message":"Not Found: Invoice not found"}}', {}, {"HTTP 404: Not Found: Invoice not found"}, {"install path"})
      		-- RestException details arrive as numbered keys beside the message.
      		upstream(500, json.encode({error = {code = 500, message = "Internal Server Error: Error when validating Invoice: " .. string.rep("x", 5000), ["0"] = "ErrorBadValue", ["1"] = "ErrorRefAlreadyExists"}}), {},
      			{"Error when validating Invoice", "; ErrorBadValue; ErrorRefAlreadyExists", "may have been saved", '"retryable":false'})
      		upstream(501, "API not found (failed to include API file)", {}, {"HTTP 501: API not found", "does not offer this endpoint", '"retryable":false'})
      		upstream(503, "<html><head><style>\nbody { color: red }</style><script>var x = 1</script></head><body><!-- WAF --><h1>Blocked</h1></body></html>",
      			{}, {"HTTP 503: WAF Blocked", "may have been saved"}, {"color: red", "var x"})
      		upstream(429, "Too many requests", {["retry-after"] = {"30"}}, {"HTTP 429: Too many requests", "Retry-After: 30", '"retryable":true'})
      		upstream(301, "", {location = {"https://www.erp.example.com/api/index.php/invoices/42/validate"}},
      			{"HTTP 301", "redirected to https://www.erp.example.com/", "domain and install path"})
      		-- With the API module off, Dolibarr answers HTTP 200 with a plain-text warning.
      		upstream(200, "WarningModuleNotActive", {}, {"not JSON", "https://erp.example.com/api/index.php/status", "may have been saved"})
      		upstream(200, "", {}, {"not JSON"})
      
      		local function read(code, body, expected, absent)
      			status, payload, responseHeaders = code, body, {}
      			local ok, err = pcall(function() erp.listInvoices() end)
      			for _, text in expected do
      				assert(not ok and string.find(tostring(err), text, 1, true), "missing " .. text .. " in " .. tostring(err))
      			end
      			for _, text in absent or {} do
      				assert(not string.find(tostring(err), text, 1, true), "unexpected " .. text .. " in " .. tostring(err))
      			end
      		end
      		-- A read that failed upstream is safe to repeat.
      		read(502, "<html><body>Bad gateway</body></html>", {"HTTP 502: Bad gateway", '"retryable":true'}, {"may have been saved"})
      		-- Only Dolibarr's own 404 is an empty list; a web server's 404 means a wrong address.
      		read(404, "<html><body>Not Found</body></html>", {"HTTP 404: Not Found", "install path", "https://erp.example.com/api/index.php"})
      		-- Restler answers a bare "Not Found" for a route this Dolibarr lacks, which is not an empty list.
      		read(404, '{"error":{"code":404,"message":"Not Found"}}', {"HTTP 404: Not Found", '"retryable":false'})
      		read(403, '{"error":{"code":403,"message":"Forbidden: Access not allowed for login houston"}}', {"Access not allowed for login houston", '"retryable":false'})
      		-- Dolibarr reports SQL errors as JSON 503, and an IP restriction as plain 503: retrying fails again.
      		read(503, '{"error":{"code":503,"message":"Service Unavailable: Error when retrieve invoice list : Unknown column t.nosuch"}}', {"Unknown column t.nosuch", '"retryable":false'})
      		read(503, "API not allowed from your IP", {"HTTP 503: API not allowed from your IP", '"retryable":false'})
      		read(500, '{"error":{"code":500,"message":"Internal Server Error: Error when retrieving invoice list"}}', {'"retryable":false'})
      		status, payload, responseHeaders = 503, "Maintenance", {["retry-after"] = {"5"}}
      		local waitOK, waitErr = pcall(function() erp.listInvoices() end)
      		assert(not waitOK and string.find(tostring(waitErr), '"retryable":true', 1, true), tostring(waitErr))
      	end,
      }
      
    • install_path.luau
      return {
      	scenario = {publisher = {}, config = {host = "example.com", install_path = " /dolibarr/htdocs/api/index.php/ "}, auth_method = "key",
      		auth_config = {token = "Zx81Kq0PnB2vLm4TcR7wYs9dHf3jGa6E"}},
      	configure = function()
      		requests = {}
      		http = {request = function(req)
      			table.insert(requests, req)
      			return fixture.operation({statusCode = 200, headers = {}, body = fixture.reader('{"id":"3"}')})
      		end}
      	end,
      	run = function(erp)
      		-- The address people open, or the API address, with or without index.php, gives the folder.
      		assert(erp.getOrder(3).id == "3")
      		assert(requests[1].url == "https://example.com/dolibarr/htdocs/api/index.php/orders/3", requests[1].url)
      		assert(#requests == 1)
      	end,
      }
      
    • manifest.luau
      return {
      	contract = function(m)
      		local assertDolibarrRoutes = function(r, key, allowed, ...)
      			local routes = { ... }
      			for _, route in routes do
      				local method, url, _ = m.cut(route, " ")
      				local recipe, err = m.recipe(r, method, url, nil)
      				if (err == nil) ~= allowed then
      					m.fail("%s allowed=%s: %s", route, (err == nil), err)
      				end
      				if err ~= nil then
      					continue
      				end
      				m.rejectPreparedOverrides(recipe, r.Context, route)
      				local headers, err = m.prepare(recipe, r.Context, {
      					Dolapikey = { "forged" },
      					Authorization = { "Bearer forged" },
      					Dolapientity = { "2" },
      					Cookie = { "http_method=DELETE" },
      				})
      				if (err ~= nil) or (m.header(headers, "DOLAPIKEY") ~= key) then
      					m.fail("credential injection for %s: %s %s", route, headers, err)
      				end
      				for _, name in { "Authorization", "DOLAPIENTITY", "Cookie" } do
      					if m.header(headers, name) ~= "" then
      						m.fail("%s kept %s", route, name)
      					end
      				end
      			end
      		end
      		-- TestDolibarrHostInstallPathAndAccessBoundaries
      		do
      			local key = "Zx81Kq0PnB2vLm4TcR7wYs9dHf3jGa6E"
      			for _, host in { "", "https://erp.example.com", "example.com/dolibarr", "*.example.com" } do
      				do
      					local _, err = m.resolve(nil, { host = host }, { token = key }, "key")
      					if err == nil then
      						m.fail("accepted Dolibarr domain %s", host)
      					end
      				end
      			end
      			for _, access in { "read", "write" } do
      				local r, err = m.resolve(
      					nil,
      					{ host = "ERP.Example.com", install_path = "/dolibarr" },
      					{ token = key },
      					"key",
      					{ data = access }
      				)
      				assert(not err, tostring(err))
      				if
      					(
      						(r.PublicConfig["host"] ~= "ERP.Example.com")
      						or (r.PublicConfig["install_path"] ~= "/dolibarr")
      					) or (m.count(r.PublicConfig) ~= 2)
      				then
      					m.fail("unexpected Lua config: %s", r.PublicConfig)
      				end
      				for _, api in
      					{
      						"https://erp.example.com/api/index.php",
      						"https://erp.example.com/dolibarr/api/index.php",
      						"https://erp.example.com/dolibarr/htdocs/api/index.php",
      					}
      				do
      					assertDolibarrRoutes(
      						r,
      						key,
      						true,
      						"GET " .. api .. "/status",
      						"GET " .. api .. "/thirdparties?limit=100&page=0",
      						"GET " .. api .. "/thirdparties/12",
      						"GET " .. api .. "/contacts/3",
      						"GET " .. api .. "/products/9/stock",
      						"GET " .. api .. "/warehouses",
      						"GET " .. api .. "/stockmovements",
      						"GET " .. api .. "/categories/2",
      						"GET " .. api .. "/orders/7",
      						"GET " .. api .. "/invoices/42/payments",
      						"GET " .. api .. "/proposals",
      						"GET " .. api .. "/shipments/1",
      						"GET " .. api .. "/supplierorders",
      						"GET " .. api .. "/supplierinvoices/5/payments",
      						"GET " .. api .. "/bankaccounts/1/lines",
      						"GET " .. api .. "/bankaccounts/1/balance",
      						"GET " .. api .. "/setup/dictionary/payment_types"
      					)
      					assertDolibarrRoutes(
      						r,
      						key,
      						(access == "write"),
      						"POST " .. api .. "/thirdparties",
      						"PUT " .. api .. "/thirdparties/12",
      						"POST " .. api .. "/contacts",
      						"PUT " .. api .. "/contacts/3",
      						"POST " .. api .. "/products",
      						"PUT " .. api .. "/products/9",
      						"POST " .. api .. "/stockmovements",
      						"POST " .. api .. "/orders",
      						"POST " .. api .. "/orders/7/lines",
      						"POST " .. api .. "/orders/7/validate",
      						"POST " .. api .. "/orders/7/close",
      						"POST " .. api .. "/invoices",
      						"POST " .. api .. "/invoices/createfromorder/7",
      						"POST " .. api .. "/invoices/42/lines",
      						"POST " .. api .. "/invoices/42/validate",
      						"POST " .. api .. "/invoices/42/payments"
      					)
      					assertDolibarrRoutes(
      						r,
      						key,
      						false,
      						"GET " .. api .. "/login?login=admin&password=x",
      						"POST " .. api .. "/login",
      						"GET " .. api .. "/users/info",
      						"GET " .. api .. "/users/1",
      						"GET " .. api .. "/users/1/setGroup/1",
      						"GET " .. api .. "/setup/conf/MAIN_MAIL_SMTPS_PW",
      						"GET " .. api .. "/setup/company",
      						"GET " .. api .. "/documents/download?modulepart=admin_temp",
      						"GET " .. api .. "/explorer/swagger.json",
      						"GET " .. api .. "/thirdparties/1/generateBankAccountDocument/1/sepamandate",
      						"GET " .. api .. "/accountancy/exportdata",
      						"GET " .. api .. "/thirdparties/1/bankaccounts",
      						"GET " .. api .. "/mailings/clone/1",
      						"DELETE " .. api .. "/invoices/42",
      						"DELETE " .. api .. "/thirdparties/12",
      						"PUT " .. api .. "/thirdparties/12/merge/13",
      						"POST " .. api .. "/contacts/3/createUser",
      						"PUT " .. api .. "/invoices/42",
      						"POST " .. api .. "/invoices/42/settopaid",
      						"POST " .. api .. "/thirdparties/12",
      						"PUT " .. api .. "/orders/7",
      						"HEAD " .. api .. "/invoices",
      						"PATCH " .. api .. "/products/9",
      						"GET " .. api .. "/invoices/%2e%2e/users/1"
      					)
      				end
      				assertDolibarrRoutes(
      					r,
      					key,
      					true,
      					"GET https://erp.example.com/index.php/api/index.php/status"
      				)
      				assertDolibarrRoutes(
      					r,
      					key,
      					false,
      					"GET https://erp.example.com/a/b/c/api/index.php/status",
      					"GET https://erp.example.com/api/status",
      					"GET https://erp.example.com/index.php",
      					"GET https://erp.example.com/api/index.php/",
      					"GET https://www.erp.example.com/api/index.php/status",
      					"GET https://erp.example.com.attacker.test/api/index.php/status",
      					"GET https://erp.example.com:8443/api/index.php/status",
      					"GET http://erp.example.com/api/index.php/status"
      				)
      			end
      		end
      	end,
      }
      
    • php_install_path.luau
      return {
      	scenario = {publisher = {}, config = {host = "example.com", install_path = "/tools.Phtml"}, auth_method = "key",
      		auth_config = {token = "Zx81Kq0PnB2vLm4TcR7wYs9dHf3jGa6E"}},
      	configure = function()
      		calls = 0
      		http = {request = function()
      			calls += 1
      			return fixture.operation({statusCode = 200, headers = {}, body = fixture.reader("{}")})
      		end}
      	end,
      	run = function(erp)
      		-- A .php, .phtml or similar folder would send the key to another script through its path info.
      		local ok, err = pcall(function() erp.getStatus() end)
      		assert(not ok and string.find(tostring(err), "install path must be empty or one or two folders", 1, true), tostring(err))
      		assert(calls == 0, "a .php install path reached Dolibarr")
      	end,
      }
      
    • read_only.luau
      return {
      	scenario = {publisher = {}, config = {host = "ERP.Example.com"}, auth_method = "key",
      		auth_config = {token = "Zx81Kq0PnB2vLm4TcR7wYs9dHf3jGa6E"}},
      	configure = function()
      		requests = {}
      		status = 200
      		payload = "{}"
      		http = {request = function(req)
      			table.insert(requests, req)
      			return fixture.operation({statusCode = status, headers = {}, body = fixture.reader(payload)})
      		end}
      	end,
      	run = function(erp)
      		local API = "https://erp.example.com/api/index.php"
      		local function last() return requests[#requests] end
      
      		local names = {}
      		for name in erp do if name ~= "help" then table.insert(names, name) end end
      		table.sort(names)
      		assert(table.concat(names, ",") == "getBankAccount,getBankAccountBalance,getCategory,getContact,getInvoice,getOrder,getProduct,getProductStock,getProposal,getShipment,getStatus,getSupplierInvoice,getSupplierOrder,getThirdparty,getWarehouse,"
      			.. "listBankAccountLines,listBankAccounts,listCategories,listContacts,listInvoicePayments,listInvoices,listOrders,listPaymentTypes,listProducts,listProposals,listShipments,listStockMovements,listSupplierInvoicePayments,listSupplierInvoices,listSupplierOrders,listThirdparties,listWarehouses",
      			"wrong read-only surface: " .. table.concat(names, ","))
      		assert(#requests == 0, "initialization reached Dolibarr")
      
      		payload = '[{"id":"42","ref":"FA2610-0042","socid":"12","total_ttc":"120.00000000","lines":[{"id":"7","qty":"2"}],"user":{"login":"ann","api_key":"dolcrypt:AES-256-CTR:x","pass_indatabase_crypted":"$2y$10$x"}}]'
      		local page = erp.listInvoices()
      		assert(last().method == "GET" and last().body == nil)
      		assert(last().url == API .. "/invoices?limit=100&page=0", last().url)
      		assert(last().headers.Accept[1] == "application/json" and last().headers["Content-Type"] == nil)
      		assert(last().headers.DOLAPIKEY == nil and last().headers.Authorization == nil, "connector set credentials")
      		assert(page[1].ref == "FA2610-0042" and page[1].lines[1].qty == "2" and page[1].user.login == "ann")
      		assert(page[1].user.api_key == nil and page[1].user.pass_indatabase_crypted == nil, "a credential was returned")
      
      		local opts = {status = "unpaid", sortfield = "t.datef", sortorder = "DESC", limit = 20, page = 2, thirdparty_ids = {12, "13"},
      			properties = {"id", "ref"}, sqlfilters = "(t.ref:like:'FA26%') and (t.fk_soc:=:12)"}
      		erp.listInvoices(opts)
      		assert(last().url == API .. "/invoices?limit=20&page=2&properties=id%2Cref&sortfield=t.datef&sortorder=DESC&sqlfilters=%28t.ref%3Alike%3A%27FA26%25%27%29%20and%20%28t.fk_soc%3A%3D%3A12%29&status=unpaid&thirdparty_ids=12%2C13", last().url)
      		assert(opts.thirdparty_ids[2] == "13" and opts.limit == 20, "caller options were modified")
      		erp.listThirdparties({mode = 4, category = 3, sortfield = "nom"})
      		assert(last().url == API .. "/thirdparties?category=3&limit=100&mode=4&page=0&sortfield=nom", last().url)
      		erp.listProducts({includestockdata = true, limit = 200})
      		assert(last().url == API .. "/products?includestockdata=1&limit=200&page=0", last().url)
      		erp.listOrders({sqlfilterlines = "(tl.fk_product:=:9)"})
      		assert(last().url == API .. "/orders?limit=100&page=0&sqlfilterlines=%28tl.fk_product%3A%3D%3A9%29", last().url)
      		erp.listSupplierOrders({status = "received_end", thirdparty_ids = 4})
      		assert(last().url == API .. "/supplierorders?limit=100&page=0&status=received_end&thirdparty_ids=4", last().url)
      		erp.listCategories({type = "product"})
      		assert(last().url == API .. "/categories?limit=100&page=0&type=product", last().url)
      		erp.listPaymentTypes({sortfield = "code"})
      		assert(last().url == API .. "/setup/dictionary/payment_types?limit=100&page=0&sortfield=code", last().url)
      
      		payload = "[]"
      		local empty = erp.listStockMovements({sqlfilters = "(t.fk_product:=:9)"})
      		assert(last().url == API .. "/stockmovements?limit=100&page=0&sqlfilters=%28t.fk_product%3A%3D%3A9%29", last().url)
      		assert(json.encode(empty) == "[]", "an empty list is not an array")
      		assert(json.encode(erp.listInvoicePayments("42")) == "[]")
      		assert(last().url == API .. "/invoices/42/payments", last().url)
      
      		-- Before Dolibarr 19 (22 for third parties), an empty list answers 404.
      		status, payload = 404, '{"error":{"code":404,"message":"Not Found: Thirdparties not found"},"debug":{"source":"api_thirdparties.class.php:263 at call stage"}}'
      		assert(json.encode(erp.listThirdparties({sqlfilters = "(t.nom:like:'zz%')"})) == "[]", "an old empty list failed")
      		status = 200
      
      		payload = '{"id":"12","name":"Ann SARL","client":"1","webservices_url":"https://partner.example.com/ws","webservices_key":"partner-secret","array_options":{"options_shop":"PS"}}'
      		local thirdparty = erp.getThirdparty(12)
      		assert(last().url == API .. "/thirdparties/12", last().url)
      		assert(thirdparty.name == "Ann SARL" and thirdparty.array_options.options_shop == "PS" and thirdparty.webservices_url == "https://partner.example.com/ws")
      		-- A third party's web service key is a credential for that partner's system.
      		assert(thirdparty.webservices_key == nil, "webservices_key was returned")
      		erp.getInvoice("42")
      		assert(last().url == API .. "/invoices/42")
      		erp.getProduct(9, {includestockdata = false})
      		assert(last().url == API .. "/products/9?includestockdata=0", last().url)
      		payload = '{"stock_reel":"5","stock_warehouses":{"1":{"real":"5"}}}'
      		assert(erp.getProductStock(9, {selected_warehouse_id = 1}).stock_warehouses["1"].real == "5")
      		assert(last().url == API .. "/products/9/stock?selected_warehouse_id=1", last().url)
      		erp.listBankAccountLines(1, {sqlfilters = "(dateo:>=:'2026-10-01')"})
      		assert(last().url == API .. "/bankaccounts/1/lines?sqlfilters=%28dateo%3A%3E%3D%3A%272026-10-01%27%29", last().url)
      		payload = "1250.5"
      		assert(erp.getBankAccountBalance(1) == 1250.5)
      		assert(last().url == API .. "/bankaccounts/1/balance")
      		payload = '{"success":{"code":200,"dolibarr_version":"24.0.2","access_locked":"0"}}'
      		assert(erp.getStatus().success.dolibarr_version == "24.0.2")
      		assert(last().url == API .. "/status")
      		for _, req in requests do
      			assert(req.method == "GET" and req.body == nil, "a read sent " .. req.method)
      			assert(req.headers.DOLAPIKEY == nil and req.headers.Authorization == nil and req.headers.Accept[1] == "application/json", "wrong headers on " .. req.url)
      		end
      		assert(#requests == 18, "wrong request count: " .. #requests)
      	end,
      }
      
    • writes.luau
      return {
      	scenario = {publisher = {}, access = {data = "write"}, config = {host = "erp.example.com", install_path = "/dolibarr"}, auth_method = "key",
      		auth_config = {token = "Zx81Kq0PnB2vLm4TcR7wYs9dHf3jGa6E"}},
      	configure = function()
      		requests = {}
      		payload = "{}"
      		http = {request = function(req)
      			table.insert(requests, req)
      			return fixture.operation({statusCode = 200, headers = {}, body = fixture.reader(payload)})
      		end}
      	end,
      	run = function(erp)
      		local API = "https://erp.example.com/dolibarr/api/index.php"
      		local function last() return requests[#requests] end
      		local function same(a, b): boolean
      			if type(a) ~= "table" or type(b) ~= "table" then return a == b end
      			for key, value in a do if not same(value, b[key]) then return false end end
      			for key in b do if a[key] == nil then return false end end
      			return true
      		end
      		local function sent(method, path, expected)
      			local req = last()
      			assert(req.method == method and req.url == API .. path, req.method .. " " .. req.url)
      			assert(req.headers.DOLAPIKEY == nil and req.headers.Authorization == nil, "connector set credentials")
      			assert(req.headers.Accept[1] == "application/json")
      			if expected == nil then
      				assert(req.body == nil and req.headers["Content-Type"] == nil, "unexpected body")
      				return
      			end
      			assert(req.headers["Content-Type"][1] == "application/json")
      			assert(same(json.decode(req.body), expected), req.body)
      		end
      
      		-- The reads are read_only.luau's exact 32; everything else must be these writes.
      		local names, reads = {}, 0
      		for name in erp do
      			if string.match(name, "^get%u") or string.match(name, "^list%u") then reads += 1
      			elseif name ~= "help" then table.insert(names, name) end
      		end
      		assert(reads == 32, "wrong read count: " .. reads)
      		table.sort(names)
      		assert(table.concat(names, ",") == "addInvoiceLine,addInvoicePayment,addOrderLine,closeOrder,createContact,createInvoice,createInvoiceFromOrder,createOrder,createProduct,createStockMovement,createThirdparty,updateContact,updateProduct,updateThirdparty,validateInvoice,validateOrder",
      			"wrong writes: " .. table.concat(names, ","))
      
      		payload = "12"
      		local thirdparty = {name = "Ann SARL", client = 1, email = "[email protected]", country_code = "FR", array_options = {options_shop = "PS"}}
      		assert(erp.createThirdparty(thirdparty) == 12)
      		sent("POST", "/thirdparties", thirdparty)
      		payload = '{"id":"12","email":"[email protected]"}'
      		assert(erp.updateThirdparty("12", {email = "[email protected]"}).email == "[email protected]")
      		sent("PUT", "/thirdparties/12", {email = "[email protected]"})
      		payload = "30"
      		assert(erp.createContact({lastname = "Martin", socid = 12}) == 30)
      		sent("POST", "/contacts", {lastname = "Martin", socid = 12})
      		erp.updateContact(30, {phone_pro = "+33 1 23 45 67 89"})
      		sent("PUT", "/contacts/30", {phone_pro = "+33 1 23 45 67 89"})
      		erp.createProduct({ref = "MUG-01", label = "Mug", price = "12.50", tva_tx = "20"})
      		sent("POST", "/products", {ref = "MUG-01", label = "Mug", price = "12.50", tva_tx = "20"})
      		erp.updateProduct(9, {price = "13.00"})
      		sent("PUT", "/products/9", {price = "13.00"})
      		erp.createStockMovement({product_id = 9, warehouse_id = 1, qty = -2, label = "Shop order PS-1042"})
      		sent("POST", "/stockmovements", {product_id = 9, warehouse_id = 1, qty = -2, label = "Shop order PS-1042"})
      
      		payload = "7"
      		assert(erp.createOrder({socid = 12, date = 1792540800, ref_ext = "PS-1042"}) == 7)
      		sent("POST", "/orders", {socid = 12, date = 1792540800, ref_ext = "PS-1042"})
      		payload = "70"
      		assert(erp.addOrderLine(7, {fk_product = 9, qty = 2, subprice = "12.50", tva_tx = "20"}) == 70)
      		sent("POST", "/orders/7/lines", {fk_product = 9, qty = 2, subprice = "12.50", tva_tx = "20"})
      		payload = '{"id":"7","ref":"CO2610-0007","statut":"1"}'
      		assert(erp.validateOrder(7).ref == "CO2610-0007")
      		sent("POST", "/orders/7/validate", {})
      		erp.validateOrder(7, {idwarehouse = 1})
      		sent("POST", "/orders/7/validate", {idwarehouse = 1})
      		erp.closeOrder("7")
      		sent("POST", "/orders/7/close", {})
      
      		payload = '{"id":"42","ref":"(PROV42)","fk_statut":"0"}'
      		assert(erp.createInvoiceFromOrder(7).ref == "(PROV42)")
      		sent("POST", "/invoices/createfromorder/7", nil)
      		payload = "43"
      		assert(erp.createInvoice({socid = 12, type = 0}) == 43)
      		sent("POST", "/invoices", {socid = 12, type = 0})
      		erp.addInvoiceLine(43, {desc = "Shipping", qty = 1, subprice = "5", tva_tx = "20", product_type = 1})
      		sent("POST", "/invoices/43/lines", {desc = "Shipping", qty = 1, subprice = "5", tva_tx = "20", product_type = 1})
      		payload = '{"id":"42","ref":"FA2610-0042"}'
      		erp.validateInvoice(42)
      		sent("POST", "/invoices/42/validate", {})
      		payload = "88"
      		local payment = {datepaye = 1792540800, paymentid = 6, accountid = 1, closepaidinvoices = "yes", num_payment = "PS-1042"}
      		assert(erp.addInvoicePayment(42, payment) == 88)
      		sent("POST", "/invoices/42/payments", payment)
      
      		payload = "[]"
      		erp.listOrders({sqlfilters = "(t.ref_ext:=:'PS-1042')"})
      		assert(last().method == "GET" and last().url == API .. "/orders?limit=100&page=0&sqlfilters=%28t.ref_ext%3A%3D%3A%27PS-1042%27%29", last().url)
      		assert(#requests == 18, "wrong request count: " .. #requests)
      	end,
      }