80 'thirdparties' => array(
'thirdparty',
'billing',
'commercial'),
81 'categories' => array(
'thirdparty',
'stock'),
82 'invoices' => array(
'billing',
'thirdparty'),
83 'supplier_invoices' => array(
'billing',
'thirdparty'),
84 'supplier_orders' => array(
'commercial',
'thirdparty'),
85 'supplier_proposals' => array(
'commercial',
'thirdparty'),
86 'proposals' => array(
'commercial',
'thirdparty'),
87 'orders' => array(
'commercial',
'thirdparty'),
88 'products' => array(
'stock',
'commercial'),
89 'stockmovements' => array(
'stock'),
90 'warehouses' => array(
'stock'),
91 'projects' => array(
'project'),
92 'tasks' => array(
'project'),
93 'agendaevents' => array(
'thirdparty',
'project'),
94 'interventions' => array(
'project',
'commercial'),
95 'contracts' => array(
'commercial',
'billing'),
96 'members' => array(
'thirdparty',
'billing'),
97 'subscriptions' => array(
'thirdparty',
'billing'),
98 'expensereports' => array(
'billing'),
99 'tickets' => array(
'thirdparty',
'project'),
100 'shipments' => array(
'stock',
'commercial',
'thirdparty'),
101 'receptions' => array(
'stock',
'thirdparty'),
102 'contacts' => array(
'thirdparty',
'commercial'),
103 'bankaccounts' => array(
'billing',
'reporting'),
104 'variouspayments' => array(
'billing',
'reporting'),
105 'socialcontributions' => array(
'billing',
'reporting'),
106 'vatpayments' => array(
'billing',
'reporting'),
107 'donations' => array(
'billing',
'thirdparty'),
108 'holidays' => array(
'project',
'reporting'),
109 'boms' => array(
'stock'),
110 'mos' => array(
'stock'),
111 'productlots' => array(
'stock'),
112 'workstations' => array(
'stock'),
113 'knowledgemanagement' => array(
'thirdparty',
'project'),
114 'memberstypes' => array(
'thirdparty',
'billing'),
115 'partnerships' => array(
'thirdparty',
'commercial'),
116 'multicurrencies' => array(
'billing',
'reporting'),
117 'websites' => array(
'commercial'),
118 'users' => array(
'thirdparty',
'project')
127 const BRIDGE_MAX_LIMIT = 100;
134 private $defs =
null;
141 private $routes = [];
149 private $endpoints = [];
172 private $enrichments = [];
180 private $unresolvedProducts = [];
188 private $writeTarget =
null;
197 private $writeProblems = [];
204 private $writeRefusedFields = [];
211 private $writeLine = array(
'line' =>
null,
'position' => 0,
'changes' => array());
221 private $commonParamDocs = [
222 'sortfield' =>
"Field to sort on, prefixed with 't.' (e.g. 't.rowid', 't.ref', 't.datec'). Use the SQL column names: creation date is 't.datec' (NEVER 'date_creation') and last modification 't.tms' (never 'date_modification').",
223 'sortorder' =>
"Sort direction: 'ASC' or 'DESC'.",
224 'limit' =>
"Maximum number of records to return.",
225 'page' =>
"Zero-based page index for pagination.",
226 'sqlfilters' =>
"Dolibarr Universal Search Filter (see 'sqlfilters format' in instructions): (t.field:operator:'value') combined with AND/OR and parentheses. E.g. \"(t.ref:like:'AB%') AND (t.datefield:>=:'2026-01-01')\"",
227 'properties' =>
"Comma-separated list of properties to include in the response, to reduce its size (e.g. 'id,ref,label').",
228 'id' =>
"Integer technical ID of the record."
242 if ($conf !==
null) {
252 $descriptioncreate =
"Create a third party (customer, prospect or supplier). The user must confirms before anything is written.";
254 $descriptionlist =
"List third parties (prospects, customers, suppliers,...).";
255 $descriptionlist .=
"Use parameter 'mode' to restrict to a nature of third party (0=all, 1=only customers, 2=only prospects, 3=neither customer nor prospect, 4=suppliers).\n";
256 $descriptionlist .=
"To find one company by name use sqlfilters on t.nom or t.name_alias (e.g. \"((t.nom:like:'%acme%') OR (t.alias_name:like:'%acme%'))\").\n";
257 $descriptionlist .=
"Prefer a small 'limit' and 'properties' (e.g. 'id,name,code_client,code_fournisseur,email,town,client,fournisseur,status') to keep answers short.\n";
258 $descriptionlist .=
"List of useful sqlfilters or output fields with type:\n";
259 $descriptionlist .=
"- t.nom : string (thirdparty name)\n";
260 $descriptionlist .=
"- t.name_alias : string (thirdparty alternative name)\n";
261 $descriptionlist .=
"- t.email : string (thirdparty email)\n";
262 $descriptionlist .=
"- t.town : string (thirdparty email)\n";
263 $descriptionlist .=
"- t.zip : string (thirdparty email)\n";
264 $descriptionlist .=
"- t.fk_pays : integer (thirdparty country ID)\n";
265 $descriptionlist .=
"- t.status : integer enum (status ID) among 1=open, 0=closed.";
266 $descriptionlist .=
"\n";
268 $descriptionfetch =
"Fetch the full record of a given thirdparty with main properties (name, name_alias, email, address, status, contact channels, customer/supplier codes, VAT number, default payment terms/modes, outstanding limit).";
269 $descriptionfetch .=
"Fetch is done from ID.\n";
270 $descriptionfetch .=
"In the result 'client' is 1=customer, 2=prospect, 3=both; 'fournisseur' is 1 when supplier.";
272 $this->enrichments[
'thirdparties'] = [
273 'label' =>
'third parties (customers, prospects, suppliers)',
276 'suffix' =>
'create',
277 'description' => $descriptioncreate,
279 'preview' =>
'AIPreviewCreateThirdparty',
280 'required' => [
'name'],
281 'object' =>
'Societe',
283 'right' => [
'societe',
'creer']
286 "name" =>
"Company or person name.",
287 "client" =>
"1 customer, 2 prospect, 3 both, 0 none.",
288 "fournisseur" =>
"1 when the third party is a supplier."
292 'default_properties' =>
'id,name,name_alias,code_client,code_fournisseur,email,town,client,fournisseur,status',
293 'description' => $descriptionlist,
295 'mode' =>
"Nature filter: 0=all (default), 1=customers/prospects, 2=prospects only, 3=neither customer nor prospect, 4=suppliers.",
296 'category' =>
"Rowid of a third-party category (tag) to restrict the list to.",
297 'pagination_data' =>
"Set to true to get {data, pagination:{total,page,page_count,limit}} instead of a bare list; use it to know the total count."
301 'description' => $descriptionfetch
304 'suffix' =>
'get_by_email',
305 'description' =>
"Find one third party by its exact company email address (not contact emails).",
306 'params' => [
'email' =>
"Exact email address of the company."]
308 'getOutStandingInvoices' => [
309 'suffix' =>
'outstanding_invoices',
310 'description' =>
"Total amount still due on validated, unpaid invoices of one third party. Returns {opened: amount} in the company currency.",
311 'params' => [
'mode' =>
"'customer' (default) for customer invoices, 'supplier' for supplier invoices."]
313 'getOutStandingOrder' => [
314 'suffix' =>
'outstanding_orders',
315 'description' =>
"Total amount of open (not yet invoiced) orders of one third party. Returns {opened: amount}.",
316 'params' => [
'mode' =>
"'customer' (default) for sales orders, 'supplier' for purchase orders."]
318 'getOutStandingProposals' => [
319 'suffix' =>
'outstanding_proposals',
320 'description' =>
"Total amount of open commercial proposals of one third party. Returns {opened: amount}.",
321 'params' => [
'mode' =>
"'customer' (default) or 'supplier'."]
326 $this->enrichments[
'categories'] = [
327 'label' =>
'categories / tags',
330 'suffix' =>
'create',
331 'description' =>
"Create a category (tag). The user confirms before anything is written.",
333 'preview' =>
'AIPreviewCreateCategory',
334 'required' => [
'label',
'type'],
335 'args' => [
'type',
'label'],
336 'right' => [
'categorie',
'creer']
339 "label" =>
"Category label.",
"type" =>
"What it classifies: product, customer, supplier, member, contact, project."
343 'description' =>
"Categories form a tree per type (fk_parent = parent rowid, 0 for root). Always pass 'type' to restrict to one kind of object. Search by name with sqlfilters on t.label.",
345 'type' =>
"Kind of object the category applies to: 'product', 'customer', 'supplier', 'contact', 'member', 'project', 'user', 'bank_account', 'warehouse', 'actioncomm', 'website_page', 'ticket', 'knowledgemanagement'."
349 'params' => [
'include_childs' =>
"Set to true to also return the sub-categories (children). The parameter name 'include_childs' is fixed by the REST API."]
352 'suffix' =>
'objects_list',
353 'description' =>
"Objects tagged with one category (e.g. all products in category 12, all customers tagged 'VIP').",
355 'id' =>
"Rowid of the category.",
356 'type' =>
"Object type to list: 'product', 'customer', 'supplier', 'contact', 'member', 'project', 'user', 'warehouse', 'actioncomm', 'ticket'.",
357 'onlyids' =>
"1 to return only rowids (faster, use it for counting), 0 (default) for full objects."
363 $this->enrichments[
'supplier_invoices'] = [
364 'label' =>
'supplier invoices (vendor bills)',
367 'description' =>
"List supplier invoices (vendor bills). Filter with sqlfilters, for example to restrict to one supplier.",
369 'sqlfilters' =>
"Universal filter, e.g. (t.fk_soc:=:2)",
370 'limit' =>
"Rows to return."
374 'description' =>
"Get one supplier invoice by rowid, with its lines."
377 'postLine' => $this->
addLineMethod(
'supplier invoice',
'api_supplier_invoices_list',
'FactureFournisseur', [
'fournisseur',
'facture',
'creer'],
true, [
'desc' =>
'description',
'subprice' =>
'pu_ht']),
379 'suffix' =>
'create',
380 'description' =>
"Create a DRAFT supplier invoice (vendor bill). Nothing is validated or paid: the draft is created and the user finishes it in Dolibarr. Give socid, or simply the supplier name, plus ref_supplier (the vendor's own invoice number) and the lines; a line may name its product with product_ref and the catalogue price is used. Do not call a search tool first. The user confirms before anything is written.",
382 'preview' =>
'AIPreviewCreateSupplierInvoice',
383 'required' => [
'socid',
'ref_supplier'],
384 'object' =>
'FactureFournisseur',
385 'thirdparty' =>
'socid',
387 'right' => [
'fournisseur',
'facture',
'creer'],
389 'defaults' => [
'date' =>
'now']
392 'socid' =>
"Rowid of the supplier, or its name: a name is resolved here, so no separate lookup call is needed.",
393 'ref_supplier' =>
"The vendor's own invoice number, as printed on the bill.",
394 'lines' =>
"Array of lines: desc, qty, subprice (unit price excl. tax), tva_tx (VAT rate). A line may instead give product_ref, and the catalogue product and price are used."
400 $this->enrichments[
'supplier_orders'] = [
401 'label' =>
'supplier order (purchase order)',
404 'suffix' =>
'create',
405 'description' =>
"Create a DRAFT supplier order (purchase order). Nothing is validated or sent: the draft is created and the user finishes it in Dolibarr, or asks for the next step explicitly. The third party is mandatory: give socid, or simply the third party name as the user said it (it is resolved here, do not call a search tool first); ask the user only when no third party is named at all. Give the lines; a line may name its product with product_ref and the catalogue price is used. The user confirms before anything is written.",
407 'preview' =>
'AIPreviewCreateSupplierOrder',
408 'required' => [
'socid'],
409 'object' =>
'CommandeFournisseur',
410 'thirdparty' =>
'socid',
412 'right' => [
'fournisseur',
'commande',
'creer'],
414 'defaults' => [
'date' =>
'now']
417 'socid' =>
"Rowid of the third party, or its name: a name is resolved here, so no separate lookup call is needed.",
418 'lines' =>
"Array of lines: desc, qty, subprice (unit price excl. tax), tva_tx (VAT rate). A line may instead give product_ref, and the catalogue product and price are used."
422 'description' =>
"List supplier order (purchase order). Filter with sqlfilters.",
423 'params' => [
'sqlfilters' =>
"Universal filter, e.g. (t.fk_soc:=:2)",
'limit' =>
"Rows to return."]
425 'get' => [
'description' =>
"Get one record by rowid, with its lines."],
426 'postLine' => $this->
addLineMethod(
'supplier order',
'api_supplier_orders_list',
'CommandeFournisseur', [
'fournisseur',
'commande',
'creer'],
true),
428 'suffix' =>
'update',
429 'description' =>
'Update selected supplier order header fields after confirmation. Identify the order by id or exact ref. Omitted fields are preserved. Status, totals, supplier and lines cannot be changed.',
431 'parent' =>
'id',
'ref' =>
'ref',
'object' =>
'CommandeFournisseur',
432 'right' => [
'fournisseur',
'commande',
'creer'],
'read_right' => [
'fournisseur',
'commande',
'lire'],
433 'access' => [
'fournisseur',
'commande_fournisseur',
'commande'],
434 'preview' =>
'AIPreviewUpdateRecord',
436 'ref_supplier' => [
'type' =>
'string'],
'note_private' => [
'type' =>
'string'],
'note_public' => [
'type' =>
'string'],
437 'delivery_date' => [
'type' => [
'integer',
'null'],
'minimum' => 0,
'description' =>
'Unix timestamp, or null to clear.'],
438 'fk_project' => [
'type' => [
'integer',
'null'],
'minimum' => 1,
'description' =>
'Rowid of the project, or null to unlink it.'],
439 'array_options' => [
'type' =>
'object',
'description' =>
'Extra fields by their options_ code, e.g. {"options_mycode": "value"}.']
441 'preview_labels' => [
'ref_supplier' =>
'RefSupplier',
'note_private' =>
'NotePrivate',
'note_public' =>
'NotePublic',
'delivery_date' =>
'DeliveryDate',
'fk_project' =>
'Project'],
442 'preview_dates' => [
'delivery_date'],
444 'preview_objects' => [
'fk_project' =>
'Project'],
447 'extrafields' =>
'commande_fournisseur',
448 'references' => [
'fk_project' => [
'projet',
'projet',
'']]
454 $this->enrichments[
'supplier_proposals'] = [
455 'label' =>
'supplier proposal (price request)',
458 'suffix' =>
'create',
459 'description' =>
"Create a DRAFT supplier proposal (price request). Nothing is validated or sent: the draft is created and the user finishes it in Dolibarr, or asks for the next step explicitly. Give socid, or simply the third party name, and the lines; a line may name its product with product_ref and the catalogue price is used. Do not call a search tool first. The user confirms before anything is written.",
461 'preview' =>
'AIPreviewCreateSupplierProposal',
462 'required' => [
'socid'],
463 'object' =>
'SupplierProposal',
464 'thirdparty' =>
'socid',
466 'right' => [
'supplier_proposal',
'creer'],
468 'defaults' => [
'date' =>
'now']
471 'socid' =>
"Rowid of the third party, or its name: a name is resolved here, so no separate lookup call is needed.",
472 'lines' =>
"Array of lines: desc, qty, subprice (unit price excl. tax), tva_tx (VAT rate). A line may instead give product_ref, and the catalogue product and price are used."
476 'description' =>
"List supplier proposal (price request). Filter with sqlfilters.",
477 'params' => [
'sqlfilters' =>
"Universal filter, e.g. (t.fk_soc:=:2)",
'limit' =>
"Rows to return."]
479 'get' => [
'description' =>
"Get one record by rowid, with its lines."],
480 'postLine' => $this->
addLineMethod(
'supplier proposal',
'api_supplier_proposals_list',
'SupplierProposal', [
'supplier_proposal',
'creer'],
true)
484 $this->enrichments[
'invoices'] = [
485 'label' =>
'customer invoices',
488 'suffix' =>
'create',
489 'description' =>
"Create a DRAFT customer invoice. Nothing is validated, sent or paid: the draft is created and the user finishes it in Dolibarr, or asks for the next step explicitly. Give socid, or simply the third party name, and the lines; a line may name its product with product_ref and the catalogue price is used. Do not call a search tool first. The user confirms before anything is written.",
493 'preview' =>
'AIPreviewCreateInvoice',
494 'required' => [
'socid'],
495 'object' =>
'Facture',
496 'thirdparty' =>
'socid',
501 'right' => [
'facture',
'creer']
504 'socid' =>
"Rowid of the customer, or its name: a name is resolved here, so no separate lookup call is needed.",
505 'lines' =>
"Array of lines: desc, qty, subprice (unit price excl. tax), tva_tx (VAT rate). A line may instead give product_ref, and the catalogue product and price are used."
509 'default_properties' =>
'id,ref,socid,date,date_lim_reglement,total_ht,total_ttc,paye,remaintopay',
510 'description' =>
"Use 'status' for the usual questions (unpaid, paid, drafts). Oldest first: sortfield 't.datef' with sortorder 'ASC' (due-date order: 't.date_lim_reglement'). Set withLines=false for lists: lines are large and rarely needed. Amounts: total_ht (excl. tax), total_tva, total_ttc (incl. tax), paye (1=paid). Dates are unix timestamps: date (invoice date), date_lim_reglement (due date). Overdue unpaid invoices: status='unpaid' plus sqlfilters \"(t.date_lim_reglement:<:'YYYY-MM-DD')\". Useful sqlfilters fields: t.ref, t.datef, t.total_ttc, t.fk_soc, t.type (0=standard, 1=replacement, 2=credit note, 3=deposit, 4=proforma), t.fk_statut (0=draft, 1=validated, 2=paid, 3=abandoned).",
512 'thirdparty_ids' =>
"Comma-separated third-party rowids to restrict to (e.g. '1,5'). Look the rowid up with api_thirdparties_list first when only a name is known.",
513 'status' =>
"One of 'draft', 'unpaid' (validated and not fully paid), 'paid', 'cancelled'. Empty = all.",
514 'withLines' =>
"false to omit invoice lines from each record (recommended for lists).",
515 'loadlinkedobjects' =>
"1 to include linked objects (orders, proposals, shipments) — slower, default 0.",
516 'pagination_data' =>
"Set to true to get {data, pagination:{total,page,page_count,limit}}; use it to know how many invoices match."
520 'description' =>
"One invoice with its lines (product, qty, unit price, VAT rate, line totals), status, remaining amount to pay and linked contacts. Look the rowid up with api_invoices_list (sqlfilters on t.ref) when only the reference is known.",
522 'contact_list' =>
"0 = no contacts, 1 (default) = contact rowids, 2 = full contact records.",
523 'withLines' =>
"false to omit the lines."
527 'suffix' =>
'get_by_ref',
528 'description' =>
"One invoice by its exact reference (e.g. 'FA2401-0001').",
529 'params' => [
'ref' =>
"Exact invoice reference.",
'contact_list' =>
"0 = no contacts, 1 (default) = contact rowids, 2 = full contact records."]
532 'suffix' =>
'payments_list',
533 'description' =>
"Payments already recorded on one invoice: amount, date, payment mode, bank reference.",
534 'params' => [
'id' =>
"Rowid of the invoice."]
536 'postLine' => $this->
addLineMethod(
'customer invoice',
'api_invoices_get_by_ref',
'Facture', [
'facture',
'creer'])
541 $descriptioncreate =
"Create a DRAFT sale order (customer order). Nothing is validated or sent: the draft is created and the user finishes it in Dolibarr, or asks for the next step explicitly. The third party is mandatory: give socid, or simply the third party name as the user said it (it is resolved here, do not call a search tool first); ask the user only when no third party is named at all. Give the lines; a line may name its product with product_ref and the catalogue price is used. The user confirms before anything is written.";
543 $descriptionlist =
"Return a list of sale orders with properties: id, ref, socid, date_commande, delivery_date, total_ht, total_ttc, statut. ";
544 $descriptionlist .=
"Useful sqlfilters fields with type:\n";
545 $descriptionlist .=
"- t.ref : string (sale order ref)\n";
546 $descriptionlist .=
"- t.fk_soc : integer (thirdparty ID),\n";
547 $descriptionlist .=
"- t.date_commande : timestamp (order date),\n";
548 $descriptionlist .=
"- t.total_ht : float, t.total_ttc : float,\n";
549 $descriptionlist .=
"- t.fk_statut : integer enum (status ID) among -1=cancelled, 0=draft, 1=validated (open), 2=shipment in progress, 3=closed (delivered / billed).";
551 $descriptionfetch =
"Fetch one order with its lines (product, qty, unit price, discount, line totals), status and dates. Fetch is done from ID.";
553 $descriptionfetchref =
"Fetch one order with its lines (product, qty, unit price, discount, line totals), status and dates. Fetch is done from exact REF (e.g. 'CO2401-0001').";
555 $this->enrichments[
'orders'] = [
556 'label' =>
'sale orders',
559 'suffix' =>
'create',
560 'description' => $descriptioncreate,
562 'preview' =>
'AIPreviewCreateOrder',
563 'required' => [
'socid'],
564 'object' =>
'Commande',
565 'thirdparty' =>
'socid',
567 'right' => [
'commande',
'creer'],
570 'defaults' => [
'date' =>
'now']
573 'socid' =>
"Rowid of the customer, or its name: a name is resolved here, so a separate lookup call can be avoided here.",
574 'lines' =>
"Array of order lines: desc, qty, subprice (unit price excl. tax), tva_tx (VAT rate). A line may instead give product_ref, and the catalogue product and price are used."
578 'default_properties' =>
'id,ref,socid,date_commande,delivery_date,total_ht,total_ttc,status',
579 'description' => $descriptionlist,
581 'thirdparty_ids' =>
"Comma-separated third-party rowids to restrict to (e.g. '1,5'). Look the rowid up with api_thirdparties_list first when only a name is known.",
582 'loadlinkedobjects' =>
"1 to include linked objects (proposals, shipments, invoices) — slower, default 0.",
583 'pagination_data' =>
"Set to true to get {data, pagination:{total,page,page_count,limit}}; use it to know how many orders match."
587 'description' => $descriptionfetch,
588 'params' => [
'contact_list' =>
"0 = no need of contacts, 1 (default) = need contact rowids, 2 = need full contact records."]
591 'suffix' =>
'get_by_ref',
592 'description' => $descriptionfetchref,
593 'params' => [
'ref' =>
"Exact order reference.",
'contact_list' =>
"0 = no need of contacts, 1 (default) = need contact rowids, 2 = need full contact records."]
595 'postLine' => $this->
addLineMethod(
'sale order',
'api_orders_get_by_ref',
'Commande', [
'commande',
'creer'])
599 $this->enrichments[
'proposals'] = [
600 'label' =>
'commercial proposals (quotes / devis)',
603 'suffix' =>
'create',
604 'description' =>
"Create a DRAFT commercial proposal (quote). Nothing is validated or sent: the draft is created and the user finishes it in Dolibarr, or asks for the next step explicitly. Give socid, or simply the third party name, and the lines; a line may name its product with product_ref and the catalogue price is used. Do not call a search tool first. The user confirms before anything is written.",
606 'preview' =>
'AIPreviewCreateProposal',
607 'required' => [
'socid'],
608 'object' =>
'Propal',
609 'thirdparty' =>
'socid',
611 'right' => [
'propal',
'creer'],
612 'defaults' => [
'date' =>
'now']
615 'socid' =>
"Rowid of the third party, or its name: a name is resolved here, so no separate lookup call is needed.",
616 'lines' =>
"Array of lines: desc, qty, subprice (unit price excl. tax), tva_tx (VAT rate). A line may instead give product_ref, and the catalogue product and price are used."
620 'default_properties' =>
'id,ref,socid,datep,fin_validite,total_ht,total_ttc,fk_statut',
621 'description' =>
"Statuses (t.fk_statut): 0=draft, 1=validated (open, awaiting answer), 2=signed/accepted, 3=not signed/refused, 4=billed. Dates are unix timestamps: datep (proposal date), fin_validite (validity end — expired open proposals: fk_statut=1 plus sqlfilters \"(t.fin_validite:<:'YYYY-MM-DD')\"). Useful sqlfilters fields: t.ref, t.datep, t.total_ht, t.total_ttc, t.fk_soc, t.fk_statut.",
623 'thirdparty_ids' =>
"Comma-separated third-party rowids to restrict to (e.g. '1,5'). Look the rowid up with api_thirdparties_list first when only a name is known.",
624 'loadlinkedobjects' =>
"1 to include linked objects (orders, invoices) — slower, default 0.",
625 'pagination_data' =>
"Set to true to get {data, pagination:{total,page,page_count,limit}}; use it to know how many proposals match."
629 'description' =>
"One proposal with its lines (product, qty, unit price, discount, line totals), status and validity date.",
630 'params' => [
'contact_list' =>
"0 = no contacts, 1 (default) = contact rowids, 2 = full contact records."]
633 'suffix' =>
'get_by_ref',
634 'description' =>
"One proposal by its exact reference (e.g. 'PR2401-0001').",
635 'params' => [
'ref' =>
"Exact proposal reference.",
'contact_list' =>
"0 = no contacts, 1 (default) = contact rowids, 2 = full contact records."]
637 'postLine' => $this->
addLineMethod(
'commercial proposal',
'api_proposals_get_by_ref',
'Propal', [
'propal',
'creer'])
641 $this->enrichments[
'tickets'] = [
642 'label' =>
'support tickets',
645 'suffix' =>
'create',
646 'description' =>
"Create a support ticket. The user confirms before anything is written. subject and message are mandatory; socid is optional (a ticket may belong to no third party).",
648 'preview' =>
'AIPreviewCreateTicket',
649 'required' => [
'subject',
'message'],
650 'object' =>
'Ticket',
651 'thirdparty' =>
'socid',
652 'right' => [
'ticket',
'write'],
653 'args' => [
'subject',
'message'],
656 'copy' => [
'socid' =>
'fk_soc'],
657 'rename' => [
'fk_statut' =>
'status'],
661 'defaults' => [
'notify_tiers_at_create' => 0],
664 'subject' =>
"Ticket subject (required).",
665 'message' =>
"First message describing the request (required).",
666 'socid' =>
"Rowid of the customer the ticket belongs to, or its name as said (resolved here). Omit or 0 for a ticket not linked to a third party.",
667 'fk_user_assign' =>
"Rowid of the user to assign the ticket to.",
668 'type_code' =>
"Nature of the request, e.g. COM=commercial question, ISSUE=incident, HELP=request, OTHER.",
669 'category_code' =>
"Ticket group/category code.",
670 'severity_code' =>
"Severity: LOW, NORMAL, HIGH or BLOCKING.",
671 'fk_project' =>
"Rowid of a project the ticket relates to.",
672 'notify_tiers_at_create' =>
"1 to notify the third party by email on creation, 0 (default) silent."
675 'postNewMessage' => [
677 'description' =>
"Post a message on an existing support ticket, given by its rowid or its ref. The user confirms before anything is written.",
679 'preview' =>
'AIPreviewReplyTicket',
680 'required' => [
'message'],
681 'object' =>
'Ticket',
683 'right' => [
'ticket',
'write'],
684 'args' => [
'track_id',
'message'],
689 'target_or' =>
'track_id',
690 'track_from_target' =>
true,
693 'id' =>
"The ticket: rowid, or its ref (e.g. TS2401-0001).",
694 'track_id' =>
"Public tracking id of the ticket, only when neither the rowid nor the ref is known.",
695 'message' =>
"Message text to post on the ticket (required).",
696 'private' =>
"1 for an internal note the customer never sees, 0 (default) for a public message."
700 'suffix' =>
'update',
701 'description' =>
"Update fields of an existing support ticket: subject, status, severity, type, category, project, third party. Only the fields given are changed. To close, cancel or assign it use api_tickets_close / api_tickets_assign. The user confirms before anything is written.",
703 'preview' =>
'AIPreviewUpdateTicket',
704 'required' => [
'id'],
705 'object' =>
'Ticket',
707 'right' => [
'ticket',
'write'],
714 'fk_statut' => [
'values' => [8, 9],
'tool' =>
'api_tickets_close'],
715 'status' => [
'values' => [8, 9],
'tool' =>
'api_tickets_close'],
716 'fk_user_assign' => [
'values' =>
null,
'tool' =>
'api_tickets_assign'],
722 'copy' => [
'socid' =>
'fk_soc'],
723 'rename' => [
'fk_statut' =>
'status'],
726 'id' =>
"The ticket: rowid, or its ref (required).",
727 'subject' =>
"New subject.",
728 'socid' =>
"Rowid of the customer to link the ticket to, or its name as said.",
729 'fk_statut' =>
"New status: 0=not read, 1=read, 3=in progress, 5=needs more info, 7=waiting. To close or cancel use api_tickets_close, to assign use api_tickets_assign.",
730 'severity_code' =>
"New severity: LOW, NORMAL, HIGH or BLOCKING.",
731 'type_code' =>
"New nature: COM, ISSUE, HELP or OTHER.",
732 'category_code' =>
"New group/category code.",
733 'fk_project' =>
"Rowid of a project to relate the ticket to."
737 'suffix' =>
'add_contact',
738 'description' =>
"Link a contact to a support ticket. The user confirms before anything is written.",
740 'preview' =>
'AIPreviewAddTicketContact',
741 'required' => [
'id',
'contactid',
'type'],
742 'object' =>
'Ticket',
744 'right' => [
'ticket',
'write'],
745 'args' => [
'contactid',
'id'],
748 'contact' =>
'ticket',
751 'id' =>
"The ticket: rowid, or its ref (required).",
752 'contactid' =>
"Rowid of the contact (a person of a third party), or of the user when source is 'internal' (required).",
753 'type' =>
"Role on the ticket (required): SUPPORTCLI (customer contact following it) or CONTRIBUTOR for a contact; SUPPORTTEC (in charge) or CONTRIBUTOR for a user.",
754 'source' =>
"'external' (default) for a third-party contact, 'internal' for a Dolibarr user."
758 'suffix' =>
'remove_contact',
759 'description' =>
"Unlink a contact from a support ticket. The user confirms before anything is written.",
761 'preview' =>
'AIPreviewRemoveTicketContact',
762 'required' => [
'id',
'contactid',
'type'],
763 'object' =>
'Ticket',
765 'right' => [
'ticket',
'write'],
766 'args' => [
'contactid',
'id'],
769 'contact' =>
'ticket',
772 'id' =>
"The ticket: rowid, or its ref (required).",
773 'contactid' =>
"Rowid of the contact, or of the user when source is 'internal' (required).",
774 'type' =>
"Role to remove (required): SUPPORTCLI, CONTRIBUTOR or SUPPORTTEC.",
775 'source' =>
"'external' (default) or 'internal'."
780 'description' =>
"Close a support ticket, or cancel it (cancel: 1), as the Close and Abandon buttons of the card do: closing date, progress and notifications included. Give 'id' (rowid, or its ref). The user confirms before anything is written.",
783 'preview' =>
'AIPreviewCloseTicket',
784 'preview_cancel' =>
'AIPreviewCancelTicket',
785 'object' =>
'Ticket',
790 'states' => [0, 1, 2, 3, 5, 6, 7],
791 'state_error' =>
'AIWriteTicketClosed',
792 'pass' => [
'cancel'],
793 'right' => [
'ticket',
'write'],
796 'id' =>
"The ticket: rowid, or its ref.",
797 'cancel' =>
"1 to cancel (abandon) the ticket instead of closing it."
801 'suffix' =>
'assign',
802 'description' =>
"Assign a support ticket to a user, or unassign it (fk_user_assign: 0), as the card does: the status follows and the user is notified. Give 'id' (rowid, or its ref) and fk_user_assign (rowid of the user, or 'me'). The user confirms before anything is written.",
805 'preview' =>
'AIPreviewAssignTicket',
806 'preview_unassign' =>
'AIPreviewUnassignTicket',
807 'object' =>
'Ticket',
811 'states' => [0, 1, 2, 3, 5, 6, 7],
812 'state_error' =>
'AIWriteTicketClosed',
813 'pass' => [
'fk_user_assign'],
814 'right' => [
'ticket',
'write'],
817 'id' =>
"The ticket: rowid, or its ref.",
818 'fk_user_assign' =>
"Rowid of the user to assign it to, 'me' for yourself, or 0 to unassign."
825 'default_properties' =>
'id,ref,subject,fk_soc,fk_statut,severity_code,type_code,datec',
826 'description' =>
"Statuses (t.fk_statut): 0=not read, 1=read, 2=assigned, 3=in progress, 5=needs more info, 7=waiting, 8=closed, 9=canceled. Open tickets = fk_statut < 8. Severity in severity_code (LOW, NORMAL, HIGH, BLOCKING), nature in type_code (COM=commercial, ISSUE=incident, ...). Useful sqlfilters fields: t.subject, t.fk_statut, t.severity_code, t.type_code, t.datec (creation), t.fk_user_assign (assigned user rowid).",
828 'socid' =>
"Third-party rowid to restrict tickets to one customer (0 = all).",
829 'loadcontacts' =>
"1 to include linked contacts per ticket, 0 (default, faster) without.",
830 'pagination_data' =>
"Set to true to get {data, pagination:{total,page,page_count,limit}}."
834 'description' =>
"One ticket with its subject, full message, status, severity, assigned user and linked third party. The public tracking id is in track_id."
837 'suffix' =>
'get_by_track_id',
838 'description' =>
"One ticket by its public tracking id (the hash customers receive by email).",
839 'params' => [
'track_id' =>
"Public tracking id of the ticket."]
842 'suffix' =>
'get_by_ref',
843 'description' =>
"One ticket by its exact internal reference (e.g. 'TS2401-0001').",
844 'params' => [
'ref' =>
"Exact ticket reference."]
849 $this->enrichments[
'projects'] = [
850 'label' =>
'projects (including opportunities/leads)',
853 'default_properties' =>
'id,ref,title,fk_soc,public,date_start,date_end,fk_statut,opp_status,opp_amount',
854 'description' =>
"Statuses (t.fk_statut): 0=draft, 1=open, 2=closed. A project used as a sales opportunity carries opp_status (pipeline step rowid), opp_percent (probability) and opp_amount. Dates are unix timestamps: date_start (dateo), date_end (datee). Useful sqlfilters fields: t.ref, t.title, t.fk_soc, t.fk_statut, t.dateo, t.datee, t.public (1=visible to everyone). Tasks of a project: use api_tasks_list with sqlfilters \"(t.fk_projet:=:'ID')\".",
856 'thirdparty_ids' =>
"Comma-separated third-party rowids to restrict to (e.g. '1,5').",
857 'category' =>
"Rowid of a project category (tag) to restrict the list to.",
858 'pagination_data' =>
"Set to true to get {data, pagination:{total,page,page_count,limit}}."
862 'description' =>
"One project with its dates, status, budget, opportunity data and linked third party."
866 'suffix' =>
'get_by_ref',
867 'description' =>
"One project by its exact reference (e.g. 'PJ2401-0001').",
868 'params' => [
'ref' =>
"Exact project reference."]
873 $this->enrichments[
'tasks'] = [
874 'label' =>
'project tasks',
877 'default_properties' =>
'id,ref,label,fk_projet,progress,planned_workload,duration_effective,date_start,date_end',
878 'description' =>
"Tasks belong to a project (fk_projet — filter one project with sqlfilters \"(t.fk_projet:=:'ID')\"). progress is a percentage (0-100); planned_workload and duration_effective (time already spent) are in SECONDS — divide by 3600 for hours. fk_task_parent > 0 for subtasks. Useful sqlfilters fields: t.label, t.fk_projet, t.progress, t.dateo (start), t.datee (end).",
880 'includetimespent' =>
"1 to also load the time-spent summary per task (slower).",
881 'pagination_data' =>
"Set to true to get {data, pagination:{total,page,page_count,limit}}."
885 'description' =>
"One task with its project, planned workload, progress and dates (durations in seconds).",
886 'params' => [
'includetimespent' =>
"1 to include the detail of time spent records."]
889 'suffix' =>
'timespent_list',
890 'description' =>
"Time records logged on one task: date, duration in seconds, user and note. Sum task_duration for the total.",
891 'params' => [
'id' =>
"Rowid of the task."]
894 'suffix' =>
'update',
895 'description' =>
"Update fields of an existing task: label, description, progress percent, planned workload, dates. Only the fields given are changed. The user confirms before anything is written.",
897 'preview' =>
'AIPreviewChangeTask',
898 'required' => [
'id'],
901 'right' => [
'projet',
'creer'],
905 'dates' => [
'date_start',
'date_end'],
906 'hours' => [
'planned_workload'],
907 'trim_fields' => [
'label',
'description'],
910 'id' =>
"The task: rowid, or its ref (required).",
911 'label' =>
"New label.",
912 'description' =>
"New description.",
913 'progress' =>
"New progress percent 0-100.",
914 'planned_workload' =>
"New planned workload in hours.",
915 'date_start' =>
"New start date YYYY-MM-DD.",
916 'date_end' =>
"New end date YYYY-MM-DD."
920 'suffix' =>
'add_timespent',
921 'description' =>
"Log a time-spent record on a task: date, duration in hours, optional note and a new progress percent. The user confirms before anything is written.",
923 'preview' =>
'AIPreviewAddTimespent',
924 'required' => [
'id',
'date',
'duration'],
927 'right' => [
'projet',
'creer'],
930 'args' => [
'duration',
'date',
'id'],
934 'text_dates' => [
'date'],
935 'hours' => [
'duration'],
938 'id' =>
"The task: rowid, or its ref (required).",
939 'date' =>
"Date of the work YYYY-MM-DD or 'today' (required).",
940 'duration' =>
"Duration in hours, e.g. 1.5 (required).",
941 'note' =>
"Optional note for the record.",
942 'user_id' =>
"Rowid of the user who did the work, or 'me' for yourself. Omit to use the acting user.",
943 'progress' =>
"New task progress percent 0-100 (optional)."
949 $this->enrichments[
'agendaevents'] = [
950 'label' =>
'agenda / calendar events (meetings, calls)',
953 'default_properties' =>
'id,ref,label,type_code,datep,datef,fulldayevent,percentage,fk_soc,userownerid',
954 'description' =>
"Default sortfield is t.id — pass sortfield 't.datep' with sortorder 'ASC' for chronological order. Nature in type_code (AC_RDV=meeting, AC_TEL=phone call, AC_EMAIL=email, AC_OTH=other, AC_OTH_AUTO=automatic log). percentage: -1 = plain event, 0-99 = to-do in progress, 100 = done. Dates are unix timestamps: datep (start), datef (end). Upcoming events: sqlfilters \"(t.datep:>=:'YYYY-MM-DD')\". Other useful fields: t.label, t.fk_soc, t.fk_element/t.elementtype (linked business object).",
956 'user_ids' =>
"Comma-separated user rowids to restrict to events owned by these users (e.g. '1,3').",
957 'pagination_data' =>
"Set to true to get {data, pagination:{total,page,page_count,limit}}."
961 'description' =>
"One event with its type, start/end dates, owner, linked third party/contact and note."
966 $this->enrichments[
'interventions'] = [
967 'label' =>
'field service interventions',
970 'default_properties' =>
'id,ref,socid,fk_statut,description,datec,duration',
971 'description' =>
"Statuses (t.fk_statut): 0=draft, 1=validated, 2=billed, 3=done/closed. duration is in SECONDS (divide by 3600 for hours). Useful sqlfilters fields: t.ref, t.fk_soc, t.fk_statut, t.datec, t.description.",
973 'thirdparty_ids' =>
"Comma-separated third-party rowids to restrict to (e.g. '1,5').",
974 'pagination_data' =>
"Set to true to get {data, pagination:{total,page,page_count,limit}}."
978 'description' =>
"One intervention with its lines (each line = one on-site work entry with date, duration in seconds and description)."
983 $this->enrichments[
'contracts'] = [
984 'label' =>
'contracts (recurring services)',
987 'default_properties' =>
'id,ref,socid,date_contrat,statut',
988 'description' =>
"Contract statuses (t.statut): 0=draft, 1=validated. What matters is usually the LINE status (each line is one service): 0=inactive/draft, 4=active/running, 5=closed. Set withLines=false for lists (lines are large), then read one contract with api_contracts_get or its lines with api_contracts_lines_list. Useful sqlfilters fields: t.ref, t.fk_soc, t.statut, t.date_contrat.",
990 'thirdparty_ids' =>
"Comma-separated third-party rowids to restrict to (e.g. '1,5').",
991 'withLines' =>
"false to omit the service lines from each record (recommended for lists).",
992 'pagination_data' =>
"Set to true to get {data, pagination:{total,page,page_count,limit}}."
996 'description' =>
"One contract with its service lines: per line fk_product, description, date_start/date_end (unix timestamps) and statut (0=inactive, 4=active, 5=closed).",
997 'params' => [
'withLines' =>
"false to omit the lines."]
1000 'suffix' =>
'lines_list',
1001 'description' =>
"Service lines of one contract, with their own pagination and sqlfilters (fields prefixed 'd.', e.g. \"(d.statut:=:'4')\" for active services).",
1002 'params' => [
'id' =>
"Rowid of the contract."]
1007 $this->enrichments[
'members'] = [
1008 'label' =>
'foundation/association members',
1011 'default_properties' =>
'id,ref,firstname,lastname,societe,email,typeid,statut,datefin',
1012 'description' =>
"Statuses (t.statut): -1=draft, 1=validated (member), 0=membership terminated (resiliated), -2=excluded. Whether the subscription is up to date is in datefin (unix timestamp of the paid-up end date): late members = statut 1 plus sqlfilters \"(t.datefin:<:'YYYY-MM-DD')\" (or datefin null). Useful sqlfilters fields: t.firstname, t.lastname, t.societe, t.email, t.statut, t.datefin.",
1014 'typeid' =>
"Rowid of a member type to restrict the list to.",
1015 'category' =>
"Rowid of a member category (tag) to restrict the list to.",
1016 'pagination_data' =>
"Set to true to get {data, pagination:{total,page,page_count,limit}}."
1020 'description' =>
"One member with identity, member type, status, linked third party and paid-up end date (datefin)."
1022 'getSubscriptions' => [
1023 'suffix' =>
'subscriptions_list',
1024 'description' =>
"Subscription (membership fee) history of one member: period start/end and amount per payment.",
1025 'params' => [
'id' =>
"Rowid of the member."]
1030 $this->enrichments[
'subscriptions'] = [
1031 'label' =>
'subscriptions',
1034 'description' =>
"All membership subscriptions (with fee payments or not) across members: fk_adherent (member rowid), dateh (period start), datef (period end), amount. NB: the default sortfield here is 'dateadh' WITHOUT the 't.' prefix (API quirk). To get the fees of one member prefer api_members_subscriptions_list.",
1036 'pagination_data' =>
"Set to true to get {data, pagination:{total,page,page_count,limit}}."
1040 'description' =>
"One subscription payment with its member, period and amount."
1045 $this->enrichments[
'stockmovements'] = [
1046 'label' =>
'stock movements (in/out/transfer history)',
1049 'default_properties' =>
'id,product_id,warehouse_id,qty,date,type,label,inventorycode',
1050 'description' =>
"History of physical stock changes; each movement carries product_id, warehouse_id, qty (SIGNED: positive=in, negative=out), date and label. Movements of one product: sqlfilters \"(t.fk_product:=:'ID')\"; of one warehouse: \"(t.fk_entrepot:=:'ID')\"; over a period: \"(t.datem:>=:'YYYY-MM-DD')\". The source document (reception, shipment, inventory...) is in origintype/fk_origin when set.",
1052 'pagination_data' =>
"Set to true to get {data, pagination:{total,page,page_count,limit}}."
1059 $this->enrichments[
'warehouses'] = [
1060 'label' =>
'warehouses',
1063 'description' =>
"Warehouses/locations: ref (name), lieu (short location), statut (1=open, 0=closed). Search by name with sqlfilters on t.ref. Per-product stock by warehouse is NOT here — use api_products_get with includestockdata=1.",
1065 'category' =>
"Rowid of a warehouse category (tag) to restrict the list to.",
1066 'pagination_data' =>
"Set to true to get {data, pagination:{total,page,page_count,limit}}."
1070 'description' =>
"One warehouse with its address, status and description."
1075 $this->enrichments[
'shipments'] = [
1076 'label' =>
'customer shipments (expéditions, goods sent)',
1079 'suffix' =>
'create',
1080 'description' =>
"Create a DRAFT customer shipment (delivery note) WITHOUT a source order, as the shipment card allows when standalone shipments are enabled. Nothing is validated and no stock moves: like the lines added on the shipment card, these lines carry no warehouse, and a product tracked by lot or serial number cannot be shipped this way. The customer is mandatory: give socid, or simply the customer name. Each line names a catalogue product (product_ref or fk_product) or carries a free desc, with a qty and an optional unit. To ship an existing order, do not use this tool: tell the user to create the shipment from the order card.",
1082 'preview' =>
'AIPreviewCreateShipment',
1083 'required' => [
'socid'],
1084 'object' =>
'Expedition',
1085 'thirdparty' =>
'socid',
1087 'right' => [
'expedition',
'creer'],
1088 'kind' =>
'shipment',
1090 'product_ref' => [
'type' =>
'string',
'description' =>
'Ref or label of a catalogue product.'],
1091 'desc' => [
'type' =>
'string',
'description' =>
'Free text, for a line with no product.'],
1092 'qty' => [
'type' =>
'number'],
1093 'unit' => [
'type' =>
'string',
'description' =>
'Unit as said, e.g. pieces, kg. Omit to use the product unit.']
1097 'socid' =>
"Rowid of the customer, or its name: a name is resolved here, so no separate lookup call is needed.",
1098 'ref_customer' =>
"Customer's own reference for this delivery (optional).",
1099 'date_delivery' =>
"Planned delivery date, YYYY-MM-DD (optional).",
1100 'lines' =>
"Array of lines: product_ref (or fk_product) or desc for a free line, qty, unit (optional)."
1104 'default_properties' =>
'id,ref,socid,ref_customer,date_delivery,date_shipping,statut',
1105 'description' =>
"Statuses (t.fk_statut): 0=draft (reference '(PROVnn)' until validated), 1=validated (goods left), 2=closed (billed / processed). Dates are unix timestamps: date_shipping (sent), date_delivery (planned delivery). Useful sqlfilters fields: t.ref, t.ref_customer, t.fk_soc, t.fk_statut, t.date_delivery.",
1107 'thirdparty_ids' =>
"Comma-separated third-party rowids to restrict to (e.g. '1,5'). Look the rowid up with api_thirdparties_list first when only a name is known.",
1108 'pagination_data' =>
"Set to true to get {data, pagination:{total,page,page_count,limit}}; use it to know how many shipments match."
1112 'description' =>
"One shipment: customer, source order, dates, status, tracking number; the lines are in api_shipments_get_lines."
1115 'suffix' =>
'get_lines',
1116 'description' =>
"Lines of a shipment: product, quantity shipped, batch/lot when the product is tracked.",
1117 'params' => [
'id' =>
"Rowid of the shipment."]
1122 $this->enrichments[
'receptions'] = [
1123 'label' =>
'supplier receptions (réceptions, goods received)',
1126 'suffix' =>
'create',
1127 'description' =>
"Create a DRAFT supplier reception (goods received, typically from a supplier delivery note) WITHOUT a supplier order, as the reception card allows when standalone receptions are enabled. Nothing is validated: stock does not move until the user validates the reception in Dolibarr. The supplier is mandatory: give socid, or simply the supplier name. Each line names a catalogue product (product_ref or fk_product) and a qty; optional: warehouse (name or rowid, else the default warehouse), cost_price (unit purchase price excl. tax, else the supplier price of the product), batch with eatby/sellby for a lot-tracked product. To receive an existing supplier order, do not use this tool: tell the user to create the reception from the order card.",
1129 'preview' =>
'AIPreviewCreateReception',
1130 'required' => [
'socid'],
1131 'object' =>
'Reception',
1132 'thirdparty' =>
'socid',
1134 'right' => [
'reception',
'creer'],
1136 'kind' =>
'reception',
1138 'product_ref' => [
'type' =>
'string',
'description' =>
'Ref or label of a catalogue product. Mandatory: a reception line moves the stock of a product.'],
1139 'qty' => [
'type' =>
'number'],
1140 'warehouse' => [
'type' =>
'string',
'description' =>
'Warehouse receiving the goods, by name or rowid. Omit to use the default warehouse.'],
1141 'cost_price' => [
'type' =>
'number',
'description' =>
'Unit purchase price excl. tax. Omit to use the supplier price of the product.'],
1142 'batch' => [
'type' =>
'string',
'description' =>
'Lot or serial number, for a lot-tracked product.'],
1143 'eatby' => [
'type' =>
'string',
'description' =>
'Eat-by date YYYY-MM-DD (lot-tracked product).'],
1144 'sellby' => [
'type' =>
'string',
'description' =>
'Sell-by date YYYY-MM-DD (lot-tracked product).']
1148 'socid' =>
"Rowid of the supplier, or its name: a name is resolved here, so no separate lookup call is needed.",
1149 'ref_supplier' =>
"Supplier's reference printed on the delivery note (optional).",
1150 'date_delivery' =>
"Delivery date, YYYY-MM-DD (optional).",
1151 'lines' =>
"Array of lines: product_ref (or fk_product), qty, warehouse (optional), cost_price (optional), batch/eatby/sellby (optional)."
1155 'default_properties' =>
'id,ref,socid,ref_supplier,date_reception,date_delivery,statut',
1156 'description' =>
"Statuses (t.fk_statut): 0=draft (reference '(PROVnn)' until validated), 1=validated (goods received into stock), 2=closed / processed. Dates are unix timestamps: date_reception (received), date_delivery (planned). Useful sqlfilters fields: t.ref, t.ref_supplier, t.fk_soc, t.fk_statut, t.date_delivery. A draft created by the chat keeps its '(PROVnn)' reference: search it by id or with sqlfilters on t.ref_supplier.",
1158 'thirdparty_ids' =>
"Comma-separated supplier rowids to restrict to (e.g. '1,5'). Look the rowid up with api_thirdparties_list first when only a name is known.",
1159 'pagination_data' =>
"Set to true to get {data, pagination:{total,page,page_count,limit}}; use it to know how many receptions match."
1163 'description' =>
"One reception: supplier, supplier reference, dates, status; the lines are in api_receptions_get_lines."
1166 'suffix' =>
'get_lines',
1167 'description' =>
"Lines of a reception: product, quantity received, batch/lot and warehouse when tracked.",
1168 'params' => [
'id' =>
"Rowid of the reception."]
1173 $this->enrichments[
'expensereports'] = [
1174 'label' =>
'employee expense reports (notes de frais)',
1177 'default_properties' =>
'id,ref,fk_user_author,date_debut,date_fin,total_ht,total_ttc,fk_statut',
1178 'description' =>
"Statuses (t.fk_statut): 0=draft, 2=validated (waiting approval), 4=canceled, 5=approved, 6=paid, 99=refused. The employee is fk_user_author (a USER rowid, not a third party). Period: date_debut/date_fin (unix timestamps). Useful sqlfilters fields: t.ref, t.fk_user_author, t.fk_statut, t.date_debut, t.total_ttc.",
1180 'user_ids' =>
"Comma-separated user rowids to restrict to the reports of these employees (e.g. '1,3').",
1181 'pagination_data' =>
"Set to true to get {data, pagination:{total,page,page_count,limit}}."
1185 'description' =>
"One expense report with its lines: per line the date, expense type code (type_fees_code: TRA_TRIP=transport, TRA_MEAL=meal, ...), VAT and amounts."
1191 $descriptioncreate =
"Create a product or service in the catalog. The user must confirm before anything is written.";
1193 $descriptionlist =
"Search products using the sqlfilters (e.g. \"(t.label:like:'%screw%')\").\n";
1194 $descriptionlist .=
"Prefer 'properties' (e.g. 'id,ref,label,type,price,price_ttc,tva_tx,status,status_buy') and a small 'limit'.\n";
1196 $descriptionlist .=
"Useful sqlfilters fields with type:\n";
1197 $descriptionlist .=
"- t.ref : string (sale order ref)\n";
1198 $descriptionlist .=
"- t.label : string (product label)\n";
1199 $descriptionlist .=
"- t.fk_soc : integer (thirdparty ID),\n";
1200 $descriptionlist .=
"- t.date_commande : timestamp (order date),\n";
1201 $descriptionlist .=
"- t.price_ttc : float (default customer price), t.tva_tx : float (default vat rate),\n";
1202 $descriptionlist .=
"- t.status : integer (status For Sale) among 0=not for sale, 1=for sale\n";
1203 $descriptionlist .=
"- t.status_buy : integer (status For purchase) among 0=not for purchase, 1=for purchase\n";
1204 $descriptionlist .=
"- t.stock_reel : float (qty in stock, output only when param includestockdata=1)\n";
1206 $descriptionfetch =
"Fetch full product record (description, prices, VAT, barcode, weight/dimensions, accounting codes, optional stock and sub-products), status and dates. Fetch is done from ID.";
1208 $this->enrichments[
'products'] = [
1209 'label' =>
'products and services catalog',
1212 'suffix' =>
'create',
1213 'description' => $descriptioncreate,
1215 'preview' =>
'AIPreviewCreateProduct',
1216 'required' => [
'ref',
'label'],
1217 'object' =>
'Product',
1218 'args' => [
'label'],
1219 'right' => [
'produit',
'creer']
1222 "ref" =>
"Internal reference.",
"label" =>
"Product label.",
"price" =>
"Selling price excl. tax.",
"type" =>
"0 product, 1 service."
1226 'default_properties' =>
'id,ref,label,type,price,price_ttc,tva_tx,status,status_buy',
1227 'description' => $descriptionlist,
1229 'mode' =>
"0=all (default), 1=products only, 2=services only.",
1230 'category' =>
"Rowid of a product category to restrict the list to.",
1231 'variant_filter' =>
"0=all (default), 1=products without variants, 2=parents of variants only, 3=variants only.",
1232 'ids_only' =>
"true to return only rowids (fast, use for counting).",
1233 'includestockdata' =>
"1 to add stock_reel / stock_theorique per product (slower; requires the Stock module).",
1234 'pagination_data' =>
"Set to true to get {data, pagination:{total,page,page_count,limit}}."
1238 'description' => $descriptionfetch,
1240 'includestockdata' =>
"1 to load stock_reel, stock_theorique and per-warehouse stock (requires the Stock module).",
1241 'includesubproducts' =>
"true to load the kit/BOM components (sub-products).",
1242 'includeparentid' =>
"true to add fk_product_parent for a variant.",
1243 'includetrans' =>
"true to load multilingual labels/descriptions."
1247 'suffix' =>
'get_by_ref',
1248 'description' =>
"One product by its exact reference (e.g. 'PROD-001'); same options as get.",
1249 'params' => [
'ref' =>
"Exact product reference."]
1252 'suffix' =>
'get_by_barcode',
1253 'description' =>
"One product by its barcode (EAN/UPC); same options as get.",
1254 'params' => [
'barcode' =>
"Barcode value as printed."]
1256 'getPurchasePrices' => [
1257 'suffix' =>
'purchase_prices_list',
1258 'description' =>
"Supplier prices of one product: for each supplier, the supplier reference, minimum quantity, unit purchase price and VAT. Identify the product by id, ref or barcode.",
1259 'params' => [
'id' =>
"Rowid of the product (use 0 when identifying by ref or barcode).",
'ref' =>
"Product reference, alternative to id.",
'barcode' =>
"Product barcode, alternative to id."]
1261 'getAttributes' => [
1262 'suffix' =>
'attributes_list',
1263 'module' =>
'variants',
1264 'description' =>
"Variant attributes (e.g. Size, Color) defined in the catalog."
1267 'suffix' =>
'variants_list',
1268 'module' =>
'variants',
1269 'description' =>
"Variants of one parent product.",
1270 'params' => [
'id' =>
'Rowid of the PARENT product.',
'includestock' =>
"1 to add stock data on each variant."]
1273 'suffix' =>
'stock',
1277 'module' =>
'stock',
1281 'right' => [[
'produit',
'lire'], [
'stock',
'lire']],
1282 'description' =>
"Physical stock of one product: per-warehouse quantities in stock_warehouses (keyed by warehouse rowid, signed qty, with batch detail when lot tracking is on) plus the stock_reel and stock_theorique totals. Answers \"how much of product X do we have\" and \"where is it stored\". Identify the product by rowid — look it up first with api_products_list when only the ref is known.",
1284 'id' =>
"Rowid of the product.",
1285 'selected_warehouse_id' =>
"Rowid of a warehouse to return its stock only; omitted for every warehouse."
1299 'filename' =>
"Name of the file to create (e.g. 'photo.jpg').",
1300 'filecontent' =>
"Content of the file. Omit to create an empty file.",
1301 'fileencoding' =>
"'base64' when filecontent is base64-encoded, empty (default) for plain text.",
1302 'overwriteifexists' =>
"1 to overwrite a file that already exists with the same name, 0 (default) to fail instead.",
1303 'createdirifnotexists' =>
"1 (default) to create the subdirectories when they do not exist, 0 to fail."
1305 $this->enrichments[
'documents_objects'] = [
1306 'endpoint' =>
'documents',
1307 'label' =>
'documents attached to business objects',
1309 'getDocumentsListByElement' => [
1311 'description' =>
"List the files attached to a business object (invoice, proposal, order, third party, product, project...). Answers \"what files does this invoice have\", \"show the documents of that order\", \"is there anything attached to this third party\". Returns each file name, size, date and a download link, never the content. Give the object by id or by ref; search for it first when neither is known. A draft ref is written in parentheses, like (PROV42): pass it with them. Not for the free directory tree of the DMS (use the api_documents_manual tools) nor for the public medias of the website (use the api_documents_medias tools).",
1313 'modulepart' =>
"Object type: invoice, supplier_invoice, order, supplier_order, propal (proposal), supplier_proposal, shipment, societe (third party), product, contract, ficheinter (intervention), project, project_task, ticket, expensereport, holiday, member, actioncomm (event), category, user.",
1314 'id' =>
"Rowid of the object, when known.",
1315 'ref' =>
"Reference of the object, when the id is unknown."
1321 'suffix' =>
'download',
1322 'description' =>
"Download one file attached to a business object and return its content base64-encoded. Give modulepart (the object type) and original_file, the path relative to that area. List the files of the object with api_documents_objects_list first to learn the path, or build it from the object (e.g. 'FA2401-0001/FA2401-0001.pdf'). Only for small files: the whole content travels in the answer.",
1324 'modulepart' =>
"Object type: same values as api_documents_objects_list modulepart.",
1325 'original_file' =>
"Relative path with filename, relative to the area (e.g. 'FA2401-0001/FA2401-0001.pdf')."
1332 'suffix' =>
'upload',
1333 'description' =>
"Attach a file to a business object. Give modulepart (the object type), the ref of the object (its directory is derived from it; for a third party or a contact use the rowid instead), and filecontent base64-encoded with fileencoding='base64'. The user confirms before anything is written.",
1335 'preview' =>
'AIPreviewUploadDocument',
1336 'required' => [
'filename',
'modulepart',
'ref'],
1337 'args' => [
'filename',
'modulepart']
1340 'filename' => $uploadParams[
'filename'],
1341 'modulepart' =>
"Object type: same values as api_documents_objects_list modulepart.",
1342 'ref' =>
"Reference of the business object the file is attached to (rowid for a third party or a contact).",
1343 'filecontent' => $uploadParams[
'filecontent'],
1344 'fileencoding' => $uploadParams[
'fileencoding'],
1345 'overwriteifexists' => $uploadParams[
'overwriteifexists']
1350 $this->enrichments[
'documents_manual'] = [
1351 'endpoint' =>
'documents',
1352 'label' =>
'documents of the DMS free directory tree',
1354 'getDocumentsListByDirectory' => [
1357 'fixed_params' => [
'modulepart' =>
'ecm'],
1358 'description' =>
"List the files and subdirectories of a directory of the DMS (ECM module) manual area, the free directory tree where users file documents not linked to a business object. Answers \"what is in the Contracts folder\", \"find the file named agreement\". Returns for each entry its type (dir or file), its path to give to api_documents_manual_download, size, date and a download link, never the content. Start at the root (empty subdir), then go down.",
1360 'subdir' =>
"Directory to list, relative to the root of the DMS manual tree (e.g. 'Contracts/2024'). Empty for the root.",
1361 'recursive' =>
"1 to also list the content of the subdirectories, 0 (default) for this directory only.",
1362 'search' =>
"Return only the files and directories whose name contains this text.",
1363 'sortfield' =>
"Sort on 'name' (default), 'date' or 'size'.",
1364 'sortorder' =>
"'asc' (default) or 'desc'."
1368 'suffix' =>
'download',
1370 'fixed_params' => [
'modulepart' =>
'ecm'],
1371 'description' =>
"Download one file of the DMS (ECM module) manual area, the free directory tree where users file documents not linked to a business object, and return its content base64-encoded. Give original_file, the path relative to the root of that tree (e.g. 'MyDirectory/MySubDirectory/agreement.pdf'): the path api_documents_manual_list returns. Only for small files: the whole content travels in the answer.",
1373 'original_file' =>
"Relative path with filename, relative to the root of the DMS manual tree (e.g. 'Contracts/2024/agreement.pdf')."
1377 'suffix' =>
'upload',
1379 'fixed_params' => [
'modulepart' =>
'ecm'],
1380 'description' =>
"Upload a file into the DMS (ECM module) manual area, the free directory tree where users file documents not linked to a business object. Give subdir (the directory inside the tree, preferably an existing one) and filecontent base64-encoded with fileencoding='base64'. The user confirms before anything is written.",
1382 'preview' =>
'AIPreviewUploadDocument',
1383 'required' => [
'filename'],
1384 'args' => [
'filename',
'modulepart']
1387 'filename' => $uploadParams[
'filename'],
1388 'subdir' =>
"Directory inside the DMS manual tree (e.g. 'Contracts/2024'). Empty for the root.",
1389 'filecontent' => $uploadParams[
'filecontent'],
1390 'fileencoding' => $uploadParams[
'fileencoding'],
1391 'overwriteifexists' => $uploadParams[
'overwriteifexists'],
1392 'createdirifnotexists' => $uploadParams[
'createdirifnotexists']
1398 $this->enrichments[
'documents_medias'] = [
1399 'endpoint' =>
'documents',
1400 'label' =>
'public medias of the website module',
1402 'getDocumentsListByDirectory' => [
1404 'fixed_params' => [
'modulepart' =>
'medias'],
1405 'description' =>
"List the files and subdirectories of a directory of the public medias directory, the files (images, videos, documents) published and reachable from the websites of the website module. Answers \"which images does the website mywebsite use\", \"is there a logo in the medias\". Returns for each entry its type (dir or file), its path to give to api_documents_medias_download, size, date and a download link, never the content. The images of a website are usually in 'image/<website ref>'.",
1407 'subdir' =>
"Directory to list, relative to the medias directory (e.g. 'image/mywebsite'). Empty for the root.",
1408 'recursive' =>
"1 to also list the content of the subdirectories, 0 (default) for this directory only.",
1409 'search' =>
"Return only the files and directories whose name contains this text.",
1410 'sortfield' =>
"Sort on 'name' (default), 'date' or 'size'.",
1411 'sortorder' =>
"'asc' (default) or 'desc'."
1415 'suffix' =>
'download',
1416 'fixed_params' => [
'modulepart' =>
'medias'],
1417 'description' =>
"Download one file of the public medias directory, the files (images, videos, documents) published and reachable from the websites of the website module, and return its content base64-encoded. Give original_file, the path inside that directory (e.g. 'image/mywebsite/picture.png'): the path api_documents_medias_list returns. Only for small files: the whole content travels in the answer.",
1419 'original_file' =>
"Relative path with filename inside the medias directory (e.g. 'image/mywebsite/picture.png')."
1423 'suffix' =>
'upload',
1424 'fixed_params' => [
'modulepart' =>
'medias'],
1425 'description' =>
"Upload a file into the public medias directory, where the images, videos and documents of the websites of the website module are stored: the file becomes publicly reachable. Give subdir (e.g. 'image/mywebsite' for the images of the website mywebsite) and filecontent base64-encoded with fileencoding='base64'. The user confirms before anything is written.",
1427 'preview' =>
'AIPreviewUploadDocument',
1428 'required' => [
'filename',
'subdir'],
1429 'args' => [
'filename',
'modulepart']
1432 'filename' => $uploadParams[
'filename'],
1433 'subdir' =>
"Directory inside the medias directory (e.g. 'image/mywebsite' for the images of the website mywebsite).",
1434 'filecontent' => $uploadParams[
'filecontent'],
1435 'fileencoding' => $uploadParams[
'fileencoding'],
1436 'overwriteifexists' => $uploadParams[
'overwriteifexists'],
1437 'createdirifnotexists' => $uploadParams[
'createdirifnotexists']
1474 global $hookmanager;
1475 if (!is_object($hookmanager)) {
1476 if (!defined(
'DOL_DOCUMENT_ROOT')) {
1479 require_once DOL_DOCUMENT_ROOT .
'/core/class/hookmanager.class.php';
1483 $hookmanager->initHooks(array(
'aimcp'));
1487 $hookmanager->executeHooks(
'addMcpApiBridgeEnrichments', array(
'db' => $this->db,
'user' => $this->
user,
'conf' => isset($this->
conf) ? $this->
conf :
null), $this, $action);
1489 if (!is_array($hookmanager->resArray)) {
1493 foreach ($hookmanager->resArray as $moduleEnrichments) {
1494 if (!is_array($moduleEnrichments)) {
1497 foreach ($moduleEnrichments as $key => $entry) {
1498 $key = strtolower((
string) $key);
1499 if (isset($this->enrichments[$key]) || !is_array($entry)) {
1502 if (empty($entry[
'methods']) || !is_array($entry[
'methods'])) {
1505 $this->enrichments[$key] = $entry;
1508 }
catch (\Throwable $e) {
1509 dol_syslog(
"[ToolApiBridge] Error during 'addMcpApiBridgeEnrichments' hook execution: ".$e->getMessage(), LOG_ERR);
1526 $pagination =
"Set to true to get {data, pagination:{total,page,page_count,limit}}; use it to know how many records match.";
1528 $this->enrichments[
'bankaccounts'] = array(
1529 'label' =>
'bank and cash accounts',
1532 'default_properties' =>
'id,ref,label,bank,currency_code,clos,courant',
1533 'description' =>
"Bank and cash accounts: ref, label, bank, currency. clos: 0 open, 1 closed. courant: 0 savings, 1 current, 2 cash. The balance is in api_bankaccounts_balance, the transactions in api_bankaccounts_lines."
1535 'get' => array(
'description' =>
"One bank account with its bank details and currency."),
1536 'getLines' => array(
1537 'suffix' =>
'lines',
1538 'description' =>
"Transactions of one bank account: date (dateo), value date (datev), amount (signed: positive is money in), label, payment type, reconciliation (rappro 1 when reconciled). Only the most recent 50 are returned: restrict the period with sqlfilters. Here the field names have NO 't.' prefix, e.g. \"(dateo:>=:'2026-01-01')\" or \"(label:like:'%rent%')\".",
1539 'params' => array(
'id' =>
"Rowid of the bank account."),
1545 'getBalance' => array(
1546 'suffix' =>
'balance',
1547 'description' =>
"Current balance of one bank account.",
1548 'params' => array(
'id' =>
"Rowid of the bank account.")
1553 $this->enrichments[
'variouspayments'] = array(
1554 'label' =>
'miscellaneous bank payments',
1557 'description' =>
"Payments recorded directly on a bank account, outside invoices: date (datep), amount, sens (0 money out, 1 money in), label, accounting account.",
1558 'params' => array(
'pagination_data' => $pagination)
1560 'get' => array(
'description' =>
"One miscellaneous payment.")
1564 $this->enrichments[
'socialcontributions'] = array(
1565 'label' =>
'social and fiscal contributions (taxes, charges)',
1568 'description' =>
"Social and fiscal charges to pay: label, type, period, amount, paye (1 paid). Unpaid ones: sqlfilters \"(t.paye:=:0)\".",
1569 'params' => array(
'pagination_data' => $pagination)
1571 'get' => array(
'description' =>
"One social or fiscal charge."),
1572 'getPayments' => array(
1573 'suffix' =>
'payments_list',
1574 'description' =>
"Payments made on one social or fiscal charge.",
1575 'params' => array(
'id' =>
"Rowid of the charge.")
1580 $this->enrichments[
'vatpayments'] = array(
1581 'label' =>
'VAT declarations and payments',
1584 'description' =>
"VAT to pay or refund per period: label, period end (datev), amount, paye (1 paid).",
1585 'params' => array(
'pagination_data' => $pagination)
1587 'get' => array(
'description' =>
"One VAT declaration."),
1588 'getPayments' => array(
1589 'suffix' =>
'payments_list',
1590 'description' =>
"Payments made on one VAT declaration.",
1591 'params' => array(
'id' =>
"Rowid of the VAT declaration.")
1596 $this->enrichments[
'donations'] = array(
1597 'label' =>
'donations',
1600 'description' =>
"Donations received: donor, amount, date, project. Statuses (t.fk_statut): 0 draft, 1 validated (promised), 2 paid, -1 canceled.",
1602 'thirdparty_ids' =>
"Comma-separated third-party rowids to restrict to (e.g. '1,5').",
1603 'pagination_data' => $pagination
1606 'get' => array(
'description' =>
"One donation with its donor, amount and status.")
1610 $this->enrichments[
'holidays'] = array(
1611 'label' =>
'leave requests (holidays, days off)',
1614 'description' =>
"Leave requests of employees: fk_user (the employee, a USER rowid), date_debut / date_fin (start / end), leave type (fk_type). Statuses (t.statut): 1 draft, 2 waiting for approval, 3 approved, 4 canceled, 5 refused. Who is off on a day: approved ones with sqlfilters \"(t.date_debut:<=:'YYYY-MM-DD') AND (t.date_fin:>=:'YYYY-MM-DD')\".",
1616 'user_ids' =>
"Comma-separated user rowids to restrict to the requests of these employees.",
1617 'pagination_data' => $pagination
1620 'drop_fields' => array(
'description',
'note_private',
'note_public')
1623 'description' =>
"One leave request with its employee, dates, type and status.",
1624 'drop_fields' => array(
'description',
'note_private',
'note_public')
1629 $this->enrichments[
'boms'] = array(
1630 'label' =>
'bills of materials (BOM)',
1633 'description' =>
"Bills of materials: ref, label, the product it makes (fk_product), quantity made. Statuses (t.status): 0 draft, 1 validated, 9 canceled. The components are in api_boms_lines."
1635 'get' => array(
'description' =>
"One bill of materials."),
1636 'getLines' => array(
1637 'suffix' =>
'lines',
1638 'description' =>
"Components of one bill of materials: product, quantity, efficiency.",
1639 'params' => array(
'id' =>
"Rowid of the bill of materials.")
1644 $this->enrichments[
'mos'] = array(
1645 'label' =>
'manufacturing orders (MO)',
1648 'description' =>
"Manufacturing orders: ref, product to make (fk_product), quantity, bill of materials (fk_bom), planned dates. Statuses (t.status): 0 draft, 1 validated (to produce), 2 in progress, 3 produced, 9 canceled."
1650 'get' => array(
'description' =>
"One manufacturing order with what it consumes and produces.")
1654 $this->enrichments[
'productlots'] = array(
1655 'label' =>
'product lots and serial numbers',
1658 'description' =>
"Lots and serial numbers of products: batch (the number), fk_product, eat-by date (eatby), sell-by date (sellby). Lots of one product: sqlfilters \"(t.fk_product:=:ID)\".",
1659 'params' => array(
'pagination_data' => $pagination)
1661 'get' => array(
'description' =>
"One lot or serial number with its dates.")
1665 $this->enrichments[
'workstations'] = array(
1666 'label' =>
'workstations (manufacturing)',
1668 'index' => array(
'description' =>
"Workstations used in manufacturing: ref, label, type, hourly costs."),
1669 'get' => array(
'description' =>
"One workstation."),
1670 'getByRef' => array(
1671 'suffix' =>
'get_by_ref',
1672 'description' =>
"One workstation by its exact reference.",
1673 'params' => array(
'ref' =>
"Exact workstation reference.")
1678 $this->enrichments[
'knowledgemanagement'] = array(
1679 'label' =>
'knowledge base articles',
1682 'description' =>
"Knowledge base articles: ref, question, answer, language. Statuses (t.status): 0 draft, 1 validated, 9 canceled. Search the question with sqlfilters \"(t.question:like:'%word%')\".",
1684 'category' =>
"Rowid of a knowledge category to restrict the list to.",
1685 'pagination_data' => $pagination
1688 'get' => array(
'description' =>
"One knowledge base article with its question and answer.")
1692 $this->enrichments[
'memberstypes'] = array(
1693 'label' =>
'member types',
1695 'index' => array(
'description' =>
"Types of members: label, whether a subscription is due, its amount and duration."),
1696 'get' => array(
'description' =>
"One member type.")
1700 $this->enrichments[
'partnerships'] = array(
1701 'label' =>
'partnerships',
1703 'index' => array(
'description' =>
"Partnerships with third parties or members: type, dates. Statuses (t.status): 0 draft, 1 validated, 2 approved, 3 refused, 9 canceled."),
1704 'get' => array(
'description' =>
"One partnership.")
1708 $this->enrichments[
'multicurrencies'] = array(
1709 'label' =>
'currencies and exchange rates',
1711 'index' => array(
'description' =>
"Currencies in use, with their code and current rate."),
1712 'get' => array(
'description' =>
"One currency."),
1713 'getByCode' => array(
1714 'suffix' =>
'get_by_code',
1715 'description' =>
"One currency by its ISO code (e.g. 'USD').",
1716 'params' => array(
'code' =>
"ISO code of the currency.")
1718 'getRates' => array(
1719 'suffix' =>
'rates',
1720 'description' =>
"Exchange rates of one currency, the most recent 30.",
1721 'params' => array(
'id' =>
"Rowid of the currency."),
1730 $this->enrichments[
'websites'] = array(
1731 'label' =>
'websites (website module)',
1734 'description' =>
"Websites built with the website module: ref, description, main language, virtual host, home page (fk_default_home). Statuses (t.status): 0 offline, 1 online.",
1735 'default_properties' =>
'id,ref,description,lang,otherlang,status,virtualhost'
1737 'get' => array(
'description' =>
"One website."),
1738 'getByRef' => array(
1739 'suffix' =>
'get_by_ref',
1740 'description' =>
"One website by its exact reference.",
1741 'params' => array(
'ref' =>
"Exact website reference.")
1743 'indexPages' => array(
1744 'suffix' =>
'pages_list',
1745 'description' =>
"Pages of one website: pageurl (alias), title, type_container ('page', 'blogpost', 'menu', 'other', 'header', 'footer'...), lang, status (0 offline, 1 online). Blog posts are the pages with type_container 'blogpost'. Search with sqlfilters \"(t.type_container:=:'blogpost')\".",
1746 'default_properties' =>
'id,pageurl,title,description,type_container,lang,status,date_creation,author_alias',
1747 'params' => array(
'id' =>
"Rowid of the website.")
1750 'suffix' =>
'page_get',
1751 'description' =>
"One page of a website, with its HTML content.",
1752 'params' => array(
'id' =>
"Rowid of the website.",
'pageid' =>
"Rowid of the page.")
1754 'postPage' => array(
1755 'suffix' =>
'page_create',
1756 'description' =>
"Create a page (type_container 'page') or a blog post (type_container 'blogpost') in a website. Give id (rowid of the website), pageurl (alias, only a-z, 0-9, - and _), title and content (HTML, put inside a <section> tag, no PHP code). It is created offline (status 0) unless status 1 is given. The user confirms before anything is written.",
1758 'preview' =>
'AIPreviewCreateWebsitePage',
1759 'required' => array(
'id',
'pageurl',
'title'),
1760 'object' =>
'WebsitePage',
1761 'args' => array(
'title',
'pageurl',
'id'),
1762 'args_objects' => array(
'id' =>
'Website'),
1763 'right' => array(
'website',
'write')
1766 'id' =>
"Rowid of the website.",
1767 'pageurl' =>
"Alias of the page, used in its URL: only a-z, 0-9, - and _.",
1768 'title' =>
"Title of the page.",
1769 'type_container' =>
"Kind of page: 'page' (default) or 'blogpost' for an article of a blog.",
1770 'content' =>
"HTML content of the page, inside a <section> tag. No PHP code.",
1771 'description' =>
"Short description (meta description), 255 characters max.",
1772 'keywords' =>
"Keywords, separated by commas.",
1773 'lang' =>
"Language code of the page, e.g. 'en' or 'fr'. Omit for the website language.",
1774 'author_alias' =>
"Name of the author to show.",
1775 'status' =>
"0 offline (default), 1 online."
1782 $this->enrichments[
'contacts'] = array(
1783 'label' =>
'contacts (people of third parties)',
1786 'default_properties' =>
'id,firstname,lastname,poste,email,phone_pro,phone_mobile,socid,statut',
1787 'description' =>
"Contacts are the people of a third party. Contacts of one third party: thirdparty_ids. Search by name with sqlfilters on t.lastname or t.firstname. statut: 1 active, 0 inactive.",
1789 'thirdparty_ids' =>
"Comma-separated third-party rowids to restrict to (e.g. '1,5').",
1790 'pagination_data' => $pagination
1793 'get' => array(
'description' =>
"One contact with name, job title, phones, email and third party."),
1794 'getByEmail' => array(
1795 'suffix' =>
'get_by_email',
1796 'description' =>
"One contact by its exact email address.",
1797 'params' => array(
'email' =>
"Exact email address of the contact."),
1799 'needs_id' =>
"No single contact has this email (none, or several): search with api_contacts_list and sqlfilters on t.email."
1801 'getCategories' => array(
1802 'suffix' =>
'categories_list',
1803 'description' =>
"Tags (categories) of one contact.",
1804 'params' => array(
'id' =>
"Rowid of the contact.")
1814 $this->enrichments[
'objectlinks'] = array(
1815 'label' =>
'links between records',
1819 'description' =>
"One object link by its rowid: the pair it joins, (fk_source, sourcetype) to (fk_target, targettype).",
1820 'params' => array(
'id' =>
"Rowid of the object link.")
1822 'getByValues' => array(
1823 'suffix' =>
'get_by_values',
1824 'description' =>
"Whether two records are linked: give the rowid and element type of each side. Answers 'is invoice X linked to proposal Y'. Element types are names like 'propal' (proposal), 'commande' (customer order), 'facture' (customer invoice), 'contrat', 'project', 'task', 'ticket', 'actioncomm' (agenda event), 'subscription' (membership), 'shipping', 'reception'.",
1826 'fk_source' =>
"Rowid of the record the link starts from.",
1827 'sourcetype' =>
"Element type of the source record (e.g. 'propal', 'facture', 'project').",
1828 'fk_target' =>
"Rowid of the record the link points to.",
1829 'targettype' =>
"Element type of the target record (e.g. 'commande', 'task', 'ticket').",
1830 'relationtype' =>
"Relation qualifier, usually left empty."
1840 $this->enrichments[
'users'] = array(
1841 'label' =>
'users (staff accounts) and user groups',
1844 'default_properties' =>
'id,login,firstname,lastname,email,job,statut,admin,employee',
1845 'description' =>
"Users of the ERP (staff accounts): login, name, email, job, employee flag. statut: 1 active, 0 inactive. Search by name with sqlfilters on t.lastname, t.firstname or t.login. Useful when you need the rowid of a user to assign him somewhere (project, task, ticket).",
1847 'user_ids' =>
"Comma-separated user rowids to restrict to (e.g. '1,5').",
1848 'category' =>
"Rowid of a user category (tag) to restrict to its members."
1850 'right' => array(
'user',
'user',
'lire')
1853 'description' =>
"One user with login, name, email, phones, job and status.",
1854 'params' => array(
'id' =>
"Rowid of the user.",
'includepermissions' =>
"1 to also load his permission set (heavy, default 0).")
1856 'getByLogin' => array(
1857 'suffix' =>
'get_by_login',
1858 'description' =>
"One user by its exact login.",
1859 'params' => array(
'login' =>
"Exact login of the user.",
'includepermissions' =>
"1 to also load his permission set (heavy, default 0).")
1861 'getByEmail' => array(
1862 'suffix' =>
'get_by_email',
1863 'description' =>
"One user by its exact email address.",
1864 'params' => array(
'email' =>
"Exact email address of the user.",
'includepermissions' =>
"1 to also load his permission set (heavy, default 0).")
1868 'description' =>
"The user currently connected: answers 'who am I', 'my email', 'my permissions'.",
1869 'params' => array(
'includepermissions' =>
"1 to also load his permission set (heavy, default 0).")
1871 'getGroups' => array(
1872 'suffix' =>
'groups_of_user',
1873 'description' =>
"Groups a user belongs to.",
1874 'params' => array(
'id' =>
"Rowid of the user."),
1875 'right' => array(
'user',
'user',
'lire')
1877 'listGroups' => array(
1878 'suffix' =>
'groups_list',
1879 'description' =>
"All user groups (e.g. administrators, sales): name, note. Members of one group come from api_users_group_info with load_members=1.",
1881 'group_ids' =>
"Comma-separated group rowids to restrict to (e.g. '1,5')."
1884 'infoGroups' => array(
1885 'suffix' =>
'group_info',
1886 'description' =>
"One user group: name, note; set load_members=1 to include its members.",
1887 'params' => array(
'group' =>
"Rowid of the user group.",
'load_members' =>
"1 to include the members of the group (default 0).",
'includepermissions' =>
"1 to also load its permission set (heavy, default 0).")
1894 'warehouses' => array(
1895 'listProducts' => array(
1896 'suffix' =>
'products_list',
1897 'description' =>
"Products stored in one warehouse, with their stock there when includestockdata=1. Answers \"what is in warehouse X\".",
1898 'params' => array(
'id' =>
"Rowid of the warehouse.",
'includestockdata' =>
"1 to add the stock of each product.",
'pagination_data' => $pagination)
1901 'products' => array(
1902 'getSubproducts' => array(
1903 'suffix' =>
'subproducts',
1904 'description' =>
"Components of a kit (virtual product): each sub-product with its quantity.",
1905 'params' => array(
'id' =>
"Rowid of the kit product.")
1907 'getCustomerPricesPerSegment' => array(
1908 'suffix' =>
'prices_per_segment',
1910 'setup' => array(
'PRODUIT_MULTIPRICES',
'PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES'),
1911 'description' =>
"Selling prices of one product per price level (segment), when several price levels are used.",
1912 'params' => array(
'id' =>
"Rowid of the product.")
1914 'getCustomerPricesPerCustomer' => array(
1915 'suffix' =>
'prices_per_customer',
1916 'setup' => array(
'PRODUIT_CUSTOMER_PRICES',
'PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES'),
1917 'description' =>
"Selling prices of one product negotiated per customer, when customer prices are used.",
1918 'params' => array(
'id' =>
"Rowid of the product.",
'thirdparty_id' =>
"Rowid of one customer to restrict to.")
1920 'getCustomerPricesPerQuantity' => array(
1921 'suffix' =>
'prices_per_quantity',
1922 'setup' => array(
'PRODUIT_CUSTOMER_PRICES_BY_QTY'),
1923 'description' =>
"Selling prices of one product by quantity, when prices by quantity are used.",
1924 'params' => array(
'id' =>
"Rowid of the product.")
1926 'getSupplierProducts' => array(
1927 'suffix' =>
'supplier_products_list',
1928 'description' =>
"Products with their supplier prices: for each, the suppliers that sell it, their reference and price. Restrict to one supplier with 'supplier'.",
1929 'params' => array(
'supplier' =>
"Rowid of one supplier to restrict to.",
'mode' =>
"0 all, 1 products only, 2 services only.",
'category' =>
"Rowid of a product category.")
1931 'getCategories' => array(
1932 'suffix' =>
'categories_list',
1933 'description' =>
"Tags (categories) of one product.",
1934 'params' => array(
'id' =>
"Rowid of the product.")
1937 'projects' => array(
1938 'getContacts' => array(
1939 'suffix' =>
'contacts_list',
1940 'description' =>
"People of one project: internal users and external contacts, with their role (project leader, contributor...).",
1941 'params' => array(
'id' =>
"Rowid of the project.",
'type' =>
"'internal' or 'external' to restrict, empty for both.")
1943 'getTimespent' => array(
1944 'suffix' =>
'timespent_list',
1945 'description' =>
"Summary of the time spent on each task of one project (first 100 tasks): total duration in seconds and the users who recorded it. The time records themselves are in api_projects_timespent_all or api_tasks_timespent_list.",
1946 'params' => array(
'id' =>
"Rowid of the project."),
1950 'listTimespent' => array(
1951 'suffix' =>
'timespent_all',
1952 'description' =>
"Time recorded across projects, with project, task, user, date and duration in seconds. Restrict with thirdparty_ids or sqlfilters (e.g. a period on t.element_date).",
1953 'params' => array(
'thirdparty_ids' =>
"Comma-separated third-party rowids.",
'pagination_data' => $pagination)
1957 'getOrderShipments' => array(
1958 'suffix' =>
'shipments_list',
1959 'description' =>
"Shipments made for one sale order, with what each shipped.",
1960 'params' => array(
'id' =>
"Rowid of the sale order.")
1962 'getContacts' => array(
1963 'suffix' =>
'contacts_list',
1964 'description' =>
"Contacts of one sale order with their role (billing, shipping, follow-up...).",
1965 'params' => array(
'id' =>
"Rowid of the sale order.",
'type' =>
"Role code to restrict to, e.g. BILLING, SHIPPING, CUSTOMER.")
1968 'proposals' => array(
1969 'getContacts' => array(
1970 'suffix' =>
'contacts_list',
1971 'description' =>
"Contacts of one commercial proposal with their role.",
1972 'params' => array(
'id' =>
"Rowid of the proposal.",
'type' =>
"Role code to restrict to.")
1975 'invoices' => array(
1976 'getContacts' => array(
1977 'suffix' =>
'contacts_list',
1978 'description' =>
"Contacts of one customer invoice with their role.",
1979 'params' => array(
'id' =>
"Rowid of the invoice.",
'type' =>
"Role code to restrict to.")
1981 'indexTemplateInvoices' => array(
1982 'suffix' =>
'templates_list',
1983 'description' =>
"Recurring invoice templates: customer, frequency, next generation date, amounts. Set withLines=false for lists.",
1984 'params' => array(
'thirdparty_ids' =>
"Comma-separated third-party rowids.",
'withLines' =>
"false to omit the lines.",
'pagination_data' => $pagination)
1986 'getTemplateInvoice' => array(
1987 'suffix' =>
'template_get',
1988 'description' =>
"One recurring invoice template with its lines and frequency.",
1989 'params' => array(
'id' =>
"Rowid of the template.")
1992 'supplier_invoices' => array(
1993 'getPayments' => array(
1994 'suffix' =>
'payments_list',
1995 'description' =>
"Payments already made on one supplier invoice: amount, date, payment mode, bank account.",
1996 'params' => array(
'id' =>
"Rowid of the supplier invoice.")
1999 'expensereports' => array(
2000 'getLines' => array(
2001 'suffix' =>
'lines',
2002 'description' =>
"Lines of one expense report: date, expense type, amounts, VAT.",
2003 'params' => array(
'id' =>
"Rowid of the expense report.")
2005 'getAllPayments' => array(
2006 'suffix' =>
'payments_list',
2007 'description' =>
"Payments of expense reports: amount, date, payment mode."
2010 'interventions' => array(
2011 'getContacts' => array(
2012 'suffix' =>
'contacts_list',
2013 'description' =>
"Contacts of one intervention with their role.",
2014 'params' => array(
'id' =>
"Rowid of the intervention.",
'type' =>
"Role code to restrict to.")
2017 'thirdparties' => array(
2018 'getByBarcode' => array(
2019 'suffix' =>
'get_by_barcode',
2020 'description' =>
"One third party by its barcode.",
2021 'params' => array(
'barcode' =>
"Barcode value.")
2023 'getFixedAmountDiscounts' => array(
2024 'suffix' =>
'discounts_list',
2025 'description' =>
"Fixed-amount discounts and credits of one third party: available, or already used on an invoice.",
2026 'params' => array(
'id' =>
"Rowid of the third party.",
'mode' =>
"'customer' (default) or 'supplier'.",
'filter' =>
"'none' (all), 'available' or 'used'.")
2028 'getSalesRepresentatives' => array(
2029 'suffix' =>
'sales_representatives_list',
2030 'description' =>
"Sales representatives (users) following one third party.",
2031 'params' => array(
'id' =>
"Rowid of the third party.",
'mode' =>
"0 full records, 1 rowids only.")
2033 'getCategories' => array(
2034 'suffix' =>
'categories_list',
2035 'description' =>
"Customer tags (categories) of one third party.",
2036 'params' => array(
'id' =>
"Rowid of the third party.")
2038 'getSupplierCategories' => array(
2039 'suffix' =>
'supplier_categories_list',
2040 'description' =>
"Supplier tags (categories) of one third party.",
2041 'params' => array(
'id' =>
"Rowid of the third party.")
2044 'categories' => array(
2045 'getListForObject' => array(
2046 'suffix' =>
'of_object_list',
2047 'description' =>
"Tags (categories) of any object: give its rowid and type.",
2048 'params' => array(
'id' =>
"Rowid of the object.",
'type' =>
"Its type: 'product', 'customer', 'supplier', 'contact', 'member', 'project', 'user', 'warehouse', 'actioncomm', 'ticket'.")
2052 'getByThirdparty' => array(
2053 'suffix' =>
'get_by_thirdparty',
2054 'description' =>
"The member linked to one third party.",
2055 'params' => array(
'thirdparty' =>
"Rowid of the third party.")
2057 'getNbByYear' => array(
2058 'suffix' =>
'count_by_year',
2059 'description' =>
"Number of new members per year."
2061 'getNbByMonth' => array(
2062 'suffix' =>
'count_by_month',
2063 'description' =>
"Number of new members per month of one year.",
2064 'params' => array(
'year' =>
"Year, e.g. 2026.")
2066 'getAmountByMonth' => array(
2067 'suffix' =>
'subscriptions_amount_by_month',
2068 'description' =>
"Amount of subscriptions per month of one year.",
2069 'params' => array(
'year' =>
"Year, e.g. 2026.")
2073 foreach ($more as $key => $methods) {
2074 if (!isset($this->enrichments[$key])) {
2077 foreach ($methods as $method => $meta) {
2078 $this->enrichments[$key][
'methods'][$method] = $meta;
2096 private function addLineMethod($label, $lookupTool, $class, array $right, $buy =
false, array $rename = array(), array $defaults = array())
2098 $lookup = (substr($lookupTool, -7) ===
'_by_ref') ? $lookupTool : $lookupTool.
" with sqlfilters (t.ref:=:'THEREF')";
2100 $description =
"Add ONE line to an existing ".$label.
". Only a DRAFT ".$label.
" (status 0) accepts new lines. ";
2101 $description .=
"Give 'id' (".$label.
" rowid; when only the ref is known, look it up with ".$lookup.
") and the line fields: product_ref (product ref or exact label) and qty, ";
2102 $description .=
"optionally subprice (unit price excl. tax, ".($buy ?
"supplier purchase price" :
"catalogue price").
" when omitted), remise_percent (discount %), tva_tx (VAT rate, default rate when omitted), desc (text of a free line without product). ";
2103 $description .=
"Call it once per line to add. The user confirms before anything is written.";
2107 'preview' =>
'AIPreviewAddDocumentLine',
2115 $write[
'buy'] =
true;
2118 $write[
'rename'] = $rename;
2121 $write[
'defaults'] = $defaults;
2125 'suffix' =>
'add_line',
2126 'description' => $description,
2129 'id' =>
"Rowid of the draft ".$label.
" to add the line to.",
2130 'request_data' =>
"The line, as an object: {\"product_ref\": \"PINKDRESS\", \"qty\": 2}, optionally with subprice, remise_percent, tva_tx, desc. The fields may also be given flat, next to 'id'."
2146 $advanced = $this->
setupValue(
'MAIN_USE_ADVANCED_PERMS');
2150 $this->enrichments[
'thirdparties'][
'methods'][
'put'] = $this->
updateMethod(
'third party',
'Societe', array(
'societe',
'creer'), array(
2151 'name' =>
"Company or person name.",
2152 'name_alias' =>
"Trade name, the name people use.",
2153 'address' =>
"Street address.",
2154 'zip' =>
"Postal code.",
2156 'phone' =>
"Phone.",
2157 'phone_mobile' =>
"Mobile phone.",
2159 'email' =>
"Email of the company.",
2160 'url' =>
"Website.",
2161 'tva_intra' =>
"Intra-community VAT number.",
2162 'note_public' =>
"Public note.",
2163 'note_private' =>
"Private note.",
2164 'client' =>
"1 customer, 2 prospect, 3 both, 0 none.",
2165 'fournisseur' =>
"1 supplier, 0 not a supplier.",
2166 'status' =>
"1 open, 0 closed."
2169 $productfields = array(
2170 'label' =>
"Label.",
2171 'description' =>
"Description.",
2172 'status' =>
"On sale: 1 yes, 0 no.",
2173 'status_buy' =>
"On purchase: 1 yes, 0 no.",
2174 'weight' =>
"Weight.",
2175 'note_public' =>
"Public note.",
2176 'note_private' =>
"Private note."
2181 $productfields[
'price'] =
"Selling price excl. tax.";
2183 $this->enrichments[
'products'][
'methods'][
'put'] = $this->
updateMethod(
'product',
'Product', array(
'produit',
'creer'), $productfields,
'ref');
2185 $this->enrichments[
'contacts'][
'methods'][
'post'] = array(
2186 'suffix' =>
'create',
2187 'description' =>
"Add a contact (a person), usually at a third party. Give lastname, and socid or simply the third party name when the person belongs to a company: it is resolved here. The user confirms before anything is written.",
2189 'preview' =>
'AIPreviewAddContact',
2190 'required' => array(
'lastname'),
2191 'object' =>
'Contact',
2192 'thirdparty' =>
'socid',
2193 'thirdparty_optional' =>
true,
2194 'args' => array(
'_name',
'_at'),
2195 'right' => array(
'societe',
'contact',
'creer')
2198 'lastname' =>
"Last name.",
2199 'firstname' =>
"First name.",
2200 'socid' =>
"Third party: rowid, or its name. Omit for a contact with no company.",
2201 'poste' =>
"Job title.",
2202 'email' =>
"Email.",
2203 'phone_pro' =>
"Work phone.",
2204 'phone_mobile' =>
"Mobile phone."
2207 $this->enrichments[
'contacts'][
'methods'][
'put'] = $this->
updateMethod(
'contact',
'Contact', array(
'societe',
'contact',
'creer'), array(
2208 'firstname' =>
"First name.",
2209 'lastname' =>
"Last name.",
2210 'poste' =>
"Job title.",
2211 'email' =>
"Email.",
2212 'phone_pro' =>
"Work phone.",
2213 'phone_perso' =>
"Personal phone.",
2214 'phone_mobile' =>
"Mobile phone.",
2215 'address' =>
"Street address.",
2216 'zip' =>
"Postal code.",
2218 'note_public' =>
"Public note.",
2219 'note_private' =>
"Private note.",
2220 'statut' =>
"1 active, 0 inactive."
2225 $this->enrichments[
'invoices'][
'methods'][
'validate'] = $this->
validateMethod(
'customer invoice',
'Facture',
'AIPreviewValidateInvoice', $advanced ? array(
'facture',
'invoice_advance',
'validate') : array(
'facture',
'creer'), array(
'force_number' =>
'',
'notrigger' => 0),
'STOCK_CALCULATE_ON_BILL');
2226 $this->enrichments[
'orders'][
'methods'][
'validate'] = $this->
validateMethod(
'sale order',
'Commande',
'AIPreviewValidateOrder', $advanced ? array(
'commande',
'order_advance',
'validate') : array(
'commande',
'creer'), array(
'notrigger' => 0),
'STOCK_CALCULATE_ON_VALIDATE_ORDER');
2227 $this->enrichments[
'proposals'][
'methods'][
'validate'] = $this->
validateMethod(
'commercial proposal',
'Propal',
'AIPreviewValidateProposal', $advanced ? array(
'propal',
'propal_advance',
'validate') : array(
'propal',
'creer'), array(
'notrigger' => 0),
'');
2233 $this->enrichments[
'receptions'][
'methods'][
'validate'] = $this->
validateMethod(
'supplier reception',
'Reception', $receptionMovesStock ?
'AIPreviewValidateReceptionStock' :
'AIPreviewValidateReception', $advanced ? array(
'reception',
'reception_advance',
'validate') : array(
'reception',
'creer'), array(
'notrigger' => 0),
'');
2234 $this->enrichments[
'shipments'][
'methods'][
'validate'] = $this->
validateMethod(
'shipment',
'Expedition', $shipmentMovesStock ?
'AIPreviewValidateShipmentStock' :
'AIPreviewValidateShipment', $advanced ? array(
'expedition',
'shipping_advance',
'validate') : array(
'expedition',
'creer'), array(
'notrigger' => 0),
'');
2235 if ($receptionMovesStock) {
2236 $this->enrichments[
'receptions'][
'methods'][
'validate'][
'description'] .=
" On this Dolibarr, validating a reception brings the received goods into the stock of their warehouses.";
2238 if ($shipmentMovesStock) {
2239 $this->enrichments[
'shipments'][
'methods'][
'validate'][
'description'] .=
" On this Dolibarr, validating a shipment takes the shipped goods out of stock.";
2243 $this->enrichments[
'invoices'][
'methods'][
'addPaymentDistributed'] = array(
2244 'suffix' =>
'add_payment',
2245 'description' =>
"Record a payment received on a VALIDATED customer invoice. Give 'id' (rowid, or its ref), and 'amount' only for a partial payment: by default what remains is paid. payment_mode is how it was paid (cash, cheque, transfer, card, or a code like LIQ, CHQ, VIR, CB); bank_account is the account it went into (name or rowid, may be omitted when there is only one). The user confirms before anything is written.",
2247 'kind' =>
'payment',
2248 'preview' =>
'AIPreviewPayInvoice',
2249 'object' =>
'Facture',
2250 'label' =>
'customer invoice',
2253 'fixed' => array(
'closepaidinvoices' =>
'yes',
'accepthigherpayment' =>
false,
'ref_ext' =>
''),
2254 'right' => array(
'facture',
'paiement')
2257 'id' =>
"The invoice: rowid, or its ref.",
2258 'amount' =>
"Amount received, incl. tax. Omit to pay what remains.",
2259 'payment_mode' =>
"How it was paid: cash, cheque, transfer, card, or a payment code.",
2260 'bank_account' =>
"Bank account it was paid into: name, ref or rowid. Omit when there is only one.",
2261 'date' =>
"Payment date YYYY-MM-DD. Omit for today.",
2262 'num_payment' =>
"Cheque or transfer number.",
2263 'issuer' =>
"Who wrote the cheque, needed for a cheque.",
2264 'comment' =>
"Note."
2271 'invoices' => array(
'customer invoice',
'Facture', array(
'facture',
'supprimer')),
2272 'orders' => array(
'sale order',
'Commande', array(
'commande',
'supprimer')),
2273 'proposals' => array(
'commercial proposal',
'Propal', array(
'propal',
'supprimer')),
2274 'supplier_invoices' => array(
'supplier invoice',
'FactureFournisseur', array(
'fournisseur',
'facture',
'supprimer')),
2275 'supplier_proposals' => array(
'supplier proposal',
'SupplierProposal', array(
'supplier_proposal',
'supprimer')),
2276 'contracts' => array(
'contract',
'Contrat', array(
'contrat',
'supprimer')),
2277 'interventions' => array(
'intervention',
'Fichinter', array(
'ficheinter',
'supprimer'))
2279 foreach ($deletes as $key => $d) {
2280 $this->enrichments[$key][
'methods'][
'delete'] = $this->
deleteMethod($d[0], $d[1], $d[2]);
2285 'proposals' => array(
'commercial proposal',
'Propal', array(
'propal',
'creer'),
'product'),
2286 'orders' => array(
'sale order',
'Commande', array(
'commande',
'creer'),
'product'),
2287 'invoices' => array(
'customer invoice',
'Facture', array(
'facture',
'creer'),
'product'),
2288 'supplier_invoices' => array(
'supplier invoice',
'FactureFournisseur', array(
'fournisseur',
'facture',
'creer'),
'supplier'),
2289 'contracts' => array(
'contract',
'Contrat', array(
'contrat',
'creer'),
'contract'),
2290 'interventions' => array(
'intervention',
'Fichinter', array(
'ficheinter',
'creer'),
'intervention')
2292 foreach ($lines as $key => $l) {
2293 $this->enrichments[$key][
'methods'][
'putLine'] = $this->
lineMethod(
'update', $l[0], $l[1], $l[2], $l[3]);
2294 $this->enrichments[$key][
'methods'][
'deleteLine'] = $this->
lineMethod(
'delete', $l[0], $l[1], $l[2], $l[3]);
2297 $this->enrichments[
'contracts'][
'methods'][
'postLine'] = $this->
addLineMethod(
'contract',
'api_contracts_list',
'Contrat', array(
'contrat',
'creer'),
false, array(), array(
'price_base_type' =>
'HT',
'localtax1_tx' => 0,
'localtax2_tx' => 0,
'remise_percent' => 0,
'date_start' =>
'',
'date_end' =>
'',
'subprice_excl_tax' => 0,
'info_bits' => 0,
'fk_fournprice' =>
null,
'pa_ht' => 0,
'array_options' => array(),
'fk_unit' =>
null,
'rang' => -1));
2298 $this->enrichments[
'interventions'][
'methods'][
'postLine'] = $this->
lineMethod(
'add',
'intervention',
'Fichinter', array(
'ficheinter',
'creer'),
'intervention');
2301 $project = array(
'type' => array(
'integer',
'null'),
'minimum' => 1,
'description' =>
'Rowid of the project, or null to unlink it.');
2302 $date = array(
'type' => array(
'integer',
'null'),
'minimum' => 0,
'description' =>
'Unix timestamp, or null to clear.');
2303 $text = array(
'type' =>
'string');
2304 $this->enrichments[
'proposals'][
'methods'][
'put'] = $this->
headerUpdateMethod(
'commercial proposal',
'Propal', array(
'propal',
'creer'), array(
'propal',
'lire'), array(
'propal',
'',
''),
'propal', array(
2305 'ref_client' => array($text,
'RefCustomer'),
'note_public' => array($text,
'NotePublic'),
'note_private' => array($text,
'NotePrivate'),
2306 'fk_project' => array($project,
'Project')
2308 $this->enrichments[
'orders'][
'methods'][
'put'] = $this->
headerUpdateMethod(
'sale order',
'Commande', array(
'commande',
'creer'), array(
'commande',
'lire'), array(
'commande',
'',
''),
'commande', array(
2309 'ref_client' => array($text,
'RefCustomer'),
'note_public' => array($text,
'NotePublic'),
'note_private' => array($text,
'NotePrivate'),
2310 'delivery_date' => array($date,
'DeliveryDate'),
'fk_project' => array($project,
'Project')
2312 $this->enrichments[
'invoices'][
'methods'][
'put'] = $this->
headerUpdateMethod(
'customer invoice',
'Facture', array(
'facture',
'creer'), array(
'facture',
'lire'), array(
'facture',
'',
''),
'facture', array(
2313 'ref_client' => array($text,
'RefCustomer'),
'note_public' => array($text,
'NotePublic'),
'note_private' => array($text,
'NotePrivate'),
2314 'date_lim_reglement' => array($date,
'DateMaxPayment'),
'fk_project' => array($project,
'Project')
2316 $this->enrichments[
'supplier_invoices'][
'methods'][
'put'] = $this->
headerUpdateMethod(
'supplier invoice',
'FactureFournisseur', array(
'fournisseur',
'facture',
'creer'), array(
'fournisseur',
'facture',
'lire'), array(
'fournisseur',
'facture_fourn',
'facture'),
'facture_fourn', array(
2317 'ref_supplier' => array($text,
'RefSupplier'),
'label' => array($text,
'Label'),
'note_public' => array($text,
'NotePublic'),
'note_private' => array($text,
'NotePrivate'),
2318 'date_echeance' => array($date,
'DateMaxPayment'),
'fk_project' => array($project,
'Project')
2320 $this->enrichments[
'supplier_proposals'][
'methods'][
'put'] = $this->
headerUpdateMethod(
'supplier proposal',
'SupplierProposal', array(
'supplier_proposal',
'creer'), array(
'supplier_proposal',
'lire'), array(
'supplier_proposal',
'',
''),
'supplier_proposal', array(
2321 'note_public' => array($text,
'NotePublic'),
'note_private' => array($text,
'NotePrivate'),
2322 'delivery_date' => array($date,
'DeliveryDate'),
'fk_project' => array($project,
'Project')
2324 $this->enrichments[
'contracts'][
'methods'][
'put'] = $this->
headerUpdateMethod(
'contract',
'Contrat', array(
'contrat',
'creer'), array(
'contrat',
'lire'), array(
'contrat',
'',
''),
'contrat', array(
2325 'ref_customer' => array($text,
'RefCustomer'),
'ref_supplier' => array($text,
'RefSupplier'),
'note_public' => array($text,
'NotePublic'),
'note_private' => array($text,
'NotePrivate'),
2326 'fk_project' => array($project,
'Project')
2328 $this->enrichments[
'interventions'][
'methods'][
'put'] = $this->
headerUpdateMethod(
'intervention',
'Fichinter', array(
'ficheinter',
'creer'), array(
'ficheinter',
'lire'), array(
'ficheinter',
'',
''),
'fichinter', array(
2329 'description' => array($text,
'Description'),
'ref_client' => array($text,
'RefCustomer'),
'note_public' => array($text,
'NotePublic'),
'note_private' => array($text,
'NotePrivate'),
2330 'fk_project' => array($project,
'Project')
2333 $this->enrichments[
'interventions'][
'methods'][
'post'] = array(
2334 'suffix' =>
'create',
2335 'description' =>
"Create a DRAFT intervention (field service) for a third party. Give socid (rowid, or simply the name: it is resolved here) and description; fk_project (rowid or ref) is optional. The user confirms before anything is written.",
2337 'preview' =>
'AIPreviewCreateIntervention',
2338 'required' => array(
'socid',
'description'),
2339 'object' =>
'Fichinter',
2340 'thirdparty' =>
'socid',
2341 'project' =>
'fk_project',
2342 'args' => array(
'_who',
'description'),
2344 'defaults' => array(
'fk_project' => 0),
2345 'right' => array(
'ficheinter',
'creer')
2348 'socid' =>
"Third party: rowid, or its name.",
2349 'description' =>
"What the intervention is about.",
2350 'fk_project' =>
"Project: rowid or ref. Optional."
2354 $this->enrichments[
'contracts'][
'methods'][
'post'] = array(
2355 'suffix' =>
'create',
2356 'description' =>
"Create a DRAFT contract for a third party; its services are added in Dolibarr. Give socid (rowid, or simply the name: it is resolved here). The user confirms before anything is written.",
2358 'preview' =>
'AIPreviewCreateContract',
2359 'required' => array(
'socid'),
2360 'object' =>
'Contrat',
2361 'thirdparty' =>
'socid',
2362 'args' => array(
'_who'),
2363 'dates' => array(
'date_contrat'),
2365 'defaults' => array(
'date_contrat' =>
'now',
'commercial_signature_id' =>
'me',
'commercial_suivi_id' =>
'me'),
2366 'right' => array(
'contrat',
'creer')
2369 'socid' =>
"Third party: rowid, or its name.",
2370 'ref_customer' =>
"The customer's own reference.",
2371 'date_contrat' =>
"Date of the contract YYYY-MM-DD. Omit for today.",
2372 'note_public' =>
"Public note."
2376 $this->enrichments[
'projects'][
'methods'][
'post'] = array(
2377 'suffix' =>
'create',
2378 'description' =>
"Create a project, with its reference from the numbering. Give title; socid (rowid or simply the name) when the project is for a third party. The user confirms before anything is written.",
2380 'preview' =>
'AIPreviewCreateProject',
2381 'required' => array(
'title'),
2382 'object' =>
'Project',
2383 'thirdparty' =>
'socid',
2384 'thirdparty_optional' =>
true,
2385 'args' => array(
'title',
'_who'),
2386 'dates' => array(
'date_start',
'date_end'),
2387 'defaults' => array(
'ref' =>
'auto',
'date_start' =>
'now'),
2390 'creator_contact' =>
'PROJECTLEADER',
2391 'right' => array(
'projet',
'creer')
2394 'title' =>
"Project title.",
2395 'socid' =>
"Third party: rowid, or its name. Optional.",
2396 'description' =>
"Description.",
2397 'date_start' =>
"Start date YYYY-MM-DD. Omit for today.",
2398 'date_end' =>
"End date YYYY-MM-DD.",
2399 'budget_amount' =>
"Budget."
2403 $this->enrichments[
'tasks'][
'methods'][
'post'] = array(
2404 'suffix' =>
'create',
2405 'description' =>
"Create a task in a project, with its reference from the numbering. Give label and fk_project (rowid, ref or exact title of the project). The user confirms before anything is written.",
2407 'preview' =>
'AIPreviewCreateTask',
2408 'required' => array(
'label',
'fk_project'),
2410 'project' =>
'fk_project',
2411 'args' => array(
'label',
'_project'),
2412 'dates' => array(
'date_start',
'date_end'),
2413 'hours' => array(
'planned_workload'),
2414 'defaults' => array(
'ref' =>
'auto'),
2415 'right' => array(
'projet',
'creer')
2418 'label' =>
"Task label.",
2419 'fk_project' =>
"Project: rowid, ref or exact title.",
2420 'description' =>
"Description.",
2421 'planned_workload' =>
"Planned workload in hours.",
2422 'date_start' =>
"Start date YYYY-MM-DD.",
2423 'date_end' =>
"End date YYYY-MM-DD."
2449 $this->writeProblems = array();
2450 $this->writeRefusedFields = array();
2451 $this->writeTarget =
null;
2452 $this->writeLine = array(
'line' =>
null,
'position' => 0,
'changes' => array());
2465 private function updateMethod($label, $class, array $right, array $fields, $lookup)
2467 $how = array(
'thirdparty' =>
"rowid, or its name",
'ref' =>
"rowid, or its exact ref",
'' =>
"rowid");
2470 'suffix' =>
'update',
2471 'description' =>
"Change fields of an existing ".$label.
". Give 'id' (".$how[$lookup].
") and ONLY the fields to change, with their new value: ".implode(
', ', array_keys($fields)).
". No other field can be changed here. The user confirms before anything is written.",
2474 'preview' =>
'AIPreviewChangeRecord',
2478 'lookup' => $lookup,
2479 'fields' => array_keys($fields),
2482 'params' => array_merge(array(
'id' =>
"The ".$label.
" to change: ".$how[$lookup].
"."), $fields)
2497 private function validateMethod($label, $class, $preview, array $right, array $fixed, $stockconst)
2499 $description =
"Validate a DRAFT ".$label.
": it gets its definitive reference and can no longer be edited. Give 'id' (rowid, or its ref, e.g. (PROV12)).";
2500 $params = array(
'id' =>
"The draft ".$label.
": rowid, or its ref.");
2501 if ($stockconst !==
'') {
2502 $description .=
" When the validation moves stock, give 'warehouse' (name or rowid) unless there is only one.";
2503 $params[
'warehouse'] =
"Warehouse the stock leaves from: name or rowid. Only needed when validating moves stock and there are several warehouses.";
2505 $description .=
" The user confirms before anything is written.";
2508 'suffix' =>
'validate',
2509 'description' => $description,
2512 'preview' => $preview,
2518 'stock' => $stockconst,
2520 ) + (count($right) === 3 ? array(
'read_right' => array($right[0],
'creer')) : array()),
2536 'suffix' =>
'delete',
2537 'description' =>
"Delete a DRAFT ".$label.
" for good. Only a draft can be deleted here. Give 'id' (rowid, or its ref, e.g. (PROV12)). The user confirms before anything is written.",
2540 'preview' =>
'AIPreviewDeleteDraft',
2547 'params' => array(
'id' =>
"The draft ".$label.
": rowid, or its ref.")
2562 private function lineMethod($action, $label, $class, array $right, $profile)
2564 $fields = ($profile ===
'intervention') ? array(
2565 'desc' =>
"Text of the line.",
2566 'date' =>
"Date of the work, YYYY-MM-DD.",
2567 'duration' =>
"Time spent, in hours (1.5 for 1h30)."
2569 'qty' =>
"New quantity.",
2570 'subprice' =>
"New unit price excl. tax.",
2571 'remise_percent' =>
"New discount, in %.",
2572 'tva_tx' =>
"New VAT rate.",
2573 'desc' =>
"New text of the line.",
2574 'unit' =>
"New unit, by name (piece, kg, hour...)."
2576 if ($profile ===
'supplier') {
2577 unset($fields[
'desc']);
2580 'line' =>
"The line: its position as shown on the document (1 = first), or its product ref or label.",
2581 'lineid' =>
"Rowid of the line, when known from a read of the document."
2583 $params = array(
'id' =>
"The draft ".$label.
": rowid, or its ref.");
2584 if ($action ===
'add') {
2585 $description =
"Add ONE line (work done) to a DRAFT ".$label.
". Give 'id', desc, and date and duration. The user confirms before anything is written.";
2587 } elseif ($action ===
'update') {
2588 $description =
"Change ONE line of a DRAFT ".$label.
". Give 'id', the line ('line' or 'lineid') and ONLY what changes: ".implode(
', ', array_keys($fields)).
". The product of a line cannot be changed: delete the line and add another. The user confirms before anything is written.";
2589 $params += $which + $fields;
2591 $description =
"Delete ONE line of a DRAFT ".$label.
". Give 'id' and the line ('line' or 'lineid'). The user confirms before anything is written.";
2596 'suffix' => $action.
'_line',
2597 'description' => $description,
2600 'line_action' => $action,
2601 'line_profile' => $profile,
2602 'preview' => ($action ===
'add') ?
'AIPreviewAddInterventionLine' : ($action ===
'update' ?
'AIPreviewChangeDocumentLine' :
'AIPreviewDeleteDocumentLine'),
2607 'fields' => ($action ===
'delete') ? array() : array_keys($fields),
2627 private function headerUpdateMethod($label, $class, array $right, array $readright, array $access, $extrafields, array $fields)
2632 foreach ($fields as $name => $f) {
2633 $update[$name] = $f[0];
2634 $labels[$name] = $f[1];
2635 if (strpos((
string) ($f[0][
'description'] ??
''),
'timestamp') !==
false) {
2639 $update[
'array_options'] = array(
'type' =>
'object',
'description' =>
'Extra fields by their options_ code, e.g. {"options_mycode": "value"}.');
2642 'suffix' =>
'update',
2643 'description' =>
"Update header fields of a DRAFT ".$label.
" after confirmation: ".implode(
', ', array_keys($update)).
". Identify it by id or exact ref. Omitted fields are preserved. Status, totals, third party and lines cannot be changed here.",
2645 'parent' =>
'id',
'ref' =>
'ref',
'object' => $class,
'label' => $label,
2646 'right' => $right,
'read_right' => $readright,
'access' => $access,
2647 'draft_only' =>
true,
2648 'preview' =>
'AIPreviewUpdateRecord',
2649 'update' => $update,
2650 'preview_labels' => $labels,
2651 'preview_dates' => $dates,
2652 'preview_objects' => isset($update[
'fk_project']) ? array(
'fk_project' =>
'Project') : array(),
2653 'extrafields' => $extrafields,
2654 'references' => isset($update[
'fk_project']) ? array(
'fk_project' => array(
'projet',
'projet',
'')) : array()
2667 'suffix' =>
'update',
2668 'description' =>
'Partially update a draft or open project by exactly one positive id or exact ref. Omitted fields stay unchanged; empty text clears it, null clears a date. Project dates have day precision in the server timezone. The user confirms old-to-new values. No status, sharing, ownership, contacts, tasks or extrafield changes.',
2670 'preview' =>
'AIPreviewUpdateProject',
2671 'right' => [
'projet',
'creer'],
'read_right' => [
'projet',
'lire'],
2672 'parent' =>
'id',
'ref' =>
'ref',
'object' =>
'Project',
2673 'access' => [
'project',
'',
''],
'project_update' =>
true,
2674 'trim_fields' => [
'title',
'description',
'note_public',
'note_private'],
2675 'sanitize_fields' => [
'title' =>
'alphanohtml',
'description' =>
'restricthtml',
'note_public' =>
'restricthtml',
'note_private' =>
'restricthtml'],
2676 'preview_labels' => [
'title' =>
'Label',
'description' =>
'Description',
'note_public' =>
'NotePublic',
'note_private' =>
'NotePrivate',
'date_start' =>
'DateStart',
'date_end' =>
'DateEnd'],
2677 'preview_dates' => [
'date_start',
'date_end'],
'preview_dateonly' =>
true,
2678 'compact_result' =>
true,
2680 'title' => [
'type' =>
'string',
'minLength' => 1,
'maxLength' => 255],
2681 'description' => [
'type' =>
'string'],
'note_public' => [
'type' =>
'string'],
'note_private' => [
'type' =>
'string'],
2682 'date_start' => [
'type' => [
'integer',
'null'],
'minimum' => 1,
'description' =>
'Unix timestamp, or null to clear. Day precision in the server timezone.'],
2683 'date_end' => [
'type' => [
'integer',
'null'],
'minimum' => 1,
'description' =>
'Unix timestamp, or null to clear. Must not precede the resulting start date.']
2699 require_once DOL_DOCUMENT_ROOT .
'/core/lib/functions2.lib.php';
2700 require_once DOL_DOCUMENT_ROOT .
'/includes/restler/framework/Luracast/Restler/AutoLoader.php';
2701 $previousloaders = spl_autoload_functions();
2702 $loader = Luracast\Restler\AutoLoader::instance();
2703 spl_autoload_register($loader);
2704 require_once DOL_DOCUMENT_ROOT .
'/api/class/api.class.php';
2705 require_once DOL_DOCUMENT_ROOT .
'/api/class/api_access.class.php';
2709 foreach ($previousloaders as $previousloader) {
2710 spl_autoload_register($previousloader);
2741 if (!is_resource($handle)) {
2745 while (($file = readdir($handle)) !==
false) {
2747 if (!is_readable($dir.$file) || !preg_match(
"/^mod(.*)\\.class\\.php$/i", $file, $regmod)) {
2751 $module = strtolower($regmod[1]);
2755 $modulenameforenabled =
$module;
2757 $modulenameforenabled =
'propal';
2758 } elseif (
$module ==
'supplierproposal') {
2759 $modulenameforenabled =
'supplier_proposal';
2760 } elseif (
$module ==
'ficheinter') {
2761 $modulenameforenabled =
'intervention';
2763 $modulenameforenabled =
'service';
2770 $dir_part =
dol_buildpath(
'/'.$moduledirforclass.
'/class/');
2772 if (!is_resource($handle_part)) {
2776 while (($file_searched = readdir($handle_part)) !==
false) {
2777 if (in_array($file_searched, [
'api_access.class.php',
'api_setup.class.php',
'api_login.class.php',
'api_status.class.php'],
true)) {
2781 if (!is_readable($dir_part.$file_searched) || !preg_match(
"/^api_(.*)\\.class\\.php$/i", $file_searched, $regapi)) {
2785 $key = strtolower($regapi[1]);
2786 if (isset($endpoints[$key])) {
2790 $endpoints[$key] = [
2791 'module' => $modulenameforenabled,
2792 'path' => $dir_part.$file_searched,
2793 'candidate' => str_replace(
'_',
'', ucwords($regapi[1])),
2795 'label' => $this->enrichments[$key][
'label'] ?? $key,
2798 closedir($handle_part);
2819 if ($this->endpoints[$key][
'class'] !==
'') {
2822 require_once $this->endpoints[$key][
'path'];
2823 $candidate = $this->endpoints[$key][
'candidate'];
2825 if (class_exists($candidate.
'Api')) {
2826 $classname = $candidate.
'Api';
2827 } elseif (class_exists($candidate)) {
2828 $classname = $candidate;
2830 if ($classname ===
'') {
2834 $reflection =
new ReflectionClass($classname);
2835 $this->endpoints[$key][
'class'] = $reflection->getName();
2839 if ($this->endpoints[$key][
'label'] === $key) {
2840 $classdoc = (string) $reflection->getDocComment();
2841 if (preg_match(
'/\*\s+([^@\s\/*][^\n]*)/', $classdoc, $mlabel)) {
2843 $this->endpoints[$key][
'label'] = trim(preg_replace(
'/^API class (for|of)\s+(the\s+)?/i',
'', trim($mlabel[1])));
2862 return [
'index' => [],
'get' => []];
2876 foreach (array_keys($this->endpoints) as $epkey) {
2877 foreach ($this->enrichments as $key => $enrichment) {
2878 if (($enrichment[
'endpoint'] ?? $key) === $epkey) {
2879 $groups[$key] = $epkey;
2898 foreach ((array) ($meta[
'fixed_params'] ?? array()) as $pname => $value) {
2899 $args[$pname] = $value;
2917 if ($configured ===
'') {
2920 $allowed = array_map(
'trim', explode(
',', $configured));
2921 return array_intersect_key($methods, array_flip($allowed));
2931 if ($this->defs !==
null) {
2943 if ($cachefile !==
'' && is_readable($cachefile) && (
dol_now() - (int) filemtime($cachefile)) < $cachettl) {
2944 $payload = json_decode((
string) file_get_contents($cachefile),
true);
2945 if (is_array($payload) && isset($payload[
'defs'], $payload[
'routes'], $payload[
'endpoints'])
2946 && is_array($payload[
'defs']) && is_array($payload[
'routes']) && is_array($payload[
'endpoints'])) {
2947 $this->defs = $payload[
'defs'];
2948 $this->routes = $payload[
'routes'];
2949 $this->endpoints = $payload[
'endpoints'];
2961 foreach ($this->
toolGroups() as $key => $epkey) {
2969 if (!isset($this->enrichments[$key])) {
2979 $ep = $this->endpoints[$epkey];
2980 $ep[
'label'] = $this->enrichments[$key][
'label'] ?? $ep[
'label'];
2982 foreach ($methods as $method => $meta) {
2986 if (!empty($meta[
'module']) && !
isModEnabled($meta[
'module'])) {
2991 if (!empty($meta[
'setup']) && !$this->
setupAllows((array) $meta[
'setup'])) {
2994 if (!method_exists($ep[
'class'], $method)) {
2997 $suffix = $meta[
'suffix'] ?? ($method ===
'index' ?
'list' : strtolower($method));
2998 $toolname =
'api_' . $key .
'_' . $suffix;
3001 $def[
'categories'] = self::ENDPOINT_CATEGORIES[$key] ?? array(
'billing',
'commercial',
'thirdparty',
'stock',
'project',
'reporting');
3002 $this->defs[] = $def;
3003 $this->routes[$toolname] = [$key, $method];
3008 if ($cachefile !==
'') {
3023 foreach ($consts as $const) {
3051 if (!empty(
$conf->ai->multidir_temp[
$conf->entity])) {
3052 $dir =
$conf->ai->multidir_temp[
$conf->entity];
3053 } elseif (!empty(
$conf->ai->dir_temp)) {
3054 $dir =
$conf->ai->dir_temp;
3056 if (empty($dir) ||
dol_mkdir($dir) < 0) {
3060 $modules = array_map(
'strval', array_values((array)
$conf->modules));
3062 $signature = implode(
',', $modules).
'|'.DOL_VERSION.
'|'.((int)
$conf->entity).
'|'.((int) @filemtime(__FILE__)).
'|'.DOL_DOCUMENT_ROOT;
3067 $signature .=
'|'.getDolGlobalString(
'AI_MCP_API_BRIDGE_METHODS');
3070 foreach (array(
'MAIN_USE_ADVANCED_PERMS',
'PRODUCT_PRICE_UNIQ',
'PRODUIT_CUSTOMER_PRICES') as $const) {
3074 foreach ($this->enrichments as $meta) {
3075 foreach (($meta[
'methods'] ?? array()) as $mmeta) {
3076 foreach ((array) ($mmeta[
'setup'] ?? array()) as $const) {
3082 return rtrim($dir,
'/').
'/bridge_tooldefs_'.md5($signature).
'.json';
3096 $payload = json_encode(array(
'defs' => $this->defs,
'routes' => $this->routes,
'endpoints' => $this->endpoints));
3097 if (!is_string($payload)) {
3100 foreach ((array) glob(dirname($cachefile).
'/bridge_tooldefs_*.json') as $old) {
3101 if (is_string($old) && $old !== $cachefile) {
3105 $tmpfile = $cachefile.
'.tmp.'.getmypid();
3106 if (file_put_contents($tmpfile, $payload) !==
false) {
3107 @rename($tmpfile, $cachefile);
3124 if (!empty(
$conf->ai->multidir_temp) && is_array(
$conf->ai->multidir_temp)) {
3125 foreach (
$conf->ai->multidir_temp as $dir) {
3126 if (is_string($dir) && $dir !==
'') {
3127 $dirs[] = rtrim($dir,
'/');
3131 if (!empty(
$conf->ai->dir_temp) && is_string(
$conf->ai->dir_temp)) {
3132 $dirs[] = rtrim(
$conf->ai->dir_temp,
'/');
3136 foreach (array_unique($dirs) as $dir) {
3139 foreach ((array) glob($dir.
'/bridge_tooldefs_*.json') as $file) {
3140 if (is_string($file) && @unlink($file)) {
3162 private function buildToolDefinition(array $ep,
string $key,
string $method,
string $toolname, array $meta = [])
3165 $rm =
new ReflectionMethod($ep[
'class'], $method);
3166 }
catch (ReflectionException $e) {
3170 $doc = (string) $rm->getDocComment();
3175 if (preg_match(
'/\*\s+([^@\s\/*][^\n]*)/', $doc, $m)) {
3176 $summary = trim($m[1]);
3181 if (preg_match_all(
'/@param\s+(\S+)\s+\$(\w+)\s+([^\n]*)/', $doc, $mm, PREG_SET_ORDER)) {
3182 foreach ($mm as $pm) {
3183 $paramDocs[$pm[2]] = [
'type' => $pm[1],
'desc' => trim($pm[3])];
3189 foreach ($rm->getParameters() as $p) {
3190 $pname = $p->getName();
3191 $ptype = isset($paramDocs[$pname]) ? $this->
docTypeToJson($paramDocs[$pname][
'type']) :
'string';
3199 $commondesc = (string) ($this->commonParamDocs[$pname] ??
'');
3200 if (isset($meta[
'params'][$pname])) {
3201 $pdesc = $meta[
'params'][$pname];
3202 } elseif (!empty($paramDocs[$pname][
'desc'])) {
3203 $pdesc = $paramDocs[$pname][
'desc'];
3204 if ($pname ===
'sqlfilters' && $commondesc !==
'') {
3205 $keptdesc = preg_replace(
'/.*Syntax example/',
'Example', rtrim($pdesc));
3206 $pdesc = $commondesc;
3208 $pdesc .=
"\n".$keptdesc;
3211 if ($pname ===
'sortfield' && $commondesc !==
'') {
3212 $pdesc = rtrim((
string) $pdesc,
'. ').
'. '.$commondesc;
3215 $pdesc = $commondesc;
3227 'description' => $pdesc
3229 $prop += $constraints;
3230 if ($p->isOptional()) {
3232 $prop[
'default'] = ($pname ==
'limit') ? self::BRIDGE_DEFAULT_LIMIT : $p->getDefaultValue();
3233 }
catch (ReflectionException $e) {
3237 $required[] = $pname;
3239 $properties[$pname] = $prop;
3245 if (!empty($meta[
'write']) && empty($meta[
'write'][
'parent']) && !empty($meta[
'params'])) {
3248 foreach ($meta[
'params'] as $pname => $pdesc) {
3249 if ($pname ===
'lines') {
3252 $lineFields = !empty($meta[
'write'][
'line_fields']) ? $meta[
'write'][
'line_fields'] : [
3253 'product_ref' => [
'type' =>
'string',
'description' =>
'Ref or label of a catalogue product.'],
3254 'desc' => [
'type' =>
'string',
'description' =>
'Free text, for a line with no product.'],
3255 'qty' => [
'type' =>
'number'],
3256 'unit' => [
'type' =>
'string',
'description' =>
'Unit as said, e.g. pieces, kg, hour. Omit to use the product unit.'],
3257 'subprice' => [
'type' =>
'number',
'description' =>
'Unit price excl. tax. Omit to use the catalogue price.'],
3258 'tva_tx' => [
'type' =>
'number',
'description' =>
'VAT rate. Omit to use the default rate.']
3260 $properties[$pname] = [
3262 'description' => $pdesc,
3265 'properties' => $lineFields
3270 $properties[$pname] = [
'type' =>
'string',
'description' => $pdesc];
3272 foreach ((array) ($meta[
'write'][
'required'] ?? array()) as $pname) {
3273 $required[] = $pname;
3278 $fixed = array_keys((array) ($meta[
'fixed_params'] ?? array()));
3280 $properties = array_diff_key($properties, array_flip($fixed));
3281 $required = array_values(array_diff($required, $fixed));
3284 if (!empty($meta[
'write'])) {
3286 } elseif ($method ===
'index') {
3287 $verb =
'List / search';
3288 } elseif ($method ===
'get') {
3289 $verb =
'Get one record of';
3291 $verb =
'Read from';
3293 $schema = [
'type' =>
'object',
'properties' => $properties];
3295 $schema[
'required'] = $required;
3297 if (!empty($meta[
'write'][
'update'])) {
3304 if (!empty($meta[
'write'])) {
3305 $schema[
'properties'][
'requestState'] = array(
3307 'description' =>
'Confirmation state returned with the input_required answer of a first call. Call again with the same arguments plus this value to run the write. Short-lived, one use.'
3313 $description = $verb .
' ' . $ep[
'label'] .
' through the Dolibarr REST API (auto-generated tool). ' . $summary;
3315 if (!empty($meta[
'description'])) {
3316 $description = $meta[
'description'];
3320 'name' => $toolname,
3321 'description' => $description,
3322 'inputSchema' => $schema
3345 $desc = (string) $desc;
3347 if (strpos($desc,
'{@') ===
false) {
3352 if (preg_match_all(
'/\{@(\w[\w-]*)\s*([^}]*)\}/', $desc, $matches, PREG_SET_ORDER)) {
3353 foreach ($matches as $tag) {
3354 $name = strtolower($tag[1]);
3355 $value = trim($tag[2]);
3357 if ($name ===
'min' && is_numeric($value)) {
3359 } elseif ($name ===
'max' && is_numeric($value)) {
3361 } elseif ($name ===
'choice' && $value !==
'') {
3362 $choices = array_map(
'trim', explode(
',', $value));
3363 if ($ptype ===
'integer' || $ptype ===
'number') {
3364 foreach ($choices as $i => $choice) {
3365 if (is_numeric($choice)) {
3370 $constraints[
'enum'] = array_values($choices);
3371 } elseif (($name ===
'const' || $name ===
'constant') && $value !==
'') {
3373 if ($ptype ===
'integer' || $ptype ===
'number') {
3374 if (is_numeric($val)) {
3377 } elseif ($ptype ===
'boolean') {
3378 $val = filter_var($val, FILTER_VALIDATE_BOOLEAN);
3382 $constraints[
'enum'] = array($val);
3383 } elseif ($name ===
'pattern' && $value !==
'') {
3385 if ($pattern !==
'') {
3386 $constraints[
'pattern'] = $pattern;
3394 $desc = preg_replace(
'/\s*\{@\w[\w-]*[^}]*\}/',
'', $desc);
3396 return trim(preg_replace(
'/\s{2,}/',
' ', (
string) $desc));
3410 return (strpos($value,
'.') ===
false) ? (int) $value : (float) $value;
3429 if (!preg_match(
'/^(.)(.*)\1([a-zA-Z]*)$/s', $value, $reg)) {
3433 $expression = $reg[2];
3436 if ($flags !==
'' && !($flags ===
'i' && !preg_match(
'/[a-zA-Z]/', $expression))) {
3451 $t = strtolower(trim(explode(
'|', $type)[0]));
3452 if (in_array($t, [
'int',
'integer'],
true)) {
3455 if (in_array($t, [
'float',
'double'],
true)) {
3458 if ($t ===
'bool' || $t ===
'boolean') {
3476 $write = isset($meta[
'write']) ? $meta[
'write'] : array();
3477 if (!empty($write[
'right'])) {
3478 return empty($write[
'read_right']) ? array($write[
'right']) : array($write[
'right'], $write[
'read_right']);
3487 if (!empty($meta[
'right'])) {
3488 $declared = (isset($meta[
'right'][0]) && is_array($meta[
'right'][0])) ? $meta[
'right'] : array($meta[
'right']);
3490 foreach ($declared as $triple) {
3491 if (!is_array($triple)) {
3495 foreach (array_values($triple) as $v) {
3496 $strings[] = (string) $v;
3499 $rights[] = $strings;
3507 return self::RIGHTS_ENFORCED_DOWNSTREAM;
3522 require_once DOL_DOCUMENT_ROOT.
'/societe/class/societe.class.php';
3523 $soc =
new Societe($this->db);
3524 if ($socid <= 0 || $soc->fetch($socid) <= 0 || !is_object(
$mysoc)) {
3542 require_once DOL_DOCUMENT_ROOT.
'/fourn/class/fournisseur.product.class.php';
3544 if ($socid > 0 && $pf->find_min_price_product_fournisseur($prod->id, $qty, $socid) > 0) {
3545 return (
float) $pf->fourn_unitprice;
3548 return (
float) $prod->cost_price;
3562 'Facture' =>
'/compta/facture/class/facture.class.php',
3563 'Commande' =>
'/commande/class/commande.class.php',
3564 'Propal' =>
'/comm/propal/class/propal.class.php',
3565 'FactureFournisseur' =>
'/fourn/class/fournisseur.facture.class.php',
3566 'CommandeFournisseur' =>
'/fourn/class/fournisseur.commande.class.php',
3567 'SupplierProposal' =>
'/supplier_proposal/class/supplier_proposal.class.php',
3568 'Societe' =>
'/societe/class/societe.class.php',
3569 'Product' =>
'/product/class/product.class.php',
3570 'Reception' =>
'/reception/class/reception.class.php',
3571 'Expedition' =>
'/expedition/class/expedition.class.php',
3572 'Ticket' =>
'/ticket/class/ticket.class.php',
3573 'Project' =>
'/projet/class/project.class.php',
3574 'Contrat' =>
'/contrat/class/contrat.class.php',
3575 'Fichinter' =>
'/fichinter/class/fichinter.class.php'
3577 if (empty($paths[$class]) || ((
int)
$id <= 0 && $ref ===
'')) {
3580 require_once DOL_DOCUMENT_ROOT.$paths[$class];
3581 $obj =
new $class($this->db);
3582 '@phan-var-force Facture|Commande|Propal|FactureFournisseur|CommandeFournisseur|SupplierProposal|Societe|Product|Reception|Expedition|Project|Contrat|Fichinter $obj';
3583 $result = $ref ===
'' ? $obj->fetch((
int)
$id) : $obj->fetch((
int)
$id, $ref);
3602 return $obj ? (string) $obj->ref :
'';
3615 if (empty(
$id) || !is_numeric(
$id)) {
3616 return json_encode(
$id);
3620 return '#'.((int)
$id);
3622 $name = (string) ($obj->title ?? ($obj->label ?? ($obj->name ??
'')));
3624 return $obj->ref.($name !==
'' ?
' - '.$name :
'');
3636 if (!empty($write[
'ref']) && !empty($write[
'object'])) {
3637 return $this->
fetchBusinessObject($write[
'object'], (
int) ($args[$write[
'parent']] ?? 0), (
string) ($args[$write[
'ref']] ??
''));
3639 if (empty($write[
'parent']) || empty($write[
'object']) || !is_numeric($args[$write[
'parent']] ??
'')) {
3654 $properties = $write[
'update'];
3655 $properties[$write[
'parent']] = [
'type' =>
'integer',
'minimum' => 1];
3656 $properties[$write[
'ref']] = [
'type' =>
'string',
'minLength' => 1];
3657 $properties[
'request_data'] = [
'oneOf' => [
3658 [
'type' =>
'object',
'additionalProperties' =>
false,
'properties' => $write[
'update'],
'minProperties' => 1],
3659 [
'type' =>
'string',
'description' =>
'A JSON object containing only the permitted update fields: '.implode(
', ', array_keys($write[
'update'])).
'.']
3661 $changes = [[
'required' => [
'request_data']]];
3662 foreach (array_keys($write[
'update']) as $field) {
3663 $changes[] = [
'required' => [$field]];
3665 return [
'type' =>
'object',
'additionalProperties' =>
false,
'properties' => $properties,
3666 'oneOf' => [[
'required' => [$write[
'parent']]], [
'required' => [$write[
'ref']]]],
'anyOf' => $changes];
3689 return $project->restrictedProjectArea($this->
user,
'write') > 0;
3703 if (!$project || !$this->
canAccessWriteObject([
'project',
'',
''], (
int) $project->id) || !$this->canWriteProject($project)) {
3704 throw new InvalidArgumentException(
'Access denied to project');
3706 if (!in_array($project->status ??
null, [0, 1,
'0',
'1'],
true)) {
3707 throw new InvalidArgumentException(
'Only draft or open projects can be edited by this tool');
3709 $start = array_key_exists(
'date_start', $args) ? $args[
'date_start'] : $parent->date_start;
3710 $end = array_key_exists(
'date_end', $args) ? $args[
'date_end'] : $parent->date_end;
3711 if ($start && $end && $end < $start) {
3712 throw new InvalidArgumentException(
'End date must not precede start date');
3726 if (array_key_exists(
'request_data', $args)) {
3727 $body = $args[
'request_data'];
3728 if (is_string($body)) {
3729 $decoded = json_decode($body);
3730 $body = $decoded instanceof
stdClass ? json_decode($body,
true) :
null;
3732 if (!is_array($body) || !$body || array_filter(array_keys($body),
'is_int')) {
3733 throw new InvalidArgumentException(
'request_data must be a non-empty object');
3735 if (array_diff_key($body, $write[
'update'])) {
3736 throw new InvalidArgumentException(
'request_data must contain only the permitted update fields');
3738 unset($args[
'request_data']);
3739 foreach ($body as $key => $value) {
3740 if (array_key_exists($key, $args) && $args[$key] !== $value) {
3741 throw new InvalidArgumentException(
'Conflicting value for '.$key);
3744 $args = array_merge($body, $args);
3746 $idkey = $write[
'parent'];
3747 $refkey = $write[
'ref'];
3748 $hasid = array_key_exists($idkey, $args);
3749 $hasref = array_key_exists($refkey, $args);
3750 if ($hasid === $hasref || ($hasid && (!is_int($args[$idkey]) || $args[$idkey] <= 0)) || ($hasref && (!is_string($args[$refkey]) || trim($args[$refkey]) ===
''))) {
3751 throw new InvalidArgumentException(
'Supply one positive integer id or one exact ref');
3753 $changes = array_diff_key($args, array_flip([$idkey, $refkey,
'requestState']));
3754 if (!$changes || array_diff_key($changes, $write[
'update'])) {
3755 throw new InvalidArgumentException(
'Supply only the permitted update fields, with at least one change');
3757 foreach ($changes as $field => $value) {
3758 if (is_string($value) && in_array($field, $write[
'trim_fields'] ?? [],
true)) {
3759 $value = trim($value);
3760 $changes[$field] = $args[$field] = $value;
3762 if (is_string($value) && !empty($write[
'sanitize_fields'][$field]) &&
sanitizeVal($value, $write[
'sanitize_fields'][$field]) !== $value) {
3763 throw new InvalidArgumentException(
'Text would be changed by API sanitization: '.$field);
3765 $types = (array) $write[
'update'][$field][
'type'];
3766 $valid = ($value ===
null && in_array(
'null', $types,
true))
3767 || (is_string($value) && in_array(
'string', $types,
true))
3768 || (is_int($value) && in_array(
'integer', $types,
true) && $value >= ($write[
'update'][$field][
'minimum'] ?? 0))
3769 || (is_array($value) && in_array(
'object', $types,
true) && !array_filter(array_keys($value),
'is_int'));
3770 $definition = $write[
'update'][$field];
3771 if (is_string($value)) {
3772 $valid = $valid &&
dol_strlen($value) >= ($definition[
'minLength'] ?? 0) &&
dol_strlen($value) <= ($definition[
'maxLength'] ?? PHP_INT_MAX);
3775 throw new InvalidArgumentException(
'Invalid value for '.$field);
3778 foreach ([$write[
'right'], $write[
'read_right']] as $right) {
3779 if (!$this->
user || !call_user_func_array([$this->
user,
'hasRight'], $right)) {
3780 throw new InvalidArgumentException(
'Not enough permissions');
3785 throw new InvalidArgumentException(
'Record not found');
3788 throw new InvalidArgumentException(
'Access denied to record');
3790 if (!empty($write[
'draft_only']) && (
int) $parent->status !== 0) {
3792 $langs->load(
'other');
3793 throw new InvalidArgumentException($langs->transnoentitiesnoconv(
'AIWriteNotDraftEdit', (
string) $write[
'label'], (
string) $parent->ref));
3795 if (!empty($write[
'project_update'])) {
3798 foreach (($write[
'references'] ?? []) as $field => $access) {
3799 if (!empty($changes[$field]) && !$this->
canAccessWriteObject($access, (
int) $changes[$field])) {
3800 throw new InvalidArgumentException(
'Access denied to '.$field);
3803 if (!empty($write[
'extrafields']) && isset($changes[
'array_options']) && !empty($this->db)) {
3804 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
3806 $extrafields->fetch_name_optionals_label((
string) $write[
'extrafields']);
3807 $known = array_keys((array) ($extrafields->attributes[$write[
'extrafields']][
'label'] ?? []));
3808 foreach (array_keys($changes[
'array_options']) as $key) {
3809 if (strpos((
string) $key,
'options_') !== 0 || !in_array(substr((
string) $key, 8), $known,
true)) {
3810 throw new InvalidArgumentException(
'Unknown extra field '.$key.($known ?
' (known: options_'.implode(
', options_', $known).
')' :
' (this record has no extra fields)'));
3814 unset($args[$refkey]);
3815 $args[$idkey] = (int) $parent->id;
3828 require_once DOL_DOCUMENT_ROOT.
'/ai/lib/ai.lib.php';
3847 $this->unresolvedProducts = array();
3848 if (!empty($write[
'update'])) {
3852 if (isset($args[
'request_data'])) {
3853 $body = $args[
'request_data'];
3854 if (is_string($body)) {
3855 $decoded = json_decode($body,
true);
3856 $body = is_array($decoded) ? $decoded : array();
3858 if (is_array($body)) {
3862 if (count($body) === 1) {
3863 $only = reset($body);
3864 if (is_array($only) && !isset($body[0])) {
3868 unset($args[
'request_data']);
3869 $args = array_merge($body, $args);
3877 if (!empty($write[
'parent'])) {
3878 if (!empty($args[
'lines']) && is_array($args[
'lines']) && count($args[
'lines']) === 1 && is_array(reset($args[
'lines']))) {
3879 $line = reset($args[
'lines']);
3880 unset($args[
'lines']);
3881 $args = array_merge($line, $args);
3883 if (!isset($args[
'qty']) && !isset($args[
'quantity'])) {
3894 $kind = (string) ($write[
'kind'] ??
'');
3895 if (in_array($kind, array(
'update',
'action',
'delete',
'payment',
'line'),
true)) {
3898 if (!empty($write[
'lookup']) && $kind ===
'') {
3904 $fieldAliases = array(
'nom' =>
'name',
'company' =>
'name',
'mail' =>
'email',
'tel' =>
'phone',
'telephone' =>
'phone',
'libelle' =>
'label',
'title' =>
'label');
3905 foreach ($fieldAliases as $from => $to) {
3907 if (in_array($from, (array) ($write[
'required'] ?? array()),
true) || in_array($from, (array) ($write[
'args'] ?? array()),
true)) {
3910 if (isset($args[$from]) && !isset($args[$to]) && !is_array($args[$from])) {
3911 $args[$to] = $args[$from];
3912 unset($args[$from]);
3919 if (empty($args[
'socid']) || !is_numeric($args[
'socid'])) {
3921 foreach (array(
'socid',
'thirdparty',
'company',
'customer',
'supplier') as $key) {
3922 if (!empty($args[$key]) && !is_numeric($args[$key])) {
3923 $named = (string) $args[$key];
3927 if ($named !==
'') {
3928 $sql =
"SELECT rowid FROM ".$this->db->prefix().
"societe";
3929 $sql .=
" WHERE entity IN (".getEntity(
'societe').
")";
3930 $sql .=
" AND (nom = '".$this->db->escape($named).
"' OR code_client = '".$this->db->escape($named).
"' OR code_fournisseur = '".$this->db->escape($named).
"')";
3932 $resql = $this->db->query($sql);
3933 if ($resql && $this->db->num_rows($resql) === 1) {
3936 $obj = $this->db->fetch_object($resql);
3937 $args[
'socid'] = (int) $obj->rowid;
3944 require_once DOL_DOCUMENT_ROOT.
'/ai/lib/ai.lib.php';
3945 $named = trim($named);
3950 if (count($found) === 1 && $found[0][
'start'] === 0 && $found[0][
'end'] === strlen($named) && count($found[0][
'candidates']) === 1) {
3951 $args[
'socid'] = (int) key($found[0][
'candidates']);
3959 $kind = (string) ($write[
'kind'] ??
'');
3960 $headerWarehouse = 0;
3962 $logisticAliases = array(
'supplier_ref' =>
'ref_supplier',
'ref_fournisseur' =>
'ref_supplier',
'delivery_note' =>
'ref_supplier',
'customer_ref' =>
'ref_customer',
'ref_client' =>
'ref_customer',
'delivery_date' =>
'date_delivery',
'date' =>
'date_delivery');
3963 foreach ($logisticAliases as $from => $to) {
3964 if (isset($args[$from]) && !isset($args[$to]) && !is_array($args[$from])) {
3965 $args[$to] = $args[$from];
3966 unset($args[$from]);
3970 foreach (array(
'date_delivery',
'date_reception') as $datefield) {
3971 if (isset($args[$datefield]) && !is_numeric($args[$datefield])) {
3972 $args[$datefield] = $this->
writeDate($datefield, $args[$datefield]);
3973 if ($args[$datefield] ===
null) {
3974 unset($args[$datefield]);
3978 foreach (array(
'warehouse',
'warehouse_id',
'fk_warehouse',
'entrepot') as $key) {
3979 if (!empty($args[$key]) && !is_array($args[$key]) && $kind ===
'reception') {
3987 if (!empty($args[
'lines']) && is_array($args[
'lines'])) {
3988 foreach ($args[
'lines'] as $i => $line) {
3989 if (is_array($line)) {
3990 $args[
'lines'][$i] = $this->
normaliseWriteLine($line, is_numeric($args[
'socid'] ??
'') ? (
int) $args[
'socid'] : 0, !empty($write[
'buy']), $kind, $headerWarehouse);
3998 if (!empty($write[
'thirdparty'])) {
4002 $socid = (int) (is_numeric($args[$write[
'thirdparty']] ??
'') ? $args[$write[
'thirdparty']] : 0);
4004 $soc = ($socid > 0 && $this->db) ? $this->
fetchRecord(
'Societe', $socid) :
null;
4005 if ($soc instanceof
Societe) {
4006 $langs->load(
'other');
4007 $args[
'_who'] =
' '.$langs->trans(
'AIPreviewForThirdparty', $soc->name);
4008 $args[
'_at'] =
' '.$langs->trans(
'AIPreviewAtThirdparty', $soc->name);
4011 if (($write[
'object'] ??
'') ===
'Contact') {
4012 $args[
'_name'] = trim(((
string) ($args[
'firstname'] ??
'')).
' '.((
string) ($args[
'lastname'] ??
'')));
4029 private function normaliseWriteLine(array $line, $socid, $buy =
false, $kind =
'', $defaultWarehouse = 0)
4031 $aliases = array(
'quantity' =>
'qty',
'unit_price' =>
'subprice',
'price' =>
'subprice',
'description' =>
'desc',
'vat_rate' =>
'tva_tx',
'product_id' =>
'fk_product');
4033 $aliases += array(
'warehouse' =>
'fk_entrepot',
'warehouse_id' =>
'fk_entrepot',
'fk_warehouse' =>
'fk_entrepot',
'entrepot' =>
'fk_entrepot',
'entrepot_id' =>
'fk_entrepot',
'lot' =>
'batch',
'serial' =>
'batch',
'lot_number' =>
'batch');
4035 foreach ($aliases as $from => $to) {
4036 if (isset($line[$from]) && !isset($line[$to])) {
4037 $line[$to] = $line[$from];
4038 unset($line[$from]);
4041 if ($kind ===
'reception') {
4044 foreach (array(
'subprice',
'buy_price',
'purchase_price',
'cost') as $from) {
4045 if (isset($line[$from]) && !isset($line[
'cost_price'])) {
4046 $line[
'cost_price'] = $line[$from];
4048 unset($line[$from]);
4054 if (empty($line[
'fk_product']) && !empty($line[
'product_ref'])) {
4055 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
4056 $prod =
new Product($this->db);
4057 $wanted = (string) $line[
'product_ref'];
4058 $found = ($prod->fetch(0, $wanted) > 0);
4063 $sql =
"SELECT rowid FROM ".$this->db->prefix().
"product";
4064 $sql .=
" WHERE entity IN (".getEntity(
'product').
")";
4065 $sql .=
" AND (label = '".$this->db->escape($wanted).
"' OR ref = '".$this->db->escape($wanted).
"')";
4067 $resql = $this->db->query($sql);
4068 if ($resql && $this->db->num_rows($resql) === 1) {
4069 $obj = $this->db->fetch_object($resql);
4070 $found = ($prod->fetch((
int) $obj->rowid) > 0);
4073 if (!$found && $buy && $socid > 0) {
4077 $sql =
"SELECT DISTINCT pfp.fk_product FROM ".$this->db->prefix().
"product_fournisseur_price as pfp";
4078 $sql .=
" WHERE pfp.entity IN (".getEntity(
'productsupplierprice').
")";
4079 $sql .=
" AND pfp.fk_soc = ".((int) $socid);
4080 $sql .=
" AND pfp.ref_fourn = '".$this->db->escape($wanted).
"'";
4082 $resql = $this->db->query($sql);
4083 if ($resql && $this->db->num_rows($resql) === 1) {
4084 $obj = $this->db->fetch_object($resql);
4085 $found = ($prod->fetch((
int) $obj->fk_product) > 0);
4089 $line[
'fk_product'] = $prod->id;
4090 if (empty($line[
'fk_unit']) && !isset($line[
'unit']) && !empty($prod->fk_unit)) {
4091 $line[
'fk_unit'] = (int) $prod->fk_unit;
4093 if (!isset($line[
'desc'])) {
4094 $line[
'desc'] = $prod->label;
4096 if (!isset($line[
'subprice'])) {
4097 $line[
'subprice'] = $buy ? $this->
defaultBuyPrice($prod, $socid, (
float) ($line[
'qty'] ?? 1)) : $prod->price;
4100 if (!$found && !isset($line[
'desc'])) {
4103 $line[
'desc'] = $wanted;
4106 $this->unresolvedProducts[$wanted] = $this->
closeProductRefs($wanted, $buy ? $socid : 0);
4108 unset($line[
'product_ref']);
4113 if (isset($line[
'unit']) || (isset($line[
'fk_unit']) && !is_numeric($line[
'fk_unit']))) {
4114 $unit = $this->
unitIdFromName((
string) ($line[
'unit'] ?? $line[
'fk_unit']));
4115 unset($line[
'unit'], $line[
'fk_unit']);
4117 $line[
'fk_unit'] = $unit;
4120 if (empty($line[
'fk_unit']) && !empty($line[
'fk_product'])) {
4122 if ($unitprod instanceof
Product && !empty($unitprod->fk_unit)) {
4123 $line[
'fk_unit'] = (int) $unitprod->fk_unit;
4130 if ($kind ===
'shipment') {
4134 unset($line[
'fk_entrepot']);
4135 $lotprod = empty($line[
'fk_product']) ? null : $this->
fetchBusinessObject(
'Product', (
int) $line[
'fk_product']);
4138 $langs->load(
'other');
4139 $this->writeProblems[] = $langs->transnoentitiesnoconv(
'AIWriteShipmentLotProduct', $lotprod->ref);
4142 if (isset($line[
'fk_entrepot']) && (
string) $line[
'fk_entrepot'] !==
'' && !is_array($line[
'fk_entrepot'])) {
4144 $line[
'fk_entrepot'] = $this->
resolveWarehouse((
string) $line[
'fk_entrepot']);
4146 if (empty($line[
'fk_entrepot'])) {
4147 $line[
'fk_entrepot'] = $defaultWarehouse > 0 ? $defaultWarehouse : $this->
defaultWarehouseId();
4149 if (empty($line[
'fk_entrepot'])) {
4150 unset($line[
'fk_entrepot']);
4155 unset($line[
'tva_tx'], $line[
'subprice']);
4156 if ($kind ===
'reception') {
4159 if (!isset($line[
'cost_price']) && !empty($line[
'fk_product'])) {
4161 if ($costprod instanceof
Product) {
4162 $line[
'cost_price'] = $this->
defaultBuyPrice($costprod, $socid, (
float) ($line[
'qty'] ?? 1));
4166 foreach (array(
'eatby',
'sellby') as $datefield) {
4167 if (isset($line[$datefield]) && !is_numeric($line[$datefield])) {
4168 $line[$datefield] = $this->
writeDate($datefield, $line[$datefield]);
4169 if ($line[$datefield] ===
null) {
4170 unset($line[$datefield]);
4181 if (!isset($line[
'tva_tx']) && $socid > 0) {
4182 $line[
'tva_tx'] = $this->
defaultVatRate($socid, (
int) ($line[
'fk_product'] ?? 0), $buy);
4201 $text = trim((
string) $value);
4209 $langs->load(
'other');
4210 $this->writeProblems[] = $langs->transnoentitiesnoconv(
'AIWriteUnreadableDate', $text, $field);
4227 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/entrepot.class.php';
4228 $warehouses = array();
4230 foreach (array_slice($lines, 0, 10) as $line) {
4231 if (!is_array($line)) {
4234 $product = empty($line[
'fk_product']) ? null : $this->
fetchBusinessObject(
'Product', (
int) $line[
'fk_product']);
4235 $name = ($product instanceof
Product) ? $product->ref.
' - '.$product->label : (string) ($line[
'desc'] ??
'');
4237 if ($kind ===
'reception') {
4238 $wid = (int) ($line[
'fk_entrepot'] ?? 0);
4239 if ($wid > 0 && !isset($warehouses[$wid])) {
4240 $warehouse =
new Entrepot($this->db);
4241 $warehouses[$wid] = ($warehouse->fetch($wid) > 0) ? $warehouse->ref :
'#'.$wid;
4244 $text .=
' '.$langs->trans(
'AIPreviewIntoWarehouse', $warehouses[$wid]);
4246 $text .= (isset($line[
'cost_price']) && (float) $line[
'cost_price'] > 0) ?
' @ '.price($line[
'cost_price']) :
' ('.$langs->trans(
'AIPreviewNoCostPrice').
')';
4247 if (!empty($line[
'batch'])) {
4248 $text .=
', '.$langs->trans(
'Batch').
' '.$line[
'batch'];
4253 if (count($lines) > 10) {
4257 return implode(
'; ', $out);
4268 if (!empty($this->
user->fk_warehouse)) {
4269 return (
int) $this->
user->fk_warehouse;
4274 $resql = $this->db->query(
"SELECT rowid FROM ".$this->db->prefix().
"entrepot WHERE entity IN (".
getEntity(
'stock').
") AND statut = 1 LIMIT 2");
4275 if ($resql && $this->db->num_rows($resql) === 1) {
4276 $obj = $this->db->fetch_object($resql);
4278 return (
int) $obj->rowid;
4300 $langs->load(
"other");
4303 if (empty($write)) {
4307 if (!empty($write[
'update'])) {
4310 }
catch (InvalidArgumentException $e) {
4311 return $e->getMessage();
4315 return 'Record not found';
4317 if (!empty($write[
'project_update'])) {
4318 $context = (string) $parent->title;
4321 $context = $supplier ? $supplier->name :
'';
4323 $langs->load(
'sendings');
4324 $langs->load(
'bills');
4326 foreach ($write[
'update'] as $field => $definition) {
4327 if (array_key_exists($field, $args)) {
4328 $old = $parent->$field ??
null;
4329 $label = isset($write[
'preview_labels'][$field]) ? $langs->trans($write[
'preview_labels'][$field]) : $field;
4330 if (is_array($args[$field])) {
4331 foreach ($args[$field] as $key => $value) {
4332 $changes[] = $label.
'.'.$key.
': '.json_encode($old[$key] ??
null, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES).
' → '.json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
4334 } elseif (!empty($write[
'preview_objects'][$field])) {
4336 $changes[] = $label.
': '.$this->
previewObjectName((
string) $write[
'preview_objects'][$field], $old).
' → '.$this->
previewObjectName((
string) $write[
'preview_objects'][$field], $args[$field]);
4338 $isdate = in_array($field, $write[
'preview_dates'] ?? [],
true);
4339 $dateonly = !empty($write[
'preview_dateonly']);
4340 $format = $dateonly ?
'dayrfc' :
'standard';
4341 $tz = $dateonly ?
'tzserver' :
'gmt';
4342 $suffix = $dateonly ?
'' :
' UTC';
4343 $oldvalue = $isdate && is_numeric($old) ?
dol_print_date($old, $format, $tz).$suffix : json_encode($old, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
4344 $newvalue = $isdate && is_numeric($args[$field]) ?
dol_print_date($args[$field], $format, $tz).$suffix : json_encode($args[$field], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
4345 $changes[] = $label.
': '.$oldvalue.
' → '.$newvalue;
4349 return $langs->trans($write[
'preview'], $parent->ref, (
string)
$context, implode(
'; ', $changes));
4354 $kind = (string) ($write[
'kind'] ??
'');
4355 if (in_array($kind, array(
'update',
'action',
'delete',
'payment',
'line'),
true)) {
4361 if (!empty($write[
'parent'])) {
4363 $what = (string) ($args[
'desc'] ??
'');
4365 if ($product instanceof
Product) {
4366 $what = $product->ref.
' - '.$product->label;
4368 $qty = (float) ($args[
'qty'] ?? 1);
4369 $total = $qty * (float) ($args[
'subprice'] ?? 0) * (1 - (float) ($args[
'remise_percent'] ?? 0) / 100);
4371 return $langs->trans($write[
'preview'], (
string) $qty,
dol_trunc($what, 60), ($parent ? $parent->ref :
''),
price(
price2num($total,
'MT')));
4379 if (!empty($write[
'args'])) {
4381 foreach ($write[
'args'] as $argname) {
4386 $declared = (array) ($this->
methodMetaFor($toolName)[
'params'] ?? array());
4388 foreach ($args as $argname => $argvalue) {
4389 if (in_array($argname, $write[
'args'],
true) || !array_key_exists($argname, $declared) || is_array($argvalue) || (
string) $argvalue ===
'') {
4394 $values[] = empty($extra) ?
'' :
' ('.implode(
', ', $extra).
')';
4395 return $langs->trans($write[
'preview'], ...$values);
4399 $socid = (int) ($args[$write[
'thirdparty']] ?? 0);
4401 require_once DOL_DOCUMENT_ROOT.
'/societe/class/societe.class.php';
4402 $soc =
new Societe($this->db);
4403 if ($soc->fetch($socid) > 0) {
4404 $who =
' '.$langs->trans(
"AIPreviewForThirdparty", $soc->name);
4408 $lines = isset($args[$write[
'lines']]) && is_array($args[$write[
'lines']]) ? $args[$write[
'lines']] : array();
4411 foreach ($lines as $line) {
4413 $unitprice = $line[
'subprice'] ?? ($line[
'cost_price'] ??
'');
4414 if ($unitprice ===
'' || is_null($unitprice)) {
4418 $total += ((float) ($line[
'qty'] ?? 1)) * ((
float) $unitprice);
4420 $what = $langs->trans(count($lines) === 1 ?
"AIPreviewLine" :
"AIPreviewLines", (string) count($lines));
4422 $what .=
', '.price($total);
4423 } elseif (($write[
'kind'] ??
'') !==
'shipment') {
4424 $what .=
', '.$langs->trans(
"AIPreviewFromCatalogue");
4426 if (($write[
'kind'] ??
'') !==
'' && $lines) {
4428 $what .=
': '.$this->previewLogisticLines($lines, (
string) $write[
'kind']);
4431 return $langs->trans($write[
'preview'], $who, $what);
4449 if (is_array($value)) {
4452 $value = (string) $value;
4453 if ($value !==
'' && in_array($argname, (array) ($write[
'hours'] ?? array()),
true) && is_numeric($value)) {
4456 if ($value !==
'' && in_array($argname, (array) ($write[
'dates'] ?? array()),
true) && is_numeric($value)) {
4459 $class = (string) ($write[
'object'] ??
'');
4462 $argsObjects = (array) ($write[
'args_objects'] ?? array());
4463 if (isset($argsObjects[$argname]) && is_numeric($value) && (int) $value > 0 && !empty($this->db)) {
4464 $obj = $this->
fetchRecord((
string) $argsObjects[$argname], (
int) $value);
4465 return ($obj && $this->
userCanReach((
string) $argsObjects[$argname], (
int) $obj->id)) ? $this->
describeRecord($obj) : $value;
4468 if ($class !==
'' && $argname === (
string) ($write[
'target'] ??
'id') && is_numeric($value) && (
int) $value > 0 && !empty($this->db)) {
4472 if ($argname === (
string) ($write[
'thirdparty'] ??
'') && is_numeric($value) && (
int) $value > 0 && !empty($this->db)) {
4473 $soc = $this->
fetchRecord(
'Societe', (
int) $value);
4476 if ($class ===
'Ticket' && $argname ===
'track_id' && $value !==
'' && !empty($this->db)) {
4477 require_once DOL_DOCUMENT_ROOT.
'/ticket/class/ticket.class.php';
4478 $ticket =
new Ticket($this->db);
4479 if ($ticket->fetch(0,
'', $value) > 0 && $this->userCanReach(
'Ticket', (
int) $ticket->id)) {
4483 if ($argname ===
'contactid' && is_numeric($value) && (
int) $value > 0 && !empty($this->db)) {
4484 if ((
string) ($args[
'source'] ??
'external') ===
'internal') {
4485 $u =
new User($this->db);
4486 return ($u->fetch((
int) $value) > 0) ? $u->getFullName($langs) : $value;
4488 $contact = $this->
fetchRecord(
'Contact', (
int) $value);
4509 global $langs, $user;
4512 if (empty($write)) {
4519 }
catch (InvalidArgumentException $e) {
4520 return $e->getMessage();
4522 if (!empty($write[
'update'])) {
4526 $kind = (string) ($write[
'kind'] ??
'');
4527 if (in_array($kind, array(
'update',
'action',
'delete',
'payment',
'line'),
true)) {
4532 if (!empty($this->writeProblems)) {
4533 return $this->writeProblems[0];
4535 foreach ((array) ($write[
'required'] ?? array()) as $field) {
4536 if ($field !== ($write[
'thirdparty'] ??
'') && (!isset($args[$field]) || $args[$field] ===
'' || $args[$field] === array())) {
4537 $langs->load(
'other');
4538 return $langs->transnoentitiesnoconv(
'AIWriteMissingField', $field);
4542 if (!empty($write[
'thirdparty'])) {
4543 $field = (string) $write[
'thirdparty'];
4545 foreach (array($field,
'thirdparty',
'company',
'customer',
'supplier') as $key) {
4546 if (!empty($args[$key])) {
4554 $optional = !empty($write[
'thirdparty_optional']) || !in_array($field, (array) ($write[
'required'] ?? array()),
true);
4555 if ($optional && !$named) {
4561 if ($field !==
'' && is_numeric($args[$field] ??
'') && (
int) $args[$field] > 0 && $this->
user instanceof
User && !$this->
userCanReach(
'Societe', (
int) $args[$field])) {
4562 $langs->load(
'other');
4563 return $langs->transnoentitiesnoconv(
'AIWriteThirdpartyNotFound', (
string) ((
int) $args[$field]));
4565 if ($field !==
'' && (empty($args[$field]) || !is_numeric($args[$field]) || (
int) $args[$field] <= 0)) {
4566 $langs->load(
'other');
4568 foreach (array($field,
'thirdparty',
'company',
'customer',
'supplier') as $key) {
4569 if (!empty($args[$key]) && is_string($args[$key]) && !is_numeric($args[$key])) {
4570 $named = trim($args[$key]);
4574 if ($named ===
'') {
4575 return $langs->transnoentitiesnoconv(
'AIWriteNoThirdparty');
4578 require_once DOL_DOCUMENT_ROOT.
'/ai/lib/ai.lib.php';
4581 foreach ($mt[
'candidates'] as
$c) {
4582 if (
$c[
'visible']) {
4583 $names[] =
$c[
'name'].
' (id '.
$c[
'id'].
')';
4587 if (count($names) > 1) {
4588 return $langs->transnoentitiesnoconv(
'AIWriteSeveralThirdparties', $named, implode(
', ', $names));
4590 if (count($names) === 1) {
4592 return $langs->transnoentitiesnoconv(
'AIWriteThirdpartyDidYouMean', $named, $names[0]);
4595 return $langs->transnoentitiesnoconv(
'AIWriteThirdpartyNotFound', $named);
4602 $kind = (string) ($write[
'kind'] ??
'');
4604 $langs->load(
'other');
4605 $standaloneConst = ($kind ===
'reception') ?
'RECEPTION_STANDALONE' :
'SHIPMENT_STANDALONE';
4606 if (!empty($args[
'origin_id']) || !empty($args[
'origin_type'])) {
4608 return $langs->transnoentitiesnoconv(
'AIWriteLogisticFromOrder', $kind);
4611 return $langs->transnoentitiesnoconv(
'AIWriteStandaloneOff', $kind, $standaloneConst);
4613 $lines = isset($args[$write[
'lines']]) && is_array($args[$write[
'lines']]) ? $args[$write[
'lines']] : array();
4614 if (empty($lines)) {
4615 return $langs->transnoentitiesnoconv(
'AIWriteNoLines');
4617 if (!empty($this->unresolvedProducts)) {
4620 if ($kind ===
'reception') {
4621 foreach ($lines as $line) {
4622 if (!is_array($line) || empty($line[
'fk_product'])) {
4623 return $langs->transnoentitiesnoconv(
'AIWriteReceptionLineNeedsProduct', (
string) (is_array($line) ? ($line[
'desc'] ??
'') :
''));
4625 if (empty($line[
'fk_entrepot']) && !
getDolGlobalString(
'STOCK_WAREHOUSE_NOT_REQUIRED_FOR_RECEPTIONS')) {
4626 return $langs->transnoentitiesnoconv(
'AIWriteNoWarehouse');
4634 if (empty($write[
'parent'])) {
4641 if (!$parent || ($this->
user instanceof
User && !$this->
userCanReach((
string) $write[
'object'], (
int) $parent->id))) {
4642 return "No record found with ".$write[
'parent'].
"=".((string) ($args[$write[
'parent']] ??
'')).
". Look its rowid up by ref first.";
4645 if ((
int) $parent->status !== 0) {
4646 return "Record ".$parent->ref.
" is not a draft (status ".((int) $parent->status).
"): lines can only be added to a draft. Nothing was written.";
4648 if (!empty($this->unresolvedProducts)) {
4666 $wanted = trim((
string) $wanted);
4674 $stems = array($wanted);
4675 if (preg_match(
'/^(.{3,})[-\/ .][^-\/ .]+$/', $wanted, $reg)) {
4678 if (preg_match(
'/^(.{3,}?)\d+$/', $wanted, $reg)) {
4682 foreach ($stems as $stem) {
4684 $sql =
"SELECT DISTINCT pfp.ref_fourn, p.ref, p.label FROM ".$this->db->prefix().
"product_fournisseur_price as pfp";
4685 $sql .=
" INNER JOIN ".$this->db->prefix().
"product as p ON p.rowid = pfp.fk_product";
4686 $sql .=
" WHERE pfp.entity IN (".getEntity(
'productsupplierprice').
") AND pfp.fk_soc = ".((int) $socid);
4687 $sql .=
" AND pfp.ref_fourn LIKE '".$this->db->escape($this->db->escapeforlike($stem)).
"%' ORDER BY pfp.ref_fourn LIMIT 6";
4688 $resql = $this->db->query($sql);
4689 while ($resql && ($obj = $this->db->fetch_object($resql))) {
4690 $found[$obj->ref_fourn] = $obj->ref_fourn.
' = '.$obj->ref.
' ('.
dol_trunc((
string) $obj->label, 30).
')';
4693 if (empty($found)) {
4694 $sql =
"SELECT ref, label FROM ".$this->db->prefix().
"product";
4695 $sql .=
" WHERE entity IN (".getEntity(
'product').
") AND ref LIKE '".$this->db->escape($this->db->escapeforlike($stem)).
"%' ORDER BY ref LIMIT 6";
4696 $resql = $this->db->query($sql);
4697 while ($resql && ($obj = $this->db->fetch_object($resql))) {
4698 $found[$obj->ref] = $obj->ref.
' ('.
dol_trunc((
string) $obj->label, 30).
')';
4701 if (!empty($found)) {
4706 return array_slice(array_values($found), 0, 5);
4718 foreach ($this->unresolvedProducts as $wanted => $close) {
4719 $parts[] =
"'".((string) $wanted).
"'".(empty($close) ?
'' :
' (close refs: '.implode(
', ', $close).
')');
4722 return "Product ".implode(
', ', $parts).
" not found, or several products match it. A supplier reference is looked up in the catalogue of the resolved supplier only. Use a close ref if it is the right product, search with api_products_list, or create it with api_products_create first.";
4738 'Facture' =>
'/compta/facture/class/facture.class.php',
4739 'Commande' =>
'/commande/class/commande.class.php',
4740 'Propal' =>
'/comm/propal/class/propal.class.php',
4741 'FactureFournisseur' =>
'/fourn/class/fournisseur.facture.class.php',
4742 'CommandeFournisseur' =>
'/fourn/class/fournisseur.commande.class.php',
4743 'SupplierProposal' =>
'/supplier_proposal/class/supplier_proposal.class.php',
4744 'Societe' =>
'/societe/class/societe.class.php',
4745 'Product' =>
'/product/class/product.class.php',
4746 'Contact' =>
'/contact/class/contact.class.php',
4747 'Project' =>
'/projet/class/project.class.php',
4748 'Task' =>
'/projet/class/task.class.php',
4749 'Ticket' =>
'/ticket/class/ticket.class.php',
4750 'Fichinter' =>
'/fichinter/class/fichinter.class.php',
4751 'Contrat' =>
'/contrat/class/contrat.class.php',
4752 'Reception' =>
'/reception/class/reception.class.php',
4753 'Expedition' =>
'/expedition/class/expedition.class.php',
4754 'WebsitePage' =>
'/website/class/websitepage.class.php',
4755 'Website' =>
'/website/class/website.class.php'
4757 $ref = trim((
string) $ref);
4758 if (empty($paths[$class]) || ((
int)
$id <= 0 && $ref ===
'')) {
4761 require_once DOL_DOCUMENT_ROOT.$paths[$class];
4762 $obj =
new $class($this->db);
4763 '@phan-var-force Facture|Commande|Propal|FactureFournisseur|CommandeFournisseur|SupplierProposal|Societe|Product|Contact|Project|Task|Ticket|Fichinter|Contrat|Reception|Expedition|WebsitePage|Website $obj';
4764 if ((
int)
$id > 0) {
4765 $found = ($obj->fetch((
int)
$id) > 0);
4769 $found = ($obj->fetch(0, $ref) > 0);
4772 return ($found && (
int) $obj->id > 0) ? $obj :
null;
4784 global $langs, $user;
4786 $class = (string) ($write[
'object'] ??
'');
4787 $label = (string) ($write[
'label'] ?? $class);
4788 if (is_numeric($value) && (int) $value > 0) {
4791 $value = trim((
string) $value);
4792 if ($value ===
'') {
4796 $lookup = (string) ($write[
'lookup'] ??
'');
4797 if ($lookup ===
'thirdparty') {
4799 require_once DOL_DOCUMENT_ROOT.
'/ai/lib/ai.lib.php';
4803 foreach ($mt[
'candidates'] as $cid =>
$c) {
4804 if (
$c[
'visible'] && !isset($ids[$cid])) {
4806 $names[] =
$c[
'name'].
' (id '.$cid.
')';
4810 if (count($ids) === 1) {
4811 return $this->
fetchRecord($class, (
int) key($ids));
4813 if (count($ids) > 1) {
4814 $this->writeProblems[] = $langs->transnoentitiesnoconv(
'AIWriteSeveralThirdparties', $value, implode(
', ', $names));
4819 if ($lookup ===
'ref') {
4838 'Task' => array(
'task',
'',
''),
4839 'Ticket' => array(
'ticket',
'',
''),
4840 'Facture' => array(
'facture',
'',
''),
4841 'Commande' => array(
'commande',
'',
''),
4842 'Propal' => array(
'propal',
'',
''),
4843 'FactureFournisseur' => array(
'fournisseur',
'facture_fourn',
'facture'),
4844 'CommandeFournisseur' => array(
'fournisseur',
'commande_fournisseur',
'commande'),
4845 'SupplierProposal' => array(
'supplier_proposal',
'',
''),
4846 'Societe' => array(
'societe',
'',
''),
4847 'Product' => array(
'product',
'',
''),
4848 'Contact' => array(
'contact',
'socpeople&societe',
''),
4849 'Project' => array(
'project',
'',
''),
4850 'Reception' => array(
'reception',
'',
''),
4851 'Expedition' => array(
'expedition',
'',
''),
4852 'Contrat' => array(
'contrat',
'',
''),
4853 'Fichinter' => array(
'ficheinter',
'',
'')
4855 if (!isset($map[$class])) {
4858 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security.lib.php';
4872 $vars = is_object($obj) ? get_object_vars($obj) : array();
4874 return (
int) ($vars[
'socid'] ?? 0);
4885 global $conf, $langs;
4887 if ($obj instanceof
Societe) {
4888 return (
string) $obj->name;
4890 if ($obj instanceof
Product) {
4891 return $obj->ref.
' - '.$obj->label;
4893 if ($obj instanceof
Contact) {
4894 return $obj->getFullName($langs);
4896 $parts = array((
string) $obj->ref);
4898 if ($obj instanceof
Task && (
string) $obj->label !==
'') {
4899 $parts[] = (string) $obj->label;
4901 if ($obj instanceof
Ticket && (
string) $obj->subject !==
'') {
4902 $parts[] = (string) $obj->subject;
4904 if ($this->
socidOf($obj) > 0) {
4905 require_once DOL_DOCUMENT_ROOT.
'/societe/class/societe.class.php';
4906 $soc =
new Societe($this->db);
4907 if ($soc->fetch($this->socidOf($obj)) > 0) {
4908 $parts[] = $soc->name;
4911 if (!empty($obj->total_ttc)) {
4912 $parts[] =
price((
float) $obj->total_ttc, 0, $langs, 1, -1, -1,
$conf->currency);
4915 return implode(
' - ', $parts);
4929 $sql =
"SELECT rowid, ref, lieu FROM ".$this->db->prefix().
"entrepot";
4930 $sql .=
" WHERE entity IN (".getEntity(
'stock').
") AND statut = 1";
4931 $sql .=
" ORDER BY ref LIMIT 100";
4932 $resql = $this->db->query($sql);
4933 while ($resql && ($obj = $this->db->fetch_object($resql))) {
4934 $list[(int) $obj->rowid] = array((
string) $obj->ref, (string) $obj->lieu);
4937 foreach ($list as
$id => $w) {
4938 $names[] = $w[0].
' (id '.
$id.
')';
4941 return $this->
pickOne($list, $value, $names,
'AIWriteWhichWarehouse',
'AIWriteWarehouseNotFound',
'AIWriteNoOpenWarehouse');
4953 $sql =
"SELECT rowid, ref, label FROM ".$this->db->prefix().
"bank_account";
4954 $sql .=
" WHERE entity IN (".getEntity(
'bank_account').
") AND clos = 0";
4955 $sql .=
" ORDER BY label LIMIT 100";
4956 $resql = $this->db->query($sql);
4957 while ($resql && ($obj = $this->db->fetch_object($resql))) {
4958 $list[(int) $obj->rowid] = array((
string) $obj->label, (string) $obj->ref);
4961 foreach ($list as
$id => $b) {
4962 $names[] = $b[0].
' (id '.
$id.
')';
4965 return $this->
pickOne($list, $value, $names,
'AIWriteWhichBankAccount',
'AIWriteBankAccountNotFound',
'AIWriteNoBankAccount');
4979 $langs->load(
'bills');
4980 $synonyms = array(
'cash' =>
'LIQ',
'espèces' =>
'LIQ',
'check' =>
'CHQ',
'cheque' =>
'CHQ',
'chèque' =>
'CHQ',
'transfer' =>
'VIR',
'bank transfer' =>
'VIR',
'wire' =>
'VIR',
'virement' =>
'VIR',
'card' =>
'CB',
'credit card' =>
'CB',
'debit card' =>
'CB',
'carte' =>
'CB',
'direct debit' =>
'PRE');
4982 $sql =
"SELECT id, code, libelle FROM ".$this->db->prefix().
"c_paiement";
4983 $sql .=
" WHERE active = 1 AND entity IN (".getEntity(
'c_paiement').
")";
4984 $sql .=
" ORDER BY id LIMIT 100";
4985 $resql = $this->db->query($sql);
4986 while ($resql && ($obj = $this->db->fetch_object($resql))) {
4987 $list[(int) $obj->id] = array((
string) $obj->code, (string) $obj->libelle, $langs->transnoentitiesnoconv(
'PaymentType'.$obj->code), $langs->transnoentitiesnoconv(
'PaymentTypeShort'.$obj->code));
4990 foreach ($list as $p) {
4991 $names[] = $p[2].
' ('.$p[0].
')';
4994 if (isset($synonyms[$want])) {
4995 $value = $synonyms[$want];
4998 return $this->
pickOne($list, $value, $names,
'AIWriteWhichPaymentMode',
'AIWritePaymentModeNotFound',
'',
false);
5014 private function pickOne(array $list, $value, array $names, $askKey, $missingKey, $noneKey, $onlyOne =
true)
5018 $langs->load(
'other');
5020 if ($noneKey !==
'') {
5021 $this->writeProblems[] = $langs->transnoentitiesnoconv($noneKey);
5025 $value = trim((
string) $value);
5026 if ($value ===
'') {
5027 if ($onlyOne && count($list) === 1) {
5028 return (
int) key($list);
5030 $this->writeProblems[] = $langs->transnoentitiesnoconv($askKey, implode(
', ', $names));
5033 if (is_numeric($value) && isset($list[(
int) $value])) {
5034 return (
int) $value;
5037 $contains = array();
5038 foreach ($list as
$id => $known) {
5039 foreach ($known as $knownname) {
5041 if ($haystack ===
'') {
5044 if ($haystack === $want) {
5047 if (strpos($haystack, $want) !==
false) {
5048 $contains[
$id] =
true;
5052 if (count($contains) === 1) {
5053 return (
int) key($contains);
5055 $this->writeProblems[] = $langs->transnoentitiesnoconv($missingKey, $value, implode(
', ', $names));
5076 $langs->load(
'other');
5077 $class = (string) ($write[
'object'] ??
'');
5078 $label = (string) ($write[
'label'] ?? $class);
5079 $field = (string) ($write[
'target'] ??
'id');
5080 $given = $args[$field] ?? ($args[
'ref'] ??
'');
5081 unset($args[
'ref']);
5082 $canCheck = !empty($this->db) && $this->
user instanceof
User;
5083 if ((
string) $given !==
'') {
5085 if ($canCheck && (!$obj || !$this->
userCanReach($class, (
int) $obj->id))) {
5086 $this->writeProblems[] = $langs->transnoentitiesnoconv(
'AIWriteRecordNotFound', $label, (
string) $given);
5088 $args[$field] = (int) $obj->id;
5089 if (!empty($write[
'track_from_target']) && empty($args[
'track_id']) && $obj instanceof
Ticket) {
5090 $args[
'track_id'] = (string) $obj->track_id;
5093 } elseif (!empty($write[
'target_or']) && (
string) ($args[$write[
'target_or']] ??
'') !==
'') {
5094 if ($class ===
'Ticket' && $canCheck) {
5095 require_once DOL_DOCUMENT_ROOT.
'/ticket/class/ticket.class.php';
5096 $ticket =
new Ticket($this->db);
5097 if ($ticket->fetch(0,
'', (
string) $args[$write[
'target_or']]) <= 0 || !$this->userCanReach(
'Ticket', (
int) $ticket->id)) {
5098 $this->writeProblems[] = $langs->transnoentitiesnoconv(
'AIWriteRecordNotFound', $label, (
string) $args[$write[
'target_or']]);
5101 } elseif (!empty($write[
'target_or'])) {
5102 $this->writeProblems[] = $langs->transnoentitiesnoconv(
'AIWriteMissingField', $field);
5105 foreach ((array) ($write[
'refuse_values'] ?? array()) as $name => $rule) {
5106 if (!array_key_exists($name, $args) || (
string) $args[$name] ===
'') {
5109 if ($rule[
'values'] ===
null || in_array((
int) $args[$name], (array) $rule[
'values'],
true)) {
5110 $this->writeProblems[] = $langs->transnoentitiesnoconv(
'AIWriteUseOtherTool', $name, (
string) $args[$name], (
string) $rule[
'tool']);
5114 if (!empty($write[
'contact']) && $canCheck) {
5115 $source = ((string) ($args[
'source'] ??
'external') ===
'internal') ?
'internal' :
'external';
5116 $args[
'source'] = $source;
5117 $cid = (int) ($args[
'contactid'] ?? 0);
5119 if ($source ===
'internal') {
5120 $u =
new User($this->db);
5121 if ($u->fetch($cid) <= 0 || (
int) $u->status !== 1) {
5122 $this->writeProblems[] = $langs->transnoentitiesnoconv(
'AIWriteRecordNotFound',
'user', (
string) $cid);
5126 if (!$contact || !$this->
userCanReach(
'Contact', $cid)) {
5127 $this->writeProblems[] = $langs->transnoentitiesnoconv(
'AIWriteRecordNotFound',
'contact', (
string) $cid);
5132 $type = strtoupper(trim((
string) ($args[
'type'] ??
'')));
5135 $sql =
"SELECT code FROM ".$this->db->prefix().
"c_type_contact";
5136 $sql .=
" WHERE element = '".$this->db->escape((
string) $write[
'contact']).
"' AND source = '".$this->db->escape($source).
"' AND active = 1";
5137 $resql = $this->db->query($sql);
5138 while ($resql && ($o = $this->db->fetch_object($resql))) {
5139 $codes[] = (string) $o->code;
5141 if (!in_array($type, $codes,
true)) {
5142 $this->writeProblems[] = $langs->transnoentitiesnoconv(
'AIWriteUnknownRole', (
string) $args[
'type'], implode(
', ', $codes));
5144 $args[
'type'] = $type;
5164 $kind = (string) $write[
'kind'];
5165 $field = (string) ($write[
'target'] ??
'id');
5166 $given = $args[$field] ?? ($args[
'ref'] ??
'');
5168 $out = array($field => ($this->writeTarget ? (
int) $this->writeTarget->id : $given));
5170 if ($kind ===
'update') {
5171 $aliases = array(
'nom' =>
'name',
'company' =>
'name',
'mail' =>
'email',
'tel' =>
'phone',
'telephone' =>
'phone',
'mobile' =>
'phone_mobile',
'job' =>
'poste',
'libelle' =>
'label',
'title' =>
'label');
5172 $this->writeRefusedFields = array();
5173 foreach ($args as $name => $value) {
5174 if (in_array($name, array($field,
'ref',
'requestState'),
true) || substr((
string) $name, 0, 1) ===
'_') {
5177 if (isset($aliases[$name]) && in_array($aliases[$name], $write[
'fields'],
true) && !isset($args[$aliases[$name]])) {
5178 $name = $aliases[$name];
5180 if (in_array($name, $write[
'fields'],
true) && !is_array($value)) {
5181 $out[$name] = $value;
5183 $this->writeRefusedFields[] = (string) $name;
5190 if ($kind ===
'action') {
5192 foreach ((array) ($write[
'pass'] ?? array()) as $name) {
5193 if (array_key_exists($name, $args) && !is_array($args[$name])) {
5194 $out[$name] = ($args[$name] ===
'me' && $this->
user instanceof
User) ? (
int) $this->
user->id : $args[$name];
5197 if (!empty($write[
'stock']) && $this->writeTarget && $this->
validationMovesStock($write, $this->writeTarget)) {
5198 $out[
'idwarehouse'] = $this->
resolveWarehouse($args[
'warehouse'] ?? ($args[
'idwarehouse'] ??
''));
5204 if ($kind ===
'payment') {
5205 $invoice = $this->writeTarget;
5206 $remain = ($invoice instanceof
Facture) ? (
float) $invoice->getRemainToPay() : 0.0;
5207 $amount = (isset($args[
'amount']) && $args[
'amount'] !==
'') ? (
float)
price2num($args[
'amount'],
'MT') : $remain;
5208 $mode = $this->
resolvePaymentMode($args[
'payment_mode'] ?? ($args[
'paymentid'] ??
''));
5210 $date = trim((
string) ($args[
'date'] ?? ($args[
'datepaye'] ??
'')));
5211 $out[
'arrayofamounts'] = array((
string) $out[$field] => array(
'amount' => (
string) $amount,
'multicurrency_amount' =>
''));
5213 $out[
'paymentid'] = $mode;
5214 $out[
'accountid'] = $account;
5215 $out[
'num_payment'] = (string) ($args[
'num_payment'] ??
'');
5216 $out[
'comment'] = (string) ($args[
'comment'] ??
'');
5217 $out[
'chqemetteur'] = (string) ($args[
'issuer'] ?? ($args[
'chqemetteur'] ??
''));
5218 $out[
'chqbank'] = (string) ($args[
'issuer_bank'] ?? ($args[
'chqbank'] ??
''));
5219 $out[
'_amount'] = $amount;
5220 $out[
'_remain'] = $remain;
5221 if ($mode > 0 &&
dol_getIdFromCode($this->db, (
string) $mode,
'c_paiement',
'id',
'code', 1) ===
'CHQ' && $out[
'chqemetteur'] ===
'') {
5222 $langs->load(
'other');
5223 $this->writeProblems[] = $langs->transnoentitiesnoconv(
'AIWriteChequeIssuer');
5229 if ($kind ===
'line') {
5249 $action = (string) $write[
'line_action'];
5250 $profile = (string) $write[
'line_profile'];
5251 $doc = $this->writeTarget;
5252 $aliases = array(
'quantity' =>
'qty',
'unit_price' =>
'subprice',
'price' =>
'subprice',
'pu_ht' =>
'subprice',
'description' =>
'desc',
'label' =>
'desc',
'vat_rate' =>
'tva_tx',
'discount' =>
'remise_percent',
'fk_unit' =>
'unit',
'line_id' =>
'lineid',
'rowid' =>
'lineid',
'position' =>
'line',
'product_ref' =>
'line',
'product' =>
'line');
5254 foreach ($args as $name => $value) {
5255 if (in_array($name, array(
'id',
'ref',
'requestState'),
true) || substr((
string) $name, 0, 1) ===
'_') {
5258 $name = (isset($aliases[$name]) && !isset($args[$aliases[$name]])) ? $aliases[$name] : $name;
5259 if (in_array($name, array(
'line',
'lineid'),
true) && $action !==
'add') {
5262 if (in_array($name, (array) $write[
'fields'],
true) && !is_array($value)) {
5263 $changes[$name] = $value;
5264 } elseif ($name !==
'request_data') {
5265 $this->writeRefusedFields[] = (string) $name;
5269 $langs->load(
'other');
5272 if ($action !==
'add' && $doc && (
int) $doc->status === 0) {
5273 $wanted = $args[
'lineid'] ?? ($args[
'line_id'] ?? ($args[
'rowid'] ??
''));
5274 $byid = ((string) $wanted !==
'');
5276 $wanted = $args[
'line'] ?? ($args[
'position'] ?? ($args[
'product_ref'] ?? ($args[
'product'] ??
'')));
5281 foreach (array_values((array) $doc->lines) as $i => $l) {
5282 if ($byid || is_numeric($wanted)) {
5284 if ($byid ? ((
int) $l->id === (
int) $wanted) : ((int) $wanted === $i + 1)) {
5285 $found[$i + 1] = $l;
5290 $ref =
dol_strtolower((
string) ($l->product_ref ?? ($l->ref ??
'')));
5292 if ($w !==
'' && $ref === $w) {
5293 $exact[$i + 1] = $l;
5294 } elseif ($w !==
'' && strpos($words, $w) !==
false) {
5295 $found[$i + 1] = $l;
5301 if ((
string) $wanted ===
'') {
5302 $this->writeProblems[] = $langs->transnoentitiesnoconv(
'AIWriteLineNotGiven', $this->
linesSummary($doc));
5303 } elseif (count($found) === 1) {
5304 $position = (int) key($found);
5305 $line = reset($found);
5307 $this->writeProblems[] = $langs->transnoentitiesnoconv(count($found) ?
'AIWriteLineSeveral' :
'AIWriteLineNotFound', (string) $wanted, $this->
linesSummary($doc));
5312 if (isset($changes[
'unit'])) {
5315 $this->writeProblems[] = $langs->transnoentitiesnoconv(
'AIWriteUnknownUnit', (
string) $changes[
'unit']);
5317 $changes[
'unit'] = $unit;
5319 foreach (array(
'qty',
'subprice',
'remise_percent',
'tva_tx') as $num) {
5320 if (isset($changes[$num])) {
5321 $changes[$num] = (float)
price2num($changes[$num]);
5324 if (isset($changes[
'duration'])) {
5325 $changes[
'duration'] = (int) round((
float)
price2num($changes[
'duration']) * 3600);
5327 if (isset($changes[
'date']) && !is_numeric($changes[
'date'])) {
5328 $changes[
'date'] = $this->
writeDate(
'date', $changes[
'date'], 0);
5329 if ($changes[
'date'] ===
null) {
5330 unset($changes[
'date']);
5333 $this->writeLine = array(
'line' => $line,
'position' => $position,
'changes' => $changes);
5335 if ($action ===
'delete') {
5336 $out[
'lineid'] = $line ? (int) $line->id : 0;
5339 if ($profile ===
'intervention') {
5341 foreach (array(
'desc' =>
'description',
'date' =>
'date',
'duration' =>
'duration') as $from => $to) {
5342 if (array_key_exists($from, $changes)) {
5343 $body[$to] = $changes[$from];
5346 if ($action ===
'add') {
5347 $body += array(
'date' =>
dol_now(),
'duration' => 0);
5349 $out[
'lineid'] = $line ? (int) $line->id : 0;
5351 $out[
'_body'] = $body;
5357 $out[
'lineid'] = $line ? (int) $line->id : 0;
5360 $keep = array(
'desc',
'label',
'subprice',
'qty',
'remise_percent',
'tva_tx',
'localtax1_tx',
'localtax2_tx',
'info_bits',
'date_start',
'date_end',
'product_type',
'fk_parent_line',
'fk_fournprice',
'pa_ht',
'special_code',
'fk_unit',
'ref_ext',
'rang',
'situation_percent',
'fk_product',
'ref_supplier',
'date_start_real',
'date_end_real');
5361 foreach ($keep as $field) {
5362 $body[$field] = $line->$field ??
null;
5364 if ($profile ===
'supplier') {
5365 $body[
'subprice'] = $line->pu_ht ?? ($line->subprice ??
null);
5366 $body[
'desc'] = $line->description ?? ($line->desc ??
null);
5367 } elseif ($profile ===
'contract') {
5368 $body[
'desc'] = $line->description ?? ($line->desc ??
null);
5369 $body[
'fk_fourn_price'] = $line->fk_fournprice ??
null;
5371 $body[
'array_options'] = is_array($line->array_options ??
null) ? $line->array_options : array();
5373 if (!array_key_exists(
'tva_tx', $changes) && !empty($line->vat_src_code) && strpos((
string) $body[
'tva_tx'],
'(') ===
false) {
5374 $body[
'tva_tx'] = $body[
'tva_tx'].
' ('.$line->vat_src_code.
')';
5377 foreach (array(
'qty',
'subprice',
'remise_percent',
'tva_tx',
'desc') as $field) {
5378 if (array_key_exists($field, $changes)) {
5379 $body[$field] = $changes[$field];
5382 if (array_key_exists(
'unit', $changes)) {
5383 $body[
'fk_unit'] = $changes[
'unit'];
5385 $body[
'price_base_type'] =
'HT';
5386 $body[
'multicurrency_subprice'] = 0;
5387 if ($profile ===
'supplier') {
5388 $body[
'pu_ht'] = $body[
'subprice'] ??
null;
5389 $body[
'description'] = $body[
'desc'] ??
null;
5390 unset($body[
'subprice'], $body[
'desc']);
5392 $out[
'_body'] = $body;
5406 foreach (array_values((array) $doc->lines) as $i => $l) {
5411 $list[] = ($i + 1).
': '.
dol_trunc($this->
lineName($l), 40).(isset($l->qty) ?
' x '.((float) $l->qty) :
'');
5414 return $list ? implode(
'; ', $list) :
'-';
5425 $ref = (string) ($l->product_ref ?? ($l->ref ??
''));
5426 $label = (string) ($l->product_label ??
'');
5429 return $ref !==
'' ? $ref.($label !==
'' ?
' - '.$label :
'') : $text;
5444 foreach ((array) $obj->lines as $line) {
5445 if (!empty($line->fk_product) && (
int) $line->product_type === 0) {
5464 if (!empty($write[
'project'])) {
5465 $field = (string) $write[
'project'];
5466 $given = $args[$field] ?? ($args[
'project'] ??
'');
5467 unset($args[
'project']);
5468 if ($given !==
'' && $given !== 0 && $given !==
'0') {
5469 $project = $this->
resolveWriteTarget(array(
'object' =>
'Project',
'lookup' =>
'ref'), $given);
5470 if (!$project && !is_numeric($given)) {
5472 $sql =
"SELECT rowid FROM ".$this->db->prefix().
"projet";
5473 $sql .=
" WHERE entity IN (".getEntity(
'project').
") AND title = '".$this->db->escape((
string) $given).
"'";
5475 $resql = $this->db->query($sql);
5476 if ($resql && $this->db->num_rows($resql) === 1) {
5477 $obj = $this->db->fetch_object($resql);
5478 $project = $this->
fetchRecord(
'Project', (
int) $obj->rowid);
5482 $args[$field] = (int) $project->id;
5483 $args[
'_project'] = $project->ref.
' - '.$project->title;
5485 $langs->load(
'other');
5486 $this->writeProblems[] = $langs->transnoentitiesnoconv(
'AIWriteProjectNotFound', (
string) $given);
5490 foreach ((array) ($write[
'dates'] ?? array()) as $field) {
5491 if (isset($args[$field]) && $args[$field] !==
'now' && !is_numeric($args[$field])) {
5492 $args[$field] = $this->
writeDate($field, $args[$field], 0);
5493 if ($args[$field] ===
null) {
5494 unset($args[$field]);
5499 foreach ((array) ($write[
'text_dates'] ?? array()) as $field) {
5500 if (!isset($args[$field]) || is_numeric($args[$field])) {
5503 if (in_array(
dol_strtolower(trim((
string) $args[$field])), array(
'today',
'now'),
true)) {
5505 } elseif ($this->
writeDate($field, $args[$field]) ===
null) {
5506 unset($args[$field]);
5509 foreach ((array) ($write[
'hours'] ?? array()) as $field) {
5510 if (isset($args[$field]) && is_numeric($args[$field])) {
5511 $args[$field] = (int) round((
float) $args[$field] * 3600);
5529 $obj = $this->writeTarget;
5530 $what = $obj ? $this->
describeRecord($obj) : (string) ($args[$write[
'target'] ??
'id'] ??
'');
5531 $kind = (string) $write[
'kind'];
5533 if ($kind ===
'update') {
5535 foreach ((array) $write[
'fields'] as $name) {
5536 if (!array_key_exists($name, $args)) {
5539 $old = ($obj && isset($obj->$name) && !is_array($obj->$name)) ? (
string) $obj->$name :
'';
5540 $changes[] = $name.
' "'.
dol_trunc($old, 40).
'" → "'.
dol_trunc((
string) $args[$name], 40).
'"';
5543 return $langs->trans($write[
'preview'], $write[
'label'], $what, implode(
', ', $changes));
5545 if ($kind ===
'delete') {
5546 return $langs->trans($write[
'preview'], $write[
'label'], $what);
5548 if ($kind ===
'line') {
5551 if ($kind ===
'payment') {
5552 $mode = (int) ($args[
'paymentid'] ?? 0);
5553 $code = $mode > 0 ? (string)
dol_getIdFromCode($this->db, (
string) $mode,
'c_paiement',
'id',
'code', 1) :
'';
5555 if ((
int) ($args[
'accountid'] ?? 0) > 0) {
5556 require_once DOL_DOCUMENT_ROOT.
'/compta/bank/class/account.class.php';
5557 $acc =
new Account($this->db);
5558 if ($acc->fetch((
int) $args[
'accountid']) > 0) {
5559 $account = $acc->label;
5563 $how = $langs->transnoentitiesnoconv(
'AIPreviewPaymentHow', ($code !==
'' ? $langs->transnoentitiesnoconv(
'PaymentType'.$code) :
''), $account,
dol_print_date(
dol_stringtotime((
string) $args[
'datepaye']),
'day'));
5565 return $langs->trans($write[
'preview'],
price((
float) ($args[
'_amount'] ?? 0)), $what, $how);
5569 if (array_key_exists(
'fk_user_assign', $args) && !empty($write[
'preview_unassign'])) {
5570 if ((
int) $args[
'fk_user_assign'] <= 0) {
5571 return $langs->trans($write[
'preview_unassign'], $what);
5573 $assignee =
new User($this->db);
5574 $name = ($assignee->fetch((
int) $args[
'fk_user_assign']) > 0) ? $assignee->getFullName($langs) : (string) $args[
'fk_user_assign'];
5576 return $langs->trans($write[
'preview'], $what, $name);
5578 if (!empty($args[
'cancel']) && !empty($write[
'preview_cancel'])) {
5579 return $langs->trans($write[
'preview_cancel'], $what);
5583 if (!empty($args[
'idwarehouse'])) {
5584 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/entrepot.class.php';
5586 if ($wh->fetch((
int) $args[
'idwarehouse']) > 0) {
5587 $what .=
', '.$langs->trans(
'AIPreviewStockFrom', (
string) $wh->ref);
5591 return $langs->trans($write[
'preview'], $what);
5606 $langs->load(
'main');
5607 $langs->load(
'products');
5608 $langs->load(
'interventions');
5609 $line = $this->writeLine[
'line'];
5610 $changes = $this->writeLine[
'changes'];
5611 $position = (string) $this->writeLine[
'position'];
5612 $labels = array(
'qty' =>
'Qty',
'subprice' =>
'PriceUHT',
'remise_percent' =>
'Discount',
'tva_tx' =>
'VAT',
'desc' =>
'Description',
'unit' =>
'Unit',
'date' =>
'Date',
'duration' =>
'Duration');
5614 foreach ($changes as $name => $new) {
5615 $old = $line ? ($line->{$name ===
'unit' ?
'fk_unit' : ($name ===
'subprice' && isset($line->pu_ht) ?
'pu_ht' : $name)} ??
null) :
null;
5616 if ($name ===
'desc') {
5617 $old = $line ? ($line->desc ?? ($line->description ??
'')) :
'';
5619 if ($name ===
'unit') {
5622 } elseif ($name ===
'subprice') {
5623 $old = ($old ===
null) ?
'' :
price((
float) $old);
5624 $new =
price((
float) $new);
5625 } elseif ($name ===
'duration') {
5628 } elseif ($name ===
'date') {
5631 } elseif (in_array($name, array(
'qty',
'remise_percent',
'tva_tx'),
true)) {
5632 $old = ($old ===
null) ?
'' : (string) ((
float) $old);
5633 $new = (string) ((
float) $new);
5638 $text[] = $langs->transnoentitiesnoconv($labels[$name]).
' '.($write[
'line_action'] ===
'add' ?
'' : $old.
' → ').$new;
5641 if ($write[
'line_action'] ===
'add') {
5642 return $langs->trans($write[
'preview'], $what, implode(
', ', $text));
5645 if ($write[
'line_action'] ===
'delete') {
5646 $amount = ($line && isset($line->total_ht)) ?
', '.
price((
float) $line->total_ht) :
'';
5647 return $langs->trans($write[
'preview'], $position, $what, $name.(isset($line->qty) ?
' x '.((float) $line->qty) :
'').$amount);
5650 if ($line && (array_key_exists(
'qty', $changes) || array_key_exists(
'subprice', $changes) || array_key_exists(
'remise_percent', $changes))) {
5651 $qty = (float) ($changes[
'qty'] ?? $line->qty);
5652 $pu = (float) ($changes[
'subprice'] ?? ($line->pu_ht ?? $line->subprice));
5653 $rem = (float) ($changes[
'remise_percent'] ?? $line->remise_percent);
5654 $text[] = $langs->transnoentitiesnoconv(
'TotalHT').
' '.
price((
float) ($line->total_ht ?? 0)).
' → '.
price(
price2num($qty * $pu * (1 - $rem / 100),
'MT'));
5657 return $langs->trans($write[
'preview'], $position, $what, $name, implode(
', ', $text));
5670 if (
$id <= 0 || empty($this->db)) {
5673 $resql = $this->db->query(
"SELECT label, short_label FROM ".$this->db->prefix().
"c_units WHERE rowid = ".((
int)
$id));
5674 $obj = $resql ? $this->db->fetch_object($resql) :
null;
5676 return $obj ? $langs->transnoentitiesnoconv((
string) $obj->label) : (string)
$id;
5690 $langs->load(
'other');
5691 $obj = $this->writeTarget;
5692 $label = (string) $write[
'label'];
5693 $given = (string) ($args[$write[
'target'] ??
'id'] ??
'');
5694 if (!empty($this->writeProblems)) {
5695 return $this->writeProblems[0];
5697 if (!$obj || !$this->userCanReach((
string) $write[
'object'], (int) $obj->id)) {
5698 return $langs->transnoentitiesnoconv(
'AIWriteRecordNotFound', $label, $given);
5700 $kind = (string) $write[
'kind'];
5702 if ($kind ===
'update') {
5703 if (!empty($this->writeRefusedFields)) {
5704 return $langs->transnoentitiesnoconv(
'AIWriteFieldsNotAllowed', implode(
', ', $this->writeRefusedFields), implode(
', ', (array) $write[
'fields']));
5706 if (count($args) < 2) {
5707 return $langs->transnoentitiesnoconv(
'AIWriteNothingToChange');
5712 if ($kind ===
'action' && isset($write[
'states'])) {
5714 if (!in_array((
int) $obj->status, (array) $write[
'states'],
true)) {
5715 return $langs->transnoentitiesnoconv((
string) $write[
'state_error'], $label, (string) $obj->ref);
5717 if (array_key_exists(
'fk_user_assign', $args) && (int) $args[
'fk_user_assign'] > 0) {
5718 $assignee =
new User($this->db);
5719 if ($assignee->fetch((
int) $args[
'fk_user_assign']) <= 0 || (
int) $assignee->status !== 1) {
5720 return $langs->transnoentitiesnoconv(
'AIWriteRecordNotFound',
'user', (
string) $args[
'fk_user_assign']);
5726 if ($kind ===
'line') {
5727 if ((
int) $obj->status !== 0) {
5728 return $langs->transnoentitiesnoconv(
'AIWriteNotDraftLines', $label, (
string) $obj->ref);
5730 if (!empty($this->writeRefusedFields)) {
5731 return $langs->transnoentitiesnoconv(
'AIWriteFieldsNotAllowed', implode(
', ', $this->writeRefusedFields), implode(
', ', (array) $write[
'fields']));
5733 $changes = $this->writeLine[
'changes'];
5734 if ($write[
'line_action'] ===
'update' && !$changes) {
5735 return $langs->transnoentitiesnoconv(
'AIWriteNothingToChange');
5737 if ($write[
'line_action'] ===
'add' && trim((
string) ($changes[
'desc'] ??
'')) ===
'') {
5738 return $langs->transnoentitiesnoconv(
'AIWriteMissingField',
'desc');
5740 if (array_key_exists(
'qty', $changes) && (
float) $changes[
'qty'] <= 0) {
5741 return $langs->transnoentitiesnoconv(
'AIWriteLineQtyZero');
5746 if ($kind ===
'action' || $kind ===
'delete') {
5747 if ((
int) $obj->status !== 0) {
5748 return $langs->transnoentitiesnoconv($kind ===
'action' ?
'AIWriteNotDraftValidate' :
'AIWriteNotDraftDelete', $label, (string) $obj->ref);
5750 if ($kind ===
'action' && count((array) $obj->lines) === 0) {
5751 return $langs->transnoentitiesnoconv(
'AIWriteValidateNoLines', $label, (
string) $obj->ref);
5756 if ($kind ===
'payment') {
5757 $remain = (float) ($args[
'_remain'] ?? 0);
5758 if ((
int) $obj->status !== 1 || !empty($obj->paye) || $remain <= 0) {
5759 return $langs->transnoentitiesnoconv(
'AIWriteInvoiceNotPayable', (
string) $obj->ref);
5761 $amount = (float) ($args[
'_amount'] ?? 0);
5763 return $langs->transnoentitiesnoconv(
'AIWritePaymentAmountInvalid');
5765 if ($amount > $remain) {
5766 return $langs->transnoentitiesnoconv(
'AIWritePaymentTooHigh',
price($amount), (string) $obj->ref,
price($remain));
5781 $meta = $this->methodMetaFor($toolName);
5783 return isset($meta[
'write']) ? $meta[
'write'] : array();
5794 foreach ($this->enrichments as $key => $meta) {
5795 foreach (($meta[
'methods'] ?? array()) as $method => $mmeta) {
5796 $suffix = $mmeta[
'suffix'] ?? ($method ===
'index' ?
'list' : strtolower($method));
5797 if ($toolName ===
'api_'.$key.
'_'.$suffix) {
5820 foreach ($args as $name => $value) {
5821 if ($value ===
'me' && stripos((
string) $name,
'user') !==
false) {
5822 $args[$name] = (int) $this->
user->id;
5823 } elseif (is_array($value)) {
5824 $args[$name] = $this->resolveUserSentinels($value);
5842 foreach (array_keys($this->enrichments) as $key) {
5843 $all = array_merge($all, self::ENDPOINT_CATEGORIES[$key] ?? array());
5846 return array_values(array_unique($all));
5857 'thirdparties' =>
'societe',
5858 'contacts' =>
'socpeople',
5859 'invoices' =>
'facture',
5860 'supplierinvoices' =>
'facture_fourn',
5861 'orders' =>
'commande',
5862 'supplierorders' =>
'commande_fournisseur',
5863 'proposals' =>
'propal',
5864 'supplierproposals' =>
'supplier_proposal',
5865 'products' =>
'product',
5866 'contracts' =>
'contrat',
5867 'interventions' =>
'fichinter',
5868 'tickets' =>
'ticket',
5869 'projects' =>
'projet',
5870 'tasks' =>
'project_task',
5871 'members' =>
'adherent',
5872 'expensereports' =>
'expensereport',
5873 'shipments' =>
'expedition',
5874 'receptions' =>
'reception',
5875 'agendaevents' =>
'actioncomm',
5876 'warehouses' =>
'stock',
5877 'categories' =>
'categorie',
5878 'bankaccounts' =>
'bank_account',
5879 'donations' =>
'don',
5880 'holidays' =>
'holiday',
5881 'boms' =>
'bom_bom',
5883 'productlots' =>
'product_lot',
5884 'knowledgemanagement' =>
'knowledgemanagement_knowledgerecord',
5885 'memberstypes' =>
'adherent_type',
5886 'partnerships' =>
'partnership',
5887 'workstations' =>
'workstation_workstation',
5888 'socialcontributions' =>
'chargesociales',
5889 'variouspayments' =>
'payment_various',
5890 'vatpayments' =>
'tva'
5893 return $map[$key] ??
'';
5906 $aliases = array(
'contrat' =>
'contract',
'projet' =>
'project',
'categorie' =>
'category',
'adherent' =>
'member');
5907 $part = $aliases[$modulepart] ?? $modulepart;
5908 $paginated = is_array($output) && isset($output[
'data']) && is_array($output[
'data']);
5909 $files = $paginated ? $output[
'data'] : $output;
5910 if (!is_array($files)) {
5914 foreach ($files as $file) {
5915 $level1 = (string) ($file[
'level1name'] ??
'');
5917 'name' => (
string) ($file[
'name'] ??
''),
5919 'modified' =>
dol_print_date((
int) ($file[
'date'] ?? 0),
'dayhour'),
5920 'url' => DOL_URL_ROOT.
'/document.php?modulepart='.urlencode($part).
'&file='.urlencode(($level1 !==
'' ? $level1.
'/' :
'').(
string) ($file[
'relativename'] ?? $file[
'name'] ??
''))
5924 $output[
'data'] = $list;
5940 $paginated = is_array($output) && isset($output[
'data']) && is_array($output[
'data']);
5941 $entries = $paginated ? $output[
'data'] : $output;
5942 if (!is_array($entries)) {
5946 foreach ($entries as $entry) {
5947 $isdir = (($entry[
'type'] ??
'') ===
'dir');
5949 'type' => $isdir ?
'dir' :
'file',
5950 'name' => (string) ($entry[
'name'] ??
''),
5951 'path' => (string) ($entry[
'relativename'] ??
''),
5952 'modified' =>
dol_print_date((
int) ($entry[
'date'] ?? 0),
'dayhour')
5956 $item[
'url'] = DOL_URL_ROOT.
'/document.php?modulepart='.urlencode($modulepart).
'&file='.urlencode($item[
'path']);
5961 $output[
'data'] = $list;
5975 $object = fetchObjectByElement((
int) ($args[
'id'] ?? 0), (
string) ($args[
'modulepart'] ??
''), (
string) ($args[
'ref'] ??
''));
5989 $paginated = isset($output[
'data']) && is_array($output[
'data']);
5990 $isList = $paginated || array_key_exists(0, $output);
5991 $records = $paginated ? $output[
'data'] : ($isList ? $output : array($output));
5993 $drop = array_flip((array) ($meta[
'drop_fields'] ?? array()));
5994 if (!empty($drop)) {
5995 foreach ($records as $i => $record) {
5996 if (is_array($record)) {
5997 $records[$i] = array_diff_key($record, $drop);
6005 $max = (int) ($meta[
'max_items'] ?? 0);
6006 $total = count($records);
6007 if ($max > 0 && $total > $max) {
6008 $records = (($meta[
'keep'] ??
'first') ===
'last') ? array_slice($records, -$max) : array_slice($records, 0, $max);
6011 'data' => array_values($records),
6012 'pagination' => array(
'total' => $total,
'shown' => $max),
6013 'note' =>
'Only '.$max.
' of '.$total.
' are shown: narrow the request (a period, a filter) to see the others.'
6017 $output[
'data'] = $records;
6037 $obj = $this->fetchRecord($class,
$id);
6038 if (!$obj || !$this->
user instanceof
User) {
6041 $result = $obj->add_contact((
int) $this->
user->id, $code,
'internal');
6043 dol_syslog(get_class($this).
'::addCreatorContact '.$class.
' '.
$id.
' '.$code.
' result='.$result.
' '.$obj->error, LOG_WARNING);
6055 public function execute(
string $name, array $args)
6057 $args = $this->applyFixedParams($name, $args);
6062 $writemeta = $this->writeMetaFor($name);
6065 $args = $this->normaliseWriteArgs($args, $writemeta);
6066 }
catch (InvalidArgumentException $e) {
6067 return [
'error' => $e->getMessage()];
6071 $args = $this->resolveUserSentinels($args);
6073 $this->getDefinitions();
6074 if (empty($this->routes[$name])) {
6075 return [
"error" =>
"Tool function '$name' not found."];
6077 list($key, $method) = $this->routes[$name];
6078 $epkey = (string) ($this->enrichments[$key][
'endpoint'] ?? $key);
6079 $ep = $this->endpoints[$epkey];
6087 $writekind = (string) ($writemeta[
'kind'] ??
'');
6088 foreach ((array) ($writemeta[
'fixed'] ?? array()) as $field => $value) {
6089 $args[$field] = $value;
6091 if ($writekind ===
'delete' && $this->writeTarget) {
6092 $refbefore = (string) $this->writeTarget->ref;
6102 $methodmeta = isset($this->enrichments[$key][
'methods'][$method]) ? $this->enrichments[$key][
'methods'][$method] : array();
6103 if (!empty($methodmeta[
'default_properties']) && !array_key_exists(
'properties', $args)) {
6104 $args[
'properties'] = $methodmeta[
'default_properties'];
6111 $this->loadApiRuntime();
6120 $saveduserapi = DolibarrApiAccess::$user;
6121 $saveduserglobal = empty($GLOBALS[
'user']) ? null : $GLOBALS[
'user'];
6122 DolibarrApiAccess::$user = $this->user;
6123 $GLOBALS[
'user'] = $this->user;
6125 require_once $ep[
'path'];
6126 $api =
new $ep[
'class']();
6129 $rm =
new ReflectionMethod($ep[
'class'], $method);
6132 foreach ($rm->getParameters() as $p) {
6133 $pname = $p->getName();
6137 if ($pname ===
'request_data') {
6139 if ($writekind ===
'line') {
6140 $callArgs[] = (array) ($args[
'_body'] ?? array());
6143 if (!empty($writemeta[
'update'])) {
6144 $callArgs[] = array_intersect_key($args, $writemeta[
'update']);
6148 unset($body[
'requestState']);
6154 if (!empty($writemeta) && empty($writemeta[
'parent']) && !empty($methodmeta[
'params'])) {
6155 $body = array_intersect_key($body, $methodmeta[
'params']);
6158 if ($writekind ===
'update') {
6159 $body = array_intersect_key($args, array_flip((array) $writemeta[
'fields']));
6161 foreach (array_keys($body) as $field) {
6162 if (substr((
string) $field, 0, 1) ===
'_') {
6163 unset($body[$field]);
6166 foreach (($writemeta[
'defaults'] ?? array()) as $field => $default) {
6167 if (!isset($body[$field])) {
6168 if ($default ===
'now') {
6170 } elseif ($default ===
'me') {
6171 $default = (int) $this->
user->id;
6173 $body[$field] = $default;
6178 foreach (($writemeta[
'rename'] ?? array()) as $from => $to) {
6179 if (array_key_exists($from, $body) && !isset($body[$to])) {
6180 $body[$to] = $body[$from];
6181 unset($body[$from]);
6187 foreach (($writemeta[
'copy'] ?? array()) as $from => $to) {
6188 if (isset($body[$from])) {
6189 $body[$to] = $body[$from];
6192 $callArgs[] = $body;
6200 if (array_key_exists($pname, $args)
6201 && (empty($writemeta) || empty($methodmeta[
'params']) || array_key_exists($pname, $methodmeta[
'params'])
6202 || isset($methodmeta[
'fixed_params'][$pname])
6203 || in_array($writekind, array(
'update',
'action',
'delete',
'payment',
'line'),
true))) {
6205 $callArgs[] = ($pname ==
'limit') ? min((
int) $args[$pname], self::BRIDGE_MAX_LIMIT) : $args[$pname];
6206 } elseif ($p->isOptional()) {
6208 $callArgs[] = ($pname ==
'limit') ? self::BRIDGE_DEFAULT_LIMIT : $p->getDefaultValue();
6210 $output = [
"error" =>
"Missing required parameter '$pname'."];
6215 if ($output ===
null) {
6220 $result = call_user_func_array([$api, $method], $callArgs);
6222 $output = json_decode(json_encode($result),
true);
6223 if (in_array($writekind, array(
'update',
'action',
'delete',
'payment',
'line'),
true)) {
6226 $targetid = (int) ($args[$writemeta[
'target'] ??
'id'] ?? 0);
6227 $done = array(
'success' =>
true,
'id' => $targetid);
6228 if ($writekind ===
'payment') {
6229 $done[
'payment_id'] = (int) $result;
6231 $ref = ($writekind ===
'delete') ? $refbefore : $this->refOfCreatedObject((
string) $writemeta[
'object'], $targetid);
6233 if ($writekind ===
'delete' && $this->fetchRecord((
string) $writemeta[
'object'], $targetid)) {
6234 $done = array(
'error' =>
'The '.$writemeta[
'label'].
' '.$refbefore.
' could not be deleted.',
'http_status' => 500);
6235 dol_syslog(get_class($this).
'::execute '.$name.
' reported success but the record is still there', LOG_ERR);
6238 $done[
'ref'] = $ref;
6241 } elseif (!empty($writemeta[
'compact_result'])) {
6242 if (!is_array($output) || (
int) ($output[
'id'] ?? 0) !== (
int) $args[$writemeta[
'parent']] || !is_string($output[
'ref'] ??
null) || $output[
'ref'] ===
'') {
6243 throw new RuntimeException(
'The API did not return the updated record');
6245 $output = [
'success' =>
true,
'id' => (int) $output[
'id'],
'ref' => $output[
'ref']];
6246 } elseif ($epkey ===
'documents' && !is_array($output)) {
6248 $output = array(
'success' =>
true,
'filename' => (
string) $output);
6249 } elseif (!is_array($output)) {
6252 $output = array(
'success' =>
true,
'id' => (
int) $output);
6255 if (!empty($writemeta[
'parent'])) {
6256 $output = array(
'success' =>
true,
'line_id' => (
int) $output[
'id'],
'id' => (
int) ($args[$writemeta[
'parent']] ?? 0));
6260 if (!empty($writemeta[
'object']) && $output[
'id'] > 0) {
6261 $ref = $this->refOfCreatedObject($writemeta[
'object'], $output[
'id']);
6263 $output[
'ref'] = $ref;
6265 if (!empty($writemeta[
'creator_contact'])) {
6266 $this->addCreatorContact((
string) $writemeta[
'object'], (
int) $output[
'id'], (
string) $writemeta[
'creator_contact']);
6270 if ($epkey ===
'documents' && $method ===
'getDocumentsListByElement') {
6271 $output = $this->projectDocumentList($output, (
string) ($args[
'modulepart'] ??
''));
6273 if ($epkey ===
'documents' && $method ===
'getDocumentsListByDirectory') {
6274 $output = $this->projectDirectoryList($output, (
string) ($args[
'modulepart'] ??
''));
6276 }
catch (Throwable $e) {
6277 $code = (int) $e->getCode();
6278 $message = $e->getMessage();
6279 if ($message ===
'') {
6282 $message =
'Access denied or resource error (HTTP '.($code > 0 ? $code : 500).
').';
6284 if (strpos($message,
'Error when validating parameter sqlfilters') === 0) {
6289 dol_syslog(get_class($this).
'::execute '.$name.
' '.$message, LOG_WARNING);
6290 $langs->load(
'other');
6291 $message = $langs->transnoentitiesnoconv(
'AIBadSearchFilter');
6294 "error" => $message,
6295 "http_status" => ($code > 0 ? $code : 500)
6300 if ($epkey ===
'documents' && $method ===
'getDocumentsListByElement' && $code == 404 && $this->documentObjectExists($args)) {
6304 $printed = ob_get_clean();
6305 if ($printed !==
'' && $printed !==
false) {
6306 dol_syslog(get_class($this).
'::execute '.$name.
' printed output: '.
dol_trunc(strip_tags($printed), 200), LOG_WARNING);
6311 if (!empty($methodmeta[
'needs_id']) && is_array($output) && !isset($output[
'error']) && empty($output[
'id'])) {
6312 $output = array(
'error' => (
string) $methodmeta[
'needs_id'],
'http_status' => 404);
6316 if (is_array($output) && !isset($output[
'error']) && (!empty($methodmeta[
'max_items']) || !empty($methodmeta[
'drop_fields']))) {
6317 $output = $this->shapeReadOutput($output, $methodmeta);
6321 $elementForExtrafields = $this->extrafieldsElementForEndpoint($epkey);
6322 if ($elementForExtrafields !==
'' && empty($writemeta[
'compact_result'])) {
6323 require_once DOL_DOCUMENT_ROOT.
'/ai/lib/ai.lib.php';
6328 DolibarrApiAccess::$user = $saveduserapi;
6329 if ($saveduserglobal !==
null) {
6330 $GLOBALS[
'user'] = $saveduserglobal;
6345 $this->getDefinitions();
6346 if (empty($this->routes[$name])) {
6349 list($key, $method) = $this->routes[$name];
6352 'endpoint' => (
string) $key,
6353 'method' => (
string) $method,
6354 'suffix' => (
string) substr($name, strlen(
'api_'.$key.
'_')),
6355 'label' => (
string) ($this->enrichments[$key][
'label'] ?? ($this->endpoints[$this->enrichments[$key][
'endpoint'] ?? $key][
'label'] ?? $key))
$id
Support class for third parties, contacts, members, users or resources.
if(! $sortfield) if(! $sortorder) $object
aiUnitIdFromName($db, $name)
Unit id from the word a user used for it: code, short label or label, in the user's language,...
aiFindThirdpartiesInText($db, $user, $text, $nature='', $stopwords=array(), $maxwords=80)
Third parties named in a text, by the words of their name or trade name (name_alias),...
aiStripPersonalExtrafields($db, $payload, $elementtype)
Remove extrafields flagged as personal data from an API-shaped payload.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to manage bank accounts.
Class to manage warehouses.
Class to manage invoices.
Class to manage predefined suppliers products.
Class to manage products or services.
hasbatch()
Return if the object has a batch management.
Class to manage projects.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage Dolibarr users.
if(! $sortfield) if(! $sortorder) $module
$context
@method int call_trigger(string $triggerName, ?User $user)
convertSecondToTime($iSecond, $format='all', $lengthOfDay=86400, $lengthOfWeek=7)
Return, in clear text, value of a number of seconds in days, hours and minutes.
dol_stringtotime($string, $gm=1, $processnotimeasnoon=0)
Convert a string date into a GM Timestamps date Warning: YYYY-MM-DDTHH:MM:SS+02:00 (RFC3339) is not s...
getModuleDirForApiClass($moduleobject)
Get name of directory where the api_...class.php file is stored.
dolGetModulesDirs($subdir='')
Return list of directories that contain modules.
dol_now($mode='gmt')
Return date for now.
dol_print_size($size, $shortvalue=0, $shortunit=0)
Return string with formatted size.
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='', $useCache=true)
Return an id or code from a code or id.
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
dol_strtolower($string, $encoding="UTF-8")
Convert a string to lower.
dol_strlen($string, $stringencoding='UTF-8', $binarycount=0)
Make a strlen call.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '...' if string larger than length.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.
isModEnabled($module)
Is Dolibarr module enabled.
get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
Function that return vat rate of a product line (according to seller, buyer and product vat rate) VAT...
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
conf($dolibarr_main_document_root, $realpathconf=null)
Load conf file (file must exists)
Class to generate the form for creating a new ticket.
$conf db user
Active Directory does not allow anonymous connections.
checkUserAccessToObject($user, array $featuresarray, $object=0, $tableandshare='', $feature2='', $dbt_keyfield='', $dbt_select='rowid', $parenttableforentity='')
Check that access by a given user to an object is ok.