109 public function generateContent($instructions, $model =
'auto', $function =
'textgeneration', $format =
'', $moreheaders = array(), $moreendpoint =
'')
111 global $dolibarr_main_data_root;
116 if (empty($this->apiKey) && in_array($this->apiService, array(
'chatgpt',
'groq',
'mistral'))) {
117 return array(
'error' =>
true,
'message' =>
'API key is not defined for the AI enabled service ('.$this->apiService.
')');
122 if (empty($this->apiEndpoint) && $this->apiService ==
'custom' && !
getDolGlobalString(
'AI_API_CUSTOM_URL')) {
123 return array(
'error' =>
true,
'message' =>
'API URL is not defined for the AI enabled service ('.$this->apiService.
')');
127 if (empty($this->apiEndpoint)) {
129 if ($function ==
'imagegeneration') {
130 $this->apiEndpoint =
getDolGlobalString(
'AI_API_'.strtoupper($this->apiService).
'_URL', $arrayofai[$this->apiService][
'url']);
131 $this->apiEndpoint .= (preg_match(
'/\/$/', $this->apiEndpoint) ?
'' :
'/').
'images/generations';
132 } elseif ($function ==
'audiogeneration') {
133 $this->apiEndpoint =
getDolGlobalString(
'AI_API_'.strtoupper($this->apiService).
'_URL', $arrayofai[$this->apiService][
'url']);
134 $this->apiEndpoint .= (preg_match(
'/\/$/', $this->apiEndpoint) ?
'' :
'/').
'audio/speech';
135 } elseif ($function ==
'transcription') {
136 $this->apiEndpoint =
getDolGlobalString(
'AI_API_'.strtoupper($this->apiService).
'_URL', $arrayofai[$this->apiService][
'url']);
137 $this->apiEndpoint .= (preg_match(
'/\/$/', $this->apiEndpoint) ?
'' :
'/').
'transcriptions';
138 } elseif ($function ==
'file') {
139 $this->apiEndpoint =
getDolGlobalString(
'AI_API_'.strtoupper($this->apiService).
'_URL', $arrayofai[$this->apiService][
'url']);
140 $this->apiEndpoint .= (preg_match(
'/\/$/', $this->apiEndpoint) ?
'' :
'/').
'files';
141 } elseif ($function ==
'assistant') {
142 $this->apiEndpoint =
getDolGlobalString(
'AI_API_'.strtoupper($this->apiService).
'_URL', $arrayofai[$this->apiService][
'url']);
143 $this->apiEndpoint .= (preg_match(
'/\/$/', $this->apiEndpoint) ?
'' :
'/').
'assistants';
144 } elseif ($function ==
'thread') {
145 $this->apiEndpoint =
getDolGlobalString(
'AI_API_'.strtoupper($this->apiService).
'_URL', $arrayofai[$this->apiService][
'url']);
146 $this->apiEndpoint .= (preg_match(
'/\/$/', $this->apiEndpoint) ?
'' :
'/').
'threads';
147 } elseif ($function ==
'ocr') {
148 $this->apiEndpoint =
getDolGlobalString(
'AI_API_'.strtoupper($this->apiService).
'_URL', $arrayofai[$this->apiService][
'url']);
149 $this->apiEndpoint .= (preg_match(
'/\/$/', $this->apiEndpoint) ?
'' :
'/').
'ocr';
151 $this->apiEndpoint =
getDolGlobalString(
'AI_API_'.strtoupper($this->apiService).
'_URL', $arrayofai[$this->apiService][
'url']);
152 if ($this->apiService ==
'google') {
156 $this->apiEndpoint = rtrim($this->apiEndpoint,
'/');
158 $this->apiEndpoint .= (preg_match(
'/\/$/', $this->apiEndpoint) ?
'' :
'/').
'chat/completions';
163 $this->apiEndpoint .=
'/'.$moreendpoint;
169 if (empty($model) || $model ==
'auto') {
171 if (in_array($function, array(
'file',
'assistant',
'thread'))) {
173 } elseif ($function ==
'imagegeneration') {
174 $model =
getDolGlobalString(
'AI_API_'.strtoupper($this->apiService).
'_MODEL_IMAGE', $arrayofai[$this->apiService][$function][
'default']);
175 } elseif ($function ==
'audiogeneration') {
176 $model =
getDolGlobalString(
'AI_API_'.strtoupper($this->apiService).
'_MODEL_AUDIO', $arrayofai[$this->apiService][$function][
'default']);
177 } elseif ($function ==
'transcription') {
178 $model =
getDolGlobalString(
'AI_API_'.strtoupper($this->apiService).
'_MODEL_TRANSCRIPT', $arrayofai[$this->apiService][$function][
'default']);
179 } elseif ($function ==
'translation') {
180 $model =
getDolGlobalString(
'AI_API_'.strtoupper($this->apiService).
'_MODEL_TRANSLATE', $arrayofai[$this->apiService][$function][
'default']);
181 } elseif (in_array($function, array(
'docparsing',
'ocr'))) {
182 $model =
getDolGlobalString(
'AI_API_'.strtoupper($this->apiService).
'_MODEL_DOCPARSING', $arrayofai[$this->apiService][
'docparsing'][
'default']);
185 $model =
getDolGlobalString(
'AI_API_'.strtoupper($this->apiService).
'_MODEL_TEXT', $arrayofai[$this->apiService][
'textgeneration'][
'default']);
190 if ($this->apiService ==
'google' && !in_array($function, array(
'file',
'assistant',
'thread',
'ocr'))
191 && strpos($this->apiEndpoint,
':generateContent') ===
false) {
192 $this->apiEndpoint .=
'/models/'.rawurlencode($model).
':generateContent';
195 dol_syslog(
"Call API for apiKey=".substr($this->apiKey, 0, 5).
'***********, apiEndpoint='.$this->apiEndpoint.
", model=".$model.
", format=".$format);
197 if (@is_writable($dolibarr_main_data_root)) {
198 $outputfile = $dolibarr_main_data_root.
"/dolibarr_ai.log";
199 $fp = fopen($outputfile,
"w");
202 fwrite($fp,
"Call API for apiKey=".substr($this->apiKey, 0, 5).
'***********, apiEndpoint='.$this->apiEndpoint.
", model=".$model.
", format=".$format.
"\n");
212 if (empty($this->apiEndpoint)) {
213 throw new Exception(
'The AI service '.$this->apiService.
' is not yet supported for the type of request '.$function);
217 $configurations = json_decode($configurationsJson,
true);
222 if (isset($configurations[$function])) {
223 if (isset($configurations[$function][
'prePrompt'])) {
224 $prePrompt = $configurations[$function][
'prePrompt'];
227 if (isset($configurations[$function][
'postPrompt'])) {
228 $postPrompt = $configurations[$function][
'postPrompt'];
234 if (empty($prePrompt) && $function ==
'textgenerationemail') {
235 $prePrompt = self::AI_DEFAULT_PROMPT_FOR_EMAIL;
236 if ($format ===
'html') {
237 $prePrompt .=
' Return all HTML content inside a section tag';
239 $prePrompt .=
' Return content in UTF8 text. Use Linux carriage return if you need to split a line. Do not include any HTML tag neither HTML entities.';
242 if (empty($prePrompt) && $function ==
'textgenerationwebpage') {
243 $prePrompt = self::AI_DEFAULT_PROMPT_FOR_WEBPAGE;
245 if (empty($prePrompt) && $function ==
'textgenerationextrafield') {
246 $prePrompt = self::AI_DEFAULT_PROMPT_FOR_EXTRAFIELD_FILLER;
248 if (empty($prePrompt) && $function ==
'texttranslation') {
249 $prePrompt = self::AI_DEFAULT_PROMPT_FOR_TEXT_TRANSLATION;
251 if (empty($prePrompt) && $function ==
'textsummarize') {
252 $prePrompt = self::AI_DEFAULT_PROMPT_FOR_TEXT_SUMMARIZE;
254 if (empty($prePrompt) && $function ==
'textrephraser') {
255 $prePrompt = self::AI_DEFAULT_PROMPT_FOR_TEXT_REPHRASER;
257 if (empty($prePrompt) && $function ==
'textspellchecker') {
258 $prePrompt = self::AI_DEFAULT_PROMPT_FOR_TEXT_SPELLCHECKER;
260 if (empty($prePrompt) && $function ==
'docparsing') {
261 $prePrompt = self::AI_DEFAULT_PROMPT_FOR_DOC_PARSING;
264 if (is_array($instructions)) {
265 $arrayforpayload = $instructions;
266 $fullInstructions =
'';
268 $fullInstructions = $instructions.($postPrompt ? (preg_match(
'/[\.\!\?]$/', $instructions) ?
'' :
'.').
' '.$postPrompt :
'');
295 $addDateTimeContext =
false;
296 if ($addDateTimeContext) {
297 $prePrompt = ($prePrompt ? $prePrompt.(preg_match(
'/[\.\!\?]$/', $prePrompt) ?
'' :
'.').
' ' :
'').
'Today we are '.
dol_print_date(
dol_now(),
'dayhourtext');
300 if ($this->apiService ==
'google') {
302 $arrayforpayload = array(
304 array(
'role' =>
'user',
'parts' => array(array(
'text' => $fullInstructions)))
308 $arrayforpayload[
'system_instruction'] = array(
309 'parts' => array(array(
'text' => $prePrompt))
314 $arrayforpayload = array(
315 'messages' => array(array(
'role' =>
'user',
'content' => $fullInstructions)),
319 $arrayforpayload[
'messages'][] = array(
'role' =>
'system',
'content' => $prePrompt);
325 if ($function ==
'docparsing' && !is_array($instructions)) {
326 if ($this->apiService ==
'google') {
327 $arrayforpayload[
'generationConfig'] = array(
'responseMimeType' =>
'application/json');
328 } elseif (in_array($this->apiService, array(
'chatgpt',
'groq',
'mistral',
'deepseek'))) {
329 $arrayforpayload[
'response_format'] = array(
'type' =>
'json_object');
339 if ($function ==
'thread') {
340 $payload = $instructions;
342 $payload = json_encode($arrayforpayload);
345 if ($this->apiService ==
'google') {
348 'x-goog-api-key: ' . $this->apiKey,
352 'Authorization: Bearer ' . $this->apiKey,
355 if ($function !=
'file') {
356 $headers[] =
'Content-Type: application/json';
358 if (!empty($moreheaders)) {
359 foreach ($moreheaders as $morekey => $moreval) {
360 $headers[] = $morekey.
': '.$moreval;
365 if (@is_writable($dolibarr_main_data_root)) {
366 $outputfile = $dolibarr_main_data_root.
"/dolibarr_ai.log";
367 $fp = fopen($outputfile,
"a");
370 if ($function ==
'docparsing' || $function ==
'ocr') {
371 fwrite($fp,
"Call endpoint ".$this->apiEndpoint.
" with POST and the following file to upload:\n");
372 fwrite($fp, (is_string($instructions) ? $instructions : var_export($instructions,
true)).
"\n");
374 fwrite($fp,
"Call endpoint ".$this->apiEndpoint.
" with POST and the following message:\n");
375 fwrite($fp, $fullInstructions.
"\n");
376 fwrite($fp,
"And prepompt:\n");
377 fwrite($fp, $prePrompt.
"\n");
379 fwrite($fp,
"HTTP Header\n");
380 fwrite($fp, var_export($headers,
true).
"\n");
381 fwrite($fp,
"Payload\n");
382 fwrite($fp, var_export($payload,
true).
"\n");
392 global $dolibarr_ai_allow_local_endpoints;
393 $localurl = $dolibarr_ai_allow_local_endpoints ?? 0;
396 $timeoutresponse = 0;
397 if (in_array($function, array(
'docparsing',
'ocr'))) {
398 $timeoutresponse = max(90,
getDolGlobalInt(
'MAIN_USE_RESPONSE_TIMEOUT', 30));
401 $response =
getURLContent($this->apiEndpoint,
'POST', $payload, 1, $headers, array(
'http',
'https'), $localurl, -1, 0, $timeoutresponse);
403 if (empty($response[
'http_code'])) {
404 throw new Exception(
'API request failed. No http received'.(empty($response[
'curl_error_no']) ?
'' :
' (curl error '.$response[
'curl_error_no'].
': '.$response[
'curl_error_msg'].
')'));
406 if (!empty($response[
'http_code']) && $response[
'http_code'] != 200) {
407 if (in_array($response[
'http_code'], array(400, 401, 403, 429)) && !empty($response[
'content'])) {
408 $tmp = json_decode($response[
'content'],
true);
409 if (!empty($tmp[
'message'])) {
412 'message' => $tmp[
'message'],
413 'code' => (empty($response[
'http_code']) ? 0 : $response[
'http_code']),
414 'curl_error_no' => (empty($response[
'curl_error_no']) ? 0 : $response[
'curl_error_no']),
416 'service' => $this->apiService,
418 'function' => $function
422 throw new Exception(
'API request on AI endpoint '.$this->apiEndpoint.
' failed with status code '.$response[
'http_code']);
426 if (@is_writable($dolibarr_main_data_root)) {
427 $outputfile = $dolibarr_main_data_root.
"/dolibarr_ai.log";
428 $fp = fopen($outputfile,
"a");
431 fwrite($fp,
"Answer\n");
432 fwrite($fp, var_export((empty($response[
'content']) ?
'No content result' : $response[
'content']),
true).
"\n");
442 $decodedResponse = json_decode($response[
'content'],
true);
445 if (!empty($decodedResponse[
'error'])) {
446 if (is_scalar($decodedResponse[
'error'])) {
450 $generatedContent = (string) $decodedResponse[
'error'];
452 $generatedContent = (string) var_export($decodedResponse[
'error'],
true);
454 } elseif ($function ==
'ocr' && !empty($decodedResponse[
'pages']) && is_array($decodedResponse[
'pages'])) {
456 $generatedContent =
'';
457 foreach ($decodedResponse[
'pages'] as $page) {
458 if (isset($page[
'markdown']) && is_scalar($page[
'markdown'])) {
459 $generatedContent .= ($generatedContent ?
"\n" :
'').(
string) $page[
'markdown'];
462 } elseif ($this->apiService ==
'google') {
466 $generatedContent =
'';
467 if (!empty($decodedResponse[
'candidates'][0][
'content'][
'parts'])) {
468 foreach ($decodedResponse[
'candidates'][0][
'content'][
'parts'] as $part) {
469 if (isset($part[
'text']) && is_scalar($part[
'text'])) {
470 $generatedContent .= (string) $part[
'text'];
483 if (isset($decodedResponse[
'choices'][0][
'message'][
'content'])
484 && is_array($decodedResponse[
'choices'][0][
'message'][
'content'])) {
486 $foundtextchunk =
false;
487 foreach ($decodedResponse[
'choices'][0][
'message'][
'content'] as $chunk) {
488 if (is_array($chunk) && ($chunk[
'type'] ??
'') ==
'text' && isset($chunk[
'text']) && is_string($chunk[
'text'])) {
489 $textofchunks .= $chunk[
'text'];
490 $foundtextchunk =
true;
493 if ($foundtextchunk) {
494 $decodedResponse[
'choices'][0][
'message'][
'content'] = $textofchunks;
497 if (!isset($decodedResponse[
'choices'][0][
'message'][
'content'])
498 || !is_string($decodedResponse[
'choices'][0][
'message'][
'content'])) {
499 throw new Exception(
'API response of AI endpoint '.$this->apiEndpoint.
' does not contain the expected choices[0].message.content string');
501 $generatedContent = $decodedResponse[
'choices'][0][
'message'][
'content'];
506 $generatedContent = (string) $generatedContent;
510 $this->tokenUsage = $decodedResponse[
'usage'] ??
null;
513 if ($format ==
'html') {
515 dol_syslog(
"Result was detected as not HTML so we convert it into HTML.");
516 $generatedContent =
dol_nl2br($generatedContent);
518 dol_syslog(
"Result was detected as already HTML. Do nothing.");
526 return $generatedContent;
528 $errormessage = $e->getMessage();
529 $errormessagelog = $e->getMessage();
530 if (!empty($response[
'content'])) {
531 $decodedResponse = json_decode($response[
'content'],
true);
532 $errormessagelog .=
' - '.$response[
'content'];
534 if (!empty($decodedResponse[
'error'][
'message'])) {
536 $errormessage .=
' - '.$decodedResponse[
'error'][
'message'];
538 $errormessage .=
' - '.$response[
'content'];
543 if (@is_writable($dolibarr_main_data_root)) {
544 $outputfile = $dolibarr_main_data_root.
"/dolibarr_ai.log";
545 $fp = fopen($outputfile,
"a");
548 fwrite($fp,
"Error: ".$errormessagelog.
"\n");
558 'message' => $errormessage,
559 'code' => (empty($response[
'http_code']) ? 0 : $response[
'http_code']),
560 'curl_error_no' => (empty($response[
'curl_error_no']) ? 0 : $response[
'curl_error_no']),
562 'service' => $this->apiService,
564 'function' => $function
642 if ($type ==
'supplier_invoice') {
644 foreach (array(
'invoice_details',
'invoice_info',
'invoice') as $keysection) {
645 if (!empty($json[$keysection]) && is_array($json[$keysection])) {
646 $json[
'document_info'] = array_merge($json[$keysection], (isset($json[
'document_info']) && is_array($json[
'document_info'])) ? $json[
'document_info'] : array());
651 if (!empty($json[
'document_info'][
'reference'])) {
652 $tmparray[
'supplierref'] = $json[
'document_info'][
'reference'];
653 } elseif (!empty($json[
'document_info'][
'invoice_number'])) {
654 $tmparray[
'supplierref'] = $json[
'document_info'][
'invoice_number'];
655 } elseif (!empty($json[
'document_info'][
'document_ref'])) {
656 $tmparray[
'supplierref'] = $json[
'document_info'][
'document_ref'];
659 if (!empty($json[
'document_info'][
'title'])) {
660 $tmparray[
'invoice_label'] = $json[
'document_info'][
'title'];
661 } elseif (!empty($json[
'recipient'][
'description'])) {
662 $tmparray[
'invoice_label'] = $json[
'recipient'][
'description'];
663 } elseif (!empty($json[
'document_info'][
'invoice_reference'])) {
664 $tmparray[
'invoice_label'] = $json[
'document_info'][
'invoice_reference'];
668 if (!empty($json[
'document_info'][
'issue_date']) && preg_match(
'/^[0-9]{4}-[0-9]{2}-[0-9]{2}((\s|T)[0-9]{2}:[0-9]{2}:[0-9]{2}Z?)?$/', $json[
'document_info'][
'issue_date'])) {
669 $tmparray[
'issue_date'] =
dol_stringtotime($json[
'document_info'][
'issue_date'],
'tzuserrel');
670 } elseif (!empty($json[
'document_info'][
'invoice_date']) && preg_match(
'/^[0-9]{4}-[0-9]{2}-[0-9]{2}((\s|T)[0-9]{2}:[0-9]{2}:[0-9]{2}Z?)?$/', $json[
'document_info'][
'invoice_date'])) {
671 $tmparray[
'issue_date'] =
dol_stringtotime($json[
'document_info'][
'invoice_date'],
'tzuserrel');
672 } elseif (!empty($json[
'document_info'][
'submission_date']) && preg_match(
'/^[0-9]{4}-[0-9]{2}-[0-9]{2}((\s|T)[0-9]{2}:[0-9]{2}:[0-9]{2}Z?)?$/', $json[
'document_info'][
'submission_date'])) {
673 $tmparray[
'issue_date'] =
dol_stringtotime($json[
'document_info'][
'submission_date'],
'tzuserrel');
674 } elseif (!empty($json[
'document_info'][
'date']) && preg_match(
'/^[0-9]{4}-[0-9]{2}-[0-9]{2}((\s|T)[0-9]{2}:[0-9]{2}:[0-9]{2}Z?)?$/', $json[
'document_info'][
'date'])) {
675 $tmparray[
'issue_date'] =
dol_stringtotime($json[
'document_info'][
'date'],
'tzuserrel');
679 if (!empty($json[
'document_info'][
'due_date']) && preg_match(
'/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/', $json[
'document_info'][
'due_date'])) {
680 $tmparray[
'due_date'] =
dol_stringtotime($json[
'document_info'][
'due_date'],
'tzuserrel');
685 $summary = (is_array($json[
'summary'] ??
null) ? $json[
'summary'] : array());
686 $documentinfo = (is_array($json[
'document_info'] ??
null) ? $json[
'document_info'] : array());
687 $currencyinsummary = (isset($summary[
'currency']) && is_string($summary[
'currency'])) ? $summary[
'currency'] :
'';
688 $currencyindocinfo = (isset($documentinfo[
'currency_code']) && is_string($documentinfo[
'currency_code'])) ? $documentinfo[
'currency_code'] :
'';
689 if ($currencyinsummary ==
'€') {
690 $tmparray[
'currency_code'] =
'EUR';
691 } elseif (
dol_strlen($currencyinsummary) == 3) {
692 $tmparray[
'currency_code'] = $currencyinsummary;
693 } elseif (
dol_strlen($currencyindocinfo) == 3) {
694 $tmparray[
'currency_code'] = $currencyindocinfo;
698 if (!empty($json[
'notes'])) {
699 if (is_scalar($json[
'notes'])) {
700 $tmparray[
'note_public'] = $json[
'notes'];
701 } elseif (is_array($json[
'notes'])) {
703 $tmparray[
'note_public'] =
'';
704 foreach ($json[
'notes'] as $val) {
705 if (is_scalar($val)) {
706 $tmparray[
'note_public'] =
dol_concat($tmparray[
'note_public'], $val);
707 } elseif (is_array($val)) {
708 foreach ($val as $val2) {
709 if (is_scalar($val2)) {
710 $tmparray[
'note_public'] =
dol_concat($tmparray[
'note_public'], $val2);
719 if (!empty($json[
'document_info'][
'vendor'])) {
720 $arrayforthirdparty = $json[
'document_info'][
'vendor'];
721 } elseif (!empty($json[
'vendor'])) {
722 $arrayforthirdparty = $json[
'vendor'];
723 } elseif (!empty($json[
'issuer'])) {
724 $arrayforthirdparty = $json[
'issuer'];
726 if (!empty($arrayforthirdparty)) {
727 if (!empty($arrayforthirdparty[
'name'])) {
728 $tmparray[
'vendor_name'] = $arrayforthirdparty[
'name'];
730 if (!empty($arrayforthirdparty[
'siren'])) {
731 $tmparray[
'vendor_profid1'] = $arrayforthirdparty[
'siren'];
733 if (!empty($arrayforthirdparty[
'siret'])) {
734 $tmparray[
'vendor_profid2'] = $arrayforthirdparty[
'siret'];
736 if (!empty($arrayforthirdparty[
'email'])) {
737 $tmparray[
'vendor_email'] = $arrayforthirdparty[
'email'];
739 if (!empty($arrayforthirdparty[
'professional_id'])) {
740 $tmparray[
'vendor_profid1'] = $arrayforthirdparty[
'professional_id'][
'siren'];
742 if (!empty($arrayforthirdparty[
'vat_number'])) {
743 $tmparray[
'vendor_vat_number'] = $arrayforthirdparty[
'vat_number'];
744 } elseif (!empty($arrayforthirdparty[
'vatnumber'])) {
745 $tmparray[
'vendor_vat_number'] = $arrayforthirdparty[
'vatnumber'];
746 } elseif (!empty($arrayforthirdparty[
'tva_num'])) {
747 $tmparray[
'vendor_vat_number'] = $arrayforthirdparty[
'tva_num'];
749 if (!empty($arrayforthirdparty[
'address'])) {
750 if (is_array($arrayforthirdparty[
'address'])) {
752 $vendoraddress = $arrayforthirdparty[
'address'];
753 if (!empty($vendoraddress[
'street'])) {
754 $tmparray[
'vendor_address'] = $vendoraddress[
'street'];
756 if (!empty($vendoraddress[
'postal_code'])) {
757 $tmparray[
'vendor_zip'] = $vendoraddress[
'postal_code'];
759 if (!empty($vendoraddress[
'city'])) {
760 $tmparray[
'vendor_town'] = $vendoraddress[
'city'];
762 if (!empty($vendoraddress[
'country'])) {
763 $tmparray[
'vendor_country'] = $vendoraddress[
'country'];
766 $tmparray[
'vendor_address'] = $arrayforthirdparty[
'address'];
769 if (!empty($arrayforthirdparty[
'phone'])) {
770 $tmparray[
'vendor_phone'] = $arrayforthirdparty[
'phone'];
771 } elseif (!empty($arrayforthirdparty[
'phone_number'])) {
772 $tmparray[
'vendor_phone'] = $arrayforthirdparty[
'phone_number'];
777 if (empty($json[
'items'])) {
778 if (!empty($json[
'summary'][
'subtotal_excluding_tax'])) {
779 $tmparray[
'description'] =
'Undefined';
780 $tmparray[
'total_ht'] = (float) $json[
'summary'][
'subtotal_excluding_tax'];
781 $tmparray[
'vat_rate'] = (float) $json[
'summary'][
'tax'][
'rate'];
785 foreach ($json[
'items'] as $item) {
787 $tmparray[
'lines'][$i] = array();
789 if (!empty($item[
'description'])) {
790 $tmparray[
'lines'][$i][
'desc'] = $item[
'description'];
791 } elseif (!empty($item[
'service']) && is_string($item[
'service'])) {
792 $tmparray[
'lines'][$i][
'desc'] = $item[
'service'];
795 $tmparray[
'lines'][$i][
'qty'] = $item[
'quantity'] ?? 1;
796 $tmparray[
'lines'][$i][
'vat_rate'] = $item[
'tax'][
'vat_rate'] ?? ($item[
'vat_rate'] ?? ($item[
'vatrate'] ??
null));
797 $tmparray[
'lines'][$i][
'total_vat'] = $item[
'tax'][
'amount'] ??
null;
798 $tmparray[
'lines'][$i][
'subprice'] = $item[
'unit_price'] ??
null;
799 $tmparray[
'lines'][$i][
'total_ht'] = $item[
'total_excluding_tax'] ??
null;
800 $tmparray[
'lines'][$i][
'total_ttc'] = $item[
'total_including_tax'] ??
null;
802 if (!empty($item[
'period_start'])) {
803 $tmparray[
'lines'][$i][
'date_start'] =
dol_stringtotime($item[
'period_start'],
'tzuserrel');
805 if (!empty($item[
'period_end'])) {
806 $tmparray[
'lines'][$i][
'date_end'] =
dol_stringtotime($item[
'period_end'],
'tzuserrel');
808 if (!empty($item[
'period']) && !empty($item[
'period'][
'start_date'])) {
809 $tmparray[
'lines'][$i][
'date_start'] =
dol_stringtotime($item[
'period'][
'start_date'],
'tzuserrel');
811 if (!empty($item[
'period']) && !empty($item[
'period'][
'end_date'])) {
812 $tmparray[
'lines'][$i][
'date_end'] =
dol_stringtotime($item[
'period'][
'end_date'],
'tzuserrel');
817 if (!empty($json[
'summary'])) {
819 $tmparray[
'total_ht'] = $json[
'summary'][
'total_excluding_tax'] ?? ($json[
'summary'][
'total_excl_tax'] ?? ($json[
'summary'][
'total_ht'] ?? ($json[
'summary'][
'subtotal'] ??
null)));
820 $tmparray[
'vat_rate'] = $json[
'summary'][
'tax_rate'] ?? ($json[
'summary'][
'vat_rate'] ?? ((isset($json[
'summary'][
'tax']) && is_array($json[
'summary'][
'tax'])) ? ($json[
'summary'][
'tax'][
'rate'] ??
null) :
null));
821 $tmparray[
'total_ttc'] = $json[
'summary'][
'total_including_tax'] ?? ($json[
'summary'][
'total_incl_tax'] ?? ($json[
'summary'][
'total_ttc'] ?? ($json[
'summary'][
'total'] ??
null)));
825 if (!isset($tmparray[
'vat_rate']) && !empty($tmparray[
'lines'])) {
826 $vatratesoflines = array_unique(array_map(
'strval', array_filter(array_column($tmparray[
'lines'],
'vat_rate'),
'is_numeric')));
827 if (count($vatratesoflines) == 1 && count(array_filter(array_column($tmparray[
'lines'],
'vat_rate'),
'is_numeric')) == count($tmparray[
'lines'])) {
828 $tmparray[
'vat_rate'] = (float) reset($vatratesoflines);
831 } elseif ($type ==
'salary') {
833 $docinfo = (isset($json[
'document_info']) && is_array($json[
'document_info'])) ? $json[
'document_info'] : array();
834 $employee = (isset($json[
'employee']) && is_array($json[
'employee'])) ? $json[
'employee'] : array();
835 $summary = (isset($json[
'summary']) && is_array($json[
'summary'])) ? $json[
'summary'] : array();
837 if (!empty($employee[
'name']) && is_string($employee[
'name'])) {
838 $tmparray[
'employee_name'] = $employee[
'name'];
840 if (!empty($docinfo[
'title']) && is_string($docinfo[
'title'])) {
841 $tmparray[
'label'] = $docinfo[
'title'];
845 $arraydatekeys = array(
846 'period_start' => array(
'period_start',
'start_date',
'date_start'),
847 'period_end' => array(
'period_end',
'end_date',
'date_end'),
848 'payment_date' => array(
'payment_date',
'date_payment',
'paid_on')
850 foreach ($arraydatekeys as $keydest => $keyssrc) {
851 foreach ($keyssrc as $keysrc) {
852 if (!empty($docinfo[$keysrc]) && is_string($docinfo[$keysrc]) && preg_match(
'/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/', $docinfo[$keysrc])) {
860 $tmparray[
'gross_salary'] = $summary[
'gross_salary'] ?? ($summary[
'gross_pay'] ?? ($summary[
'gross'] ??
null));
861 $tmparray[
'net_to_pay'] = $summary[
'net_to_pay'] ?? ($summary[
'net_pay'] ?? ($summary[
'net_paid'] ?? ($summary[
'net_salary'] ??
null)));
863 $currency = (isset($docinfo[
'currency_code']) && is_string($docinfo[
'currency_code'])) ? $docinfo[
'currency_code'] :
'';
865 $tmparray[
'currency_code'] = $currency;
867 } elseif ($type ==
'social_contribution') {
869 $docinfo = (isset($json[
'document_info']) && is_array($json[
'document_info'])) ? $json[
'document_info'] : array();
870 $summary = (isset($json[
'summary']) && is_array($json[
'summary'])) ? $json[
'summary'] : array();
872 foreach (array(
'title' =>
'label',
'organization' =>
'organization',
'reference' =>
'reference') as $keysrc => $keydest) {
873 if (!empty($docinfo[$keysrc]) && is_string($docinfo[$keysrc])) {
874 $tmparray[$keydest] = $docinfo[$keysrc];
877 if (!empty($json[
'employee'][
'name']) && is_string($json[
'employee'][
'name'])) {
878 $tmparray[
'employee_name'] = $json[
'employee'][
'name'];
882 $arraydatekeys = array(
883 'period_start' => array(
'period_start',
'start_date'),
884 'period_end' => array(
'period_end',
'end_date'),
885 'due_date' => array(
'due_date',
'payment_date',
'date_limit')
887 foreach ($arraydatekeys as $keydest => $keyssrc) {
888 foreach ($keyssrc as $keysrc) {
889 if (!empty($docinfo[$keysrc]) && is_string($docinfo[$keysrc]) && preg_match(
'/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/', $docinfo[$keysrc])) {
897 $tmparray[
'amount'] = $summary[
'amount_to_pay'] ?? ($summary[
'total_to_pay'] ?? ($summary[
'amount'] ?? ($summary[
'total'] ??
null)));
899 $currency = (isset($docinfo[
'currency_code']) && is_string($docinfo[
'currency_code'])) ? $docinfo[
'currency_code'] :
'';
901 $tmparray[
'currency_code'] = $currency;
903 } elseif ($type ==
'expense') {
905 $docinfo = (isset($json[
'document_info']) && is_array($json[
'document_info'])) ? $json[
'document_info'] : array();
906 $summary = (isset($json[
'summary']) && is_array($json[
'summary'])) ? $json[
'summary'] : array();
908 foreach (array(
'merchant' =>
'merchant',
'title' =>
'label',
'category' =>
'category') as $keysrc => $keydest) {
909 if (!empty($docinfo[$keysrc]) && is_string($docinfo[$keysrc])) {
910 $tmparray[$keydest] = $docinfo[$keysrc];
915 foreach (array(
'date',
'expense_date',
'issue_date') as $keysrc) {
916 if (!empty($docinfo[$keysrc]) && is_string($docinfo[$keysrc]) && preg_match(
'/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/', $docinfo[$keysrc])) {
923 $tmparray[
'total_ttc'] = $summary[
'total_including_tax'] ?? ($summary[
'total_ttc'] ?? ($summary[
'total'] ??
null));
924 $tmparray[
'total_ht'] = $summary[
'total_excluding_tax'] ?? ($summary[
'total_ht'] ??
null);
925 $tmparray[
'vat_rate'] = $summary[
'vat_rate'] ?? ($summary[
'tax_rate'] ??
null);
926 $vatamount = $summary[
'vat_amount'] ?? ($summary[
'tax_amount'] ??
null);
927 if (!is_numeric($tmparray[
'vat_rate']) && is_numeric($vatamount) && is_numeric($tmparray[
'total_ht']) && $tmparray[
'total_ht'] > 0) {
928 $tmparray[
'vat_rate'] = round(100 * (
float) $vatamount / (
float) $tmparray[
'total_ht'], 1);
931 $currency = (isset($docinfo[
'currency_code']) && is_string($docinfo[
'currency_code'])) ? $docinfo[
'currency_code'] :
'';
933 $tmparray[
'currency_code'] = $currency;