29if (!defined(
'NOTOKENRENEWAL')) {
30 define(
'NOTOKENRENEWAL', 1);
32if (!defined(
'NOREQUIREMENU')) {
33 define(
'NOREQUIREMENU', 1);
35if (!defined(
'NOREQUIREHTML')) {
36 define(
'NOREQUIREHTML', 1);
38if (!defined(
'NOREQUIREAJAX')) {
39 define(
'NOREQUIREAJAX', 1);
42if (!defined(
'NOCSRFCHECK')) {
43 define(
'NOCSRFCHECK', 1);
46require
'../../main.inc.php';
47require_once DOL_DOCUMENT_ROOT.
'/ai/class/mcp.class.php';
48require_once DOL_DOCUMENT_ROOT.
'/ai/lib/ai.lib.php';
61if (!$user->hasRight(
'ai',
'assistant',
'use')) {
67$langs->loadLangs(array(
'main',
'other',
'bills'));
71$documentCommands = array(
72 'invoice' => array(
'tool' =>
'api_invoices_create',
'label' =>
'AICmdInvoice',
'who' =>
'Customer'),
73 'order' => array(
'tool' =>
'api_orders_create',
'label' =>
'AICmdOrder',
'who' =>
'Customer'),
74 'proposal' => array(
'tool' =>
'api_proposals_create',
'label' =>
'AICmdProposal',
'who' =>
'Customer'),
75 'supplier-invoice' => array(
'tool' =>
'api_supplier_invoices_create',
'label' =>
'AICmdSupplierInvoice',
'who' =>
'Supplier',
'ref' =>
true),
76 'supplier-order' => array(
'tool' =>
'api_supplier_orders_create',
'label' =>
'AICmdSupplierOrder',
'who' =>
'Supplier'),
79$totalElements = array(
80 'facture' => array(
'table' =>
'facture',
'right' => array(
'facture',
'lire'),
'paid' => array(
'paiement_facture',
'fk_facture')),
81 'invoice_supplier' => array(
'table' =>
'facture_fourn',
'right' => array(
'fournisseur',
'facture',
'lire'),
'paid' => array(
'paiementfourn_facturefourn',
'fk_facturefourn')),
82 'commande' => array(
'table' =>
'commande',
'right' => array(
'commande',
'lire')),
83 'propal' => array(
'table' =>
'propal',
'right' => array(
'propal',
'lire')),
84 'order_supplier' => array(
'table' =>
'commande_fournisseur',
'right' => array(
'fournisseur',
'commande',
'lire')),
85 'supplier_proposal' => array(
'table' =>
'supplier_proposal',
'right' => array(
'supplier_proposal',
'lire')),
91$allowedTools = array_flip(array_column($mcp->getToolsSchemaForLLM(),
'name'));
94if (
GETPOST(
'action',
'aZ09') ===
'list') {
96 foreach ($documentCommands as $cmd => $def) {
97 if (!isset($allowedTools[$def[
'tool']])) {
102 'label' => $langs->transnoentitiesnoconv($def[
'label']),
103 'syntax' =>
'/'.$cmd.
' '.$langs->transnoentitiesnoconv(
'AICmdSyntaxDocument',
dol_strtolower($langs->transnoentitiesnoconv($def[
'who']))).(!empty($def[
'ref']) ?
' ref:...' :
'')
106 $list[] = array(
'name' =>
'total',
'label' => $langs->transnoentitiesnoconv(
'AICmdTotal'),
'syntax' =>
'/total');
107 print json_encode(array(
'commands' => $list));
113if (
GETPOST(
'action',
'aZ09') ===
'suggest') {
114 $kind =
GETPOST(
'kind',
'aZ09');
115 $q = trim(
GETPOST(
'q',
'restricthtml'));
116 $cmdName =
GETPOST(
'cmd',
'alphanohtml');
117 $side = (strpos($cmdName,
'supplier') === 0) ?
'buy' :
'sell';
120 if ($kind ===
'thirdparty' &&
dol_strlen($q) >= 2 && $user->hasRight(
'societe',
'lire')) {
122 $sql =
"SELECT s.rowid, s.nom, s.name_alias, s.town, s.client, s.fournisseur FROM ".$db->prefix().
"societe as s";
123 $sql .=
" WHERE s.entity IN (".getEntity(
'societe').
") AND s.status = 1";
124 foreach (array_slice(preg_split(
'/\s+/', $q, -1, PREG_SPLIT_NO_EMPTY) ?: array(), 0, 6) as $w) {
125 $like = $db->escape($db->escapeforlike($w));
126 $sql .=
" AND (s.nom LIKE '%".$like.
"%' OR s.name_alias LIKE '%".$like.
"%')";
130 if ($user->socid > 0) {
131 $sql .=
" AND s.rowid = ".((int) $user->socid);
132 } elseif (!$user->hasRight(
'societe',
'client',
'voir')) {
133 $sql .=
" AND s.rowid IN (SELECT sc.fk_soc FROM ".$db->prefix().
"societe_commerciaux as sc WHERE sc.fk_user = ".((int) $user->id).
")";
135 $sql .=
" ORDER BY s.nom LIMIT 10";
136 $resql = $db->query($sql);
137 $langs->load(
'companies');
138 while ($resql && ($obj = $db->fetch_object($resql))) {
141 if (in_array((
int) $obj->client, array(1, 3),
true)) {
142 $roles[] = $langs->transnoentitiesnoconv(
'Customer');
144 if (in_array((
int) $obj->client, array(2, 3),
true)) {
145 $roles[] = $langs->transnoentitiesnoconv(
'Prospect');
147 if ((
int) $obj->fournisseur === 1) {
148 $roles[] = $langs->transnoentitiesnoconv(
'Supplier');
150 $detail = implode(
', ', array_filter(array(implode(
' / ', $roles), (
string) $obj->town)));
151 $items[] = array(
'value' => (
string) $obj->nom,
'ref' => (
string) $obj->nom,
'label' => (
string) $obj->nom.((string) $obj->name_alias !==
'' ?
' ('.$obj->name_alias.
')' :
''),
'detail' => $detail);
153 } elseif ($kind ===
'product') {
155 $words = preg_split(
'/\s+/', trim(str_replace(
'"',
' ', ltrim($q,
'#'))), -1, PREG_SPLIT_NO_EMPTY) ?: array();
156 if (count($words) >= 1 &&
aiUnitIdFromName($db, $words[0]) > 0 && (count($words) > 1 || substr($q, -1) ===
' ')) {
159 $consumed = implode(
' ', $words);
160 if ($consumed !==
'') {
165 $name = trim(
GETPOST(
'name',
'restricthtml'));
166 if ($socid <= 0 && $name !==
'') {
167 $best = array(
'words' => 0,
'candidates' => array());
169 if ($mt[
'words'] > $best[
'words']) {
174 foreach ($best[
'candidates'] as $cid =>
$c) {
175 if (!empty(
$c[
'visible'])) {
179 $socid = (count($visible) === 1) ? (
int) key($visible) : 0;
183 $langs->load(
'products');
184 foreach ($found as $pr) {
189 $name = trim(str_replace(
'"',
'', (
string) ($pr[
'label'] !==
'' ? $pr[
'label'] : $pr[
'ref'])));
190 $plain = (preg_match(
'/^\S+$/', $name) && !preg_match(
'/^\d+(?:[.,]\d+)?$/', $name));
191 $value = $plain ? $name :
'"'.$name.
'"';
193 $detail =
price($pr[
'price'], 0, $langs, 1, -1, -1,
$conf->currency);
195 $detail .=
' - '.$langs->transnoentitiesnoconv(
'Stock').
' '.
price2num($pr[
'stock'],
'MS');
198 $items[] = array(
'value' => $value,
'ref' => $sentence,
'label' => $pr[
'ref'].
' - '.$pr[
'label'],
'detail' => $detail);
201 print json_encode(array(
'items' => $items,
'consumed' => $consumed));
206$input = json_decode((
string) file_get_contents(
'php://input'),
true);
207$command = is_array($input) ? (string) ($input[
'command'] ??
'') :
'';
208$text = is_array($input) ? trim((
string) ($input[
'text'] ??
'')) :
'';
209$context = (is_array($input) && isset($input[
'context']) && is_array($input[
'context'])) ? $input[
'context'] : array();
210$choices = (is_array($input) && isset($input[
'thirdparty_choices']) && is_array($input[
'thirdparty_choices'])) ? $input[
'thirdparty_choices'] : array();
211$productChoices = (is_array($input) && isset($input[
'product_choices']) && is_array($input[
'product_choices'])) ? $input[
'product_choices'] : array();
212$startTime = microtime(
true);
225function aiCommandAnswer($db, $user, $query, $startTime, array $response, $status =
'Success')
227 ai_log_request($db, $user, $query, $response,
'palette', microtime(
true) - $startTime, 1.0, $status, (
string) ($response[
'error'] ??
''));
228 print json_encode($response);
232$typedQuery =
'/'.$command.
' '.$text;
235if ($command ===
'total') {
236 $element = (string) (
$context[
'element'] ??
'');
237 if (empty(
$context[
'list']) || !isset($totalElements[$element])) {
238 aiCommandAnswer($db, $user, $typedQuery, $startTime, array(
'error' => $langs->transnoentitiesnoconv(
'AICmdTotalNoList')),
'Error');
240 $def = $totalElements[$element];
241 if (!$user->hasRight($def[
'right'][0], $def[
'right'][1], $def[
'right'][2] ??
'')) {
242 aiCommandAnswer($db, $user, $typedQuery, $startTime, array(
'error' => $langs->transnoentitiesnoconv(
'NotEnoughPermissions')),
'Error');
245 $ids = array_values(array_filter(array_map(
'intval', (array) (
$context[
'selected'] ?? array()))));
248 $ids = array_values(array_filter(array_map(
'intval', (array) (
$context[
'ids'] ?? array()))));
250 $ids = array_slice(array_unique($ids), 0, 500);
252 aiCommandAnswer($db, $user, $typedQuery, $startTime, array(
'error' => $langs->transnoentitiesnoconv(
'AICmdTotalNoList')),
'Error');
256 $sql =
"SELECT COUNT(t.rowid) as nb, SUM(t.total_ht) as ht, SUM(t.total_tva) as tva, SUM(t.total_ttc) as ttc";
257 if (!empty($def[
'paid'])) {
258 $sql .=
", SUM((SELECT COALESCE(SUM(p.amount), 0) FROM ".$db->prefix().$db->sanitize($def[
'paid'][0]).
" as p WHERE p.".$db->sanitize($def[
'paid'][1]).
" = t.rowid)) as paid";
260 $sql .=
" FROM ".$db->prefix().$db->sanitize($def[
'table']).
" as t";
261 $sql .=
" WHERE t.rowid IN (".$db->sanitize(implode(
',', $ids)).
")";
262 $sql .=
" AND t.entity IN (".getEntity($element).
")";
263 if ($user->socid > 0) {
264 $sql .=
" AND t.fk_soc = ".((int) $user->socid);
265 } elseif (!$user->hasRight(
'societe',
'client',
'voir')) {
266 $sql .=
" AND t.fk_soc IN (SELECT sc.fk_soc FROM ".$db->prefix().
"societe_commerciaux as sc WHERE sc.fk_user = ".((int) $user->id).
")";
268 $resql = $db->query($sql);
269 $obj = $resql ? $db->fetch_object($resql) :
null;
271 dol_syslog(
'command.php total '.$db->lasterror(), LOG_ERR);
272 aiCommandAnswer($db, $user, $typedQuery, $startTime, array(
'error' => $langs->transnoentitiesnoconv(
'Error')),
'Error');
275 array($langs->transnoentitiesnoconv(
'AmountHT'),
price((
float) $obj->ht, 0, $langs, 1, -1, -1,
$conf->currency)),
276 array($langs->transnoentitiesnoconv(
'AmountVAT'),
price((
float) $obj->tva, 0, $langs, 1, -1, -1,
$conf->currency)),
277 array($langs->transnoentitiesnoconv(
'AmountTTC'),
price((
float) $obj->ttc, 0, $langs, 1, -1, -1,
$conf->currency)),
279 if (!empty($def[
'paid'])) {
280 $rows[] = array($langs->transnoentitiesnoconv(
'AlreadyPaid'),
price((
float) $obj->paid, 0, $langs, 1, -1, -1,
$conf->currency));
281 $rows[] = array($langs->transnoentitiesnoconv(
'RemainderToPay'),
price((
float) $obj->ttc - (
float) $obj->paid, 0, $langs, 1, -1, -1,
$conf->currency));
285 'title' => $langs->transnoentitiesnoconv($scope ===
'ticked' ?
'AICmdTotalTicked' :
'AICmdTotalShown', (string) ((int) $obj->nb)),
292if (!isset($documentCommands[$command]) || !isset($allowedTools[$documentCommands[$command][
'tool']])) {
293 aiCommandAnswer($db, $user, $typedQuery, $startTime, array(
'error' => $langs->transnoentitiesnoconv(
'AICmdUnknown', $command)),
'Error');
295$def = $documentCommands[$command];
296$side = (strpos($command,
'supplier') === 0) ?
'buy' :
'sell';
298if ($parsed[
'error'] ===
'nolines') {
299 aiCommandAnswer($db, $user, $typedQuery, $startTime, array(
'error' => $langs->transnoentitiesnoconv(
'AICmdNoLines',
'/'.$command.
' '.$langs->transnoentitiesnoconv(
'AICmdSyntaxDocument',
dol_strtolower($langs->transnoentitiesnoconv($def[
'who']))))),
'Error');
301if (!empty($def[
'ref']) && $parsed[
'ref'] ===
'') {
302 aiCommandAnswer($db, $user, $typedQuery, $startTime, array(
'error' => $langs->transnoentitiesnoconv(
'AICmdNeedRefSupplier')),
'Error');
308if ($parsed[
'name'] !==
'') {
310 $best = array(
'phrase' =>
'',
'raw' => $parsed[
'name'],
'words' => 0,
'candidates' => array());
312 if ($mt[
'words'] > $best[
'words']) {
317 foreach ($best[
'candidates'] as $cid =>
$c) {
319 $visible[(int) $cid] =
$c;
322 if (empty($visible)) {
323 aiCommandAnswer($db, $user, $typedQuery, $startTime, array(
'error' => $langs->transnoentitiesnoconv(
'AIWriteThirdpartyNotFound', $parsed[
'name'])),
'Error');
325 $chosen = isset($choices[$best[
'phrase']]) ? (int) $choices[$best[
'phrase']] : 0;
326 if ($chosen > 0 && isset($visible[$chosen])) {
328 } elseif (count($visible) === 1) {
329 $socid = (int) key($visible);
331 $langs->load(
'companies');
333 foreach ($visible as $cid =>
$c) {
335 if (in_array(
$c[
'client'], array(1, 3))) {
336 $nat[] = $langs->transnoentitiesnoconv(
'Customer');
338 if (in_array(
$c[
'client'], array(2, 3))) {
339 $nat[] = $langs->transnoentitiesnoconv(
'Prospect');
341 if (
$c[
'fournisseur'] == 1) {
342 $nat[] = $langs->transnoentitiesnoconv(
'Supplier');
344 $options[] = array(
'id' => $cid,
'label' =>
$c[
'name'].(
$c[
'name_alias'] !==
'' ?
' ('.
$c[
'name_alias'].
')' :
'').(!empty($nat) ?
' - '.implode(
', ', $nat) :
'').(
$c[
'town'] !==
'' ?
' - '.
$c[
'town'] :
''));
346 aiCommandAnswer($db, $user, $typedQuery, $startTime, array(
'tool' =>
'ask_for_clarification',
'arguments' => array(
347 'question' => $langs->transnoentitiesnoconv(
'AIWhichThirdparty', $best[
'raw']),
348 'thirdparty_choice' => array(
'phrase' => $best[
'phrase'],
'options' => $options)
352 $element = (string) (
$context[
'element'] ??
'');
353 $socid = ($element ===
'societe') ? (
int) (
$context[
'id'] ?? 0) : (int) (
$context[
'socid'] ?? 0);
355 aiCommandAnswer($db, $user, $typedQuery, $startTime, array(
'error' => $langs->transnoentitiesnoconv(
'AICmdNeedThirdparty',
dol_strtolower($langs->transnoentitiesnoconv($def[
'who'])))),
'Error');
359 aiCommandAnswer($db, $user, $typedQuery, $startTime, array(
'error' => $langs->transnoentitiesnoconv(
'AICmdNeedThirdparty',
dol_strtolower($langs->transnoentitiesnoconv($def[
'who'])))),
'Error');
366foreach ($parsed[
'lines'] as $li => $line) {
367 $typed = (string) ($line[
'product_ref'] ??
'');
368 $key = $li.
':'.$typed;
370 if (isset($productChoices[$key]) && is_numeric($productChoices[$key])) {
371 $pick = (int) $productChoices[$key];
373 $parsed[
'lines'][$li][
'desc'] = $typed;
374 unset($parsed[
'lines'][$li][
'product_ref']);
380 $search = trim(str_replace(
'"',
' ', ltrim($typed,
'#')));
382 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
384 if ($prod->fetch($pick) > 0 && ($side ===
'buy' ? $prod->status_buy : $prod->
status) && $user->hasRight($prod->
type == 1 ?
'service' :
'produit',
'lire')) {
385 $parsed[
'lines'][$li][
'product_ref'] = $prod->ref;
391 foreach ($found as $pr) {
392 if (!empty($pr[
'exact'])) {
396 if (count($exact) === 1 || count($found) === 1) {
397 $parsed[
'lines'][$li][
'product_ref'] = (count($exact) === 1 ? $exact[0][
'ref'] : $found[0][
'ref']);
401 foreach ($found as $pr) {
402 $options[] = array(
'id' => $pr[
'id'],
'label' => $pr[
'ref'].
' - '.$pr[
'label'].
' - '.
price($pr[
'price'], 0, $langs, 1, -1, -1,
$conf->currency));
404 aiCommandAnswer($db, $user, $typedQuery, $startTime, array(
'tool' =>
'ask_for_clarification',
'arguments' => array(
405 'question' => $langs->transnoentitiesnoconv(empty($options) ?
'AICmdProductNotFound' :
'AICmdWhichProduct', $search),
406 'product_choice' => array(
'key' => $key,
'options' => $options)
410$args = array(
'socid' => $socid,
'lines' => $parsed[
'lines']);
411if ($parsed[
'ref'] !==
'') {
412 $args[
'ref_supplier'] = $parsed[
'ref'];
416$result = $mcp->executeTool($def[
'tool'], $args);
417if (isset($result[
'error'])) {
418 aiCommandAnswer($db, $user, $typedQuery, $startTime, array(
'error' => (
string) $result[
'error']),
'Error');
420aiCommandAnswer($db, $user, $typedQuery, $startTime, array(
'result' => $result,
'tool' => $def[
'tool'],
'arguments' => $args), (($result[
'resultType'] ??
'') ===
'input_required') ?
'Confirm' :
'Success');
$propal type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
aiFindProducts($db, $user, $text, $side='sell', $limit=10)
Products of the catalogue matching what a user typed: every word must be in the ref or the label,...
aiUnitIdFromName($db, $name)
Unit id from the word a user used for it: code, short label or label, in the user's language,...
aiFindThirdpartiesInText($db, $user, $text, $nature='', $stopwords=array(), $maxwords=80)
Third parties named in a text, by the words of their name or trade name (name_alias),...
aiParseDocumentCommand($db, $text, $user=null, $side='sell')
Read a one-line document command of the chat palette, e.g.
ai_log_request($db, $user, $query, array $response, $provider, float $time, float $confidence, $status, $error='', $rawReq='', $rawRes='', array $context=array(), &$logId=null)
Log AI Request with Raw Payloads.
aiCheckCsrfToken($context='')
Check the anti-CSRF token of a request sent to one of the AI Assistant endpoints.
aiRecentProducts($db, $user, $socid, $side='sell', $limit=8)
Products of a third party's latest documents, newest first: what is most likely to be sold (or bought...
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 handle MCP (Model Context Protocol).
Class to manage products or services.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
aiCommandAnswer($db, $user, $query, $startTime, array $response, $status='Success')
Answer the browser, log the command like the other assistant requests, and stop.
$context
@method int call_trigger(string $triggerName, ?User $user)
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.
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.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
if(!defined( 'NOREQUIREMENU')) if(!empty(GETPOST('seteventmessages', 'alpha'))) if(!function_exists("llxHeader")) top_httphead($contenttype='text/html', $forcenocache=0)
Show HTTP header.
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.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.