dolibarr 25.0.0-alpha
upload_page.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2005-2017 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2024-2025 Frédéric France <frederic.france@free.fr>
4 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
5 *
6 * This file is a modified version of datepicker.php from phpBSM to fix some
7 * bugs, to add new features and to dramatically increase speed.
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 */
22
28require_once '../main.inc.php';
37require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
38require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
39require_once DOL_DOCUMENT_ROOT.'/ai/class/ai.class.php';
40require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
41require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
42require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
43require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
44require_once DOL_DOCUMENT_ROOT.'/salaries/class/salary.class.php';
45require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php';
46require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
47require_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; // Needed by ExpenseReport::addline()
48
49$langs->loadLangs(array("main", "exports", "other"));
50
51$action = GETPOST('action', 'aZ09');
52$modulepart = GETPOST('modulepart', 'aZ09');
53$socid = GETPOSTINT('socid');
54// The product selector returns 'idprod_X' (X = product id) or the id of a supplier price, so we convert it into a product id
55$prodid = 0;
56$reg = array();
57if (preg_match('/^idprod_(\d+)$/', GETPOST('prodid', 'alpha'), $reg)) {
58 $prodid = (int) $reg[1];
59} elseif (GETPOSTINT('prodid') > 0) {
60 $tmpproductfournisseur = new ProductFournisseur($db);
61 if ($tmpproductfournisseur->fetch_product_fournisseur_price(GETPOSTINT('prodid')) > 0) {
62 $prodid = (int) $tmpproductfournisseur->fk_product;
63 }
64}
65// The selector of type of fees of the upload form returns the code of the type, the one of the summary page returns the id, so we convert it into an id
66$feetypeid = 0;
67if (preg_match('/^\d+$/', GETPOST('feetypeid', 'aZ09'))) {
68 $feetypeid = GETPOSTINT('feetypeid');
69} elseif (GETPOST('feetypeid', 'aZ09') && GETPOST('feetypeid', 'aZ09') != '-1') {
70 $sql = "SELECT id FROM ".$db->prefix()."c_type_fees WHERE code = '".$db->escape(GETPOST('feetypeid', 'aZ09'))."'";
71 $resql = $db->query($sql);
72 if ($resql && ($obj = $db->fetch_object($resql))) {
73 $feetypeid = (int) $obj->id;
74 }
75}
76
77
78// users/temp/import
79$upload_dir = $conf->user->dir_temp.'/import';
80dol_mkdir($upload_dir);
81
82$file = GETPOST('file');
83
84$originalfilename = $file;
85$uid = $thiid = $pid = $erid = $salid = 0;
86$reg = array();
87if (preg_match('/-uid([\d+])/', $file, $reg)) {
88 $uid = $reg[1];
89 $originalfilename = preg_replace('/-uid\d+/', '', $originalfilename);
90}
91if (preg_match('/-thiid([\d+])/', $file, $reg)) {
92 $thiid = $reg[1];
93 $originalfilename = preg_replace('/-thiid\d+/', '', $originalfilename);
94}
95if (preg_match('/-pid([\d+])/', $file, $reg)) {
96 $pid = $reg[1];
97 $originalfilename = preg_replace('/-pid\d+/', '', $originalfilename);
98}
99if (preg_match('/-erid([\d+])/', $file, $reg)) {
100 $erid = $reg[1];
101 $originalfilename = preg_replace('/-erid\d+/', '', $originalfilename);
102}
103if (preg_match('/-salid([\d+])/', $file, $reg)) {
104 $salid = $reg[1];
105 $originalfilename = preg_replace('/-salid\d+/', '', $originalfilename);
106}
107$originalfilename = preg_replace('/^upload_page-[a-z_]+-/', '', $originalfilename);
108
109$error = 0;
110
111$ai = new Ai($db);
112$ajaxFileUrl = '';
113$fullnewname = '';
114$uploadedfilename = '';
115
116// Name of the model or local tool used to convert the file into text, and name of the model used to analyze it
117// (used to show the progress of the processing during the "uploadfile" action).
118// For the 'custom' service, the hardcoded defaults have no meaning for an unknown provider, so a missing constant means the model is not configured.
119$converternamefortext = '';
120$modelforanalysis = '';
121$arrayofaiservices = getListOfAIServices();
122$apiservice = $ai->getApiService();
123if (getDolGlobalString('AI_USED_FOR_FILE_TO_TEXT_CONVERTION')) {
124 $defaultmodel = ($apiservice != 'custom' && !empty($arrayofaiservices[$apiservice]['docparsing']['default']) && $arrayofaiservices[$apiservice]['docparsing']['default'] != 'na') ? $arrayofaiservices[$apiservice]['docparsing']['default'] : '';
125 $converternamefortext = getDolGlobalString('AI_API_'.strtoupper($apiservice).'_MODEL_DOCPARSING', $defaultmodel);
126} elseif (preg_match('/\.pdf$/i', $originalfilename)) {
127 $converternamefortext = 'pdftotext';
128} elseif (preg_match('/\.(png|jpe?g|gif|bmp|tiff?|webp)$/i', $originalfilename)) {
129 $converternamefortext = 'docling';
130}
131$defaultmodelfortext = ($apiservice != 'custom' && !empty($arrayofaiservices[$apiservice]['textgeneration']['default'])) ? $arrayofaiservices[$apiservice]['textgeneration']['default'] : '';
132$modelforanalysis = getDolGlobalString('AI_API_'.strtoupper($apiservice).'_MODEL_TEXT', $defaultmodelfortext);
133// Show "Not configured" when no model or converter is defined
134if (empty($converternamefortext)) {
135 $converternamefortext = $langs->trans("AIModelNotConfigured");
136}
137if (empty($modelforanalysis)) {
138 $modelforanalysis = $langs->trans("AIModelNotConfigured");
139}
140
141
142/*
143 * Actions
144 */
145
146if (getDolGlobalString('MAIN_USE_TOP_MENU_IMPORT_FILE') && !is_numeric(getDolGlobalString('MAIN_USE_TOP_MENU_IMPORT_FILE'))) {
147 $urlforuploadpage = getDolGlobalString('MAIN_USE_TOP_MENU_IMPORT_FILE');
148
149 header("Location: ".$urlforuploadpage);
150 exit(1);
151}
152
153// Access control: this page uses the AI module to parse the uploaded files, so it is blocked when the module is not enabled.
154// Note: the redirect to a custom url defined into MAIN_USE_TOP_MENU_IMPORT_FILE must stay reachable.
155if (!isModEnabled('ai')) {
156 accessforbidden('ErrorAIModuleNotActive', 1, 1, 1);
157}
158
159if ($action == 'displayfile') { // Test on permission not required here. Only files uploaded by the current user are returned: the file name embeds the user id.
160 $filetodisplay = dol_sanitizeFileName(GETPOST('originalfilename', 'alphanohtml'));
161 $mimetodisplay = dol_mimetype($filetodisplay);
162 if (!preg_match('/^upload_page-[a-z_]+-uid'.((int) $user->id).'-/', $filetodisplay)
163 || !preg_match('/^(application\/pdf|image\/(png|jpeg|gif|webp|bmp))$/', $mimetodisplay)
164 || !dol_is_file($upload_dir.'/'.$filetodisplay)) {
165 httponly_accessforbidden('File not found or not allowed', 404);
166 }
167
168 top_httphead($mimetodisplay);
169 header('Content-Disposition: inline; filename="'.dol_escape_htmltag($filetodisplay).'"');
170 header('Content-Length: '.dol_filesize($upload_dir.'/'.$filetodisplay));
171 readfileLowMemory($upload_dir.'/'.$filetodisplay);
172
173 $db->close();
174 exit(0);
175}
176
177if ($action == 'uploadfile') { // Test on permission not required here. Done later
178 if (!$modulepart) { // Should not happen
179 print 'Error, modulepart param is empty';
180 exit(1);
181 }
182
183 // $modulepart can be 'invoice_supplier', ...
184 $arrayobject = getElementProperties($modulepart);
185
186 $module = $arrayobject['module'];
187 $element = $arrayobject['element'];
188 $dir_output = $arrayobject['dir_output'];
189 $dir_temp = $arrayobject['dir_temp'];
190
191 $permlevel1 = 'read';
192 $permlevel2 = '';
193 $fileprefix = 'unknown';
194 if (in_array($modulepart, array('fournisseur', 'invoice_supplier'))) {
195 $permlevel1 = 'facture';
196 $permlevel2 = 'read';
197 $fileprefix = 'upload_page-'.$modulepart.'-uid'.$user->id.'-thiid'.(GETPOSTINT('socid') > 0 ? GETPOSTINT('socid') : 0).'-pid'.(GETPOSTINT('search_prodid') > 0 ? GETPOSTINT('search_prodid') : 0);
198 } elseif ($modulepart == 'expensereport') {
199 $permlevel1 = 'lire';
200 $fileprefix = 'upload_page-'.$modulepart.'-uid'.$user->id.'-erid'.(GETPOSTINT('userexpensereportid') > 0 ? GETPOSTINT('userexpensereportid') : 0).'-pid'.(GETPOSTINT('search_prodid') > 0 ? GETPOSTINT('search_prodid') : 0);
201 } elseif ($modulepart == 'salaries') {
202 $fileprefix = 'upload_page-'.$modulepart.'-uid'.$user->id.'-salid'.(GETPOSTINT('usersalaryid') > 0 ? GETPOSTINT('usersalaryid') : 0);
203 } elseif ($modulepart == 'chargesociales') {
204 $permlevel1 = 'charges';
205 $permlevel2 = 'lire';
206 $fileprefix = 'upload_page-'.$modulepart.'-uid'.$user->id;
207 }
208
209 if ($permlevel2) {
210 $permissiontoadd = $user->hasRight($module, $permlevel1, $permlevel2); // Used by actions_linkedfiles
211 } else {
212 $permissiontoadd = $user->hasRight($module, $permlevel1); // Used by actions_linkedfiles
213 }
214 $forceFullTextIndexation = '0'; // Used by actions_linkedfiles
215
216
217 if (!empty($_FILES['userfile']['name'])) {
218 $uploadedfilename = $_FILES['userfile']['name'];
219 $fullnewname = $fileprefix.'-'.$_FILES['userfile']['name'];
220 $_FILES['userfile']['name'] = $fullnewname;
221
222 // Delete the JSON cache file of a previous import of the same file, so the AI service result is always refreshed
223 dol_delete_file($upload_dir.'/'.dol_sanitizeFileName($fullnewname).'.json');
224
225 // $dir_output = output dir of object
226 // $dir_temp = temp dir of object
227 // $upload_dir is "users/temp/import"
228 include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; // Save uploaded file into $upload_dir (with overwrite if file already exists)
229
230 // Call AI to decrypt the file
231 // Use AJAX call instead of redirect
232 // @phpstan-ignore-next-line $error may have been modified by actions_linkedfiles.inc.php
233 if (!$error) {
234 // Remove the success messages (like "FileTransferComplete" set by dol_add_file_process()), useless here
235 // because the page immediately shows the progress of the processing of the file
236 unset($_SESSION['dol_events']['mesgs']);
237
238 // We will make the AJAX call from the bottom of the page
239 $ajaxFileUrl = DOL_URL_ROOT.'/core/ajax/ajaxuploadpage.php?file='.urlencode($fullnewname);
240 }
241 }
242} else {
243 // Delete the temporary files that are used when uploading files
244 dol_delete_file($upload_dir.'/upload_page-by'.$user->id.'-*');
245}
246
247if ($action == 'addobject') { // Test on permission done later
248 $mandatoryfieldsareko = 0;
249
250 if ($modulepart == 'invoice_supplier' && GETPOSTINT('invoiceid') <= 0) {
251 // Check mandatory fields for supplier invoice (not needed when the invoice already exists, as we only attach the file to it)
252 if (GETPOSTINT('socid') <= 0 ) {
253 $langs->load("companies");
254 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ThirdParty")), null, 'errors');
255 $mandatoryfieldsareko = 1;
256 }
257 if ($prodid <= 0) {
258 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Product")), null, 'errors');
259 $mandatoryfieldsareko = 1;
260 }
261 if (GETPOSTFLOAT('amount_ttc') <= 0 ) {
262 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Amount")), null, 'errors');
263 $mandatoryfieldsareko = 1;
264 }
265 if (!GETPOST('supplierref', 'alphanohtml')) {
266 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("RefSupplier")), null, 'errors');
267 $mandatoryfieldsareko = 1;
268 }
269 if (GETPOST('supplierref', 'alphanohtml') && GETPOSTINT('socid') > 0) {
270 // Check the supplier ref entered by user is not already used by another invoice of the same supplier
271 $sql = "SELECT rowid FROM ".$db->prefix()."facture_fourn";
272 $sql .= " WHERE ref_supplier = '".$db->escape(trim(GETPOST('supplierref', 'alphanohtml')))."'";
273 $sql .= " AND fk_soc = ".((int) GETPOSTINT('socid'));
274 $sql .= " AND entity IN (".getEntity('facture_fourn').")";
275 $sql .= $db->plimit(1);
276 $resql = $db->query($sql);
277 if (!$resql) {
278 setEventMessages($db->lasterror(), null, 'errors');
279 $mandatoryfieldsareko = 1;
280 } elseif ($db->num_rows($resql) > 0) {
281 $langs->load("errors");
282 setEventMessages($langs->trans("ErrorRefAlreadyExists", GETPOST('supplierref', 'alphanohtml')), null, 'errors');
283 $mandatoryfieldsareko = 1;
284 }
285 }
286 }
287 if ($modulepart == 'invoice_supplier') {
288 if (!$user->hasRight('fournisseur', 'facture', 'creer') && !$user->hasRight('supplier_invoice', 'creer')) {
289 setEventMessages($langs->trans("NotEnoughPermissions"), null, 'errors');
290 $mandatoryfieldsareko = 1;
291 }
292 } elseif ($modulepart == 'salaries') {
293 // Check mandatory fields for salary (same rules than salaries/card.php)
294 $langs->load("salaries");
295 $datesp = dol_mktime(12, 0, 0, GETPOSTINT("datespmonth"), GETPOSTINT("datespday"), GETPOSTINT("datespyear"));
296 $dateep = dol_mktime(12, 0, 0, GETPOSTINT("dateepmonth"), GETPOSTINT("dateepday"), GETPOSTINT("dateepyear"));
297 if (GETPOSTINT('usersalaryid') <= 0) {
298 $langs->load("hrm");
299 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Employee")), null, 'errors');
300 $mandatoryfieldsareko = 1;
301 }
302 if (!GETPOST('label', 'alphanohtml')) {
303 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors');
304 $mandatoryfieldsareko = 1;
305 }
306 if (empty($datesp) || empty($dateep)) {
307 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Period")), null, 'errors');
308 $mandatoryfieldsareko = 1;
309 }
310 if (GETPOSTFLOAT('amount') <= 0) {
311 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Amount")), null, 'errors');
312 $mandatoryfieldsareko = 1;
313 }
314 if (!$mandatoryfieldsareko) {
315 // Check there is not already a salary for the same employee and the same period
316 $sql = "SELECT rowid FROM ".$db->prefix()."salary";
317 $sql .= " WHERE fk_user = ".((int) GETPOSTINT('usersalaryid'));
318 $sql .= " AND datesp = '".$db->escape(dol_print_date($datesp, 'dayrfc'))."'";
319 $sql .= " AND dateep = '".$db->escape(dol_print_date($dateep, 'dayrfc'))."'";
320 $sql .= " AND entity IN (".getEntity('salary').")";
321 $sql .= $db->plimit(1);
322 $resql = $db->query($sql);
323 if (!$resql) {
324 setEventMessages($db->lasterror(), null, 'errors');
325 $mandatoryfieldsareko = 1;
326 } elseif ($db->num_rows($resql) > 0) {
327 $langs->load("errors");
328 setEventMessages($langs->trans("ErrorSalaryAlreadyExistsForThisPeriod"), null, 'errors');
329 $mandatoryfieldsareko = 1;
330 }
331 }
332 if (!$user->hasRight('salaries', 'write')) {
333 setEventMessages($langs->trans("NotEnoughPermissions"), null, 'errors');
334 $mandatoryfieldsareko = 1;
335 }
336 } elseif ($modulepart == 'chargesociales') {
337 // Check mandatory fields for social or fiscal tax (same rules than compta/sociales/card.php)
338 if (GETPOSTINT('socialcontrib') <= 0) {
339 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
340 $mandatoryfieldsareko = 1;
341 }
342 if (!GETPOST('label', 'alphanohtml')) {
343 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors');
344 $mandatoryfieldsareko = 1;
345 }
346 if (!dol_mktime(12, 0, 0, GETPOSTINT("echmonth"), GETPOSTINT("echday"), GETPOSTINT("echyear"))) {
347 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateDue")), null, 'errors');
348 $mandatoryfieldsareko = 1;
349 }
350 if (!dol_mktime(12, 0, 0, GETPOSTINT("periodmonth"), GETPOSTINT("periodday"), GETPOSTINT("periodyear"))) {
351 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("PeriodEndDate")), null, 'errors');
352 $mandatoryfieldsareko = 1;
353 }
354 if (GETPOSTFLOAT('amount') <= 0) {
355 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Amount")), null, 'errors');
356 $mandatoryfieldsareko = 1;
357 }
358 if (!$user->hasRight('tax', 'charges', 'creer')) {
359 setEventMessages($langs->trans("NotEnoughPermissions"), null, 'errors');
360 $mandatoryfieldsareko = 1;
361 }
362 } elseif ($modulepart == 'expensereport') {
363 // Check mandatory fields for a line of expense report (same rules than expensereport/card.php)
364 $langs->loadLangs(array("trips", "hrm"));
365 if (GETPOSTINT('userexpensereportid') <= 0) {
366 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Employee")), null, 'errors');
367 $mandatoryfieldsareko = 1;
368 }
369 if ($feetypeid <= 0) {
370 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
371 $mandatoryfieldsareko = 1;
372 }
373 if (!dol_mktime(0, 0, 0, GETPOSTINT("datemonth"), GETPOSTINT("dateday"), GETPOSTINT("dateyear"))) {
374 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
375 $mandatoryfieldsareko = 1;
376 }
377 if (GETPOSTFLOAT('amount_ttc') <= 0) {
378 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("AmountTTC")), null, 'errors');
379 $mandatoryfieldsareko = 1;
380 }
381 if (isModEnabled('project') && getDolGlobalString('EXPENSEREPORT_PROJECT_IS_REQUIRED')) {
382 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Project")), null, 'errors');
383 $mandatoryfieldsareko = 1;
384 }
385 // Check that expense report is for a user inside the hierarchy, or that advanced permission for all is set (as in expensereport/card.php)
386 if (!$user->hasRight('expensereport', 'creer') && !(getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('expensereport', 'writeall_advance'))) {
387 setEventMessages($langs->trans("NotEnoughPermissions"), null, 'errors');
388 $mandatoryfieldsareko = 1;
389 } elseif (GETPOSTINT('userexpensereportid') > 0 && (!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') || !$user->hasRight('expensereport', 'writeall_advance'))) {
390 if (!in_array(GETPOSTINT('userexpensereportid'), $user->getAllChildIds(1))) {
391 setEventMessages($langs->trans("UserNotInHierachy"), null, 'errors');
392 $mandatoryfieldsareko = 1;
393 }
394 }
395 }
396
397 if ($mandatoryfieldsareko) {
398 $action = 'showsummary';
399 }
400}
401
402$createdobject = null;
403$destdir = ''; // Directory where to move the uploaded file once object is created
404$destfilename = ''; // Name of the attached file once moved into $destdir
405$dateexpense = ''; // Date of expense, defined when adding a line into an expense report
406$attachtoexistinginvoice = 0; // Set to 1 when the file is attached to an existing supplier invoice instead of creating a new one
407if ($action == 'addobject' && in_array($modulepart, array('invoice_supplier', 'salaries', 'chargesociales', 'expensereport'))) { // Test on permission already done
408 $error = 0;
409
410 $db->begin();
411}
412if ($action == 'addobject' && $modulepart == 'invoice_supplier' && GETPOSTINT('invoiceid') > 0) { // Test on permission already done
413 // The invoice already exists, so we do not create a new one, we just attach the file to it
414 $createdobject = new FactureFournisseur($db);
415 $result = $createdobject->fetch(GETPOSTINT('invoiceid'));
416 if ($result <= 0 || !in_array($createdobject->entity, explode(',', getEntity('facture_fourn')))) {
417 $error++;
418 $langs->load("errors");
419 setEventMessages($langs->trans("ErrorRecordNotFound"), null, 'errors');
420 } else {
421 $attachtoexistinginvoice = 1;
422 $destdir = getMultidirOutput($createdobject).'/'.get_exdir($createdobject->id, 2, 0, 0, $createdobject, 'invoice_supplier').dol_sanitizeFileName($createdobject->ref);
423 }
424} elseif ($action == 'addobject' && $modulepart == 'invoice_supplier') { // Test on permission already done
425 $tmpthirdparty = new Societe($db);
426 $tmpthirdparty->fetch(GETPOSTINT('socid'));
427 $tmpproduct = new Product($db);
428 $tmpproduct->fetch($prodid);
429
430 $amount_ttc = GETPOSTFLOAT('amount_ttc');
431 $vat_rate = GETPOST('vat_rate', 'alphanohtml');
432 if ($vat_rate === '') {
433 $vat_rate = get_default_tva($tmpthirdparty, $mysoc, $tmpproduct->id);
434 }
435 $vat_rate = price2num($vat_rate);
436 $currency_code = GETPOST('currency_code', 'aZ09');
437
438 $createdobject = new FactureFournisseur($db);
439 $createdobject->socid = $tmpthirdparty->id;
440 $createdobject->type = FactureFournisseur::TYPE_STANDARD;
441 $createdobject->ref_supplier = GETPOST('supplierref', 'alphanohtml');
442 // Dates found in document are timestamps of the day in user timezone. Invoice dates are "date only" fields, so we convert them into the same day in server timezone (as in fourn/facture/card.php).
443 $dateinvoice = dol_now();
444 $datedue = 0;
445 $reg = array();
446 if (GETPOSTINT('issue_date') > 0 && preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', dol_print_date(GETPOSTINT('issue_date'), '%Y-%m-%d', 'tzuserrel'), $reg)) {
447 $dateinvoice = dol_mktime(0, 0, 0, (int) $reg[2], (int) $reg[3], (int) $reg[1], 'tzserver');
448 }
449 if (GETPOSTINT('due_date') > 0 && preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', dol_print_date(GETPOSTINT('due_date'), '%Y-%m-%d', 'tzuserrel'), $reg)) {
450 $datedue = dol_mktime(0, 0, 0, (int) $reg[2], (int) $reg[3], (int) $reg[1], 'tzserver');
451 }
452 $createdobject->date = $dateinvoice;
453 $createdobject->label = GETPOST('invoice_label', 'alphanohtml');
454 $createdobject->libelle = $createdobject->label; // deprecated
455 $createdobject->cond_reglement_id = $tmpthirdparty->cond_reglement_supplier_id;
456 $createdobject->mode_reglement_id = $tmpthirdparty->mode_reglement_supplier_id;
457 $createdobject->fk_account = $tmpthirdparty->fk_account;
458 $pu_devise = 0;
459 if (isModEnabled('multicurrency') && $currency_code && $currency_code != $conf->currency) {
460 $createdobject->multicurrency_code = $currency_code;
461 $pu_devise = $amount_ttc;
462 }
463 $createdobject->date_echeance = $datedue;
464 if (empty($createdobject->date_echeance)) {
465 $createdobject->date_echeance = $createdobject->calculate_date_lim_reglement();
466 }
467
468 $result = $createdobject->create($user);
469 if ($result <= 0) {
470 $error++;
471 setEventMessages($createdobject->error, $createdobject->errors, 'errors');
472 }
473
474 // Add one line with the product and the total amount including tax
475 if (!$error) {
476 $localtax1 = get_localtax($vat_rate, 1, $mysoc, $tmpthirdparty);
477 $localtax2 = get_localtax($vat_rate, 2, $mysoc, $tmpthirdparty);
478 $result = $createdobject->addline('', $amount_ttc, $vat_rate, $localtax1, $localtax2, 1, $tmpproduct->id, 0, 0, 0, 0, 0, 'TTC', $tmpproduct->type, -1, 0, array(), null, 0, $pu_devise);
479 if ($result <= 0) {
480 $error++;
481 setEventMessages($createdobject->error, $createdobject->errors, 'errors');
482 }
483 }
484
485 if (!$error) {
486 $destdir = getMultidirOutput($createdobject).'/'.get_exdir($createdobject->id, 2, 0, 0, $createdobject, 'invoice_supplier').dol_sanitizeFileName($createdobject->ref);
487 }
488}
489if ($action == 'addobject' && $modulepart == 'salaries') { // Test on permission already done
490 $fuser = new User($db);
491 $fuser->fetch(GETPOSTINT('usersalaryid'));
492
493 $createdobject = new Salary($db);
494 $createdobject->fk_user = $fuser->id;
495 $createdobject->label = GETPOST('label', 'alphanohtml');
496 $createdobject->datesp = dol_mktime(12, 0, 0, GETPOSTINT("datespmonth"), GETPOSTINT("datespday"), GETPOSTINT("datespyear"));
497 $createdobject->dateep = dol_mktime(12, 0, 0, GETPOSTINT("dateepmonth"), GETPOSTINT("dateepday"), GETPOSTINT("dateepyear"));
498 $createdobject->amount = price2num(GETPOST('amount', 'alpha'), 'MT', 2);
499 $createdobject->salary = $fuser->salary; // Set user current salary as ref salary, as in salaries/card.php
500 $createdobject->type_payment = 0;
501 $createdobject->fk_user_author = $user->id;
502 if (GETPOSTFLOAT('gross_salary') > 0) {
503 $createdobject->note = $langs->transnoentitiesnoconv("GrossSalary").': '.price(GETPOSTFLOAT('gross_salary'), 0, $langs, 1, -1, -1, $conf->currency);
504 }
505
506 $result = $createdobject->create($user);
507 if ($result <= 0) {
508 $error++;
509 setEventMessages($createdobject->error, $createdobject->errors, 'errors');
510 } else {
511 $createdobject->fetch($createdobject->id); // To get properties like ref, used by getNomUrl()
512 $destdir = $conf->salaries->dir_output.'/'.dol_sanitizeFileName((string) $createdobject->id);
513 }
514}
515if ($action == 'addobject' && $modulepart == 'chargesociales') { // Test on permission already done
516 $createdobject = new ChargeSociales($db);
517 $createdobject->type = GETPOSTINT('socialcontrib');
518 $createdobject->label = GETPOST('label', 'alphanohtml');
519 $createdobject->date_ech = dol_mktime(12, 0, 0, GETPOSTINT("echmonth"), GETPOSTINT("echday"), GETPOSTINT("echyear"));
520 $createdobject->period = dol_mktime(12, 0, 0, GETPOSTINT("periodmonth"), GETPOSTINT("periodday"), GETPOSTINT("periodyear"));
521 $createdobject->amount = price2num(GETPOST('amount', 'alpha'), 'MT');
522 $createdobject->fk_user = (GETPOSTINT('usertaxid') > 0 ? GETPOSTINT('usertaxid') : 0);
523 $createdobject->paye = ChargeSociales::STATUS_UNPAID;
524
525 $result = $createdobject->create($user);
526 if ($result <= 0) {
527 $error++;
528 setEventMessages($createdobject->error, $createdobject->errors, 'errors');
529 } else {
530 $createdobject->fetch($createdobject->id); // To get properties like ref, used by getNomUrl()
531 $destdir = $conf->tax->dir_output.'/'.dol_sanitizeFileName((string) $createdobject->ref);
532 }
533}
534if ($action == 'addobject' && $modulepart == 'expensereport') { // Test on permission already done
535 $dateexpense = dol_mktime(0, 0, 0, GETPOSTINT("datemonth"), GETPOSTINT("dateday"), GETPOSTINT("dateyear"));
536 $fuser = new User($db);
537 $fuser->fetch(GETPOSTINT('userexpensereportid'));
538
539 // Search a draft expense report of the employee whose period includes the date of expense
540 $createdobject = new ExpenseReport($db);
541 $sql = "SELECT rowid FROM ".$db->prefix()."expensereport";
542 $sql .= " WHERE fk_user_author = ".((int) $fuser->id);
543 $sql .= " AND fk_statut = ".((int) ExpenseReport::STATUS_DRAFT);
544 $sql .= " AND date_debut <= '".$db->escape(dol_print_date($dateexpense, 'dayrfc'))."' AND date_fin >= '".$db->escape(dol_print_date($dateexpense, 'dayrfc'))."'";
545 $sql .= " AND entity IN (".getEntity('expensereport').")";
546 $sql .= " ORDER BY rowid DESC";
547 $sql .= $db->plimit(1);
548 $resql = $db->query($sql);
549 $obj = ($resql ? $db->fetch_object($resql) : null);
550 if (!$resql) {
551 $error++;
552 setEventMessages($db->lasterror(), null, 'errors');
553 } elseif ($obj) {
554 $createdobject->fetch($obj->rowid);
555 } else {
556 // No draft found, so we create a new expense report for the month of the expense
557 $tmpdate = dol_getdate($dateexpense);
558 $createdobject->date_debut = dol_get_first_day($tmpdate['year'], $tmpdate['mon']);
559 $createdobject->date_fin = dol_get_last_day($tmpdate['year'], $tmpdate['mon']);
560 $createdobject->fk_user_author = $fuser->id;
561 $createdobject->fk_user_validator = $fuser->fk_user_expense_validator;
562 $createdobject->status = ExpenseReport::STATUS_DRAFT;
563
564 if (!getDolGlobalString('EXPENSEREPORT_ALLOW_OVERLAPPING_PERIODS') && $createdobject->periodExists($fuser, $createdobject->date_debut, $createdobject->date_fin) > 0) {
565 $error++;
566 setEventMessages($langs->trans("ErrorDoubleDeclaration"), null, 'errors');
567 } else {
568 $result = $createdobject->create($user);
569 if ($result <= 0) {
570 $error++;
571 setEventMessages($createdobject->error, $createdobject->errors, 'errors');
572 } else {
573 $createdobject->fetch($result);
574 }
575 }
576 }
577 if (!$error) {
578 $destdir = $conf->expensereport->dir_output.'/'.dol_sanitizeFileName($createdobject->ref);
579 }
580}
581if ($action == 'addobject' && in_array($modulepart, array('invoice_supplier', 'salaries', 'chargesociales', 'expensereport'))) { // Test on permission already done
582 // Move the uploaded file as an attached file of the created object
583 if (!$error && $destdir) {
584 $filetoattach = dol_sanitizeFileName(GETPOST('originalfilename', 'alphanohtml'));
585 if (preg_match('/^upload_page-[a-z_]+-uid'.((int) $user->id).'-/', $filetoattach) && dol_is_file($upload_dir.'/'.$filetoattach)) {
586 $destfilename = preg_replace('/^upload_page-[a-z_]+-uid\d+(-(thiid|pid|erid|salid)\d+)*-/', '', $filetoattach); // Markers can be in any order
587 dol_mkdir($destdir);
588 $result = dol_move($upload_dir.'/'.$filetoattach, $destdir.'/'.$destfilename, '0', 1, 0, 1, array('gen_or_uploaded' => 'uploaded'));
589 if (!$result) {
590 $error++;
591 $langs->load("errors");
592 setEventMessages($langs->trans("ErrorFailToRenameFile", $filetoattach, $destfilename), null, 'errors');
593 } else {
594 dol_delete_file($upload_dir.'/'.$filetoattach.'.json');
595 }
596 }
597 }
598
599 // For an expense report, we add the line of expense, linked to the file we just attached (as done by expensereport/card.php)
600 if (!$error && $createdobject instanceof ExpenseReport) {
601 $fk_ecm_files = 0;
602 if (!empty($destfilename)) {
603 include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
604 $ecmfiles = new EcmFiles($db);
605 $ecmfiles->fetch(0, '', 'expensereport/'.dol_sanitizeFileName($createdobject->ref).'/'.$destfilename);
606 $fk_ecm_files = (int) $ecmfiles->id;
607 }
608 $vatrate = (GETPOST('vat_rate', 'alpha') !== '' ? price2num(GETPOST('vat_rate', 'alpha')) : 0);
609 $result = $createdobject->addline(1, (float) price2num(GETPOST('amount_ttc', 'alpha'), 'MU'), $feetypeid, $vatrate, $dateexpense, GETPOST('comments', 'alphanohtml'), 0, 0, 0, $fk_ecm_files);
610 if ($result <= 0) {
611 $error++;
612 setEventMessages($createdobject->error, $createdobject->errors, 'errors');
613 }
614 }
615
616 if (!$error) {
617 $db->commit();
618
619 // Redirect to the card of the created object (or of the invoice the file has been attached to).
620 // The confirmation message is shown on the card by setEventMessages().
621 $urltocreatedobject = '/fourn/facture/card.php?id='.$createdobject->id;
622 if ($createdobject instanceof Salary) {
623 $urltocreatedobject = '/salaries/card.php?id='.$createdobject->id;
624 setEventMessages($langs->trans("SalaryCreatedFromFile"), null, 'mesgs');
625 } elseif ($createdobject instanceof ChargeSociales) {
626 $urltocreatedobject = '/compta/sociales/card.php?id='.$createdobject->id;
627 setEventMessages($langs->trans("SocialContributionCreatedFromFile"), null, 'mesgs');
628 } elseif ($createdobject instanceof ExpenseReport) {
629 $urltocreatedobject = '/expensereport/card.php?id='.$createdobject->id;
630 setEventMessages($langs->trans("ExpenseAddedFromFile"), null, 'mesgs');
631 } elseif ($attachtoexistinginvoice) {
632 setEventMessages($langs->trans("FileAttachedToExistingInvoice"), null, 'mesgs');
633 } else {
634 setEventMessages($langs->trans("DraftInvoiceCreatedFromFile"), null, 'mesgs');
635 }
636 header("Location: ".dol_buildpath($urltocreatedobject, 1));
637 $db->close();
638 exit;
639 } else {
640 $db->rollback();
641 $createdobject = null;
642 $action = 'showsummary';
643 }
644}
645
646
647/*
648 * View
649 */
650
651$form = new Form($db);
652
653// Important: Following code is to avoid page request by browser and PHP CPU at each Dolibarr page access.
654/*
655if (GETPOSTINT('cache')) {
656 header('Cache-Control: max-age='.GETPOSTINT('cache').', public');
657 // For a .php, we must set an Expires to avoid to have it forced to an expired value by the web server
658 header('Expires: '.gmdate('D, d M Y H:i:s', dol_now('gmt') + GETPOSTINT('cache')).' GMT');
659 // HTTP/1.0
660 header('Pragma: token=public');
661} else {
662 // HTTP/1.0
663 header('Cache-Control: no-cache');
664}
665*/
666
667$title = $langs->trans("UploadFile");
668$help_url = '';
669
670$arrayofjs = array();
671$arrayofcss = array();
672
673llxHeader('', $title, $help_url, '', 0, 0, $arrayofjs, $arrayofcss, '', 'mod-upload page-card');
674
675print load_fiche_titre('', '', '', 0, '', '', '<h2>'.img_picto('', 'upload').' '.$title.'</h2>');
676
677
678// Instantiate hooks of thirdparty module
679$hookmanager->initHooks(array('uploadform'));
680
681// Define $uploadform
682$uploadform = '';
683
684
685// Form to upload a supplier invoice
686if (empty($action)) {
687 $uploadform = '<div class="display-flex">';
688
689 if (isModEnabled('supplier_invoice')) {
690 $prodtext = $langs->trans("RefOrLabel");
691
692 $langs->load("bills");
693 $uploadform .= '
694 <div id="supplierinvoice" class="flex-item flex-item-uploadfile">'.img_picto('', 'bill', 'class="fa-2x"').'<br>
695 <div>'.$langs->trans("SupplierInvoice").'<br><br>';
696
697 //$uploadform .= '<div class="disableautoopen paddingbottom">';
698 //$uploadform .= '<input type="checkbox" name="newsupplierinvoice" id="newsupplierinvoice" value="1" checked="checked" class="disableautoopen"><label for="newsupplierinvoice" class="disableautoopen">'.$langs->trans("NewInvoice").'</label><br>';
699 //$uploadform .= '</div>';
700
701 $uploadform .= img_picto('', 'company', 'class="pictofixedwidth"');
702 $uploadform .= $form->select_company($socid, 'socid', '(statut:=:0)', $langs->transnoentitiesnoconv("Supplier"), 0, 0, array(), 0, 'maxwidth200 disableautoopen');
703
704 $uploadform .= '<br>';
705
706 //$uploadform .= $form->select_produits_fournisseurs(0, $prodid, 'prodid', '', '', 0, 1, 2, $prodtext, 0, array(), GETPOSTINT('socid'), '1', 0, 'maxwidth200 disableautoopen', 0, '', null, 1);
707 $uploadform .= img_picto('', 'product', 'class="pictofixedwidth"');
708 $uploadform .= $form->select_produits_fournisseurs(0, $prodid, 'prodid', '', '', array(), 1, 1, 'maxwidth200 disableautoopen', $prodtext, 1);
709
710 $uploadform .= '<br>';
711
712 $uploadform .= '<br>
713 <small class="opacitymedium">'.$langs->trans("OrClickToSelectAFile").'...</small>
714 </div>
715 </div>';
716 }
717
718 // Form to upload an expense report
719 if (isModEnabled('expensereport')) {
720 $langs->load("expensereport");
721 $uploadform .= '
722 <div id="userexpensereport" class="flex-item flex-item-uploadfile">'.img_picto('', 'expensereport', 'class="fa-2x"').'<br>
723 <div>'.$langs->trans("ExpenseReport").'<br><br>';
724
725 $uploadform .= img_picto('', 'user', 'class="pictofixedwidth"');
726 //$uploadform .= '<span class="disableautoopen">';
727 $uploadform .= $form->select_dolusers(GETPOSTINT('userexpensereportid') > 0 ? GETPOSTINT('userexpensereportid') : $user->id, 'userexpensereportid', $langs->transnoentitiesnoconv("User"), null, 0, 'hierarchyme', '', '', 0, 0, '', 0, '', 'maxwidth200 disableautoopen', 1);
728 //$uploadform .= '</span>';
729
730 $uploadform .= '<br>';
731
732 $uploadform .= img_picto('', 'invoice', 'class="pictofixedwidth"');
733 $uploadform .= $form->select_type_fees(GETPOSTINT('feetypeid') > 0 ? GETPOSTINT('feetypeid') : -1, 'feetypeid', $langs->transnoentitiesnoconv("TypeFees"), 'maxwidth200 disableautoopen', 1, 1);
734
735 $uploadform .= '<br>';
736
737 $uploadform .= '<br>
738 <small class="opacitymedium">'.$langs->trans("OrClickToSelectAFile").'...</small>
739 </div>
740 </div>';
741 }
742
743
744 // Form to upload a salary document
745 if (isModEnabled('salaries')) {
746 $langs->load("salaries");
747 $uploadform .= '
748 <div id="userpayroll" class="flex-item flex-item-uploadfile">'.img_picto('', 'salary', 'class="fa-2x"').'<br>
749 <div>'.$langs->trans("UserPaySlip").'<br><br>';
750
751 $uploadform .= img_picto('', 'user', 'class="pictofixedwidth"');
752 $uploadform .= $form->select_dolusers(GETPOSTINT('usersalaryid') > 0 ? GETPOSTINT('usersalaryid') : -1, 'usersalaryid', $langs->transnoentitiesnoconv("Employee"), null, 0, 'hierarchyme', '', '', 0, 0, '', 0, '', 'maxwidth200 disableautoopen', 1);
753
754 $uploadform .= '<br>';
755
756 $uploadform .= '<br>
757 <small class="opacitymedium">'.$langs->trans("OrClickToSelectAFile").'...</small>
758 </div>
759 </div>';
760 }
761
762 // Form to upload a salary document
763 if (isModEnabled('tax')) {
764 $langs->loadLangs(array("taxes", "compta"));
765 $uploadform .= '
766 <div id="socialcontribution" class="flex-item flex-item-uploadfile">'.img_picto('', 'invoice', 'class="fa-2x"').'<br>
767 <div>'.$langs->trans("SocialContribution").'<br><br>';
768
769 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formsocialcontrib.class.php';
770 $formsocialcontrib = new FormSocialContrib($db);
771
772 $uploadform .= img_picto('', 'invoice', 'class="pictofixedwidth"');
773 $uploadform .= $formsocialcontrib->select_type_socialcontrib(GETPOST('socialcontrib', 'alpha') ? GETPOSTINT('socialcontrib') : -1, 'socialcontrib', $langs->transnoentities("TypeContrib"), 0, 0, 'minwidth150 maxwidth200 disableautoopen', 0, 1);
774
775 $uploadform .= '<br>';
776
777 $uploadform .= img_picto('', 'user', 'class="pictofixedwidth"');
778 $uploadform .= $form->select_dolusers(GETPOSTINT('usertaxid') > 0 ? GETPOSTINT('usertaxid') : -1, 'usertaxid', $langs->transnoentitiesnoconv("Employee"), null, 0, 'hierarchyme', '', '', 0, 0, '', 0, '', 'maxwidth200 disableautoopen', 1);
779
780 $uploadform .= '<br>
781 <small class="opacitymedium">'.$langs->trans("OrClickToSelectAFile").'...</small>
782 </div>
783 </div>';
784 }
785
786 $uploadform .= '</div>';
787}
788
789
790
791// Execute hook printSearchForm
792$parameters = array('uploadform' => $uploadform);
793$reshook = $hookmanager->executeHooks('printUploadForm', $parameters); // Note that $action and $object may have been modified by some hooks
794if (empty($reshook)) {
795 $uploadform .= $hookmanager->resPrint;
796} else {
797 $uploadform = $hookmanager->resPrint;
798}
799
800$uploadform .= '<br>';
801
802
803if ($action == 'uploadfile' || $action == 'showsummary') {
804 //print '<b>'.$langs->trans("ImportingFile", $originalfilename).'</b><br>';
805 //print '<br>';
806
807 // Blinking dots shown after the progress messages (the blinking is stopped by removing the span)
808 print '<style>
809.blink { animation: blinkerdots 1s linear infinite; }
810@keyframes blinkerdots { 50% { opacity: 0; } }
811</style>';
812
813 print '<div class="'.($action == 'showsummary' ? 'green' : 'neutral').'" style="padding-left: 20px; padding-right: 20px;'.($action == 'showsummary' ? ' border-left: solid 5px #118822;' : '').'">';
814
815 print '<div class="marginbottom">';
816 if ($action == 'showsummary') {
817 // Name of the original file to show: the value posted by the form of the "uploadfile" action, or the posted
818 // originalfilename cleaned of the prefix and ids added during the upload (so the prefix is never shown)
819 $filenamefordisplay = (string) GETPOST('displayedfilename', 'alphanohtml');
820 if ($filenamefordisplay === '' || preg_match('/^upload_page-/', $filenamefordisplay)) {
821 $filenamefordisplay = preg_replace('/^upload_page-[a-z_]+(-uid\d+|-thiid\d+|-pid\d+|-erid\d+|-salid\d+)+-/', '', (string) GETPOST('originalfilename', 'alphanohtml'));
822 }
823 print $langs->trans("AIProcessingDocumentPleaseWait", dol_trunc($filenamefordisplay, 32, 'middle'), $ai->getApiService());
824 // Duration of the processing, posted by the form of the "uploadfile" action, or computed from the
825 // modification times of the uploaded file and of its JSON cache file saved at the end of the processing
826 $processingduration = GETPOSTFLOAT('processingduration');
827 if ($processingduration <= 0) {
828 $fileforduration = dol_sanitizeFileName(GETPOST('originalfilename', 'alphanohtml'));
829 if (preg_match('/^upload_page-[a-z_]+-uid'.((int) $user->id).'-/', $fileforduration)
830 && dol_is_file($upload_dir.'/'.$fileforduration) && dol_is_file($upload_dir.'/'.$fileforduration.'.json')) {
831 $processingduration = dol_filemtime($upload_dir.'/'.$fileforduration.'.json') - dol_filemtime($upload_dir.'/'.$fileforduration);
832 }
833 }
834 if ($processingduration > 0) {
835 print '<br><span id="ajax-progress-message">'.$langs->trans("AIProcessingDocumentAnalyzingComplete", sprintf('%.1f', $processingduration)).'</span>';
836 }
837 } else {
838 print $langs->trans("AIProcessingDocumentPleaseWait", dol_trunc($uploadedfilename, 32, 'middle'), $ai->getApiService());
839 print '<br><span id="ajax-progress-message">'.$langs->trans("AIProcessingDocumentConvertingIntoText", $converternamefortext).'</span><span class="blink"> ...</span>';
840 }
841 print '</div>';
842 print '<br>';
843
844 print '<div class="progress" title="80%">
845 <div class="progress-bar" role="progressbar" style="width: '.($action == 'showsummary' ? '100' : '0').'%" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
846 </div>';
847
848 print '</div>';
849 print '<br>';
850}
851
852if ($action == 'uploadfile') {
853 // Add AJAX call script ($ajaxFileUrl is core/ajax/ajaxuploadpage.php?filename=...) where filename is into $conf->user->dir_temp.'/import';
854 // ajaxuploadpage returns a JSON string also saved as filename.json.
855 if (!empty($ajaxFileUrl)) {
856 print '<script>
857 $(document).ready(function() {
858 $("#form-result-back").on("click", function() {
859 window.location.href = $(this).data("url");
860 });
861
862 var ajaxUrlBase = \''.dol_escape_js($ajaxFileUrl).'\';
863 var timestartprocessing = Date.now();
864
865 console.log(\'Call ajaxFileUrl (step converttotext): \'.concat(ajaxUrlBase, "&step=converttotext"));
866 $.ajax({
867 url: ajaxUrlBase.concat("&step=converttotext"),
868 type: "GET",
869 dataType: "json",
870 beforeSend: function() {
871 $(".progress-bar").css("width", "25%");
872 },
873 success: function(data, textStatus, jqXHR) {
874 if (jqXHR.status === 200) {
875 // The conversion of the file into text is complete, we can ask the AI to analyze it
876 console.log("Conversion of the file into text complete, call the analysis");
877 $("#ajax-progress-message").text(\''.dol_escape_js($langs->trans("AIProcessingDocumentAskingAnalyze", $modelforanalysis)).'\');
878 $(".progress-bar").css("width", "60%");
879 $.ajax({
880 url: ajaxUrlBase.concat("&step=analyze"),
881 type: "GET",
882 dataType: "json",
883 success: function(data, textStatus, jqXHR) {
884 if (jqXHR.status === 200) {
885 // Display the JSON content
886 console.log("Fill the #ajax-result with json result");
887 console.log(data);
888 // Store the JSON encoded in base64 (UTF-8 safe) so it is not altered when posted
889 $("#ajax-result").val(btoa(Array.from(new TextEncoder().encode(JSON.stringify(data, null, 2)), function (c) { return String.fromCharCode(c); }).join("")));
890 $(".progress-bar").css("width", "100%");
891
892 $("span.blink").remove();
893 var durationofprocessing = ((Date.now() - timestartprocessing) / 1000).toFixed(1);
894 // The translation is made with "%s" as parameter, so the %s of the template survives the sprintf() done by trans()
895 $("#ajax-progress-message").text(\''.dol_escape_js($langs->trans("AIProcessingDocumentAnalyzingComplete", '%s')).'\'.replace("%s", durationofprocessing));
896 $("#processing-duration").val(durationofprocessing);
897
898 // Submit the form directly to show the summary of the analysis (instead of showing the button Next)
899 $("#form-result").submit();
900 } else {
901 console.log("We received an error");
902 $("span.blink").remove();
903
904 // Display error if status is not 200
905 $("#ajax-result-message").html("<div class=\"error\">Error: HTTP status " + jqXHR.status + "</div>");
906 // Replace the button Next by the button to go back to restart
907 $("#form-result-submit").hide();
908 $("#form-result-back").show();
909 }
910 },
911 error: function(jqXHR, textStatus, errorThrown) {
912 // Display error
913 console.log("We received an error");
914 $("span.blink").remove();
915 // Show the messages of the JSON answer {"errors": [...]} as text, or the raw answer if it is not this format
916 var errormsg = (jqXHR.responseJSON && jqXHR.responseJSON.errors) ? jqXHR.responseJSON.errors.join(" - ") : (jqXHR.responseText || errorThrown || "Unknown error");
917 $("#ajax-result-message").html($("<div class=\"error\"></div>").text("Error: " + errormsg));
918 $(".progress-bar").css("width", "100%");
919 // Replace the button Next by the button to go back to restart
920 $("#form-result-submit").hide();
921 $("#form-result-back").show();
922 }
923 });
924 } else {
925 console.log("We received an error");
926 $("span.blink").remove();
927
928 // Display error if status is not 200
929 $("#ajax-result-message").html("<div class=\"error\">Error: HTTP status " + jqXHR.status + "</div>");
930 // Replace the button Next by the button to go back to restart
931 $("#form-result-submit").hide();
932 $("#form-result-back").show();
933 }
934 },
935 error: function(jqXHR, textStatus, errorThrown) {
936 // Display error
937 console.log("We received an error");
938 $("span.blink").remove();
939 // Show the messages of the JSON answer {"errors": [...]} as text, or the raw answer if it is not this format
940 var errormsg = (jqXHR.responseJSON && jqXHR.responseJSON.errors) ? jqXHR.responseJSON.errors.join(" - ") : (jqXHR.responseText || errorThrown || "Unknown error");
941 $("#ajax-result-message").html($("<div class=\"error\"></div>").text("Error: " + errormsg));
942 $(".progress-bar").css("width", "100%");
943 // Replace the button Next by the button to go back to restart
944 $("#form-result-submit").hide();
945 $("#form-result-back").show();
946 }
947 });
948 });
949 </script>';
950 }
951
952 // Example of JSON result when importing a supplier PDF invoice
953 /* {
954 "document_info": {
955 "type": "Facture",
956 "invoice_number": "MSTRL-API-1234-001",
957 "invoice_reference": "Pro - Annual",
958 "issue_date": "2026-08-21",
959 "due_date": "2026-08-21",
960 "payment_terms": {
961 "days": 0,
962 "description": "0 jours"
963 },
964 "organization": "MyBigCompany"
965 },
966 "vendor": {
967 "name": "Mistral AI SAS",
968 "address": {
969 "street": "15, rue des Halles",
970 "postal_code": "75001",
971 "city": "Paris",
972 "country": "France"
973 },
974 "vat_number": "FR95952418325",
975 "professional_id": {
976 "siren": "952 418 325",
977 "capital": "19,189.04 €",
978 "rcs": "Paris"
979 },
980 "email": "no-reply@mistral.ai",
981 "contact_url": "https://help.mistral.ai/en"
982 },
983 "recipient": {
984 "name": "MyBigCompany",
985 "address": {
986 "street": "1 rue de la paix",
987 "postal_code": "75000",
988 "city": "Paris",
989 "country": "France"
990 },
991 "vat_number": "FR012345678901",
992 "email": "contact@mybigcompany.com"
993 },
994 "items": [
995 {
996 "description": "Fee for use- August",
997 "service": "Pro - Annual",
998 "quantity": 1,
999 "unit_price": 143.9,
1000 "vat_rate": 20,
1001 "total_excluding_tax": 143.9,
1002 "total_including_tax": 172.68,
1003 "period_start": "2026-08-21",
1004 "period_end": "2027-08-20"
1005 }
1006 ],
1007 "summary": {
1008 "subtotal_excluding_tax": 143.9,
1009 "tax": {
1010 "rate": 20,
1011 "amount": 28.78,
1012 "description": "EU FR Standard (20.0% sur 143,90 €)"
1013 },
1014 "total_including_tax": 172.68
1015 },
1016 "payment_info": {
1017 "due_date": "2026-08-21",
1018 "amount_due": 172.68,
1019 "currency": "EUR"
1020 },
1021 "other": {
1022 "notes": [
1023 {
1024 "type": "legal",
1025 "content": "Mistral AI - SAS au capital de 19,189.04€ - 952 418 325 R.C.S. Paris"
1026 },
1027 {
1028 "type": "contact",
1029 "content": "For any inquiry, please refer to https://help.mistral.ai/en"
1030 }
1031 ]
1032 }
1033 }
1034 */
1035
1036 print '<form class="" id="form-result" method="POST" action="'.dolBuildUrl($_SERVER["PHP_SELF"]).'">';
1037 print '<input type="hidden" name="token" value="'.newToken().'">';
1038 print '<input type="hidden" name="action" value="showsummary">';
1039 print '<input type="hidden" name="modulepart" value="'.$modulepart.'">';
1040 print '<input type="hidden" name="socid" value="'.$socid.'">';
1041 print '<input type="hidden" name="prodid" value="'.($prodid > 0 ? 'idprod_'.$prodid : '').'">';
1042 print '<input type="hidden" name="usersalaryid" value="'.GETPOSTINT('usersalaryid').'">';
1043 print '<input type="hidden" name="socialcontrib" value="'.GETPOSTINT('socialcontrib').'">';
1044 print '<input type="hidden" name="usertaxid" value="'.GETPOSTINT('usertaxid').'">';
1045 print '<input type="hidden" name="userexpensereportid" value="'.GETPOSTINT('userexpensereportid').'">';
1046 print '<input type="hidden" name="feetypeid" value="'.$feetypeid.'">';
1047 print '<input type="hidden" name="originalfilename" value="'.$fullnewname.'">';
1048 print '<input type="hidden" name="jsonstring" id="ajax-result" value="">'; // Fill by the ajax answer with the JSON encoded in base64
1049 print '<input type="hidden" name="displayedfilename" value="'.dolPrintHTMLForAttribute($uploadedfilename).'">';
1050 print '<input type="hidden" name="processingduration" id="processing-duration" value="">'; // Fill by the JS at the end of the processing
1051 print '<div id="ajax-result-message"></div>';
1052 if ($action == 'uploadfile') {
1053 print '<br>';
1054 // The buttons are hidden until the end of the ajax call: Next is shown on success, Go back on error
1055 print '<input type="submit" name="form-result-submit" id="form-result-submit" class="button" style="display: none" value="'.$langs->trans("Next").'">';
1056 print '<input type="button" name="form-result-back" id="form-result-back" class="button" style="display: none" value="'.$langs->trans("GoBack").'" data-url="'.dolPrintHTMLForAttributeUrl($_SERVER["PHP_SELF"]).'">';
1057 }
1058 print '</form>'."\n";
1059 print "\n";
1060}
1061
1062if ($action == 'showsummary') {
1063 print '<form class="" id="summary-result" method="POST" action="'.dolBuildUrl($_SERVER["PHP_SELF"]).'">';
1064 // On wide screens (>= 1280), the summary and the preview of the file are shown side by side,
1065 // both stretched to the height of the tallest one
1066 print '<style>
1067@media (min-width: 1280px) {
1068 #summary-result { display: flex; flex-wrap: wrap; align-items: stretch; }
1069 #divsummary { flex: 1 1 58%; display: flex; }
1070 #divpreview { flex: 1 1 40%; }
1071}
1072</style>';
1073 print '<input type="hidden" name="token" value="'.newToken().'">';
1074 print '<input type="hidden" name="action" value="addobject">';
1075 print '<input type="hidden" name="modulepart" value="'.$modulepart.'">';
1076 print '<input type="hidden" name="originalfilename" value="'.dolPrintHTMLForAttribute(GETPOST('originalfilename', 'alphanohtml')).'">';
1077 print '<div id="ajax-result-message"></div>';
1078 //print '<br>';
1079
1080 //print load_fiche_titre('Summary', '', 'upload');
1081
1082 print '<div id="divsummary">';
1083 print '<div class="neutral" style="margin-top: 0px; margin-bottom: 0px">';
1084
1085 print '<input type="hidden" name="token" value="'.newToken().'">';
1086
1087 // Read the result of the AI service from the JSON cache file saved by ajaxuploadpage.php, or from the posted value as fallback
1088 $jsonstring = (string) base64_decode(GETPOST('jsonstring', 'alpha'), true); // The posted JSON is encoded in base64. Strict mode returns false (so '') on invalid chars.
1089 $filejsoncache = dol_sanitizeFileName(GETPOST('originalfilename', 'alphanohtml'));
1090 if (preg_match('/^upload_page-[a-z_]+-uid'.((int) $user->id).'-/', $filejsoncache) && dol_is_file($upload_dir.'/'.$filejsoncache.'.json')) {
1091 $jsonstring = (string) file_get_contents($upload_dir.'/'.$filejsoncache.'.json');
1092 }
1093
1094 $json = null;
1095 if (!empty($jsonstring)) { // This can happen if we resubmit a page after doc was created, both jsonsting and cache file does not exists anymore.
1096 $json = json_decode($jsonstring, true);
1097 if (json_last_error() === JSON_ERROR_NONE) {
1098 print '<!-- JSON string -->';
1099 // Insert a space between consecutive dashes so content can't close the HTML comment ("-->" or "--!>")
1100 print '<!-- '.preg_replace('/-(?=-)/', '- ', $jsonstring).' -->';
1101 //print '<!-- '.$jsonstring.' -->';
1102 } else {
1103 print 'Failed to decode the result of the AI service. Error: '.dolPrintHTML(json_last_error_msg());
1104 print '<br>';
1105 print 'Result: '.dolPrintHTML($jsonstring);
1106 print '<br>';
1107 print '<br>';
1108 $json = null;
1109 }
1110 }
1111
1112 if ($modulepart == 'invoice_supplier') {
1113 $langs->loadLangs(array("bills", "companies", "products"));
1114
1115 // Parse JSON to get information for an invoice
1116 $invoiceindoc = $ai->decodeJsonIntoArray(is_array($json) ? $json : array(), 'supplier_invoice');
1117
1118 // If the document has a due date but no invoice date, we use the due date as invoice date
1119 if (empty($invoiceindoc['issue_date']) && !empty($invoiceindoc['due_date'])) {
1120 $invoiceindoc['issue_date'] = $invoiceindoc['due_date'];
1121 }
1122
1123 //var_dump($json, $invoiceindoc);
1124
1125 print "\n\n";
1126 print '<div id="supplierinvoice" class="">';
1127
1128 //print '<div class="inline-block">'.img_picto('', 'bill', '').' '.$langs->trans("SupplierInvoice").'</div>';
1129 //print '<br><br>';
1130
1131 $nameindoc = (string) $invoiceindoc['vendor_name'];
1132 $addressindoc = (string) $invoiceindoc['vendor_address'];
1133 $idprof1indoc = (string) $invoiceindoc['vendor_profid1'];
1134 $idprof2indoc = (string) $invoiceindoc['vendor_profid2'];
1135 $emailindoc = (string) $invoiceindoc['vendor_email'];
1136 $vatnumberindoc = (string) $invoiceindoc['vendor_vat_number'];
1137 $phoneindoc = (string) $invoiceindoc['vendor_phone'];
1138 $zipindoc = (string) $invoiceindoc['vendor_zip'];
1139 $townindoc = (string) $invoiceindoc['vendor_town'];
1140 $countryindoc = (string) $invoiceindoc['vendor_country'];
1141
1142
1143 // Thirdparty
1144 $tmpthirdparty = new Societe($db);
1145 print img_picto('', 'company', 'class="pictofixedwidth"').$langs->trans("ThirdParty").'<br>';
1146 if (GETPOSTINT('socid')) {
1147 $tmpthirdparty->fetch(GETPOSTINT('socid'));
1148 // TODO We can show a warning if we find a diff with autodetected value $nameindoc
1149 } else {
1150 // Try to find thirdparty
1151 $result = $tmpthirdparty->findNearest(0, $nameindoc, '', '', $idprof1indoc, $idprof2indoc, '', '', '', '', $emailindoc, $nameindoc, 0, 0, $vatnumberindoc);
1152
1153 if ($result > 0) {
1154 $tmpthirdparty->fetch($result);
1155 }
1156 }
1157
1158 print '<span class="opacitymedium">'.$langs->trans("KeyDataFoundInDocument").' :</span> ';
1159 $s = $nameindoc;
1160 if (!empty($addressindoc)) {
1161 $s .= ', &nbsp;'.$addressindoc;
1162 }
1163 if (!$s) {
1164 print '<span class="warning">'.$langs->trans("NoDataRelatedTo").'</span>';
1165 }
1166 print $s;
1167 print '<br><br>';
1168 if (empty($tmpthirdparty->id)) {
1169 if ($s) {
1170 print '<span class="warning">'.$langs->trans("NotFoundInDatabase").'</span><br>';
1171 }
1172 print $form->select_company($socid, 'socid', '((s.fournisseur:=:1) AND (s.status:=:1))', 'ChooseTheThirdPartyTouse', 1, 0, array(), 0, 'minwidth300 maxwidth400 disableautoopen', '', '', 1, array(), false, array(), 'supplier');
1173 //print ' &nbsp; '.$langs->trans("or").' &nbsp; <input type="checkbox" name="createthirdparty" id="createthirdparty" value="1" checked><label for="createthirdparty"> '.$langs->trans("CreateIt").'</label>';
1174 if ($user->hasRight('societe', 'creer')) {
1175 $langs->load("companies");
1176 // Back to the summary (the result of the AI analysis is read again from its JSON cache file), with the new thirdparty id
1177 $paramsbacktosummary = array('action' => 'showsummary', 'modulepart' => $modulepart, 'originalfilename' => GETPOST('originalfilename', 'alphanohtml'), 'socid' => '--IDFORBACKTOPAGE--');
1178 if (GETPOST('prodid', 'alpha') !== '') {
1179 $paramsbacktosummary['prodid'] = GETPOST('prodid', 'alpha');
1180 }
1181 if (GETPOST('supplierref', 'alphanohtml') !== '') {
1182 $paramsbacktosummary['supplierref'] = GETPOST('supplierref', 'alphanohtml');
1183 }
1184 // Prefill the thirdparty creation form with the vendor data detected into the document
1185 $paramstocreatethirdparty = array();
1186 if ($nameindoc !== '') {
1187 $paramstocreatethirdparty['name'] = $nameindoc;
1188 }
1189 if ($addressindoc !== '') {
1190 $paramstocreatethirdparty['address'] = $addressindoc;
1191 }
1192 if ($phoneindoc !== '') {
1193 $paramstocreatethirdparty['phone'] = $phoneindoc;
1194 }
1195 if ($emailindoc !== '') {
1196 $paramstocreatethirdparty['email'] = $emailindoc;
1197 }
1198 if ($vatnumberindoc !== '') {
1199 $paramstocreatethirdparty['tva_intra'] = $vatnumberindoc;
1200 }
1201 if ($idprof1indoc !== '') {
1202 $paramstocreatethirdparty['idprof1'] = $idprof1indoc;
1203 }
1204 if ($idprof2indoc !== '') {
1205 $paramstocreatethirdparty['idprof2'] = $idprof2indoc;
1206 }
1207 if ($zipindoc !== '') {
1208 $paramstocreatethirdparty['zipcode'] = $zipindoc;
1209 }
1210 if ($townindoc !== '') {
1211 $paramstocreatethirdparty['town'] = $townindoc;
1212 }
1213 if ($countryindoc !== '') {
1214 $countryidindoc = (int) dol_getIdFromCode($db, $countryindoc, 'c_country', 'code', 'rowid');
1215 if (empty($countryidindoc)) {
1216 $countryidindoc = (int) dol_getIdFromCode($db, $countryindoc, 'c_country', 'label', 'rowid');
1217 }
1218 if (!empty($countryidindoc)) {
1219 $paramstocreatethirdparty['country_id'] = $countryidindoc;
1220 }
1221 }
1222 $paramstocreatethirdparty = array_merge(array('action' => 'create', 'client' => 0, 'fournisseur' => 1, 'backtopage' => dolBuildUrl($_SERVER["PHP_SELF"], $paramsbacktosummary)), $paramstocreatethirdparty);
1223 print ' <a href="'.dolBuildUrl(DOL_URL_ROOT.'/societe/card.php', $paramstocreatethirdparty).'"><span class="fa fa-plus-circle valignmiddle paddingleft" title="'.$langs->trans("AddThirdParty").'"></span></a>';
1224 }
1225 } else {
1226 print '<span class="valignmiddle">'.$langs->trans("WillUse").'</span> ';
1227 print $tmpthirdparty->getNomUrl(1);
1228 print '<input type="hidden" name="socid" value="'.$tmpthirdparty->id.'">';
1229 }
1230
1231
1232 print "\n";
1233 print '<br><br><hr style="margin: 0px"><br>';
1234 print "\n";
1235
1236
1237 // @phan-suppress-next-line PhanTypeMismatchDimFetch
1238 $nameprodindoc = $invoiceindoc['items'][0]['description'];
1239 if (empty($nameprodindoc) && !empty($invoiceindoc['items'][0]['service'])) {
1240 $nameprodindoc = $invoiceindoc['items'][0]['service'];
1241 }
1242 $nbofitems = 0;
1243 if (!empty($invoiceindoc['lines']) && is_array($invoiceindoc['lines'])) {
1244 $nbofitems = count($invoiceindoc['lines']);
1245 }
1246
1247 // Product ($prodid was already converted into a product id at top of page)
1248
1249 $tmpproduct = new Product($db);
1250 print img_picto('', 'product', 'class="pictofixedwidth"').$langs->trans("Product").'<br>';
1251
1252 $amount_ttc = (GETPOSTFLOAT('amount_ttc', '', 2) ? price(GETPOSTFLOAT('amount_ttc', '', 2)) : ($invoiceindoc['total_ttc'] ?? ''));
1253 $vat_rate = (GETPOSTFLOAT('vat_rate', '', 2) ? price(GETPOSTFLOAT('vat_rate', '', 2)) : ($invoiceindoc['vat_rate'] ?? ''));
1254
1255 if ($prodid) {
1256 $tmpproduct->fetch($prodid);
1257 if (empty($amount_ttc)) {
1258 // TODO get price of product
1259 }
1260 } else {
1261 //$tmpproduct->ref = $json['ref'];
1262 // Try to find product
1263 //$result = $tmpproduct->findNearest(...);
1264 }
1265
1266
1267 print '<span class="opacitymedium">'.$langs->trans("KeyDataFoundInDocument").' :</span> ';
1268 $s = $nameprodindoc;
1269 if (!empty($nbofitems)) {
1270 $s .= ($s ? ', &nbsp;' : '').$langs->trans("NbOfLines").': '.$nbofitems;
1271 }
1272 if (!$s) {
1273 print '<span class="warning">'.$langs->trans("NoDataRelatedTo").'</span>';
1274 }
1275 print $s;
1276 print '<br><br>';
1277 if (empty($tmpproduct->id)) {
1278 print $form->select_produits_fournisseurs(0, ($prodid > 0 ? 'idprod_'.$prodid : $prodid), 'prodid', '', '', array(), 1, 1, 'minwidth300 maxwidth400 disableautoopen', $langs->trans("ChooseTheProductOrServiceTouse"), 1);
1279
1280 // TODO On selection of product, refresh next section with the product price ref
1281
1282 $addproducton = (isModEnabled('product') && $user->hasRight('produit', 'creer'));
1283 $addserviceon = (isModEnabled('service') && $user->hasRight('service', 'creer'));
1284 // Back to the summary (the result of the AI analysis is read again from its JSON cache file).
1285 // After creation, product card replaces --IDFORBACKTOPAGE-- with the new product id so it is preselected in the form
1286 $paramsbacktosummary = array('action' => 'showsummary', 'modulepart' => $modulepart, 'originalfilename' => GETPOST('originalfilename', 'alphanohtml'));
1287 if (GETPOSTINT('socid') > 0) {
1288 $paramsbacktosummary['socid'] = GETPOSTINT('socid');
1289 }
1290 if (GETPOST('supplierref', 'alphanohtml') !== '') {
1291 $paramsbacktosummary['supplierref'] = GETPOST('supplierref', 'alphanohtml');
1292 }
1293 $urlbacktocancel = dolBuildUrl($_SERVER["PHP_SELF"], $paramsbacktosummary);
1294 $paramsbacktosummary['prodid'] = 'idprod_--IDFORBACKTOPAGE--';
1295 $urlbacktoobject = dolBuildUrl($_SERVER["PHP_SELF"], $paramsbacktosummary);
1296 if ($addproducton || $addserviceon) {
1297 $langs->load("products");
1298 if ($addproducton && $addserviceon) {
1299 print ' <div id="dropdownAddProductAndService" class="dropdown inline-block">';
1300 print '<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" id="dropdownAddProductAndServiceLink" aria-haspopup="true" aria-expanded="false">';
1301 print '<span class="fa fa-plus-circle valignmiddle paddingleft"></span>';
1302 print '</a>';
1303 print '<div class="dropdown-menu" aria-labelledby="dropdownAddProductAndServiceLink" style="top:auto; left:auto;">';
1304 print '<a class="dropdown-item" href="'.DOL_URL_ROOT.'/product/card.php?action=create&type=0&backtopage='.urlencode($urlbacktoobject).'&backtopageforcancel='.urlencode($urlbacktocancel).'"> '.$langs->trans("NewProduct").'</a>';
1305 print '<a class="dropdown-item" href="'.DOL_URL_ROOT.'/product/card.php?action=create&type=1&backtopage='.urlencode($urlbacktoobject).'&backtopageforcancel='.urlencode($urlbacktocancel).'"> '.$langs->trans("NewService").'</a>';
1306 print '</div>';
1307 print '</div>';
1308 print '<script nonce="'.getNonce().'">
1309 jQuery(document).ready(function() {
1310 jQuery("#dropdownAddProductAndService .dropdown-toggle").on("click", function(event) {
1311 console.log("toggle addproduct dropdown");
1312 event.preventDefault();
1313 jQuery("#dropdownAddProductAndService").toggleClass("open");
1314 });
1315 // Close the dropdown when clicking outside of it
1316 jQuery(document).on("click", function(event) {
1317 if (jQuery(event.target).closest("#dropdownAddProductAndService").length == 0) {
1318 jQuery("#dropdownAddProductAndService").removeClass("open");
1319 }
1320 });
1321 });
1322 </script>';
1323 } elseif ($addproducton) {
1324 print ' <a href="'.DOL_URL_ROOT.'/product/card.php?action=create&type=0&backtopage='.urlencode($urlbacktoobject).'&backtopageforcancel='.urlencode($urlbacktocancel).'" title="'.dol_escape_htmltag($langs->trans("NewProduct")).'"><span class="fa fa-plus-circle valignmiddle paddingleft"></span></a>';
1325 } else {
1326 print ' <a href="'.DOL_URL_ROOT.'/product/card.php?action=create&type=1&backtopage='.urlencode($urlbacktoobject).'&backtopageforcancel='.urlencode($urlbacktocancel).'" title="'.dol_escape_htmltag($langs->trans("NewService")).'"><span class="fa fa-plus-circle valignmiddle paddingleft"></span></a>';
1327 }
1328 }
1329 } else {
1330 print $langs->trans("WillUse").' ';
1331 print $tmpproduct->getNomUrl(1);
1332 print '<input type="hidden" name="prodid" value="idprod_'.$tmpproduct->id.'">';
1333 }
1334
1335 print '<br>';
1336 print $langs->trans("VATRate").' ';
1337 print '<input type="text" class="width75 right" name="vat_rate" id="vat_rate" value="'.$vat_rate.'"> %';
1338
1339 print '<br>';
1340 print $langs->trans("TotalTTC").' ';
1341 print '<input type="text" class="width100 right" name="amount_ttc" id="amount_ttc" value="'.$amount_ttc.'">';
1342
1343 print "\n";
1344 print '<br><br><hr style="margin: 0px"><br>';
1345 print "\n";
1346
1347
1348 // Supplier invoice
1349 $tmpinvoice = new FactureFournisseur($db);
1350
1351 print img_picto('', 'supplier_invoice', 'class="pictofixedwidth"').$langs->trans("SupplierInvoice").'<br>';
1352
1353 print '<span class="opacitymedium">'.$langs->trans("KeyDataFoundInDocument").' :</span> ';
1354 $tmpvalue = array();
1355 $invoiceindoc['supplierref'] ? $tmpvalue[] = $langs->transnoentitiesnoconv("InvoiceRef").': '.$invoiceindoc['supplierref'] : '';
1356 $invoiceindoc['issue_date'] ? $tmpvalue[] = $langs->transnoentitiesnoconv("DateInvoice").': '.dol_print_date($invoiceindoc['issue_date'], 'day', 'tzuserrel') : '';
1357 $invoiceindoc['due_date'] ? $tmpvalue[] = $langs->transnoentitiesnoconv("DateDue").': '.dol_print_date($invoiceindoc['due_date'], 'day', 'tzuserrel') : '';
1358 $invoiceindoc['currency_code'] ? $tmpvalue[] = $langs->transnoentitiesnoconv("Currency").': '.$invoiceindoc['currency_code'] : '';
1359 $invoiceindoc['invoice_label'] ? $tmpvalue[] = $langs->transnoentitiesnoconv("Label").': '.$invoiceindoc['invoice_label'] : '';
1360
1361 $s = implode(', ', $tmpvalue);
1362 if (!$s) {
1363 print '<span class="warning">'.$langs->trans("NoDataRelatedTo").'</span>';
1364 }
1365 print $s;
1366 print '<br><br>';
1367 if (!empty($invoiceindoc['supplierref'])) {
1368 // Try to find supplier invoice
1369
1370 // Exact match. Always tried first, and always enough on its own.
1371 $sql = "SELECT rowid, total_ttc FROM " . $db->prefix() . "facture_fourn";
1372 $sql .= " WHERE ref_supplier = '" . $db->escape($invoiceindoc['supplierref']) . "'";
1373 $sql .= " AND fk_soc = " . ((int) $tmpthirdparty->id);
1374 $sql .= " AND entity IN (" . getEntity('facture_fourn') . ")";
1375 $sql .= " LIMIT 1";
1376 $resql = $db->query($sql);
1377 if (!$resql) {
1378 dol_syslog("SQL Error " . $db->lasterror(), LOG_ERR);
1379 return -1;
1380 }
1381 $obj = $db->fetch_object($resql);
1382 if ($obj) {
1383 $tmpinvoice->fetch($obj->rowid);
1384 }
1385 }
1386
1387 print "\n";
1388 print "\n";
1389 if (empty($tmpinvoice->id)) {
1390 print $langs->trans("InvoiceWillBeCreated");
1391 // Supplier ref is editable, prefilled with the posted value (when back after an error) or with the value detected in document
1392 $supplierref = (GETPOSTISSET('supplierref') ? GETPOST('supplierref', 'alphanohtml') : (string) $invoiceindoc['supplierref']);
1393
1394 print '<br>'.$langs->trans("RefSupplier").' ';
1395 print '<input type="text" class="minwidth150" name="supplierref" id="supplierref" value="'.dolPrintHTMLForAttribute($supplierref).'">';
1396
1397 print '<input type="hidden" name="due_date" value="'.$invoiceindoc['due_date'].'">';
1398 print '<input type="hidden" name="issue_date" value="'.$invoiceindoc['issue_date'].'">';
1399 print '<input type="hidden" name="currency_code" value="'.$invoiceindoc['currency_code'].'">';
1400 print '<input type="hidden" name="invoice_label" value="'.$invoiceindoc['invoice_label'].'">';
1401 } else {
1402 // The link is inserted after the translation, because trans() encodes the HTML of its parameters
1403 print str_replace('__INVOICELINK__', $tmpinvoice->getNomUrl(1), $langs->trans("InvoiceSeemsToAlreadyExist", $tmpinvoice->ref_supplier, '__INVOICELINK__'));
1404 print '<input type="hidden" name="invoiceid" value="'.$tmpinvoice->id.'">';
1405 }
1406
1407 print '<br>
1408 </div>';
1409 print "\n";
1410
1411 print '<br><br><center><input type="submit" name="submit" class="button" value="'.$langs->trans(empty($tmpinvoice->id) ? "CreateBill" : "AttachFileToExistingInvoice").'"></center>';
1412 print "\n";
1413 } elseif ($modulepart == 'salaries') {
1414 $langs->loadLangs(array("salaries", "hrm", "compta", "bills"));
1415
1416 // Parse JSON to get information for a salary
1417 $salaryindoc = $ai->decodeJsonIntoArray(is_array($json) ? $json : array(), 'salary');
1418
1419 // Dates found in document are timestamps of the day in user timezone. We convert them into the same day at noon, as dates of salaries/card.php.
1420 $arrayofdates = array();
1421 foreach (array('period_start', 'period_end', 'payment_date') as $keydate) {
1422 $arrayofdates[$keydate] = '';
1423 $reg = array();
1424 if (!empty($salaryindoc[$keydate]) && preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', dol_print_date($salaryindoc[$keydate], '%Y-%m-%d', 'tzuserrel'), $reg)) {
1425 $arrayofdates[$keydate] = dol_mktime(12, 0, 0, (int) $reg[2], (int) $reg[3], (int) $reg[1]);
1426 }
1427 }
1428 // Values posted (when back after an error) have priority on values found in document
1429 $datesp = GETPOSTISSET('datespday') ? dol_mktime(12, 0, 0, GETPOSTINT("datespmonth"), GETPOSTINT("datespday"), GETPOSTINT("datespyear")) : $arrayofdates['period_start'];
1430 $dateep = GETPOSTISSET('dateepday') ? dol_mktime(12, 0, 0, GETPOSTINT("dateepmonth"), GETPOSTINT("dateepday"), GETPOSTINT("dateepyear")) : $arrayofdates['period_end'];
1431 $amount = GETPOSTISSET('amount') ? GETPOST('amount', 'alpha') : (is_numeric($salaryindoc['net_to_pay'] ?? null) ? price((float) $salaryindoc['net_to_pay']) : '');
1432 $label = GETPOSTISSET('label') ? GETPOST('label', 'alphanohtml') : $langs->transnoentitiesnoconv("Salary").($datesp ? ' '.dol_print_date($datesp, '%m/%Y') : '');
1433
1434 print "\n\n";
1435 print '<div id="userpayroll" class="">';
1436
1437 // Employee
1438 print img_picto('', 'user', 'class="pictofixedwidth"').$langs->trans("Employee").'<br>';
1439 print '<span class="opacitymedium">'.$langs->trans("KeyDataFoundInDocument").' :</span> ';
1440 if (empty($salaryindoc['employee_name'])) {
1441 print '<span class="warning">'.$langs->trans("NoDataRelatedTo").'</span>';
1442 } else {
1443 print dolPrintLabel($salaryindoc['employee_name']);
1444 }
1445 print '<br><br>';
1446 print $langs->trans("WillUse").' ';
1447 print $form->select_dolusers(GETPOSTINT('usersalaryid') > 0 ? GETPOSTINT('usersalaryid') : -1, 'usersalaryid', $langs->transnoentitiesnoconv("Employee"), null, 0, 'hierarchyme', '', '', 0, 0, '', 0, '', 'maxwidth200 disableautoopen', 1);
1448
1449 print "\n";
1450 print '<br><br><hr style="margin: 0px"><br>';
1451 print "\n";
1452
1453 // Salary
1454 print img_picto('', 'salary', 'class="pictofixedwidth"').$langs->trans("Salary").'<br>';
1455 print '<span class="opacitymedium">'.$langs->trans("KeyDataFoundInDocument").' :</span> ';
1456 $tmpvalue = array();
1457 if ($arrayofdates['period_start'] && $arrayofdates['period_end']) {
1458 $tmpvalue[] = $langs->transnoentitiesnoconv("Period").': '.dol_print_date($arrayofdates['period_start'], 'day').' - '.dol_print_date($arrayofdates['period_end'], 'day');
1459 }
1460 if ($arrayofdates['payment_date']) {
1461 $tmpvalue[] = $langs->transnoentitiesnoconv("DatePayment").': '.dol_print_date($arrayofdates['payment_date'], 'day');
1462 }
1463 if (is_numeric($salaryindoc['gross_salary'] ?? null)) {
1464 $tmpvalue[] = $langs->transnoentitiesnoconv("GrossSalary").': '.price((float) $salaryindoc['gross_salary']);
1465 }
1466 if (is_numeric($salaryindoc['net_to_pay'] ?? null)) {
1467 $tmpvalue[] = $langs->transnoentitiesnoconv("NetToBePaid").': '.price((float) $salaryindoc['net_to_pay']);
1468 }
1469 if (!empty($salaryindoc['currency_code'])) {
1470 $tmpvalue[] = $langs->transnoentitiesnoconv("Currency").': '.dolPrintLabel($salaryindoc['currency_code']);
1471 }
1472 $s = implode(', ', $tmpvalue);
1473 if (!$s) {
1474 print '<span class="warning">'.$langs->trans("NoDataRelatedTo").'</span>';
1475 }
1476 print $s;
1477 print '<br><br>';
1478 print $langs->trans("SalaryWillBeCreated").'<br>';
1479
1480 print $langs->trans("Label").' ';
1481 print '<input type="text" class="minwidth300" name="label" id="label" value="'.dolPrintHTMLForAttribute($label).'"><br>';
1482 print $langs->trans("DateStartPeriod").' ';
1483 print $form->selectDate($datesp, 'datesp', 0, 0, 1, 'summary-result', 1, 0);
1484 print '<br>';
1485 print $langs->trans("DateEndPeriod").' ';
1486 print $form->selectDate($dateep, 'dateep', 0, 0, 1, 'summary-result', 1, 0);
1487 print '<br>';
1488 print $langs->trans("NetToBePaid").' ';
1489 print '<input type="text" class="width100 right" name="amount" id="amount" value="'.dolPrintHTMLForAttribute((string) $amount).'">';
1490 if (is_numeric($salaryindoc['gross_salary'] ?? null)) {
1491 print '<input type="hidden" name="gross_salary" value="'.((float) $salaryindoc['gross_salary']).'">';
1492 }
1493
1494 print '<br>
1495 </div>';
1496 print "\n";
1497
1498 print '<br><br><center><input type="submit" name="submit" class="button" value="'.$langs->trans("Create").'"></center>';
1499 print "\n";
1500 } elseif ($modulepart == 'chargesociales') {
1501 $langs->loadLangs(array("compta", "hrm", "bills"));
1502 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formsocialcontrib.class.php';
1503 $formsocialcontrib = new FormSocialContrib($db);
1504
1505 // Parse JSON to get information for a social or fiscal tax
1506 $taxindoc = $ai->decodeJsonIntoArray(is_array($json) ? $json : array(), 'social_contribution');
1507
1508 // Dates found in document are timestamps of the day in user timezone. We convert them into the same day at noon, as dates of compta/sociales/card.php.
1509 $arrayofdates = array();
1510 foreach (array('period_start', 'period_end', 'due_date') as $keydate) {
1511 $arrayofdates[$keydate] = '';
1512 $reg = array();
1513 if (!empty($taxindoc[$keydate]) && preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', dol_print_date($taxindoc[$keydate], '%Y-%m-%d', 'tzuserrel'), $reg)) {
1514 $arrayofdates[$keydate] = dol_mktime(12, 0, 0, (int) $reg[2], (int) $reg[3], (int) $reg[1]);
1515 }
1516 }
1517 // Values posted (when back after an error) have priority on values found in document
1518 $dateech = GETPOSTISSET('echday') ? dol_mktime(12, 0, 0, GETPOSTINT("echmonth"), GETPOSTINT("echday"), GETPOSTINT("echyear")) : $arrayofdates['due_date'];
1519 $dateperiod = GETPOSTISSET('periodday') ? dol_mktime(12, 0, 0, GETPOSTINT("periodmonth"), GETPOSTINT("periodday"), GETPOSTINT("periodyear")) : $arrayofdates['period_end'];
1520 $amount = GETPOSTISSET('amount') ? GETPOST('amount', 'alpha') : (is_numeric($taxindoc['amount'] ?? null) ? price((float) $taxindoc['amount']) : '');
1521 $label = GETPOSTISSET('label') ? GETPOST('label', 'alphanohtml') : trim((string) ($taxindoc['label'] ?? '').(!empty($taxindoc['organization']) && ($taxindoc['organization'] != ($taxindoc['label'] ?? '')) ? ' - '.$taxindoc['organization'] : ''));
1522
1523 print "\n\n";
1524 print '<div id="socialcontribution" class="">';
1525
1526 print img_picto('', 'bill', 'class="pictofixedwidth"').$langs->trans("SocialContribution").'<br>';
1527 print '<span class="opacitymedium">'.$langs->trans("KeyDataFoundInDocument").' :</span> ';
1528 $tmpvalue = array();
1529 if (!empty($taxindoc['organization'])) {
1530 $tmpvalue[] = dolPrintLabel($taxindoc['organization']);
1531 }
1532 if (!empty($taxindoc['label'])) {
1533 $tmpvalue[] = $langs->transnoentitiesnoconv("Label").': '.dolPrintLabel($taxindoc['label']);
1534 }
1535 if (!empty($taxindoc['reference'])) {
1536 $tmpvalue[] = $langs->transnoentitiesnoconv("Ref").': '.dolPrintLabel($taxindoc['reference']);
1537 }
1538 if ($arrayofdates['period_start'] || $arrayofdates['period_end']) {
1539 $tmpvalue[] = $langs->transnoentitiesnoconv("Period").': '.dol_print_date($arrayofdates['period_start'], 'day').' - '.dol_print_date($arrayofdates['period_end'], 'day');
1540 }
1541 if ($arrayofdates['due_date']) {
1542 $tmpvalue[] = $langs->transnoentitiesnoconv("DateDue").': '.dol_print_date($arrayofdates['due_date'], 'day');
1543 }
1544 if (is_numeric($taxindoc['amount'] ?? null)) {
1545 $tmpvalue[] = $langs->transnoentitiesnoconv("Amount").': '.price((float) $taxindoc['amount']);
1546 }
1547 if (!empty($taxindoc['currency_code'])) {
1548 $tmpvalue[] = $langs->transnoentitiesnoconv("Currency").': '.dolPrintLabel($taxindoc['currency_code']);
1549 }
1550 if (!empty($taxindoc['employee_name'])) {
1551 $tmpvalue[] = $langs->transnoentitiesnoconv("Employee").': '.dolPrintLabel($taxindoc['employee_name']);
1552 }
1553 $s = implode(', ', $tmpvalue);
1554 if (!$s) {
1555 print '<span class="warning">'.$langs->trans("NoDataRelatedTo").'</span>';
1556 }
1557 print $s;
1558 print '<br><br>';
1559 print $langs->trans("SocialContributionWillBeCreated").'<br>';
1560
1561 print $langs->trans("Type").' ';
1562 print $formsocialcontrib->select_type_socialcontrib(GETPOSTINT('socialcontrib') > 0 ? GETPOSTINT('socialcontrib') : 0, 'socialcontrib', 1, 0, 1, 'minwidth200 maxwidth300', 0, 1);
1563 print '<br>';
1564 print $langs->trans("Label").' ';
1565 print '<input type="text" class="minwidth300" name="label" id="label" value="'.dolPrintHTMLForAttribute($label).'"><br>';
1566 print $langs->trans("DateDue").' ';
1567 print $form->selectDate($dateech, 'ech', 0, 0, 1, 'summary-result', 1, 0);
1568 print '<br>';
1569 print $langs->trans("PeriodEndDate").' ';
1570 print $form->selectDate($dateperiod, 'period', 0, 0, 1, 'summary-result', 1, 0);
1571 print '<br>';
1572 print $langs->trans("Amount").' ';
1573 print '<input type="text" class="width100 right" name="amount" id="amount" value="'.dolPrintHTMLForAttribute((string) $amount).'"><br>';
1574 print $langs->trans("Employee").' ';
1575 print $form->select_dolusers(GETPOSTINT('usertaxid') > 0 ? GETPOSTINT('usertaxid') : -1, 'usertaxid', 1, null, 0, 'hierarchyme', '', '', 0, 0, '', 0, '', 'maxwidth200 disableautoopen', 1);
1576
1577 print '<br>
1578 </div>';
1579 print "\n";
1580
1581 print '<br><br><center><input type="submit" name="submit" class="button" value="'.$langs->trans("Create").'"></center>';
1582 print "\n";
1583 } elseif ($modulepart == 'expensereport') {
1584 $langs->loadLangs(array("trips", "hrm", "bills"));
1585
1586 // Parse JSON to get information for an expense
1587 $expenseindoc = $ai->decodeJsonIntoArray(is_array($json) ? $json : array(), 'expense');
1588
1589 // Date found in document is a timestamp of the day in user timezone. We convert it into the same day, as dates of expensereport/card.php.
1590 $dateindoc = '';
1591 $reg = array();
1592 if (!empty($expenseindoc['date']) && preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', dol_print_date($expenseindoc['date'], '%Y-%m-%d', 'tzuserrel'), $reg)) {
1593 $dateindoc = dol_mktime(0, 0, 0, (int) $reg[2], (int) $reg[3], (int) $reg[1]);
1594 }
1595 // Values posted (when back after an error) have priority on values found in document
1596 $dateexpense = GETPOSTISSET('dateday') ? dol_mktime(0, 0, 0, GETPOSTINT("datemonth"), GETPOSTINT("dateday"), GETPOSTINT("dateyear")) : $dateindoc;
1597 $amount_ttc = GETPOSTISSET('amount_ttc') ? GETPOST('amount_ttc', 'alpha') : (is_numeric($expenseindoc['total_ttc'] ?? null) ? price((float) $expenseindoc['total_ttc']) : '');
1598 $vat_rate = GETPOSTISSET('vat_rate') ? GETPOST('vat_rate', 'alpha') : (is_numeric($expenseindoc['vat_rate'] ?? null) ? price((float) $expenseindoc['vat_rate']) : '');
1599 $comments = GETPOSTISSET('comments') ? GETPOST('comments', 'alphanohtml') : trim((string) ($expenseindoc['merchant'] ?? '').(!empty($expenseindoc['label']) ? ' - '.$expenseindoc['label'] : ''), ' -');
1600 $expenseuserid = GETPOSTINT('userexpensereportid');
1601
1602 print "\n\n";
1603 print '<div id="userexpensereport" class="">';
1604
1605 // Employee
1606 print img_picto('', 'user', 'class="pictofixedwidth"').$langs->trans("Employee").'<br>';
1607 print $langs->trans("WillUse").' ';
1608 print $form->select_dolusers($expenseuserid > 0 ? $expenseuserid : -1, 'userexpensereportid', 1, null, 0, 'hierarchyme', '', '', 0, 0, '', 0, '', 'maxwidth200 disableautoopen', 1);
1609
1610 print "\n";
1611 print '<br><br><hr style="margin: 0px"><br>';
1612 print "\n";
1613
1614 // Expense
1615 print img_picto('', 'expensereport', 'class="pictofixedwidth"').$langs->trans("ExpenseReportLine").'<br>';
1616 print '<span class="opacitymedium">'.$langs->trans("KeyDataFoundInDocument").' :</span> ';
1617 $tmpvalue = array();
1618 if (!empty($expenseindoc['merchant'])) {
1619 $tmpvalue[] = dolPrintLabel($expenseindoc['merchant']);
1620 }
1621 if (!empty($expenseindoc['label'])) {
1622 $tmpvalue[] = $langs->transnoentitiesnoconv("Label").': '.dolPrintLabel($expenseindoc['label']);
1623 }
1624 if (!empty($expenseindoc['category'])) {
1625 $tmpvalue[] = $langs->transnoentitiesnoconv("Type").': '.dolPrintLabel($expenseindoc['category']);
1626 }
1627 if ($dateindoc) {
1628 $tmpvalue[] = $langs->transnoentitiesnoconv("Date").': '.dol_print_date($dateindoc, 'day');
1629 }
1630 if (is_numeric($expenseindoc['vat_rate'] ?? null)) {
1631 $tmpvalue[] = $langs->transnoentitiesnoconv("VATRate").': '.vatrate((string) $expenseindoc['vat_rate'], true);
1632 }
1633 if (is_numeric($expenseindoc['total_ttc'] ?? null)) {
1634 $tmpvalue[] = $langs->transnoentitiesnoconv("AmountTTC").': '.price((float) $expenseindoc['total_ttc']);
1635 }
1636 if (!empty($expenseindoc['currency_code'])) {
1637 $tmpvalue[] = $langs->transnoentitiesnoconv("Currency").': '.dolPrintLabel($expenseindoc['currency_code']);
1638 }
1639 $s = implode(', ', $tmpvalue);
1640 if (!$s) {
1641 print '<span class="warning">'.$langs->trans("NoDataRelatedTo").'</span>';
1642 }
1643 print $s;
1644 print '<br><br>';
1645
1646 // Show the draft expense report the line will be added to, if there is one for this employee and this date
1647 $tmpexpensereport = new ExpenseReport($db);
1648 if ($expenseuserid > 0 && $dateexpense) {
1649 $sql = "SELECT rowid FROM ".$db->prefix()."expensereport";
1650 $sql .= " WHERE fk_user_author = ".((int) $expenseuserid);
1651 $sql .= " AND fk_statut = ".((int) ExpenseReport::STATUS_DRAFT);
1652 $sql .= " AND date_debut <= '".$db->escape(dol_print_date($dateexpense, 'dayrfc'))."' AND date_fin >= '".$db->escape(dol_print_date($dateexpense, 'dayrfc'))."'";
1653 $sql .= " AND entity IN (".getEntity('expensereport').")";
1654 $sql .= " ORDER BY rowid DESC";
1655 $sql .= $db->plimit(1);
1656 $resql = $db->query($sql);
1657 if ($resql && ($obj = $db->fetch_object($resql))) {
1658 $tmpexpensereport->fetch($obj->rowid);
1659 }
1660 }
1661 if ($tmpexpensereport->id > 0) {
1662 print $langs->trans("ExpenseWillBeAddedToDraftExpenseReport").' '.$tmpexpensereport->getNomUrl(1).'<br>';
1663 } else {
1664 print $langs->trans("NewExpenseReportWillBeCreated").'<br>';
1665 }
1666
1667 print $langs->trans("Type").' ';
1668 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formexpensereport.class.php';
1669 $formexpensereport = new FormExpenseReport($db);
1670 print $formexpensereport->selectTypeExpenseReport($feetypeid > 0 ? $feetypeid : '', 'feetypeid', 1);
1671 print '<br>';
1672 print $langs->trans("Date").' ';
1673 print $form->selectDate($dateexpense, 'date', 0, 0, 1, 'summary-result', 1, 0);
1674 print '<br>';
1675 print $langs->trans("Description").' ';
1676 print '<input type="text" class="minwidth300" name="comments" id="comments" value="'.dolPrintHTMLForAttribute($comments).'"><br>';
1677 print $langs->trans("VATRate").' ';
1678 print '<input type="text" class="width50 right" name="vat_rate" id="vat_rate" value="'.dolPrintHTMLForAttribute((string) $vat_rate).'">%<br>';
1679 print $langs->trans("AmountTTC").' ';
1680 print '<input type="text" class="width100 right" name="amount_ttc" id="amount_ttc" value="'.dolPrintHTMLForAttribute((string) $amount_ttc).'">';
1681
1682 print '<br>
1683 </div>';
1684 print "\n";
1685
1686 print '<br><br><center><input type="submit" name="submit" class="button" value="'.$langs->trans("Create").'"></center>';
1687 print "\n";
1688 }
1689 print '</div>'; // end of div neutral
1690 print '</div>'; // end of div summary
1691
1692 print '<br><br>';
1693 print '<div id="divpreview">';
1694
1695 // Preview of the uploaded file (PDF is shown with the native viewer of the browser)
1696 $filetopreview = dol_sanitizeFileName(GETPOST('originalfilename', 'alphanohtml'));
1697 if ($filetopreview && dol_is_file($upload_dir.'/'.$filetopreview)) {
1698 $mimetopreview = dol_mimetype($filetopreview);
1699 $urltopreview = $_SERVER["PHP_SELF"].'?action=displayfile&originalfilename='.urlencode($filetopreview);
1700 print "\n";
1701 if ($mimetopreview == 'application/pdf' && !empty($conf->dol_use_jmobile)) {
1702 // Webviews of smartphone apps can't show a PDF, so we show its first page converted into an image (no preview if conversion fails)
1703 $fileimagetopreview = $filetopreview.'_preview.png';
1704 $ret = 1;
1705 if (!dol_is_file($upload_dir.'/'.$fileimagetopreview) || (dol_filemtime($upload_dir.'/'.$fileimagetopreview) < dol_filemtime($upload_dir.'/'.$filetopreview))) {
1706 $ret = getDolGlobalString('MAIN_DISABLE_PDF_THUMBS') ? 0 : dol_convert_file($upload_dir.'/'.$filetopreview, 'png', $upload_dir.'/'.$fileimagetopreview, '0');
1707 }
1708 if ($ret > 0) {
1709 $urlimagetopreview = $_SERVER["PHP_SELF"].'?action=displayfile&originalfilename='.urlencode($fileimagetopreview);
1710 print '<div class="center">';
1711 print '<img src="'.dolPrintHTMLForAttributeUrl($urlimagetopreview).'" alt="'.dolPrintHTMLForAttribute($langs->transnoentitiesnoconv("Preview")).'" style="max-width: 100%;">';
1712 print '</div>';
1713 }
1714 } elseif ($mimetopreview == 'application/pdf') {
1715 print '<div class="center">';
1716 print '<iframe src="'.dolPrintHTMLForAttributeUrl($urltopreview).'" title="'.dolPrintHTMLForAttribute($langs->transnoentitiesnoconv("Preview")).'" style="width: 100%; height: 800px; border: none;"></iframe>';
1717 print '</div>';
1718 } elseif (preg_match('/^image\/(png|jpeg|gif|webp|bmp)$/', $mimetopreview)) {
1719 print '<div class="center">';
1720 print '<img src="'.dolPrintHTMLForAttributeUrl($urltopreview).'" alt="'.dolPrintHTMLForAttribute($langs->transnoentitiesnoconv("Preview")).'" style="max-width: 100%;">';
1721 print '</div>';
1722 }
1723 print "\n";
1724 }
1725
1726 print '<input type="hidden" name="jsonstring" value="'.base64_encode($jsonstring).'">';
1727
1728 print '</div>';
1729 print '</form>';
1730 print "\n";
1731} elseif ($action == 'objectcreated' && is_object($createdobject)) {
1732 //print load_fiche_titre('Summary', '', 'upload');
1733
1734 print '<div class="neutral">';
1735 print '<br>';
1736 if ($createdobject instanceof Salary) {
1737 print $langs->trans("SalaryCreatedFromFile").' ';
1738 } elseif ($createdobject instanceof ChargeSociales) {
1739 print $langs->trans("SocialContributionCreatedFromFile").' ';
1740 } elseif ($createdobject instanceof ExpenseReport) {
1741 print $langs->trans("ExpenseAddedFromFile").' ';
1742 } elseif ($attachtoexistinginvoice) {
1743 print $langs->trans("FileAttachedToExistingInvoice").' ';
1744 } else {
1745 print $langs->trans("DraftInvoiceCreatedFromFile").' ';
1746 }
1747 print $createdobject->getNomUrl(1);
1748 print '<br>';
1749 print '<br>';
1750 print '</div>';
1751 print "\n";
1752} else {
1753 // Show all forms
1754 print "\n";
1755 print "<!-- Begin UploadForm -->\n";
1756 print '<form id="uploadform" enctype="multipart/form-data" method="POST" action="'.dolBuildUrl($_SERVER["PHP_SELF"]).'">';
1757 print '<input type="hidden" name="token" value="'.newToken().'">';
1758 print '<input type="hidden" name="action" value="uploadfile">';
1759 print '<input type="hidden" name="sendit" value="1">';
1760 print '<input type="hidden" name="modulepart" id="modulepart" value="">';
1761 print '<input type="hidden" name="overwritefile" value="1">';
1762
1763 print '<div class="center"><div class="center" style="padding: 10px;">';
1764 print '<style>.menu_titre { padding-top: 7px; }</style>';
1765 print '<div id="blockupload" class="center">'."\n";
1766 //print '<input name="filenamePDF" id="filenamePDF" type="hideobject">';
1767 print $uploadform;
1768
1769
1770 $accept = '.pdf,image/*';
1771 $disablemulti = 1;
1772 $perm = 1;
1773 $capture = 1;
1774
1775 $maxfilesizearray = getMaxFileSizeArray();
1776 $max = $maxfilesizearray['max'];
1777 $maxmin = $maxfilesizearray['maxmin'];
1778 $maxphptoshow = $maxfilesizearray['maxphptoshow'];
1779 $maxphptoshowparam = $maxfilesizearray['maxphptoshowparam'];
1780 $out = '';
1781 if ($maxmin > 0) {
1782 $out .= '<input type="hidden" name="MAX_FILE_SIZE" value="'.($maxmin * 1024).'">'; // MAX_FILE_SIZE must precede the field type=file
1783 }
1784 $out .= '<input class="hideobject" type="file" id="fileInput" value=""';
1785 // @phpstan-ignore-next-line
1786 $out .= ((getDolGlobalString('MAIN_DISABLE_MULTIPLE_FILEUPLOAD') || $disablemulti) ? ' name="userfile"' : ' name="userfile[]" multiple');
1787 // @phpstan-ignore-next-line
1788 $out .= (!getDolGlobalString('MAIN_UPLOAD_DOC') || empty($perm) ? ' disabled' : '');
1789 // @phpstan-ignore-next-line
1790 $out .= (!empty($accept) ? ' accept="'.$accept.'"' : ' accept=""');
1791 // @phpstan-ignore-next-line
1792 $out .= (!empty($capture) ? ' capture="capture"' : '');
1793 $out .= '>';
1794
1795 print $out;
1796
1797
1798 print "<script>
1799 $(document).ready(function() {
1800 jQuery('#supplierinvoice:not(.disableautoopen)').on('click', function(event) {
1801 console.log('Click on link supplierinvoice to open input file');
1802 console.log(event);
1803 if (!event.target.closest('.disableautoopen')) {
1804 $('#modulepart').val('invoice_supplier');
1805 $('#fileInput').click();
1806 }
1807 });
1808
1809 jQuery('#userexpensereport:not(.disableautoopen)').on('click', function(event) {
1810 console.log('Click on link userexpensereport to open input file');
1811 console.log(event);
1812 if (!event.target.closest('.disableautoopen')) {
1813 $('#modulepart').val('expensereport');
1814 $('#fileInput').click();
1815 }
1816 });
1817
1818 jQuery('#userpayroll:not(.disableautoopen)').on('click', function(event) {
1819 console.log('Click on link userpayroll to open input file');
1820 console.log(event);
1821 if (!event.target.closest('.disableautoopen')) {
1822 $('#modulepart').val('salaries');
1823 $('#fileInput').click();
1824 }
1825 });
1826
1827 jQuery('#socialcontribution:not(.disableautoopen)').on('click', function(event) {
1828 console.log('Click on link socialcontribution to open input file');
1829 console.log(event);
1830 if (!event.target.closest('.disableautoopen')) {
1831 $('#modulepart').val('chargesociales');
1832 $('#fileInput').click();
1833 }
1834 });
1835
1836 jQuery('#fileInput').on('change', function(event) {
1837 console.log(event);
1838 console.log('A file was selected, we submit the form');
1839 $('#uploadform').submit();
1840 });
1841
1842 // Drag and drop of a file on an upload zone. A counter is used because dragenter/dragleave are also fired by child elements.
1843 var modulepartforzone = {'supplierinvoice': 'invoice_supplier', 'userexpensereport': 'expensereport', 'userpayroll': 'salaries', 'socialcontribution': 'chargesociales'};
1844 jQuery('.flex-item-uploadfile').each(function() {
1845 var zone = $(this);
1846 var dragcounter = 0;
1847 zone.on('dragenter', function(ev) {
1848 var dataTypes = ev.originalEvent.dataTransfer.types;
1849 if (!dataTypes || $.inArray('Files', dataTypes) === -1) {
1850 return;
1851 }
1852 ev.preventDefault();
1853 dragcounter++;
1854 zone.addClass('highlightDragDropArea');
1855 });
1856 zone.on('dragover', function(ev) {
1857 ev.preventDefault();
1858 });
1859 zone.on('dragleave', function(ev) {
1860 dragcounter--;
1861 if (dragcounter <= 0) {
1862 dragcounter = 0;
1863 zone.removeClass('highlightDragDropArea');
1864 }
1865 });
1866 zone.on('drop', function(ev) {
1867 ev.preventDefault();
1868 dragcounter = 0;
1869 zone.removeClass('highlightDragDropArea');
1870 var files = ev.originalEvent.dataTransfer.files;
1871 if (!files || !files.length || !modulepartforzone[zone.attr('id')]) {
1872 return;
1873 }
1874 console.log('A file was dropped on '+zone.attr('id')+', we submit the form');
1875 var dt = new DataTransfer();
1876 dt.items.add(files[0]);
1877 $('#fileInput')[0].files = dt.files;
1878 $('#modulepart').val(modulepartforzone[zone.attr('id')]);
1879 $('#uploadform').submit();
1880 });
1881 });
1882 });
1883 </script>";
1884
1885 print '</div>'."\n";
1886 print '</div></div>';
1887
1888 print '</form>';
1889 print "\n<!-- End UploadForm -->\n";
1890}
1891
1892
1893// End of page
1894llxFooter();
1895$db->close();
$propal type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
Definition propal.php:281
getListOfAIServices()
Get list of available ai services.
Definition ai.lib.php:69
llxFooter($comment='', $zone='private', $disabledoutputofmessages=0)
Empty footer.
Definition wrapper.php:91
if(!defined('NOREQUIRESOC')) if(!defined( 'NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined( 'NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined( 'NOREQUIREAJAX')) llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='', $disablenofollow=0, $disablenoindex=0)
Empty header.
Definition wrapper.php:73
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class for AI feature.
Definition ai.class.php:37
Class for managing the social charges.
Class to manage ECM files.
Class to manage Trips and Expenses.
const STATUS_DRAFT
Draft status.
Class to manage suppliers invoices.
const TYPE_STANDARD
Standard invoice.
Class to manage generation of HTML components for contract module.
Class to manage generation of HTML components Only common components must be here.
Class to manage generation of HTML components for social contributions management.
Class to manage predefined suppliers products.
Class to manage products or services.
Class to manage salary payments.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage Dolibarr users.
if(! $sortfield) if(! $sortorder) $module
Definition list.php:193
global $mysoc
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition date.lib.php:626
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition date.lib.php:645
dol_move($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=1, $moreinfo=array(), $entity=null)
Move a file into another name.
dol_filemtime($pathoffile)
Return time of a file.
dol_filesize($pathoffile)
Return size of a file.
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_convert_file($fileinput, $ext='png', $fileoutput='', $page='')
Convert a PDF file into another image format.
dol_is_file($pathoffile)
Return if path is a file.
dol_now($mode='gmt')
Return date for now.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='', $useCache=true)
Return an id or code from a code or id.
vatrate($rate, $addpercent=false, $info_bits=0, $usestarfornpr=0, $html=0)
Return a string with VAT rate label formatted for view output Used into pdf and HTML pages.
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
dol_mimetype($file, $default='application/octet-stream', $mode=0)
Return MIME type of a file from its name with extension.
dolBuildUrl($url, $params=[], $addtoken=false, $anchor='')
Return path of url.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
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.
getElementProperties($elementType)
Get an array with properties of an element.
dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
Returns text escaped for inclusion into JavaScript code.
getMultidirOutput($object, $module='', $forobject=0, $mode='output')
Return the full path of the directory where a module (or an object of a module) stores its files.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
GETPOSTFLOAT($paramname, $rounding='', $option=2)
Return the value of a $_GET or $_POST supervariable, converted into float.
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
readfileLowMemory($fullpath_original_file_osencoded, $method=-1)
Return a file on output using a low memory.
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.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
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...
get_localtax($vatrate, $local, $thirdparty_buyer=null, $thirdparty_seller=null, $vatnpr=0)
Return localtax rate for a particular VAT rate, when selling a product with vat $vatrate,...
get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart='')
Return a path to have a the directory according to object where files are stored.
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_getdate($timestamp, $fast=false, $forcetimezone='')
Return an array with locale date info.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='', $morecssonpicto='widthpictotitle')
Load a title with picto.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Definition html.lib.php:183
if(!defined( 'NOREQUIREMENU')) if(!empty(GETPOST('seteventmessages', 'alpha'))) if(!function_exists("llxHeader")) top_httphead($contenttype='text/html', $forcenocache=0)
Show HTTP header.
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition repair.php:165
httponly_accessforbidden($message='1', $http_response_code=403, $stringalreadysanitized=0)
Show a message to say access is forbidden and stop program.
getMaxFileSizeArray()
Return the max allowed for file upload.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.
encode($string)
Escape a text value for a vCard 4.0 (RFC 6350 section 3.4): backslash, semicolon, comma and line brea...