dolibarr 25.0.0-alpha
html.formai.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2005-2012 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@inodbox.com>
4 * Copyright (C) 2010-2011 Juanjo Menent <jmenent@2byte.es>
5 * Copyright (C) 2015-2017 Marcos García <marcosgdf@gmail.com>
6 * Copyright (C) 2015-2017 Nicolas ZABOURI <info@inovea-conseil.com>
7 * Copyright (C) 2018-2024 Frédéric France <frederic.france@free.fr>
8 * Copyright (C) 2022 Charlene Benke <charlene@patas-monkey.com>
9 * Copyright (C) 2023 Anthony Berton <anthony.berton@bb2a.fr>
10 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
11 *
12 *
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 3 of the License, or
16 * (at your option) any later version.
17 *
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
22 *
23 * You should have received a copy of the GNU General Public License
24 * along with this program. If not, see <https://www.gnu.org/licenses/>.
25 */
26
32require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
33
34
41class FormAI extends Form
42{
46 public $db;
47
51 public $withlayout;
52
56 public $withaiprompt;
57
61 public $substit = array();
62
66 public $substit_lines = array();
67
71 public $param = array();
72
76 public $withoptiononeemailperrecipient;
77
81 public $aicallfunctioncalled = false;
82
88 public function __construct($db)
89 {
90 $this->db = $db;
91 }
92
103 public function getSectionForAIEnhancement($function = 'textgeneration', $format = '', $htmlContent = 'message', $onlyenhancements = '', $aiprompt = "")
104 {
105 global $langs, $form;
106 require_once DOL_DOCUMENT_ROOT."/ai/lib/ai.lib.php";
107 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php';
108 $formadmin = new FormAdmin($this->db);
109
110 if (!is_object($form)) {
111 $form = new Form($this->db);
112 }
113
114 $langs->load("other");
115
116 $messageaiwait = '<i class="fa fa-spinner fa-spin fa-2x fa-fw valignmiddle marginrightonly"></i>'.$langs->trans("AIProcessingPleaseWait", getDolGlobalString('AI_API_SERVICE', 'chatgpt'));
117
118 $htmlContent = preg_replace('/[^a-z0-9_]/i', '', $htmlContent);
119
120 $out = '';
121 if (empty($onlyenhancements) || in_array($onlyenhancements, array('textgenerationemail', 'textgenerationwebpage'))) {
122 $out .= '<div id="ai_textgeneration'.$htmlContent.'" class="ai_textgeneration'.$htmlContent.' paddingtop paddingbottom ai_feature">';
123 //$out .= '<span>'.$langs->trans("FillMessageWithAIContent").'</span>';
124 $out .= '<textarea class="centpercent textarea-ai_feature" data-functionai="textgeneration" id="ai_instructions'.$htmlContent.'" name="instruction" placeholder="'.$langs->trans("EnterYourAIPromptHere").'..." /></textarea>';
125 $out .= '<input id="generate_button'.$htmlContent.'" type="button" class="button smallpaddingimp" disabled data-functionai="'.$function.'" value="'.$langs->trans('Generate').'"/>';
126 $out .= '</div>';
127 }
128
129 if (empty($onlyenhancements) || in_array($onlyenhancements, array('texttranslation'))) {
130 $out .= ($out ? '<div style="height: 10px;"></div>' : '');
131 $out .= '<div id="ai_translation'.$htmlContent.'" class="ai_translation'.$htmlContent.' paddingtop paddingbottom ai_feature">';
132 $out .= img_picto('', 'language', 'class="pictofixedwidth paddingrightonly"');
133 $out .= $formadmin->select_language("", "ai_translation".$htmlContent."_select", 0, array(), $langs->trans("TranslateByAI").'...', 0, 0, 'minwidth250 ai_translation'.$htmlContent.'_select');
134 $out .= '</div>';
135 }
136
137 if (empty($onlyenhancements) || in_array($onlyenhancements, array('textsummarize'))) {
138 $summarizearray = getListForAISummarize();
139 $out .= ($out ? '<div style="height: 10px;"></div>' : '');
140 $out .= '<div id="ai_summarize'.$htmlContent.'" class="ai_summarize'.$htmlContent.' paddingtop paddingbottom ai_feature">';
141 $out .= img_picto('', 'edit', 'class="pictofixedwidth paddingrightonly"');
142 $out .= $form->selectarray("ai_summarize".$htmlContent."_select", $summarizearray, 0, $langs->trans("SummarizeByAI").'...', 0, 0, '', 1, 0, 0, '', 'minwidth250 ai_summarize'.$htmlContent.'_select');
143 $out .= '</div>';
144 }
145
146 if (empty($onlyenhancements) || in_array($onlyenhancements, array('textrephraser'))) {
147 $stylearray = getListForAIRephraseStyle();
148 $out .= ($out ? '<div style="height: 10px;"></div>' : '');
149 $out .= '<div id="ai_rephraser'.$htmlContent.'" class="ai_rephraser'.$htmlContent.' paddingtop paddingbottom ai_feature">';
150 $out .= img_picto('', 'edit', 'class="pictofixedwidth paddingrightonly"');
151 $out .= $form->selectarray("ai_rephraser".$htmlContent."_select", $stylearray, 0, $langs->trans("RephraserByAI").'...', 0, 0, '', 1, 0, 0, '', 'minwidth250 ai_rephraser'.$htmlContent.'_select');
152 $out .= '</div>';
153 }
154
155 if (in_array($onlyenhancements, array('textgenerationextrafield'))) {
156 $out .= '<div id="ai_textgenerationextrafield'.$htmlContent.'" class="ai_textgenerationextrafield'.$htmlContent.' paddingtop paddingbottom ai_feature">';
157 $out .= '<input id="input_ai_textgenerationextrafield'.$htmlContent.'" type="hidden" class="button smallpaddingimp" data-functionai="textgenerationextrafield" value="'.$aiprompt.'"/>';
158 $out .= '</div>';
159 }
160
161 $out = '<!-- getSectionForAIEnhancement -->'.$out;
162 $out = '<div id="ai_dropdown'.$htmlContent.'" class="dropdown-menu ai_dropdown ai_dropdown'.$htmlContent.' paddingtop paddingbottom">'.$out;
163
164 $out .= '<div id="ai_status_message'.$htmlContent.'" class="fieldrequired hideobject marginrightonly margintoponly">';
165 $out .= $messageaiwait;
166 $out .= '</div>';
167
168 if ($function == 'imagegeneration') {
169 $out .= '<div id="ai_image_result" class="margintoponly"></div>'; // Div for displaying the generated image
170 }
171
172 $out .= "</div>\n";
173 $out .= "<script type='text/javascript'>
174 $(document).ready(function() {
175 $('#ai_translation".$htmlContent."_select').data('functionai', 'texttranslation')
176 $('#ai_summarize".$htmlContent."_select').data('functionai', 'textsummarize')
177 $('#ai_rephraser".$htmlContent."_select').data('functionai', 'textrephraser')
178
179 $('#ai_instructions".$htmlContent."').keyup(function(){
180 console.log('We type a key up on #ai_instructions".$htmlContent."');
181 if ($(this).val() != '') {
182 $('#generate_button".$htmlContent."').prop('disabled', false);
183 } else {
184 $('#generate_button".$htmlContent."').prop('disabled', true);
185 }
186 });
187
188 // for keydown
189 $('#ai_instructions".$htmlContent."').keydown(function(event) {
190 if (event.keyCode === 13 && $(this).val() != '') {
191 console.log('We type enter on #ai_instructions".$htmlContent."');
192 event.preventDefault();
193 $('#generate_button".$htmlContent."').click();
194 }
195 });
196
197 $('#generate_button".$htmlContent."').click(function() {
198 console.log('We click on #generate_button".$htmlContent."');
199 prepareCallAIGenerator($(this));
200 });
201
202 $('#ai_translation".$htmlContent."_select').on('change', function() {
203 console.log('We change #ai_translation".$htmlContent."_select with lang '+$(this).val());
204 if ($(this).val() != null && $(this).val() != '' && $(this).val() != '-1') {
205 prepareCallAIGenerator($(this));
206 }
207 });
208
209 $('#ai_summarize".$htmlContent."_select').on('change', function() {
210 console.log('We change #ai_summarize".$htmlContent."_select with length '+$(this).val());
211 if ($(this).val() != null && $(this).val() != '' && $(this).val() != '-1') {
212 prepareCallAIGenerator($(this));
213 }
214 });
215
216 $('#ai_rephraser".$htmlContent."_select').on('change', function() {
217 console.log('We change #ai_summarize".$htmlContent."_select with mode '+$(this).val());
218 if ($(this).val() != null && $(this).val() != '' && $(this).val() != '-1') {
219 prepareCallAIGenerator($(this));
220 }
221 });
222 $('#linkforaiprompt".$function."').on('click', function() {
223 //Get value aiprompt + prepare ai generator
224 elementforprompt = $('#input_ai_textgenerationextrafield".$htmlContent."');
225 aiprompt = elementforprompt.val();
226 if (aiprompt != null && aiprompt != '' && aiprompt != '-1'){
227 prepareCallAIGenerator(elementforprompt);
228 }
229 });
230
231 function prepareCallAIGenerator(element) {
232 console.log('We prepare ajax call to AI to url /ai/ajax/generate_content.php function=".dol_escape_js($function)." format=".dol_escape_js($format)."');
233
234 var userprompt = $('#ai_instructions".$htmlContent."').val();
235 var timeoutfinished = 0;
236 var apicallfinished = 0;
237
238 instructions = '';
239 htmlname = '".dol_escape_js($htmlContent)."';
240 format = '".dol_escape_js($format)."';
241 functionai = $(element).data('functionai'); /* element is the html element we have manipulated in the ai tool */
242 style = $('#ai_rephraser'+htmlname+'_select').val();
243 texttomodify = '';
244
245 console.log('htmlname='+htmlname+' functionai='+functionai+' style='+style);
246 if ($('#'+htmlname).is('div')) {
247 texttomodify = $('#'+htmlname).html(); /* for div */
248 } else {
249 texttomodify = $('#'+htmlname).val(); /* for input or textarea */
250 }
251 if (window.ace && $('#'+htmlname+'aceeditorid').length) {
252 texttomodify = window.ace.edit(htmlname+'aceeditorid').getSession().getValue(); /* for ACE editor */
253 }
254 if (functionai == 'texttranslation') {
255 /*
256 if (CKEDITOR.instances) {
257 editorInstance = CKEDITOR.instances[htmlname];
258 if (editorInstance) {
259 texttomodify = editorInstance.getData();
260 }
261 }
262 */
263 if (!texttomodify) {
264 instructions = '';
265 } else {
266 lang = $('#ai_translation'+htmlname+'_select').val();
267 instructions = 'Translate only the following text to ' + lang + ': ' + texttomodify;
268 }
269 } else if (functionai == 'textsummarize') {
270 width = $('#ai_summarize'+htmlname+'_select').val();
271 arr = width.split('_');
272 width = arr[0];
273 unit = arr[1];
274 if (width == undefined || unit == undefined){
275 console.log('Bad value so we choose 20 words')
276 width = '50';
277 unit = 'w';
278 }
279 switch(unit){
280 case 'w':
281 unit = 'words';
282 break;
283 case 'p':
284 unit = 'paragraphs';
285 break;
286 case 'pc':
287 unit = 'percent';
288 break;
289 default:
290 console.log('unit not found so we choose words');
291 unit = 'words';
292 break;
293 }
294 instructions = 'Summarize the following text '+ (unit == 'percent' ? 'by ' : 'in') + width + ' ' + unit + ': ' + texttomodify;
295 } else if (functionai == 'textrephraser') {
296 if (style == 'spellchecker') {
297 instructions = 'Fix spelling and grammar errors in the following text : ' + texttomodify;
298 functionai = 'textspellchecker';
299 } else {
300 instructions = 'Rephrase the following text in a '+style+' style: ' + texttomodify;
301 }
302 } else if (functionai == 'textgenerationextrafield'){
303 instructions = $(element).val();
304 } else {
305 instructions = userprompt;
306 /* For a web page or an email, the existing content is sent too so the AI can modify it instead of generating it from scratch */
307 if ((functionai == 'textgenerationwebpage' || functionai == 'textgenerationemail') && userprompt && texttomodify && texttomodify.trim() != '') {
308 instructions = userprompt + '\\n\\nApply this instruction to the following existing content of the ' + (functionai == 'textgenerationemail' ? 'email' : 'page') + ', and return the full modified content (if the instruction asks for a new content, ignore the existing one):\\n' + texttomodify;
309 }
310 }
311
312 /* Show message API running */
313 $('#ai_status_message".$htmlContent."').show();
314 $('#ai_status_message".$htmlContent."').html('".dol_escape_js($messageaiwait)."');
315 $('.icon-container .loader').show();
316
317 setTimeout(function() {
318 timeoutfinished = 1;
319 $('#ai_status_message".$htmlContent."').hide();
320 }, 30000);
321
322 console.log('Instruction forged by javascript = '+instructions);
323
324 callAIGenerator(functionai, instructions, format, htmlname);
325 }
326
327 CKEDITOR.on( 'instanceReady', function(e) {
328 if (CKEDITOR.instances) {
329 var htmlname = '".$htmlContent."';
330 /* if a ckeditor handler exist for this div, we add a handler to have the main html component updated */
331 console.log('Add handler on CKEDITOR.instances[".$htmlContent."]');
332 if (CKEDITOR.instances[htmlname] != undefined) {
333 CKEDITOR.instances[htmlname].on('change', function() {
334 data = CKEDITOR.instances[htmlname].getData();
335 $('#'+htmlname).val(data); /* for input or textarea */
336 $('#'+htmlname).html(data); /* for div */
337 })
338 }
339 }
340 })
341 });
342 </script>
343 ";
344 return $out;
345 }
346
352 public function getAjaxAICallFunction()
353 {
354 $out = "";
355 if ($this->aicallfunctioncalled) {
356 return $out;
357 }
358
359 $out .= "
360 <script>
361 function callAIGenerator(aifunction, instructions, format, htmlname){
362 if (aifunction === 'imagegeneration') {
363 // Handle image generation request
364 $.ajax({
365 url: '". DOL_URL_ROOT."/ai/ajax/generate_content.php?token=".currentToken()."',
366 type: 'POST',
367 contentType: 'application/json',
368 data: JSON.stringify({
369 'format': format, /* the format for output */
370 'function': aifunction, /* the AI feature to call */
371 'instructions': instructions, /* the prompt string */
372 }),
373 success: function(response) {
374 console.log('Received image URL: '+response);
375
376 // make substitutions
377 let substit = ". json_encode($this->substit).";
378 for (let key in substit) {
379 if (substit.hasOwnProperty(key)) {
380 // Replace the placeholder with its corresponding value
381 response = response.replace(key, substit[key]);
382 }
383 }
384
385 // Assuming response is the URL of the generated image
386 var imageUrl = response;
387 $('#ai_image_result').html('<img src=\"' + imageUrl + '\" alt=\"Generated Image\" />');
388
389 // Clear the input field
390 $('#ai_instructions').val('');
391
392 apicallfinished = 1;
393 if (timeoutfinished) {
394 $('#ai_status_message').hide();
395 }
396 },
397 error: function(xhr, status, error) {
398 /* alert(error); */
399 console.log('error ajax', status, error);
400 /*$('#ai_status_message'+htmlname).hide();*/
401 $('#ai_status_message'+htmlname).val(error);
402 $('#ai_status_message'+htmlname).html(error);
403 }
404 });
405 } else {
406 // set editor in readonly
407 if (CKEDITOR.instances[htmlname]) {
408 CKEDITOR.instances[htmlname].setReadOnly(1);
409 }
410
411 console.log('Call generate_content.php');
412 $.ajax({
413 url: '". DOL_URL_ROOT."/ai/ajax/generate_content.php?token=".currentToken()."',
414 type: 'POST',
415 contentType: 'application/json',
416 data: JSON.stringify({
417 'format': format, /* the format for output */
418 'function': aifunction, /* the AI feature to call */
419 'instructions': instructions, /* the prompt string */
420 }),
421 success: function(response) {
422 console.log('Add response into field \'#'+htmlname+'\': '+response);
423
424 jQuery('#'+htmlname).val(response); // If #htmlcontent is a input name or textarea
425 jQuery('#'+htmlname).html(response).trigger('change'); // If #htmlContent is a div and trigger event change for extrafield update
426
427 if (window.ace && jQuery('#'+htmlname+'aceeditorid').length) {
428 window.ace.edit(htmlname+'aceeditorid').getSession().setValue(response); // If field is an ACE editor
429 }
430 //jQuery('#'+htmlname+'preview').val(response);
431
432 if (CKEDITOR.instances) {
433 var editorInstance = CKEDITOR.instances[htmlname];
434 if (editorInstance) {
435 editorInstance.setReadOnly(0);
436 editorInstance.setData(response);
437 }
438 //var editorInstancepreview = CKEDITOR.instances[htmlname+'preview'];
439 //if (editorInstancepreview) {
440 // editorInstancepreview.setData(response);
441 //}
442 }
443
444 // Remove all value from Ai Section select
445 $('#ai_instructions'+htmlname).val('');
446 $('#ai_translation'+htmlname+'_select').val('-1');
447 $('#ai_translation'+htmlname+'_select').trigger('change');
448 $('#ai_summarize'+htmlname+'_select').val('-1');
449 $('#ai_summarize'+htmlname+'_select').trigger('change');
450 $('#ai_rephraser'+htmlname+'_select').val('-1');
451 $('#ai_rephraser'+htmlname+'_select').trigger('change');
452 $('#ai_status_message'+htmlname).hide();
453 $('#ai_dropdown'+htmlname).hide();
454 },
455 error: function(xhr, status, error) {
456 /* alert(error); */
457 console.log('error ajax ', status, error);
458 /* $('#ai_status_message'+htmlname).hide(); */
459 if (xhr.responseText) {
460 $('#ai_status_message'+htmlname).val(xhr.responseText);
461 $('#ai_status_message'+htmlname).html(xhr.responseText);
462 } else {
463 $('#ai_status_message'+htmlname).val(error);
464 $('#ai_status_message'+htmlname).html(error);
465 }
466 }
467
468 });
469 }
470 }
471 </script>";
472 $this->aicallfunctioncalled = true;
473 return $out;
474 }
475
484 public function setSubstitFromObject($object, $outputlangs)
485 {
486 global $extrafields;
487
488 $parameters = array();
489 $tmparray = getCommonSubstitutionArray($outputlangs, 0, null, $object);
490 complete_substitutions_array($tmparray, $outputlangs, null, $parameters);
491
492 $this->substit = $tmparray;
493
494 // Fill substit_lines with each object lines content
495 if (is_array($object->lines)) {
496 foreach ($object->lines as $line) {
497 $substit_line = array(
498 '__PRODUCT_REF__' => isset($line->product_ref) ? $line->product_ref : '',
499 '__PRODUCT_LABEL__' => isset($line->product_label) ? $line->product_label : '',
500 '__PRODUCT_DESCRIPTION__' => isset($line->product_desc) ? $line->product_desc : '',
501 '__LABEL__' => isset($line->label) ? $line->label : '',
502 '__DESCRIPTION__' => isset($line->desc) ? $line->desc : '',
503 '__DATE_START_YMD__' => dol_print_date($line->date_start, 'day', false, $outputlangs),
504 '__DATE_END_YMD__' => dol_print_date($line->date_end, 'day', false, $outputlangs),
505 '__QUANTITY__' => $line->qty,
506 '__SUBPRICE__' => price($line->subprice),
507 '__AMOUNT__' => price($line->total_ttc),
508 '__AMOUNT_EXCL_TAX__' => price($line->total_ht)
509 );
510
511 // Create dynamic tags for __PRODUCT_EXTRAFIELD_FIELD__
512 if (!empty($line->fk_product)) {
513 if (!is_object($extrafields)) {
514 $extrafields = new ExtraFields($this->db);
515 }
516 $product = new Product($this->db);
517 $product->fetch($line->fk_product);
518 $product->fetch_optionals();
519
520 $extrafields->fetch_name_optionals_label($product->table_element, true);
521
522 if (!empty($extrafields->attributes[$product->table_element]['label']) && is_array($extrafields->attributes[$product->table_element]['label']) && count($extrafields->attributes[$product->table_element]['label']) > 0) {
523 foreach ($extrafields->attributes[$product->table_element]['label'] as $key => $label) {
524 $substit_line['__PRODUCT_EXTRAFIELD_'.strtoupper($key).'__'] = isset($product->array_options['options_'.$key]) ? $product->array_options['options_'.$key] : '';
525 }
526 }
527 }
528
529 $this->substit_lines[$line->id] = $substit_line; // @phan-suppress-current-line PhanTypeMismatchProperty
530 }
531 }
532 }
533}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
getListForAIRephraseStyle()
Get list for AI style of writing.
Definition ai.lib.php:515
getListForAISummarize()
Get list for AI summarize.
Definition ai.lib.php:493
Class to manage standard extra fields.
Class to generate HTML forms for single email Usage: $formai = new FormAI($db) $formai->proprietes=1 ...
getSectionForAIEnhancement($function='textgeneration', $format='', $htmlContent='message', $onlyenhancements='', $aiprompt="")
Return Html code for AI instructions of message and autofill result.
getAjaxAICallFunction()
Return javascript code for call to AI function callAIGenerator()
setSubstitFromObject($object, $outputlangs)
Set ->substit (and ->substit_line) array from object.
__construct($db)
Constructor.
Class to generate html code for admin pages.
Class to manage generation of HTML components Only common components must be here.
Class to manage products or services.
currentToken()
Return the value of token currently saved into session with name 'token'.
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.
dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
Returns text escaped for inclusion into JavaScript code.
complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
Complete the $substitutionarray with more entries coming from external module that had set the "subst...
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).
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.