card-rec.php 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741
  1. <?php
  2. /* Copyright (C) 2002-2003 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004-2016 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@inodbox.com>
  5. * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
  6. * Copyright (C) 2013-2023 Juanjo Menent <jmenent@2byte.es>
  7. * Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
  8. * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
  9. * Copyright (C) 2015 Alexandre Spangaro <aspangaro@open-dsi.fr>
  10. * Copyright (C) 2016 Meziane Sof <virtualsof@yahoo.fr>
  11. * Copyright (C) 2017-2018 Frédéric France <frederic.france@netlogic.fr>
  12. *
  13. * This program is free software; you can redistribute it and/or modify
  14. * it under the terms of the GNU General Public License as published by
  15. * the Free Software Foundation; either version 3 of the License, or
  16. * (at your option) any later version.
  17. *
  18. * This program is distributed in the hope that it will be useful,
  19. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. * GNU General Public License for more details.
  22. *
  23. * You should have received a copy of the GNU General Public License
  24. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  25. */
  26. /**
  27. * \file htdocs/compta/facture/card-rec.php
  28. * \ingroup facture
  29. * \brief Page to show predefined invoice
  30. */
  31. // Load Dolibarr environment
  32. require '../../main.inc.php';
  33. require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php';
  34. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  35. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
  36. if (isModEnabled('project')) {
  37. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  38. //include_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php';
  39. }
  40. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
  41. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  42. require_once DOL_DOCUMENT_ROOT.'/core/lib/invoice.lib.php';
  43. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  44. // Load translation files required by the page
  45. $langs->loadLangs(array('bills', 'companies', 'compta', 'admin', 'other', 'products', 'banks'));
  46. $action = GETPOST('action', 'alpha');
  47. $massaction = GETPOST('massaction', 'alpha');
  48. $show_files = GETPOST('show_files', 'int');
  49. $confirm = GETPOST('confirm', 'alpha');
  50. $cancel = GETPOST('cancel', 'alpha');
  51. $toselect = GETPOST('toselect', 'array');
  52. $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'invoicetemplatelist'; // To manage different context of search
  53. // Security check
  54. $id = (GETPOST('facid', 'int') ?GETPOST('facid', 'int') : GETPOST('id', 'int'));
  55. $lineid = GETPOST('lineid', 'int');
  56. $ref = GETPOST('ref', 'alpha');
  57. if ($user->socid) {
  58. $socid = $user->socid;
  59. }
  60. $objecttype = 'facture_rec';
  61. if ($action == "create" || $action == "add") {
  62. $objecttype = '';
  63. }
  64. $projectid = GETPOST('projectid', 'int');
  65. $year_date_when = GETPOST('year_date_when');
  66. $month_date_when = GETPOST('month_date_when');
  67. $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
  68. $sortfield = GETPOST('sortfield', 'aZ09comma');
  69. $sortorder = GETPOST('sortorder', 'aZ09comma');
  70. $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
  71. if (empty($page) || $page == -1) {
  72. $page = 0;
  73. } // If $page is not defined, or '' or -1
  74. $offset = $limit * $page;
  75. if (!$sortorder) {
  76. $sortorder = 'DESC';
  77. }
  78. if (!$sortfield) {
  79. $sortfield = 'f.titre';
  80. }
  81. $pageprev = $page - 1;
  82. $pagenext = $page + 1;
  83. $object = new FactureRec($db);
  84. if (($id > 0 || $ref) && $action != 'create' && $action != 'add') {
  85. $ret = $object->fetch($id, $ref);
  86. if (!$ret) {
  87. setEventMessages($langs->trans("ErrorRecordNotFound"), null, 'errors');
  88. }
  89. }
  90. // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
  91. $hookmanager->initHooks(array('invoicereccard', 'globalcard'));
  92. $extrafields = new ExtraFields($db);
  93. // fetch optionals attributes and labels
  94. $extrafields->fetch_name_optionals_label($object->table_element);
  95. $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
  96. $permissionnote = $user->rights->facture->creer; // Used by the include of actions_setnotes.inc.php
  97. $permissiondellink = $user->rights->facture->creer; // Used by the include of actions_dellink.inc.php
  98. $permissiontoedit = $user->rights->facture->creer; // Used by the include of actions_lineupdonw.inc.php
  99. $usercanread = $user->rights->facture->lire;
  100. $usercancreate = $user->rights->facture->creer;
  101. $usercanissuepayment = $user->rights->facture->paiement;
  102. $usercandelete = $user->rights->facture->supprimer;
  103. $usercanvalidate = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $usercancreate) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->facture->invoice_advance->validate)));
  104. $usercansend = (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->facture->invoice_advance->send);
  105. $usercanreopen = (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->facture->invoice_advance->reopen);
  106. $usercanunvalidate = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($usercancreate)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->facture->invoice_advance->unvalidate)));
  107. $usercanproductignorepricemin = ((!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->produit->ignore_price_min_advance)) || empty($conf->global->MAIN_USE_ADVANCED_PERMS));
  108. $usercancreatemargin = $user->hasRight("margins", "creer");
  109. $usercanreadallmargin = $user->hasRight("margins", "liretous");
  110. $usercancreatewithdrarequest = $user->hasRight("prelevement", "bons", "creer");
  111. $now = dol_now();
  112. $error = 0;
  113. $result = restrictedArea($user, 'facture', $object->id, $objecttype);
  114. /*
  115. * Actions
  116. */
  117. if (GETPOST('cancel', 'alpha')) {
  118. $action = 'list';
  119. $massaction = '';
  120. }
  121. if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
  122. $massaction = '';
  123. }
  124. $parameters = array();
  125. $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  126. if ($reshook < 0) {
  127. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  128. }
  129. if (empty($reshook)) {
  130. if (GETPOST('cancel', 'alpha')) {
  131. $action = '';
  132. }
  133. // Selection of new fields
  134. include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
  135. // Set note
  136. include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once
  137. include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once
  138. include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once
  139. // Mass actions
  140. /*$objectclass='MyObject';
  141. $objectlabel='MyObject';
  142. $permissiontoread = $user->rights->mymodule->read;
  143. $permissiontodelete = $user->rights->mymodule->delete;
  144. $uploaddir = $conf->mymodule->dir_output;
  145. include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';*/
  146. // Create predefined invoice
  147. if ($action == 'add') {
  148. if (!GETPOST('title', 'alphanohtml')) {
  149. setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->trans("Title")), null, 'errors');
  150. $action = "create";
  151. $error++;
  152. }
  153. $frequency = GETPOST('frequency', 'int');
  154. $reyear = GETPOST('reyear', 'int');
  155. $remonth = GETPOST('remonth', 'int');
  156. $reday = GETPOST('reday', 'int');
  157. $rehour = GETPOST('rehour', 'int');
  158. $remin = GETPOST('remin', 'int');
  159. $nb_gen_max = GETPOST('nb_gen_max', 'int');
  160. //if (empty($nb_gen_max)) $nb_gen_max =0;
  161. if (GETPOST('frequency', 'int')) {
  162. if (empty($reyear) || empty($remonth) || empty($reday)) {
  163. setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->trans("Date")), null, 'errors');
  164. $action = "create";
  165. $error++;
  166. }
  167. /*if ($nb_gen_max === '') {
  168. setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->trans("MaxPeriodNumber")), null, 'errors');
  169. $action = "create";
  170. $error++;
  171. }*/
  172. }
  173. if (!$error) {
  174. $object->titre = GETPOST('title', 'alphanohtml'); // deprecated
  175. $object->title = GETPOST('title', 'alphanohtml');
  176. $object->note_private = GETPOST('note_private', 'restricthtml');
  177. $object->note_public = GETPOST('note_public', 'restricthtml');
  178. $object->model_pdf = GETPOST('modelpdf', 'alphanohtml');
  179. $object->usenewprice = GETPOST('usenewprice', 'alphanohtml');
  180. $object->mode_reglement_id = GETPOST('mode_reglement_id', 'int');
  181. $object->cond_reglement_id = GETPOST('cond_reglement_id', 'int');
  182. $object->frequency = $frequency;
  183. $object->unit_frequency = GETPOST('unit_frequency', 'alpha');
  184. $object->nb_gen_max = $nb_gen_max;
  185. $object->auto_validate = GETPOST('auto_validate', 'int');
  186. $object->generate_pdf = GETPOST('generate_pdf', 'int');
  187. $object->fk_project = $projectid;
  188. $date_next_execution = dol_mktime($rehour, $remin, 0, $remonth, $reday, $reyear);
  189. $object->date_when = $date_next_execution;
  190. // Get first contract linked to invoice used to generate template (facid is id of source invoice)
  191. if (GETPOST('facid', 'int') > 0) {
  192. $srcObject = new Facture($db);
  193. $srcObject->fetch(GETPOST('facid', 'int'));
  194. $srcObject->fetchObjectLinked();
  195. if (!empty($srcObject->linkedObjectsIds['contrat'])) {
  196. $contractidid = reset($srcObject->linkedObjectsIds['contrat']);
  197. $object->origin = 'contrat';
  198. $object->origin_id = $contractidid;
  199. $object->linked_objects[$object->origin] = $object->origin_id;
  200. }
  201. }
  202. $db->begin();
  203. $oldinvoice = new Facture($db);
  204. $oldinvoice->fetch(GETPOST('facid', 'int'));
  205. $result = $object->create($user, $oldinvoice->id);
  206. if ($result > 0) {
  207. $result = $oldinvoice->delete($user, 1);
  208. if ($result < 0) {
  209. $error++;
  210. setEventMessages($oldinvoice->error, $oldinvoice->errors, 'errors');
  211. $action = "create";
  212. }
  213. } else {
  214. $error++;
  215. setEventMessages($object->error, $object->errors, 'errors');
  216. $action = "create";
  217. }
  218. if (!$error) {
  219. $db->commit();
  220. header("Location: ".$_SERVER['PHP_SELF'].'?facid='.$object->id);
  221. exit;
  222. } else {
  223. $db->rollback();
  224. $action = "create";
  225. }
  226. }
  227. }
  228. // Delete
  229. if ($action == 'confirm_deleteinvoice' && $confirm == 'yes' && $user->rights->facture->supprimer) {
  230. $object->delete($user);
  231. header("Location: ".DOL_URL_ROOT.'/compta/facture/invoicetemplate_list.php');
  232. exit;
  233. }
  234. // Update field
  235. // Set condition
  236. if ($action == 'setconditions' && $user->rights->facture->creer) {
  237. $result = $object->setPaymentTerms(GETPOST('cond_reglement_id', 'int'));
  238. } elseif ($action == 'setmode' && $user->rights->facture->creer) {
  239. // Set mode
  240. $result = $object->setPaymentMethods(GETPOST('mode_reglement_id', 'int'));
  241. } elseif ($action == 'classin' && $user->rights->facture->creer) {
  242. // Set project
  243. $object->setProject(GETPOST('projectid', 'int'));
  244. } elseif ($action == 'setref' && $user->rights->facture->creer) {
  245. // Set bank account
  246. //var_dump(GETPOST('ref', 'alpha'));exit;
  247. $result = $object->setValueFrom('titre', $ref, '', null, 'text', '', $user, 'BILLREC_MODIFY');
  248. if ($result > 0) {
  249. $object->titre = $ref; // deprecated
  250. $object->title = $ref;
  251. $object->ref = $object->title;
  252. } else {
  253. $error++;
  254. if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  255. $langs->load("errors");
  256. setEventMessages($langs->trans('ErrorRefAlreadyExists', $ref), null, 'errors');
  257. } else {
  258. setEventMessages($object->error, $object->errors, 'errors');
  259. }
  260. }
  261. } elseif ($action == 'setbankaccount' && $user->rights->facture->creer) {
  262. // Set bank account
  263. $result = $object->setBankAccount(GETPOST('fk_account', 'int'));
  264. } elseif ($action == 'setfrequency' && $user->rights->facture->creer) {
  265. // Set frequency and unit frequency
  266. $object->setFrequencyAndUnit(GETPOST('frequency', 'int'), GETPOST('unit_frequency', 'alpha'));
  267. } elseif ($action == 'setdate_when' && $user->rights->facture->creer) {
  268. // Set next date of execution
  269. $date = dol_mktime(GETPOST('date_whenhour'), GETPOST('date_whenmin'), 0, GETPOST('date_whenmonth'), GETPOST('date_whenday'), GETPOST('date_whenyear'));
  270. if (!empty($date)) {
  271. $object->setNextDate($date);
  272. }
  273. } elseif ($action == 'setnb_gen_max' && $user->rights->facture->creer) {
  274. // Set max period
  275. $object->setMaxPeriod(GETPOST('nb_gen_max', 'int'));
  276. } elseif ($action == 'setauto_validate' && $user->rights->facture->creer) {
  277. // Set auto validate
  278. $object->setAutoValidate(GETPOST('auto_validate', 'int'));
  279. } elseif ($action == 'setgenerate_pdf' && $user->rights->facture->creer) {
  280. // Set generate pdf
  281. $object->setGeneratepdf(GETPOST('generate_pdf', 'int'));
  282. } elseif ($action == 'setmodelpdf' && $user->rights->facture->creer) {
  283. // Set model pdf
  284. $object->setModelpdf(GETPOST('modelpdf', 'alpha'));
  285. } elseif ($action == 'disable' && $user->rights->facture->creer) {
  286. // Set status disabled
  287. $db->begin();
  288. $object->fetch($id);
  289. $res = $object->setValueFrom('suspended', 1);
  290. if ($res <= 0) {
  291. $error++;
  292. }
  293. if (!$error) {
  294. $db->commit();
  295. } else {
  296. $db->rollback();
  297. setEventMessages($object->error, $object->errors, 'errors');
  298. }
  299. } elseif ($action == 'enable' && $user->rights->facture->creer) {
  300. // Set status enabled
  301. $db->begin();
  302. $object->fetch($id);
  303. $res = $object->setValueFrom('suspended', 0);
  304. if ($res <= 0) {
  305. $error++;
  306. }
  307. if (!$error) {
  308. $db->commit();
  309. } else {
  310. $db->rollback();
  311. setEventMessages($object->error, $object->errors, 'errors');
  312. }
  313. } elseif ($action == 'setmulticurrencycode' && $usercancreate) {
  314. // Multicurrency Code
  315. $result = $object->setMulticurrencyCode(GETPOST('multicurrency_code', 'alpha'));
  316. } elseif ($action == 'setmulticurrencyrate' && $usercancreate) {
  317. // Multicurrency rate
  318. $result = $object->setMulticurrencyRate(price2num(GETPOST('multicurrency_tx')), GETPOST('calculation_mode', 'int'));
  319. }
  320. // Delete line
  321. if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->facture->creer) {
  322. $object->fetch($id);
  323. $object->fetch_thirdparty();
  324. $db->begin();
  325. $line = new FactureLigneRec($db);
  326. // For triggers
  327. $line->id = $lineid;
  328. if ($line->delete($user) > 0) {
  329. $result = $object->update_price(1);
  330. if ($result > 0) {
  331. $db->commit();
  332. $object->fetch($object->id); // Reload lines
  333. } else {
  334. $db->rollback();
  335. setEventMessages($db->lasterror(), null, 'errors');
  336. }
  337. } else {
  338. $db->rollback();
  339. setEventMessages($line->error, $line->errors, 'errors');
  340. }
  341. } elseif ($action == 'update_extras') {
  342. $object->oldcopy = dol_clone($object);
  343. // Fill array 'array_options' with data from update form
  344. $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml'));
  345. if ($ret < 0) {
  346. $error++;
  347. }
  348. if (!$error) {
  349. $result = $object->insertExtraFields('BILLREC_MODIFY');
  350. if ($result < 0) {
  351. setEventMessages($object->error, $object->errors, 'errors');
  352. $error++;
  353. }
  354. }
  355. }
  356. // Add a new line
  357. if ($action == 'addline' && $user->rights->facture->creer) {
  358. $langs->load('errors');
  359. $error = 0;
  360. // Set if we used free entry or predefined product
  361. $predef = '';
  362. $product_desc = (GETPOSTISSET('dp_desc') ? GETPOST('dp_desc', 'restricthtml') : '');
  363. $price_ht = price2num(GETPOST('price_ht'), 'MU', 2);
  364. $price_ht_devise = price2num(GETPOST('multicurrency_price_ht'), 'CU', 2);
  365. $prod_entry_mode = GETPOST('prod_entry_mode', 'alpha');
  366. if ($prod_entry_mode == 'free') {
  367. $idprod = 0;
  368. $tva_tx = (GETPOST('tva_tx', 'alpha') ? GETPOST('tva_tx', 'alpha') : 0);
  369. } else {
  370. $idprod = GETPOST('idprod', 'int');
  371. $tva_tx = '';
  372. }
  373. $qty = price2num(GETPOST('qty'.$predef, 'alpha'), 'MS', 2);
  374. $remise_percent = price2num(GETPOST('remise_percent'.$predef), '', 2);
  375. if (empty($remise_percent)) {
  376. $remise_percent = 0;
  377. }
  378. // Extrafields
  379. $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
  380. $array_options = $extrafields->getOptionalsFromPost($object->table_element_line, $predef);
  381. // Unset extrafield
  382. if (is_array($extralabelsline)) {
  383. // Get extra fields
  384. foreach ($extralabelsline as $key => $value) {
  385. unset($_POST["options_".$key.$predef]);
  386. }
  387. }
  388. if ((empty($idprod) || $idprod < 0) && ($price_ht < 0) && ($qty < 0)) {
  389. setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPriceHT'), $langs->transnoentitiesnoconv('Qty')), null, 'errors');
  390. $error++;
  391. }
  392. if ($prod_entry_mode == 'free' && (empty($idprod) || $idprod < 0) && GETPOST('type') < 0) {
  393. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors');
  394. $error++;
  395. }
  396. if ($prod_entry_mode == 'free' && (empty($idprod) || $idprod < 0) && (!($price_ht >= 0) || $price_ht == '')) { // Unit price can be 0 but not ''
  397. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("UnitPriceHT")), null, 'errors');
  398. $error++;
  399. }
  400. if ($qty == '') {
  401. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors');
  402. $error++;
  403. }
  404. if ($prod_entry_mode == 'free' && (empty($idprod) || $idprod < 0) && empty($product_desc)) {
  405. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors');
  406. $error++;
  407. }
  408. if ($qty < 0) {
  409. $langs->load("errors");
  410. setEventMessages($langs->trans('ErrorQtyForCustomerInvoiceCantBeNegative'), null, 'errors');
  411. $error++;
  412. }
  413. if (!$error && ($qty >= 0) && (!empty($product_desc) || (!empty($idprod) && $idprod > 0))) {
  414. $ret = $object->fetch($id);
  415. if ($ret < 0) {
  416. dol_print_error($db, $object->error);
  417. exit();
  418. }
  419. $ret = $object->fetch_thirdparty();
  420. // Clean parameters
  421. $date_start = dol_mktime(GETPOST('date_start'.$predef.'hour'), GETPOST('date_start'.$predef.'min'), GETPOST('date_start'.$predef.'sec'), GETPOST('date_start'.$predef.'month'), GETPOST('date_start'.$predef.'day'), GETPOST('date_start'.$predef.'year'));
  422. $date_end = dol_mktime(GETPOST('date_end'.$predef.'hour'), GETPOST('date_end'.$predef.'min'), GETPOST('date_end'.$predef.'sec'), GETPOST('date_end'.$predef.'month'), GETPOST('date_end'.$predef.'day'), GETPOST('date_end'.$predef.'year'));
  423. $price_base_type = (GETPOST('price_base_type', 'alpha') ? GETPOST('price_base_type', 'alpha') : 'HT');
  424. // Define special_code for special lines
  425. $special_code = 0;
  426. // if (!GETPOST('qty')) $special_code=3; // Options should not exists on invoices
  427. // Ecrase $pu par celui du produit
  428. // Ecrase $desc par celui du produit
  429. // Ecrase $tva_tx par celui du produit
  430. // Ecrase $base_price_type par celui du produit
  431. // Replaces $fk_unit with the product's
  432. if (!empty($idprod) && $idprod > 0) {
  433. $prod = new Product($db);
  434. $prod->fetch($idprod);
  435. $label = ((GETPOST('product_label') && GETPOST('product_label') != $prod->label) ? GETPOST('product_label') : '');
  436. // Update if prices fields are defined
  437. $tva_tx = get_default_tva($mysoc, $object->thirdparty, $prod->id);
  438. $tva_npr = get_default_npr($mysoc, $object->thirdparty, $prod->id);
  439. if (empty($tva_tx)) {
  440. $tva_npr = 0;
  441. }
  442. // Search the correct price into loaded array product_price_by_qty using id of array retrieved into POST['pqp'].
  443. $pqp = (GETPOST('pbq', 'int') ? GETPOST('pbq', 'int') : 0);
  444. $datapriceofproduct = $prod->getSellPrice($mysoc, $object->thirdparty, $pqp);
  445. $pu_ht = $datapriceofproduct['pu_ht'];
  446. $pu_ttc = $datapriceofproduct['pu_ttc'];
  447. $price_min = $datapriceofproduct['price_min'];
  448. $price_base_type = $datapriceofproduct['price_base_type'];
  449. $tva_tx = $datapriceofproduct['tva_tx'];
  450. $tva_npr = $datapriceofproduct['tva_npr'];
  451. $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $tva_tx));
  452. $tmpprodvat = price2num(preg_replace('/\s*\(.*\)/', '', $prod->tva_tx));
  453. // if price ht was forced (ie: from gui when calculated by margin rate and cost price). TODO Why this ?
  454. if (!empty($price_ht)) {
  455. $pu_ht = price2num($price_ht, 'MU');
  456. $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU');
  457. } elseif ($tmpvat != $tmpprodvat) {
  458. // On reevalue prix selon taux tva car taux tva transaction peut etre different
  459. // de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur).
  460. if ($price_base_type != 'HT') {
  461. $pu_ht = price2num($pu_ttc / (1 + ($tmpvat / 100)), 'MU');
  462. } else {
  463. $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU');
  464. }
  465. }
  466. $desc = '';
  467. // Define output language
  468. if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
  469. $outputlangs = $langs;
  470. $newlang = '';
  471. if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  472. $newlang = GETPOST('lang_id', 'aZ09');
  473. }
  474. if (empty($newlang)) {
  475. $newlang = $object->thirdparty->default_lang;
  476. }
  477. if (!empty($newlang)) {
  478. $outputlangs = new Translate("", $conf);
  479. $outputlangs->setDefaultLang($newlang);
  480. }
  481. $desc = (!empty($prod->multilangs [$outputlangs->defaultlang] ["description"])) ? $prod->multilangs [$outputlangs->defaultlang] ["description"] : $prod->description;
  482. } else {
  483. $desc = $prod->description;
  484. }
  485. $desc = dol_concatdesc($desc, $product_desc);
  486. // Add custom code and origin country into description
  487. if (empty($conf->global->MAIN_PRODUCT_DISABLE_CUSTOMCOUNTRYCODE) && (!empty($prod->customcode) || !empty($prod->country_code))) {
  488. $tmptxt = '(';
  489. // Define output language
  490. if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
  491. $outputlangs = $langs;
  492. $newlang = '';
  493. if (empty($newlang) && GETPOST('lang_id', 'alpha')) {
  494. $newlang = GETPOST('lang_id', 'alpha');
  495. }
  496. if (empty($newlang)) {
  497. $newlang = $object->thirdparty->default_lang;
  498. }
  499. if (!empty($newlang)) {
  500. $outputlangs = new Translate("", $conf);
  501. $outputlangs->setDefaultLang($newlang);
  502. $outputlangs->load('products');
  503. }
  504. if (!empty($prod->customcode)) {
  505. $tmptxt .= $outputlangs->transnoentitiesnoconv("CustomCode").': '.$prod->customcode;
  506. }
  507. if (!empty($prod->customcode) && !empty($prod->country_code)) {
  508. $tmptxt .= ' - ';
  509. }
  510. if (!empty($prod->country_code)) {
  511. $tmptxt .= $outputlangs->transnoentitiesnoconv("CountryOrigin").': '.getCountry($prod->country_code, 0, $db, $outputlangs, 0);
  512. }
  513. } else {
  514. if (!empty($prod->customcode)) {
  515. $tmptxt .= $langs->transnoentitiesnoconv("CustomCode").': '.$prod->customcode;
  516. }
  517. if (!empty($prod->customcode) && !empty($prod->country_code)) {
  518. $tmptxt .= ' - ';
  519. }
  520. if (!empty($prod->country_code)) {
  521. $tmptxt .= $langs->transnoentitiesnoconv("CountryOrigin").': '.getCountry($prod->country_code, 0, $db, $langs, 0);
  522. }
  523. }
  524. $tmptxt .= ')';
  525. $desc = dol_concatdesc($desc, $tmptxt);
  526. }
  527. $type = $prod->type;
  528. $fk_unit = $prod->fk_unit;
  529. } else {
  530. $pu_ht = price2num($price_ht, 'MU');
  531. $pu_ttc = price2num(GETPOST('price_ttc'), 'MU');
  532. $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0);
  533. $tva_tx = str_replace('*', '', $tva_tx);
  534. if (empty($tva_tx)) {
  535. $tva_npr = 0;
  536. }
  537. $label = (GETPOST('product_label') ? GETPOST('product_label') : '');
  538. $desc = $product_desc;
  539. $type = GETPOST('type');
  540. $fk_unit = GETPOST('units', 'alpha');
  541. }
  542. $date_start_fill = GETPOST('date_start_fill', 'int');
  543. $date_end_fill = GETPOST('date_end_fill', 'int');
  544. // Margin
  545. $fournprice = price2num(GETPOST('fournprice'.$predef) ? GETPOST('fournprice'.$predef) : '');
  546. $buyingprice = price2num(GETPOST('buying_price'.$predef) != '' ? GETPOST('buying_price'.$predef) : ''); // If buying_price is '0', we must keep this value
  547. // Local Taxes
  548. $localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty, $mysoc, $tva_npr);
  549. $localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty, $mysoc, $tva_npr);
  550. $info_bits = 0;
  551. if ($tva_npr) {
  552. $info_bits |= 0x01;
  553. }
  554. if ($usercanproductignorepricemin && (!empty($price_min) && (price2num($pu_ht) * (1 - price2num($remise_percent) / 100) < price2num($price_min)))) {
  555. $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, - 1, $conf->currency));
  556. setEventMessages($mesg, null, 'errors');
  557. } else {
  558. // Insert line
  559. $result = $object->addline($desc, $pu_ht, $qty, $tva_tx, $localtax1_tx, $localtax2_tx, $idprod, $remise_percent, $price_base_type, $info_bits, '', $pu_ttc, $type, -1, $special_code, $label, $fk_unit, 0, $date_start_fill, $date_end_fill, $fournprice, $buyingprice);
  560. if ($result > 0) {
  561. // Define output language and generate document
  562. /*if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
  563. {
  564. // Define output language
  565. $outputlangs = $langs;
  566. $newlang = '';
  567. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09');
  568. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) $newlang = $object->thirdparty->default_lang;
  569. if (!empty($newlang)) {
  570. $outputlangs = new Translate("", $conf);
  571. $outputlangs->setDefaultLang($newlang);
  572. }
  573. $model=$object->model_pdf;
  574. $ret = $object->fetch($id); // Reload to get new records
  575. $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  576. if ($result < 0) setEventMessages($object->error, $object->errors, 'errors');
  577. }*/
  578. $object->fetch($object->id); // Reload lines
  579. unset($_POST['prod_entry_mode']);
  580. unset($_POST['qty']);
  581. unset($_POST['type']);
  582. unset($_POST['remise_percent']);
  583. unset($_POST['price_ht']);
  584. unset($_POST['multicurrency_price_ht']);
  585. unset($_POST['price_ttc']);
  586. unset($_POST['tva_tx']);
  587. unset($_POST['product_ref']);
  588. unset($_POST['product_label']);
  589. unset($_POST['product_desc']);
  590. unset($_POST['fournprice']);
  591. unset($_POST['buying_price']);
  592. unset($_POST['np_marginRate']);
  593. unset($_POST['np_markRate']);
  594. unset($_POST['dp_desc']);
  595. unset($_POST['idprod']);
  596. unset($_POST['units']);
  597. unset($_POST['date_starthour']);
  598. unset($_POST['date_startmin']);
  599. unset($_POST['date_startsec']);
  600. unset($_POST['date_startday']);
  601. unset($_POST['date_startmonth']);
  602. unset($_POST['date_startyear']);
  603. unset($_POST['date_endhour']);
  604. unset($_POST['date_endmin']);
  605. unset($_POST['date_endsec']);
  606. unset($_POST['date_endday']);
  607. unset($_POST['date_endmonth']);
  608. unset($_POST['date_endyear']);
  609. unset($_POST['date_start_fill']);
  610. unset($_POST['date_end_fill']);
  611. unset($_POST['situations']);
  612. unset($_POST['progress']);
  613. } else {
  614. setEventMessages($object->error, $object->errors, 'errors');
  615. }
  616. $action = '';
  617. }
  618. }
  619. } elseif ($action == 'updateline' && $usercancreate && !GETPOST('cancel', 'alpha')) {
  620. if (!$object->fetch($id) > 0) {
  621. dol_print_error($db);
  622. }
  623. $object->fetch_thirdparty();
  624. // Clean parameters
  625. $date_start = '';
  626. $date_end = '';
  627. //$date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear'));
  628. //$date_end = dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear'));
  629. $description = dol_htmlcleanlastbr(GETPOST('product_desc', 'restricthtml') ? GETPOST('product_desc', 'restricthtml') : GETPOST('desc', 'restricthtml'));
  630. $pu_ht = price2num(GETPOST('price_ht'), '', 2);
  631. $vat_rate = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0);
  632. $qty = GETPOST('qty');
  633. $pu_ht_devise = price2num(GETPOST('multicurrency_subprice'), '', 2);
  634. // Define info_bits
  635. $info_bits = 0;
  636. if (preg_match('/\*/', $vat_rate)) {
  637. $info_bits |= 0x01;
  638. }
  639. // Define vat_rate
  640. $vat_rate = str_replace('*', '', $vat_rate);
  641. $localtax1_rate = get_localtax($vat_rate, 1, $object->thirdparty);
  642. $localtax2_rate = get_localtax($vat_rate, 2, $object->thirdparty);
  643. // Add buying price
  644. $fournprice = price2num(GETPOST('fournprice') ? GETPOST('fournprice') : '');
  645. $buyingprice = price2num(GETPOST('buying_price') != '' ? GETPOST('buying_price') : ''); // If buying_price is '0', we muste keep this value
  646. // Extrafields
  647. $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
  648. $array_options = $extrafields->getOptionalsFromPost($object->table_element_line);
  649. $objectline = new FactureLigneRec($db);
  650. if ($objectline->fetch(GETPOST('lineid', 'int'))) {
  651. $objectline->array_options = $array_options;
  652. $result = $objectline->insertExtraFields();
  653. if ($result < 0) {
  654. setEventMessages($langs->trans('Error').$result, null, 'errors');
  655. }
  656. }
  657. $position = ($objectline->rang >= 0 ? $objectline->rang : 0);
  658. // Unset extrafield
  659. if (is_array($extralabelsline)) {
  660. // Get extra fields
  661. foreach ($extralabelsline as $key => $value) {
  662. unset($_POST["options_".$key]);
  663. }
  664. }
  665. // Define special_code for special lines
  666. $special_code = GETPOST('special_code', 'int');
  667. if ($special_code == 3) {
  668. $special_code = 0; // Options should not exists on invoices
  669. }
  670. /*$line = new FactureLigne($db);
  671. $line->fetch(GETPOST('lineid', 'int'));
  672. $percent = $line->get_prev_progress($object->id);
  673. if (GETPOST('progress') < $percent)
  674. {
  675. $mesg = '<div class="warning">' . $langs->trans("CantBeLessThanMinPercent") . '</div>';
  676. setEventMessages($mesg, null, 'warnings');
  677. $error++;
  678. $result = -1;
  679. }*/
  680. $remise_percent = price2num(GETPOST('remise_percent'), '', 2);
  681. if (empty($remise_percent)) {
  682. $remise_percent = 0;
  683. }
  684. // Check minimum price
  685. $productid = GETPOST('productid', 'int');
  686. if (!empty($productid)) {
  687. $product = new Product($db);
  688. $product->fetch($productid);
  689. $type = $product->type;
  690. $price_min = $product->price_min;
  691. if (!empty($conf->global->PRODUIT_MULTIPRICES) && !empty($object->thirdparty->price_level)) {
  692. $price_min = $product->multiprices_min[$object->thirdparty->price_level];
  693. }
  694. $label = ((GETPOST('update_label') && GETPOST('product_label')) ? GETPOST('product_label') : '');
  695. $typeinvoice = Facture::TYPE_STANDARD;
  696. // Check price is not lower than minimum (check is done only for standard or replacement invoices)
  697. if (((!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->produit->ignore_price_min_advance)) || empty($conf->global->MAIN_USE_ADVANCED_PERMS)) && (($typeinvoice == Facture::TYPE_STANDARD || $typeinvoice == Facture::TYPE_REPLACEMENT) && $price_min && ((float) price2num($pu_ht) * (1 - (float) $remise_percent / 100) < (float) price2num($price_min)))) {
  698. setEventMessages($langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, - 1, $conf->currency)), null, 'errors');
  699. $error++;
  700. }
  701. } else {
  702. $type = GETPOST('type', 'int');
  703. $label = (GETPOST('product_label') ? GETPOST('product_label') : '');
  704. // Check parameters
  705. if (GETPOST('type', 'int') < 0) {
  706. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
  707. $error++;
  708. }
  709. }
  710. if ($qty < 0) {
  711. $langs->load("errors");
  712. setEventMessages($langs->trans('ErrorQtyForCustomerInvoiceCantBeNegative'), null, 'errors');
  713. $error++;
  714. }
  715. $date_start_fill = GETPOST('date_start_fill', 'int');
  716. $date_end_fill = GETPOST('date_end_fill', 'int');
  717. // Update line
  718. if (!$error) {
  719. $result = $object->updateline(
  720. GETPOST('lineid', 'int'),
  721. $description,
  722. $pu_ht,
  723. $qty,
  724. $vat_rate,
  725. $localtax1_rate,
  726. $localtax1_rate,
  727. GETPOST('productid', 'int'),
  728. $remise_percent,
  729. 'HT',
  730. $info_bits,
  731. 0,
  732. 0,
  733. $type,
  734. $position,
  735. $special_code,
  736. $label,
  737. GETPOST('units'),
  738. $pu_ht_devise,
  739. 0,
  740. $date_start_fill,
  741. $date_end_fill,
  742. $fournprice,
  743. $buyingprice
  744. );
  745. if ($result >= 0) {
  746. /*if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  747. // Define output language
  748. $outputlangs = $langs;
  749. $newlang = '';
  750. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id','aZ09'))
  751. $newlang = GETPOST('lang_id','aZ09');
  752. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang))
  753. $newlang = $object->thirdparty->default_lang;
  754. if (!empty($newlang)) {
  755. $outputlangs = new Translate("", $conf);
  756. $outputlangs->setDefaultLang($newlang);
  757. }
  758. $ret = $object->fetch($id); // Reload to get new records
  759. $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  760. }*/
  761. $object->fetch($object->id); // Reload lines
  762. unset($_POST['qty']);
  763. unset($_POST['type']);
  764. unset($_POST['productid']);
  765. unset($_POST['remise_percent']);
  766. unset($_POST['price_ht']);
  767. unset($_POST['multicurrency_price_ht']);
  768. unset($_POST['price_ttc']);
  769. unset($_POST['tva_tx']);
  770. unset($_POST['product_ref']);
  771. unset($_POST['product_label']);
  772. unset($_POST['product_desc']);
  773. unset($_POST['fournprice']);
  774. unset($_POST['buying_price']);
  775. unset($_POST['np_marginRate']);
  776. unset($_POST['np_markRate']);
  777. unset($_POST['dp_desc']);
  778. unset($_POST['idprod']);
  779. unset($_POST['units']);
  780. unset($_POST['date_starthour']);
  781. unset($_POST['date_startmin']);
  782. unset($_POST['date_startsec']);
  783. unset($_POST['date_startday']);
  784. unset($_POST['date_startmonth']);
  785. unset($_POST['date_startyear']);
  786. unset($_POST['date_endhour']);
  787. unset($_POST['date_endmin']);
  788. unset($_POST['date_endsec']);
  789. unset($_POST['date_endday']);
  790. unset($_POST['date_endmonth']);
  791. unset($_POST['date_endyear']);
  792. unset($_POST['situations']);
  793. unset($_POST['progress']);
  794. } else {
  795. setEventMessages($object->error, $object->errors, 'errors');
  796. }
  797. }
  798. }
  799. }
  800. /*
  801. * View
  802. */
  803. $help_url = '';
  804. llxHeader('', $langs->trans("RepeatableInvoices"), $help_url);
  805. $form = new Form($db);
  806. $formother = new FormOther($db);
  807. if (isModEnabled('project')) {
  808. $formproject = new FormProjets($db);
  809. }
  810. $companystatic = new Societe($db);
  811. $invoicerectmp = new FactureRec($db);
  812. $now = dol_now();
  813. $nowlasthour = dol_get_last_hour($now);
  814. /*
  815. * Create mode
  816. */
  817. if ($action == 'create') {
  818. print load_fiche_titre($langs->trans("CreateRepeatableInvoice"), '', 'bill');
  819. $object = new Facture($db); // Source invoice
  820. $product_static = new Product($db);
  821. if ($object->fetch($id, $ref) > 0) {
  822. $result = $object->getLinesArray();
  823. print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
  824. print '<input type="hidden" name="token" value="'.newToken().'">';
  825. print '<input type="hidden" name="action" value="add">';
  826. print '<input type="hidden" name="facid" value="'.$object->id.'">';
  827. print dol_get_fiche_head(null, '', '', 0);
  828. $rowspan = 4;
  829. if (isModEnabled('project')) {
  830. $rowspan++;
  831. }
  832. if ($object->fk_account > 0) {
  833. $rowspan++;
  834. }
  835. print '<table class="border centpercent">';
  836. $object->fetch_thirdparty();
  837. // Title
  838. print '<tr><td class="titlefieldcreate fieldrequired">'.$langs->trans("Title").'</td><td>';
  839. print '<input class="flat quatrevingtpercent" type="text" name="title" value="'.dol_escape_htmltag(GETPOST("title", 'alphanohtml')).'" autofocus>';
  840. print '</td></tr>';
  841. // Third party
  842. print '<tr><td class="titlefieldcreate">'.$langs->trans("Customer").'</td><td>'.$object->thirdparty->getNomUrl(1, 'customer').'</td>';
  843. print '</tr>';
  844. $note_public = GETPOSTISSET('note_public') ? GETPOST('note_public', 'restricthtml') : $object->note_public;
  845. $note_private = GETPOSTISSET('note_private') ? GETPOST('note_private', 'restricthtml') : $object->note_private;
  846. // Help of substitution key
  847. $substitutionarray = getCommonSubstitutionArray($langs, 2, null, $object);
  848. $substitutionarray['__INVOICE_PREVIOUS_MONTH__'] = $langs->trans("PreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, -1, 'm'), '%m').')';
  849. $substitutionarray['__INVOICE_MONTH__'] = $langs->trans("MonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($object->date, '%m').')';
  850. $substitutionarray['__INVOICE_NEXT_MONTH__'] = $langs->trans("NextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, 1, 'm'), '%m').')';
  851. $substitutionarray['__INVOICE_PREVIOUS_MONTH_TEXT__'] = $langs->trans("TextPreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, -1, 'm'), '%B').')';
  852. $substitutionarray['__INVOICE_MONTH_TEXT__'] = $langs->trans("TextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($object->date, '%B').')';
  853. $substitutionarray['__INVOICE_NEXT_MONTH_TEXT__'] = $langs->trans("TextNextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, 1, 'm'), '%B').')';
  854. $substitutionarray['__INVOICE_PREVIOUS_YEAR__'] = $langs->trans("PreviousYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, -1, 'y'), '%Y').')';
  855. $substitutionarray['__INVOICE_YEAR__'] = $langs->trans("YearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($object->date, '%Y').')';
  856. $substitutionarray['__INVOICE_NEXT_YEAR__'] = $langs->trans("NextYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, 1, 'y'), '%Y').')';
  857. // Only on template invoices
  858. $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = $langs->trans("DateNextInvoiceBeforeGen").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, 1, 'm'), 'dayhour').')';
  859. $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = $langs->trans("DateNextInvoiceAfterGen").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, 2, 'm'), 'dayhour').')';
  860. $substitutionarray['__INVOICE_COUNTER_CURRENT__'] = $langs->trans("Count");
  861. $substitutionarray['__INVOICE_COUNTER_MAX__'] = $langs->trans("MaxPeriodNumber");
  862. $htmltext = '<i>'.$langs->trans("FollowingConstantsWillBeSubstituted").':<br>';
  863. foreach ($substitutionarray as $key => $val) {
  864. $htmltext .= $key.' = '.$langs->trans($val).'<br>';
  865. }
  866. $htmltext .= '</i>';
  867. // Public note
  868. print '<tr>';
  869. print '<td class="tdtop">';
  870. print $form->textwithpicto($langs->trans('NotePublic'), $htmltext, 1, 'help', '', 0, 2, 'notepublic');
  871. print '</td>';
  872. print '<td>';
  873. $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PUBLIC) ? 0 : 1, ROWS_3, '90%');
  874. print $doleditor->Create(1);
  875. // Private note
  876. if (empty($user->socid)) {
  877. print '<tr>';
  878. print '<td class="tdtop">';
  879. print $form->textwithpicto($langs->trans('NotePrivate'), $htmltext, 1, 'help', '', 0, 2, 'noteprivate');
  880. print '</td>';
  881. print '<td>';
  882. $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PRIVATE) ? 0 : 1, ROWS_3, '90%');
  883. print $doleditor->Create(1);
  884. // print '<textarea name="note_private" wrap="soft" cols="70" rows="'.ROWS_3.'">'.$note_private.'.</textarea>
  885. print '</td></tr>';
  886. }
  887. // Author
  888. print "<tr><td>".$langs->trans("Author")."</td><td>".$user->getFullName($langs)."</td></tr>";
  889. // Payment term
  890. print "<tr><td>".$langs->trans("PaymentConditions")."</td><td>";
  891. print $form->getSelectConditionsPaiements(GETPOSTISSET('cond_reglement_id') ? GETPOST('cond_reglement_id', 'int') : $object->cond_reglement_id, 'cond_reglement_id', -1, 0, 0, '');
  892. //$form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->cond_reglement_id, 'cond_reglement_id');
  893. print "</td></tr>";
  894. // Payment mode
  895. print "<tr><td>".$langs->trans("PaymentMode")."</td><td>";
  896. print img_picto('', 'payment', 'class="pictofixedwidth"');
  897. print $form->select_types_paiements(GETPOSTISSET('mode_reglement_id') ? GETPOST('mode_reglement_id', 'int') : $object->mode_reglement_id, 'mode_reglement_id', '', 0, 1, 0, 0, 1, '', 1);
  898. //$form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'mode_reglement_id', '', 1);
  899. print "</td></tr>";
  900. // Bank account
  901. if ($object->fk_account > 0) {
  902. print "<tr><td>".$langs->trans('BankAccount')."</td><td>";
  903. $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none');
  904. print "</td></tr>";
  905. }
  906. // Project
  907. if (isModEnabled('project') && is_object($object->thirdparty) && $object->thirdparty->id > 0) {
  908. $projectid = GETPOST('projectid') ?GETPOST('projectid') : $object->fk_project;
  909. $langs->load('projects');
  910. print '<tr><td>'.$langs->trans('Project').'</td><td>';
  911. print img_picto('', 'project', 'class="pictofixedwidth"');
  912. $numprojet = $formproject->select_projects($object->thirdparty->id, $projectid, 'projectid', 0, 0, 1, 0, 0, 0, 0, '', 0, 0, '');
  913. print ' &nbsp; <a href="'.DOL_URL_ROOT.'/projet/card.php?socid='.$object->thirdparty->id.'&action=create&status=1&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=create&socid='.$object->thirdparty->id.(!empty($id) ? '&id='.$id : '')).'">'.img_object($langs->trans("AddProject"), 'add').'</a>';
  914. print '</td></tr>';
  915. }
  916. // Model pdf
  917. print "<tr><td>".$langs->trans('Model')."</td><td>";
  918. include_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php';
  919. $list = ModelePDFFactures::liste_modeles($db);
  920. print img_picto('', 'generic', 'class="pictofixedwidth"');
  921. print $form->selectarray('modelpdf', $list, $conf->global->FACTURE_ADDON_PDF);
  922. print "</td></tr>";
  923. print "</table>";
  924. print dol_get_fiche_end();
  925. // Autogeneration
  926. $title = $langs->trans("Recurrence");
  927. print load_fiche_titre(img_picto('', 'recurring', 'class="pictofixedwidth"').$title, '', '');
  928. print dol_get_fiche_head(null, '', '', 0);
  929. print '<table class="border centpercent">';
  930. // Frequency + unit
  931. print '<tr><td class="titlefieldcreate">'.$form->textwithpicto($langs->trans("Frequency"), $langs->transnoentitiesnoconv('toolTipFrequency'))."</td><td>";
  932. print "<input type='text' name='frequency' value='".GETPOST('frequency', 'int')."' size='4' />&nbsp;";
  933. print $form->selectarray('unit_frequency', array('d'=>$langs->trans('Day'), 'm'=>$langs->trans('Month'), 'y'=>$langs->trans('Year')), (GETPOST('unit_frequency') ?GETPOST('unit_frequency') : 'm'));
  934. print "</td></tr>";
  935. // Date next run
  936. print "<tr><td>".$langs->trans('NextDateToExecution')."</td><td>";
  937. $date_next_execution = isset($date_next_execution) ? $date_next_execution : (GETPOST('remonth') ? dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')) : -1);
  938. print $form->selectDate($date_next_execution, '', 1, 1, '', "add", 1, 1);
  939. print "</td></tr>";
  940. // Number max of generation
  941. print "<tr><td>".$langs->trans("MaxPeriodNumber")."</td><td>";
  942. print '<input type="text" name="nb_gen_max" value="'.GETPOST('nb_gen_max').'" size="5" />';
  943. print "</td></tr>";
  944. // Auto validate the invoice
  945. print "<tr><td>".$langs->trans("StatusOfGeneratedInvoices")."</td><td>";
  946. $select = array('0'=>$langs->trans('BillStatusDraft'), '1'=>$langs->trans('BillStatusValidated'));
  947. print $form->selectarray('auto_validate', $select, GETPOST('auto_validate'));
  948. print "</td></tr>";
  949. // Auto generate document
  950. if (!empty($conf->global->INVOICE_REC_CAN_DISABLE_DOCUMENT_FILE_GENERATION)) {
  951. print "<tr><td>".$langs->trans("StatusOfGeneratedDocuments")."</td><td>";
  952. $select = array('0'=>$langs->trans('DoNotGenerateDoc'), '1'=>$langs->trans('AutoGenerateDoc'));
  953. print $form->selectarray('generate_pdf', $select, GETPOST('generate_pdf'));
  954. print "</td></tr>";
  955. } else {
  956. print '<input type="hidden" name="generate_pdf" value="1">';
  957. }
  958. print "</table>";
  959. print dol_get_fiche_end();
  960. $title = $langs->trans("ProductsAndServices");
  961. if (!isModEnabled('service')) {
  962. $title = $langs->trans("Products");
  963. } elseif (!isModEnabled('product')) {
  964. $title = $langs->trans("Services");
  965. }
  966. print load_fiche_titre($title, '', '');
  967. /*
  968. * Invoice lines
  969. */
  970. print '<div class="div-table-responsive-no-min">';
  971. print '<table id="tablelines" class="noborder noshadow" width="100%">';
  972. // Show object lines
  973. if (!empty($object->lines)) {
  974. $disableedit = 1;
  975. $disablemove = 1;
  976. $disableremove = 1;
  977. $object->printObjectLines('', $mysoc, $object->thirdparty, $lineid, 0); // No date selector for template invoice
  978. }
  979. print "</table>\n";
  980. print '<div>';
  981. print '</td></tr>';
  982. if ($flag_price_may_change) {
  983. print '<tr><td colspan="3" class="left">';
  984. print '<select name="usenewprice" class="flat">';
  985. print '<option value="0">'.$langs->trans("AlwaysUseFixedPrice").'</option>';
  986. print '<option value="1" disabled>'.$langs->trans("AlwaysUseNewPrice").'</option>';
  987. print '</select>';
  988. print '</td></tr>';
  989. }
  990. print "</table>\n";
  991. print $form->buttonsSaveCancel("Create");
  992. print "</form>\n";
  993. } else {
  994. dol_print_error('', "Error, no invoice ".$object->id);
  995. }
  996. } else {
  997. /*
  998. * View mode
  999. */
  1000. if ($object->id > 0) {
  1001. $object->fetch_thirdparty();
  1002. // Confirmation de la suppression d'une ligne produit
  1003. if ($action == 'ask_deleteline') {
  1004. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 'no', 1);
  1005. }
  1006. // Confirm delete of repeatable invoice
  1007. if ($action == 'delete') {
  1008. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteRepeatableInvoice'), $langs->trans('ConfirmDeleteRepeatableInvoice'), 'confirm_deleteinvoice', '', 'no', 1);
  1009. }
  1010. // Call Hook formConfirm
  1011. $parameters = array('formConfirm' => $formconfirm);
  1012. $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  1013. if (empty($reshook)) {
  1014. $formconfirm .= $hookmanager->resPrint;
  1015. } elseif ($reshook > 0) {
  1016. $formconfirm = $hookmanager->resPrint;
  1017. }
  1018. print $formconfirm;
  1019. $author = new User($db);
  1020. $author->fetch($object->user_author);
  1021. $head = invoice_rec_prepare_head($object);
  1022. print dol_get_fiche_head($head, 'card', $langs->trans("RepeatableInvoice"), -1, 'bill'); // Add a div
  1023. // Recurring invoice content
  1024. $linkback = '<a href="'.DOL_URL_ROOT.'/compta/facture/invoicetemplate_list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
  1025. $morehtmlref = '';
  1026. if ($action != 'editref') {
  1027. $morehtmlref .= $form->editfieldkey($object->ref, 'ref', $object->ref, $object, $user->rights->facture->creer, '', '', 0, 2);
  1028. } else {
  1029. $morehtmlref .= $form->editfieldval('', 'ref', $object->ref, $object, $user->rights->facture->creer, 'string');
  1030. }
  1031. $morehtmlref .= '<div class="refidno">';
  1032. // Ref customer
  1033. //$morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->facture->creer, 'string', '', 0, 1);
  1034. //$morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->facture->creer, 'string', '', null, null, '', 1);
  1035. // Thirdparty
  1036. $morehtmlref .= $langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1);
  1037. // Project
  1038. if (isModEnabled('project')) {
  1039. $langs->load("projects");
  1040. $morehtmlref .= '<br>'.$langs->trans('Project').' ';
  1041. if ($user->rights->facture->creer) {
  1042. if ($action != 'classify') {
  1043. $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : ';
  1044. }
  1045. if ($action == 'classify') {
  1046. //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
  1047. $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
  1048. $morehtmlref .= '<input type="hidden" name="action" value="classin">';
  1049. $morehtmlref .= '<input type="hidden" name="token" value="'.newToken().'">';
  1050. $morehtmlref .= $formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
  1051. $morehtmlref .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  1052. $morehtmlref .= '</form>';
  1053. } else {
  1054. $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1, '', 'maxwidth300');
  1055. }
  1056. } else {
  1057. if (!empty($object->fk_project)) {
  1058. $proj = new Project($db);
  1059. $proj->fetch($object->fk_project);
  1060. $morehtmlref .= ' : '.$proj->getNomUrl(1);
  1061. if ($proj->title) {
  1062. $morehtmlref .= ' - '.$proj->title;
  1063. }
  1064. } else {
  1065. $morehtmlref .= '';
  1066. }
  1067. }
  1068. }
  1069. $morehtmlref .= '</div>';
  1070. $morehtmlright = '';
  1071. dol_banner_tab($object, 'ref', $linkback, 1, 'title', 'none', $morehtmlref, '', 0, '', $morehtmlright);
  1072. print '<div class="fichecenter">';
  1073. print '<div class="fichehalfleft">';
  1074. print '<div class="underbanner clearboth"></div>';
  1075. print '<table class="border centpercent tableforfield">';
  1076. print '<tr><td class="titlefield">'.$langs->trans("Author").'</td><td>';
  1077. print $author->getNomUrl(-1);
  1078. print "</td></tr>";
  1079. print '<tr><td>'.$langs->trans("AmountHT").'</td>';
  1080. print '<td>'.price($object->total_ht, '', $langs, 1, -1, -1, $conf->currency).'</td>';
  1081. print '</tr>';
  1082. print '<tr><td>'.$langs->trans("AmountVAT").'</td><td>'.price($object->total_tva, '', $langs, 1, -1, -1, $conf->currency).'</td>';
  1083. print '</tr>';
  1084. // Amount Local Taxes
  1085. if (($mysoc->localtax1_assuj == "1" && $mysoc->useLocalTax(1)) || $object->total_localtax1 != 0) { // Localtax1
  1086. print '<tr><td>'.$langs->transcountry("AmountLT1", $mysoc->country_code).'</td>';
  1087. print '<td class="nowrap">'.price($object->total_localtax1, 1, '', 1, - 1, - 1, $conf->currency).'</td></tr>';
  1088. }
  1089. if (($mysoc->localtax2_assuj == "1" && $mysoc->useLocalTax(2)) || $object->total_localtax2 != 0) { // Localtax2
  1090. print '<tr><td>'.$langs->transcountry("AmountLT2", $mysoc->country_code).'</td>';
  1091. print '<td class=nowrap">'.price($object->total_localtax2, 1, '', 1, - 1, - 1, $conf->currency).'</td></tr>';
  1092. }
  1093. print '<tr><td>'.$langs->trans("AmountTTC").'</td><td colspan="3">'.price($object->total_ttc, '', $langs, 1, -1, -1, $conf->currency).'</td>';
  1094. print '</tr>';
  1095. // Payment term
  1096. print '<tr><td>';
  1097. print '<table class="nobordernopadding centpercent"><tr><td>';
  1098. print $langs->trans('PaymentConditionsShort');
  1099. print '</td>';
  1100. if ($action != 'editconditions' && $user->rights->facture->creer) {
  1101. print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editconditions&token='.newToken().'&facid='.$object->id.'">'.img_edit($langs->trans('SetConditions'), 1).'</a></td>';
  1102. }
  1103. print '</tr></table>';
  1104. print '</td><td>';
  1105. if ($object->type != Facture::TYPE_CREDIT_NOTE) {
  1106. if ($action == 'editconditions') {
  1107. $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->cond_reglement_id, 'cond_reglement_id');
  1108. } else {
  1109. $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->cond_reglement_id, 'none');
  1110. }
  1111. } else {
  1112. print '&nbsp;';
  1113. }
  1114. print '</td></tr>';
  1115. // Payment mode
  1116. print '<tr><td>';
  1117. print '<table class="nobordernopadding" width="100%"><tr><td>';
  1118. print $langs->trans('PaymentMode');
  1119. print '</td>';
  1120. if ($action != 'editmode' && $user->rights->facture->creer) {
  1121. print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmode&token='.newToken().'&facid='.$object->id.'">'.img_edit($langs->trans('SetMode'), 1).'</a></td>';
  1122. }
  1123. print '</tr></table>';
  1124. print '</td><td>';
  1125. if ($action == 'editmode') {
  1126. $form->form_modes_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->mode_reglement_id, 'mode_reglement_id', 'CRDT', 1, 1);
  1127. } else {
  1128. $form->form_modes_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->mode_reglement_id, 'none');
  1129. }
  1130. print '</td></tr>';
  1131. // Multicurrency
  1132. if (isModEnabled('multicurrency')) {
  1133. // Multicurrency code
  1134. print '<tr>';
  1135. print '<td>';
  1136. print '<table class="nobordernopadding" width="100%"><tr><td>';
  1137. print $form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0);
  1138. print '</td>';
  1139. if ($usercancreate && $action != 'editmulticurrencycode' && !empty($object->brouillon)) {
  1140. print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmulticurrencycode&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1).'</a></td>';
  1141. }
  1142. print '</tr></table>';
  1143. print '</td><td>';
  1144. $htmlname = (($usercancreate && $action == 'editmulticurrencycode') ? 'multicurrency_code' : 'none');
  1145. $form->form_multicurrency_code($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_code, $htmlname);
  1146. print '</td></tr>';
  1147. // Multicurrency rate
  1148. if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) {
  1149. print '<tr>';
  1150. print '<td>';
  1151. print '<table class="nobordernopadding" width="100%"><tr><td>';
  1152. print $form->editfieldkey('CurrencyRate', 'multicurrency_tx', '', $object, 0);
  1153. print '</td>';
  1154. if ($usercancreate && $action != 'editmulticurrencyrate' && !empty($object->brouillon) && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) {
  1155. print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmulticurrencyrate&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1).'</a></td>';
  1156. }
  1157. print '</tr></table>';
  1158. print '</td><td>';
  1159. if ($action == 'editmulticurrencyrate' || $action == 'actualizemulticurrencyrate') {
  1160. if ($action == 'actualizemulticurrencyrate') {
  1161. list($object->fk_multicurrency, $object->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($object->db, $object->multicurrency_code);
  1162. }
  1163. $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_tx, ($usercancreate ? 'multicurrency_tx' : 'none'), $object->multicurrency_code);
  1164. } else {
  1165. $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_tx, 'none', $object->multicurrency_code);
  1166. if ($object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) {
  1167. print '<div class="inline-block"> &nbsp; &nbsp; &nbsp; &nbsp; ';
  1168. print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=actualizemulticurrencyrate">'.$langs->trans("ActualizeCurrency").'</a>';
  1169. print '</div>';
  1170. }
  1171. }
  1172. print '</td></tr>';
  1173. }
  1174. }
  1175. // Help of substitution key
  1176. $dateexample = dol_now();
  1177. if (!empty($object->frequency) && !empty($object->date_when)) {
  1178. $dateexample = $object->date_when;
  1179. }
  1180. // Help of substitution key
  1181. $substitutionarray = getCommonSubstitutionArray($langs, 2, null, $object);
  1182. $substitutionarray['__INVOICE_PREVIOUS_MONTH__'] = $langs->trans("PreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'), '%m').')';
  1183. $substitutionarray['__INVOICE_MONTH__'] = $langs->trans("MonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample, '%m').')';
  1184. $substitutionarray['__INVOICE_NEXT_MONTH__'] = $langs->trans("NextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'), '%m').')';
  1185. $substitutionarray['__INVOICE_PREVIOUS_MONTH_TEXT__'] = $langs->trans("TextPreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'), '%B').')';
  1186. $substitutionarray['__INVOICE_MONTH_TEXT__'] = $langs->trans("TextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample, '%B').')';
  1187. $substitutionarray['__INVOICE_NEXT_MONTH_TEXT__'] = $langs->trans("TextNextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'), '%B').')';
  1188. $substitutionarray['__INVOICE_PREVIOUS_YEAR__'] = $langs->trans("PreviousYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'y'), '%Y').')';
  1189. $substitutionarray['__INVOICE_YEAR__'] = $langs->trans("YearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample, '%Y').')';
  1190. $substitutionarray['__INVOICE_NEXT_YEAR__'] = $langs->trans("NextYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'y'), '%Y').')';
  1191. // Only on template invoices
  1192. $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = $langs->trans("DateNextInvoiceBeforeGen").' ('.$langs->trans("Example").': '.dol_print_date(($object->date_when ? $object->date_when : dol_now()), 'dayhour').')';
  1193. $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = $langs->trans("DateNextInvoiceAfterGen").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree(($object->date_when ? $object->date_when : dol_now()), $object->frequency, $object->unit_frequency), 'dayhour').')';
  1194. $substitutionarray['__INVOICE_COUNTER_CURRENT__'] = $object->nb_gen_done;
  1195. $substitutionarray['__INVOICE_COUNTER_MAX__'] = $object->nb_gen_max;
  1196. $htmltext = '<i>'.$langs->trans("FollowingConstantsWillBeSubstituted").':<br>';
  1197. foreach ($substitutionarray as $key => $val) {
  1198. $htmltext .= $key.' = '.$langs->trans($val).'<br>';
  1199. }
  1200. $htmltext .= '</i>';
  1201. // Note public
  1202. print '<tr><td>';
  1203. print $form->editfieldkey($form->textwithpicto($langs->trans('NotePublic'), $htmltext, 1, 'help', '', 0, 2, 'notepublic'), 'note_public', $object->note_public, $object, $user->rights->facture->creer);
  1204. print '</td><td class="wordbreak">';
  1205. print $form->editfieldval($langs->trans("NotePublic"), 'note_public', $object->note_public, $object, $user->rights->facture->creer, 'textarea:'.ROWS_4.':90%', '', null, null, '', 1);
  1206. print '</td>';
  1207. print '</tr>';
  1208. // Note private
  1209. print '<tr><td>';
  1210. print $form->editfieldkey($form->textwithpicto($langs->trans("NotePrivate"), $htmltext, 1, 'help', '', 0, 2, 'noteprivate'), 'note_private', $object->note_private, $object, $user->rights->facture->creer);
  1211. print '</td><td class="wordbreak">';
  1212. print $form->editfieldval($langs->trans("NotePrivate"), 'note_private', $object->note_private, $object, $user->rights->facture->creer, 'textarea:'.ROWS_4.':90%', '', null, null, '', 1);
  1213. print '</td>';
  1214. print '</tr>';
  1215. // Bank Account
  1216. print '<tr><td class="nowrap">';
  1217. print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">';
  1218. print $langs->trans('BankAccount');
  1219. print '<td>';
  1220. if (($action != 'editbankaccount') && $user->rights->facture->creer && $object->statut == FactureRec::STATUS_DRAFT) {
  1221. print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editbankaccount&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->trans('SetBankAccount'), 1).'</a></td>';
  1222. }
  1223. print '</tr></table>';
  1224. print '</td><td>';
  1225. if ($action == 'editbankaccount') {
  1226. $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1);
  1227. } else {
  1228. $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none');
  1229. }
  1230. print "</td>";
  1231. print '</tr>';
  1232. // Model pdf
  1233. print '<tr><td class="nowrap">';
  1234. print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">';
  1235. print $langs->trans('Model');
  1236. print '<td>';
  1237. if (($action != 'editmodelpdf') && $user->rights->facture->creer && $object->statut == FactureRec::STATUS_DRAFT) {
  1238. print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmodelpdf&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->trans('SetModel'), 1).'</a></td>';
  1239. }
  1240. print '</tr></table>';
  1241. print '</td><td>';
  1242. if ($action == 'editmodelpdf') {
  1243. include_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php';
  1244. $list = array();
  1245. $models = ModelePDFFactures::liste_modeles($db);
  1246. foreach ($models as $k => $model) {
  1247. $list[] = str_replace(':', '|', $k).':'.$model;
  1248. }
  1249. $select = 'select;'.implode(',', $list);
  1250. print $form->editfieldval($langs->trans("Model"), 'modelpdf', $object->model_pdf, $object, $user->rights->facture->creer, $select);
  1251. } else {
  1252. print $object->model_pdf;
  1253. }
  1254. print "</td>";
  1255. print '</tr>';
  1256. // Other attributes
  1257. $cols = 2;
  1258. include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
  1259. print '</table>';
  1260. print '</div>';
  1261. print '<div class="fichehalfright">';
  1262. print '<div class="underbanner clearboth"></div>';
  1263. /*
  1264. * Recurrence
  1265. */
  1266. $title = $langs->trans("Recurrence");
  1267. //print load_fiche_titre($title, '', 'calendar');
  1268. print '<table class="border centpercent tableforfield">';
  1269. print '<tr><td colspan="2">'.img_picto('', 'recurring', 'class="pictofixedwidth"').$title.'</td></tr>';
  1270. // if "frequency" is empty or = 0, the reccurence is disabled
  1271. print '<tr><td style="width: 50%">';
  1272. print '<table class="nobordernopadding" width="100%"><tr><td>';
  1273. print $langs->trans('Frequency');
  1274. print '</td>';
  1275. if ($action != 'editfrequency' && $user->rights->facture->creer) {
  1276. print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editfrequency&token='.newToken().'&facid='.$object->id.'">'.img_edit($langs->trans('Edit'), 1).'</a></td>';
  1277. }
  1278. print '</tr></table>';
  1279. print '</td><td>';
  1280. if ($action == 'editfrequency') {
  1281. print '<form method="post" action="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'">';
  1282. print '<input type="hidden" name="action" value="setfrequency">';
  1283. print '<input type="hidden" name="token" value="'.newToken().'">';
  1284. print '<table class="nobordernopadding">';
  1285. print '<tr><td>';
  1286. print "<input type='text' name='frequency' value='".$object->frequency."' size='5' />&nbsp;";
  1287. print $form->selectarray('unit_frequency', array('d'=>$langs->trans('Day'), 'm'=>$langs->trans('Month'), 'y'=>$langs->trans('Year')), ($object->unit_frequency ? $object->unit_frequency : 'm'));
  1288. print '</td>';
  1289. print '<td class="left"><input type="submit" class="button button-edit smallpaddingimp" value="'.$langs->trans("Modify").'"></td>';
  1290. print '</tr></table></form>';
  1291. } else {
  1292. if ($object->frequency > 0) {
  1293. print $langs->trans('FrequencyPer_'.$object->unit_frequency, $object->frequency);
  1294. } else {
  1295. print '<span class="opacitymedium">'.$langs->trans("NotARecurringInvoiceTemplate").'</span>';
  1296. }
  1297. }
  1298. print '</td></tr>';
  1299. // Date when (next invoice generation)
  1300. print '<tr><td>';
  1301. if ($action == 'date_when' || $object->frequency > 0) {
  1302. print $form->editfieldkey($langs->trans("NextDateToExecution"), 'date_when', $object->date_when, $object, $user->rights->facture->creer, 'day');
  1303. } else {
  1304. print $langs->trans("NextDateToExecution");
  1305. }
  1306. print '</td><td>';
  1307. if ($action == 'date_when' || $object->frequency > 0) {
  1308. print $form->editfieldval($langs->trans("NextDateToExecution"), 'date_when', $object->date_when, $object, $user->rights->facture->creer, 'day', $object->date_when, null, '', '', 0, 'strikeIfMaxNbGenReached');
  1309. }
  1310. //var_dump(dol_print_date($object->date_when+60, 'dayhour').' - '.dol_print_date($now, 'dayhour'));
  1311. if (!$object->isMaxNbGenReached()) {
  1312. if (!$object->suspended && $action != 'editdate_when' && $object->frequency > 0 && $object->date_when && $object->date_when < $now) {
  1313. print img_warning($langs->trans("Late"));
  1314. }
  1315. } else {
  1316. print img_info($langs->trans("MaxNumberOfGenerationReached"));
  1317. }
  1318. print '</td>';
  1319. print '</tr>';
  1320. // Max period / Rest period
  1321. print '<tr><td>';
  1322. if ($action == 'nb_gen_max' || $object->frequency > 0) {
  1323. print $form->editfieldkey($langs->trans("MaxPeriodNumber"), 'nb_gen_max', $object->nb_gen_max, $object, $user->rights->facture->creer);
  1324. } else {
  1325. print $langs->trans("MaxPeriodNumber");
  1326. }
  1327. print '</td><td>';
  1328. if ($action == 'nb_gen_max' || $object->frequency > 0) {
  1329. print $form->editfieldval($langs->trans("MaxPeriodNumber"), 'nb_gen_max', $object->nb_gen_max ? $object->nb_gen_max : '', $object, $user->rights->facture->creer);
  1330. } else {
  1331. print '';
  1332. }
  1333. print '</td>';
  1334. print '</tr>';
  1335. // Status of generated invoices
  1336. print '<tr><td>';
  1337. if ($action == 'auto_validate' || $object->frequency > 0) {
  1338. print $form->editfieldkey($langs->trans("StatusOfGeneratedInvoices"), 'auto_validate', $object->auto_validate, $object, $user->rights->facture->creer);
  1339. } else {
  1340. print $langs->trans("StatusOfGeneratedInvoices");
  1341. }
  1342. print '</td><td>';
  1343. $select = 'select;0:'.$langs->trans('BillStatusDraft').',1:'.$langs->trans('BillStatusValidated');
  1344. if ($action == 'auto_validate' || $object->frequency > 0) {
  1345. print $form->editfieldval($langs->trans("StatusOfGeneratedInvoices"), 'auto_validate', $object->auto_validate, $object, $user->rights->facture->creer, $select);
  1346. }
  1347. print '</td>';
  1348. // Auto generate documents
  1349. if (!empty($conf->global->INVOICE_REC_CAN_DISABLE_DOCUMENT_FILE_GENERATION)) {
  1350. print '<tr>';
  1351. print '<td>';
  1352. if ($action == 'generate_pdf' || $object->frequency > 0) {
  1353. print $form->editfieldkey($langs->trans("StatusOfGeneratedDocuments"), 'generate_pdf', $object->generate_pdf, $object, $user->rights->facture->creer);
  1354. } else {
  1355. print $langs->trans("StatusOfGeneratedDocuments");
  1356. }
  1357. print '</td>';
  1358. print '<td>';
  1359. $select = 'select;0:'.$langs->trans('DoNotGenerateDoc').',1:'.$langs->trans('AutogenerateDoc');
  1360. if ($action == 'generate_pdf' || $object->frequency > 0) {
  1361. print $form->editfieldval($langs->trans("StatusOfGeneratedDocuments"), 'generate_pdf', $object->generate_pdf, $object, $user->rights->facture->creer, $select);
  1362. }
  1363. print '</td>';
  1364. print '</tr>';
  1365. } else {
  1366. print '<input type="hidden" name="generate_pdf" value="1">';
  1367. }
  1368. print '</table>';
  1369. // Frequencry/Recurring section
  1370. if ($object->frequency > 0) {
  1371. print '<br>';
  1372. if (!isModEnabled('cron')) {
  1373. print info_admin($langs->trans("EnableAndSetupModuleCron", $langs->transnoentitiesnoconv("Module2300Name")));
  1374. }
  1375. print '<div class="underbanner clearboth"></div>';
  1376. print '<table class="border centpercent tableforfield">';
  1377. // Nb of generation already done
  1378. print '<tr><td style="width: 50%">'.$langs->trans("NbOfGenerationDone").'</td>';
  1379. print '<td>';
  1380. print $object->nb_gen_done ? $object->nb_gen_done : '0';
  1381. print '</td>';
  1382. print '</tr>';
  1383. // Date last
  1384. print '<tr><td>';
  1385. print $langs->trans("DateLastGeneration");
  1386. print '</td><td>';
  1387. print dol_print_date($object->date_last_gen, 'dayhour');
  1388. print '</td>';
  1389. print '</tr>';
  1390. print '</table>';
  1391. print '<br>';
  1392. }
  1393. print '</div>';
  1394. print '</div>';
  1395. print '<div class="clearboth"></div><br>';
  1396. // Lines
  1397. print '<form name="addproduct" id="addproduct" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.(($action != 'editline') ? '#add' : '#line_'.GETPOST('lineid', 'int')).'" method="POST">';
  1398. print '<input type="hidden" name="token" value="' . newToken().'">';
  1399. print '<input type="hidden" name="action" value="' . (($action != 'editline') ? 'addline' : 'updateline').'">';
  1400. print '<input type="hidden" name="mode" value="">';
  1401. print '<input type="hidden" name="id" value="' . $object->id.'">';
  1402. print '<input type="hidden" name="page_y" value="">';
  1403. if (!empty($conf->use_javascript_ajax) && $object->statut == 0) {
  1404. include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php';
  1405. }
  1406. print '<div class="div-table-responsive-no-min">';
  1407. print '<table id="tablelines" class="noborder noshadow centpercent">';
  1408. // Show object lines
  1409. if (!empty($object->lines)) {
  1410. $canchangeproduct = 1;
  1411. $object->printObjectLines($action, $mysoc, $object->thirdparty, $lineid, 0); // No date selector for template invoice
  1412. }
  1413. // Form to add new line
  1414. if ($object->statut == $object::STATUS_DRAFT && $user->rights->facture->creer && $action != 'valid' && $action != 'editline') {
  1415. if ($action != 'editline') {
  1416. // Add free products/services
  1417. $parameters = array();
  1418. $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  1419. if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  1420. if (empty($reshook))
  1421. $object->formAddObjectLine(0, $mysoc, $object->thirdparty); // No date selector for template invoice
  1422. }
  1423. }
  1424. print "</table>\n";
  1425. print '</div>';
  1426. print "</form>\n";
  1427. print dol_get_fiche_end();
  1428. /*
  1429. * Action bar
  1430. */
  1431. print '<div class="tabsAction">';
  1432. $parameters = array();
  1433. $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  1434. if (empty($reshook)) {
  1435. $params = array(
  1436. 'attr' => array(
  1437. 'class' => 'classfortooltip',
  1438. ),
  1439. );
  1440. if (empty($object->suspended)) {
  1441. if ($user->rights->facture->creer) {
  1442. if (!empty($object->frequency) && $object->nb_gen_max > 0 && ($object->nb_gen_done >= $object->nb_gen_max)) {
  1443. print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="' . dol_escape_htmltag($langs->trans("MaxGenerationReached")) . '">' . $langs->trans("CreateBill") . '</a></div>';
  1444. } else {
  1445. if (empty($object->frequency) || $object->date_when <= $nowlasthour) {
  1446. print '<div class="inline-block divButAction"><a class="butAction" href="' . DOL_URL_ROOT . '/compta/facture/card.php?action=create&socid=' . $object->thirdparty->id . '&fac_rec=' . $object->id . '">' . $langs->trans("CreateBill") . '</a></div>';
  1447. } else {
  1448. print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="' . dol_escape_htmltag($langs->trans("DateIsNotEnough")) . '">' . $langs->trans("CreateBill") . '</a></div>';
  1449. }
  1450. }
  1451. } else {
  1452. print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#">' . $langs->trans("CreateBill") . '</a></div>';
  1453. }
  1454. }
  1455. if ($user->rights->facture->creer) {
  1456. if (empty($object->suspended)) {
  1457. print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?action=disable&id='.$object->id.'&token='.newToken().'">'.$langs->trans("Disable").'</a></div>';
  1458. } else {
  1459. print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=enable&id='.$object->id.'&token='.newToken().'">'.$langs->trans("Enable").'</a></div>';
  1460. }
  1461. }
  1462. // Delete
  1463. print dolGetButtonAction($langs->trans("Delete"), '', 'delete', $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&action=delete&token=' . newToken(), 'delete', $user->rights->facture->supprimer);
  1464. }
  1465. print '</div>';
  1466. print '<div class="fichecenter"><div class="fichehalfleft">';
  1467. print '<a name="builddoc"></a>'; // ancre
  1468. // Show links to link elements
  1469. $linktoelem = $form->showLinkToObjectBlock($object, null, array('invoice'));
  1470. $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem);
  1471. print '</div>';
  1472. print '<div class="fichehalfright">';
  1473. $MAXEVENT = 10;
  1474. //$morehtmlcenter = dolGetButtonTitle($langs->trans('SeeAll'), '', 'fa fa-bars imgforviewmode', dol_buildpath('/mymodule/myobject_agenda.php', 1).'?id='.$object->id);
  1475. // List of actions on element
  1476. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
  1477. $formactions = new FormActions($db);
  1478. $somethingshown = $formactions->showactions($object, $object->element, (is_object($object->thirdparty) ? $object->thirdparty->id : 0), 1, '', $MAXEVENT, '', $morehtmlcenter);
  1479. print '</div>';
  1480. print '</div>';
  1481. }
  1482. }
  1483. // End of page
  1484. llxFooter();
  1485. $db->close();