card-rec.php 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746
  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->hasRight('facture', 'creer'); // Used by the include of actions_setnotes.inc.php
  97. $permissiondellink = $user->hasRight('facture', 'creer'); // Used by the include of actions_dellink.inc.php
  98. $permissiontoedit = $user->hasRight('facture', 'creer'); // Used by the include of actions_lineupdonw.inc.php
  99. $usercanread = $user->hasRight('facture', 'lire');
  100. $usercancreate = $user->hasRight('facture', 'creer');
  101. $usercanissuepayment = $user->hasRight('facture', 'paiement');
  102. $usercandelete = $user->hasRight('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_delete' && $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->hasRight('facture', 'creer')) {
  237. $result = $object->setPaymentTerms(GETPOST('cond_reglement_id', 'int'));
  238. } elseif ($action == 'setmode' && $user->hasRight('facture', 'creer')) {
  239. // Set mode
  240. $result = $object->setPaymentMethods(GETPOST('mode_reglement_id', 'int'));
  241. } elseif ($action == 'classin' && $user->hasRight('facture', 'creer')) {
  242. // Set project
  243. $object->setProject(GETPOST('projectid', 'int'));
  244. } elseif ($action == 'setref' && $user->hasRight('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->hasRight('facture', 'creer')) {
  262. // Set bank account
  263. $result = $object->setBankAccount(GETPOST('fk_account', 'int'));
  264. } elseif ($action == 'setfrequency' && $user->hasRight('facture', 'creer')) {
  265. // Set frequency and unit frequency
  266. $object->setFrequencyAndUnit(GETPOST('frequency', 'int'), GETPOST('unit_frequency', 'alpha'));
  267. } elseif ($action == 'setdate_when' && $user->hasRight('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->hasRight('facture', 'creer')) {
  274. // Set max period
  275. $object->setMaxPeriod(GETPOST('nb_gen_max', 'int'));
  276. } elseif ($action == 'setauto_validate' && $user->hasRight('facture', 'creer')) {
  277. // Set auto validate
  278. $object->setAutoValidate(GETPOST('auto_validate', 'int'));
  279. } elseif ($action == 'setgenerate_pdf' && $user->hasRight('facture', 'creer')) {
  280. // Set generate pdf
  281. $object->setGeneratepdf(GETPOST('generate_pdf', 'int'));
  282. } elseif ($action == 'setmodelpdf' && $user->hasRight('facture', 'creer')) {
  283. // Set model pdf
  284. $object->setModelpdf(GETPOST('modelpdf', 'alpha'));
  285. } elseif ($action == 'disable' && $user->hasRight('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->hasRight('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->hasRight('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->hasRight('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. if (!empty($conf->global->MAIN_DISABLE_FREE_LINES) && $idprod <= 0) {
  373. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ProductOrService")), null, 'errors');
  374. $error++;
  375. }
  376. }
  377. $qty = price2num(GETPOST('qty'.$predef, 'alpha'), 'MS', 2);
  378. $remise_percent = price2num(GETPOST('remise_percent'.$predef), '', 2);
  379. if (empty($remise_percent)) {
  380. $remise_percent = 0;
  381. }
  382. // Extrafields
  383. $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
  384. $array_options = $extrafields->getOptionalsFromPost($object->table_element_line, $predef);
  385. // Unset extrafield
  386. if (is_array($extralabelsline)) {
  387. // Get extra fields
  388. foreach ($extralabelsline as $key => $value) {
  389. unset($_POST["options_".$key.$predef]);
  390. }
  391. }
  392. if ((empty($idprod) || $idprod < 0) && ($price_ht < 0) && ($qty < 0)) {
  393. setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPriceHT'), $langs->transnoentitiesnoconv('Qty')), null, 'errors');
  394. $error++;
  395. }
  396. if ($prod_entry_mode == 'free' && (empty($idprod) || $idprod < 0) && GETPOST('type') < 0) {
  397. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors');
  398. $error++;
  399. }
  400. if ($prod_entry_mode == 'free' && (empty($idprod) || $idprod < 0) && (!($price_ht >= 0) || $price_ht == '')) { // Unit price can be 0 but not ''
  401. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("UnitPriceHT")), null, 'errors');
  402. $error++;
  403. }
  404. if ($qty == '') {
  405. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors');
  406. $error++;
  407. }
  408. if ($prod_entry_mode == 'free' && (empty($idprod) || $idprod < 0) && empty($product_desc)) {
  409. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors');
  410. $error++;
  411. }
  412. if ($qty < 0) {
  413. $langs->load("errors");
  414. setEventMessages($langs->trans('ErrorQtyForCustomerInvoiceCantBeNegative'), null, 'errors');
  415. $error++;
  416. }
  417. if (!$error && ($qty >= 0) && (!empty($product_desc) || (!empty($idprod) && $idprod > 0))) {
  418. $ret = $object->fetch($id);
  419. if ($ret < 0) {
  420. dol_print_error($db, $object->error);
  421. exit();
  422. }
  423. $ret = $object->fetch_thirdparty();
  424. // Clean parameters
  425. $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'));
  426. $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'));
  427. $price_base_type = (GETPOST('price_base_type', 'alpha') ? GETPOST('price_base_type', 'alpha') : 'HT');
  428. // Define special_code for special lines
  429. $special_code = 0;
  430. // if (!GETPOST('qty')) $special_code=3; // Options should not exists on invoices
  431. // Ecrase $pu par celui du produit
  432. // Ecrase $desc par celui du produit
  433. // Ecrase $tva_tx par celui du produit
  434. // Ecrase $base_price_type par celui du produit
  435. // Replaces $fk_unit with the product's
  436. if (!empty($idprod) && $idprod > 0) {
  437. $prod = new Product($db);
  438. $prod->fetch($idprod);
  439. $label = ((GETPOST('product_label') && GETPOST('product_label') != $prod->label) ? GETPOST('product_label') : '');
  440. // Update if prices fields are defined
  441. $tva_tx = get_default_tva($mysoc, $object->thirdparty, $prod->id);
  442. $tva_npr = get_default_npr($mysoc, $object->thirdparty, $prod->id);
  443. if (empty($tva_tx)) {
  444. $tva_npr = 0;
  445. }
  446. // Search the correct price into loaded array product_price_by_qty using id of array retrieved into POST['pqp'].
  447. $pqp = (GETPOST('pbq', 'int') ? GETPOST('pbq', 'int') : 0);
  448. $datapriceofproduct = $prod->getSellPrice($mysoc, $object->thirdparty, $pqp);
  449. $pu_ht = $datapriceofproduct['pu_ht'];
  450. $pu_ttc = $datapriceofproduct['pu_ttc'];
  451. $price_min = $datapriceofproduct['price_min'];
  452. $price_base_type = $datapriceofproduct['price_base_type'];
  453. $tva_tx = $datapriceofproduct['tva_tx'];
  454. $tva_npr = $datapriceofproduct['tva_npr'];
  455. $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $tva_tx));
  456. $tmpprodvat = price2num(preg_replace('/\s*\(.*\)/', '', $prod->tva_tx));
  457. // if price ht was forced (ie: from gui when calculated by margin rate and cost price). TODO Why this ?
  458. if (!empty($price_ht)) {
  459. $pu_ht = price2num($price_ht, 'MU');
  460. $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU');
  461. } elseif ($tmpvat != $tmpprodvat) {
  462. // On reevalue prix selon taux tva car taux tva transaction peut etre different
  463. // de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur).
  464. if ($price_base_type != 'HT') {
  465. $pu_ht = price2num($pu_ttc / (1 + ($tmpvat / 100)), 'MU');
  466. } else {
  467. $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU');
  468. }
  469. }
  470. $desc = '';
  471. // Define output language
  472. if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
  473. $outputlangs = $langs;
  474. $newlang = '';
  475. if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  476. $newlang = GETPOST('lang_id', 'aZ09');
  477. }
  478. if (empty($newlang)) {
  479. $newlang = $object->thirdparty->default_lang;
  480. }
  481. if (!empty($newlang)) {
  482. $outputlangs = new Translate("", $conf);
  483. $outputlangs->setDefaultLang($newlang);
  484. }
  485. $desc = (!empty($prod->multilangs [$outputlangs->defaultlang] ["description"])) ? $prod->multilangs [$outputlangs->defaultlang] ["description"] : $prod->description;
  486. } else {
  487. $desc = $prod->description;
  488. }
  489. $desc = dol_concatdesc($desc, $product_desc);
  490. // Add custom code and origin country into description
  491. if (empty($conf->global->MAIN_PRODUCT_DISABLE_CUSTOMCOUNTRYCODE) && (!empty($prod->customcode) || !empty($prod->country_code))) {
  492. $tmptxt = '(';
  493. // Define output language
  494. if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
  495. $outputlangs = $langs;
  496. $newlang = '';
  497. if (empty($newlang) && GETPOST('lang_id', 'alpha')) {
  498. $newlang = GETPOST('lang_id', 'alpha');
  499. }
  500. if (empty($newlang)) {
  501. $newlang = $object->thirdparty->default_lang;
  502. }
  503. if (!empty($newlang)) {
  504. $outputlangs = new Translate("", $conf);
  505. $outputlangs->setDefaultLang($newlang);
  506. $outputlangs->load('products');
  507. }
  508. if (!empty($prod->customcode)) {
  509. $tmptxt .= $outputlangs->transnoentitiesnoconv("CustomCode").': '.$prod->customcode;
  510. }
  511. if (!empty($prod->customcode) && !empty($prod->country_code)) {
  512. $tmptxt .= ' - ';
  513. }
  514. if (!empty($prod->country_code)) {
  515. $tmptxt .= $outputlangs->transnoentitiesnoconv("CountryOrigin").': '.getCountry($prod->country_code, 0, $db, $outputlangs, 0);
  516. }
  517. } else {
  518. if (!empty($prod->customcode)) {
  519. $tmptxt .= $langs->transnoentitiesnoconv("CustomCode").': '.$prod->customcode;
  520. }
  521. if (!empty($prod->customcode) && !empty($prod->country_code)) {
  522. $tmptxt .= ' - ';
  523. }
  524. if (!empty($prod->country_code)) {
  525. $tmptxt .= $langs->transnoentitiesnoconv("CountryOrigin").': '.getCountry($prod->country_code, 0, $db, $langs, 0);
  526. }
  527. }
  528. $tmptxt .= ')';
  529. $desc = dol_concatdesc($desc, $tmptxt);
  530. }
  531. $type = $prod->type;
  532. $fk_unit = $prod->fk_unit;
  533. } else {
  534. $pu_ht = price2num($price_ht, 'MU');
  535. $pu_ttc = price2num(GETPOST('price_ttc'), 'MU');
  536. $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0);
  537. $tva_tx = str_replace('*', '', $tva_tx);
  538. if (empty($tva_tx)) {
  539. $tva_npr = 0;
  540. }
  541. $label = (GETPOST('product_label') ? GETPOST('product_label') : '');
  542. $desc = $product_desc;
  543. $type = GETPOST('type');
  544. $fk_unit = GETPOST('units', 'alpha');
  545. }
  546. $date_start_fill = GETPOST('date_start_fill', 'int');
  547. $date_end_fill = GETPOST('date_end_fill', 'int');
  548. // Margin
  549. $fournprice = price2num(GETPOST('fournprice'.$predef) ? GETPOST('fournprice'.$predef) : '');
  550. $buyingprice = price2num(GETPOST('buying_price'.$predef) != '' ? GETPOST('buying_price'.$predef) : ''); // If buying_price is '0', we must keep this value
  551. // Local Taxes
  552. $localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty, $mysoc, $tva_npr);
  553. $localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty, $mysoc, $tva_npr);
  554. $info_bits = 0;
  555. if ($tva_npr) {
  556. $info_bits |= 0x01;
  557. }
  558. if ($usercanproductignorepricemin && (!empty($price_min) && (price2num($pu_ht) * (1 - price2num($remise_percent) / 100) < price2num($price_min)))) {
  559. $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, - 1, $conf->currency));
  560. setEventMessages($mesg, null, 'errors');
  561. } else {
  562. // Insert line
  563. $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);
  564. if ($result > 0) {
  565. // Define output language and generate document
  566. /*if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
  567. {
  568. // Define output language
  569. $outputlangs = $langs;
  570. $newlang = '';
  571. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09');
  572. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) $newlang = $object->thirdparty->default_lang;
  573. if (!empty($newlang)) {
  574. $outputlangs = new Translate("", $conf);
  575. $outputlangs->setDefaultLang($newlang);
  576. }
  577. $model=$object->model_pdf;
  578. $ret = $object->fetch($id); // Reload to get new records
  579. $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  580. if ($result < 0) setEventMessages($object->error, $object->errors, 'errors');
  581. }*/
  582. $object->fetch($object->id); // Reload lines
  583. unset($_POST['prod_entry_mode']);
  584. unset($_POST['qty']);
  585. unset($_POST['type']);
  586. unset($_POST['remise_percent']);
  587. unset($_POST['price_ht']);
  588. unset($_POST['multicurrency_price_ht']);
  589. unset($_POST['price_ttc']);
  590. unset($_POST['tva_tx']);
  591. unset($_POST['product_ref']);
  592. unset($_POST['product_label']);
  593. unset($_POST['product_desc']);
  594. unset($_POST['fournprice']);
  595. unset($_POST['buying_price']);
  596. unset($_POST['np_marginRate']);
  597. unset($_POST['np_markRate']);
  598. unset($_POST['dp_desc']);
  599. unset($_POST['idprod']);
  600. unset($_POST['units']);
  601. unset($_POST['date_starthour']);
  602. unset($_POST['date_startmin']);
  603. unset($_POST['date_startsec']);
  604. unset($_POST['date_startday']);
  605. unset($_POST['date_startmonth']);
  606. unset($_POST['date_startyear']);
  607. unset($_POST['date_endhour']);
  608. unset($_POST['date_endmin']);
  609. unset($_POST['date_endsec']);
  610. unset($_POST['date_endday']);
  611. unset($_POST['date_endmonth']);
  612. unset($_POST['date_endyear']);
  613. unset($_POST['date_start_fill']);
  614. unset($_POST['date_end_fill']);
  615. unset($_POST['situations']);
  616. unset($_POST['progress']);
  617. } else {
  618. setEventMessages($object->error, $object->errors, 'errors');
  619. }
  620. $action = '';
  621. }
  622. }
  623. } elseif ($action == 'updateline' && $usercancreate && !GETPOST('cancel', 'alpha')) {
  624. if (!$object->fetch($id) > 0) {
  625. dol_print_error($db);
  626. }
  627. $object->fetch_thirdparty();
  628. // Clean parameters
  629. $date_start = '';
  630. $date_end = '';
  631. //$date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear'));
  632. //$date_end = dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear'));
  633. $description = dol_htmlcleanlastbr(GETPOST('product_desc', 'restricthtml') ? GETPOST('product_desc', 'restricthtml') : GETPOST('desc', 'restricthtml'));
  634. $pu_ht = price2num(GETPOST('price_ht'), '', 2);
  635. $vat_rate = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0);
  636. $qty = GETPOST('qty');
  637. $pu_ht_devise = price2num(GETPOST('multicurrency_subprice'), '', 2);
  638. // Define info_bits
  639. $info_bits = 0;
  640. if (preg_match('/\*/', $vat_rate)) {
  641. $info_bits |= 0x01;
  642. }
  643. // Define vat_rate
  644. $vat_rate = str_replace('*', '', $vat_rate);
  645. $localtax1_rate = get_localtax($vat_rate, 1, $object->thirdparty);
  646. $localtax2_rate = get_localtax($vat_rate, 2, $object->thirdparty);
  647. // Add buying price
  648. $fournprice = price2num(GETPOST('fournprice') ? GETPOST('fournprice') : '');
  649. $buyingprice = price2num(GETPOST('buying_price') != '' ? GETPOST('buying_price') : ''); // If buying_price is '0', we muste keep this value
  650. // Extrafields
  651. $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
  652. $array_options = $extrafields->getOptionalsFromPost($object->table_element_line);
  653. $objectline = new FactureLigneRec($db);
  654. if ($objectline->fetch(GETPOST('lineid', 'int'))) {
  655. $objectline->array_options = $array_options;
  656. $result = $objectline->insertExtraFields();
  657. if ($result < 0) {
  658. setEventMessages($langs->trans('Error').$result, null, 'errors');
  659. }
  660. }
  661. $position = ($objectline->rang >= 0 ? $objectline->rang : 0);
  662. // Unset extrafield
  663. if (is_array($extralabelsline)) {
  664. // Get extra fields
  665. foreach ($extralabelsline as $key => $value) {
  666. unset($_POST["options_".$key]);
  667. }
  668. }
  669. // Define special_code for special lines
  670. $special_code = GETPOST('special_code', 'int');
  671. if ($special_code == 3) {
  672. $special_code = 0; // Options should not exists on invoices
  673. }
  674. /*$line = new FactureLigne($db);
  675. $line->fetch(GETPOST('lineid', 'int'));
  676. $percent = $line->get_prev_progress($object->id);
  677. if (GETPOST('progress') < $percent)
  678. {
  679. $mesg = '<div class="warning">' . $langs->trans("CantBeLessThanMinPercent") . '</div>';
  680. setEventMessages($mesg, null, 'warnings');
  681. $error++;
  682. $result = -1;
  683. }*/
  684. $remise_percent = price2num(GETPOST('remise_percent'), '', 2);
  685. if (empty($remise_percent)) {
  686. $remise_percent = 0;
  687. }
  688. // Check minimum price
  689. $productid = GETPOST('productid', 'int');
  690. if (!empty($productid)) {
  691. $product = new Product($db);
  692. $product->fetch($productid);
  693. $type = $product->type;
  694. $price_min = $product->price_min;
  695. if (!empty($conf->global->PRODUIT_MULTIPRICES) && !empty($object->thirdparty->price_level)) {
  696. $price_min = $product->multiprices_min[$object->thirdparty->price_level];
  697. }
  698. $label = ((GETPOST('update_label') && GETPOST('product_label')) ? GETPOST('product_label') : '');
  699. $typeinvoice = Facture::TYPE_STANDARD;
  700. // Check price is not lower than minimum (check is done only for standard or replacement invoices)
  701. 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)))) {
  702. setEventMessages($langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, - 1, $conf->currency)), null, 'errors');
  703. $error++;
  704. }
  705. } else {
  706. $type = GETPOST('type', 'int');
  707. $label = (GETPOST('product_label') ? GETPOST('product_label') : '');
  708. // Check parameters
  709. if (GETPOST('type', 'int') < 0) {
  710. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
  711. $error++;
  712. }
  713. }
  714. if ($qty < 0) {
  715. $langs->load("errors");
  716. setEventMessages($langs->trans('ErrorQtyForCustomerInvoiceCantBeNegative'), null, 'errors');
  717. $error++;
  718. }
  719. $date_start_fill = GETPOST('date_start_fill', 'int');
  720. $date_end_fill = GETPOST('date_end_fill', 'int');
  721. // Update line
  722. if (!$error) {
  723. $result = $object->updateline(
  724. GETPOST('lineid', 'int'),
  725. $description,
  726. $pu_ht,
  727. $qty,
  728. $vat_rate,
  729. $localtax1_rate,
  730. $localtax1_rate,
  731. GETPOST('productid', 'int'),
  732. $remise_percent,
  733. 'HT',
  734. $info_bits,
  735. 0,
  736. 0,
  737. $type,
  738. $position,
  739. $special_code,
  740. $label,
  741. GETPOST('units'),
  742. $pu_ht_devise,
  743. 0,
  744. $date_start_fill,
  745. $date_end_fill,
  746. $fournprice,
  747. $buyingprice
  748. );
  749. if ($result >= 0) {
  750. /*if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  751. // Define output language
  752. $outputlangs = $langs;
  753. $newlang = '';
  754. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id','aZ09'))
  755. $newlang = GETPOST('lang_id','aZ09');
  756. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang))
  757. $newlang = $object->thirdparty->default_lang;
  758. if (!empty($newlang)) {
  759. $outputlangs = new Translate("", $conf);
  760. $outputlangs->setDefaultLang($newlang);
  761. }
  762. $ret = $object->fetch($id); // Reload to get new records
  763. $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  764. }*/
  765. $object->fetch($object->id); // Reload lines
  766. unset($_POST['qty']);
  767. unset($_POST['type']);
  768. unset($_POST['productid']);
  769. unset($_POST['remise_percent']);
  770. unset($_POST['price_ht']);
  771. unset($_POST['multicurrency_price_ht']);
  772. unset($_POST['price_ttc']);
  773. unset($_POST['tva_tx']);
  774. unset($_POST['product_ref']);
  775. unset($_POST['product_label']);
  776. unset($_POST['product_desc']);
  777. unset($_POST['fournprice']);
  778. unset($_POST['buying_price']);
  779. unset($_POST['np_marginRate']);
  780. unset($_POST['np_markRate']);
  781. unset($_POST['dp_desc']);
  782. unset($_POST['idprod']);
  783. unset($_POST['units']);
  784. unset($_POST['date_starthour']);
  785. unset($_POST['date_startmin']);
  786. unset($_POST['date_startsec']);
  787. unset($_POST['date_startday']);
  788. unset($_POST['date_startmonth']);
  789. unset($_POST['date_startyear']);
  790. unset($_POST['date_endhour']);
  791. unset($_POST['date_endmin']);
  792. unset($_POST['date_endsec']);
  793. unset($_POST['date_endday']);
  794. unset($_POST['date_endmonth']);
  795. unset($_POST['date_endyear']);
  796. unset($_POST['situations']);
  797. unset($_POST['progress']);
  798. } else {
  799. setEventMessages($object->error, $object->errors, 'errors');
  800. }
  801. }
  802. }
  803. }
  804. /*
  805. * View
  806. */
  807. $help_url = '';
  808. llxHeader('', $langs->trans("RepeatableInvoices"), $help_url);
  809. $form = new Form($db);
  810. $formother = new FormOther($db);
  811. if (isModEnabled('project')) {
  812. $formproject = new FormProjets($db);
  813. }
  814. $companystatic = new Societe($db);
  815. $invoicerectmp = new FactureRec($db);
  816. $now = dol_now();
  817. $nowlasthour = dol_get_last_hour($now);
  818. /*
  819. * Create mode
  820. */
  821. if ($action == 'create') {
  822. print load_fiche_titre($langs->trans("CreateRepeatableInvoice"), '', 'bill');
  823. $object = new Facture($db); // Source invoice
  824. $product_static = new Product($db);
  825. if ($object->fetch($id, $ref) > 0) {
  826. $result = $object->getLinesArray();
  827. print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
  828. print '<input type="hidden" name="token" value="'.newToken().'">';
  829. print '<input type="hidden" name="action" value="add">';
  830. print '<input type="hidden" name="facid" value="'.$object->id.'">';
  831. print dol_get_fiche_head(null, '', '', 0);
  832. $rowspan = 4;
  833. if (isModEnabled('project')) {
  834. $rowspan++;
  835. }
  836. if ($object->fk_account > 0) {
  837. $rowspan++;
  838. }
  839. print '<table class="border centpercent">';
  840. $object->fetch_thirdparty();
  841. // Title
  842. print '<tr><td class="titlefieldcreate fieldrequired">'.$langs->trans("Title").'</td><td>';
  843. print '<input class="flat quatrevingtpercent" type="text" name="title" value="'.dol_escape_htmltag(GETPOST("title", 'alphanohtml')).'" autofocus>';
  844. print '</td></tr>';
  845. // Third party
  846. print '<tr><td class="titlefieldcreate">'.$langs->trans("Customer").'</td><td>'.$object->thirdparty->getNomUrl(1, 'customer').'</td>';
  847. print '</tr>';
  848. $note_public = GETPOSTISSET('note_public') ? GETPOST('note_public', 'restricthtml') : $object->note_public;
  849. $note_private = GETPOSTISSET('note_private') ? GETPOST('note_private', 'restricthtml') : $object->note_private;
  850. // Help of substitution key
  851. $substitutionarray = getCommonSubstitutionArray($langs, 2, null, $object);
  852. $substitutionarray['__INVOICE_PREVIOUS_MONTH__'] = $langs->trans("PreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, -1, 'm'), '%m').')';
  853. $substitutionarray['__INVOICE_MONTH__'] = $langs->trans("MonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($object->date, '%m').')';
  854. $substitutionarray['__INVOICE_NEXT_MONTH__'] = $langs->trans("NextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, 1, 'm'), '%m').')';
  855. $substitutionarray['__INVOICE_PREVIOUS_MONTH_TEXT__'] = $langs->trans("TextPreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, -1, 'm'), '%B').')';
  856. $substitutionarray['__INVOICE_MONTH_TEXT__'] = $langs->trans("TextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($object->date, '%B').')';
  857. $substitutionarray['__INVOICE_NEXT_MONTH_TEXT__'] = $langs->trans("TextNextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, 1, 'm'), '%B').')';
  858. $substitutionarray['__INVOICE_PREVIOUS_YEAR__'] = $langs->trans("PreviousYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, -1, 'y'), '%Y').')';
  859. $substitutionarray['__INVOICE_YEAR__'] = $langs->trans("YearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($object->date, '%Y').')';
  860. $substitutionarray['__INVOICE_NEXT_YEAR__'] = $langs->trans("NextYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, 1, 'y'), '%Y').')';
  861. // Only on template invoices
  862. $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').')';
  863. $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').')';
  864. $substitutionarray['__INVOICE_COUNTER_CURRENT__'] = $langs->trans("Count");
  865. $substitutionarray['__INVOICE_COUNTER_MAX__'] = $langs->trans("MaxPeriodNumber");
  866. $htmltext = '<i>'.$langs->trans("FollowingConstantsWillBeSubstituted").':<br>';
  867. foreach ($substitutionarray as $key => $val) {
  868. $htmltext .= $key.' = '.$langs->trans($val).'<br>';
  869. }
  870. $htmltext .= '</i>';
  871. // Public note
  872. print '<tr>';
  873. print '<td class="tdtop">';
  874. print $form->textwithpicto($langs->trans('NotePublic'), $htmltext, 1, 'help', '', 0, 2, 'notepublic');
  875. print '</td>';
  876. print '<td>';
  877. $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%');
  878. print $doleditor->Create(1);
  879. // Private note
  880. if (empty($user->socid)) {
  881. print '<tr>';
  882. print '<td class="tdtop">';
  883. print $form->textwithpicto($langs->trans('NotePrivate'), $htmltext, 1, 'help', '', 0, 2, 'noteprivate');
  884. print '</td>';
  885. print '<td>';
  886. $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%');
  887. print $doleditor->Create(1);
  888. // print '<textarea name="note_private" wrap="soft" cols="70" rows="'.ROWS_3.'">'.$note_private.'.</textarea>
  889. print '</td></tr>';
  890. }
  891. // Author
  892. print "<tr><td>".$langs->trans("Author")."</td><td>".$user->getFullName($langs)."</td></tr>";
  893. // Payment term
  894. print "<tr><td>".$langs->trans("PaymentConditions")."</td><td>";
  895. print $form->getSelectConditionsPaiements(GETPOSTISSET('cond_reglement_id') ? GETPOST('cond_reglement_id', 'int') : $object->cond_reglement_id, 'cond_reglement_id', -1, 0, 0, '');
  896. //$form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->cond_reglement_id, 'cond_reglement_id');
  897. print "</td></tr>";
  898. // Payment mode
  899. print "<tr><td>".$langs->trans("PaymentMode")."</td><td>";
  900. print img_picto('', 'payment', 'class="pictofixedwidth"');
  901. 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);
  902. //$form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'mode_reglement_id', '', 1);
  903. print "</td></tr>";
  904. // Bank account
  905. if ($object->fk_account > 0) {
  906. print "<tr><td>".$langs->trans('BankAccount')."</td><td>";
  907. $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none');
  908. print "</td></tr>";
  909. }
  910. // Project
  911. if (isModEnabled('project') && is_object($object->thirdparty) && $object->thirdparty->id > 0) {
  912. $projectid = GETPOST('projectid') ?GETPOST('projectid') : $object->fk_project;
  913. $langs->load('projects');
  914. print '<tr><td>'.$langs->trans('Project').'</td><td>';
  915. print img_picto('', 'project', 'class="pictofixedwidth"');
  916. $numprojet = $formproject->select_projects($object->thirdparty->id, $projectid, 'projectid', 0, 0, 1, 0, 0, 0, 0, '', 0, 0, '');
  917. 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>';
  918. print '</td></tr>';
  919. }
  920. // Model pdf
  921. print "<tr><td>".$langs->trans('Model')."</td><td>";
  922. include_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php';
  923. $list = ModelePDFFactures::liste_modeles($db);
  924. print img_picto('', 'generic', 'class="pictofixedwidth"');
  925. print $form->selectarray('modelpdf', $list, $conf->global->FACTURE_ADDON_PDF);
  926. print "</td></tr>";
  927. print "</table>";
  928. print dol_get_fiche_end();
  929. // Autogeneration
  930. $title = $langs->trans("Recurrence");
  931. print load_fiche_titre(img_picto('', 'recurring', 'class="pictofixedwidth"').$title, '', '');
  932. print dol_get_fiche_head(null, '', '', 0);
  933. print '<table class="border centpercent">';
  934. // Frequency + unit
  935. print '<tr><td class="titlefieldcreate">'.$form->textwithpicto($langs->trans("Frequency"), $langs->transnoentitiesnoconv('toolTipFrequency'))."</td><td>";
  936. print "<input type='text' name='frequency' value='".GETPOST('frequency', 'int')."' size='4' />&nbsp;";
  937. 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'));
  938. print "</td></tr>";
  939. // Date next run
  940. print "<tr><td>".$langs->trans('NextDateToExecution')."</td><td>";
  941. $date_next_execution = isset($date_next_execution) ? $date_next_execution : (GETPOST('remonth') ? dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')) : -1);
  942. print $form->selectDate($date_next_execution, '', 1, 1, '', "add", 1, 1);
  943. print "</td></tr>";
  944. // Number max of generation
  945. print "<tr><td>".$langs->trans("MaxPeriodNumber")."</td><td>";
  946. print '<input type="text" name="nb_gen_max" value="'.GETPOST('nb_gen_max').'" size="5" />';
  947. print "</td></tr>";
  948. // Auto validate the invoice
  949. print "<tr><td>".$langs->trans("StatusOfGeneratedInvoices")."</td><td>";
  950. $select = array('0'=>$langs->trans('BillStatusDraft'), '1'=>$langs->trans('BillStatusValidated'));
  951. print $form->selectarray('auto_validate', $select, GETPOST('auto_validate'));
  952. print "</td></tr>";
  953. // Auto generate document
  954. if (!empty($conf->global->INVOICE_REC_CAN_DISABLE_DOCUMENT_FILE_GENERATION)) {
  955. print "<tr><td>".$langs->trans("StatusOfGeneratedDocuments")."</td><td>";
  956. $select = array('0'=>$langs->trans('DoNotGenerateDoc'), '1'=>$langs->trans('AutoGenerateDoc'));
  957. print $form->selectarray('generate_pdf', $select, GETPOST('generate_pdf'));
  958. print "</td></tr>";
  959. } else {
  960. print '<input type="hidden" name="generate_pdf" value="1">';
  961. }
  962. print "</table>";
  963. print dol_get_fiche_end();
  964. $title = $langs->trans("ProductsAndServices");
  965. if (!isModEnabled('service')) {
  966. $title = $langs->trans("Products");
  967. } elseif (!isModEnabled('product')) {
  968. $title = $langs->trans("Services");
  969. }
  970. print load_fiche_titre($title, '', '');
  971. /*
  972. * Invoice lines
  973. */
  974. print '<div class="div-table-responsive-no-min">';
  975. print '<table id="tablelines" class="noborder noshadow" width="100%">';
  976. // Show object lines
  977. if (!empty($object->lines)) {
  978. $disableedit = 1;
  979. $disablemove = 1;
  980. $disableremove = 1;
  981. $object->printObjectLines('', $mysoc, $object->thirdparty, $lineid, 0); // No date selector for template invoice
  982. }
  983. print "</table>\n";
  984. print '<div>';
  985. print '</td></tr>';
  986. if ($flag_price_may_change) {
  987. print '<tr><td colspan="3" class="left">';
  988. print '<select name="usenewprice" class="flat">';
  989. print '<option value="0">'.$langs->trans("AlwaysUseFixedPrice").'</option>';
  990. print '<option value="1" disabled>'.$langs->trans("AlwaysUseNewPrice").'</option>';
  991. print '</select>';
  992. print '</td></tr>';
  993. }
  994. print "</table>\n";
  995. print $form->buttonsSaveCancel("Create");
  996. print "</form>\n";
  997. } else {
  998. dol_print_error('', "Error, no invoice ".$object->id);
  999. }
  1000. } else {
  1001. /*
  1002. * View mode
  1003. */
  1004. if ($object->id > 0) {
  1005. $object->fetch_thirdparty();
  1006. // Confirmation de la suppression d'une ligne produit
  1007. if ($action == 'ask_deleteline') {
  1008. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 'no', 1);
  1009. }
  1010. // Confirm delete of repeatable invoice
  1011. if ($action == 'delete') {
  1012. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteRepeatableInvoice'), $langs->trans('ConfirmDeleteRepeatableInvoice'), 'confirm_delete', '', 'no', 1);
  1013. }
  1014. // Call Hook formConfirm
  1015. $parameters = array('formConfirm' => $formconfirm);
  1016. $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  1017. if (empty($reshook)) {
  1018. $formconfirm .= $hookmanager->resPrint;
  1019. } elseif ($reshook > 0) {
  1020. $formconfirm = $hookmanager->resPrint;
  1021. }
  1022. print $formconfirm;
  1023. $author = new User($db);
  1024. $author->fetch($object->user_author);
  1025. $head = invoice_rec_prepare_head($object);
  1026. print dol_get_fiche_head($head, 'card', $langs->trans("RepeatableInvoice"), -1, 'bill'); // Add a div
  1027. // Recurring invoice content
  1028. $linkback = '<a href="'.DOL_URL_ROOT.'/compta/facture/invoicetemplate_list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
  1029. $morehtmlref = '';
  1030. if ($action != 'editref') {
  1031. $morehtmlref .= $form->editfieldkey($object->ref, 'ref', $object->ref, $object, $user->hasRight('facture', 'creer'), '', '', 0, 2);
  1032. } else {
  1033. $morehtmlref .= $form->editfieldval('', 'ref', $object->ref, $object, $user->hasRight('facture', 'creer'), 'string');
  1034. }
  1035. $morehtmlref .= '<div class="refidno">';
  1036. // Ref customer
  1037. //$morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $user->hasRight('facture', 'creer'), 'string', '', 0, 1);
  1038. //$morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $user->hasRight('facture', 'creer'), 'string', '', null, null, '', 1);
  1039. // Thirdparty
  1040. $morehtmlref .= $langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1);
  1041. // Project
  1042. if (isModEnabled('project')) {
  1043. $langs->load("projects");
  1044. $morehtmlref .= '<br>'.$langs->trans('Project').' ';
  1045. if ($user->hasRight('facture', 'creer')) {
  1046. if ($action != 'classify') {
  1047. $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : ';
  1048. }
  1049. if ($action == 'classify') {
  1050. //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
  1051. $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
  1052. $morehtmlref .= '<input type="hidden" name="action" value="classin">';
  1053. $morehtmlref .= '<input type="hidden" name="token" value="'.newToken().'">';
  1054. $morehtmlref .= $formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
  1055. $morehtmlref .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  1056. $morehtmlref .= '</form>';
  1057. } else {
  1058. $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1, '', 'maxwidth300');
  1059. }
  1060. } else {
  1061. if (!empty($object->fk_project)) {
  1062. $proj = new Project($db);
  1063. $proj->fetch($object->fk_project);
  1064. $morehtmlref .= ' : '.$proj->getNomUrl(1);
  1065. if ($proj->title) {
  1066. $morehtmlref .= ' - '.$proj->title;
  1067. }
  1068. } else {
  1069. $morehtmlref .= '';
  1070. }
  1071. }
  1072. }
  1073. $morehtmlref .= '</div>';
  1074. $morehtmlright = '';
  1075. dol_banner_tab($object, 'ref', $linkback, 1, 'title', 'none', $morehtmlref, '', 0, '', $morehtmlright);
  1076. print '<div class="fichecenter">';
  1077. print '<div class="fichehalfleft">';
  1078. print '<div class="underbanner clearboth"></div>';
  1079. print '<table class="border centpercent tableforfield">';
  1080. print '<tr><td class="titlefield">'.$langs->trans("Author").'</td><td>';
  1081. print $author->getNomUrl(-1);
  1082. print "</td></tr>";
  1083. print '<tr><td>'.$langs->trans("AmountHT").'</td>';
  1084. print '<td>'.price($object->total_ht, '', $langs, 1, -1, -1, $conf->currency).'</td>';
  1085. print '</tr>';
  1086. print '<tr><td>'.$langs->trans("AmountVAT").'</td><td>'.price($object->total_tva, '', $langs, 1, -1, -1, $conf->currency).'</td>';
  1087. print '</tr>';
  1088. // Amount Local Taxes
  1089. if (($mysoc->localtax1_assuj == "1" && $mysoc->useLocalTax(1)) || $object->total_localtax1 != 0) { // Localtax1
  1090. print '<tr><td>'.$langs->transcountry("AmountLT1", $mysoc->country_code).'</td>';
  1091. print '<td class="nowrap">'.price($object->total_localtax1, 1, '', 1, - 1, - 1, $conf->currency).'</td></tr>';
  1092. }
  1093. if (($mysoc->localtax2_assuj == "1" && $mysoc->useLocalTax(2)) || $object->total_localtax2 != 0) { // Localtax2
  1094. print '<tr><td>'.$langs->transcountry("AmountLT2", $mysoc->country_code).'</td>';
  1095. print '<td class=nowrap">'.price($object->total_localtax2, 1, '', 1, - 1, - 1, $conf->currency).'</td></tr>';
  1096. }
  1097. print '<tr><td>'.$langs->trans("AmountTTC").'</td><td colspan="3">'.price($object->total_ttc, '', $langs, 1, -1, -1, $conf->currency).'</td>';
  1098. print '</tr>';
  1099. // Payment term
  1100. print '<tr><td>';
  1101. print '<table class="nobordernopadding centpercent"><tr><td>';
  1102. print $langs->trans('PaymentConditionsShort');
  1103. print '</td>';
  1104. if ($action != 'editconditions' && $user->hasRight('facture', 'creer')) {
  1105. 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>';
  1106. }
  1107. print '</tr></table>';
  1108. print '</td><td>';
  1109. if ($object->type != Facture::TYPE_CREDIT_NOTE) {
  1110. if ($action == 'editconditions') {
  1111. $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->cond_reglement_id, 'cond_reglement_id');
  1112. } else {
  1113. $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->cond_reglement_id, 'none');
  1114. }
  1115. } else {
  1116. print '&nbsp;';
  1117. }
  1118. print '</td></tr>';
  1119. // Payment mode
  1120. print '<tr><td>';
  1121. print '<table class="nobordernopadding" width="100%"><tr><td>';
  1122. print $langs->trans('PaymentMode');
  1123. print '</td>';
  1124. if ($action != 'editmode' && $user->hasRight('facture', 'creer')) {
  1125. 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>';
  1126. }
  1127. print '</tr></table>';
  1128. print '</td><td>';
  1129. if ($action == 'editmode') {
  1130. $form->form_modes_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->mode_reglement_id, 'mode_reglement_id', 'CRDT', 1, 1);
  1131. } else {
  1132. $form->form_modes_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->mode_reglement_id, 'none');
  1133. }
  1134. print '</td></tr>';
  1135. // Multicurrency
  1136. if (isModEnabled('multicurrency')) {
  1137. // Multicurrency code
  1138. print '<tr>';
  1139. print '<td>';
  1140. print '<table class="nobordernopadding" width="100%"><tr><td>';
  1141. print $form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0);
  1142. print '</td>';
  1143. if ($usercancreate && $action != 'editmulticurrencycode' && !empty($object->brouillon)) {
  1144. 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>';
  1145. }
  1146. print '</tr></table>';
  1147. print '</td><td>';
  1148. $htmlname = (($usercancreate && $action == 'editmulticurrencycode') ? 'multicurrency_code' : 'none');
  1149. $form->form_multicurrency_code($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_code, $htmlname);
  1150. print '</td></tr>';
  1151. // Multicurrency rate
  1152. if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) {
  1153. print '<tr>';
  1154. print '<td>';
  1155. print '<table class="nobordernopadding" width="100%"><tr><td>';
  1156. print $form->editfieldkey('CurrencyRate', 'multicurrency_tx', '', $object, 0);
  1157. print '</td>';
  1158. if ($usercancreate && $action != 'editmulticurrencyrate' && !empty($object->brouillon) && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) {
  1159. 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>';
  1160. }
  1161. print '</tr></table>';
  1162. print '</td><td>';
  1163. if ($action == 'editmulticurrencyrate' || $action == 'actualizemulticurrencyrate') {
  1164. if ($action == 'actualizemulticurrencyrate') {
  1165. list($object->fk_multicurrency, $object->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($object->db, $object->multicurrency_code);
  1166. }
  1167. $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_tx, ($usercancreate ? 'multicurrency_tx' : 'none'), $object->multicurrency_code);
  1168. } else {
  1169. $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_tx, 'none', $object->multicurrency_code);
  1170. if ($object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) {
  1171. print '<div class="inline-block"> &nbsp; &nbsp; &nbsp; &nbsp; ';
  1172. print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=actualizemulticurrencyrate">'.$langs->trans("ActualizeCurrency").'</a>';
  1173. print '</div>';
  1174. }
  1175. }
  1176. print '</td></tr>';
  1177. }
  1178. }
  1179. // Help of substitution key
  1180. $dateexample = dol_now();
  1181. if (!empty($object->frequency) && !empty($object->date_when)) {
  1182. $dateexample = $object->date_when;
  1183. }
  1184. // Help of substitution key
  1185. $substitutionarray = getCommonSubstitutionArray($langs, 2, null, $object);
  1186. $substitutionarray['__INVOICE_PREVIOUS_MONTH__'] = $langs->trans("PreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'), '%m').')';
  1187. $substitutionarray['__INVOICE_MONTH__'] = $langs->trans("MonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample, '%m').')';
  1188. $substitutionarray['__INVOICE_NEXT_MONTH__'] = $langs->trans("NextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'), '%m').')';
  1189. $substitutionarray['__INVOICE_PREVIOUS_MONTH_TEXT__'] = $langs->trans("TextPreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'), '%B').')';
  1190. $substitutionarray['__INVOICE_MONTH_TEXT__'] = $langs->trans("TextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample, '%B').')';
  1191. $substitutionarray['__INVOICE_NEXT_MONTH_TEXT__'] = $langs->trans("TextNextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'), '%B').')';
  1192. $substitutionarray['__INVOICE_PREVIOUS_YEAR__'] = $langs->trans("PreviousYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'y'), '%Y').')';
  1193. $substitutionarray['__INVOICE_YEAR__'] = $langs->trans("YearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample, '%Y').')';
  1194. $substitutionarray['__INVOICE_NEXT_YEAR__'] = $langs->trans("NextYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'y'), '%Y').')';
  1195. // Only on template invoices
  1196. $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').')';
  1197. $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').')';
  1198. $substitutionarray['__INVOICE_COUNTER_CURRENT__'] = $object->nb_gen_done;
  1199. $substitutionarray['__INVOICE_COUNTER_MAX__'] = $object->nb_gen_max;
  1200. $htmltext = '<i>'.$langs->trans("FollowingConstantsWillBeSubstituted").':<br>';
  1201. foreach ($substitutionarray as $key => $val) {
  1202. $htmltext .= $key.' = '.$langs->trans($val).'<br>';
  1203. }
  1204. $htmltext .= '</i>';
  1205. // Note public
  1206. print '<tr><td>';
  1207. print $form->editfieldkey($form->textwithpicto($langs->trans('NotePublic'), $htmltext, 1, 'help', '', 0, 2, 'notepublic'), 'note_public', $object->note_public, $object, $user->hasRight('facture', 'creer'));
  1208. print '</td><td class="wordbreak">';
  1209. print $form->editfieldval($langs->trans("NotePublic"), 'note_public', $object->note_public, $object, $user->hasRight('facture', 'creer'), 'textarea:'.ROWS_4.':90%', '', null, null, '', 1);
  1210. print '</td>';
  1211. print '</tr>';
  1212. // Note private
  1213. print '<tr><td>';
  1214. print $form->editfieldkey($form->textwithpicto($langs->trans("NotePrivate"), $htmltext, 1, 'help', '', 0, 2, 'noteprivate'), 'note_private', $object->note_private, $object, $user->hasRight('facture', 'creer'));
  1215. print '</td><td class="wordbreak">';
  1216. print $form->editfieldval($langs->trans("NotePrivate"), 'note_private', $object->note_private, $object, $user->hasRight('facture', 'creer'), 'textarea:'.ROWS_4.':90%', '', null, null, '', 1);
  1217. print '</td>';
  1218. print '</tr>';
  1219. // Bank Account
  1220. print '<tr><td class="nowrap">';
  1221. print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">';
  1222. print $langs->trans('BankAccount');
  1223. print '<td>';
  1224. if (($action != 'editbankaccount') && $user->hasRight('facture', 'creer') && $object->statut == FactureRec::STATUS_DRAFT) {
  1225. 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>';
  1226. }
  1227. print '</tr></table>';
  1228. print '</td><td>';
  1229. if ($action == 'editbankaccount') {
  1230. $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1);
  1231. } else {
  1232. $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none');
  1233. }
  1234. print "</td>";
  1235. print '</tr>';
  1236. // Model pdf
  1237. print '<tr><td class="nowrap">';
  1238. print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">';
  1239. print $langs->trans('Model');
  1240. print '<td>';
  1241. if (($action != 'editmodelpdf') && $user->hasRight('facture', 'creer') && $object->statut == FactureRec::STATUS_DRAFT) {
  1242. 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>';
  1243. }
  1244. print '</tr></table>';
  1245. print '</td><td>';
  1246. if ($action == 'editmodelpdf') {
  1247. include_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php';
  1248. $list = array();
  1249. $models = ModelePDFFactures::liste_modeles($db);
  1250. foreach ($models as $k => $model) {
  1251. $list[] = str_replace(':', '|', $k).':'.$model;
  1252. }
  1253. $select = 'select;'.implode(',', $list);
  1254. print $form->editfieldval($langs->trans("Model"), 'modelpdf', $object->model_pdf, $object, $user->hasRight('facture', 'creer'), $select);
  1255. } else {
  1256. print $object->model_pdf;
  1257. }
  1258. print "</td>";
  1259. print '</tr>';
  1260. // Other attributes
  1261. $cols = 2;
  1262. include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
  1263. print '</table>';
  1264. print '</div>';
  1265. print '<div class="fichehalfright">';
  1266. print '<div class="underbanner clearboth"></div>';
  1267. /*
  1268. * Recurrence
  1269. */
  1270. $title = $langs->trans("Recurrence");
  1271. //print load_fiche_titre($title, '', 'calendar');
  1272. print '<table class="border centpercent tableforfield">';
  1273. print '<tr><td colspan="2">'.img_picto('', 'recurring', 'class="pictofixedwidth"').$title.'</td></tr>';
  1274. // if "frequency" is empty or = 0, the reccurence is disabled
  1275. print '<tr><td style="width: 50%">';
  1276. print '<table class="nobordernopadding" width="100%"><tr><td>';
  1277. print $langs->trans('Frequency');
  1278. print '</td>';
  1279. if ($action != 'editfrequency' && $user->hasRight('facture', 'creer')) {
  1280. 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>';
  1281. }
  1282. print '</tr></table>';
  1283. print '</td><td>';
  1284. if ($action == 'editfrequency') {
  1285. print '<form method="post" action="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'">';
  1286. print '<input type="hidden" name="action" value="setfrequency">';
  1287. print '<input type="hidden" name="token" value="'.newToken().'">';
  1288. print '<table class="nobordernopadding">';
  1289. print '<tr><td>';
  1290. print "<input type='text' name='frequency' value='".$object->frequency."' size='5' />&nbsp;";
  1291. 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'));
  1292. print '</td>';
  1293. print '<td class="left"><input type="submit" class="button button-edit smallpaddingimp" value="'.$langs->trans("Modify").'"></td>';
  1294. print '</tr></table></form>';
  1295. } else {
  1296. if ($object->frequency > 0) {
  1297. print $langs->trans('FrequencyPer_'.$object->unit_frequency, $object->frequency);
  1298. } else {
  1299. print '<span class="opacitymedium">'.$langs->trans("NotARecurringInvoiceTemplate").'</span>';
  1300. }
  1301. }
  1302. print '</td></tr>';
  1303. // Date when (next invoice generation)
  1304. print '<tr><td>';
  1305. if ($action == 'date_when' || $object->frequency > 0) {
  1306. print $form->editfieldkey($langs->trans("NextDateToExecution"), 'date_when', $object->date_when, $object, $user->hasRight('facture', 'creer'), 'day');
  1307. } else {
  1308. print $langs->trans("NextDateToExecution");
  1309. }
  1310. print '</td><td>';
  1311. if ($action == 'date_when' || $object->frequency > 0) {
  1312. print $form->editfieldval($langs->trans("NextDateToExecution"), 'date_when', $object->date_when, $object, $user->hasRight('facture', 'creer'), 'day', $object->date_when, null, '', '', 0, 'strikeIfMaxNbGenReached');
  1313. }
  1314. //var_dump(dol_print_date($object->date_when+60, 'dayhour').' - '.dol_print_date($now, 'dayhour'));
  1315. if (!$object->isMaxNbGenReached()) {
  1316. if (!$object->suspended && $action != 'editdate_when' && $object->frequency > 0 && $object->date_when && $object->date_when < $now) {
  1317. print img_warning($langs->trans("Late"));
  1318. }
  1319. } else {
  1320. print img_info($langs->trans("MaxNumberOfGenerationReached"));
  1321. }
  1322. print '</td>';
  1323. print '</tr>';
  1324. // Max period / Rest period
  1325. print '<tr><td>';
  1326. if ($action == 'nb_gen_max' || $object->frequency > 0) {
  1327. print $form->editfieldkey($langs->trans("MaxPeriodNumber"), 'nb_gen_max', $object->nb_gen_max, $object, $user->hasRight('facture', 'creer'));
  1328. } else {
  1329. print $langs->trans("MaxPeriodNumber");
  1330. }
  1331. print '</td><td>';
  1332. if ($action == 'nb_gen_max' || $object->frequency > 0) {
  1333. print $form->editfieldval($langs->trans("MaxPeriodNumber"), 'nb_gen_max', $object->nb_gen_max ? $object->nb_gen_max : '', $object, $user->hasRight('facture', 'creer'));
  1334. } else {
  1335. print '';
  1336. }
  1337. print '</td>';
  1338. print '</tr>';
  1339. // Status of generated invoices
  1340. print '<tr><td>';
  1341. if ($action == 'auto_validate' || $object->frequency > 0) {
  1342. print $form->editfieldkey($langs->trans("StatusOfGeneratedInvoices"), 'auto_validate', $object->auto_validate, $object, $user->hasRight('facture', 'creer'));
  1343. } else {
  1344. print $langs->trans("StatusOfGeneratedInvoices");
  1345. }
  1346. print '</td><td>';
  1347. $select = 'select;0:'.$langs->trans('BillStatusDraft').',1:'.$langs->trans('BillStatusValidated');
  1348. if ($action == 'auto_validate' || $object->frequency > 0) {
  1349. print $form->editfieldval($langs->trans("StatusOfGeneratedInvoices"), 'auto_validate', $object->auto_validate, $object, $user->hasRight('facture', 'creer'), $select);
  1350. }
  1351. print '</td>';
  1352. // Auto generate documents
  1353. if (!empty($conf->global->INVOICE_REC_CAN_DISABLE_DOCUMENT_FILE_GENERATION)) {
  1354. print '<tr>';
  1355. print '<td>';
  1356. if ($action == 'generate_pdf' || $object->frequency > 0) {
  1357. print $form->editfieldkey($langs->trans("StatusOfGeneratedDocuments"), 'generate_pdf', $object->generate_pdf, $object, $user->hasRight('facture', 'creer'));
  1358. } else {
  1359. print $langs->trans("StatusOfGeneratedDocuments");
  1360. }
  1361. print '</td>';
  1362. print '<td>';
  1363. $select = 'select;0:'.$langs->trans('DoNotGenerateDoc').',1:'.$langs->trans('AutogenerateDoc');
  1364. if ($action == 'generate_pdf' || $object->frequency > 0) {
  1365. print $form->editfieldval($langs->trans("StatusOfGeneratedDocuments"), 'generate_pdf', $object->generate_pdf, $object, $user->hasRight('facture', 'creer'), $select);
  1366. }
  1367. print '</td>';
  1368. print '</tr>';
  1369. } else {
  1370. print '<input type="hidden" name="generate_pdf" value="1">';
  1371. }
  1372. print '</table>';
  1373. // Frequencry/Recurring section
  1374. if ($object->frequency > 0) {
  1375. print '<br>';
  1376. if (!isModEnabled('cron')) {
  1377. print info_admin($langs->trans("EnableAndSetupModuleCron", $langs->transnoentitiesnoconv("Module2300Name")));
  1378. }
  1379. print '<div class="underbanner clearboth"></div>';
  1380. print '<table class="border centpercent tableforfield">';
  1381. // Nb of generation already done
  1382. print '<tr><td style="width: 50%">'.$langs->trans("NbOfGenerationDone").'</td>';
  1383. print '<td>';
  1384. print $object->nb_gen_done ? $object->nb_gen_done : '0';
  1385. print '</td>';
  1386. print '</tr>';
  1387. // Date last
  1388. print '<tr><td>';
  1389. print $langs->trans("DateLastGeneration");
  1390. print '</td><td>';
  1391. print dol_print_date($object->date_last_gen, 'dayhour');
  1392. print '</td>';
  1393. print '</tr>';
  1394. print '</table>';
  1395. print '<br>';
  1396. }
  1397. print '</div>';
  1398. print '</div>';
  1399. print '<div class="clearboth"></div><br>';
  1400. // Lines
  1401. print '<form name="addproduct" id="addproduct" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.(($action != 'editline') ? '#add' : '#line_'.GETPOST('lineid', 'int')).'" method="POST">';
  1402. print '<input type="hidden" name="token" value="' . newToken().'">';
  1403. print '<input type="hidden" name="action" value="' . (($action != 'editline') ? 'addline' : 'updateline').'">';
  1404. print '<input type="hidden" name="mode" value="">';
  1405. print '<input type="hidden" name="id" value="' . $object->id.'">';
  1406. print '<input type="hidden" name="page_y" value="">';
  1407. if (!empty($conf->use_javascript_ajax) && $object->statut == 0) {
  1408. include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php';
  1409. }
  1410. print '<div class="div-table-responsive-no-min">';
  1411. print '<table id="tablelines" class="noborder noshadow centpercent">';
  1412. // Show object lines
  1413. if (!empty($object->lines)) {
  1414. $canchangeproduct = 1;
  1415. $object->printObjectLines($action, $mysoc, $object->thirdparty, $lineid, 0); // No date selector for template invoice
  1416. }
  1417. // Form to add new line
  1418. if ($object->statut == $object::STATUS_DRAFT && $user->hasRight('facture', 'creer') && $action != 'valid' && $action != 'editline') {
  1419. if ($action != 'editline') {
  1420. // Add free products/services
  1421. $parameters = array();
  1422. $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  1423. if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  1424. if (empty($reshook))
  1425. $object->formAddObjectLine(0, $mysoc, $object->thirdparty); // No date selector for template invoice
  1426. }
  1427. }
  1428. print "</table>\n";
  1429. print '</div>';
  1430. print "</form>\n";
  1431. print dol_get_fiche_end();
  1432. /*
  1433. * Action bar
  1434. */
  1435. print '<div class="tabsAction">';
  1436. $parameters = array();
  1437. $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  1438. if (empty($reshook)) {
  1439. $params = array(
  1440. 'attr' => array(
  1441. 'class' => 'classfortooltip',
  1442. ),
  1443. );
  1444. if (empty($object->suspended)) {
  1445. if ($user->hasRight('facture', 'creer')) {
  1446. if (!empty($object->frequency) && $object->nb_gen_max > 0 && ($object->nb_gen_done >= $object->nb_gen_max)) {
  1447. print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="' . dol_escape_htmltag($langs->trans("MaxGenerationReached")) . '">' . $langs->trans("CreateBill") . '</a></div>';
  1448. } else {
  1449. if (empty($object->frequency) || $object->date_when <= $nowlasthour) {
  1450. 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>';
  1451. } else {
  1452. print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="' . dol_escape_htmltag($langs->trans("DateIsNotEnough")) . '">' . $langs->trans("CreateBill") . '</a></div>';
  1453. }
  1454. }
  1455. } else {
  1456. print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#">' . $langs->trans("CreateBill") . '</a></div>';
  1457. }
  1458. }
  1459. if ($user->hasRight('facture', 'creer')) {
  1460. if (empty($object->suspended)) {
  1461. 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>';
  1462. } else {
  1463. 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>';
  1464. }
  1465. }
  1466. // Delete
  1467. print dolGetButtonAction($langs->trans("Delete"), '', 'delete', $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&action=delete&token=' . newToken(), 'delete', $user->hasRight('facture', 'supprimer'));
  1468. }
  1469. print '</div>';
  1470. print '<div class="fichecenter"><div class="fichehalfleft">';
  1471. print '<a name="builddoc"></a>'; // ancre
  1472. // Show links to link elements
  1473. $linktoelem = $form->showLinkToObjectBlock($object, null, array('invoice'));
  1474. $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem);
  1475. print '</div>';
  1476. print '<div class="fichehalfright">';
  1477. $MAXEVENT = 10;
  1478. //$morehtmlcenter = dolGetButtonTitle($langs->trans('SeeAll'), '', 'fa fa-bars imgforviewmode', dol_buildpath('/mymodule/myobject_agenda.php', 1).'?id='.$object->id);
  1479. // List of actions on element
  1480. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
  1481. $formactions = new FormActions($db);
  1482. $somethingshown = $formactions->showactions($object, $object->element, (is_object($object->thirdparty) ? $object->thirdparty->id : 0), 1, '', $MAXEVENT, '', $morehtmlcenter);
  1483. print '</div>';
  1484. print '</div>';
  1485. }
  1486. }
  1487. // End of page
  1488. llxFooter();
  1489. $db->close();