fiche-rec.php 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863
  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@capnetworks.com>
  5. * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
  6. * Copyright (C) 2013 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.dolibarr@gmail.com>
  10. * Copyright (C) 2016 Meziane Sof <virtualsof@yahoo.fr>
  11. *
  12. * This program is free software; you can redistribute it and/or modify
  13. * it under the terms of the GNU General Public License as published by
  14. * the Free Software Foundation; either version 3 of the License, or
  15. * (at your option) any later version.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU General Public License
  23. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  24. */
  25. /**
  26. * \file htdocs/compta/facture/fiche-rec.php
  27. * \ingroup facture
  28. * \brief Page to show predefined invoice
  29. */
  30. require '../../main.inc.php';
  31. require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php';
  32. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  33. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
  34. if (! empty($conf->projet->enabled)) {
  35. require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
  36. //require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php';
  37. }
  38. require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php';
  39. require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
  40. require_once DOL_DOCUMENT_ROOT . '/core/lib/invoice.lib.php';
  41. $langs->load('bills');
  42. $langs->load('compta');
  43. $langs->load('admin');
  44. $langs->load('other');
  45. // Security check
  46. $id=(GETPOST('facid','int')?GETPOST('facid','int'):GETPOST('id','int'));
  47. $confirm = GETPOST('confirm', 'alpha');
  48. $cancel = GETPOST('cancel', 'alpha');
  49. $lineid=GETPOST('lineid','int');
  50. $ref=GETPOST('ref','alpha');
  51. $action=GETPOST('action', 'alpha');
  52. if ($user->societe_id) $socid=$user->societe_id;
  53. $objecttype = 'facture_rec';
  54. if ($action == "create" || $action == "add") $objecttype = '';
  55. $result = restrictedArea($user, 'facture', $id, $objecttype);
  56. $projectid = GETPOST('projectid','int');
  57. $search_ref=GETPOST('search_ref');
  58. $search_societe=GETPOST('search_societe');
  59. $search_montant_ht=GETPOST('search_montant_ht');
  60. $search_montant_vat=GETPOST('search_montant_vat');
  61. $search_montant_ttc=GETPOST('search_montant_ttc');
  62. $day=GETPOST('day');
  63. $year=GETPOST('year');
  64. $month=GETPOST('month');
  65. $day_date_when=GETPOST('day_date_when');
  66. $year_date_when=GETPOST('year_date_when');
  67. $month_date_when=GETPOST('month_date_when');
  68. $search_frequency=GETPOST('search_frequency');
  69. $limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit;
  70. $sortfield = GETPOST("sortfield",'alpha');
  71. $sortorder = GETPOST("sortorder",'alpha');
  72. $page = GETPOST("page",'int');
  73. if ($page == -1) { $page = 0; }
  74. $offset = $limit * $page;
  75. if (! $sortorder) $sortorder='DESC';
  76. if (! $sortfield) $sortfield='f.titre';
  77. $pageprev = $page - 1;
  78. $pagenext = $page + 1;
  79. $object = new FactureRec($db);
  80. if (($id > 0 || $ref) && $action != 'create' && $action != 'add')
  81. {
  82. $ret = $object->fetch($id, $ref);
  83. if (!$ret)
  84. {
  85. setEventMessages($langs->trans("ErrorRecordNotFound"), null, 'errors');
  86. }
  87. }
  88. // Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array
  89. $hookmanager->initHooks(array('invoicereccard','globalcard'));
  90. $extrafields = new ExtraFields($db);
  91. // fetch optionals attributes and labels
  92. $extralabels = $extrafields->fetch_name_optionals_label('facture');
  93. $search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search_');
  94. $permissionnote = $user->rights->facture->creer; // Used by the include of actions_setnotes.inc.php
  95. $permissiondellink=$user->rights->facture->creer; // Used by the include of actions_dellink.inc.php
  96. $permissiontoedit = $user->rights->facture->creer; // Used by the include of actions_lineupdonw.inc.php
  97. $arrayfields=array(
  98. 'f.titre'=>array('label'=>$langs->trans("Ref"), 'checked'=>1),
  99. 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1),
  100. 'f.total'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1),
  101. 'f.tva'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>1),
  102. 'f.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>1),
  103. 'f.frequency'=>array('label'=>$langs->trans("RecurringInvoiceTemplate"), 'checked'=>1),
  104. 'f.nb_gen_done'=>array('label'=>$langs->trans("NbGeneration"), 'checked'=>1),
  105. 'f.date_last_gen'=>array('label'=>$langs->trans("DateLastGeneration"), 'checked'=>1),
  106. 'f.date_when'=>array('label'=>$langs->trans("NextDateToExecution"), 'checked'=>1),
  107. 'f.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500),
  108. 'f.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500),
  109. );
  110. // Extra fields
  111. if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label))
  112. {
  113. foreach($extrafields->attribute_label as $key => $val)
  114. {
  115. $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>$extrafields->attribute_list[$key], 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]);
  116. }
  117. }
  118. /*
  119. * Actions
  120. */
  121. $parameters = array('socid' => $socid);
  122. $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  123. if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  124. if (empty($reshook))
  125. {
  126. if (GETPOST('cancel')) $action='';
  127. // Set note
  128. include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once
  129. include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once
  130. include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once
  131. // Do we click on purge search criteria ?
  132. if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETPOST("button_removefilter")) // All test are required to be compatible with all browsers
  133. {
  134. $search_ref='';
  135. $search_societe='';
  136. $search_montant_ht='';
  137. $search_montant_vat='';
  138. $search_montant_ttc='';
  139. $day='';
  140. $year='';
  141. $month='';
  142. $day_date_when='';
  143. $year_date_when='';
  144. $month_date_when='';
  145. $search_frequency='';
  146. $search_array_options=array();
  147. }
  148. // Create predefined invoice
  149. if ($action == 'add')
  150. {
  151. if (! GETPOST('titre'))
  152. {
  153. setEventMessages($langs->transnoentities("ErrorFieldRequired",$langs->trans("Title")), null, 'errors');
  154. $action = "create";
  155. $error++;
  156. }
  157. $frequency=GETPOST('frequency', 'int');
  158. $reyear=GETPOST('reyear');
  159. $remonth=GETPOST('remonth');
  160. $reday=GETPOST('reday');
  161. $rehour=GETPOST('rehour');
  162. $remin=GETPOST('remin');
  163. $nb_gen_max=GETPOST('nb_gen_max', 'int');
  164. //if (empty($nb_gen_max)) $nb_gen_max =0;
  165. if (GETPOST('frequency'))
  166. {
  167. if (empty($reyear) || empty($remonth) || empty($reday))
  168. {
  169. setEventMessages($langs->transnoentities("ErrorFieldRequired",$langs->trans("Date")), null, 'errors');
  170. $action = "create";
  171. $error++;
  172. }
  173. if ($nb_gen_max === '')
  174. {
  175. setEventMessages($langs->transnoentities("ErrorFieldRequired",$langs->trans("MaxPeriodNumber")), null, 'errors');
  176. $action = "create";
  177. $error++;
  178. }
  179. }
  180. if (! $error)
  181. {
  182. $object->titre = GETPOST('titre', 'alpha');
  183. $object->note_private = GETPOST('note_private');
  184. $object->note_public = GETPOST('note_public');
  185. $object->usenewprice = GETPOST('usenewprice');
  186. $object->frequency = $frequency;
  187. $object->unit_frequency = GETPOST('unit_frequency', 'alpha');
  188. $object->nb_gen_max = $nb_gen_max;
  189. $object->auto_validate = GETPOST('auto_validate', 'int');
  190. $object->fk_project = $projectid;
  191. $date_next_execution = dol_mktime($rehour, $remin, 0, $remonth, $reday, $reyear);
  192. $object->date_when = $date_next_execution;
  193. // Get first contract linked to invoice used to generate template
  194. if ($id > 0)
  195. {
  196. $srcObject = new Facture($db);
  197. $srcObject->fetch(GETPOST('facid','int'));
  198. $srcObject->fetchObjectLinked();
  199. if (! empty($srcObject->linkedObjectsIds['contrat']))
  200. {
  201. $contractidid = reset($srcObject->linkedObjectsIds['contrat']);
  202. $object->origin = 'contrat';
  203. $object->origin_id = $contractidid;
  204. $object->linked_objects[$object->origin] = $object->origin_id;
  205. }
  206. }
  207. $db->begin();
  208. $oldinvoice = new Facture($db);
  209. $oldinvoice->fetch($id);
  210. $result = $object->create($user, $oldinvoice->id);
  211. if ($result > 0)
  212. {
  213. $result=$oldinvoice->delete($user, 1);
  214. if ($result < 0)
  215. {
  216. $error++;
  217. setEventMessages($oldinvoice->error, $oldinvoice->errors, 'errors');
  218. $action = "create";
  219. }
  220. }
  221. else
  222. {
  223. $error++;
  224. setEventMessages($object->error, $object->errors, 'errors');
  225. $action = "create";
  226. }
  227. if (! $error)
  228. {
  229. $db->commit();
  230. header("Location: " . $_SERVER['PHP_SELF'] . '?facid=' . $object->id);
  231. exit;
  232. }
  233. else
  234. {
  235. $db->rollback();
  236. $error++;
  237. setEventMessages($object->error, $object->errors, 'errors');
  238. $action = "create";
  239. }
  240. }
  241. }
  242. // Delete
  243. if ($action == 'confirm_deleteinvoice' && $confirm == 'yes' && $user->rights->facture->supprimer)
  244. {
  245. $object->delete();
  246. header("Location: " . $_SERVER['PHP_SELF'] );
  247. exit;
  248. }
  249. // Update field
  250. // Set condition
  251. if ($action == 'setconditions' && $user->rights->facture->creer)
  252. {
  253. $result=$object->setPaymentTerms(GETPOST('cond_reglement_id', 'int'));
  254. }
  255. // Set mode
  256. elseif ($action == 'setmode' && $user->rights->facture->creer)
  257. {
  258. $result=$object->setPaymentMethods(GETPOST('mode_reglement_id', 'int'));
  259. }
  260. // Set project
  261. elseif ($action == 'classin' && $user->rights->facture->creer)
  262. {
  263. $object->setProject(GETPOST('projectid', 'int'));
  264. }
  265. // Set bank account
  266. elseif ($action == 'setref' && $user->rights->facture->creer)
  267. {
  268. //var_dump(GETPOST('ref', 'alpha'));exit;
  269. $result=$object->setValueFrom('titre', GETPOST('ref', 'alpha'), '', null, 'text', '', $user, 'BILLREC_MODIFY');
  270. if ($result > 0)
  271. {
  272. $object->titre = GETPOST('ref', 'alpha');
  273. $object->ref = $object->titre;
  274. }
  275. else dol_print_error($db, $object->error, $object->errors);
  276. }
  277. // Set bank account
  278. elseif ($action == 'setbankaccount' && $user->rights->facture->creer)
  279. {
  280. $result=$object->setBankAccount(GETPOST('fk_account', 'int'));
  281. }
  282. // Set frequency and unit frequency
  283. elseif ($action == 'setfrequency' && $user->rights->facture->creer)
  284. {
  285. $object->setFrequencyAndUnit(GETPOST('frequency', 'int'), GETPOST('unit_frequency', 'alpha'));
  286. }
  287. // Set next date of execution
  288. elseif ($action == 'setdate_when' && $user->rights->facture->creer)
  289. {
  290. $date = dol_mktime(GETPOST('date_whenhour'), GETPOST('date_whenmin'), 0, GETPOST('date_whenmonth'), GETPOST('date_whenday'), GETPOST('date_whenyear'));
  291. if (!empty($date)) $object->setNextDate($date);
  292. }
  293. // Set max period
  294. elseif ($action == 'setnb_gen_max' && $user->rights->facture->creer)
  295. {
  296. $object->setMaxPeriod(GETPOST('nb_gen_max', 'int'));
  297. }
  298. // Set auto validate
  299. elseif ($action == 'setauto_validate' && $user->rights->facture->creer)
  300. {
  301. $object->setAutoValidate(GETPOST('auto_validate', 'int'));
  302. }
  303. // Delete line
  304. if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->facture->creer)
  305. {
  306. $object->fetch($id);
  307. $object->fetch_thirdparty();
  308. $db->begin();
  309. $line=new FactureLigneRec($db);
  310. // For triggers
  311. $line->id = $lineid;
  312. if ($line->delete() > 0)
  313. {
  314. $result=$object->update_price(1);
  315. if ($result > 0)
  316. {
  317. $db->commit();
  318. $object->fetch($object->id); // Reload lines
  319. }
  320. else
  321. {
  322. $db->rollback();
  323. setEventMessages($db->lasterror(), null, 'errors');
  324. }
  325. }
  326. else
  327. {
  328. $db->rollback();
  329. setEventMessages($line->error, $line->errors, 'errors');
  330. }
  331. }
  332. // Add a new line
  333. if ($action == 'addline' && $user->rights->facture->creer)
  334. {
  335. $langs->load('errors');
  336. $error = 0;
  337. // Set if we used free entry or predefined product
  338. $predef='';
  339. $product_desc=(GETPOST('dp_desc')?GETPOST('dp_desc'):'');
  340. $price_ht = GETPOST('price_ht');
  341. if (GETPOST('prod_entry_mode') == 'free')
  342. {
  343. $idprod=0;
  344. $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0);
  345. }
  346. else
  347. {
  348. $idprod=GETPOST('idprod', 'int');
  349. $tva_tx = '';
  350. }
  351. $qty = GETPOST('qty' . $predef);
  352. $remise_percent = GETPOST('remise_percent' . $predef);
  353. // Extrafields
  354. $extrafieldsline = new ExtraFields($db);
  355. $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line);
  356. $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef);
  357. // Unset extrafield
  358. if (is_array($extralabelsline))
  359. {
  360. // Get extra fields
  361. foreach ($extralabelsline as $key => $value) {
  362. unset($_POST["options_" . $key . $predef]);
  363. }
  364. }
  365. if (empty($idprod) && ($price_ht < 0) && ($qty < 0)) {
  366. setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPriceHT'), $langs->transnoentitiesnoconv('Qty')), null, 'errors');
  367. $error ++;
  368. }
  369. if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && GETPOST('type') < 0) {
  370. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors');
  371. $error ++;
  372. }
  373. if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && (! ($price_ht >= 0) || $price_ht == '')) // Unit price can be 0 but not ''
  374. {
  375. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("UnitPriceHT")), null, 'errors');
  376. $error ++;
  377. }
  378. if ($qty == '') {
  379. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors');
  380. $error ++;
  381. }
  382. if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && empty($product_desc)) {
  383. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors');
  384. $error ++;
  385. }
  386. if ($qty < 0) {
  387. $langs->load("errors");
  388. setEventMessages($langs->trans('ErrorQtyForCustomerInvoiceCantBeNegative'), null, 'errors');
  389. $error ++;
  390. }
  391. if (! $error && ($qty >= 0) && (! empty($product_desc) || ! empty($idprod)))
  392. {
  393. $ret = $object->fetch($id);
  394. if ($ret < 0) {
  395. dol_print_error($db, $object->error);
  396. exit();
  397. }
  398. $ret = $object->fetch_thirdparty();
  399. // Clean parameters
  400. $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'));
  401. $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'));
  402. $price_base_type = (GETPOST('price_base_type', 'alpha') ? GETPOST('price_base_type', 'alpha') : 'HT');
  403. // Define special_code for special lines
  404. $special_code = 0;
  405. // if (empty($_POST['qty'])) $special_code=3; // Options should not exists on invoices
  406. // Ecrase $pu par celui du produit
  407. // Ecrase $desc par celui du produit
  408. // Ecrase $tva_tx par celui du produit
  409. // Ecrase $base_price_type par celui du produit
  410. // Replaces $fk_unit with the product's
  411. if (! empty($idprod))
  412. {
  413. $prod = new Product($db);
  414. $prod->fetch($idprod);
  415. $label = ((GETPOST('product_label') && GETPOST('product_label') != $prod->label) ? GETPOST('product_label') : '');
  416. // Update if prices fields are defined
  417. $tva_tx = get_default_tva($mysoc, $object->thirdparty, $prod->id);
  418. $tva_npr = get_default_npr($mysoc, $object->thirdparty, $prod->id);
  419. if (empty($tva_tx)) $tva_npr=0;
  420. $pu_ht = $prod->price;
  421. $pu_ttc = $prod->price_ttc;
  422. $price_min = $prod->price_min;
  423. $price_base_type = $prod->price_base_type;
  424. // We define price for product
  425. if (! empty($conf->global->PRODUIT_MULTIPRICES) && ! empty($object->thirdparty->price_level))
  426. {
  427. $pu_ht = $prod->multiprices[$object->thirdparty->price_level];
  428. $pu_ttc = $prod->multiprices_ttc[$object->thirdparty->price_level];
  429. $price_min = $prod->multiprices_min[$object->thirdparty->price_level];
  430. $price_base_type = $prod->multiprices_base_type[$object->thirdparty->price_level];
  431. if (! empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) // using this option is a bug. kept for backward compatibility
  432. {
  433. if (isset($prod->multiprices_tva_tx[$object->thirdparty->price_level])) $tva_tx=$prod->multiprices_tva_tx[$object->thirdparty->price_level];
  434. if (isset($prod->multiprices_recuperableonly[$object->thirdparty->price_level])) $tva_npr=$prod->multiprices_recuperableonly[$object->thirdparty->price_level];
  435. if (empty($tva_tx)) $tva_npr=0;
  436. }
  437. }
  438. elseif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES))
  439. {
  440. require_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php';
  441. $prodcustprice = new Productcustomerprice($db);
  442. $filter = array('t.fk_product' => $prod->id,'t.fk_soc' => $object->thirdparty->id);
  443. $result = $prodcustprice->fetch_all('', '', 0, 0, $filter);
  444. if ($result)
  445. {
  446. if (count($prodcustprice->lines) > 0)
  447. {
  448. $pu_ht = price($prodcustprice->lines[0]->price);
  449. $pu_ttc = price($prodcustprice->lines[0]->price_ttc);
  450. $price_base_type = $prodcustprice->lines[0]->price_base_type;
  451. $tva_tx = $prodcustprice->lines[0]->tva_tx;
  452. }
  453. }
  454. }
  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. {
  460. $pu_ht = price2num($price_ht, 'MU');
  461. $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU');
  462. }
  463. // On reevalue prix selon taux tva car taux tva transaction peut etre different
  464. // de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur).
  465. elseif ($tmpvat != $tmpprodvat)
  466. {
  467. if ($price_base_type != 'HT')
  468. {
  469. $pu_ht = price2num($pu_ttc / (1 + ($tmpvat / 100)), 'MU');
  470. }
  471. else
  472. {
  473. $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU');
  474. }
  475. }
  476. $desc = '';
  477. // Define output language
  478. if (! empty($conf->global->MAIN_MULTILANGS) && ! empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE))
  479. {
  480. $outputlangs = $langs;
  481. $newlang = '';
  482. if (empty($newlang) && GETPOST('lang_id'))
  483. $newlang = GETPOST('lang_id');
  484. if (empty($newlang))
  485. $newlang = $object->thirdparty->default_lang;
  486. if (! empty($newlang))
  487. {
  488. $outputlangs = new Translate("", $conf);
  489. $outputlangs->setDefaultLang($newlang);
  490. }
  491. $desc = (! empty($prod->multilangs [$outputlangs->defaultlang] ["description"])) ? $prod->multilangs [$outputlangs->defaultlang] ["description"] : $prod->description;
  492. }
  493. else
  494. {
  495. $desc = $prod->description;
  496. }
  497. $desc = dol_concatdesc($desc, $product_desc);
  498. // Add custom code and origin country into description
  499. if (empty($conf->global->MAIN_PRODUCT_DISABLE_CUSTOMCOUNTRYCODE) && (! empty($prod->customcode) || ! empty($prod->country_code)))
  500. {
  501. $tmptxt = '(';
  502. if (! empty($prod->customcode))
  503. $tmptxt .= $langs->transnoentitiesnoconv("CustomCode") . ': ' . $prod->customcode;
  504. if (! empty($prod->customcode) && ! empty($prod->country_code))
  505. $tmptxt .= ' - ';
  506. if (! empty($prod->country_code))
  507. $tmptxt .= $langs->transnoentitiesnoconv("CountryOrigin") . ': ' . getCountry($prod->country_code, 0, $db, $langs, 0);
  508. $tmptxt .= ')';
  509. $desc = dol_concatdesc($desc, $tmptxt);
  510. }
  511. $type = $prod->type;
  512. $fk_unit = $prod->fk_unit;
  513. }
  514. else
  515. {
  516. $pu_ht = price2num($price_ht, 'MU');
  517. $pu_ttc = price2num(GETPOST('price_ttc'), 'MU');
  518. $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0);
  519. $tva_tx = str_replace('*', '', $tva_tx);
  520. if (empty($tva_tx)) $tva_npr=0;
  521. $label = (GETPOST('product_label') ? GETPOST('product_label') : '');
  522. $desc = $product_desc;
  523. $type = GETPOST('type');
  524. $fk_unit= GETPOST('units', 'alpha');
  525. }
  526. // Margin
  527. $fournprice = price2num(GETPOST('fournprice' . $predef) ? GETPOST('fournprice' . $predef) : '');
  528. $buyingprice = price2num(GETPOST('buying_price' . $predef) != '' ? GETPOST('buying_price' . $predef) : ''); // If buying_price is '0', we must keep this value
  529. // Local Taxes
  530. $localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty, $mysoc, $tva_npr);
  531. $localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty, $mysoc, $tva_npr);
  532. $info_bits = 0;
  533. if ($tva_npr)
  534. $info_bits |= 0x01;
  535. if (! empty($price_min) && (price2num($pu_ht) * (1 - price2num($remise_percent) / 100) < price2num($price_min)))
  536. {
  537. $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, - 1, $conf->currency));
  538. setEventMessages($mesg, null, 'errors');
  539. }
  540. else
  541. {
  542. // Insert line
  543. $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);
  544. if ($result > 0)
  545. {
  546. /*if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
  547. {
  548. // Define output language
  549. $outputlangs = $langs;
  550. $newlang = '';
  551. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id','alpha');
  552. if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
  553. if (! empty($newlang)) {
  554. $outputlangs = new Translate("", $conf);
  555. $outputlangs->setDefaultLang($newlang);
  556. }
  557. $model=$object->modelpdf;
  558. $ret = $object->fetch($id); // Reload to get new records
  559. $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  560. if ($result < 0) setEventMessages($object->error, $object->errors, 'errors');
  561. }*/
  562. $object->fetch($object->id); // Reload lines
  563. unset($_POST['prod_entry_mode']);
  564. unset($_POST['qty']);
  565. unset($_POST['type']);
  566. unset($_POST['remise_percent']);
  567. unset($_POST['price_ht']);
  568. unset($_POST['multicurrency_price_ht']);
  569. unset($_POST['price_ttc']);
  570. unset($_POST['tva_tx']);
  571. unset($_POST['product_ref']);
  572. unset($_POST['product_label']);
  573. unset($_POST['product_desc']);
  574. unset($_POST['fournprice']);
  575. unset($_POST['buying_price']);
  576. unset($_POST['np_marginRate']);
  577. unset($_POST['np_markRate']);
  578. unset($_POST['dp_desc']);
  579. unset($_POST['idprod']);
  580. unset($_POST['units']);
  581. unset($_POST['date_starthour']);
  582. unset($_POST['date_startmin']);
  583. unset($_POST['date_startsec']);
  584. unset($_POST['date_startday']);
  585. unset($_POST['date_startmonth']);
  586. unset($_POST['date_startyear']);
  587. unset($_POST['date_endhour']);
  588. unset($_POST['date_endmin']);
  589. unset($_POST['date_endsec']);
  590. unset($_POST['date_endday']);
  591. unset($_POST['date_endmonth']);
  592. unset($_POST['date_endyear']);
  593. unset($_POST['situations']);
  594. unset($_POST['progress']);
  595. }
  596. else
  597. {
  598. setEventMessages($object->error, $object->errors, 'errors');
  599. }
  600. $action = '';
  601. }
  602. }
  603. }
  604. elseif ($action == 'updateligne' && $user->rights->facture->creer && ! GETPOST('cancel'))
  605. {
  606. if (! $object->fetch($id) > 0) dol_print_error($db);
  607. $object->fetch_thirdparty();
  608. // Clean parameters
  609. $date_start = '';
  610. $date_end = '';
  611. //$date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear'));
  612. //$date_end = dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear'));
  613. $description = dol_htmlcleanlastbr(GETPOST('product_desc') ? GETPOST('product_desc') : GETPOST('desc'));
  614. $pu_ht = GETPOST('price_ht');
  615. $vat_rate = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0);
  616. $qty = GETPOST('qty');
  617. // Define info_bits
  618. $info_bits = 0;
  619. if (preg_match('/\*/', $vat_rate))
  620. $info_bits |= 0x01;
  621. // Define vat_rate
  622. $vat_rate = str_replace('*', '', $vat_rate);
  623. $localtax1_rate = get_localtax($vat_rate, 1, $object->thirdparty);
  624. $localtax2_rate = get_localtax($vat_rate, 2, $object->thirdparty);
  625. // Add buying price
  626. $fournprice = price2num(GETPOST('fournprice') ? GETPOST('fournprice') : '');
  627. $buyingprice = price2num(GETPOST('buying_price') != '' ? GETPOST('buying_price') : ''); // If buying_price is '0', we muste keep this value
  628. // Extrafields
  629. $extrafieldsline = new ExtraFields($db);
  630. $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line);
  631. $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline);
  632. // Unset extrafield
  633. if (is_array($extralabelsline))
  634. {
  635. // Get extra fields
  636. foreach ($extralabelsline as $key => $value)
  637. {
  638. unset($_POST["options_" . $key]);
  639. }
  640. }
  641. // Define special_code for special lines
  642. $special_code=GETPOST('special_code');
  643. if (! GETPOST('qty')) $special_code=3;
  644. /*$line = new FactureLigne($db);
  645. $line->fetch(GETPOST('lineid'));
  646. $percent = $line->get_prev_progress($object->id);
  647. if (GETPOST('progress') < $percent)
  648. {
  649. $mesg = '<div class="warning">' . $langs->trans("CantBeLessThanMinPercent") . '</div>';
  650. setEventMessages($mesg, null, 'warnings');
  651. $error++;
  652. $result = -1;
  653. }*/
  654. // Check minimum price
  655. $productid = GETPOST('productid', 'int');
  656. if (! empty($productid))
  657. {
  658. $product = new Product($db);
  659. $product->fetch($productid);
  660. $type = $product->type;
  661. $price_min = $product->price_min;
  662. if (! empty($conf->global->PRODUIT_MULTIPRICES) && ! empty($object->thirdparty->price_level))
  663. $price_min = $product->multiprices_min [$object->thirdparty->price_level];
  664. $label = ((GETPOST('update_label') && GETPOST('product_label')) ? GETPOST('product_label') : '');
  665. // Check price is not lower than minimum (check is done only for standard or replacement invoices)
  666. if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT) && $price_min && (price2num($pu_ht) * (1 - price2num(GETPOST('remise_percent')) / 100) < price2num($price_min))) {
  667. setEventMessages($langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, - 1, $conf->currency)), null, 'errors');
  668. $error ++;
  669. }
  670. } else {
  671. $type = GETPOST('type');
  672. $label = (GETPOST('product_label') ? GETPOST('product_label') : '');
  673. // Check parameters
  674. if (GETPOST('type') < 0) {
  675. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
  676. $error ++;
  677. }
  678. }
  679. if ($qty < 0) {
  680. $langs->load("errors");
  681. setEventMessages($langs->trans('ErrorQtyForCustomerInvoiceCantBeNegative'), null, 'errors');
  682. $error ++;
  683. }
  684. // Update line
  685. if (! $error)
  686. {
  687. $result = $object->updateline(
  688. GETPOST('lineid'),
  689. $description,
  690. $pu_ht,
  691. $qty,
  692. $vat_rate,
  693. $localtax1_rate,
  694. $localtax1_rate,
  695. GETPOST('productid'),
  696. GETPOST('remise_percent'),
  697. 'HT',
  698. $info_bits,
  699. 0,
  700. 0,
  701. $type,
  702. 0,
  703. $special_code,
  704. $label,
  705. GETPOST('units')
  706. );
  707. if ($result >= 0)
  708. {
  709. /*if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  710. // Define output language
  711. $outputlangs = $langs;
  712. $newlang = '';
  713. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id'))
  714. $newlang = GETPOST('lang_id');
  715. if ($conf->global->MAIN_MULTILANGS && empty($newlang))
  716. $newlang = $object->thirdparty->default_lang;
  717. if (! empty($newlang)) {
  718. $outputlangs = new Translate("", $conf);
  719. $outputlangs->setDefaultLang($newlang);
  720. }
  721. $ret = $object->fetch($id); // Reload to get new records
  722. $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  723. }*/
  724. $object->fetch($object->id); // Reload lines
  725. unset($_POST['qty']);
  726. unset($_POST['type']);
  727. unset($_POST['productid']);
  728. unset($_POST['remise_percent']);
  729. unset($_POST['price_ht']);
  730. unset($_POST['multicurrency_price_ht']);
  731. unset($_POST['price_ttc']);
  732. unset($_POST['tva_tx']);
  733. unset($_POST['product_ref']);
  734. unset($_POST['product_label']);
  735. unset($_POST['product_desc']);
  736. unset($_POST['fournprice']);
  737. unset($_POST['buying_price']);
  738. unset($_POST['np_marginRate']);
  739. unset($_POST['np_markRate']);
  740. unset($_POST['dp_desc']);
  741. unset($_POST['idprod']);
  742. unset($_POST['units']);
  743. unset($_POST['date_starthour']);
  744. unset($_POST['date_startmin']);
  745. unset($_POST['date_startsec']);
  746. unset($_POST['date_startday']);
  747. unset($_POST['date_startmonth']);
  748. unset($_POST['date_startyear']);
  749. unset($_POST['date_endhour']);
  750. unset($_POST['date_endmin']);
  751. unset($_POST['date_endsec']);
  752. unset($_POST['date_endday']);
  753. unset($_POST['date_endmonth']);
  754. unset($_POST['date_endyear']);
  755. unset($_POST['situations']);
  756. unset($_POST['progress']);
  757. }
  758. else
  759. {
  760. setEventMessages($object->error, $object->errors, 'errors');
  761. }
  762. }
  763. }
  764. }
  765. /*
  766. * View
  767. */
  768. llxHeader('',$langs->trans("RepeatableInvoices"),'ch-facture.html#s-fac-facture-rec');
  769. $form = new Form($db);
  770. $formother = new FormOther($db);
  771. if (! empty($conf->projet->enabled)) { $formproject = new FormProjets($db); }
  772. $companystatic = new Societe($db);
  773. $now = dol_now();
  774. $tmparray=dol_getdate($now);
  775. $today = dol_mktime(23,59,59,$tmparray['mon'],$tmparray['mday'],$tmparray['year']); // Today is last second of current day
  776. /*
  777. * Create mode
  778. */
  779. if ($action == 'create')
  780. {
  781. print load_fiche_titre($langs->trans("CreateRepeatableInvoice"),'','title_accountancy.png');
  782. $object = new Facture($db); // Source invoice
  783. $product_static = new Product($db);
  784. if ($object->fetch($id, $ref) > 0)
  785. {
  786. $result = $object->getLinesArray();
  787. print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
  788. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  789. print '<input type="hidden" name="action" value="add">';
  790. print '<input type="hidden" name="facid" value="'.$object->id.'">';
  791. dol_fiche_head();
  792. $rowspan=4;
  793. if (! empty($conf->projet->enabled)) $rowspan++;
  794. if ($object->fk_account > 0) $rowspan++;
  795. print '<table class="border" width="100%">';
  796. $object->fetch_thirdparty();
  797. // Title
  798. print '<tr><td class="titlefieldcreate fieldrequired">'.$langs->trans("Title").'</td><td>';
  799. print '<input class="flat quatrevingtpercent" type="text" name="titre" value="'.$_POST["titre"].'">';
  800. print '</td></tr>';
  801. // Third party
  802. print '<tr><td class="titlefieldcreate">'.$langs->trans("Customer").'</td><td>'.$object->thirdparty->getNomUrl(1,'customer').'</td>';
  803. print '</tr>';
  804. $note_public=GETPOST('note_public')?GETPOST('note_public'):$object->note_public;
  805. $note_private=GETPOST('note_private')?GETPOST('note_private'):$object->note_private;
  806. // Help of substitution key
  807. $substitutionarray=array(
  808. '__TOTAL_HT__' => $langs->trans("AmountHT").' ('.$langs->trans("Example").': '.price($object->total_ht).')',
  809. '__TOTAL_TTC__' => $langs->trans("AmountTTC").' ('.$langs->trans("Example").': '.price($object->total_ttc).')',
  810. '__INVOICE_PREVIOUS_MONTH__' => $langs->trans("PreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, -1, 'm'),'%m').')',
  811. '__INVOICE_MONTH__' => $langs->trans("MonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($object->date,'%m').')',
  812. '__INVOICE_NEXT_MONTH__' => $langs->trans("NextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, 1, 'm'),'%m').')',
  813. '__INVOICE_PREVIOUS_MONTH_TEXT__' => $langs->trans("TextPreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, -1, 'm'),'%B').')',
  814. '__INVOICE_MONTH_TEXT__' => $langs->trans("TextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($object->date,'%B').')',
  815. '__INVOICE_NEXT_MONTH_TEXT__' => $langs->trans("TextNextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, 1, 'm'), '%B').')',
  816. '__INVOICE_PREVIOUS_YEAR__' => $langs->trans("YearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, -1, 'y'),'%Y').')',
  817. '__INVOICE_YEAR__' => $langs->trans("PreviousYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($object->date,'%Y').')',
  818. '__INVOICE_NEXT_YEAR__' => $langs->trans("NextYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, 1, 'y'),'%Y').')'
  819. );
  820. $substitutionarray['__(TransKey)__']=$langs->trans("TransKey");
  821. $htmltext = '<i>'.$langs->trans("FollowingConstantsWillBeSubstituted").':<br>';
  822. foreach($substitutionarray as $key => $val)
  823. {
  824. $htmltext.=$key.' = '.$langs->trans($val).'<br>';
  825. }
  826. $htmltext.='</i>';
  827. // Public note
  828. print '<tr>';
  829. print '<td class="border tdtop">';
  830. print $form->textwithpicto($langs->trans('NotePublic'), $htmltext, 1, 'help', '', 0, 2, 'notepublic');
  831. print '</td>';
  832. print '<td valign="top" colspan="2">';
  833. $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%');
  834. print $doleditor->Create(1);
  835. // Private note
  836. if (empty($user->societe_id))
  837. {
  838. print '<tr>';
  839. print '<td class="border tdtop">';
  840. print $form->textwithpicto($langs->trans('NotePrivate'), $htmltext, 1, 'help', '', 0, 2, 'noteprivate');
  841. print '</td>';
  842. print '<td valign="top" colspan="2">';
  843. $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%');
  844. print $doleditor->Create(1);
  845. // print '<textarea name="note_private" wrap="soft" cols="70" rows="'.ROWS_3.'">'.$note_private.'.</textarea>
  846. print '</td></tr>';
  847. }
  848. // Author
  849. print "<tr><td>".$langs->trans("Author")."</td><td>".$user->getFullName($langs)."</td></tr>";
  850. // Payment term
  851. print "<tr><td>".$langs->trans("PaymentConditions")."</td><td>";
  852. $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->cond_reglement_id, 'none');
  853. print "</td></tr>";
  854. // Payment mode
  855. print "<tr><td>".$langs->trans("PaymentMode")."</td><td>";
  856. $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'none');
  857. print "</td></tr>";
  858. // Project
  859. if (! empty($conf->projet->enabled) && is_object($object->thirdparty) && $object->thirdparty->id > 0)
  860. {
  861. $projectid = GETPOST('projectid')?GETPOST('projectid'):$object->fk_project;
  862. $langs->load('projects');
  863. print '<tr><td>' . $langs->trans('Project') . '</td><td>';
  864. $numprojet = $formproject->select_projects($object->thirdparty->id, $projectid, 'projectid', 0, 0, 1, 0, 0, 0, 0, '', 0, 0, '');
  865. 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:'')).'">' . $langs->trans("AddProject") . '</a>';
  866. print '</td></tr>';
  867. }
  868. // Bank account
  869. if ($object->fk_account > 0)
  870. {
  871. print "<tr><td>".$langs->trans('RIB')."</td><td>";
  872. $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none');
  873. print "</td></tr>";
  874. }
  875. print "</table>";
  876. print '<br><br>';
  877. // Autogeneration
  878. $title = $langs->trans("Recurrence");
  879. print load_fiche_titre($title, '', 'calendar');
  880. print '<table class="border" width="100%">';
  881. // Frequency
  882. print '<tr><td class="titlefieldcreate">'.$form->textwithpicto($langs->trans("Frequency"), $langs->transnoentitiesnoconv('toolTipFrequency'))."</td><td>";
  883. print "<input type='text' name='frequency' value='".GETPOST('frequency', 'int')."' size='4' />&nbsp;".$form->selectarray('unit_frequency', array('d'=>$langs->trans('Day'), 'm'=>$langs->trans('Month'), 'y'=>$langs->trans('Year')), (GETPOST('unit_frequency')?GETPOST('unit_frequency'):'m'));
  884. print "</td></tr>";
  885. // First date of execution for cron
  886. print "<tr><td>".$langs->trans('NextDateToExecution')."</td><td>";
  887. $date_next_execution = isset($date_next_execution) ? $date_next_execution : (GETPOST('remonth') ? dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')) : -1);
  888. print $form->select_date($date_next_execution, '', 1, 1, '', "add", 1, 1, 1);
  889. print "</td></tr>";
  890. // Number max of generation
  891. print "<tr><td>".$langs->trans("MaxPeriodNumber")."</td><td>";
  892. print '<input type="text" name="nb_gen_max" value="'.GETPOST('nb_gen_max').'" size="5" />';
  893. print "</td></tr>";
  894. // Auto validate the invoice
  895. print "<tr><td>".$langs->trans("StatusOfGeneratedInvoices")."</td><td>";
  896. $select = array('0'=>$langs->trans('BillStatusDraft'),'1'=>$langs->trans('BillStatusValidated'));
  897. print $form->selectarray('auto_validate', $select, GETPOST('auto_validate'));
  898. print "</td></tr>";
  899. print "</table>";
  900. print '<br><br>';
  901. $title = $langs->trans("ProductsAndServices");
  902. if (empty($conf->service->enabled))
  903. $title = $langs->trans("Products");
  904. else if (empty($conf->product->enabled))
  905. $title = $langs->trans("Services");
  906. print load_fiche_titre($title, '', '');
  907. /*
  908. * Invoice lines
  909. */
  910. print '<table id="tablelines" class="noborder noshadow" width="100%">';
  911. // Show object lines
  912. if (! empty($object->lines))
  913. {
  914. $disableedit=1;
  915. $disablemove=1;
  916. $disableremove=1;
  917. $ret = $object->printObjectLines('', $mysoc, $soc, $lineid, 0); // No date selector for template invoice
  918. }
  919. print "</table>\n";
  920. print '</td></tr>';
  921. if ($flag_price_may_change)
  922. {
  923. print '<tr><td colspan="3" align="left">';
  924. print '<select name="usenewprice" class="flat">';
  925. print '<option value="0">'.$langs->trans("AlwaysUseFixedPrice").'</option>';
  926. print '<option value="1" disabled>'.$langs->trans("AlwaysUseNewPrice").'</option>';
  927. print '</select>';
  928. print '</td></tr>';
  929. }
  930. print "</table>\n";
  931. dol_fiche_end();
  932. print '<div align="center"><input type="submit" class="button" value="'.$langs->trans("Create").'">';
  933. print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  934. print '<input type="button" class="button" value="' . $langs->trans("Cancel") . '" onClick="javascript:history.go(-1)">';
  935. print '</div>';
  936. print "</form>\n";
  937. }
  938. else
  939. {
  940. dol_print_error('',"Error, no invoice ".$object->id);
  941. }
  942. }
  943. else
  944. {
  945. /*
  946. * View mode
  947. */
  948. if ($object->id > 0)
  949. {
  950. $object->fetch_thirdparty();
  951. // Confirmation de la suppression d'une ligne produit
  952. if ($action == 'ask_deleteline') {
  953. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id . '&lineid=' . $lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 'no', 1);
  954. }
  955. // Confirm delete of repeatable invoice
  956. if ($action == 'ask_deleteinvoice') {
  957. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('DeleteRepeatableInvoice'), $langs->trans('ConfirmDeleteRepeatableInvoice'), 'confirm_deleteinvoice', '', 'no', 1);
  958. }
  959. print $formconfirm;
  960. $author = new User($db);
  961. $author->fetch($object->user_author);
  962. $head=invoice_rec_prepare_head($object);
  963. dol_fiche_head($head, 'card', $langs->trans("RepeatableInvoice"), -1, 'bill'); // Add a div
  964. // Recurring invoice content
  965. $linkback = '<a href="' . DOL_URL_ROOT . '/compta/facture/fiche-rec.php' . (! empty($socid) ? '?socid=' . $socid : '') . '">' . $langs->trans("BackToList") . '</a>';
  966. $morehtmlref='';
  967. if ($action != 'editref') $morehtmlref.=$form->editfieldkey($object->ref, 'ref', $object->ref, $object, $user->rights->facture->creer, '', '', 0, 2);
  968. else $morehtmlref.= $form->editfieldval('', 'ref', $object->ref, $object, $user->rights->facture->creer, 'string');
  969. $morehtmlref.='<div class="refidno">';
  970. // Ref customer
  971. //$morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->facture->creer, 'string', '', 0, 1);
  972. //$morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->facture->creer, 'string', '', null, null, '', 1);
  973. // Thirdparty
  974. $morehtmlref.=$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1);
  975. // Project
  976. if (! empty($conf->projet->enabled))
  977. {
  978. $langs->load("projects");
  979. $morehtmlref.='<br>'.$langs->trans('Project') . ' ';
  980. if ($user->rights->facture->creer)
  981. {
  982. if ($action != 'classify')
  983. $morehtmlref.='<a href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : ';
  984. if ($action == 'classify') {
  985. //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
  986. $morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
  987. $morehtmlref.='<input type="hidden" name="action" value="classin">';
  988. $morehtmlref.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  989. $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
  990. $morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  991. $morehtmlref.='</form>';
  992. } else {
  993. $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
  994. }
  995. } else {
  996. if (! empty($object->fk_project)) {
  997. $proj = new Project($db);
  998. $proj->fetch($object->fk_project);
  999. $morehtmlref.='<a href="'.DOL_URL_ROOT.'/projet/card.php?id=' . $object->fk_project . '" title="' . $langs->trans('ShowProject') . '">';
  1000. $morehtmlref.=$proj->ref;
  1001. $morehtmlref.='</a>';
  1002. } else {
  1003. $morehtmlref.='';
  1004. }
  1005. }
  1006. }
  1007. $morehtmlref.='</div>';
  1008. dol_banner_tab($object, 'ref', $linkback, 1, 'titre', 'none', $morehtmlref, '', 0, '', $morehtmlright);
  1009. print '<div class="fichecenter">';
  1010. print '<div class="fichehalfleft">';
  1011. print '<div class="underbanner clearboth"></div>';
  1012. print '<table class="border" width="100%">';
  1013. print '<tr><td class="titlefield">'.$langs->trans("Author").'</td><td colspan="3">'.$author->getFullName($langs)."</td></tr>";
  1014. print '<tr><td>'.$langs->trans("AmountHT").'</td>';
  1015. print '<td colspan="3">'.price($object->total_ht,'',$langs,1,-1,-1,$conf->currency).'</td>';
  1016. print '</tr>';
  1017. print '<tr><td>'.$langs->trans("AmountVAT").'</td><td colspan="3">'.price($object->total_tva,'',$langs,1,-1,-1,$conf->currency).'</td>';
  1018. print '</tr>';
  1019. // Amount Local Taxes
  1020. if (($mysoc->localtax1_assuj == "1" && $mysoc->useLocalTax(1)) || $object->total_localtax1 != 0) // Localtax1
  1021. {
  1022. print '<tr><td>' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '</td>';
  1023. print '<td class="nowrap">' . price($object->total_localtax1, 1, '', 1, - 1, - 1, $conf->currency) . '</td></tr>';
  1024. }
  1025. if (($mysoc->localtax2_assuj == "1" && $mysoc->useLocalTax(2)) || $object->total_localtax2 != 0) // Localtax2
  1026. {
  1027. print '<tr><td>' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '</td>';
  1028. print '<td class=nowrap">' . price($object->total_localtax2, 1, '', 1, - 1, - 1, $conf->currency) . '</td></tr>';
  1029. }
  1030. print '<tr><td>'.$langs->trans("AmountTTC").'</td><td colspan="3">'.price($object->total_ttc,'',$langs,1,-1,-1,$conf->currency).'</td>';
  1031. print '</tr>';
  1032. // Payment term
  1033. print '<tr><td>';
  1034. print '<table class="nobordernopadding" width="100%"><tr><td>';
  1035. print $langs->trans('PaymentConditionsShort');
  1036. print '</td>';
  1037. if ($object->type != Facture::TYPE_CREDIT_NOTE && $action != 'editconditions' && ! empty($object->brouillon) && $user->rights->facture->creer)
  1038. print '<td align="right"><a href="' . $_SERVER["PHP_SELF"] . '?action=editconditions&amp;facid=' . $object->id . '">' . img_edit($langs->trans('SetConditions'), 1) . '</a></td>';
  1039. print '</tr></table>';
  1040. print '</td><td colspan="3">';
  1041. if ($object->type != Facture::TYPE_CREDIT_NOTE)
  1042. {
  1043. if ($action == 'editconditions')
  1044. {
  1045. $form->form_conditions_reglement($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->cond_reglement_id, 'cond_reglement_id');
  1046. }
  1047. else
  1048. {
  1049. $form->form_conditions_reglement($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->cond_reglement_id, 'none');
  1050. }
  1051. } else {
  1052. print '&nbsp;';
  1053. }
  1054. print '</td></tr>';
  1055. // Payment mode
  1056. print '<tr><td>';
  1057. print '<table class="nobordernopadding" width="100%"><tr><td>';
  1058. print $langs->trans('PaymentMode');
  1059. print '</td>';
  1060. if ($action != 'editmode' && ! empty($object->brouillon) && $user->rights->facture->creer)
  1061. print '<td align="right"><a href="' . $_SERVER["PHP_SELF"] . '?action=editmode&amp;facid=' . $object->id . '">' . img_edit($langs->trans('SetMode'), 1) . '</a></td>';
  1062. print '</tr></table>';
  1063. print '</td><td colspan="3">';
  1064. if ($action == 'editmode')
  1065. {
  1066. $form->form_modes_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->mode_reglement_id, 'mode_reglement_id', 'CRDT');
  1067. }
  1068. else
  1069. {
  1070. $form->form_modes_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->mode_reglement_id, 'none', 'CRDT');
  1071. }
  1072. print '</td></tr>';
  1073. // Help of substitution key
  1074. $dateexample=dol_now();
  1075. if (! empty($object->frequency) && ! empty($object->date_when)) $dateexample=$object->date_when;
  1076. $substitutionarray=array(
  1077. '__TOTAL_HT__' => $langs->trans("AmountHT").' ('.$langs->trans("Example").': '.price($object->total_ht).')',
  1078. '__TOTAL_TTC__' => $langs->trans("AmountTTC").' ('.$langs->trans("Example").': '.price($object->total_ttc).')',
  1079. '__INVOICE_PREVIOUS_MONTH__' => $langs->trans("PreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'),'%m').')',
  1080. '__INVOICE_MONTH__' => $langs->trans("MonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample,'%m').')',
  1081. '__INVOICE_NEXT_MONTH__' => $langs->trans("NextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'),'%m').')',
  1082. '__INVOICE_PREVIOUS_MONTH_TEXT__' => $langs->trans("TextPreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'),'%B').')',
  1083. '__INVOICE_MONTH_TEXT__' => $langs->trans("TextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample,'%B').')',
  1084. '__INVOICE_NEXT_MONTH_TEXT__' => $langs->trans("TextNextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'), '%B').')',
  1085. '__INVOICE_PREVIOUS_YEAR__' => $langs->trans("YearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'y'),'%Y').')',
  1086. '__INVOICE_YEAR__' => $langs->trans("PreviousYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample,'%Y').')',
  1087. '__INVOICE_NEXT_YEAR__' => $langs->trans("NextYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'y'),'%Y').')'
  1088. );
  1089. $substitutionarray['__(TransKey)__']=$langs->trans("TransKey");
  1090. $htmltext = '<i>'.$langs->trans("FollowingConstantsWillBeSubstituted").':<br>';
  1091. foreach($substitutionarray as $key => $val)
  1092. {
  1093. $htmltext.=$key.' = '.$langs->trans($val).'<br>';
  1094. }
  1095. $htmltext.='</i>';
  1096. // Note public
  1097. print '<tr><td>';
  1098. print $form->editfieldkey($form->textwithpicto($langs->trans('NotePublic'), $htmltext, 1, 'help', '', 0, 2, 'notepublic'), 'note_public', $object->note_public, $object, $user->rights->facture->creer);
  1099. print '</td><td colspan="5">';
  1100. print $form->editfieldval($langs->trans("NotePublic"), 'note_public', $object->note_public, $object, $user->rights->facture->creer, 'textarea:'.ROWS_4.':60');
  1101. print '</td>';
  1102. print '</tr>';
  1103. // Note private
  1104. print '<tr><td>';
  1105. print $form->editfieldkey($form->textwithpicto($langs->trans("NotePrivate"), $htmltext, 1, 'help', '', 0, 2, 'noteprivate'), 'note_private', $object->note_private, $object, $user->rights->facture->creer);
  1106. print '</td><td colspan="5">';
  1107. print $form->editfieldval($langs->trans("NotePrivate"), 'note_private', $object->note_private, $object, $user->rights->facture->creer, 'textarea:'.ROWS_4.':60');
  1108. print '</td>';
  1109. print '</tr>';
  1110. // Bank Account
  1111. $langs->load('banks');
  1112. print '<tr><td class="nowrap">';
  1113. print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">';
  1114. print $langs->trans('RIB');
  1115. print '<td>';
  1116. if (($action != 'editbankaccount') && $user->rights->commande->creer && ! empty($object->brouillon))
  1117. print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editbankaccount&amp;id='.$object->id.'">'.img_edit($langs->trans('SetBankAccount'),1).'</a></td>';
  1118. print '</tr></table>';
  1119. print '</td><td colspan="3">';
  1120. if ($action == 'editbankaccount')
  1121. {
  1122. $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1);
  1123. }
  1124. else
  1125. {
  1126. $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none');
  1127. }
  1128. print "</td>";
  1129. print '</tr>';
  1130. print '</table>';
  1131. print '</div>';
  1132. print '<div class="fichehalfright">';
  1133. print '<div class="ficheaddleft">';
  1134. print '<div class="underbanner clearboth"></div>';
  1135. /*
  1136. * Recurrence
  1137. */
  1138. $title = $langs->trans("Recurrence");
  1139. //print load_fiche_titre($title, '', 'calendar');
  1140. print '<table class="border" width="100%">';
  1141. print '<tr><td colspan="2"><span class="fa fa-calendar"></span> '.$title.'</td></tr>';
  1142. // if "frequency" is empty or = 0, the reccurence is disabled
  1143. print '<tr><td style="width: 50%">';
  1144. print '<table class="nobordernopadding" width="100%"><tr><td>';
  1145. print $langs->trans('Frequency');
  1146. print '</td>';
  1147. if ($action != 'editfrequency' && ! empty($object->brouillon) && $user->rights->facture->creer)
  1148. print '<td align="right"><a href="' . $_SERVER["PHP_SELF"] . '?action=editfrequency&amp;facid=' . $object->id . '">' . img_edit($langs->trans('Edit'), 1) . '</a></td>';
  1149. print '</tr></table>';
  1150. print '</td><td>';
  1151. if ($action == 'editfrequency')
  1152. {
  1153. print '<form method="post" action="'.$_SERVER["PHP_SELF"] . '?facid=' . $object->id.'">';
  1154. print '<input type="hidden" name="action" value="setfrequency">';
  1155. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  1156. print '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  1157. print '<tr><td>';
  1158. print "<input type='text' name='frequency' value='".$object->frequency."' size='5' />&nbsp;".$form->selectarray('unit_frequency', array('d'=>$langs->trans('Day'), 'm'=>$langs->trans('Month'), 'y'=>$langs->trans('Year')), ($object->unit_frequency?$object->unit_frequency:'m'));
  1159. print '</td>';
  1160. print '<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
  1161. print '</tr></table></form>';
  1162. }
  1163. else
  1164. {
  1165. if ($object->frequency > 0)
  1166. {
  1167. print $langs->trans('FrequencyPer_'.$object->unit_frequency, $object->frequency);
  1168. }
  1169. else
  1170. {
  1171. print $langs->trans("NotARecurringInvoiceTemplate");
  1172. }
  1173. }
  1174. print '</td></tr>';
  1175. // Date when
  1176. print '<tr><td>';
  1177. if ($action == 'date_when' || $object->frequency > 0)
  1178. {
  1179. print $form->editfieldkey($langs->trans("NextDateToExecution"), 'date_when', $object->date_when, $object, $user->rights->facture->creer, 'day');
  1180. }
  1181. else
  1182. {
  1183. print $langs->trans("NextDateToExecution");
  1184. }
  1185. print '</td><td>';
  1186. if ($action == 'date_when' || $object->frequency > 0)
  1187. {
  1188. print $form->editfieldval($langs->trans("NextDateToExecution"), 'date_when', $object->date_when, $object, $user->rights->facture->creer, 'day');
  1189. }
  1190. print '</td>';
  1191. print '</tr>';
  1192. // Max period / Rest period
  1193. print '<tr><td>';
  1194. if ($action == 'nb_gen_max' || $object->frequency > 0)
  1195. {
  1196. print $form->editfieldkey($langs->trans("MaxPeriodNumber"), 'nb_gen_max', $object->nb_gen_max, $object, $user->rights->facture->creer);
  1197. }
  1198. else
  1199. {
  1200. print $langs->trans("MaxPeriodNumber");
  1201. }
  1202. print '</td><td>';
  1203. if ($action == 'nb_gen_max' || $object->frequency > 0)
  1204. {
  1205. print $form->editfieldval($langs->trans("MaxPeriodNumber"), 'nb_gen_max', $object->nb_gen_max?$object->nb_gen_max:'', $object, $user->rights->facture->creer);
  1206. }
  1207. else
  1208. {
  1209. print '';
  1210. }
  1211. print '</td>';
  1212. print '</tr>';
  1213. // Status of generated invoices
  1214. print '<tr><td>';
  1215. if ($action == 'auto_validate' || $object->frequency > 0)
  1216. print $form->editfieldkey($langs->trans("StatusOfGeneratedInvoices"), 'auto_validate', $object->auto_validate, $object, $user->rights->facture->creer);
  1217. else
  1218. print $langs->trans("StatusOfGeneratedInvoices");
  1219. print '</td><td>';
  1220. $select = 'select;0:'.$langs->trans('BillStatusDraft').',1:'.$langs->trans('BillStatusValidated');
  1221. if ($action == 'auto_validate' || $object->frequency > 0)
  1222. {
  1223. print $form->editfieldval($langs->trans("StatusOfGeneratedInvoices"), 'auto_validate', $object->auto_validate, $object, $user->rights->facture->creer, $select);
  1224. }
  1225. print '</td>';
  1226. print '</tr>';
  1227. print '</table>';
  1228. // Frequencry/Recurring section
  1229. if ($object->frequency > 0)
  1230. {
  1231. print '<br>';
  1232. if (empty($conf->cron->enabled))
  1233. {
  1234. print info_admin($langs->trans("EnableAndSetupModuleCron", $langs->transnoentitiesnoconv("Module2300Name")));
  1235. }
  1236. print '<div class="underbanner clearboth"></div>';
  1237. print '<table class="border centpercent">';
  1238. // Nb of generation already done
  1239. print '<tr><td style="width: 50%">'.$langs->trans("NbOfGenerationDone").'</td>';
  1240. print '<td>';
  1241. print $object->nb_gen_done?$object->nb_gen_done:'0';
  1242. print '</td>';
  1243. print '</tr>';
  1244. // Date last
  1245. print '<tr><td>';
  1246. print $langs->trans("DateLastGeneration");
  1247. print '</td><td>';
  1248. print dol_print_date($object->date_last_gen, 'dayhour');
  1249. print '</td>';
  1250. print '</tr>';
  1251. print '</table>';
  1252. print '<br>';
  1253. }
  1254. print '</div>';
  1255. print '</div>';
  1256. print '</div>';
  1257. print '<div class="clearboth"></div><br>';
  1258. // Lines
  1259. print ' <form name="addproduct" id="addproduct" action="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . (($action != 'editline') ? '#add' : '#line_' . GETPOST('lineid')) . '" method="POST">
  1260. <input type="hidden" name="token" value="' . $_SESSION ['newtoken'] . '">
  1261. <input type="hidden" name="action" value="' . (($action != 'editline') ? 'addline' : 'updateligne') . '">
  1262. <input type="hidden" name="mode" value="">
  1263. <input type="hidden" name="id" value="' . $object->id . '">
  1264. ';
  1265. if (! empty($conf->use_javascript_ajax) && $object->statut == 0) {
  1266. include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php';
  1267. }
  1268. print '<table id="tablelines" class="noborder noshadow" width="100%">';
  1269. // Show object lines
  1270. if (! empty($object->lines))
  1271. {
  1272. //$disableedit=1;
  1273. //$disablemove=1;
  1274. $ret = $object->printObjectLines($action, $mysoc, $soc, $lineid, 0); // No date selector for template invoice
  1275. }
  1276. // Form to add new line
  1277. if ($object->statut == 0 && $user->rights->facture->creer && $action != 'valid' && $action != 'editline')
  1278. {
  1279. if ($action != 'editline')
  1280. {
  1281. $var = true;
  1282. // Add free products/services
  1283. $object->formAddObjectLine(0, $mysoc, $soc); // No date selector for template invoice
  1284. $parameters = array();
  1285. $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  1286. }
  1287. }
  1288. print "</table>\n";
  1289. print "</form>\n";
  1290. dol_fiche_end();
  1291. /**
  1292. * Barre d'actions
  1293. */
  1294. print '<div class="tabsAction">';
  1295. //if ($object->statut == Facture::STATUS_DRAFT) // there is no draft status on templates.
  1296. //{
  1297. if ($user->rights->facture->creer)
  1298. {
  1299. if (! empty($object->frequency) && $object->nb_gen_max > 0 && ($object->nb_gen_done >= $object->nb_gen_max))
  1300. {
  1301. print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="'.dol_escape_htmltag($langs->trans("MaxGenerationReached")).'">'.$langs->trans("CreateBill").'</a></div>';
  1302. }
  1303. else
  1304. {
  1305. if (empty($object->frequency) || $object->date_when <= $today)
  1306. {
  1307. print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/compta/facture/card.php?action=create&amp;socid='.$object->thirdparty->id.'&amp;fac_rec='.$object->id.'">'.$langs->trans("CreateBill").'</a></div>';
  1308. }
  1309. else
  1310. {
  1311. print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="'.dol_escape_htmltag($langs->trans("DateIsNotEnough")).'">'.$langs->trans("CreateBill").'</a></div>';
  1312. }
  1313. }
  1314. }
  1315. else
  1316. {
  1317. print '<div class="inline-block divButAction"><a class="butActionRefused" href="#">'.$langs->trans("CreateBill").'</a></div>';
  1318. }
  1319. //}
  1320. //if ($object->statut == Facture::STATUS_DRAFT && $user->rights->facture->supprimer)
  1321. if ($user->rights->facture->supprimer)
  1322. {
  1323. print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER['PHP_SELF'].'?action=ask_deleteinvoice&id='.$object->id.'">'.$langs->trans('Delete').'</a></div>';
  1324. }
  1325. print '</div>';
  1326. print '<div class="fichecenter"><div class="fichehalfleft">';
  1327. print '<a name="builddoc"></a>'; // ancre
  1328. // Show links to link elements
  1329. $linktoelem = $form->showLinkToObjectBlock($object, null, array('invoice'));
  1330. $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem);
  1331. print '</div></div>';
  1332. }
  1333. else
  1334. {
  1335. /*
  1336. * List mode
  1337. */
  1338. $sql = "SELECT s.nom as name, s.rowid as socid, f.rowid as facid, f.titre, f.total, f.tva as total_vat, f.total_ttc, f.frequency,";
  1339. $sql.= " f.nb_gen_done, f.nb_gen_max, f.date_last_gen, f.date_when";
  1340. $sql.= " FROM ".MAIN_DB_PREFIX."societe as s,".MAIN_DB_PREFIX."facture_rec as f";
  1341. if (! $user->rights->societe->client->voir && ! $socid) {
  1342. $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
  1343. }
  1344. $sql.= " WHERE f.fk_soc = s.rowid";
  1345. $sql.= " AND f.entity = ".$conf->entity;
  1346. if (! $user->rights->societe->client->voir && ! $socid) {
  1347. $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
  1348. }
  1349. if ($search_ref) $sql .= natural_search('f.titre', $search_ref);
  1350. if ($search_societe) $sql .= natural_search('s.nom', $search_societe);
  1351. if ($search_frequency) $sql .= natural_search('f.frequency', $search_frequency);
  1352. if ($search_montant_ht != '') $sql.= natural_search('f.total', $search_montant_ht, 1);
  1353. if ($search_montant_vat != '') $sql.= natural_search('f.tva', $search_montant_vat, 1);
  1354. if ($search_montant_ttc != '') $sql.= natural_search('f.total_ttc', $search_montant_ttc, 1);
  1355. if ($search_frequency == '1') $sql.= ' AND f.frequency > 0';
  1356. if ($search_frequency == '0') $sql.= ' AND (f.frequency IS NULL or f.frequency = 0)';
  1357. if ($month > 0)
  1358. {
  1359. if ($year > 0 && empty($day))
  1360. $sql.= " AND f.date_last_gen BETWEEN '".$db->idate(dol_get_first_day($year,$month,false))."' AND '".$db->idate(dol_get_last_day($year,$month,false))."'";
  1361. else if ($year > 0 && ! empty($day))
  1362. $sql.= " AND f.date_last_gen BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."'";
  1363. else
  1364. $sql.= " AND date_format(f.date_last_gen, '%m') = '".$month."'";
  1365. }
  1366. else if ($year > 0)
  1367. {
  1368. $sql.= " AND f.date_last_gen BETWEEN '".$db->idate(dol_get_first_day($year,1,false))."' AND '".$db->idate(dol_get_last_day($year,12,false))."'";
  1369. }
  1370. if ($month_date_when > 0)
  1371. {
  1372. if ($year_date_when > 0 && empty($day_date_when))
  1373. $sql.= " AND f.date_when BETWEEN '".$db->idate(dol_get_first_day($year_date_when,$month_date_when,false))."' AND '".$db->idate(dol_get_last_day($year_date_when,$month_date_when,false))."'";
  1374. else if ($year_date_when > 0 && ! empty($day_date_when))
  1375. $sql.= " AND f.date_date_when_reglement BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month_date_when, $day_date_when, $year_date_when))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month_date_when, $day_date_when, $year_date_when))."'";
  1376. else
  1377. $sql.= " AND date_format(f.date_when, '%m') = '".$month_date_when."'";
  1378. }
  1379. else if ($year_date_when > 0)
  1380. {
  1381. $sql.= " AND f.date_when BETWEEN '".$db->idate(dol_get_first_day($year_date_when,1,false))."' AND '".$db->idate(dol_get_last_day($year_date_when,12,false))."'";
  1382. }
  1383. $nbtotalofrecords = '';
  1384. if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
  1385. {
  1386. $result = $db->query($sql);
  1387. $nbtotalofrecords = $db->num_rows($result);
  1388. }
  1389. $sql.= $db->order($sortfield, $sortorder);
  1390. $sql.= $db->plimit($limit+1,$offset);
  1391. $resql = $db->query($sql);
  1392. if ($resql)
  1393. {
  1394. $num = $db->num_rows($resql);
  1395. $param='&socid='.$socid;
  1396. if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage;
  1397. if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit;
  1398. if ($day) $param.='&day='.$day;
  1399. if ($month) $param.='&month='.$month;
  1400. if ($year) $param.='&year=' .$year;
  1401. if ($day_date_when) $param.='&day_date_when='.$day_date_when;
  1402. if ($month_date_when) $param.='&month_date_when='.$month_date_when;
  1403. if ($year_date_when) $param.='&year_date_when=' .$year_date_when;
  1404. if ($search_ref) $param.='&search_ref=' .$search_ref;
  1405. if ($search_societe) $param.='&search_societe=' .$search_societe;
  1406. if ($search_montant_ht != '') $param.='&search_montant_ht='.$search_montant_ht;
  1407. if ($search_montant_vat != '') $param.='&search_montant_vat='.$search_montant_vat;
  1408. if ($search_montant_ttc != '') $param.='&search_montant_ttc='.$search_montant_ttc;
  1409. if ($search_frequency) $param.='&search_frequency=' .$search_frequency;
  1410. if ($option) $param.="&option=".$option;
  1411. if ($optioncss != '') $param.='&optioncss='.$optioncss;
  1412. // Add $param from extra fields
  1413. foreach ($search_array_options as $key => $val)
  1414. {
  1415. $crit=$val;
  1416. $tmpkey=preg_replace('/search_options_/','',$key);
  1417. if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val);
  1418. }
  1419. $massactionbutton=$form->selectMassAction('', $massaction == 'presend' ? array() : array('presend'=>$langs->trans("SendByMail"), 'builddoc'=>$langs->trans("PDFMerge")));
  1420. print '<form method="POST" name="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'."\n";
  1421. if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
  1422. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  1423. print '<input type="hidden" name="action" value="list">';
  1424. print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
  1425. print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
  1426. print '<input type="hidden" name="page" value="'.$page.'">';
  1427. print '<input type="hidden" name="viewstatut" value="'.$viewstatut.'">';
  1428. print_barre_liste($langs->trans("RepeatableInvoices"),$page,$_SERVER['PHP_SELF'],$param,$sortfield,$sortorder,'',$num,$nbtotalofrecords,'title_accountancy.png',0,'','',$limit);
  1429. print $langs->trans("ToCreateAPredefinedInvoice", $langs->transnoentitiesnoconv("ChangeIntoRepeatableInvoice")).'<br><br>';
  1430. $i = 0;
  1431. print '<div class="div-table-responsive">';
  1432. print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n";
  1433. // Filters lines
  1434. print '<tr class="liste_titre_filter">';
  1435. // Ref
  1436. if (! empty($arrayfields['f.titre']['checked']))
  1437. {
  1438. print '<td class="liste_titre" align="left">';
  1439. print '<input class="flat" size="6" type="text" name="search_ref" value="'.dol_escape_htmltag($search_ref).'">';
  1440. print '</td>';
  1441. }
  1442. // Thirpdarty
  1443. if (! empty($arrayfields['s.nom']['checked']))
  1444. {
  1445. print '<td class="liste_titre" align="left"><input class="flat" type="text" size="8" name="search_societe" value="'.dol_escape_htmltag($search_societe).'"></td>';
  1446. }
  1447. if (! empty($arrayfields['f.total']['checked']))
  1448. {
  1449. // Amount
  1450. print '<td class="liste_titre" align="right">';
  1451. print '<input class="flat" type="text" size="5" name="search_montant_ht" value="'.dol_escape_htmltag($search_montant_ht).'">';
  1452. print '</td>';
  1453. }
  1454. if (! empty($arrayfields['f.tva']['checked']))
  1455. {
  1456. // Amount
  1457. print '<td class="liste_titre" align="right">';
  1458. print '<input class="flat" type="text" size="5" name="search_montant_vat" value="'.dol_escape_htmltag($search_montant_vat).'">';
  1459. print '</td>';
  1460. }
  1461. if (! empty($arrayfields['f.total_ttc']['checked']))
  1462. {
  1463. // Amount
  1464. print '<td class="liste_titre" align="right">';
  1465. print '<input class="flat" type="text" size="5" name="search_montant_ttc" value="'.dol_escape_htmltag($search_montant_ttc).'">';
  1466. print '</td>';
  1467. }
  1468. if (! empty($arrayfields['f.frequency']['checked']))
  1469. {
  1470. // Recurring or not
  1471. print '<td class="liste_titre" align="center">';
  1472. print $form->selectyesno('search_frequency', $search_frequency, 1, false, 1);
  1473. print '</td>';
  1474. }
  1475. if (! empty($arrayfields['f.nb_gen_done']['checked']))
  1476. {
  1477. // Nb generation
  1478. print '<td class="liste_titre" align="center">';
  1479. print '</td>';
  1480. }
  1481. // Date invoice
  1482. if (! empty($arrayfields['f.date_last_gen']['checked']))
  1483. {
  1484. print '<td class="liste_titre" align="center">';
  1485. if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat" type="text" size="1" maxlength="2" name="day" value="'.$day.'">';
  1486. print '<input class="flat" type="text" size="1" maxlength="2" name="month" value="'.$month.'">';
  1487. $formother->select_year($year?$year:-1,'year',1, 20, 5);
  1488. print '</td>';
  1489. }
  1490. // Date due
  1491. if (! empty($arrayfields['f.date_when']['checked']))
  1492. {
  1493. print '<td class="liste_titre" align="center">';
  1494. if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat" type="text" size="1" maxlength="2" name="day_date_when" value="'.$day_date_when.'">';
  1495. print '<input class="flat" type="text" size="1" maxlength="2" name="month_date_when" value="'.$month_date_when.'">';
  1496. $formother->select_year($year_date_when?$year_date_when:-1,'year_date_when',1, 20, 5);
  1497. print '</td>';
  1498. }
  1499. // Extra fields
  1500. if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label))
  1501. {
  1502. foreach($extrafields->attribute_label as $key => $val)
  1503. {
  1504. if (! empty($arrayfields["ef.".$key]['checked']))
  1505. {
  1506. $align=$extrafields->getAlignFlag($key);
  1507. $typeofextrafield=$extrafields->attribute_type[$key];
  1508. print '<td class="liste_titre'.($align?' '.$align:'').'">';
  1509. if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select')))
  1510. {
  1511. $crit=$val;
  1512. $tmpkey=preg_replace('/search_options_/','',$key);
  1513. $searchclass='';
  1514. if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring';
  1515. if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum';
  1516. print '<input class="flat'.($searchclass?' '.$searchclass:'').'" size="4" type="text" name="search_options_'.$tmpkey.'" value="'.dol_escape_htmltag($search_array_options['search_options_'.$tmpkey]).'">';
  1517. }
  1518. print '</td>';
  1519. }
  1520. }
  1521. }
  1522. // Fields from hook
  1523. $parameters=array('arrayfields'=>$arrayfields);
  1524. $reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // Note that $action and $object may have been modified by hook
  1525. print $hookmanager->resPrint;
  1526. // Date creation
  1527. if (! empty($arrayfields['f.datec']['checked']))
  1528. {
  1529. print '<td class="liste_titre">';
  1530. print '</td>';
  1531. }
  1532. // Date modification
  1533. if (! empty($arrayfields['f.tms']['checked']))
  1534. {
  1535. print '<td class="liste_titre">';
  1536. print '</td>';
  1537. }
  1538. // Action column
  1539. print '<td class="liste_titre" align="middle">';
  1540. $searchpicto=$form->showFilterAndCheckAddButtons(0, 'checkforselect', 1);
  1541. print $searchpicto;
  1542. print '</td>';
  1543. print "</tr>\n";
  1544. print '<tr class="liste_titre">';
  1545. print_liste_field_titre($langs->trans("Ref"),$_SERVER['PHP_SELF'],"f.titre","",$param,"",$sortfield,$sortorder);
  1546. print_liste_field_titre($langs->trans("ThirdParty"),$_SERVER['PHP_SELF'],"s.nom","",$param,"",$sortfield,$sortorder);
  1547. print_liste_field_titre($langs->trans("AmountHT"),$_SERVER['PHP_SELF'],"f.total","",$param,'align="right"',$sortfield,$sortorder);
  1548. print_liste_field_titre($langs->trans("AmountVAT"),$_SERVER['PHP_SELF'],"f.tva","",$param,'align="right"',$sortfield,$sortorder);
  1549. print_liste_field_titre($langs->trans("AmountTTC"),$_SERVER['PHP_SELF'],"f.total_ttc","",$param,'align="right"',$sortfield,$sortorder);
  1550. print_liste_field_titre($langs->trans("RecurringInvoiceTemplate"),$_SERVER['PHP_SELF'],"f.frequency","",$param,'align="center"',$sortfield,$sortorder);
  1551. if (! empty($arrayfields['f.nb_gen_done']['checked']))
  1552. {
  1553. print_liste_field_titre($langs->trans("NbOfGenerationDone"),$_SERVER['PHP_SELF'],"f.nb_gen_done","",$param,'align="center"',$sortfield,$sortorder);
  1554. }
  1555. print_liste_field_titre($langs->trans("DateLastGeneration"),$_SERVER['PHP_SELF'],"f.date_last_gen","",$param,'align="center"',$sortfield,$sortorder);
  1556. print_liste_field_titre($langs->trans("NextDateToExecution"),$_SERVER['PHP_SELF'],"f.date_when","",$param,'align="center"',$sortfield,$sortorder);
  1557. print_liste_field_titre(''); // Field may contains ling text
  1558. print "</tr>\n";
  1559. if ($num > 0)
  1560. {
  1561. $var=true;
  1562. while ($i < min($num,$limit))
  1563. {
  1564. $objp = $db->fetch_object($resql);
  1565. print '<tr class="oddeven">';
  1566. print '<td><a href="'.$_SERVER['PHP_SELF'].'?id='.$objp->facid.'">'.img_object($langs->trans("ShowBill"),"bill").' '.$objp->titre;
  1567. print "</a></td>\n";
  1568. $companystatic->id=$objp->socid;
  1569. $companystatic->name=$objp->name;
  1570. print '<td class="tdoverflowmax200">'.$companystatic->getNomUrl(1,'customer').'</td>';
  1571. print '<td align="right">'.price($objp->total).'</td>'."\n";
  1572. print '<td align="right">'.price($objp->total_vat).'</td>'."\n";
  1573. print '<td align="right">'.price($objp->total_ttc).'</td>'."\n";
  1574. print '<td align="center">'.yn($objp->frequency?1:0).'</td>';
  1575. if (! empty($arrayfields['f.nb_gen_done']['checked']))
  1576. {
  1577. print '<td align="center">'.($objp->frequency ? $objp->nb_gen_done.($objp->nb_gen_max>0?' / '. $objp->nb_gen_max:'') : '').'</td>';
  1578. }
  1579. print '<td align="center">'.($objp->frequency ? dol_print_date($objp->date_last_gen,'day') : '').'</td>';
  1580. print '<td align="center">'.($objp->frequency ? dol_print_date($objp->date_when,'day') : '').'</td>';
  1581. print '<td align="center">';
  1582. if ($user->rights->facture->creer)
  1583. {
  1584. if (empty($objp->frequency) || $db->jdate($objp->date_when) <= $today)
  1585. {
  1586. print '<a href="'.DOL_URL_ROOT.'/compta/facture/card.php?action=create&amp;socid='.$objp->socid.'&amp;fac_rec='.$objp->facid.'">';
  1587. print $langs->trans("CreateBill").'</a>';
  1588. }
  1589. else
  1590. {
  1591. print $langs->trans("DateIsNotEnough");
  1592. }
  1593. }
  1594. else
  1595. {
  1596. print "&nbsp;";
  1597. }
  1598. print "</td>";
  1599. print "</tr>\n";
  1600. $i++;
  1601. }
  1602. }
  1603. else print '<tr '.$bc[false].'><td colspan="9" class="opacitymedium">'.$langs->trans("NoneF").'</td></tr>';
  1604. print "</table>";
  1605. print "</div>";
  1606. print "</form>";
  1607. $db->free($resql);
  1608. }
  1609. else
  1610. {
  1611. dol_print_error($db);
  1612. }
  1613. }
  1614. }
  1615. llxFooter();
  1616. $db->close();