dolibarr 25.0.0-alpha
api_bridge.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2026 Jose Martinez <jose.martinez@pichinov.com>
3 * Copyright (C) 2026 Nick Fragoulis
4 * Copyright (C) 2026 Carlos Herrera <cehojac@gmail.com>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
68{
69
79 const ENDPOINT_CATEGORIES = array(
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')
119 );
120
127 const BRIDGE_MAX_LIMIT = 100;
128
134 private $defs = null;
135
141 private $routes = [];
142
149 private $endpoints = [];
150
172 private $enrichments = [];
173
180 private $unresolvedProducts = [];
181
188 private $writeTarget = null;
189
197 private $writeProblems = [];
198
204 private $writeRefusedFields = [];
205
211 private $writeLine = array('line' => null, 'position' => 0, 'changes' => array());
212
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."
229 ];
230
238 public function __construct($db, $user = null, $conf = null)
239 {
240 $this->db = $db;
241 $this->user = $user;
242 if ($conf !== null) {
243 $this->conf = $conf;
244 }
245
246 // Note: the list of parameters for each tool is described into "params" to overload the one found into the API.
247 // They are completed with descriptions like for searchfields, pagination_data, ... if the parameter exists in the API. using the content
248 // found into $this->commonParamDocs.
249
250
251 // Third parties
252 $descriptioncreate = "Create a third party (customer, prospect or supplier). The user must confirms before anything is written.";
253
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";
267
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.";
271
272 $this->enrichments['thirdparties'] = [
273 'label' => 'third parties (customers, prospects, suppliers)',
274 'methods' => [
275 'post' => [
276 'suffix' => 'create',
277 'description' => $descriptioncreate,
278 'write' => [
279 'preview' => 'AIPreviewCreateThirdparty',
280 'required' => ['name'],
281 'object' => 'Societe',
282 'args' => ['name'],
283 'right' => ['societe', 'creer']
284 ],
285 'params' => [
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."
289 ]
290 ],
291 'index' => [
292 'default_properties' => 'id,name,name_alias,code_client,code_fournisseur,email,town,client,fournisseur,status',
293 'description' => $descriptionlist,
294 'params' => [
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."
298 ]
299 ],
300 'get' => [
301 'description' => $descriptionfetch
302 ],
303 'getByEmail' => [
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."]
307 ],
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."]
312 ],
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."]
317 ],
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'."]
322 ]
323 ]
324 ];
325
326 $this->enrichments['categories'] = [
327 'label' => 'categories / tags',
328 'methods' => [
329 'post' => [
330 'suffix' => 'create',
331 'description' => "Create a category (tag). The user confirms before anything is written.",
332 'write' => [
333 'preview' => 'AIPreviewCreateCategory',
334 'required' => ['label', 'type'],
335 'args' => ['type', 'label'],
336 'right' => ['categorie', 'creer']
337 ],
338 'params' => [
339 "label" => "Category label.", "type" => "What it classifies: product, customer, supplier, member, contact, project."
340 ]
341 ],
342 'index' => [
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.",
344 'params' => [
345 'type' => "Kind of object the category applies to: 'product', 'customer', 'supplier', 'contact', 'member', 'project', 'user', 'bank_account', 'warehouse', 'actioncomm', 'website_page', 'ticket', 'knowledgemanagement'."
346 ]
347 ],
348 'get' => [
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."]
350 ],
351 'getObjects' => [
352 'suffix' => 'objects_list',
353 'description' => "Objects tagged with one category (e.g. all products in category 12, all customers tagged 'VIP').",
354 'params' => [
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."
358 ]
359 ]
360 ]
361 ];
362
363 $this->enrichments['supplier_invoices'] = [
364 'label' => 'supplier invoices (vendor bills)',
365 'methods' => [
366 'index' => [
367 'description' => "List supplier invoices (vendor bills). Filter with sqlfilters, for example to restrict to one supplier.",
368 'params' => [
369 'sqlfilters' => "Universal filter, e.g. (t.fk_soc:=:2)",
370 'limit' => "Rows to return."
371 ]
372 ],
373 'get' => [
374 'description' => "Get one supplier invoice by rowid, with its lines."
375 ],
376 // The REST endpoint names the line fields description and pu_ht.
377 'postLine' => $this->addLineMethod('supplier invoice', 'api_supplier_invoices_list', 'FactureFournisseur', ['fournisseur', 'facture', 'creer'], true, ['desc' => 'description', 'subprice' => 'pu_ht']),
378 'post' => [
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.",
381 'write' => [
382 'preview' => 'AIPreviewCreateSupplierInvoice',
383 'required' => ['socid', 'ref_supplier'],
384 'object' => 'FactureFournisseur',
385 'thirdparty' => 'socid',
386 'lines' => 'lines',
387 'right' => ['fournisseur', 'facture', 'creer'],
388 'buy' => true,
389 'defaults' => ['date' => 'now']
390 ],
391 'params' => [
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."
395 ]
396 ]
397 ]
398 ];
399
400 $this->enrichments['supplier_orders'] = [
401 'label' => 'supplier order (purchase order)',
402 'methods' => [
403 'post' => [
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.",
406 'write' => [
407 'preview' => 'AIPreviewCreateSupplierOrder',
408 'required' => ['socid'],
409 'object' => 'CommandeFournisseur',
410 'thirdparty' => 'socid',
411 'lines' => 'lines',
412 'right' => ['fournisseur', 'commande', 'creer'],
413 'buy' => true,
414 'defaults' => ['date' => 'now']
415 ],
416 'params' => [
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."
419 ]
420 ],
421 'index' => [
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."]
424 ],
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),
427 'put' => [
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.',
430 'write' => [
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',
435 'update' => [
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"}.']
440 ],
441 'preview_labels' => ['ref_supplier' => 'RefSupplier', 'note_private' => 'NotePrivate', 'note_public' => 'NotePublic', 'delivery_date' => 'DeliveryDate', 'fk_project' => 'Project'],
442 'preview_dates' => ['delivery_date'],
443 // Named in the confirmation by ref and label, not by rowid.
444 'preview_objects' => ['fk_project' => 'Project'],
445 // Extra fields the order really has: a misspelt one is refused
446 // before the confirmation rather than silently ignored.
447 'extrafields' => 'commande_fournisseur',
448 'references' => ['fk_project' => ['projet', 'projet', '']]
449 ]
450 ]
451 ]
452 ];
453
454 $this->enrichments['supplier_proposals'] = [
455 'label' => 'supplier proposal (price request)',
456 'methods' => [
457 'post' => [
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.",
460 'write' => [
461 'preview' => 'AIPreviewCreateSupplierProposal',
462 'required' => ['socid'],
463 'object' => 'SupplierProposal',
464 'thirdparty' => 'socid',
465 'lines' => 'lines',
466 'right' => ['supplier_proposal', 'creer'],
467 'buy' => true,
468 'defaults' => ['date' => 'now']
469 ],
470 'params' => [
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."
473 ]
474 ],
475 'index' => [
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."]
478 ],
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)
481 ]
482 ];
483
484 $this->enrichments['invoices'] = [
485 'label' => 'customer invoices',
486 'methods' => [
487 'post' => [
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.",
490 'write' => [
491 // Hand-written: a preview cannot be derived from a method
492 // signature, and it is the sentence a human approves.
493 'preview' => 'AIPreviewCreateInvoice',
494 'required' => ['socid'],
495 'object' => 'Facture',
496 'thirdparty' => 'socid',
497 'lines' => 'lines',
498 // The REST method checks this itself, but declaring it
499 // here refuses the call before a confirmation is issued:
500 // no preview for a write the user could never perform.
501 'right' => ['facture', 'creer']
502 ],
503 'params' => [
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."
506 ]
507 ],
508 'index' => [
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).",
511 'params' => [
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."
517 ]
518 ],
519 'get' => [
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.",
521 'params' => [
522 'contact_list' => "0 = no contacts, 1 (default) = contact rowids, 2 = full contact records.",
523 'withLines' => "false to omit the lines."
524 ]
525 ],
526 'getByRef' => [
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."]
530 ],
531 'getPayments' => [
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."]
535 ],
536 'postLine' => $this->addLineMethod('customer invoice', 'api_invoices_get_by_ref', 'Facture', ['facture', 'creer'])
537 ]
538 ];
539
540 // Sale orders
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.";
542
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).";
550
551 $descriptionfetch = "Fetch one order with its lines (product, qty, unit price, discount, line totals), status and dates. Fetch is done from ID.";
552
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').";
554
555 $this->enrichments['orders'] = [
556 'label' => 'sale orders',
557 'methods' => [
558 'post' => [
559 'suffix' => 'create',
560 'description' => $descriptioncreate,
561 'write' => [
562 'preview' => 'AIPreviewCreateOrder',
563 'required' => ['socid'],
564 'object' => 'Commande',
565 'thirdparty' => 'socid',
566 'lines' => 'lines',
567 'right' => ['commande', 'creer'],
568 // Commande::create() refuses without one, and a draft
569 // created today is what the user means.
570 'defaults' => ['date' => 'now']
571 ],
572 'params' => [
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."
575 ]
576 ],
577 'index' => [
578 'default_properties' => 'id,ref,socid,date_commande,delivery_date,total_ht,total_ttc,status',
579 'description' => $descriptionlist,
580 'params' => [
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."
584 ]
585 ],
586 'get' => [
587 'description' => $descriptionfetch,
588 'params' => ['contact_list' => "0 = no need of contacts, 1 (default) = need contact rowids, 2 = need full contact records."]
589 ],
590 'getByRef' => [
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."]
594 ],
595 'postLine' => $this->addLineMethod('sale order', 'api_orders_get_by_ref', 'Commande', ['commande', 'creer'])
596 ]
597 ];
598
599 $this->enrichments['proposals'] = [
600 'label' => 'commercial proposals (quotes / devis)',
601 'methods' => [
602 'post' => [
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.",
605 'write' => [
606 'preview' => 'AIPreviewCreateProposal',
607 'required' => ['socid'],
608 'object' => 'Propal',
609 'thirdparty' => 'socid',
610 'lines' => 'lines',
611 'right' => ['propal', 'creer'],
612 'defaults' => ['date' => 'now']
613 ],
614 'params' => [
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."
617 ]
618 ],
619 'index' => [
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.",
622 'params' => [
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."
626 ]
627 ],
628 'get' => [
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."]
631 ],
632 'getByRef' => [
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."]
636 ],
637 'postLine' => $this->addLineMethod('commercial proposal', 'api_proposals_get_by_ref', 'Propal', ['propal', 'creer'])
638 ]
639 ];
640
641 $this->enrichments['tickets'] = [
642 'label' => 'support tickets',
643 'methods' => [
644 'post' => [
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).",
647 'write' => [
648 'preview' => 'AIPreviewCreateTicket',
649 'required' => ['subject', 'message'],
650 'object' => 'Ticket',
651 'thirdparty' => 'socid',
652 'right' => ['ticket', 'write'],
653 'args' => ['subject', 'message'],
654 // The ticket API validates 'socid' but the object persists
655 // 'fk_soc'; the status column reads 'status'.
656 'copy' => ['socid' => 'fk_soc'],
657 'rename' => ['fk_statut' => 'status'],
658 // Silent by default: the assistant must not turn a
659 // creation the human approved into an emailed
660 // notification nobody saw coming.
661 'defaults' => ['notify_tiers_at_create' => 0],
662 ],
663 'params' => [
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."
673 ]
674 ],
675 'postNewMessage' => [
676 'suffix' => 'reply',
677 'description' => "Post a message on an existing support ticket, given by its rowid or its ref. The user confirms before anything is written.",
678 'write' => [
679 'preview' => 'AIPreviewReplyTicket',
680 'required' => ['message'],
681 'object' => 'Ticket',
682 'label' => 'ticket',
683 'right' => ['ticket', 'write'],
684 'args' => ['track_id', 'message'],
685 // The ticket by rowid or ref; its tracking id is filled in here,
686 // so the model never has to read or repeat that credential.
687 'target' => 'id',
688 'lookup' => 'ref',
689 'target_or' => 'track_id',
690 'track_from_target' => true,
691 ],
692 'params' => [
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."
697 ]
698 ],
699 'put' => [
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.",
702 'write' => [
703 'preview' => 'AIPreviewUpdateTicket',
704 'required' => ['id'],
705 'object' => 'Ticket',
706 'label' => 'ticket',
707 'right' => ['ticket', 'write'],
708 'args' => ['id'],
709 'target' => 'id',
710 'lookup' => 'ref',
711 // Closing and assigning go through their own tools, which run
712 // what the card runs (closing date, triggers, notifications).
713 'refuse_values' => [
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'],
717 ],
718 // Same name mismatch as the create: the API validates
719 // 'socid' while Ticket::update persists 'fk_soc', and
720 // the status column reads 'status' (fk_statut is a
721 // read-only backward-compatible alias).
722 'copy' => ['socid' => 'fk_soc'],
723 'rename' => ['fk_statut' => 'status'],
724 ],
725 'params' => [
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."
734 ]
735 ],
736 'postContact' => [
737 'suffix' => 'add_contact',
738 'description' => "Link a contact to a support ticket. The user confirms before anything is written.",
739 'write' => [
740 'preview' => 'AIPreviewAddTicketContact',
741 'required' => ['id', 'contactid', 'type'],
742 'object' => 'Ticket',
743 'label' => 'ticket',
744 'right' => ['ticket', 'write'],
745 'args' => ['contactid', 'id'],
746 'target' => 'id',
747 'lookup' => 'ref',
748 'contact' => 'ticket',
749 ],
750 'params' => [
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."
755 ]
756 ],
757 'deleteContact' => [
758 'suffix' => 'remove_contact',
759 'description' => "Unlink a contact from a support ticket. The user confirms before anything is written.",
760 'write' => [
761 'preview' => 'AIPreviewRemoveTicketContact',
762 'required' => ['id', 'contactid', 'type'],
763 'object' => 'Ticket',
764 'label' => 'ticket',
765 'right' => ['ticket', 'write'],
766 'args' => ['contactid', 'id'],
767 'target' => 'id',
768 'lookup' => 'ref',
769 'contact' => 'ticket',
770 ],
771 'params' => [
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'."
776 ]
777 ],
778 'close' => [
779 'suffix' => 'close',
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.",
781 'write' => [
782 'kind' => 'action',
783 'preview' => 'AIPreviewCloseTicket',
784 'preview_cancel' => 'AIPreviewCancelTicket',
785 'object' => 'Ticket',
786 'label' => 'ticket',
787 'target' => 'id',
788 'lookup' => 'ref',
789 // Every status but closed (8) and canceled (9).
790 'states' => [0, 1, 2, 3, 5, 6, 7],
791 'state_error' => 'AIWriteTicketClosed',
792 'pass' => ['cancel'],
793 'right' => ['ticket', 'write'],
794 ],
795 'params' => [
796 'id' => "The ticket: rowid, or its ref.",
797 'cancel' => "1 to cancel (abandon) the ticket instead of closing it."
798 ]
799 ],
800 'assign' => [
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.",
803 'write' => [
804 'kind' => 'action',
805 'preview' => 'AIPreviewAssignTicket',
806 'preview_unassign' => 'AIPreviewUnassignTicket',
807 'object' => 'Ticket',
808 'label' => 'ticket',
809 'target' => 'id',
810 'lookup' => 'ref',
811 'states' => [0, 1, 2, 3, 5, 6, 7],
812 'state_error' => 'AIWriteTicketClosed',
813 'pass' => ['fk_user_assign'],
814 'right' => ['ticket', 'write'],
815 ],
816 'params' => [
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."
819 ]
820 ],
821 'index' => [
822 // track_id stays out of list results on purpose: it is the
823 // bearer credential of the public ticket interface, and api_tickets_get
824 // still returns it when the reply flow needs it.
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).",
827 'params' => [
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}}."
831 ]
832 ],
833 'get' => [
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."
835 ],
836 'getByTrackId' => [
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."]
840 ],
841 'getByRef' => [
842 'suffix' => 'get_by_ref',
843 'description' => "One ticket by its exact internal reference (e.g. 'TS2401-0001').",
844 'params' => ['ref' => "Exact ticket reference."]
845 ]
846 ]
847 ];
848
849 $this->enrichments['projects'] = [
850 'label' => 'projects (including opportunities/leads)',
851 'methods' => [
852 'index' => [
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')\".",
855 'params' => [
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}}."
859 ]
860 ],
861 'get' => [
862 'description' => "One project with its dates, status, budget, opportunity data and linked third party."
863 ],
864 'put' => $this->projectUpdateMethod(),
865 'getByRef' => [
866 'suffix' => 'get_by_ref',
867 'description' => "One project by its exact reference (e.g. 'PJ2401-0001').",
868 'params' => ['ref' => "Exact project reference."]
869 ]
870 ]
871 ];
872
873 $this->enrichments['tasks'] = [
874 'label' => 'project tasks',
875 'methods' => [
876 'index' => [
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).",
879 'params' => [
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}}."
882 ]
883 ],
884 'get' => [
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."]
887 ],
888 'getTimespent' => [
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."]
892 ],
893 'put' => [
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.",
896 'write' => [
897 'preview' => 'AIPreviewChangeTask',
898 'required' => ['id'],
899 'object' => 'Task',
900 'label' => 'task',
901 'right' => ['projet', 'creer'],
902 'args' => ['id'],
903 'target' => 'id',
904 'lookup' => 'ref',
905 'dates' => ['date_start', 'date_end'],
906 'hours' => ['planned_workload'],
907 'trim_fields' => ['label', 'description'],
908 ],
909 'params' => [
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."
917 ]
918 ],
919 'addTimeSpent' => [
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.",
922 'write' => [
923 'preview' => 'AIPreviewAddTimespent',
924 'required' => ['id', 'date', 'duration'],
925 'object' => 'Task',
926 'label' => 'task',
927 'right' => ['projet', 'creer'],
928 'target' => 'id',
929 'lookup' => 'ref',
930 'args' => ['duration', 'date', 'id'],
931 // No 'dates' entry: the REST method parses the text
932 // itself — a timestamp would be re-parsed into garbage.
933 // It is checked as text instead.
934 'text_dates' => ['date'],
935 'hours' => ['duration'],
936 ],
937 'params' => [
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)."
944 ]
945 ]
946 ]
947 ];
948
949 $this->enrichments['agendaevents'] = [
950 'label' => 'agenda / calendar events (meetings, calls)',
951 'methods' => [
952 'index' => [
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).",
955 'params' => [
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}}."
958 ]
959 ],
960 'get' => [
961 'description' => "One event with its type, start/end dates, owner, linked third party/contact and note."
962 ]
963 ]
964 ];
965
966 $this->enrichments['interventions'] = [
967 'label' => 'field service interventions',
968 'methods' => [
969 'index' => [
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.",
972 'params' => [
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}}."
975 ]
976 ],
977 'get' => [
978 'description' => "One intervention with its lines (each line = one on-site work entry with date, duration in seconds and description)."
979 ]
980 ]
981 ];
982
983 $this->enrichments['contracts'] = [
984 'label' => 'contracts (recurring services)',
985 'methods' => [
986 'index' => [
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.",
989 'params' => [
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}}."
993 ]
994 ],
995 'get' => [
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."]
998 ],
999 'getLines' => [
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."]
1003 ]
1004 ]
1005 ];
1006
1007 $this->enrichments['members'] = [
1008 'label' => 'foundation/association members',
1009 'methods' => [
1010 'index' => [
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.",
1013 'params' => [
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}}."
1017 ]
1018 ],
1019 'get' => [
1020 'description' => "One member with identity, member type, status, linked third party and paid-up end date (datefin)."
1021 ],
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."]
1026 ]
1027 ]
1028 ];
1029
1030 $this->enrichments['subscriptions'] = [
1031 'label' => 'subscriptions',
1032 'methods' => [
1033 'index' => [
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.",
1035 'params' => [
1036 'pagination_data' => "Set to true to get {data, pagination:{total,page,page_count,limit}}."
1037 ]
1038 ],
1039 'get' => [
1040 'description' => "One subscription payment with its member, period and amount."
1041 ]
1042 ]
1043 ];
1044
1045 $this->enrichments['stockmovements'] = [
1046 'label' => 'stock movements (in/out/transfer history)',
1047 'methods' => [
1048 'index' => [
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.",
1051 'params' => [
1052 'pagination_data' => "Set to true to get {data, pagination:{total,page,page_count,limit}}."
1053 ]
1054 ],
1055 'get' => []
1056 ]
1057 ];
1058
1059 $this->enrichments['warehouses'] = [
1060 'label' => 'warehouses',
1061 'methods' => [
1062 'index' => [
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.",
1064 'params' => [
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}}."
1067 ]
1068 ],
1069 'get' => [
1070 'description' => "One warehouse with its address, status and description."
1071 ]
1072 ]
1073 ];
1074
1075 $this->enrichments['shipments'] = [
1076 'label' => 'customer shipments (expéditions, goods sent)',
1077 'methods' => [
1078 'post' => [
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.",
1081 'write' => [
1082 'preview' => 'AIPreviewCreateShipment',
1083 'required' => ['socid'],
1084 'object' => 'Expedition',
1085 'thirdparty' => 'socid',
1086 'lines' => 'lines',
1087 'right' => ['expedition', 'creer'],
1088 'kind' => 'shipment',
1089 'line_fields' => [
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.']
1094 ]
1095 ],
1096 'params' => [
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)."
1101 ]
1102 ],
1103 'index' => [
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.",
1106 'params' => [
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."
1109 ]
1110 ],
1111 'get' => [
1112 'description' => "One shipment: customer, source order, dates, status, tracking number; the lines are in api_shipments_get_lines."
1113 ],
1114 'getLines' => [
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."]
1118 ]
1119 ]
1120 ];
1121
1122 $this->enrichments['receptions'] = [
1123 'label' => 'supplier receptions (réceptions, goods received)',
1124 'methods' => [
1125 'post' => [
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.",
1128 'write' => [
1129 'preview' => 'AIPreviewCreateReception',
1130 'required' => ['socid'],
1131 'object' => 'Reception',
1132 'thirdparty' => 'socid',
1133 'lines' => 'lines',
1134 'right' => ['reception', 'creer'],
1135 'buy' => true,
1136 'kind' => 'reception',
1137 'line_fields' => [
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).']
1145 ]
1146 ],
1147 'params' => [
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)."
1152 ]
1153 ],
1154 'index' => [
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.",
1157 'params' => [
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."
1160 ]
1161 ],
1162 'get' => [
1163 'description' => "One reception: supplier, supplier reference, dates, status; the lines are in api_receptions_get_lines."
1164 ],
1165 'getLines' => [
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."]
1169 ]
1170 ]
1171 ];
1172
1173 $this->enrichments['expensereports'] = [
1174 'label' => 'employee expense reports (notes de frais)',
1175 'methods' => [
1176 'index' => [
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.",
1179 'params' => [
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}}."
1182 ]
1183 ],
1184 'get' => [
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."
1186 ]
1187 ]
1188 ];
1189
1190 // Sale orders
1191 $descriptioncreate = "Create a product or service in the catalog. The user must confirm before anything is written.";
1192
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";
1195
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";
1205
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.";
1207
1208 $this->enrichments['products'] = [
1209 'label' => 'products and services catalog',
1210 'methods' => [
1211 'post' => [
1212 'suffix' => 'create',
1213 'description' => $descriptioncreate,
1214 'write' => [
1215 'preview' => 'AIPreviewCreateProduct',
1216 'required' => ['ref', 'label'],
1217 'object' => 'Product',
1218 'args' => ['label'],
1219 'right' => ['produit', 'creer']
1220 ],
1221 'params' => [
1222 "ref" => "Internal reference.", "label" => "Product label.", "price" => "Selling price excl. tax.", "type" => "0 product, 1 service."
1223 ]
1224 ],
1225 'index' => [
1226 'default_properties' => 'id,ref,label,type,price,price_ttc,tva_tx,status,status_buy',
1227 'description' => $descriptionlist,
1228 'params' => [
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}}."
1235 ]
1236 ],
1237 'get' => [
1238 'description' => $descriptionfetch,
1239 'params' => [
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."
1244 ]
1245 ],
1246 'getByRef' => [
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."]
1250 ],
1251 'getByBarcode' => [
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."]
1255 ],
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."]
1260 ],
1261 'getAttributes' => [
1262 'suffix' => 'attributes_list',
1263 'module' => 'variants',
1264 'description' => "Variant attributes (e.g. Size, Color) defined in the catalog."
1265 ],
1266 'getVariants' => [
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."]
1271 ],
1272 'getStock' => [
1273 'suffix' => 'stock',
1274 // Needs the Stock module on top of Products: when it is off
1275 // the tool does not exist, instead of the bare 403 the API
1276 // method throws.
1277 'module' => 'stock',
1278 // Declared so a caller without stock/lire neither sees the
1279 // tool in tools/list nor hits the API's bare 403; the
1280 // endpoint's own produit/lire check stays downstream.
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.",
1283 'params' => [
1284 'id' => "Rowid of the product.",
1285 'selected_warehouse_id' => "Rowid of a warehouse to return its stock only; omitted for every warehouse."
1286 ]
1287 ]
1288 ]
1289 ];
1290
1291 // NB: stock inventories have no REST API class in core yet (no api_inventories) —
1292 // they cannot be bridged until one exists.
1293 // The REST class documents serves three different file areas, each one
1294 // exposed as its own group of tools so the model never mixes them: the
1295 // files of business objects, the free tree of the ECM module, and the
1296 // public medias of the website module. 'endpoint' names the REST class
1297 // they all call, 'fixed_params' the arguments forced on the call.
1298 $uploadParams = [
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."
1304 ];
1305 $this->enrichments['documents_objects'] = [
1306 'endpoint' => 'documents',
1307 'label' => 'documents attached to business objects',
1308 'methods' => [
1309 'getDocumentsListByElement' => [
1310 'suffix' => 'list',
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).",
1312 'params' => [
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."
1316 ]
1317 ],
1318 // GET /documents/download of the same REST class: the answer carries
1319 // the file content base64-encoded, so keep it for small files only.
1320 'index' => [
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.",
1323 'params' => [
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')."
1326 ]
1327 ],
1328 // POST /documents/upload of the same REST class. No 'right' is
1329 // declared: the API checks the access per modulepart, and no single
1330 // Dolibarr right covers every area (an invoice needs facture/...).
1331 'post' => [
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.",
1334 'write' => [
1335 'preview' => 'AIPreviewUploadDocument',
1336 'required' => ['filename', 'modulepart', 'ref'],
1337 'args' => ['filename', 'modulepart']
1338 ],
1339 'params' => [
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']
1346 ]
1347 ]
1348 ]
1349 ];
1350 $this->enrichments['documents_manual'] = [
1351 'endpoint' => 'documents',
1352 'label' => 'documents of the DMS free directory tree',
1353 'methods' => [
1354 'getDocumentsListByDirectory' => [
1355 'suffix' => 'list',
1356 'module' => 'ecm',
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.",
1359 'params' => [
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'."
1365 ]
1366 ],
1367 'index' => [
1368 'suffix' => 'download',
1369 'module' => 'ecm',
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.",
1372 'params' => [
1373 'original_file' => "Relative path with filename, relative to the root of the DMS manual tree (e.g. 'Contracts/2024/agreement.pdf')."
1374 ]
1375 ],
1376 'post' => [
1377 'suffix' => 'upload',
1378 'module' => 'ecm',
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.",
1381 'write' => [
1382 'preview' => 'AIPreviewUploadDocument',
1383 'required' => ['filename'],
1384 'args' => ['filename', 'modulepart']
1385 ],
1386 'params' => [
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']
1393 ]
1394 ]
1395 ]
1396 ];
1397 // No 'right' declared on medias: the API checks it (website/write to upload).
1398 $this->enrichments['documents_medias'] = [
1399 'endpoint' => 'documents',
1400 'label' => 'public medias of the website module',
1401 'methods' => [
1402 'getDocumentsListByDirectory' => [
1403 'suffix' => 'list',
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>'.",
1406 'params' => [
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'."
1412 ]
1413 ],
1414 'index' => [
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.",
1418 'params' => [
1419 'original_file' => "Relative path with filename inside the medias directory (e.g. 'image/mywebsite/picture.png')."
1420 ]
1421 ],
1422 'post' => [
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.",
1426 'write' => [
1427 'preview' => 'AIPreviewUploadDocument',
1428 'required' => ['filename', 'subdir'],
1429 'args' => ['filename', 'modulepart']
1430 ],
1431 'params' => [
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']
1438 ]
1439 ]
1440 ]
1441 ];
1442
1443 $this->addReadEndpoints();
1445 // Modules answer last so their enrichment keys can never shadow a core one.
1446 $this->loadExternalEnrichments();
1447 }
1448
1472 private function loadExternalEnrichments()
1473 {
1474 global $hookmanager;
1475 if (!is_object($hookmanager)) {
1476 if (!defined('DOL_DOCUMENT_ROOT')) {
1477 return; // No Dolibarr bootstrap (unit tests): no module can answer anyway
1478 }
1479 require_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
1480 $hookmanager = new HookManager($this->db);
1481 }
1482
1483 $hookmanager->initHooks(array('aimcp'));
1484
1485 try {
1486 $action = '';
1487 $hookmanager->executeHooks('addMcpApiBridgeEnrichments', array('db' => $this->db, 'user' => $this->user, 'conf' => isset($this->conf) ? $this->conf : null), $this, $action);
1488
1489 if (!is_array($hookmanager->resArray)) {
1490 return;
1491 }
1492
1493 foreach ($hookmanager->resArray as $moduleEnrichments) {
1494 if (!is_array($moduleEnrichments)) {
1495 continue;
1496 }
1497 foreach ($moduleEnrichments as $key => $entry) {
1498 $key = strtolower((string) $key);
1499 if (isset($this->enrichments[$key]) || !is_array($entry)) {
1500 continue; // core entries win; non-array garbage ignored
1501 }
1502 if (empty($entry['methods']) || !is_array($entry['methods'])) {
1503 $entry['methods'] = $this->defaultMethods();
1504 }
1505 $this->enrichments[$key] = $entry;
1506 }
1507 }
1508 } catch (\Throwable $e) {
1509 dol_syslog("[ToolApiBridge] Error during 'addMcpApiBridgeEnrichments' hook execution: ".$e->getMessage(), LOG_ERR);
1510 }
1511 }
1512
1524 private function addReadEndpoints()
1525 {
1526 $pagination = "Set to true to get {data, pagination:{total,page,page_count,limit}}; use it to know how many records match.";
1527
1528 $this->enrichments['bankaccounts'] = array(
1529 'label' => 'bank and cash accounts',
1530 'methods' => array(
1531 'index' => array(
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."
1534 ),
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."),
1540 // The REST method has no limit: a real account would send its whole history.
1541 // Oldest first there, so the end is the most recent.
1542 'max_items' => 50,
1543 'keep' => 'last'
1544 ),
1545 'getBalance' => array(
1546 'suffix' => 'balance',
1547 'description' => "Current balance of one bank account.",
1548 'params' => array('id' => "Rowid of the bank account.")
1549 )
1550 )
1551 );
1552
1553 $this->enrichments['variouspayments'] = array(
1554 'label' => 'miscellaneous bank payments',
1555 'methods' => array(
1556 'index' => array(
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)
1559 ),
1560 'get' => array('description' => "One miscellaneous payment.")
1561 )
1562 );
1563
1564 $this->enrichments['socialcontributions'] = array(
1565 'label' => 'social and fiscal contributions (taxes, charges)',
1566 'methods' => array(
1567 'index' => array(
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)
1570 ),
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.")
1576 )
1577 )
1578 );
1579
1580 $this->enrichments['vatpayments'] = array(
1581 'label' => 'VAT declarations and payments',
1582 'methods' => array(
1583 'index' => array(
1584 'description' => "VAT to pay or refund per period: label, period end (datev), amount, paye (1 paid).",
1585 'params' => array('pagination_data' => $pagination)
1586 ),
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.")
1592 )
1593 )
1594 );
1595
1596 $this->enrichments['donations'] = array(
1597 'label' => 'donations',
1598 'methods' => array(
1599 'index' => array(
1600 'description' => "Donations received: donor, amount, date, project. Statuses (t.fk_statut): 0 draft, 1 validated (promised), 2 paid, -1 canceled.",
1601 'params' => array(
1602 'thirdparty_ids' => "Comma-separated third-party rowids to restrict to (e.g. '1,5').",
1603 'pagination_data' => $pagination
1604 )
1605 ),
1606 'get' => array('description' => "One donation with its donor, amount and status.")
1607 )
1608 );
1609
1610 $this->enrichments['holidays'] = array(
1611 'label' => 'leave requests (holidays, days off)',
1612 'methods' => array(
1613 'index' => array(
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')\".",
1615 'params' => array(
1616 'user_ids' => "Comma-separated user rowids to restrict to the requests of these employees.",
1617 'pagination_data' => $pagination
1618 ),
1619 // The reason of a leave is free text, sometimes medical: it stays here.
1620 'drop_fields' => array('description', 'note_private', 'note_public')
1621 ),
1622 'get' => array(
1623 'description' => "One leave request with its employee, dates, type and status.",
1624 'drop_fields' => array('description', 'note_private', 'note_public')
1625 )
1626 )
1627 );
1628
1629 $this->enrichments['boms'] = array(
1630 'label' => 'bills of materials (BOM)',
1631 'methods' => array(
1632 'index' => array(
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."
1634 ),
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.")
1640 )
1641 )
1642 );
1643
1644 $this->enrichments['mos'] = array(
1645 'label' => 'manufacturing orders (MO)',
1646 'methods' => array(
1647 'index' => array(
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."
1649 ),
1650 'get' => array('description' => "One manufacturing order with what it consumes and produces.")
1651 )
1652 );
1653
1654 $this->enrichments['productlots'] = array(
1655 'label' => 'product lots and serial numbers',
1656 'methods' => array(
1657 'index' => array(
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)
1660 ),
1661 'get' => array('description' => "One lot or serial number with its dates.")
1662 )
1663 );
1664
1665 $this->enrichments['workstations'] = array(
1666 'label' => 'workstations (manufacturing)',
1667 'methods' => array(
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.")
1674 )
1675 )
1676 );
1677
1678 $this->enrichments['knowledgemanagement'] = array(
1679 'label' => 'knowledge base articles',
1680 'methods' => array(
1681 'index' => array(
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%')\".",
1683 'params' => array(
1684 'category' => "Rowid of a knowledge category to restrict the list to.",
1685 'pagination_data' => $pagination
1686 )
1687 ),
1688 'get' => array('description' => "One knowledge base article with its question and answer.")
1689 )
1690 );
1691
1692 $this->enrichments['memberstypes'] = array(
1693 'label' => 'member types',
1694 'methods' => array(
1695 'index' => array('description' => "Types of members: label, whether a subscription is due, its amount and duration."),
1696 'get' => array('description' => "One member type.")
1697 )
1698 );
1699
1700 $this->enrichments['partnerships'] = array(
1701 'label' => 'partnerships',
1702 'methods' => array(
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.")
1705 )
1706 );
1707
1708 $this->enrichments['multicurrencies'] = array(
1709 'label' => 'currencies and exchange rates',
1710 'methods' => array(
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.")
1717 ),
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."),
1722 'max_items' => 30,
1723 'keep' => 'first'
1724 )
1725 )
1726 );
1727
1728 // Websites of the website module, with their pages and blog posts. The page content is
1729 // left out of the lists (it can be large): read one page with api_websites_page_get.
1730 $this->enrichments['websites'] = array(
1731 'label' => 'websites (website module)',
1732 'methods' => array(
1733 'index' => array(
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'
1736 ),
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.")
1742 ),
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.")
1748 ),
1749 'getPage' => array(
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.")
1753 ),
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.",
1757 'write' => array(
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')
1764 ),
1765 'params' => array(
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."
1776 )
1777 )
1778 )
1779 );
1780
1781 // Contacts (people of third parties), read side.
1782 $this->enrichments['contacts'] = array(
1783 'label' => 'contacts (people of third parties)',
1784 'methods' => array(
1785 'index' => array(
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.",
1788 'params' => array(
1789 'thirdparty_ids' => "Comma-separated third-party rowids to restrict to (e.g. '1,5').",
1790 'pagination_data' => $pagination
1791 )
1792 ),
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."),
1798 // The REST method returns an empty contact when several share the address.
1799 'needs_id' => "No single contact has this email (none, or several): search with api_contacts_list and sqlfilters on t.email."
1800 ),
1801 'getCategories' => array(
1802 'suffix' => 'categories_list',
1803 'description' => "Tags (categories) of one contact.",
1804 'params' => array('id' => "Rowid of the contact.")
1805 )
1806 )
1807 );
1808
1809 // Object links (llx_element_element): which record is linked to which.
1810 // Rights are dynamic - the REST class checks lire/read on the module of
1811 // EACH side of the link - so everything is enforced downstream. The
1812 // write side (create/delete links) needs rights on both element types
1813 // too and is left for a follow-up.
1814 $this->enrichments['objectlinks'] = array(
1815 'label' => 'links between records',
1816 'methods' => array(
1817 'getById' => array(
1818 'suffix' => 'get',
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.")
1821 ),
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'.",
1825 'params' => array(
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."
1831 )
1832 )
1833 )
1834 );
1835
1836 // Users (staff accounts) and their groups, read side. Lookups by id,
1837 // login, email and self stay downstream-gated so a user may still read
1838 // his own record without the user/user/lire right. Write side (user
1839 // creation, password, group assignment) is left out on purpose.
1840 $this->enrichments['users'] = array(
1841 'label' => 'users (staff accounts) and user groups',
1842 'methods' => array(
1843 'index' => array(
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).",
1846 'params' => array(
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."
1849 ),
1850 'right' => array('user', 'user', 'lire')
1851 ),
1852 'get' => array(
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).")
1855 ),
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).")
1860 ),
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).")
1865 ),
1866 'getInfo' => array(
1867 'suffix' => 'me',
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).")
1870 ),
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')
1876 ),
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.",
1880 'params' => array(
1881 'group_ids' => "Comma-separated group rowids to restrict to (e.g. '1,5')."
1882 )
1883 ),
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).")
1888 )
1889 )
1890 );
1891
1892 // Read methods of endpoints already exposed.
1893 $more = array(
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)
1899 )
1900 ),
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.")
1906 ),
1907 'getCustomerPricesPerSegment' => array(
1908 'suffix' => 'prices_per_segment',
1909 // Only in that price mode: elsewhere the REST method refuses.
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.")
1913 ),
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.")
1919 ),
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.")
1925 ),
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.")
1930 ),
1931 'getCategories' => array(
1932 'suffix' => 'categories_list',
1933 'description' => "Tags (categories) of one product.",
1934 'params' => array('id' => "Rowid of the product.")
1935 )
1936 ),
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.")
1942 ),
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."),
1947 'max_items' => 100,
1948 'keep' => 'first'
1949 ),
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)
1954 )
1955 ),
1956 'orders' => array(
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.")
1961 ),
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.")
1966 )
1967 ),
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.")
1973 )
1974 ),
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.")
1980 ),
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)
1985 ),
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.")
1990 )
1991 ),
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.")
1997 )
1998 ),
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.")
2004 ),
2005 'getAllPayments' => array(
2006 'suffix' => 'payments_list',
2007 'description' => "Payments of expense reports: amount, date, payment mode."
2008 )
2009 ),
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.")
2015 )
2016 ),
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.")
2022 ),
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'.")
2027 ),
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.")
2032 ),
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.")
2037 ),
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.")
2042 )
2043 ),
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'.")
2049 )
2050 ),
2051 'members' => array(
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.")
2056 ),
2057 'getNbByYear' => array(
2058 'suffix' => 'count_by_year',
2059 'description' => "Number of new members per year."
2060 ),
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.")
2065 ),
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.")
2070 )
2071 )
2072 );
2073 foreach ($more as $key => $methods) {
2074 if (!isset($this->enrichments[$key])) {
2075 continue;
2076 }
2077 foreach ($methods as $method => $meta) {
2078 $this->enrichments[$key]['methods'][$method] = $meta;
2079 }
2080 }
2081 }
2082
2096 private function addLineMethod($label, $lookupTool, $class, array $right, $buy = false, array $rename = array(), array $defaults = array())
2097 {
2098 $lookup = (substr($lookupTool, -7) === '_by_ref') ? $lookupTool : $lookupTool." with sqlfilters (t.ref:=:'THEREF')";
2099
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.";
2104
2105 $write = array(
2106 // One sentence for every document: the ref names it.
2107 'preview' => 'AIPreviewAddDocumentLine',
2108 'object' => $class,
2109 // The line is written into an existing record, named by this
2110 // argument, instead of creating a new one.
2111 'parent' => 'id',
2112 'right' => $right
2113 );
2114 if ($buy) {
2115 $write['buy'] = true;
2116 }
2117 if ($rename) {
2118 $write['rename'] = $rename;
2119 }
2120 if ($defaults) {
2121 $write['defaults'] = $defaults;
2122 }
2123
2124 return array(
2125 'suffix' => 'add_line',
2126 'description' => $description,
2127 'write' => $write,
2128 'params' => array(
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'."
2131 )
2132 );
2133 }
2134
2145 {
2146 $advanced = $this->setupValue('MAIN_USE_ADVANCED_PERMS');
2147
2148 // Edits: only the listed fields, so a model cannot change a status, an
2149 // entity or an amount behind a sentence about a phone number.
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.",
2155 'town' => "Town.",
2156 'phone' => "Phone.",
2157 'phone_mobile' => "Mobile phone.",
2158 'fax' => "Fax.",
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."
2167 ), 'thirdparty');
2168
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."
2177 );
2178 // The REST update writes a price only in these price modes: elsewhere the
2179 // change would be silently ignored, so it is not offered.
2180 if ($this->setupValue('PRODUCT_PRICE_UNIQ') || $this->setupValue('PRODUIT_CUSTOMER_PRICES')) {
2181 $productfields['price'] = "Selling price excl. tax.";
2182 }
2183 $this->enrichments['products']['methods']['put'] = $this->updateMethod('product', 'Product', array('produit', 'creer'), $productfields, 'ref');
2184
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.",
2188 'write' => array(
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')
2196 ),
2197 'params' => array(
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."
2205 )
2206 );
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.",
2217 'town' => "Town.",
2218 'note_public' => "Public note.",
2219 'note_private' => "Private note.",
2220 'statut' => "1 active, 0 inactive."
2221 ), '');
2222
2223 // Validation. The trigger and the numbering stay core's: a model can
2224 // never skip the triggers or force a number.
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), '');
2228 // Logistic documents. Each line carries its own warehouse, so none is asked
2229 // here; whether validating moves the stock is a setup choice of the instance
2230 // (STOCK_CALCULATE_ON_RECEPTION / _SHIPMENT), and the confirmation says so.
2231 $receptionMovesStock = isModEnabled('stock') && getDolGlobalInt('STOCK_CALCULATE_ON_RECEPTION');
2232 $shipmentMovesStock = isModEnabled('stock') && getDolGlobalInt('STOCK_CALCULATE_ON_SHIPMENT');
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.";
2237 }
2238 if ($shipmentMovesStock) {
2239 $this->enrichments['shipments']['methods']['validate']['description'] .= " On this Dolibarr, validating a shipment takes the shipped goods out of stock.";
2240 }
2241
2242 // A payment: the distributed method, the only one that takes an amount.
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.",
2246 'write' => array(
2247 'kind' => 'payment',
2248 'preview' => 'AIPreviewPayInvoice',
2249 'object' => 'Facture',
2250 'label' => 'customer invoice',
2251 'target' => 'id',
2252 'lookup' => 'ref',
2253 'fixed' => array('closepaidinvoices' => 'yes', 'accepthigherpayment' => false, 'ref_ext' => ''),
2254 'right' => array('facture', 'paiement')
2255 ),
2256 'params' => array(
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."
2265 )
2266 );
2267
2268 // Deletion, of drafts only: a validated document has a number and an
2269 // accounting life, it is cancelled in Dolibarr, never deleted from a chat.
2270 $deletes = array(
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'))
2278 );
2279 foreach ($deletes as $key => $d) {
2280 $this->enrichments[$key]['methods']['delete'] = $this->deleteMethod($d[0], $d[1], $d[2]);
2281 }
2282
2283 // Lines of a draft: changed or removed, never on a validated document.
2284 $lines = array(
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')
2291 );
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]);
2295 }
2296 // The REST postLine() of a contract reads every field: none is left unset.
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');
2299
2300 // Header of a draft: the fields a user corrects, by their old and new value.
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')
2307 ));
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')
2311 ));
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')
2315 ));
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')
2319 ));
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')
2323 ));
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')
2327 ));
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')
2331 ));
2332
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.",
2336 'write' => array(
2337 'preview' => 'AIPreviewCreateIntervention',
2338 'required' => array('socid', 'description'),
2339 'object' => 'Fichinter',
2340 'thirdparty' => 'socid',
2341 'project' => 'fk_project',
2342 'args' => array('_who', 'description'),
2343 // Mandatory for the REST endpoint, even without a project.
2344 'defaults' => array('fk_project' => 0),
2345 'right' => array('ficheinter', 'creer')
2346 ),
2347 'params' => array(
2348 'socid' => "Third party: rowid, or its name.",
2349 'description' => "What the intervention is about.",
2350 'fk_project' => "Project: rowid or ref. Optional."
2351 )
2352 );
2353
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.",
2357 'write' => array(
2358 'preview' => 'AIPreviewCreateContract',
2359 'required' => array('socid'),
2360 'object' => 'Contrat',
2361 'thirdparty' => 'socid',
2362 'args' => array('_who'),
2363 'dates' => array('date_contrat'),
2364 // Contrat::create() refuses without them; the card proposes the user.
2365 'defaults' => array('date_contrat' => 'now', 'commercial_signature_id' => 'me', 'commercial_suivi_id' => 'me'),
2366 'right' => array('contrat', 'creer')
2367 ),
2368 'params' => array(
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."
2373 )
2374 );
2375
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.",
2379 'write' => array(
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'),
2388 // The card makes its creator the project leader; without it a user
2389 // who cannot see every project could not see the one just made.
2390 'creator_contact' => 'PROJECTLEADER',
2391 'right' => array('projet', 'creer')
2392 ),
2393 'params' => array(
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."
2400 )
2401 );
2402
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.",
2406 'write' => array(
2407 'preview' => 'AIPreviewCreateTask',
2408 'required' => array('label', 'fk_project'),
2409 'object' => 'Task',
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')
2416 ),
2417 'params' => array(
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."
2424 )
2425 );
2426 }
2427
2436 private function setupValue($name)
2437 {
2438 return function_exists('getDolGlobalString') ? getDolGlobalString($name) : '';
2439 }
2440
2447 private function resetWriteState()
2448 {
2449 $this->writeProblems = array();
2450 $this->writeRefusedFields = array();
2451 $this->writeTarget = null;
2452 $this->writeLine = array('line' => null, 'position' => 0, 'changes' => array());
2453 }
2454
2465 private function updateMethod($label, $class, array $right, array $fields, $lookup)
2466 {
2467 $how = array('thirdparty' => "rowid, or its name", 'ref' => "rowid, or its exact ref", '' => "rowid");
2468
2469 return array(
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.",
2472 'write' => array(
2473 'kind' => 'update',
2474 'preview' => 'AIPreviewChangeRecord',
2475 'object' => $class,
2476 'label' => $label,
2477 'target' => 'id',
2478 'lookup' => $lookup,
2479 'fields' => array_keys($fields),
2480 'right' => $right
2481 ),
2482 'params' => array_merge(array('id' => "The ".$label." to change: ".$how[$lookup]."."), $fields)
2483 );
2484 }
2485
2497 private function validateMethod($label, $class, $preview, array $right, array $fixed, $stockconst)
2498 {
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.";
2504 }
2505 $description .= " The user confirms before anything is written.";
2506
2507 return array(
2508 'suffix' => 'validate',
2509 'description' => $description,
2510 'write' => array(
2511 'kind' => 'action',
2512 'preview' => $preview,
2513 'object' => $class,
2514 'label' => $label,
2515 'target' => 'id',
2516 'lookup' => 'ref',
2517 'fixed' => $fixed,
2518 'stock' => $stockconst,
2519 'right' => $right
2520 ) + (count($right) === 3 ? array('read_right' => array($right[0], 'creer')) : array()),
2521 'params' => $params
2522 );
2523 }
2524
2533 private function deleteMethod($label, $class, array $right)
2534 {
2535 return 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.",
2538 'write' => array(
2539 'kind' => 'delete',
2540 'preview' => 'AIPreviewDeleteDraft',
2541 'object' => $class,
2542 'label' => $label,
2543 'target' => 'id',
2544 'lookup' => 'ref',
2545 'right' => $right
2546 ),
2547 'params' => array('id' => "The draft ".$label.": rowid, or its ref.")
2548 );
2549 }
2550
2562 private function lineMethod($action, $label, $class, array $right, $profile)
2563 {
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)."
2568 ) : array(
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...)."
2575 );
2576 if ($profile === 'supplier') {
2577 unset($fields['desc']); // FactureFournisseur::updateline() keeps the old text
2578 }
2579 $which = array(
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."
2582 );
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.";
2586 $params += $fields;
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;
2590 } else {
2591 $description = "Delete ONE line of a DRAFT ".$label.". Give 'id' and the line ('line' or 'lineid'). The user confirms before anything is written.";
2592 $params += $which;
2593 }
2594
2595 return array(
2596 'suffix' => $action.'_line',
2597 'description' => $description,
2598 'write' => array(
2599 'kind' => 'line',
2600 'line_action' => $action,
2601 'line_profile' => $profile,
2602 'preview' => ($action === 'add') ? 'AIPreviewAddInterventionLine' : ($action === 'update' ? 'AIPreviewChangeDocumentLine' : 'AIPreviewDeleteDocumentLine'),
2603 'object' => $class,
2604 'label' => $label,
2605 'target' => 'id',
2606 'lookup' => 'ref',
2607 'fields' => ($action === 'delete') ? array() : array_keys($fields),
2608 'right' => $right
2609 ),
2610 'params' => $params
2611 );
2612 }
2613
2627 private function headerUpdateMethod($label, $class, array $right, array $readright, array $access, $extrafields, array $fields)
2628 {
2629 $update = array();
2630 $labels = array();
2631 $dates = array();
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) {
2636 $dates[] = $name;
2637 }
2638 }
2639 $update['array_options'] = array('type' => 'object', 'description' => 'Extra fields by their options_ code, e.g. {"options_mycode": "value"}.');
2640
2641 return array(
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.",
2644 'write' => array(
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()
2655 )
2656 );
2657 }
2658
2664 private function projectUpdateMethod()
2665 {
2666 return [
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.',
2669 'write' => [
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,
2679 'update' => [
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.']
2684 ]
2685 ]
2686 ];
2687 }
2688
2697 private function loadApiRuntime()
2698 {
2699 require_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php'; // dolGetModulesDirs(), getModuleDirForApiClass() — main.inc.php loads this only conditionally; api/index.php requires it explicitly for the same reason
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';
2706 // Luracast\Restler\AutoLoader::instance() (called here and by api_access.class.php) unregisters all the other autoloaders
2707 // (the Composer one, the one of PHPUnit...). Put them back: outside of the Restler HTTP runtime, the rest of the code still
2708 // needs them to load the classes that are not loaded yet.
2709 foreach ($previousloaders as $previousloader) {
2710 spl_autoload_register($previousloader);
2711 }
2712 }
2713
2735 private function discoverEndpoints(): array
2736 {
2737 $endpoints = [];
2738
2739 foreach (dolGetModulesDirs() as $dir) {
2740 $handle = @opendir(dol_osencode($dir));
2741 if (!is_resource($handle)) {
2742 continue;
2743 }
2744
2745 while (($file = readdir($handle)) !== false) {
2746 $regmod = [];
2747 if (!is_readable($dir.$file) || !preg_match("/^mod(.*)\\.class\\.php$/i", $file, $regmod)) {
2748 continue;
2749 }
2750
2751 $module = strtolower($regmod[1]);
2752 $moduledirforclass = getModuleDirForApiClass($module);
2753
2754 // Same descriptor-name to module-name exceptions as api/index.php.
2755 $modulenameforenabled = $module;
2756 if ($module == 'propale') {
2757 $modulenameforenabled = 'propal';
2758 } elseif ($module == 'supplierproposal') {
2759 $modulenameforenabled = 'supplier_proposal';
2760 } elseif ($module == 'ficheinter') {
2761 $modulenameforenabled = 'intervention';
2762 } elseif ($module == 'product' && !isModEnabled('product') && isModEnabled('service')) {
2763 $modulenameforenabled = 'service';
2764 }
2765
2766 if (!isModEnabled($modulenameforenabled)) {
2767 continue; // A disabled module exposes no tools.
2768 }
2769
2770 $dir_part = dol_buildpath('/'.$moduledirforclass.'/class/');
2771 $handle_part = @opendir(dol_osencode($dir_part));
2772 if (!is_resource($handle_part)) {
2773 continue;
2774 }
2775
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)) {
2778 continue; // Framework plumbing, not business endpoints.
2779 }
2780 $regapi = [];
2781 if (!is_readable($dir_part.$file_searched) || !preg_match("/^api_(.*)\\.class\\.php$/i", $file_searched, $regapi)) {
2782 continue;
2783 }
2784
2785 $key = strtolower($regapi[1]);
2786 if (isset($endpoints[$key])) {
2787 continue; // First module wins, as in the REST layer.
2788 }
2789
2790 $endpoints[$key] = [
2791 'module' => $modulenameforenabled,
2792 'path' => $dir_part.$file_searched,
2793 'candidate' => str_replace('_', '', ucwords($regapi[1])),
2794 'class' => '', // resolved lazily by resolveEndpointClass()
2795 'label' => $this->enrichments[$key]['label'] ?? $key,
2796 ];
2797 }
2798 closedir($handle_part);
2799 }
2800 closedir($handle);
2801 }
2802
2803 ksort($endpoints);
2804
2805 return $endpoints;
2806 }
2807
2817 private function resolveEndpointClass(string $key): bool
2818 {
2819 if ($this->endpoints[$key]['class'] !== '') {
2820 return true;
2821 }
2822 require_once $this->endpoints[$key]['path'];
2823 $candidate = $this->endpoints[$key]['candidate'];
2824 $classname = '';
2825 if (class_exists($candidate.'Api')) {
2826 $classname = $candidate.'Api';
2827 } elseif (class_exists($candidate)) {
2828 $classname = $candidate;
2829 }
2830 if ($classname === '') {
2831 return false; // api_xxx file without the matching class.
2832 }
2833 // $classname passed class_exists() above, so the constructor cannot throw.
2834 $reflection = new ReflectionClass($classname);
2835 $this->endpoints[$key]['class'] = $reflection->getName();
2836
2837 // A key-only label ("paiements") is poor guidance for the model; take
2838 // the first line of the class docblock when no enrichment names it.
2839 if ($this->endpoints[$key]['label'] === $key) {
2840 $classdoc = (string) $reflection->getDocComment();
2841 if (preg_match('/\*\s+([^@\s\/*][^\n]*)/', $classdoc, $mlabel)) {
2842 // "API class for contacts" -> "contacts": keep the object, drop the boilerplate.
2843 $this->endpoints[$key]['label'] = trim(preg_replace('/^API class (for|of)\s+(the\s+)?/i', '', trim($mlabel[1])));
2844 }
2845 }
2846
2847 return true;
2848 }
2849
2860 private function defaultMethods(): array
2861 {
2862 return ['index' => [], 'get' => []];
2863 }
2864
2873 private function toolGroups(): array
2874 {
2875 $groups = [];
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;
2880 }
2881 }
2882 }
2883
2884 return $groups;
2885 }
2886
2895 private function applyFixedParams(string $toolName, array $args)
2896 {
2897 $meta = $this->methodMetaFor($toolName);
2898 foreach ((array) ($meta['fixed_params'] ?? array()) as $pname => $value) {
2899 $args[$pname] = $value;
2900 }
2901
2902 return $args;
2903 }
2904
2914 private function applyMethodRestriction(array $methods): array
2915 {
2916 $configured = getDolGlobalString('AI_MCP_API_BRIDGE_METHODS');
2917 if ($configured === '') {
2918 return $methods;
2919 }
2920 $allowed = array_map('trim', explode(',', $configured));
2921 return array_intersect_key($methods, array_flip($allowed));
2922 }
2923
2929 public function getDefinitions(): array
2930 {
2931 if ($this->defs !== null) {
2932 return $this->defs;
2933 }
2934
2935 // Cross-request cache of the generated definitions: the directory scans
2936 // and the per-method reflection/docblock work below produce the same
2937 // result for a given set of enabled modules, so it is generated once
2938 // and reread from a JSON file until something relevant changes. The
2939 // routes and the endpoint map ride along because execute() needs them
2940 // (the endpoint class itself is still required lazily at call time).
2941 $cachettl = getDolGlobalInt('AI_MCP_BRIDGE_DEFS_CACHE_TTL', 86400);
2942 $cachefile = ($cachettl > 0) ? $this->defsCacheFile() : '';
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'];
2950
2951 return $this->defs;
2952 }
2953 }
2954
2955 $this->loadApiRuntime();
2956
2957 $this->defs = [];
2958 $this->routes = [];
2959 $this->endpoints = $this->discoverEndpoints();
2960
2961 foreach ($this->toolGroups() as $key => $epkey) {
2962 // Endpoint whitelist, per the review that merged the bridge in
2963 // #39856 ("we should add a whitelist of api we think it is enable
2964 // for ai"): a discovered endpoint is exposed only when it carries a
2965 // hand-written $enrichments entry. Discovery decides what is
2966 // reachable; the enrichment entry is the conscious line that makes
2967 // it exposed. Removing this guard means auto-exposing every enabled
2968 // module's endpoints — an explicit decision to make, not a default.
2969 if (!isset($this->enrichments[$key])) {
2970 continue;
2971 }
2972 // Method whitelist: only the listed methods are exposed — nothing
2973 // else, whatever reflection could find on the API class. Enriched
2974 // endpoints without a 'methods' key fall back to the read-only pair.
2975 $methods = $this->applyMethodRestriction($this->enrichments[$key]['methods'] ?? $this->defaultMethods());
2976 if (empty($methods) || !$this->resolveEndpointClass($epkey)) {
2977 continue; // nothing left to expose, or api file without its class
2978 }
2979 $ep = $this->endpoints[$epkey]; // re-read: 'class' is now resolved
2980 $ep['label'] = $this->enrichments[$key]['label'] ?? $ep['label'];
2981
2982 foreach ($methods as $method => $meta) {
2983 // A method may need an optional module beyond its endpoint's own
2984 // (e.g. products getVariants needs Variants): skip when off, so
2985 // the tool does not exist instead of failing opaquely.
2986 if (!empty($meta['module']) && !isModEnabled($meta['module'])) {
2987 continue;
2988 }
2989 // A method that only works in a mode of the setup (a price mode)
2990 // does not exist when that mode is off.
2991 if (!empty($meta['setup']) && !$this->setupAllows((array) $meta['setup'])) {
2992 continue;
2993 }
2994 if (!method_exists($ep['class'], $method)) {
2995 continue; // whitelisted method absent in this Dolibarr version
2996 }
2997 $suffix = $meta['suffix'] ?? ($method === 'index' ? 'list' : strtolower($method));
2998 $toolname = 'api_' . $key . '_' . $suffix;
2999 $def = $this->buildToolDefinition($ep, $key, $method, $toolname, $meta);
3000 if ($def) {
3001 $def['categories'] = self::ENDPOINT_CATEGORIES[$key] ?? array('billing', 'commercial', 'thirdparty', 'stock', 'project', 'reporting');
3002 $this->defs[] = $def;
3003 $this->routes[$toolname] = [$key, $method];
3004 }
3005 }
3006 }
3007
3008 if ($cachefile !== '') {
3009 $this->writeDefsCache($cachefile);
3010 }
3011
3012 return $this->defs;
3013 }
3014
3021 private function setupAllows(array $consts)
3022 {
3023 foreach ($consts as $const) {
3024 if (getDolGlobalString($const)) {
3025 return true;
3026 }
3027 }
3028
3029 return false;
3030 }
3031
3046 private function defsCacheFile()
3047 {
3048 global $conf;
3049
3050 $dir = '';
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;
3055 }
3056 if (empty($dir) || dol_mkdir($dir) < 0) {
3057 return '';
3058 }
3059
3060 $modules = array_map('strval', array_values((array) $conf->modules));
3061 sort($modules);
3062 $signature = implode(',', $modules).'|'.DOL_VERSION.'|'.((int) $conf->entity).'|'.((int) @filemtime(__FILE__)).'|'.DOL_DOCUMENT_ROOT;
3063 // Security-relevant runtime restrictions live in the DATABASE, not in
3064 // this file: they must be part of the signature too, or restricting
3065 // them would silently keep serving the wider cached toolset for up to
3066 // a full TTL (review sonikf on the initial version).
3067 $signature .= '|'.getDolGlobalString('AI_MCP_API_BRIDGE_METHODS');
3068 // The setup the writes are declared with: the validation right and the
3069 // product fields an edit offers.
3070 foreach (array('MAIN_USE_ADVANCED_PERMS', 'PRODUCT_PRICE_UNIQ', 'PRODUIT_CUSTOMER_PRICES') as $const) {
3071 $signature .= '|'.$const.'='.getDolGlobalString($const);
3072 }
3073 // The setup modes some methods depend on: turning one on shows its tools at once.
3074 foreach ($this->enrichments as $meta) {
3075 foreach (($meta['methods'] ?? array()) as $mmeta) {
3076 foreach ((array) ($mmeta['setup'] ?? array()) as $const) {
3077 $signature .= '|'.$const.'='.getDolGlobalString($const);
3078 }
3079 }
3080 }
3081
3082 return rtrim($dir, '/').'/bridge_tooldefs_'.md5($signature).'.json';
3083 }
3084
3094 private function writeDefsCache(string $cachefile)
3095 {
3096 $payload = json_encode(array('defs' => $this->defs, 'routes' => $this->routes, 'endpoints' => $this->endpoints));
3097 if (!is_string($payload)) {
3098 return;
3099 }
3100 foreach ((array) glob(dirname($cachefile).'/bridge_tooldefs_*.json') as $old) {
3101 if (is_string($old) && $old !== $cachefile) {
3102 @unlink($old);
3103 }
3104 }
3105 $tmpfile = $cachefile.'.tmp.'.getmypid();
3106 if (file_put_contents($tmpfile, $payload) !== false) {
3107 @rename($tmpfile, $cachefile);
3108 }
3109 }
3110
3119 public function purgeDefsCache(): int
3120 {
3121 global $conf;
3122
3123 $dirs = array();
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, '/');
3128 }
3129 }
3130 }
3131 if (!empty($conf->ai->dir_temp) && is_string($conf->ai->dir_temp)) {
3132 $dirs[] = rtrim($conf->ai->dir_temp, '/');
3133 }
3134
3135 $count = 0;
3136 foreach (array_unique($dirs) as $dir) {
3137 // Same @unlink as writeDefsCache() pruning the previous states: no
3138 // dol_delete_file() here, files.lib.php is not loaded in every context.
3139 foreach ((array) glob($dir.'/bridge_tooldefs_*.json') as $file) {
3140 if (is_string($file) && @unlink($file)) {
3141 $count++;
3142 }
3143 }
3144 }
3145
3146 return $count;
3147 }
3148
3162 private function buildToolDefinition(array $ep, string $key, string $method, string $toolname, array $meta = [])
3163 {
3164 try {
3165 $rm = new ReflectionMethod($ep['class'], $method);
3166 } catch (ReflectionException $e) {
3167 return null;
3168 }
3169
3170 $doc = (string) $rm->getDocComment();
3171
3172 // First docblock line = human description of the endpoint. The leading
3173 // asterisk of the line is excluded so "/**\n * Foo" yields "Foo", not "* Foo".
3174 $summary = '';
3175 if (preg_match('/\*\s+([^@\s\/*][^\n]*)/', $doc, $m)) {
3176 $summary = trim($m[1]);
3177 }
3178
3179 // @param <type> $<name> <description>
3180 $paramDocs = [];
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])];
3184 }
3185 }
3186
3187 $properties = [];
3188 $required = [];
3189 foreach ($rm->getParameters() as $p) {
3190 $pname = $p->getName();
3191 $ptype = isset($paramDocs[$pname]) ? $this->docTypeToJson($paramDocs[$pname]['type']) : 'string';
3192 // Parameter doc priority: hand-written per-method enrichment, then the
3193 // description guessed from the docblock, then the shared common docs.
3194 // Exception for the two syntax-bearing params (sqlfilters, sortfield):
3195 // their API docblocks carry a thin per-endpoint example that would win
3196 // over — and hide — the full syntax contract (operators, and/or, the
3197 // unsupported IN, the datec/tms column names), so there the common doc
3198 // is APPENDED to the docblock description instead of being shadowed.
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;
3207 if ($keptdesc) {
3208 $pdesc .= "\n".$keptdesc;
3209 }
3210 }
3211 if ($pname === 'sortfield' && $commondesc !== '') {
3212 $pdesc = rtrim((string) $pdesc, '. ').'. '.$commondesc;
3213 }
3214 } else {
3215 $pdesc = $commondesc;
3216 }
3217 // The API docblocks carry Restler's inline validation tags. They are
3218 // markup, not prose: left in place they reach the model as noise
3219 // ("... (example '1' or '1,2,3') {@pattern /^[0-9,]*$/i}"). Lift the
3220 // ones JSON Schema can express into real constraints, and drop the
3221 // rest from the text.
3222 $constraints = [];
3223 $pdesc = $this->liftInlineTags($pdesc, $ptype, $constraints);
3224
3225 $prop = [
3226 'type' => $ptype,
3227 'description' => $pdesc
3228 ];
3229 $prop += $constraints;
3230 if ($p->isOptional()) {
3231 try {
3232 $prop['default'] = ($pname == 'limit') ? self::BRIDGE_DEFAULT_LIMIT : $p->getDefaultValue();
3233 } catch (ReflectionException $e) {
3234 // keep without default
3235 }
3236 } else {
3237 $required[] = $pname;
3238 }
3239 $properties[$pname] = $prop;
3240 }
3241
3242 // A create receives one request_data body, which tells the model nothing:
3243 // show the fields it accepts instead, flat, as the call is made. A line
3244 // added to an existing record ('parent') keeps the API's own parameters.
3245 if (!empty($meta['write']) && empty($meta['write']['parent']) && !empty($meta['params'])) {
3246 $properties = [];
3247 $required = [];
3248 foreach ($meta['params'] as $pname => $pdesc) {
3249 if ($pname === 'lines') {
3250 // Lines of a commercial document, unless the write declares its own
3251 // line fields (a reception names a warehouse and a cost price, not a VAT rate).
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.']
3259 ];
3260 $properties[$pname] = [
3261 'type' => 'array',
3262 'description' => $pdesc,
3263 'items' => [
3264 'type' => 'object',
3265 'properties' => $lineFields
3266 ]
3267 ];
3268 continue;
3269 }
3270 $properties[$pname] = ['type' => 'string', 'description' => $pdesc];
3271 }
3272 foreach ((array) ($meta['write']['required'] ?? array()) as $pname) {
3273 $required[] = $pname;
3274 }
3275 }
3276
3277 // Arguments the tool forces on the call are not the caller's to give.
3278 $fixed = array_keys((array) ($meta['fixed_params'] ?? array()));
3279 if ($fixed) {
3280 $properties = array_diff_key($properties, array_flip($fixed));
3281 $required = array_values(array_diff($required, $fixed));
3282 }
3283
3284 if (!empty($meta['write'])) {
3285 $verb = 'Write to';
3286 } elseif ($method === 'index') {
3287 $verb = 'List / search';
3288 } elseif ($method === 'get') {
3289 $verb = 'Get one record of';
3290 } else {
3291 $verb = 'Read from'; // other whitelisted read helpers (e.g. product variants)
3292 }
3293 $schema = ['type' => 'object', 'properties' => $properties];
3294 if ($required) {
3295 $schema['required'] = $required;
3296 }
3297 if (!empty($meta['write']['update'])) {
3298 $schema = $this->updateInputSchema($meta['write']);
3299 }
3300
3301 // A write runs only once confirmed: the first call answers input_required
3302 // with a requestState (see McpHandler::checkWriteConfirmation()), and the
3303 // caller runs it by calling again with the same arguments plus it.
3304 if (!empty($meta['write'])) {
3305 $schema['properties']['requestState'] = array(
3306 'type' => 'string',
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.'
3308 );
3309 }
3310
3311 $schema = self::normalizeInputSchema($schema);
3312
3313 $description = $verb . ' ' . $ep['label'] . ' through the Dolibarr REST API (auto-generated tool). ' . $summary;
3314 // When an explicit description is given, it has priority on auto-generated description
3315 if (!empty($meta['description'])) {
3316 $description = $meta['description'];
3317 }
3318
3319 return [
3320 'name' => $toolname,
3321 'description' => $description,
3322 'inputSchema' => $schema
3323 ];
3324 }
3325
3343 private function liftInlineTags($desc, string $ptype, array &$constraints): string
3344 {
3345 $desc = (string) $desc;
3346
3347 if (strpos($desc, '{@') === false) {
3348 return $desc;
3349 }
3350
3351 $matches = [];
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]);
3356
3357 if ($name === 'min' && is_numeric($value)) {
3358 $constraints['minimum'] = $this->tagValueToNumber($value);
3359 } elseif ($name === 'max' && is_numeric($value)) {
3360 $constraints['maximum'] = $this->tagValueToNumber($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)) {
3366 $choices[$i] = $this->tagValueToNumber($choice);
3367 }
3368 }
3369 }
3370 $constraints['enum'] = array_values($choices);
3371 } elseif (($name === 'const' || $name === 'constant') && $value !== '') {
3372 $val = $value;
3373 if ($ptype === 'integer' || $ptype === 'number') {
3374 if (is_numeric($val)) {
3375 $val = $this->tagValueToNumber($val);
3376 }
3377 } elseif ($ptype === 'boolean') {
3378 $val = filter_var($val, FILTER_VALIDATE_BOOLEAN);
3379 }
3380 // JSON Schema const is rejected by Gemini and some LLM function-calling APIs;
3381 // normalize to a single-element enum instead.
3382 $constraints['enum'] = array($val);
3383 } elseif ($name === 'pattern' && $value !== '') {
3384 $pattern = $this->restlerPatternToJsonSchema($value);
3385 if ($pattern !== '') {
3386 $constraints['pattern'] = $pattern;
3387 }
3388 }
3389 }
3390 }
3391
3392 // Remove every tag, including the ones left untranslated, then tidy the
3393 // whitespace the removal leaves behind.
3394 $desc = preg_replace('/\s*\{@\w[\w-]*[^}]*\}/', '', $desc);
3395
3396 return trim(preg_replace('/\s{2,}/', ' ', (string) $desc));
3397 }
3398
3408 private function tagValueToNumber(string $value)
3409 {
3410 return (strpos($value, '.') === false) ? (int) $value : (float) $value;
3411 }
3412
3426 private function restlerPatternToJsonSchema(string $value): string
3427 {
3428 $reg = [];
3429 if (!preg_match('/^(.)(.*)\1([a-zA-Z]*)$/s', $value, $reg)) {
3430 return ''; // not delimited: not a PCRE literal, leave it in the description
3431 }
3432
3433 $expression = $reg[2];
3434 $flags = $reg[3];
3435
3436 if ($flags !== '' && !($flags === 'i' && !preg_match('/[a-zA-Z]/', $expression))) {
3437 return '';
3438 }
3439
3440 return $expression;
3441 }
3442
3449 private function docTypeToJson(string $type): string
3450 {
3451 $t = strtolower(trim(explode('|', $type)[0]));
3452 if (in_array($t, ['int', 'integer'], true)) {
3453 return 'integer';
3454 }
3455 if (in_array($t, ['float', 'double'], true)) {
3456 return 'number';
3457 }
3458 if ($t === 'bool' || $t === 'boolean') {
3459 return 'boolean';
3460 }
3461 return 'string';
3462 }
3463
3470 public function getRequiredRights(string $toolName)
3471 {
3472 // A write declares its right here as well as relying on the REST class,
3473 // so the call is refused before the gate issues a confirmation: no
3474 // preview for a write the user could never perform.
3475 $meta = $this->methodMetaFor($toolName);
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']);
3479 }
3480
3481 // A read method may declare the rights it needs on top of the
3482 // endpoint's own base checks (products.getStock also needs
3483 // stock/lire). Declaring them keeps the tool out of tools/list for a
3484 // caller who lacks them, and refuses the call with a named right
3485 // instead of the bare 403 the API class would throw. Both shapes are
3486 // accepted: a single triple ['module','perm'] or a list of triples.
3487 if (!empty($meta['right'])) {
3488 $declared = (isset($meta['right'][0]) && is_array($meta['right'][0])) ? $meta['right'] : array($meta['right']);
3489 $rights = array();
3490 foreach ($declared as $triple) {
3491 if (!is_array($triple)) {
3492 continue;
3493 }
3494 $strings = array();
3495 foreach (array_values($triple) as $v) {
3496 $strings[] = (string) $v;
3497 }
3498 if ($strings) {
3499 $rights[] = $strings;
3500 }
3501 }
3502 if ($rights) {
3503 return $rights;
3504 }
3505 }
3506
3507 return self::RIGHTS_ENFORCED_DOWNSTREAM;
3508 }
3509
3518 private function defaultVatRate($socid, $fk_product, $buy = false)
3519 {
3520 global $mysoc;
3521
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)) {
3525 return 0;
3526 }
3527
3528 return (float) ($buy ? get_default_tva($soc, $mysoc, $fk_product) : get_default_tva($mysoc, $soc, $fk_product));
3529 }
3530
3540 private function defaultBuyPrice($prod, $socid, $qty)
3541 {
3542 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
3543 $pf = new ProductFournisseur($this->db);
3544 if ($socid > 0 && $pf->find_min_price_product_fournisseur($prod->id, $qty, $socid) > 0) {
3545 return (float) $pf->fourn_unitprice;
3546 }
3547
3548 return (float) $prod->cost_price;
3549 }
3550
3559 protected function fetchBusinessObject($class, $id, $ref = '')
3560 {
3561 $paths = array(
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'
3576 );
3577 if (empty($paths[$class]) || ((int) $id <= 0 && $ref === '')) {
3578 return null;
3579 }
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);
3584 if ($result > 0) {
3585 return $obj;
3586 }
3587
3588 return null;
3589 }
3590
3598 private function refOfCreatedObject($class, $id)
3599 {
3600 $obj = $this->fetchRecord($class, $id);
3601
3602 return $obj ? (string) $obj->ref : '';
3603 }
3604
3613 private function previewObjectName($class, $id)
3614 {
3615 if (empty($id) || !is_numeric($id)) {
3616 return json_encode($id);
3617 }
3618 $obj = $this->fetchBusinessObject($class, (int) $id);
3619 if (!$obj) {
3620 return '#'.((int) $id);
3621 }
3622 $name = (string) ($obj->title ?? ($obj->label ?? ($obj->name ?? '')));
3623
3624 return $obj->ref.($name !== '' ? ' - '.$name : '');
3625 }
3626
3634 private function fetchWriteParent(array $write, array $args)
3635 {
3636 if (!empty($write['ref']) && !empty($write['object'])) {
3637 return $this->fetchBusinessObject($write['object'], (int) ($args[$write['parent']] ?? 0), (string) ($args[$write['ref']] ?? ''));
3638 }
3639 if (empty($write['parent']) || empty($write['object']) || !is_numeric($args[$write['parent']] ?? '')) {
3640 return null;
3641 }
3642
3643 return $this->fetchBusinessObject($write['object'], (int) $args[$write['parent']]);
3644 }
3645
3652 private function updateInputSchema(array $write)
3653 {
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'])).'.']
3660 ]];
3661 $changes = [['required' => ['request_data']]];
3662 foreach (array_keys($write['update']) as $field) {
3663 $changes[] = ['required' => [$field]];
3664 }
3665 return ['type' => 'object', 'additionalProperties' => false, 'properties' => $properties,
3666 'oneOf' => [['required' => [$write['parent']]], ['required' => [$write['ref']]]], 'anyOf' => $changes];
3667 }
3668
3676 protected function canAccessWriteObject(array $access, $id)
3677 {
3678 return checkUserAccessToObject($this->user, [$access[0]], $id, $access[1], $access[2] === '' ? '' : [$access[2]], 'fk_soc');
3679 }
3680
3687 protected function canWriteProject($project)
3688 {
3689 return $project->restrictedProjectArea($this->user, 'write') > 0;
3690 }
3691
3700 private function validateProjectUpdate(array $args, $parent)
3701 {
3702 $project = $parent;
3703 if (!$project || !$this->canAccessWriteObject(['project', '', ''], (int) $project->id) || !$this->canWriteProject($project)) {
3704 throw new InvalidArgumentException('Access denied to project');
3705 }
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');
3708 }
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');
3713 }
3714 }
3715
3724 private function normaliseUpdateArgs(array $args, array $write)
3725 {
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;
3731 }
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');
3734 }
3735 if (array_diff_key($body, $write['update'])) {
3736 throw new InvalidArgumentException('request_data must contain only the permitted update fields');
3737 }
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);
3742 }
3743 }
3744 $args = array_merge($body, $args);
3745 }
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');
3752 }
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');
3756 }
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;
3761 }
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);
3764 }
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);
3773 }
3774 if (!$valid) {
3775 throw new InvalidArgumentException('Invalid value for '.$field);
3776 }
3777 }
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');
3781 }
3782 }
3783 $parent = $this->fetchWriteParent($write, $args);
3784 if (!$parent) {
3785 throw new InvalidArgumentException('Record not found');
3786 }
3787 if (!$this->canAccessWriteObject($write['access'], (int) $parent->id)) {
3788 throw new InvalidArgumentException('Access denied to record');
3789 }
3790 if (!empty($write['draft_only']) && (int) $parent->status !== 0) {
3791 global $langs;
3792 $langs->load('other');
3793 throw new InvalidArgumentException($langs->transnoentitiesnoconv('AIWriteNotDraftEdit', (string) $write['label'], (string) $parent->ref));
3794 }
3795 if (!empty($write['project_update'])) {
3796 $this->validateProjectUpdate($args, $parent);
3797 }
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);
3801 }
3802 }
3803 if (!empty($write['extrafields']) && isset($changes['array_options']) && !empty($this->db)) {
3804 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
3805 $extrafields = new ExtraFields($this->db);
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)'));
3811 }
3812 }
3813 }
3814 unset($args[$refkey]);
3815 $args[$idkey] = (int) $parent->id;
3816 return $args;
3817 }
3818
3826 private function unitIdFromName($name)
3827 {
3828 require_once DOL_DOCUMENT_ROOT.'/ai/lib/ai.lib.php';
3829
3830 return aiUnitIdFromName($this->db, $name);
3831 }
3832
3845 private function normaliseWriteArgs(array $args, array $write = array())
3846 {
3847 $this->unresolvedProducts = array();
3848 if (!empty($write['update'])) {
3849 return $this->normaliseUpdateArgs($args, $write);
3850 }
3851
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();
3857 }
3858 if (is_array($body)) {
3859 // A model may nest the record under a key of its own naming
3860 // ({"thirdparty": {...}}): unwrap a lone array value rather than
3861 // passing the wrapper to the API, which sees no fields at all.
3862 if (count($body) === 1) {
3863 $only = reset($body);
3864 if (is_array($only) && !isset($body[0])) {
3865 $body = $only;
3866 }
3867 }
3868 unset($args['request_data']);
3869 $args = array_merge($body, $args);
3870 }
3871 }
3872
3873 // A line added to an existing record: its fields come flat, next to the
3874 // record id. A model used to the create tools may still wrap it in a
3875 // one-line 'lines' array. The third party, needed for the default VAT
3876 // rate, is the record's.
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);
3882 }
3883 if (!isset($args['qty']) && !isset($args['quantity'])) {
3884 $args['qty'] = 1; // "add product X to the order" means one
3885 }
3886 $parent = $this->fetchWriteParent($write, $args);
3887 $this->resetWriteState();
3888
3889 return $this->normaliseWriteLine($args, $this->socidOf($parent), !empty($write['buy']));
3890 }
3891
3892 // A write on a record that exists.
3893 $this->resetWriteState();
3894 $kind = (string) ($write['kind'] ?? '');
3895 if (in_array($kind, array('update', 'action', 'delete', 'payment', 'line'), true)) {
3896 return $this->normaliseTargetArgs($args, $write);
3897 }
3898 if (!empty($write['lookup']) && $kind === '') {
3899 $args = $this->normaliseOneRecordArgs($args, $write);
3900 }
3901
3902 // Record fields under the names a model is likely to use: the database
3903 // column (nom) rather than the API field (name), or the obvious synonym.
3904 $fieldAliases = array('nom' => 'name', 'company' => 'name', 'mail' => 'email', 'tel' => 'phone', 'telephone' => 'phone', 'libelle' => 'label', 'title' => 'label');
3905 foreach ($fieldAliases as $from => $to) {
3906 // A field the write itself names is never renamed (a project has a title).
3907 if (in_array($from, (array) ($write['required'] ?? array()), true) || in_array($from, (array) ($write['args'] ?? array()), true)) {
3908 continue;
3909 }
3910 if (isset($args[$from]) && !isset($args[$to]) && !is_array($args[$from])) {
3911 $args[$to] = $args[$from];
3912 unset($args[$from]);
3913 }
3914 }
3915
3916 // The third party may arrive as a name: resolve it here rather than making
3917 // the model spend a turn on a lookup, which with one tool call per answer
3918 // means the write never happens.
3919 if (empty($args['socid']) || !is_numeric($args['socid'])) {
3920 $named = '';
3921 foreach (array('socid', 'thirdparty', 'company', 'customer', 'supplier') as $key) {
3922 if (!empty($args[$key]) && !is_numeric($args[$key])) {
3923 $named = (string) $args[$key];
3924 break;
3925 }
3926 }
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)."')";
3931 $sql .= " LIMIT 2";
3932 $resql = $this->db->query($sql);
3933 if ($resql && $this->db->num_rows($resql) === 1) {
3934 // One match only: several would mean guessing which company the
3935 // user meant, and the guess would only surface in the preview.
3936 $obj = $this->db->fetch_object($resql);
3937 $args['socid'] = (int) $obj->rowid;
3938 } else {
3939 // The name as people say it: the trade name, or some words of the
3940 // legal name in any order ("Anthropic" for "Anthropic Ireland,
3941 // Limited"). One match only, and only when the whole name given
3942 // is that phrase.
3943 global $user;
3944 require_once DOL_DOCUMENT_ROOT.'/ai/lib/ai.lib.php';
3945 $named = trim($named);
3946 // No narrowing to customers or suppliers here: a company the user
3947 // may mean is never dropped silently. Several fit -> nothing is
3948 // resolved and writePrecheck() lists them for the user.
3949 $found = aiFindThirdpartiesInText($this->db, $user, $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']);
3952 }
3953 }
3954 }
3955 }
3956
3957 // A logistic document (reception, shipment): the header names a model is
3958 // likely to use, dates as text, and a warehouse given once for every line.
3959 $kind = (string) ($write['kind'] ?? '');
3960 $headerWarehouse = 0;
3961 if ($kind !== '') {
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]);
3967 }
3968 }
3969 // The business classes want timestamps, a model writes dates as text.
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]);
3975 }
3976 }
3977 }
3978 foreach (array('warehouse', 'warehouse_id', 'fk_warehouse', 'entrepot') as $key) {
3979 if (!empty($args[$key]) && !is_array($args[$key]) && $kind === 'reception') {
3980 // A warehouse that was named must exist and be open: never the default instead.
3981 $headerWarehouse = $this->resolveWarehouse((string) $args[$key]);
3982 }
3983 unset($args[$key]); // the API reads the warehouse on each line, never on the header
3984 }
3985 }
3986
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);
3991 }
3992 }
3993 }
3994
3995 $args = $this->normaliseCreateExtras($args, $write);
3996
3997 // Names for the confirmation sentence; '_' arguments never reach the API.
3998 if (!empty($write['thirdparty'])) {
3999 global $langs;
4000 $args['_who'] = '';
4001 $args['_at'] = '';
4002 $socid = (int) (is_numeric($args[$write['thirdparty']] ?? '') ? $args[$write['thirdparty']] : 0);
4003 // No database when the tools are only declared (unit tests): nothing to name.
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);
4009 }
4010 }
4011 if (($write['object'] ?? '') === 'Contact') {
4012 $args['_name'] = trim(((string) ($args['firstname'] ?? '')).' '.((string) ($args['lastname'] ?? '')));
4013 }
4014
4015 return $args;
4016 }
4017
4029 private function normaliseWriteLine(array $line, $socid, $buy = false, $kind = '', $defaultWarehouse = 0)
4030 {
4031 $aliases = array('quantity' => 'qty', 'unit_price' => 'subprice', 'price' => 'subprice', 'description' => 'desc', 'vat_rate' => 'tva_tx', 'product_id' => 'fk_product');
4032 if ($kind !== '') {
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');
4034 }
4035 foreach ($aliases as $from => $to) {
4036 if (isset($line[$from]) && !isset($line[$to])) {
4037 $line[$to] = $line[$from];
4038 unset($line[$from]);
4039 }
4040 }
4041 if ($kind === 'reception') {
4042 // The price of a received line is what it cost: whatever the model
4043 // called it, the API reads cost_price.
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];
4047 }
4048 unset($line[$from]);
4049 }
4050 }
4051 // A line given by product ref carries no price: resolve it so the
4052 // preview and the write use the catalogue product, as the REST
4053 // endpoint expects an id.
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);
4059 if (!$found) {
4060 // A user names a product the way it appears on screen, which is
4061 // its label: accept that too, and only when it is not ambiguous,
4062 // so nothing is billed off a guess.
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)."')";
4066 $sql .= " LIMIT 2";
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);
4071 }
4072 }
4073 if (!$found && $buy && $socid > 0) {
4074 // A supplier document carries the SUPPLIER's references - a delivery
4075 // note almost never shows ours. Look the ref up in that supplier's
4076 // catalogue, and only there, so another supplier's "33303" never fits.
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)."'";
4081 $sql .= " LIMIT 2";
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);
4086 }
4087 }
4088 if ($found) {
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; // the product is in hand: its unit costs nothing more
4092 }
4093 if (!isset($line['desc'])) {
4094 $line['desc'] = $prod->label;
4095 }
4096 if (!isset($line['subprice'])) {
4097 $line['subprice'] = $buy ? $this->defaultBuyPrice($prod, $socid, (float) ($line['qty'] ?? 1)) : $prod->price;
4098 }
4099 }
4100 if (!$found && !isset($line['desc'])) {
4101 // Unknown or ambiguous: keep what the user called it, so the
4102 // line reads "popularpt" instead of appearing blank.
4103 $line['desc'] = $wanted;
4104 }
4105 if (!$found) {
4106 $this->unresolvedProducts[$wanted] = $this->closeProductRefs($wanted, $buy ? $socid : 0);
4107 }
4108 unset($line['product_ref']);
4109 }
4110 // Unit: the one the user named else the product's own,
4111 // as the card would. A name matching no unit, or several, is dropped
4112 // rather than guessed.
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']);
4116 if ($unit > 0) {
4117 $line['fk_unit'] = $unit;
4118 }
4119 }
4120 if (empty($line['fk_unit']) && !empty($line['fk_product'])) {
4121 $unitprod = $this->fetchBusinessObject('Product', (int) $line['fk_product']);
4122 if ($unitprod instanceof Product && !empty($unitprod->fk_unit)) {
4123 $line['fk_unit'] = (int) $unitprod->fk_unit;
4124 }
4125 }
4126 if ($kind !== '') {
4127 // A logistic line moves stock: it needs a warehouse, by name or rowid,
4128 // else the one given on the header, else the default one. No VAT, no
4129 // selling price on such a line.
4130 if ($kind === 'shipment') {
4131 // A shipment line without a source order is a free line, which core
4132 // records with no warehouse (as the shipment card does): none is
4133 // given, so none is announced in the confirmation either.
4134 unset($line['fk_entrepot']);
4135 $lotprod = empty($line['fk_product']) ? null : $this->fetchBusinessObject('Product', (int) $line['fk_product']);
4136 if (isModEnabled('productbatch') && $lotprod instanceof Product && $lotprod->hasbatch()) {
4137 global $langs;
4138 $langs->load('other');
4139 $this->writeProblems[] = $langs->transnoentitiesnoconv('AIWriteShipmentLotProduct', $lotprod->ref);
4140 }
4141 } else {
4142 if (isset($line['fk_entrepot']) && (string) $line['fk_entrepot'] !== '' && !is_array($line['fk_entrepot'])) {
4143 // Named on the line, by name or rowid: an open warehouse, or refused.
4144 $line['fk_entrepot'] = $this->resolveWarehouse((string) $line['fk_entrepot']);
4145 }
4146 if (empty($line['fk_entrepot'])) {
4147 $line['fk_entrepot'] = $defaultWarehouse > 0 ? $defaultWarehouse : $this->defaultWarehouseId();
4148 }
4149 if (empty($line['fk_entrepot'])) {
4150 unset($line['fk_entrepot']);
4151 }
4152 }
4153 // No VAT and no selling price on a logistic line: a shipment line carries
4154 // no amount at all, a received line is valued by its cost price.
4155 unset($line['tva_tx'], $line['subprice']);
4156 if ($kind === 'reception') {
4157 // A received line without a price is valued at the supplier price of
4158 // the product, as the card would propose.
4159 if (!isset($line['cost_price']) && !empty($line['fk_product'])) {
4160 $costprod = $this->fetchBusinessObject('Product', (int) $line['fk_product']);
4161 if ($costprod instanceof Product) {
4162 $line['cost_price'] = $this->defaultBuyPrice($costprod, $socid, (float) ($line['qty'] ?? 1));
4163 }
4164 }
4165 // Lot dates arrive as text: the line class wants timestamps.
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]);
4171 }
4172 }
4173 }
4174 }
4175
4176 return $line;
4177 }
4178 // A line with no rate is written at 0 %: ask core for the rate that
4179 // applies between the two companies for this product, which is what
4180 // the card would have filled in.
4181 if (!isset($line['tva_tx']) && $socid > 0) {
4182 $line['tva_tx'] = $this->defaultVatRate($socid, (int) ($line['fk_product'] ?? 0), $buy);
4183 }
4184
4185 return $line;
4186 }
4187
4197 private function writeDate($field, $value, $gmt = 1)
4198 {
4199 global $langs;
4200
4201 $text = trim((string) $value);
4202 if ($text === '') {
4203 return null;
4204 }
4205 $ts = dol_stringtotime($text, $gmt);
4206 if ($ts > 0) {
4207 return $ts;
4208 }
4209 $langs->load('other');
4210 $this->writeProblems[] = $langs->transnoentitiesnoconv('AIWriteUnreadableDate', $text, $field);
4211
4212 return null;
4213 }
4214
4223 private function previewLogisticLines(array $lines, $kind)
4224 {
4225 global $langs;
4226
4227 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
4228 $warehouses = array();
4229 $out = array();
4230 foreach (array_slice($lines, 0, 10) as $line) {
4231 if (!is_array($line)) {
4232 continue;
4233 }
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'] ?? '');
4236 $text = price2num($line['qty'] ?? 1).' × '.dol_trunc($name, 50);
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;
4242 }
4243 if ($wid > 0) {
4244 $text .= ' '.$langs->trans('AIPreviewIntoWarehouse', $warehouses[$wid]);
4245 }
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'];
4249 }
4250 }
4251 $out[] = $text;
4252 }
4253 if (count($lines) > 10) {
4254 $out[] = '…';
4255 }
4256
4257 return implode('; ', $out);
4258 }
4259
4266 private function defaultWarehouseId()
4267 {
4268 if (!empty($this->user->fk_warehouse)) {
4269 return (int) $this->user->fk_warehouse;
4270 }
4271 if (getDolGlobalInt('MAIN_DEFAULT_WAREHOUSE') > 0) {
4272 return getDolGlobalInt('MAIN_DEFAULT_WAREHOUSE');
4273 }
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);
4277
4278 return (int) $obj->rowid;
4279 }
4280
4281 return 0;
4282 }
4283
4296 public function writeConfirmationPreview(string $toolName, array $args)
4297 {
4298 global $langs;
4299
4300 $langs->load("other");
4301
4302 $write = $this->writeMetaFor($toolName);
4303 if (empty($write)) {
4304 return McpTool::NO_WRITE;
4305 }
4306 $args = $this->applyFixedParams($toolName, $args);
4307 if (!empty($write['update'])) {
4308 try {
4309 $args = $this->normaliseWriteArgs($args, $write);
4310 } catch (InvalidArgumentException $e) {
4311 return $e->getMessage();
4312 }
4313 $parent = $this->fetchWriteParent($write, $args);
4314 if (!$parent) {
4315 return 'Record not found';
4316 }
4317 if (!empty($write['project_update'])) {
4318 $context = (string) $parent->title;
4319 } else {
4320 $supplier = $this->fetchBusinessObject('Societe', (int) $parent->socid);
4321 $context = $supplier ? $supplier->name : '';
4322 }
4323 $langs->load('sendings');
4324 $langs->load('bills');
4325 $changes = [];
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);
4333 }
4334 } elseif (!empty($write['preview_objects'][$field])) {
4335 // A linked record by its ref and label, "none" when unlinked.
4336 $changes[] = $label.': '.$this->previewObjectName((string) $write['preview_objects'][$field], $old).' → '.$this->previewObjectName((string) $write['preview_objects'][$field], $args[$field]);
4337 } else {
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;
4346 }
4347 }
4348 }
4349 return $langs->trans($write['preview'], $parent->ref, (string) $context, implode('; ', $changes));
4350 }
4351
4352 $args = $this->normaliseWriteArgs($args, $write);
4353
4354 $kind = (string) ($write['kind'] ?? '');
4355 if (in_array($kind, array('update', 'action', 'delete', 'payment', 'line'), true)) {
4356 return $this->previewTargetWrite($write, $args);
4357 }
4358
4359 // A line added to an existing record names the product, the record and
4360 // the amount of the line.
4361 if (!empty($write['parent'])) {
4362 $parent = $this->fetchWriteParent($write, $args);
4363 $what = (string) ($args['desc'] ?? '');
4364 $product = $this->fetchBusinessObject('Product', (int) ($args['fk_product'] ?? 0));
4365 if ($product instanceof Product) {
4366 $what = $product->ref.' - '.$product->label;
4367 }
4368 $qty = (float) ($args['qty'] ?? 1);
4369 $total = $qty * (float) ($args['subprice'] ?? 0) * (1 - (float) ($args['remise_percent'] ?? 0) / 100);
4370
4371 return $langs->trans($write['preview'], (string) $qty, dol_trunc($what, 60), ($parent ? $parent->ref : ''), price(price2num($total, 'MT')));
4372 }
4373
4374 // A single record (third party, product, category, ticket) has no lines:
4375 // it names the arguments that make up its sentence, then every other
4376 // argument the call will write, so the human approves nothing they did
4377 // not get to see. Language keys opt in to that extra list with a
4378 // trailing %s; keys without it simply ignore the appended value.
4379 if (!empty($write['args'])) {
4380 $values = array();
4381 foreach ($write['args'] as $argname) {
4382 $values[] = dol_trunc($this->previewValue($write, $argname, $args[$argname] ?? '', $args), 80);
4383 }
4384 // Only the declared parameters reach the REST call (see execute()): an
4385 // internal '_' argument or one the call drops is never shown as written.
4386 $declared = (array) ($this->methodMetaFor($toolName)['params'] ?? array());
4387 $extra = 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 === '') {
4390 continue;
4391 }
4392 $extra[] = $argname.'='.dol_trunc($this->previewValue($write, $argname, $argvalue, $args), 40);
4393 }
4394 $values[] = empty($extra) ? '' : ' ('.implode(', ', $extra).')';
4395 return $langs->trans($write['preview'], ...$values);
4396 }
4397
4398 $who = '';
4399 $socid = (int) ($args[$write['thirdparty']] ?? 0);
4400 if ($socid > 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);
4405 }
4406 }
4407
4408 $lines = isset($args[$write['lines']]) && is_array($args[$write['lines']]) ? $args[$write['lines']] : array();
4409 $total = 0.0;
4410 $priced = false;
4411 foreach ($lines as $line) {
4412 // A received line is valued at its cost price, a sold one at its selling price.
4413 $unitprice = $line['subprice'] ?? ($line['cost_price'] ?? '');
4414 if ($unitprice === '' || is_null($unitprice)) {
4415 continue;
4416 }
4417 $priced = true;
4418 $total += ((float) ($line['qty'] ?? 1)) * ((float) $unitprice);
4419 }
4420 $what = $langs->trans(count($lines) === 1 ? "AIPreviewLine" : "AIPreviewLines", (string) count($lines));
4421 if ($priced) {
4422 $what .= ', '.price($total);
4423 } elseif (($write['kind'] ?? '') !== 'shipment') {
4424 $what .= ', '.$langs->trans("AIPreviewFromCatalogue"); // a shipment line carries no price at all
4425 }
4426 if (($write['kind'] ?? '') !== '' && $lines) {
4427 // Goods are confirmed line by line: what, how many, and where they go.
4428 $what .= ': '.$this->previewLogisticLines($lines, (string) $write['kind']);
4429 }
4430
4431 return $langs->trans($write['preview'], $who, $what);
4432 }
4433
4445 private function previewValue(array $write, $argname, $value, array $args)
4446 {
4447 global $langs;
4448
4449 if (is_array($value)) {
4450 return '';
4451 }
4452 $value = (string) $value;
4453 if ($value !== '' && in_array($argname, (array) ($write['hours'] ?? array()), true) && is_numeric($value)) {
4454 return convertSecondToTime((int) $value, 'allhourmin');
4455 }
4456 if ($value !== '' && in_array($argname, (array) ($write['dates'] ?? array()), true) && is_numeric($value)) {
4457 return dol_print_date((int) $value, 'day');
4458 }
4459 $class = (string) ($write['object'] ?? '');
4460 // An argument naming a record other than the written one (the website a
4461 // page is created in) is resolved to what the user knows it by.
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;
4466 }
4467 // The record the write is about, named only to a user who may see it.
4468 if ($class !== '' && $argname === (string) ($write['target'] ?? 'id') && is_numeric($value) && (int) $value > 0 && !empty($this->db)) {
4469 $obj = $this->fetchRecord($class, (int) $value);
4470 return ($obj && $this->userCanReach($class, (int) $obj->id)) ? $this->describeRecord($obj) : $value;
4471 }
4472 if ($argname === (string) ($write['thirdparty'] ?? '') && is_numeric($value) && (int) $value > 0 && !empty($this->db)) {
4473 $soc = $this->fetchRecord('Societe', (int) $value);
4474 return ($soc && $this->userCanReach('Societe', (int) $soc->id)) ? $this->describeRecord($soc) : $value;
4475 }
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)) {
4480 return $this->describeRecord($ticket);
4481 }
4482 }
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;
4487 }
4488 $contact = $this->fetchRecord('Contact', (int) $value);
4489 return ($contact && $this->userCanReach('Contact', (int) $contact->id)) ? $this->describeRecord($contact) : $value;
4490 }
4491
4492 return $value;
4493 }
4494
4507 public function writePrecheck(string $toolName, array $args)
4508 {
4509 global $langs, $user;
4510
4511 $write = $this->writeMetaFor($toolName);
4512 if (empty($write)) {
4513 return '';
4514 }
4515 $args = $this->applyFixedParams($toolName, $args);
4516
4517 try {
4518 $args = $this->normaliseWriteArgs($args, $write);
4519 } catch (InvalidArgumentException $e) {
4520 return $e->getMessage();
4521 }
4522 if (!empty($write['update'])) {
4523 return '';
4524 }
4525
4526 $kind = (string) ($write['kind'] ?? '');
4527 if (in_array($kind, array('update', 'action', 'delete', 'payment', 'line'), true)) {
4528 return $this->precheckTargetWrite($write, $args);
4529 }
4530 // What the arguments already showed: a project that cannot be found, a
4531 // required field left empty (the third party is checked below).
4532 if (!empty($this->writeProblems)) {
4533 return $this->writeProblems[0];
4534 }
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);
4539 }
4540 }
4541
4542 if (!empty($write['thirdparty'])) {
4543 $field = (string) $write['thirdparty'];
4544 $named = false;
4545 foreach (array($field, 'thirdparty', 'company', 'customer', 'supplier') as $key) {
4546 if (!empty($args[$key])) {
4547 $named = true;
4548 }
4549 }
4550 // A contact, a project or a ticket may be for no third party at all:
4551 // a third party the write does not require is checked only when one
4552 // was given. When it is required, any missing, non-numeric or
4553 // non-positive value stays refused.
4554 $optional = !empty($write['thirdparty_optional']) || !in_array($field, (array) ($write['required'] ?? array()), true);
4555 if ($optional && !$named) {
4556 $field = '';
4557 }
4558 // A rowid the user may not see is refused like an unknown one, before
4559 // a confirmation sentence could name it (the REST class would refuse
4560 // the write itself, but only after the user read the sentence).
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]));
4564 }
4565 if ($field !== '' && (empty($args[$field]) || !is_numeric($args[$field]) || (int) $args[$field] <= 0)) {
4566 $langs->load('other');
4567 $named = '';
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]);
4571 break;
4572 }
4573 }
4574 if ($named === '') {
4575 return $langs->transnoentitiesnoconv('AIWriteNoThirdparty');
4576 }
4577
4578 require_once DOL_DOCUMENT_ROOT.'/ai/lib/ai.lib.php';
4579 $names = array();
4580 foreach (aiFindThirdpartiesInText($this->db, $user, $named) as $mt) {
4581 foreach ($mt['candidates'] as $c) {
4582 if ($c['visible']) {
4583 $names[] = $c['name'].' (id '.$c['id'].')';
4584 }
4585 }
4586 }
4587 if (count($names) > 1) {
4588 return $langs->transnoentitiesnoconv('AIWriteSeveralThirdparties', $named, implode(', ', $names));
4589 }
4590 if (count($names) === 1) {
4591 // Part of the name fits one company, the rest does not: ask, never assume.
4592 return $langs->transnoentitiesnoconv('AIWriteThirdpartyDidYouMean', $named, $names[0]);
4593 }
4594
4595 return $langs->transnoentitiesnoconv('AIWriteThirdpartyNotFound', $named);
4596 }
4597 }
4598
4599 // A logistic document: nothing is asked of the user when the write would
4600 // fail anyway - standalone documents switched off, no line, a line with
4601 // no product to move, or no warehouse to receive into.
4602 $kind = (string) ($write['kind'] ?? '');
4603 if ($kind !== '') {
4604 $langs->load('other');
4605 $standaloneConst = ($kind === 'reception') ? 'RECEPTION_STANDALONE' : 'SHIPMENT_STANDALONE';
4606 if (!empty($args['origin_id']) || !empty($args['origin_type'])) {
4607 // These tools write free lines: from an order, the card is the way.
4608 return $langs->transnoentitiesnoconv('AIWriteLogisticFromOrder', $kind);
4609 }
4610 if (!getDolGlobalString($standaloneConst)) {
4611 return $langs->transnoentitiesnoconv('AIWriteStandaloneOff', $kind, $standaloneConst);
4612 }
4613 $lines = isset($args[$write['lines']]) && is_array($args[$write['lines']]) ? $args[$write['lines']] : array();
4614 if (empty($lines)) {
4615 return $langs->transnoentitiesnoconv('AIWriteNoLines');
4616 }
4617 if (!empty($this->unresolvedProducts)) {
4618 return $this->unresolvedProductsMessage();
4619 }
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'] ?? '') : ''));
4624 }
4625 if (empty($line['fk_entrepot']) && !getDolGlobalString('STOCK_WAREHOUSE_NOT_REQUIRED_FOR_RECEPTIONS')) {
4626 return $langs->transnoentitiesnoconv('AIWriteNoWarehouse');
4627 }
4628 }
4629 }
4630
4631 return '';
4632 }
4633
4634 if (empty($write['parent'])) {
4635 return '';
4636 }
4637
4638 $parent = $this->fetchWriteParent($write, $args);
4639 // A document the user may not see is answered like a missing one: no ref,
4640 // no status, no sentence naming it.
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.";
4643 }
4644 // Core only adds lines to a draft, and otherwise fails with no message.
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.";
4647 }
4648 if (!empty($this->unresolvedProducts)) {
4649 return $this->unresolvedProductsMessage();
4650 }
4651
4652 return '';
4653 }
4654
4664 private function closeProductRefs($wanted, $socid)
4665 {
4666 $wanted = trim((string) $wanted);
4667 if (dol_strlen($wanted) < 3) {
4668 return array();
4669 }
4670 // "5553-987" on the note, "5553-12" and "5553-14" in the catalogue (a size
4671 // the note omits): try the stem before the last separator too. Then the
4672 // stem before a trailing number ("SEAFXR20" -> the SEAFXR family), so a
4673 // missing size still shows its siblings.
4674 $stems = array($wanted);
4675 if (preg_match('/^(.{3,})[-\/ .][^-\/ .]+$/', $wanted, $reg)) {
4676 $stems[] = $reg[1];
4677 }
4678 if (preg_match('/^(.{3,}?)\d+$/', $wanted, $reg)) {
4679 $stems[] = $reg[1];
4680 }
4681 $found = array();
4682 foreach ($stems as $stem) {
4683 if ($socid > 0) {
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).')';
4691 }
4692 }
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).')';
4699 }
4700 }
4701 if (!empty($found)) {
4702 break;
4703 }
4704 }
4705
4706 return array_slice(array_values($found), 0, 5);
4707 }
4708
4715 private function unresolvedProductsMessage()
4716 {
4717 $parts = array();
4718 foreach ($this->unresolvedProducts as $wanted => $close) {
4719 $parts[] = "'".((string) $wanted)."'".(empty($close) ? '' : ' (close refs: '.implode(', ', $close).')');
4720 }
4721
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.";
4723 }
4724
4735 private function fetchRecord($class, $id, $ref = '')
4736 {
4737 $paths = array(
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'
4756 );
4757 $ref = trim((string) $ref);
4758 if (empty($paths[$class]) || ((int) $id <= 0 && $ref === '')) {
4759 return null;
4760 }
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);
4766 } elseif ($obj instanceof Contact || $obj instanceof Societe) {
4767 $found = false; // no ref: found by name elsewhere, or by rowid
4768 } else {
4769 $found = ($obj->fetch(0, $ref) > 0);
4770 }
4771
4772 return ($found && (int) $obj->id > 0) ? $obj : null;
4773 }
4774
4782 private function resolveWriteTarget(array $write, $value)
4783 {
4784 global $langs, $user;
4785
4786 $class = (string) ($write['object'] ?? '');
4787 $label = (string) ($write['label'] ?? $class);
4788 if (is_numeric($value) && (int) $value > 0) {
4789 return $this->fetchRecord($class, (int) $value);
4790 }
4791 $value = trim((string) $value);
4792 if ($value === '') {
4793 return null;
4794 }
4795
4796 $lookup = (string) ($write['lookup'] ?? '');
4797 if ($lookup === 'thirdparty') {
4798 // The same matching as the documents: trade name, words in any order.
4799 require_once DOL_DOCUMENT_ROOT.'/ai/lib/ai.lib.php';
4800 $names = array();
4801 $ids = array();
4802 foreach (aiFindThirdpartiesInText($this->db, $user, $value) as $mt) {
4803 foreach ($mt['candidates'] as $cid => $c) {
4804 if ($c['visible'] && !isset($ids[$cid])) {
4805 $ids[$cid] = true;
4806 $names[] = $c['name'].' (id '.$cid.')';
4807 }
4808 }
4809 }
4810 if (count($ids) === 1) {
4811 return $this->fetchRecord($class, (int) key($ids));
4812 }
4813 if (count($ids) > 1) {
4814 $this->writeProblems[] = $langs->transnoentitiesnoconv('AIWriteSeveralThirdparties', $value, implode(', ', $names));
4815 }
4816
4817 return null;
4818 }
4819 if ($lookup === 'ref') {
4820 return $this->fetchRecord($class, 0, $value);
4821 }
4822
4823 return null;
4824 }
4825
4834 private function userCanReach($class, $id)
4835 {
4836 // Feature, table&shared element, second level feature: as each REST class passes them.
4837 $map = array(
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', '', '')
4854 );
4855 if (!isset($map[$class])) {
4856 return true;
4857 }
4858 require_once DOL_DOCUMENT_ROOT.'/core/lib/security.lib.php';
4859 $m = $map[$class];
4860
4861 return (bool) checkUserAccessToObject($this->user, array($m[0]), (int) $id, $m[1], ($m[2] !== '' ? array($m[2]) : ''), 'fk_soc', 'rowid');
4862 }
4863
4870 private function socidOf($obj)
4871 {
4872 $vars = is_object($obj) ? get_object_vars($obj) : array();
4873
4874 return (int) ($vars['socid'] ?? 0);
4875 }
4876
4883 private function describeRecord($obj)
4884 {
4885 global $conf, $langs;
4886
4887 if ($obj instanceof Societe) {
4888 return (string) $obj->name;
4889 }
4890 if ($obj instanceof Product) {
4891 return $obj->ref.' - '.$obj->label;
4892 }
4893 if ($obj instanceof Contact) {
4894 return $obj->getFullName($langs);
4895 }
4896 $parts = array((string) $obj->ref);
4897 // A task or a ticket is known by its label or subject more than its ref.
4898 if ($obj instanceof Task && (string) $obj->label !== '') {
4899 $parts[] = (string) $obj->label;
4900 }
4901 if ($obj instanceof Ticket && (string) $obj->subject !== '') {
4902 $parts[] = (string) $obj->subject;
4903 }
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;
4909 }
4910 }
4911 if (!empty($obj->total_ttc)) {
4912 $parts[] = price((float) $obj->total_ttc, 0, $langs, 1, -1, -1, $conf->currency);
4913 }
4914
4915 return implode(' - ', $parts);
4916 }
4917
4924 private function resolveWarehouse($value)
4925 {
4926 global $langs;
4927
4928 $list = array();
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);
4935 }
4936 $names = array();
4937 foreach ($list as $id => $w) {
4938 $names[] = $w[0].' (id '.$id.')';
4939 }
4940
4941 return $this->pickOne($list, $value, $names, 'AIWriteWhichWarehouse', 'AIWriteWarehouseNotFound', 'AIWriteNoOpenWarehouse');
4942 }
4943
4950 private function resolveBankAccount($value)
4951 {
4952 $list = array();
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);
4959 }
4960 $names = array();
4961 foreach ($list as $id => $b) {
4962 $names[] = $b[0].' (id '.$id.')';
4963 }
4964
4965 return $this->pickOne($list, $value, $names, 'AIWriteWhichBankAccount', 'AIWriteBankAccountNotFound', 'AIWriteNoBankAccount');
4966 }
4967
4975 private function resolvePaymentMode($value)
4976 {
4977 global $langs;
4978
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');
4981 $list = array();
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));
4988 }
4989 $names = array();
4990 foreach ($list as $p) {
4991 $names[] = $p[2].' ('.$p[0].')';
4992 }
4993 $want = dol_strtolower(trim((string) $value));
4994 if (isset($synonyms[$want])) {
4995 $value = $synonyms[$want];
4996 }
4997
4998 return $this->pickOne($list, $value, $names, 'AIWriteWhichPaymentMode', 'AIWritePaymentModeNotFound', '', false);
4999 }
5000
5014 private function pickOne(array $list, $value, array $names, $askKey, $missingKey, $noneKey, $onlyOne = true)
5015 {
5016 global $langs;
5017
5018 $langs->load('other');
5019 if (empty($list)) {
5020 if ($noneKey !== '') {
5021 $this->writeProblems[] = $langs->transnoentitiesnoconv($noneKey);
5022 }
5023 return 0;
5024 }
5025 $value = trim((string) $value);
5026 if ($value === '') {
5027 if ($onlyOne && count($list) === 1) {
5028 return (int) key($list);
5029 }
5030 $this->writeProblems[] = $langs->transnoentitiesnoconv($askKey, implode(', ', $names));
5031 return 0;
5032 }
5033 if (is_numeric($value) && isset($list[(int) $value])) {
5034 return (int) $value;
5035 }
5036 $want = dol_strtolower($value);
5037 $contains = array();
5038 foreach ($list as $id => $known) {
5039 foreach ($known as $knownname) {
5040 $haystack = dol_strtolower((string) $knownname);
5041 if ($haystack === '') {
5042 continue;
5043 }
5044 if ($haystack === $want) {
5045 return (int) $id;
5046 }
5047 if (strpos($haystack, $want) !== false) {
5048 $contains[$id] = true;
5049 }
5050 }
5051 }
5052 if (count($contains) === 1) {
5053 return (int) key($contains);
5054 }
5055 $this->writeProblems[] = $langs->transnoentitiesnoconv($missingKey, $value, implode(', ', $names));
5056
5057 return 0;
5058 }
5059
5072 private function normaliseOneRecordArgs(array $args, array $write)
5073 {
5074 global $langs;
5075
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 !== '') {
5084 $obj = $canCheck ? $this->resolveWriteTarget($write, $given) : null;
5085 if ($canCheck && (!$obj || !$this->userCanReach($class, (int) $obj->id))) {
5086 $this->writeProblems[] = $langs->transnoentitiesnoconv('AIWriteRecordNotFound', $label, (string) $given);
5087 } elseif ($obj) {
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;
5091 }
5092 }
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']]);
5099 }
5100 }
5101 } elseif (!empty($write['target_or'])) {
5102 $this->writeProblems[] = $langs->transnoentitiesnoconv('AIWriteMissingField', $field);
5103 }
5104
5105 foreach ((array) ($write['refuse_values'] ?? array()) as $name => $rule) {
5106 if (!array_key_exists($name, $args) || (string) $args[$name] === '') {
5107 continue;
5108 }
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']);
5111 }
5112 }
5113
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);
5118 if ($cid > 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);
5123 }
5124 } else {
5125 $contact = $this->fetchRecord('Contact', $cid);
5126 if (!$contact || !$this->userCanReach('Contact', $cid)) {
5127 $this->writeProblems[] = $langs->transnoentitiesnoconv('AIWriteRecordNotFound', 'contact', (string) $cid);
5128 }
5129 }
5130 }
5131 // The role by its code, as the dictionary of contact types has it.
5132 $type = strtoupper(trim((string) ($args['type'] ?? '')));
5133 if ($type !== '') {
5134 $codes = array();
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;
5140 }
5141 if (!in_array($type, $codes, true)) {
5142 $this->writeProblems[] = $langs->transnoentitiesnoconv('AIWriteUnknownRole', (string) $args['type'], implode(', ', $codes));
5143 }
5144 $args['type'] = $type;
5145 }
5146 }
5147
5148 return $args;
5149 }
5150
5160 private function normaliseTargetArgs(array $args, array $write)
5161 {
5162 global $langs;
5163
5164 $kind = (string) $write['kind'];
5165 $field = (string) ($write['target'] ?? 'id');
5166 $given = $args[$field] ?? ($args['ref'] ?? '');
5167 $this->writeTarget = $this->resolveWriteTarget($write, $given);
5168 $out = array($field => ($this->writeTarget ? (int) $this->writeTarget->id : $given));
5169
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) === '_') {
5175 continue;
5176 }
5177 if (isset($aliases[$name]) && in_array($aliases[$name], $write['fields'], true) && !isset($args[$aliases[$name]])) {
5178 $name = $aliases[$name];
5179 }
5180 if (in_array($name, $write['fields'], true) && !is_array($value)) {
5181 $out[$name] = $value;
5182 } else {
5183 $this->writeRefusedFields[] = (string) $name;
5184 }
5185 }
5186
5187 return $out;
5188 }
5189
5190 if ($kind === 'action') {
5191 // An action taking more than its record (who to assign it to, cancel).
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];
5195 }
5196 }
5197 if (!empty($write['stock']) && $this->writeTarget && $this->validationMovesStock($write, $this->writeTarget)) {
5198 $out['idwarehouse'] = $this->resolveWarehouse($args['warehouse'] ?? ($args['idwarehouse'] ?? ''));
5199 }
5200
5201 return $out;
5202 }
5203
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'] ?? ''));
5209 $account = isModEnabled('bank') ? $this->resolveBankAccount($args['bank_account'] ?? ($args['accountid'] ?? '')) : 0;
5210 $date = trim((string) ($args['date'] ?? ($args['datepaye'] ?? '')));
5211 $out['arrayofamounts'] = array((string) $out[$field] => array('amount' => (string) $amount, 'multicurrency_amount' => ''));
5212 $out['datepaye'] = ($date !== '' && dol_stringtotime($date) > 0) ? $date : dol_print_date(dol_now(), 'dayrfc');
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');
5224 }
5225
5226 return $out;
5227 }
5228
5229 if ($kind === 'line') {
5230 return $this->normaliseLineArgs($args, $write, $out);
5231 }
5232
5233 return $out; // delete: the record alone
5234 }
5235
5245 private function normaliseLineArgs(array $args, array $write, array $out)
5246 {
5247 global $langs;
5248
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');
5253 $changes = array();
5254 foreach ($args as $name => $value) {
5255 if (in_array($name, array('id', 'ref', 'requestState'), true) || substr((string) $name, 0, 1) === '_') {
5256 continue;
5257 }
5258 $name = (isset($aliases[$name]) && !isset($args[$aliases[$name]])) ? $aliases[$name] : $name;
5259 if (in_array($name, array('line', 'lineid'), true) && $action !== 'add') {
5260 continue;
5261 }
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;
5266 }
5267 }
5268
5269 $langs->load('other');
5270 $line = null;
5271 $position = 0;
5272 if ($action !== 'add' && $doc && (int) $doc->status === 0) {
5273 $wanted = $args['lineid'] ?? ($args['line_id'] ?? ($args['rowid'] ?? ''));
5274 $byid = ((string) $wanted !== '');
5275 if (!$byid) {
5276 $wanted = $args['line'] ?? ($args['position'] ?? ($args['product_ref'] ?? ($args['product'] ?? '')));
5277 }
5278 $w = dol_strtolower(trim((string) $wanted));
5279 $found = array();
5280 $exact = array();
5281 foreach (array_values((array) $doc->lines) as $i => $l) {
5282 if ($byid || is_numeric($wanted)) {
5283 // By rowid, or by its position on the document (1 = first).
5284 if ($byid ? ((int) $l->id === (int) $wanted) : ((int) $wanted === $i + 1)) {
5285 $found[$i + 1] = $l;
5286 }
5287 continue;
5288 }
5289 // By product: its ref exactly, else words of its label or text.
5290 $ref = dol_strtolower((string) ($l->product_ref ?? ($l->ref ?? '')));
5291 $words = dol_strtolower($this->lineName($l).' '.dol_string_nohtmltag((string) ($l->desc ?? ($l->description ?? ''))));
5292 if ($w !== '' && $ref === $w) {
5293 $exact[$i + 1] = $l;
5294 } elseif ($w !== '' && strpos($words, $w) !== false) {
5295 $found[$i + 1] = $l;
5296 }
5297 }
5298 if ($exact) {
5299 $found = $exact;
5300 }
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);
5306 } else {
5307 $this->writeProblems[] = $langs->transnoentitiesnoconv(count($found) ? 'AIWriteLineSeveral' : 'AIWriteLineNotFound', (string) $wanted, $this->linesSummary($doc));
5308 }
5309 }
5310
5311 // Values as the line stores them: hours in seconds, dates as timestamps, a unit by its rowid.
5312 if (isset($changes['unit'])) {
5313 $unit = $this->unitIdFromName((string) $changes['unit']);
5314 if ($unit <= 0) {
5315 $this->writeProblems[] = $langs->transnoentitiesnoconv('AIWriteUnknownUnit', (string) $changes['unit']);
5316 }
5317 $changes['unit'] = $unit;
5318 }
5319 foreach (array('qty', 'subprice', 'remise_percent', 'tva_tx') as $num) {
5320 if (isset($changes[$num])) {
5321 $changes[$num] = (float) price2num($changes[$num]);
5322 }
5323 }
5324 if (isset($changes['duration'])) {
5325 $changes['duration'] = (int) round((float) price2num($changes['duration']) * 3600);
5326 }
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']);
5331 }
5332 }
5333 $this->writeLine = array('line' => $line, 'position' => $position, 'changes' => $changes);
5334
5335 if ($action === 'delete') {
5336 $out['lineid'] = $line ? (int) $line->id : 0;
5337 return $out;
5338 }
5339 if ($profile === 'intervention') {
5340 $body = array();
5341 foreach (array('desc' => 'description', 'date' => 'date', 'duration' => 'duration') as $from => $to) {
5342 if (array_key_exists($from, $changes)) {
5343 $body[$to] = $changes[$from];
5344 }
5345 }
5346 if ($action === 'add') {
5347 $body += array('date' => dol_now(), 'duration' => 0);
5348 } else {
5349 $out['lineid'] = $line ? (int) $line->id : 0;
5350 }
5351 $out['_body'] = $body;
5352 return $out;
5353 }
5354
5355 // Every value the REST updateline() reads, from the line itself, so only what
5356 // the user changed is changed (most REST putLine() pass absent fields as null).
5357 $out['lineid'] = $line ? (int) $line->id : 0;
5358 $body = array();
5359 if ($line) {
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;
5363 }
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;
5370 }
5371 $body['array_options'] = is_array($line->array_options ?? null) ? $line->array_options : array();
5372 // A VAT code stays with its rate, else updateline() drops it.
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.')';
5375 }
5376 }
5377 foreach (array('qty', 'subprice', 'remise_percent', 'tva_tx', 'desc') as $field) {
5378 if (array_key_exists($field, $changes)) {
5379 $body[$field] = $changes[$field];
5380 }
5381 }
5382 if (array_key_exists('unit', $changes)) {
5383 $body['fk_unit'] = $changes['unit'];
5384 }
5385 $body['price_base_type'] = 'HT';
5386 $body['multicurrency_subprice'] = 0; // recomputed from the unit price
5387 if ($profile === 'supplier') {
5388 $body['pu_ht'] = $body['subprice'] ?? null;
5389 $body['description'] = $body['desc'] ?? null;
5390 unset($body['subprice'], $body['desc']);
5391 }
5392 $out['_body'] = $body;
5393
5394 return $out;
5395 }
5396
5403 private function linesSummary($doc)
5404 {
5405 $list = array();
5406 foreach (array_values((array) $doc->lines) as $i => $l) {
5407 if ($i >= 15) {
5408 $list[] = '...';
5409 break;
5410 }
5411 $list[] = ($i + 1).': '.dol_trunc($this->lineName($l), 40).(isset($l->qty) ? ' x '.((float) $l->qty) : '');
5412 }
5413
5414 return $list ? implode('; ', $list) : '-';
5415 }
5416
5423 private function lineName($l)
5424 {
5425 $ref = (string) ($l->product_ref ?? ($l->ref ?? ''));
5426 $label = (string) ($l->product_label ?? '');
5427 $text = trim(dol_string_nohtmltag((string) ($l->desc ?? ($l->description ?? ''))));
5428
5429 return $ref !== '' ? $ref.($label !== '' ? ' - '.$label : '') : $text;
5430 }
5431
5439 private function validationMovesStock(array $write, $obj)
5440 {
5441 if (!isModEnabled('stock') || !getDolGlobalString((string) $write['stock'])) {
5442 return false;
5443 }
5444 foreach ((array) $obj->lines as $line) {
5445 if (!empty($line->fk_product) && (int) $line->product_type === 0) {
5446 return true;
5447 }
5448 }
5449
5450 return false;
5451 }
5452
5460 private function normaliseCreateExtras(array $args, array $write)
5461 {
5462 global $langs;
5463
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)) {
5471 // A project is often named by its title.
5472 $sql = "SELECT rowid FROM ".$this->db->prefix()."projet";
5473 $sql .= " WHERE entity IN (".getEntity('project').") AND title = '".$this->db->escape((string) $given)."'";
5474 $sql .= " LIMIT 2";
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);
5479 }
5480 }
5481 if ($project instanceof Project && $this->userCanReach('Project', (int) $project->id)) {
5482 $args[$field] = (int) $project->id;
5483 $args['_project'] = $project->ref.' - '.$project->title;
5484 } else {
5485 $langs->load('other');
5486 $this->writeProblems[] = $langs->transnoentitiesnoconv('AIWriteProjectNotFound', (string) $given);
5487 }
5488 }
5489 }
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]);
5495 }
5496 }
5497 }
5498 // Dates the REST method reads as text itself: checked here, 'today' as a date.
5499 foreach ((array) ($write['text_dates'] ?? array()) as $field) {
5500 if (!isset($args[$field]) || is_numeric($args[$field])) {
5501 continue;
5502 }
5503 if (in_array(dol_strtolower(trim((string) $args[$field])), array('today', 'now'), true)) {
5504 $args[$field] = dol_print_date(dol_now(), 'dayrfc', 'tzuserrel');
5505 } elseif ($this->writeDate($field, $args[$field]) === null) {
5506 unset($args[$field]);
5507 }
5508 }
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);
5512 }
5513 }
5514
5515 return $args;
5516 }
5517
5525 private function previewTargetWrite(array $write, array $args)
5526 {
5527 global $langs;
5528
5529 $obj = $this->writeTarget;
5530 $what = $obj ? $this->describeRecord($obj) : (string) ($args[$write['target'] ?? 'id'] ?? '');
5531 $kind = (string) $write['kind'];
5532
5533 if ($kind === 'update') {
5534 $changes = array();
5535 foreach ((array) $write['fields'] as $name) {
5536 if (!array_key_exists($name, $args)) {
5537 continue;
5538 }
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).'"';
5541 }
5542
5543 return $langs->trans($write['preview'], $write['label'], $what, implode(', ', $changes));
5544 }
5545 if ($kind === 'delete') {
5546 return $langs->trans($write['preview'], $write['label'], $what);
5547 }
5548 if ($kind === 'line') {
5549 return $this->previewLineWrite($write, $what);
5550 }
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) : '';
5554 $account = '';
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;
5560 }
5561 }
5562
5563 $how = $langs->transnoentitiesnoconv('AIPreviewPaymentHow', ($code !== '' ? $langs->transnoentitiesnoconv('PaymentType'.$code) : ''), $account, dol_print_date(dol_stringtotime((string) $args['datepaye']), 'day'));
5564
5565 return $langs->trans($write['preview'], price((float) ($args['_amount'] ?? 0)), $what, $how);
5566 }
5567
5568 // Other actions: who the record goes to, or the other way to end it.
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);
5572 }
5573 $assignee = new User($this->db);
5574 $name = ($assignee->fetch((int) $args['fk_user_assign']) > 0) ? $assignee->getFullName($langs) : (string) $args['fk_user_assign'];
5575
5576 return $langs->trans($write['preview'], $what, $name);
5577 }
5578 if (!empty($args['cancel']) && !empty($write['preview_cancel'])) {
5579 return $langs->trans($write['preview_cancel'], $what);
5580 }
5581
5582 // Validation: the warehouse is said when the stock moves.
5583 if (!empty($args['idwarehouse'])) {
5584 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
5585 $wh = new Entrepot($this->db);
5586 if ($wh->fetch((int) $args['idwarehouse']) > 0) {
5587 $what .= ', '.$langs->trans('AIPreviewStockFrom', (string) $wh->ref);
5588 }
5589 }
5590
5591 return $langs->trans($write['preview'], $what);
5592 }
5593
5602 private function previewLineWrite(array $write, $what)
5603 {
5604 global $langs;
5605
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');
5613 $text = array();
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 ?? '')) : '';
5618 }
5619 if ($name === 'unit') {
5620 $old = $this->unitLabel((int) $old);
5621 $new = $this->unitLabel((int) $new);
5622 } elseif ($name === 'subprice') {
5623 $old = ($old === null) ? '' : price((float) $old);
5624 $new = price((float) $new);
5625 } elseif ($name === 'duration') {
5626 $old = ($old === null) ? '' : convertSecondToTime((int) $old, 'allhourmin');
5627 $new = convertSecondToTime((int) $new, 'allhourmin');
5628 } elseif ($name === 'date') {
5629 $old = empty($old) ? '' : dol_print_date((int) $old, 'day');
5630 $new = dol_print_date((int) $new, 'day');
5631 } elseif (in_array($name, array('qty', 'remise_percent', 'tva_tx'), true)) {
5632 $old = ($old === null) ? '' : (string) ((float) $old);
5633 $new = (string) ((float) $new);
5634 } else {
5635 $old = dol_trunc(dol_string_nohtmltag((string) $old), 40);
5636 $new = dol_trunc(dol_string_nohtmltag((string) $new), 40);
5637 }
5638 $text[] = $langs->transnoentitiesnoconv($labels[$name]).' '.($write['line_action'] === 'add' ? '' : $old.' → ').$new;
5639 }
5640
5641 if ($write['line_action'] === 'add') {
5642 return $langs->trans($write['preview'], $what, implode(', ', $text));
5643 }
5644 $name = $line ? dol_trunc($this->lineName($line), 60) : '';
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);
5648 }
5649 // The new total of the line, as core will compute it before taxes.
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'));
5655 }
5656
5657 return $langs->trans($write['preview'], $position, $what, $name, implode(', ', $text));
5658 }
5659
5666 private function unitLabel($id)
5667 {
5668 global $langs;
5669
5670 if ($id <= 0 || empty($this->db)) {
5671 return '-';
5672 }
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;
5675
5676 return $obj ? $langs->transnoentitiesnoconv((string) $obj->label) : (string) $id;
5677 }
5678
5686 private function precheckTargetWrite(array $write, array $args)
5687 {
5688 global $langs;
5689
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];
5696 }
5697 if (!$obj || !$this->userCanReach((string) $write['object'], (int) $obj->id)) {
5698 return $langs->transnoentitiesnoconv('AIWriteRecordNotFound', $label, $given);
5699 }
5700 $kind = (string) $write['kind'];
5701
5702 if ($kind === 'update') {
5703 if (!empty($this->writeRefusedFields)) {
5704 return $langs->transnoentitiesnoconv('AIWriteFieldsNotAllowed', implode(', ', $this->writeRefusedFields), implode(', ', (array) $write['fields']));
5705 }
5706 if (count($args) < 2) {
5707 return $langs->transnoentitiesnoconv('AIWriteNothingToChange');
5708 }
5709
5710 return '';
5711 }
5712 if ($kind === 'action' && isset($write['states'])) {
5713 // An action other than a validation: allowed in the statuses it lists.
5714 if (!in_array((int) $obj->status, (array) $write['states'], true)) {
5715 return $langs->transnoentitiesnoconv((string) $write['state_error'], $label, (string) $obj->ref);
5716 }
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']);
5721 }
5722 }
5723
5724 return '';
5725 }
5726 if ($kind === 'line') {
5727 if ((int) $obj->status !== 0) {
5728 return $langs->transnoentitiesnoconv('AIWriteNotDraftLines', $label, (string) $obj->ref);
5729 }
5730 if (!empty($this->writeRefusedFields)) {
5731 return $langs->transnoentitiesnoconv('AIWriteFieldsNotAllowed', implode(', ', $this->writeRefusedFields), implode(', ', (array) $write['fields']));
5732 }
5733 $changes = $this->writeLine['changes'];
5734 if ($write['line_action'] === 'update' && !$changes) {
5735 return $langs->transnoentitiesnoconv('AIWriteNothingToChange');
5736 }
5737 if ($write['line_action'] === 'add' && trim((string) ($changes['desc'] ?? '')) === '') {
5738 return $langs->transnoentitiesnoconv('AIWriteMissingField', 'desc');
5739 }
5740 if (array_key_exists('qty', $changes) && (float) $changes['qty'] <= 0) {
5741 return $langs->transnoentitiesnoconv('AIWriteLineQtyZero');
5742 }
5743
5744 return '';
5745 }
5746 if ($kind === 'action' || $kind === 'delete') {
5747 if ((int) $obj->status !== 0) {
5748 return $langs->transnoentitiesnoconv($kind === 'action' ? 'AIWriteNotDraftValidate' : 'AIWriteNotDraftDelete', $label, (string) $obj->ref);
5749 }
5750 if ($kind === 'action' && count((array) $obj->lines) === 0) {
5751 return $langs->transnoentitiesnoconv('AIWriteValidateNoLines', $label, (string) $obj->ref);
5752 }
5753
5754 return '';
5755 }
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);
5760 }
5761 $amount = (float) ($args['_amount'] ?? 0);
5762 if ($amount <= 0) {
5763 return $langs->transnoentitiesnoconv('AIWritePaymentAmountInvalid');
5764 }
5765 if ($amount > $remain) {
5766 return $langs->transnoentitiesnoconv('AIWritePaymentTooHigh', price($amount), (string) $obj->ref, price($remain));
5767 }
5768 }
5769
5770 return '';
5771 }
5772
5779 private function writeMetaFor($toolName)
5780 {
5781 $meta = $this->methodMetaFor($toolName);
5782
5783 return isset($meta['write']) ? $meta['write'] : array();
5784 }
5785
5792 private function methodMetaFor($toolName)
5793 {
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) {
5798 return $mmeta;
5799 }
5800 }
5801 }
5802
5803 return array();
5804 }
5805
5818 private function resolveUserSentinels(array $args)
5819 {
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);
5825 }
5826 }
5827
5828 return $args;
5829 }
5830
5836 public function getCategories(): array
5837 {
5838 // Union of the classifier categories of the whitelisted endpoints —
5839 // derived so it cannot drift, expressed in the classifier vocabulary
5840 // so query filtering keeps working (see ENDPOINT_CATEGORIES).
5841 $all = array();
5842 foreach (array_keys($this->enrichments) as $key) {
5843 $all = array_merge($all, self::ENDPOINT_CATEGORIES[$key] ?? array());
5844 }
5845
5846 return array_values(array_unique($all));
5847 }
5854 private function extrafieldsElementForEndpoint($key)
5855 {
5856 $map = array(
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',
5882 'mos' => 'mrp_mo',
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'
5891 );
5892
5893 return $map[$key] ?? '';
5894 }
5895
5903 private function projectDocumentList($output, $modulepart)
5904 {
5905 // document.php does not know every alias the API accepts
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)) {
5911 return $output;
5912 }
5913 $list = array();
5914 foreach ($files as $file) {
5915 $level1 = (string) ($file['level1name'] ?? '');
5916 $list[] = array(
5917 'name' => (string) ($file['name'] ?? ''),
5918 'size' => dol_print_size((int) ($file['size'] ?? 0), 1),
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'] ?? ''))
5921 );
5922 }
5923 if ($paginated) {
5924 $output['data'] = $list;
5925 return $output;
5926 }
5927 return $list;
5928 }
5929
5938 private function projectDirectoryList($output, $modulepart)
5939 {
5940 $paginated = is_array($output) && isset($output['data']) && is_array($output['data']);
5941 $entries = $paginated ? $output['data'] : $output;
5942 if (!is_array($entries)) {
5943 return $output;
5944 }
5945 $list = array();
5946 foreach ($entries as $entry) {
5947 $isdir = (($entry['type'] ?? '') === 'dir');
5948 $item = array(
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')
5953 );
5954 if (!$isdir) {
5955 $item['size'] = dol_print_size((int) ($entry['size'] ?? 0), 1);
5956 $item['url'] = DOL_URL_ROOT.'/document.php?modulepart='.urlencode($modulepart).'&file='.urlencode($item['path']);
5957 }
5958 $list[] = $item;
5959 }
5960 if ($paginated) {
5961 $output['data'] = $list;
5962 return $output;
5963 }
5964 return $list;
5965 }
5966
5973 private function documentObjectExists(array $args)
5974 {
5975 $object = fetchObjectByElement((int) ($args['id'] ?? 0), (string) ($args['modulepart'] ?? ''), (string) ($args['ref'] ?? ''));
5976 return is_object($object) && $object->id > 0;
5977 }
5978
5987 private function shapeReadOutput(array $output, array $meta)
5988 {
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));
5992
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);
5998 }
5999 }
6000 }
6001 if (!$isList) {
6002 return $records[0];
6003 }
6004
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);
6009
6010 return array(
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.'
6014 );
6015 }
6016 if ($paginated) {
6017 $output['data'] = $records;
6018
6019 return $output;
6020 }
6021
6022 return $records;
6023 }
6024
6035 private function addCreatorContact($class, $id, $code)
6036 {
6037 $obj = $this->fetchRecord($class, $id);
6038 if (!$obj || !$this->user instanceof User) {
6039 return;
6040 }
6041 $result = $obj->add_contact((int) $this->user->id, $code, 'internal');
6042 if ($result < 0) {
6043 dol_syslog(get_class($this).'::addCreatorContact '.$class.' '.$id.' '.$code.' result='.$result.' '.$obj->error, LOG_WARNING);
6044 }
6045 }
6046
6055 public function execute(string $name, array $args)
6056 {
6057 $args = $this->applyFixedParams($name, $args);
6058
6059 // A model may send the record as a request_data body, or name line fields
6060 // the way the custom tools do: accept both, so the write receives what the
6061 // preview described.
6062 $writemeta = $this->writeMetaFor($name);
6063 if ($writemeta) {
6064 try {
6065 $args = $this->normaliseWriteArgs($args, $writemeta);
6066 } catch (InvalidArgumentException $e) {
6067 return ['error' => $e->getMessage()];
6068 }
6069 }
6070
6071 $args = $this->resolveUserSentinels($args);
6072
6073 $this->getDefinitions(); // ensure routes are built
6074 if (empty($this->routes[$name])) {
6075 return ["error" => "Tool function '$name' not found."];
6076 }
6077 list($key, $method) = $this->routes[$name];
6078 $epkey = (string) ($this->enrichments[$key]['endpoint'] ?? $key); // REST endpoint the tool group calls
6079 $ep = $this->endpoints[$epkey];
6080
6081 // A write on a record that exists: what the call always carries, whatever
6082 // the model sent (the triggers run and core gives the number), and the
6083 // ref of a record to delete, only known before.
6084 $writekind = '';
6085 $refbefore = '';
6086 if ($writemeta) {
6087 $writekind = (string) ($writemeta['kind'] ?? '');
6088 foreach ((array) ($writemeta['fixed'] ?? array()) as $field => $value) {
6089 $args[$field] = $value;
6090 }
6091 if ($writekind === 'delete' && $this->writeTarget) {
6092 $refbefore = (string) $this->writeTarget->ref;
6093 }
6094 }
6095
6096 // Server-side guarantee of compact list results: doc-strings recommend
6097 // 'properties', but a model that ignores them would otherwise pull full
6098 // ~130-column objects — unreadable in the chat table and in the PDF
6099 // report. When the whitelist entry declares default_properties and the
6100 // caller did not choose, the default applies; an explicit 'properties'
6101 // from the model always wins.
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'];
6105 }
6106
6107 // --- Authentication bridge (in-process replacement of DolibarrApiAccess::__isAllowed) ---
6108 // The API endpoint methods read the authenticated user from DolibarrApiAccess::$user
6109 // and their permission checks (hasRight) run against it. TODO: replicate entity
6110 // switching for multicompany setups.
6111 $this->loadApiRuntime();
6112 // Establish the caller's permission context, the same way the REST entry
6113 // point does in api_access.class.php ("Set also the global variable $user
6114 // to the $user of API"): the API layer authenticates via
6115 // DolibarrApiAccess::$user, and API/business code reads the global.
6116 // Unlike a REST request, this runs in-process mid-request, so both are
6117 // restored at the single exit point below — nothing after a tool call
6118 // (hooks, triggers, log attribution, another handler) may inherit the
6119 // tool's user.
6120 $saveduserapi = DolibarrApiAccess::$user;
6121 $saveduserglobal = empty($GLOBALS['user']) ? null : $GLOBALS['user'];
6122 DolibarrApiAccess::$user = $this->user;
6123 $GLOBALS['user'] = $this->user;
6124
6125 require_once $ep['path'];
6126 $api = new $ep['class']();
6127
6128 // Map named MCP args onto the method's positional signature.
6129 $rm = new ReflectionMethod($ep['class'], $method);
6130 $callArgs = [];
6131 $output = null;
6132 foreach ($rm->getParameters() as $p) {
6133 $pname = $p->getName();
6134 // A write method takes the record as one body parameter. The tool
6135 // advertises the fields flat, because that is what a model fills
6136 // in, so the body is rebuilt here from everything it sent.
6137 if ($pname === 'request_data') {
6138 // A line write: the body normaliseLineArgs() built, unchanged values included.
6139 if ($writekind === 'line') {
6140 $callArgs[] = (array) ($args['_body'] ?? array());
6141 continue;
6142 }
6143 if (!empty($writemeta['update'])) {
6144 $callArgs[] = array_intersect_key($args, $writemeta['update']);
6145 continue;
6146 }
6147 $body = $args;
6148 unset($body['requestState']);
6149 // Only the fields the tool advertised may be written: the human
6150 // approved a preview of those, not of arbitrary object properties
6151 // (a ticket update must not rewrite track_id, fk_user_create,
6152 // origin_email, dates...). 'parent' writes keep the flat line
6153 // fields, which are not individually declared in 'params'.
6154 if (!empty($writemeta) && empty($writemeta['parent']) && !empty($methodmeta['params'])) {
6155 $body = array_intersect_key($body, $methodmeta['params']);
6156 }
6157 // An update writes the allowed fields it was given, nothing else.
6158 if ($writekind === 'update') {
6159 $body = array_intersect_key($args, array_flip((array) $writemeta['fields']));
6160 }
6161 foreach (array_keys($body) as $field) {
6162 if (substr((string) $field, 0, 1) === '_') {
6163 unset($body[$field]);
6164 }
6165 }
6166 foreach (($writemeta['defaults'] ?? array()) as $field => $default) {
6167 if (!isset($body[$field])) {
6168 if ($default === 'now') {
6169 $default = dol_now();
6170 } elseif ($default === 'me') {
6171 $default = (int) $this->user->id;
6172 }
6173 $body[$field] = $default;
6174 }
6175 }
6176 // Fields named the common way up to here, renamed for an
6177 // endpoint that reads them under another name.
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]);
6182 }
6183 }
6184 // Fields the object persists under another name while the API
6185 // still validates the documented one (the ticket API checks
6186 // access on 'socid' but Ticket::create/update write 'fk_soc').
6187 foreach (($writemeta['copy'] ?? array()) as $from => $to) {
6188 if (isset($body[$from])) {
6189 $body[$to] = $body[$from];
6190 }
6191 }
6192 $callArgs[] = $body;
6193 continue;
6194 }
6195 // A write tool advertises a flat schema: only the declared arguments
6196 // may reach a positional parameter (a caller must not fill
6197 // 'notrigger' or any other option the schema never showed). A write
6198 // on an existing record is the exception: its arguments were rebuilt
6199 // from scratch by normaliseTargetArgs(), with the options fixed there.
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))) {
6204 // Cap an explicit 'limit': one call must not pull thousands of full objects.
6205 $callArgs[] = ($pname == 'limit') ? min((int) $args[$pname], self::BRIDGE_MAX_LIMIT) : $args[$pname];
6206 } elseif ($p->isOptional()) {
6207 // Bridge default for an omitted 'limit' is smaller than the API's 100.
6208 $callArgs[] = ($pname == 'limit') ? self::BRIDGE_DEFAULT_LIMIT : $p->getDefaultValue();
6209 } else {
6210 $output = ["error" => "Missing required parameter '$pname'."];
6211 break;
6212 }
6213 }
6214
6215 if ($output === null) {
6216 // Core can print an error page while refusing access (reproducible on
6217 // the REST route): keep it out of the JSON answer, in the log instead.
6218 ob_start();
6219 try {
6220 $result = call_user_func_array([$api, $method], $callArgs);
6221 // Serialize API return (cleaned objects) into plain arrays for the MCP client.
6222 $output = json_decode(json_encode($result), true);
6223 if (in_array($writekind, array('update', 'action', 'delete', 'payment', 'line'), true)) {
6224 // The record the user named, under its ref (a new one once
6225 // validated), rather than the whole object the API returns.
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;
6230 }
6231 $ref = ($writekind === 'delete') ? $refbefore : $this->refOfCreatedObject((string) $writemeta['object'], $targetid);
6232 // Some REST deletes answer success when core failed: check.
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);
6236 }
6237 if ($ref !== '') {
6238 $done['ref'] = $ref;
6239 }
6240 $output = $done;
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');
6244 }
6245 $output = ['success' => true, 'id' => (int) $output['id'], 'ref' => $output['ref']];
6246 } elseif ($epkey === 'documents' && !is_array($output)) {
6247 // The upload REST method answers with the file name it wrote, not a rowid.
6248 $output = array('success' => true, 'filename' => (string) $output);
6249 } elseif (!is_array($output)) {
6250 // A create returns the new rowid as a scalar: name it, so the
6251 // caller gets the same shape as any other tool result.
6252 $output = array('success' => true, 'id' => (int) $output);
6253 // A line write returns the rowid of the new line: the record it
6254 // went into is what the user knows.
6255 if (!empty($writemeta['parent'])) {
6256 $output = array('success' => true, 'line_id' => (int) $output['id'], 'id' => (int) ($args[$writemeta['parent']] ?? 0));
6257 }
6258 // Name what was written: an id alone tells the user nothing, and
6259 // the ref is what they see on the document itself.
6260 if (!empty($writemeta['object']) && $output['id'] > 0) {
6261 $ref = $this->refOfCreatedObject($writemeta['object'], $output['id']);
6262 if ($ref !== '') {
6263 $output['ref'] = $ref;
6264 }
6265 if (!empty($writemeta['creator_contact'])) {
6266 $this->addCreatorContact((string) $writemeta['object'], (int) $output['id'], (string) $writemeta['creator_contact']);
6267 }
6268 }
6269 }
6270 if ($epkey === 'documents' && $method === 'getDocumentsListByElement') {
6271 $output = $this->projectDocumentList($output, (string) ($args['modulepart'] ?? ''));
6272 }
6273 if ($epkey === 'documents' && $method === 'getDocumentsListByDirectory') {
6274 $output = $this->projectDirectoryList($output, (string) ($args['modulepart'] ?? ''));
6275 }
6276 } catch (Throwable $e) {
6277 $code = (int) $e->getCode();
6278 $message = $e->getMessage();
6279 if ($message === '') {
6280 // Core throws bare RestException(403) in places: give the model
6281 // something to reason on instead of an empty string.
6282 $message = 'Access denied or resource error (HTTP '.($code > 0 ? $code : 500).').';
6283 }
6284 if (strpos($message, 'Error when validating parameter sqlfilters') === 0) {
6285 // The API's own wording ("Bad syntax of the search string: ...")
6286 // shows the user a query they never wrote: say what went wrong
6287 // and what to do instead.
6288 global $langs;
6289 dol_syslog(get_class($this).'::execute '.$name.' '.$message, LOG_WARNING);
6290 $langs->load('other');
6291 $message = $langs->transnoentitiesnoconv('AIBadSearchFilter');
6292 }
6293 $output = [
6294 "error" => $message,
6295 "http_status" => ($code > 0 ? $code : 500)
6296 ];
6297 // The API answers 404 for an object with no files: that is an empty
6298 // list, unless the object itself does not exist. For a download,
6299 // 404 means the file itself is missing: keep the error.
6300 if ($epkey === 'documents' && $method === 'getDocumentsListByElement' && $code == 404 && $this->documentObjectExists($args)) {
6301 $output = [];
6302 }
6303 }
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);
6307 }
6308 }
6309
6310 // A record read that came back empty is no record.
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);
6313 }
6314
6315 // A list the REST method does not bound, and fields that stay on the server.
6316 if (is_array($output) && !isset($output['error']) && (!empty($methodmeta['max_items']) || !empty($methodmeta['drop_fields']))) {
6317 $output = $this->shapeReadOutput($output, $methodmeta);
6318 }
6319
6320 // Extrafields flagged as personal data (GDPR) must not reach an AI provider.
6321 $elementForExtrafields = $this->extrafieldsElementForEndpoint($epkey);
6322 if ($elementForExtrafields !== '' && empty($writemeta['compact_result'])) {
6323 require_once DOL_DOCUMENT_ROOT.'/ai/lib/ai.lib.php';
6324 $output = aiStripPersonalExtrafields($this->db, $output, $elementForExtrafields);
6325 }
6326
6327 // Restore the caller's context (single exit point).
6328 DolibarrApiAccess::$user = $saveduserapi;
6329 if ($saveduserglobal !== null) {
6330 $GLOBALS['user'] = $saveduserglobal;
6331 }
6332
6333 return $output;
6334 }
6335
6343 public function toolRoute(string $name)
6344 {
6345 $this->getDefinitions();
6346 if (empty($this->routes[$name])) {
6347 return null;
6348 }
6349 list($key, $method) = $this->routes[$name];
6350
6351 return array(
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))
6356 );
6357 }
6358}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
aiUnitIdFromName($db, $name)
Unit id from the word a user used for it: code, short label or label, in the user's language,...
Definition ai.lib.php:1816
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),...
Definition ai.lib.php:1490
aiStripPersonalExtrafields($db, $payload, $elementtype)
Remove extrafields flagged as personal data from an API-shaped payload.
Definition ai.lib.php:1317
$c
Definition line.php:353
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 contact/addresses.
Class to manage warehouses.
Class to manage standard extra fields.
Class to manage invoices.
Class to manage hooks.
Abstract base class for all MCP (Model Context Protocol) tools.
static normalizeInputSchema(array $schema)
Normalize a tool input schema to ensure broad compatibility with LLM function-calling APIs (e....
const NO_WRITE
Returned by writeConfirmationPreview() when the tool writes nothing.
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 tasks.
Class ToolApiBridge.
fetchBusinessObject($class, $id, $ref='')
Load a business record of one of the classes the writes declare.
writePrecheck(string $toolName, array $args)
Refuse, before any confirmation, a write that could only fail, so the user is never asked to approve ...
setupAllows(array $consts)
Whether one of these setup constants is on.
addReadEndpoints()
Read-only tools the whitelist did not reach yet: new endpoints (bank, donations, leave,...
resolvePaymentMode($value)
Active payment mode from the words of the user: its code, its label in the dictionary or in the user'...
canAccessWriteObject(array $access, $id)
Check object visibility with the same resource arguments as REST.
resolveWriteTarget(array $write, $value)
Record a targeted write is about, from the id or the words the model sent.
resolveBankAccount($value)
Open bank account from the words of the user, or the only one there is.
linesSummary($doc)
Lines of a document, as a numbered list for a message: position, product, quantity.
resolveEndpointClass(string $key)
Load an endpoint's api file and resolve its real class name (lazy, cached in $this->endpoints).
resetWriteState()
Forget what the previous normaliseWriteArgs() call found, so a problem of one call is never reported ...
extrafieldsElementForEndpoint($key)
Map a bridge endpoint key to the element type ExtraFields uses.
projectUpdateMethod()
Describe bounded edits of an existing project.
writeDate($field, $value, $gmt=1)
A date written as text, as a timestamp.
previewObjectName($class, $id)
A record linked by a header field, as the confirmation names it: its ref and label,...
resolveWarehouse($value)
Open warehouse from the words of the user, or the only one there is.
writeConfirmationPreview(string $toolName, array $args)
Preview of what a bridge write would do, for the confirmation gate.
socidOf($obj)
Third party of a record, 0 for a record that has none (product, third party).
buildToolDefinition(array $ep, string $key, string $method, string $toolname, array $meta=[])
Build one MCP tool definition from an API class method: reflection + docblock give the skeleton,...
getRequiredRights(string $toolName)
Rights are enforced by the REST API classes themselves.
execute(string $name, array $args)
Execute a bridged tool: authenticate the acting user, call the API method in-process with positional ...
unitLabel($id)
Label of a unit, as the user reads it.
defaultVatRate($socid, $fk_product, $buy=false)
VAT rate core would apply to a line, when the caller gave none.
refOfCreatedObject($class, $id)
Ref of a record just created, for the confirmation shown to the user.
updateMethod($label, $class, array $right, array $fields, $lookup)
Enrichment of the put method of a record: change some of its fields.
addWritesOnExistingRecords()
Writes on records that already exist, and the creates that need more than a third party and lines: ed...
precheckTargetWrite(array $write, array $args)
Why a write on an existing record cannot run, or '' when it can.
defsCacheFile()
Path of the definitions cache file for the CURRENT state, or '' when no writable temp directory exist...
documentObjectExists(array $args)
Whether the object a file list was asked for exists.
normaliseTargetArgs(array $args, array $write)
Arguments of a write on an existing record (update, validation, deletion, payment): the record found ...
canWriteProject($project)
Apply native project write authorization, not merely read-all visibility.
applyMethodRestriction(array $methods)
Apply the AI_MCP_API_BRIDGE_METHODS restriction.
previewValue(array $write, $argname, $value, array $args)
One value of a confirmation sentence, the way the user knows it: the record an id stands for,...
previewLogisticLines(array $lines, $kind)
The lines of a reception or shipment as the confirmation lists them: quantity, product,...
defaultMethods()
Methods exposed for an endpoint carrying no hand-written entry.
userCanReach($class, $id)
Whether the acting user may reach a record, with the same check the REST class makes before touching ...
shapeReadOutput(array $output, array $meta)
Shape a read result as its enrichment asks: drop the fields that must not leave the server,...
normaliseWriteArgs(array $args, array $write=array())
Normalise the arguments of a write before they are previewed or executed.
pickOne(array $list, $value, array $names, $askKey, $missingKey, $noneKey, $onlyOne=true)
One entry of a short list from what the user said: its rowid, one of its names said in full,...
normaliseOneRecordArgs(array $args, array $write)
Arguments of a write on one existing record that is not a targeted write (a ticket reply,...
closeProductRefs($wanted, $socid)
References close to one that matched no product, for the user to pick from: the supplier's references...
previewTargetWrite(array $write, array $args)
Confirmation sentence of a write on an existing record.
setupValue($name)
A setup constant read while the tools are declared.
restlerPatternToJsonSchema(string $value)
Convert a Restler {@pattern} value to a JSON Schema pattern.
getCategories()
Return categories this tool belongs to.
discoverEndpoints()
Discover the REST API endpoints of every enabled module.
unitIdFromName($name)
Unit id from the word a user used for it: code, short label or label, in the user's language,...
normaliseLineArgs(array $args, array $write, array $out)
Arguments of a line write on a draft: the line found from what the user said, and the full body the R...
const ENDPOINT_CATEGORIES
Endpoint key -> intent categories of the assistant's query classifier (classifyIntentUniversal() in p...
addCreatorContact($class, $id, $code)
Link the acting user to a record just created, with the role the card gives its creator (the leader o...
projectDirectoryList($output, $modulepart)
Keep what the chat shows of the content of a directory: type, name, path, size, date,...
purgeDefsCache()
Delete every bridge_tooldefs_*.json cache file of the ai temp directories (current entity and the oth...
lineName($l)
A line as the user knows it: product ref and label, else its text.
resolveUserSentinels(array $args)
Resolve 'me' sent as an argument value on user-referencing fields.
toolRoute(string $name)
Endpoint and method a bridge tool calls, for a page that shows the tool to a person (the palette of t...
writeMetaFor($toolName)
The 'write' enrichment of a tool, when it has one.
previewLineWrite(array $write, $what)
Confirmation sentence of a line write: the line by its position and product, each change from its old...
getDefinitions()
Returns tool definitions derived from the enabled REST API endpoints.
projectDocumentList($output, $modulepart)
Keep what the chat shows of a file list: name, size, date and a link.
normaliseCreateExtras(array $args, array $write)
Arguments of a create that names a project, or gives dates or hours.
defaultWarehouseId()
Warehouse a logistic line goes to when none is named: the user's default warehouse,...
writeDefsCache(string $cachefile)
Persist the generated definitions/routes/endpoints, pruning cache files of previous states so stale s...
addLineMethod($label, $lookupTool, $class, array $right, $buy=false, array $rename=array(), array $defaults=array())
Enrichment of the postLine method of a document (order, proposal, invoice, and their supplier counter...
describeRecord($obj)
Short description of a document for a confirmation: ref, third party, amount.
defaultBuyPrice($prod, $socid, $qty)
Unit purchase price of a product, for a supplier document line given by product ref: the sale price w...
validateProjectUpdate(array $args, $parent)
Check resulting dates, project write access and native update side effects.
loadApiRuntime()
Load the REST API runtime (Restler autoloader + DolibarrApi base classes), mirroring the bootstrap se...
loadExternalEnrichments()
Merge endpoint enrichments declared by external modules through the 'addMcpApiBridgeEnrichments' hook...
fetchWriteParent(array $write, array $args)
Record a line write goes into, for a write declaring a 'parent'.
validationMovesStock(array $write, $obj)
Whether validating this document moves stock, so a warehouse is needed.
tagValueToNumber(string $value)
Convert a numeric tag value to the PHP number JSON encodes as a number.
validateMethod($label, $class, $preview, array $right, array $fixed, $stockconst)
Enrichment of the validate method of a document.
lineMethod($action, $label, $class, array $right, $profile)
Enrichment of a line method of a draft document: change, delete or, for an intervention,...
methodMetaFor($toolName)
Find the enrichment of the method a tool name maps to.
docTypeToJson(string $type)
Convert a docblock type to a JSON Schema type.
unresolvedProductsMessage()
Message refusing a write whose products could not be resolved, with the close references found for ea...
applyFixedParams(string $toolName, array $args)
Arguments a tool forces on its call ('fixed_params' of its enrichment), whatever the caller sent: the...
liftInlineTags($desc, string $ptype, array &$constraints)
Lift Restler's inline validation tags out of a parameter description.
__construct($db, $user=null, $conf=null)
Constructor.
fetchRecord($class, $id, $ref='')
Record of a write on an existing record, by rowid or by ref: the business documents of fetchBusinessO...
toolGroups()
Groups of tools to build: enrichment key => key of the discovered endpoint whose REST class it calls.
deleteMethod($label, $class, array $right)
Enrichment of the delete method of a document, for its drafts only.
updateInputSchema(array $write)
Schema of a partial update declared by an endpoint's write metadata.
normaliseWriteLine(array $line, $socid, $buy=false, $kind='', $defaultWarehouse=0)
Normalise one document line: field names, product given by ref or label, default VAT rate.
normaliseUpdateArgs(array $args, array $write)
Normalise and validate partial updates without creation defaults.
const BRIDGE_DEFAULT_LIMIT
Default and ceiling applied to list 'limit' parameters when called through the bridge.
headerUpdateMethod($label, $class, array $right, array $readright, array $access, $extrafields, array $fields)
Enrichment of the put method of a document header: the listed fields of a draft, confirmed with their...
Class to manage Dolibarr users.
if(! $sortfield) if(! $sortorder) $module
Definition list.php:193
$context
@method int call_trigger(string $triggerName, ?User $user)
Definition command.php:209
global $mysoc
convertSecondToTime($iSecond, $format='all', $lengthOfDay=86400, $lengthOfWeek=7)
Return, in clear text, value of a number of seconds in days, hours and minutes.
Definition date.lib.php:263
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...
Definition date.lib.php:452
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)
Definition inc.php:431
Class to generate the form for creating a new ticket.
$conf db user
Active Directory does not allow anonymous connections.
Definition repair.php:166
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.