card.php 163 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828
  1. <?php
  2. /* Copyright (C) 2002-2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004-2020 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2004 Christophe Combelles <ccomb@free.fr>
  5. * Copyright (C) 2005 Marc Barilley <marc@ocebo.fr>
  6. * Copyright (C) 2005-2013 Regis Houssin <regis.houssin@inodbox.com>
  7. * Copyright (C) 2010-2019 Juanjo Menent <jmenent@2byte.es>
  8. * Copyright (C) 2013-2015 Philippe Grand <philippe.grand@atoo-net.com>
  9. * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
  10. * Copyright (C) 2014-2016 Marcos García <marcosgdf@gmail.com>
  11. * Copyright (C) 2016-2021 Alexandre Spangaro <aspangaro@open-dsi.fr>
  12. * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
  13. * Copyright (C) 2019 Ferran Marcet <fmarcet@2byte.es>
  14. * Copyright (C) 2022 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
  15. *
  16. * This program is free software; you can redistribute it and/or modify
  17. * it under the terms of the GNU General Public License as published by
  18. * the Free Software Foundation; either version 3 of the License, or
  19. * (at your option) any later version.
  20. *
  21. * This program is distributed in the hope that it will be useful,
  22. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  24. * GNU General Public License for more details.
  25. *
  26. * You should have received a copy of the GNU General Public License
  27. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  28. */
  29. /**
  30. * \file htdocs/fourn/facture/card.php
  31. * \ingroup facture, fournisseur
  32. * \brief Page for supplier invoice card (view, edit, validate)
  33. */
  34. require '../../main.inc.php';
  35. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
  36. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.class.php';
  37. require_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_invoice/modules_facturefournisseur.php';
  38. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
  39. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture-rec.class.php';
  40. require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php';
  41. require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
  42. require_once DOL_DOCUMENT_ROOT.'/core/lib/fourn.lib.php';
  43. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  44. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  45. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  46. if (!empty($conf->product->enabled)) {
  47. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  48. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  49. }
  50. if (!empty($conf->projet->enabled)) {
  51. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  52. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
  53. }
  54. if (!empty($conf->variants->enabled)) {
  55. require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php';
  56. }
  57. if (!empty($conf->accounting->enabled)) {
  58. require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php';
  59. }
  60. $langs->loadLangs(array('bills', 'compta', 'suppliers', 'companies', 'products', 'banks', 'admin'));
  61. if (!empty($conf->incoterm->enabled)) {
  62. $langs->load('incoterm');
  63. }
  64. $id = (GETPOST('facid', 'int') ? GETPOST('facid', 'int') : GETPOST('id', 'int'));
  65. $socid = GETPOST('socid', 'int');
  66. $action = GETPOST('action', 'aZ09');
  67. $confirm = GETPOST("confirm");
  68. $ref = GETPOST('ref', 'alpha');
  69. $cancel = GETPOST('cancel', 'alpha');
  70. $lineid = GETPOST('lineid', 'int');
  71. $projectid = GETPOST('projectid', 'int');
  72. $origin = GETPOST('origin', 'alpha');
  73. $originid = GETPOST('originid', 'int');
  74. $fac_recid = GETPOST('fac_rec', 'int');
  75. $rank = (GETPOST('rank', 'int') > 0) ? GETPOST('rank', 'int') : -1;
  76. // PDF
  77. $hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0));
  78. $hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0));
  79. $hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0));
  80. // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
  81. $hookmanager->initHooks(array('invoicesuppliercard', 'globalcard'));
  82. $object = new FactureFournisseur($db);
  83. $extrafields = new ExtraFields($db);
  84. // fetch optionals attributes and labels
  85. $extrafields->fetch_name_optionals_label($object->table_element);
  86. // Load object
  87. if ($id > 0 || !empty($ref)) {
  88. $ret = $object->fetch($id, $ref);
  89. if ($ret < 0) {
  90. dol_print_error($db, $object->error);
  91. }
  92. $ret = $object->fetch_thirdparty();
  93. if ($ret < 0) {
  94. dol_print_error($db, $object->error);
  95. }
  96. }
  97. // Security check
  98. $socid = '';
  99. if (!empty($user->socid)) {
  100. $socid = $user->socid;
  101. }
  102. $isdraft = (($object->statut == FactureFournisseur::STATUS_DRAFT) ? 1 : 0);
  103. $result = restrictedArea($user, 'fournisseur', $id, 'facture_fourn', 'facture', 'fk_soc', 'rowid', $isdraft);
  104. // Common permissions
  105. $usercanread = ($user->rights->fournisseur->facture->lire || $user->rights->supplier_invoice->lire);
  106. $usercancreate = ($user->rights->fournisseur->facture->creer || $user->rights->supplier_invoice->creer);
  107. $usercandelete = ($user->rights->fournisseur->facture->supprimer || $user->rights->supplier_invoice->supprimer);
  108. // Advanced permissions
  109. $usercanvalidate = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($usercancreate)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->fournisseur->supplier_invoice_advance->validate)));
  110. $usercansend = (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->fournisseur->supplier_invoice_advance->send);
  111. // Permissions for includes
  112. $permissionnote = $usercancreate; // Used by the include of actions_setnotes.inc.php
  113. $permissiondellink = $usercancreate; // Used by the include of actions_dellink.inc.php
  114. $permissiontoedit = $usercancreate; // Used by the include of actions_lineupdown.inc.php
  115. $permissiontoadd = $usercancreate; // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php
  116. $error = 0;
  117. /*
  118. * Actions
  119. */
  120. $parameters = array('socid'=>$socid);
  121. $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  122. if ($reshook < 0) {
  123. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  124. }
  125. if (empty($reshook)) {
  126. $backurlforlist = DOL_URL_ROOT.'/fourn/facture/list.php';
  127. if (empty($backtopage) || ($cancel && empty($id))) {
  128. if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) {
  129. if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) {
  130. $backtopage = $backurlforlist;
  131. } else {
  132. $backtopage = DOL_URL_ROOT.'/fourn/facture/card.php?id='.((!empty($id) && $id > 0) ? $id : '__ID__');
  133. }
  134. }
  135. }
  136. if ($cancel) {
  137. if (!empty($backtopageforcancel)) {
  138. header("Location: ".$backtopageforcancel);
  139. exit;
  140. } elseif (!empty($backtopage)) {
  141. header("Location: ".$backtopage);
  142. exit;
  143. }
  144. $action = '';
  145. }
  146. include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once
  147. include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once
  148. include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once
  149. // Link invoice to order
  150. if (GETPOST('linkedOrder') && empty($cancel) && $id > 0) {
  151. $object->fetch($id);
  152. $object->fetch_thirdparty();
  153. $result = $object->add_object_linked('order_supplier', GETPOST('linkedOrder'));
  154. }
  155. // Action clone object
  156. if ($action == 'confirm_clone' && $confirm == 'yes' && $permissiontoadd) {
  157. $objectutil = dol_clone($object, 1); // To avoid to denaturate loaded object when setting some properties for clone. We use native clone to keep this->db valid.
  158. if (GETPOST('newsupplierref', 'alphanohtml')) {
  159. $objectutil->ref_supplier = GETPOST('newsupplierref', 'alphanohtml');
  160. }
  161. $objectutil->date = dol_mktime(12, 0, 0, GETPOST('newdatemonth', 'int'), GETPOST('newdateday', 'int'), GETPOST('newdateyear', 'int'));
  162. $result = $objectutil->createFromClone($user, $id);
  163. if ($result > 0) {
  164. header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result);
  165. exit;
  166. } else {
  167. $langs->load("errors");
  168. setEventMessages($objectutil->error, $objectutil->errors, 'errors');
  169. $action = '';
  170. }
  171. } elseif ($action == 'confirm_valid' && $confirm == 'yes' && $usercanvalidate) {
  172. $idwarehouse = GETPOST('idwarehouse');
  173. $object->fetch($id);
  174. $object->fetch_thirdparty();
  175. $qualified_for_stock_change = 0;
  176. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  177. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  178. } else {
  179. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  180. }
  181. // Check parameters
  182. if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) {
  183. $langs->load("stocks");
  184. if (!$idwarehouse || $idwarehouse == -1) {
  185. $error++;
  186. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
  187. $action = '';
  188. }
  189. }
  190. if (!$error) {
  191. $result = $object->validate($user, '', $idwarehouse);
  192. if ($result < 0) {
  193. setEventMessages($object->error, $object->errors, 'errors');
  194. } else {
  195. // Define output language
  196. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  197. $outputlangs = $langs;
  198. $newlang = '';
  199. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  200. $newlang = GETPOST('lang_id', 'aZ09');
  201. }
  202. if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
  203. $newlang = $object->thirdparty->default_lang;
  204. }
  205. if (!empty($newlang)) {
  206. $outputlangs = new Translate("", $conf);
  207. $outputlangs->setDefaultLang($newlang);
  208. }
  209. $model = $object->model_pdf;
  210. $ret = $object->fetch($id); // Reload to get new records
  211. $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  212. if ($result < 0) {
  213. dol_print_error($db, $result);
  214. }
  215. }
  216. }
  217. }
  218. } elseif ($action == 'confirm_delete' && $confirm == 'yes') {
  219. $object->fetch($id);
  220. $object->fetch_thirdparty();
  221. $isErasable = $object->is_erasable();
  222. if (($usercandelete && $isErasable > 0) || ($usercancreate && $isErasable == 1)) {
  223. $result = $object->delete($user);
  224. if ($result > 0) {
  225. header('Location: list.php?restore_lastsearch_values=1');
  226. exit;
  227. } else {
  228. setEventMessages($object->error, $object->errors, 'errors');
  229. }
  230. }
  231. } elseif ($action == 'confirm_deleteline' && $confirm == 'yes' && $usercancreate) {
  232. // Remove a product line
  233. $result = $object->deleteline($lineid);
  234. if ($result > 0) {
  235. // reorder lines
  236. $object->line_order(true);
  237. // Define output language
  238. /*$outputlangs = $langs;
  239. $newlang = '';
  240. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09'))
  241. $newlang = GETPOST('lang_id','aZ09');
  242. if ($conf->global->MAIN_MULTILANGS && empty($newlang))
  243. $newlang = $object->thirdparty->default_lang;
  244. if (! empty($newlang)) {
  245. $outputlangs = new Translate("", $conf);
  246. $outputlangs->setDefaultLang($newlang);
  247. }
  248. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  249. $ret = $object->fetch($object->id); // Reload to get new records
  250. $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  251. }*/
  252. header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id);
  253. exit;
  254. } else {
  255. setEventMessages($object->error, $object->errors, 'errors');
  256. /* Fix bug 1485 : Reset action to avoid asking again confirmation on failure */
  257. $action = '';
  258. }
  259. } elseif ($action == 'unlinkdiscount' && $usercancreate) {
  260. // Delete link of credit note to invoice
  261. $discount = new DiscountAbsolute($db);
  262. $result = $discount->fetch(GETPOST("discountid"));
  263. $discount->unlink_invoice();
  264. } elseif ($action == 'confirm_paid' && $confirm == 'yes' && $usercancreate) {
  265. $object->fetch($id);
  266. $result = $object->setPaid($user);
  267. if ($result < 0) {
  268. setEventMessages($object->error, $object->errors, 'errors');
  269. }
  270. } elseif ($action == 'confirm_paid_partially' && $confirm == 'yes') {
  271. // Classif "paid partialy"
  272. $object->fetch($id);
  273. $close_code = GETPOST("close_code", 'restricthtml');
  274. $close_note = GETPOST("close_note", 'restricthtml');
  275. if ($close_code) {
  276. $result = $object->setPaid($user, $close_code, $close_note);
  277. if ($result < 0) {
  278. setEventMessages($object->error, $object->errors, 'errors');
  279. }
  280. } else {
  281. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Reason")), null, 'errors');
  282. }
  283. } elseif ($action == 'confirm_canceled' && $confirm == 'yes') {
  284. // Classify "abandoned"
  285. $object->fetch($id);
  286. $close_code = GETPOST("close_code", 'restricthtml');
  287. $close_note = GETPOST("close_note", 'restricthtml');
  288. if ($close_code) {
  289. $result = $object->setCanceled($user, $close_code, $close_note);
  290. if ($result < 0) {
  291. setEventMessages($object->error, $object->errors, 'errors');
  292. }
  293. } else {
  294. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Reason")), null, 'errors');
  295. }
  296. }
  297. // Set supplier ref
  298. if ($action == 'setref_supplier' && $usercancreate) {
  299. $object->ref_supplier = GETPOST('ref_supplier', 'alpha');
  300. if ($object->update($user) < 0) {
  301. setEventMessages($object->error, $object->errors, 'errors');
  302. } else {
  303. // Define output language
  304. $outputlangs = $langs;
  305. $newlang = '';
  306. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  307. $newlang = GETPOST('lang_id', 'aZ09');
  308. }
  309. if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
  310. $newlang = $object->thirdparty->default_lang;
  311. }
  312. if (!empty($newlang)) {
  313. $outputlangs = new Translate("", $conf);
  314. $outputlangs->setDefaultLang($newlang);
  315. }
  316. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  317. $ret = $object->fetch($object->id); // Reload to get new records
  318. $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  319. }
  320. }
  321. }
  322. // payments conditions
  323. if ($action == 'setconditions' && $usercancreate) {
  324. $object->fetch($id);
  325. $object->cond_reglement_code = 0; // To clean property
  326. $object->cond_reglement_id = 0; // To clean property
  327. $error = 0;
  328. $db->begin();
  329. if (!$error) {
  330. $result = $object->setPaymentTerms(GETPOST('cond_reglement_id', 'int'));
  331. if ($result < 0) {
  332. $error++;
  333. setEventMessages($object->error, $object->errors, 'errors');
  334. }
  335. }
  336. if (!$error) {
  337. $old_date_echeance = $object->date_echeance;
  338. $new_date_echeance = $object->calculate_date_lim_reglement();
  339. if ($new_date_echeance > $old_date_echeance) {
  340. $object->date_echeance = $new_date_echeance;
  341. }
  342. if ($object->date_echeance < $object->date) {
  343. $object->date_echeance = $object->date;
  344. }
  345. $result = $object->update($user);
  346. if ($result < 0) {
  347. $error++;
  348. setEventMessages($object->error, $object->errors, 'errors');
  349. }
  350. }
  351. if ($error) {
  352. $db->rollback();
  353. } else {
  354. $db->commit();
  355. }
  356. } elseif ($action == 'set_incoterms' && !empty($conf->incoterm->enabled)) {
  357. // Set incoterm
  358. $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha'));
  359. } elseif ($action == 'setmode' && $usercancreate) {
  360. // payment mode
  361. $result = $object->setPaymentMethods(GETPOST('mode_reglement_id', 'int'));
  362. } elseif ($action == 'setmulticurrencycode' && $usercancreate) {
  363. // Multicurrency Code
  364. $result = $object->setMulticurrencyCode(GETPOST('multicurrency_code', 'alpha'));
  365. } elseif ($action == 'setmulticurrencyrate' && $usercancreate) {
  366. // Multicurrency rate
  367. $result = $object->setMulticurrencyRate(price2num(GETPOST('multicurrency_tx', 'alpha')), GETPOST('calculation_mode', 'int'));
  368. } elseif ($action == 'setbankaccount' && $usercancreate) {
  369. // bank account
  370. $result = $object->setBankAccount(GETPOST('fk_account', 'int'));
  371. }
  372. if ($action == 'settransportmode' && ($user->rights->fournisseur->facture->creer || $user->rights->supplier_invoice->creer)) {
  373. // transport mode
  374. $result = $object->setTransportMode(GETPOST('transport_mode_id', 'int'));
  375. } elseif ($action == 'setlabel' && $usercancreate) {
  376. // Set label
  377. $object->fetch($id);
  378. $object->label = GETPOST('label');
  379. $result = $object->update($user);
  380. if ($result < 0) {
  381. dol_print_error($db);
  382. }
  383. } elseif ($action == 'setdatef' && $usercancreate) {
  384. $newdate = dol_mktime(0, 0, 0, GETPOST('datefmonth', 'int'), GETPOST('datefday', 'int'), GETPOST('datefyear', 'int'), 'tzserver');
  385. if ($newdate > (dol_now('tzuserrel') + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
  386. if (empty($conf->global->INVOICE_MAX_FUTURE_DELAY)) {
  387. setEventMessages($langs->trans("WarningInvoiceDateInFuture"), null, 'warnings');
  388. } else {
  389. setEventMessages($langs->trans("WarningInvoiceDateTooFarInFuture"), null, 'warnings');
  390. }
  391. }
  392. $object->fetch($id);
  393. $object->date = $newdate;
  394. $date_echence_calc = $object->calculate_date_lim_reglement();
  395. if (!empty($object->date_echeance) && $object->date_echeance < $date_echence_calc) {
  396. $object->date_echeance = $date_echence_calc;
  397. }
  398. if ($object->date_echeance && $object->date_echeance < $object->date) {
  399. $object->date_echeance = $object->date;
  400. }
  401. $result = $object->update($user);
  402. if ($result < 0) {
  403. dol_print_error($db, $object->error);
  404. }
  405. } elseif ($action == 'setdate_lim_reglement' && $usercancreate) {
  406. $object->fetch($id);
  407. $object->date_echeance = dol_mktime(12, 0, 0, GETPOST('date_lim_reglementmonth', 'int'), GETPOST('date_lim_reglementday', 'int'), GETPOST('date_lim_reglementyear', 'int'));
  408. if (!empty($object->date_echeance) && $object->date_echeance < $object->date) {
  409. $object->date_echeance = $object->date;
  410. setEventMessages($langs->trans("DatePaymentTermCantBeLowerThanObjectDate"), null, 'warnings');
  411. }
  412. $result = $object->update($user);
  413. if ($result < 0) {
  414. dol_print_error($db, $object->error);
  415. }
  416. } elseif ($action == "setabsolutediscount" && $usercancreate) {
  417. // We use the credit to reduce amount of invoice
  418. if (GETPOST("remise_id", "int")) {
  419. $ret = $object->fetch($id);
  420. if ($ret > 0) {
  421. $result = $object->insert_discount(GETPOST("remise_id", "int"));
  422. if ($result < 0) {
  423. setEventMessages($object->error, $object->errors, 'errors');
  424. }
  425. } else {
  426. dol_print_error($db, $object->error);
  427. }
  428. }
  429. // We use the credit to reduce remain to pay
  430. if (GETPOST("remise_id_for_payment", "int")) {
  431. require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
  432. $discount = new DiscountAbsolute($db);
  433. $discount->fetch(GETPOST("remise_id_for_payment", "int"));
  434. //var_dump($object->getRemainToPay(0));
  435. //var_dump($discount->amount_ttc);exit;
  436. if (price2num($discount->amount_ttc) > price2num($object->getRemainToPay(0))) {
  437. // TODO Split the discount in 2 automatically
  438. $error++;
  439. setEventMessages($langs->trans("ErrorDiscountLargerThanRemainToPaySplitItBefore"), null, 'errors');
  440. }
  441. if (!$error) {
  442. $result = $discount->link_to_invoice(0, $id);
  443. if ($result < 0) {
  444. setEventMessages($discount->error, $discount->errors, 'errors');
  445. }
  446. }
  447. }
  448. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  449. $outputlangs = $langs;
  450. $newlang = '';
  451. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  452. $newlang = GETPOST('lang_id', 'aZ09');
  453. }
  454. if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
  455. $newlang = $object->thirdparty->default_lang;
  456. }
  457. if (!empty($newlang)) {
  458. $outputlangs = new Translate("", $conf);
  459. $outputlangs->setDefaultLang($newlang);
  460. }
  461. $ret = $object->fetch($id); // Reload to get new records
  462. $result = $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  463. if ($result < 0) {
  464. setEventMessages($object->error, $object->errors, 'errors');
  465. }
  466. }
  467. } elseif ($action == 'confirm_converttoreduc' && $confirm == 'yes' && $usercancreate) {
  468. // Convertir en reduc
  469. $object->fetch($id);
  470. $object->fetch_thirdparty();
  471. //$object->fetch_lines(); // Already done into fetch
  472. // Check if there is already a discount (protection to avoid duplicate creation when resubmit post)
  473. $discountcheck = new DiscountAbsolute($db);
  474. $result = $discountcheck->fetch(0, 0, $object->id);
  475. $canconvert = 0;
  476. if ($object->type == FactureFournisseur::TYPE_DEPOSIT && empty($discountcheck->id)) {
  477. $canconvert = 1; // we can convert deposit into discount if deposit is paid (completely, partially or not at all) and not already converted (see real condition into condition used to show button converttoreduc)
  478. }
  479. if (($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_STANDARD) && $object->paye == 0 && empty($discountcheck->id)) {
  480. $canconvert = 1; // we can convert credit note into discount if credit note is not refunded completely and not already converted and amount of payment is 0 (see also the real condition used as the condition to show button converttoreduc)
  481. }
  482. if ($canconvert) {
  483. $db->begin();
  484. $amount_ht = $amount_tva = $amount_ttc = array();
  485. $multicurrency_amount_ht = $multicurrency_amount_tva = $multicurrency_amount_ttc = array();
  486. // Loop on each vat rate
  487. $i = 0;
  488. foreach ($object->lines as $line) {
  489. if ($line->product_type < 9 && $line->total_ht != 0) { // Remove lines with product_type greater than or equal to 9 and no need to create discount if amount is null
  490. $keyforvatrate = $line->tva_tx.($line->vat_src_code ? ' ('.$line->vat_src_code.')' : '');
  491. $amount_ht[$keyforvatrate] += $line->total_ht;
  492. $amount_tva[$keyforvatrate] += $line->total_tva;
  493. $amount_ttc[$keyforvatrate] += $line->total_ttc;
  494. $multicurrency_amount_ht[$keyforvatrate] += $line->multicurrency_total_ht;
  495. $multicurrency_amount_tva[$keyforvatrate] += $line->multicurrency_total_tva;
  496. $multicurrency_amount_ttc[$keyforvatrate] += $line->multicurrency_total_ttc;
  497. $i++;
  498. }
  499. }
  500. // If some payments were already done, we change the amount to pay using same prorate
  501. if (!empty($conf->global->SUPPLIER_INVOICE_ALLOW_REUSE_OF_CREDIT_WHEN_PARTIALLY_REFUNDED) && $object->type == FactureFournisseur::TYPE_CREDIT_NOTE) {
  502. $alreadypaid = $object->getSommePaiement(); // This can be not 0 if we allow to create credit to reuse from credit notes partially refunded.
  503. if ($alreadypaid && abs($alreadypaid) < abs($object->total_ttc)) {
  504. $ratio = abs(($object->total_ttc - $alreadypaid) / $object->total_ttc);
  505. foreach ($amount_ht as $vatrate => $val) {
  506. $amount_ht[$vatrate] = price2num($amount_ht[$vatrate] * $ratio, 'MU');
  507. $amount_tva[$vatrate] = price2num($amount_tva[$vatrate] * $ratio, 'MU');
  508. $amount_ttc[$vatrate] = price2num($amount_ttc[$vatrate] * $ratio, 'MU');
  509. $multicurrency_amount_ht[$vatrate] = price2num($multicurrency_amount_ht[$vatrate] * $ratio, 'MU');
  510. $multicurrency_amount_tva[$vatrate] = price2num($multicurrency_amount_tva[$vatrate] * $ratio, 'MU');
  511. $multicurrency_amount_ttc[$vatrate] = price2num($multicurrency_amount_ttc[$vatrate] * $ratio, 'MU');
  512. }
  513. }
  514. }
  515. //var_dump($amount_ht);var_dump($amount_tva);var_dump($amount_ttc);exit;
  516. // Insert one discount by VAT rate category
  517. $discount = new DiscountAbsolute($db);
  518. if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) {
  519. $discount->description = '(CREDIT_NOTE)';
  520. } elseif ($object->type == FactureFournisseur::TYPE_DEPOSIT) {
  521. $discount->description = '(DEPOSIT)';
  522. } elseif ($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_REPLACEMENT || $object->type == FactureFournisseur::TYPE_SITUATION) {
  523. $discount->description = '(EXCESS PAID)';
  524. } else {
  525. setEventMessages($langs->trans('CantConvertToReducAnInvoiceOfThisType'), null, 'errors');
  526. }
  527. $discount->discount_type = 1; // Supplier discount
  528. $discount->fk_soc = $object->socid;
  529. $discount->fk_invoice_supplier_source = $object->id;
  530. $error = 0;
  531. if ($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_REPLACEMENT || $object->type == FactureFournisseur::TYPE_SITUATION) {
  532. // If we're on a standard invoice, we have to get excess paid to create a discount in TTC without VAT
  533. // Total payments
  534. $sql = 'SELECT SUM(pf.amount) as total_paiements';
  535. $sql .= ' FROM '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf, '.MAIN_DB_PREFIX.'paiementfourn as p';
  536. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id AND c.entity IN ('.getEntity('c_paiement').')';
  537. $sql .= ' WHERE pf.fk_facturefourn = '.((int) $object->id);
  538. $sql .= ' AND pf.fk_paiementfourn = p.rowid';
  539. $sql .= ' AND p.entity IN ('.getEntity('invoice').')';
  540. $resql = $db->query($sql);
  541. if (!$resql) {
  542. dol_print_error($db);
  543. }
  544. $res = $db->fetch_object($resql);
  545. $total_paiements = $res->total_paiements;
  546. // Total credit note and deposit
  547. $total_creditnote_and_deposit = 0;
  548. $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
  549. $sql .= " re.description, re.fk_invoice_supplier_source";
  550. $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re";
  551. $sql .= " WHERE fk_invoice_supplier = ".((int) $object->id);
  552. $resql = $db->query($sql);
  553. if (!empty($resql)) {
  554. while ($obj = $db->fetch_object($resql)) {
  555. $total_creditnote_and_deposit += $obj->amount_ttc;
  556. }
  557. } else {
  558. dol_print_error($db);
  559. }
  560. $discount->amount_ht = $discount->amount_ttc = $total_paiements + $total_creditnote_and_deposit - $object->total_ttc;
  561. $discount->amount_tva = 0;
  562. $discount->tva_tx = 0;
  563. $discount->vat_src_code = '';
  564. $result = $discount->create($user);
  565. if ($result < 0) {
  566. $error++;
  567. }
  568. }
  569. if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) {
  570. foreach ($amount_ht as $tva_tx => $xxx) {
  571. $discount->amount_ht = abs($amount_ht[$tva_tx]);
  572. $discount->amount_tva = abs($amount_tva[$tva_tx]);
  573. $discount->amount_ttc = abs($amount_ttc[$tva_tx]);
  574. $discount->multicurrency_amount_ht = abs($multicurrency_amount_ht[$tva_tx]);
  575. $discount->multicurrency_amount_tva = abs($multicurrency_amount_tva[$tva_tx]);
  576. $discount->multicurrency_amount_ttc = abs($multicurrency_amount_ttc[$tva_tx]);
  577. // Clean vat code
  578. $reg = array();
  579. $vat_src_code = '';
  580. if (preg_match('/\((.*)\)/', $tva_tx, $reg)) {
  581. $vat_src_code = $reg[1];
  582. $tva_tx = preg_replace('/\s*\(.*\)/', '', $tva_tx); // Remove code into vatrate.
  583. }
  584. $discount->tva_tx = abs($tva_tx);
  585. $discount->vat_src_code = $vat_src_code;
  586. $result = $discount->create($user);
  587. if ($result < 0) {
  588. $error++;
  589. break;
  590. }
  591. }
  592. }
  593. if (empty($error)) {
  594. if ($object->type != FactureFournisseur::TYPE_DEPOSIT) {
  595. // Classe facture
  596. $result = $object->setPaid($user);
  597. if ($result >= 0) {
  598. $db->commit();
  599. } else {
  600. setEventMessages($object->error, $object->errors, 'errors');
  601. $db->rollback();
  602. }
  603. } else {
  604. $db->commit();
  605. }
  606. } else {
  607. setEventMessages($discount->error, $discount->errors, 'errors');
  608. $db->rollback();
  609. }
  610. }
  611. } elseif ($action == 'confirm_delete_paiement' && $confirm == 'yes' && $usercancreate) {
  612. // Delete payment
  613. $object->fetch($id);
  614. if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0) {
  615. $paiementfourn = new PaiementFourn($db);
  616. $result = $paiementfourn->fetch(GETPOST('paiement_id'));
  617. if ($result > 0) {
  618. $result = $paiementfourn->delete(); // If fetch ok and found
  619. header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
  620. }
  621. if ($result < 0) {
  622. setEventMessages($paiementfourn->error, $paiementfourn->errors, 'errors');
  623. }
  624. }
  625. } elseif ($action == 'add' && $usercancreate) {
  626. // Insert new invoice in database
  627. if ($socid > 0) {
  628. $object->socid = GETPOST('socid', 'int');
  629. }
  630. $selectedLines = GETPOST('toselect', 'array');
  631. $db->begin();
  632. $error = 0;
  633. // Fill array 'array_options' with data from add form
  634. $ret = $extrafields->setOptionalsFromPost(null, $object);
  635. if ($ret < 0) {
  636. $error++;
  637. }
  638. $dateinvoice = dol_mktime(0, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int'), 'tzserver'); // If we enter the 02 january, we need to save the 02 january for server
  639. $datedue = dol_mktime(0, 0, 0, GETPOST('echmonth', 'int'), GETPOST('echday', 'int'), GETPOST('echyear', 'int'), 'tzserver');
  640. //var_dump($dateinvoice.' '.dol_print_date($dateinvoice, 'dayhour'));
  641. //var_dump(dol_now('tzuserrel').' '.dol_get_last_hour(dol_now('tzuserrel')).' '.dol_print_date(dol_now('tzuserrel'),'dayhour').' '.dol_print_date(dol_get_last_hour(dol_now('tzuserrel')), 'dayhour'));
  642. //var_dump($db->idate($dateinvoice));
  643. //exit;
  644. // Replacement invoice
  645. if (GETPOST('type', 'int') === '') {
  646. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
  647. $error++;
  648. }
  649. if (GETPOST('type') == FactureFournisseur::TYPE_REPLACEMENT) {
  650. if (empty($dateinvoice)) {
  651. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('DateInvoice')), null, 'errors');
  652. $action = 'create';
  653. $_GET['socid'] = $_POST['socid'];
  654. $error++;
  655. } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
  656. $error++;
  657. setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
  658. $action = 'create';
  659. }
  660. if (!(GETPOST('fac_replacement', 'int') > 0)) {
  661. $error++;
  662. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ReplaceInvoice")), null, 'errors');
  663. }
  664. if (!$error) {
  665. // This is a replacement invoice
  666. $result = $object->fetch(GETPOST('fac_replacement', 'int'));
  667. $object->fetch_thirdparty();
  668. $object->ref = GETPOST('ref', 'nohtml');
  669. $object->ref_supplier = GETPOST('ref_supplier', 'alpha');
  670. $object->socid = GETPOST('socid', 'int');
  671. $object->libelle = GETPOST('label', 'nohtml');
  672. $object->date = $dateinvoice;
  673. $object->date_echeance = $datedue;
  674. $object->note_public = GETPOST('note_public', 'restricthtml');
  675. $object->note_private = GETPOST('note_private', 'restricthtml');
  676. $object->cond_reglement_id = GETPOST('cond_reglement_id', 'int');
  677. $object->mode_reglement_id = GETPOST('mode_reglement_id', 'int');
  678. $object->fk_account = GETPOST('fk_account', 'int');
  679. $object->fk_project = ($tmpproject > 0) ? $tmpproject : null;
  680. $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  681. $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  682. $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  683. $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
  684. $object->transport_mode_id = GETPOST('transport_mode_id', 'int');
  685. // Proprietes particulieres a facture de remplacement
  686. $object->fk_facture_source = GETPOST('fac_replacement', 'int');
  687. $object->type = FactureFournisseur::TYPE_REPLACEMENT;
  688. $id = $object->createFromCurrent($user);
  689. if ($id <= 0) {
  690. $error++;
  691. setEventMessages($object->error, $object->errors, 'errors');
  692. }
  693. }
  694. }
  695. // Credit note invoice
  696. if (GETPOST('type') == FactureFournisseur::TYPE_CREDIT_NOTE) {
  697. $sourceinvoice = GETPOST('fac_avoir', 'int');
  698. if (!($sourceinvoice > 0) && empty($conf->global->INVOICE_CREDIT_NOTE_STANDALONE)) {
  699. $error++;
  700. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CorrectInvoice")), null, 'errors');
  701. }
  702. if (GETPOST('socid', 'int') < 1) {
  703. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('Supplier')), null, 'errors');
  704. $action = 'create';
  705. $error++;
  706. }
  707. if (empty($dateinvoice)) {
  708. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('DateInvoice')), null, 'errors');
  709. $action = 'create';
  710. $_GET['socid'] = $_POST['socid'];
  711. $error++;
  712. } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
  713. $error++;
  714. setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
  715. $action = 'create';
  716. }
  717. if (!GETPOST('ref_supplier')) {
  718. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('RefSupplier')), null, 'errors');
  719. $action = 'create';
  720. $_GET['socid'] = $_POST['socid'];
  721. $error++;
  722. }
  723. if (!$error) {
  724. $tmpproject = GETPOST('projectid', 'int');
  725. // Creation facture
  726. $object->ref = GETPOST('ref', 'nohtml');
  727. $object->ref_supplier = GETPOST('ref_supplier', 'nohtml');
  728. $object->socid = GETPOST('socid', 'int');
  729. $object->libelle = GETPOST('label', 'nohtml');
  730. $object->label = GETPOST('label', 'nohtml');
  731. $object->date = $dateinvoice;
  732. $object->date_echeance = $datedue;
  733. $object->note_public = GETPOST('note_public', 'restricthtml');
  734. $object->note_private = GETPOST('note_private', 'restricthtml');
  735. $object->cond_reglement_id = GETPOST('cond_reglement_id');
  736. $object->mode_reglement_id = GETPOST('mode_reglement_id');
  737. $object->fk_account = GETPOST('fk_account', 'int');
  738. $object->fk_project = ($tmpproject > 0) ? $tmpproject : null;
  739. $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  740. $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  741. $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  742. $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
  743. $object->transport_mode_id = GETPOST('transport_mode_id', 'int');
  744. // Proprietes particulieres a facture avoir
  745. $object->fk_facture_source = $sourceinvoice > 0 ? $sourceinvoice : '';
  746. $object->type = FactureFournisseur::TYPE_CREDIT_NOTE;
  747. $id = $object->create($user);
  748. if ($id <= 0) {
  749. $error++;
  750. }
  751. if (GETPOST('invoiceAvoirWithLines', 'int') == 1 && $id > 0) {
  752. $facture_source = new FactureFournisseur($db); // fetch origin object
  753. if ($facture_source->fetch($object->fk_facture_source) > 0) {
  754. $fk_parent_line = 0;
  755. foreach ($facture_source->lines as $line) {
  756. // Reset fk_parent_line for no child products and special product
  757. if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
  758. $fk_parent_line = 0;
  759. }
  760. $line->fk_facture_fourn = $object->id;
  761. $line->fk_parent_line = $fk_parent_line;
  762. $line->subprice = -$line->subprice; // invert price for object
  763. $line->pa_ht = -$line->pa_ht;
  764. $line->total_ht = -$line->total_ht;
  765. $line->total_tva = -$line->total_tva;
  766. $line->total_ttc = -$line->total_ttc;
  767. $line->total_localtax1 = -$line->total_localtax1;
  768. $line->total_localtax2 = -$line->total_localtax2;
  769. $result = $line->insert();
  770. $object->lines[] = $line; // insert new line in current object
  771. // Defined the new fk_parent_line
  772. if ($result > 0 && $line->product_type == 9) {
  773. $fk_parent_line = $result;
  774. }
  775. }
  776. $object->update_price(1);
  777. }
  778. }
  779. if (GETPOST('invoiceAvoirWithPaymentRestAmount', 'int') == 1 && $id > 0) {
  780. $facture_source = new FactureFournisseur($db); // fetch origin object if not previously defined
  781. if ($facture_source->fetch($object->fk_facture_source) > 0) {
  782. $totalpaid = $facture_source->getSommePaiement();
  783. $totalcreditnotes = $facture_source->getSumCreditNotesUsed();
  784. $totaldeposits = $facture_source->getSumDepositsUsed();
  785. $remain_to_pay = abs($facture_source->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits);
  786. $object->addline($langs->trans('invoiceAvoirLineWithPaymentRestAmount'), $remain_to_pay, 0, 0, 0, 1, 0, 0, '', '', 'TTC');
  787. }
  788. }
  789. }
  790. } elseif ($fac_recid > 0 && (GETPOST('type') == FactureFournisseur::TYPE_STANDARD || GETPOST('type') == FactureFournisseur::TYPE_DEPOSIT)) {
  791. // Standard invoice or Deposit invoice, created from a Predefined template invoice
  792. if (empty($dateinvoice)) {
  793. $error++;
  794. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
  795. $action = 'create';
  796. } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
  797. $error++;
  798. setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
  799. $action = 'create';
  800. }
  801. if (!$error) {
  802. $object->socid = GETPOST('socid', 'int');
  803. $object->type = GETPOST('type');
  804. $object->ref = GETPOST('ref');
  805. $object->date = $dateinvoice;
  806. $object->note_public = trim(GETPOST('note_public', 'restricthtml'));
  807. $object->note_private = trim(GETPOST('note_private', 'restricthtml'));
  808. $object->ref_supplier = GETPOST('ref_supplier', 'nohtml');
  809. $object->model_pdf = GETPOST('model');
  810. $object->fk_project = GETPOST('projectid', 'int');
  811. $object->cond_reglement_id = (GETPOST('type') == 3 ? 1 : GETPOST('cond_reglement_id'));
  812. $object->mode_reglement_id = GETPOST('mode_reglement_id', 'int');
  813. $object->fk_account = GETPOST('fk_account', 'int');
  814. $object->amount = price2num(GETPOST('amount'));
  815. $object->remise_absolue = price2num(GETPOST('remise_absolue'), 'MU');
  816. $object->remise_percent = price2num(GETPOST('remise_percent'), '', 2);
  817. $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  818. $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  819. $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  820. $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
  821. // Source facture
  822. $object->fac_rec = $fac_recid;
  823. $fac_rec = new FactureFournisseurRec($db);
  824. $fac_rec->fetch($object->fac_rec);
  825. $fac_rec->fetch_lines();
  826. $object->lines = $fac_rec->lines;
  827. $id = $object->create($user); // This include recopy of links from recurring invoice and recurring invoice lines
  828. }
  829. } elseif ($fac_recid <= 0 && (GETPOST('type') == FactureFournisseur::TYPE_STANDARD || GETPOST('type') == FactureFournisseur::TYPE_DEPOSIT)) {
  830. // Standard invoice or Deposit invoice, not from a Predefined template invoice
  831. if (GETPOST('socid', 'int') < 1) {
  832. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('Supplier')), null, 'errors');
  833. $action = 'create';
  834. $error++;
  835. }
  836. if (empty($dateinvoice)) {
  837. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('DateInvoice')), null, 'errors');
  838. $action = 'create';
  839. $_GET['socid'] = $_POST['socid'];
  840. $error++;
  841. } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
  842. $error++;
  843. setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
  844. $action = 'create';
  845. }
  846. if (!GETPOST('ref_supplier')) {
  847. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('RefSupplier')), null, 'errors');
  848. $action = 'create';
  849. $_GET['socid'] = $_POST['socid'];
  850. $error++;
  851. }
  852. if (!$error) {
  853. $tmpproject = GETPOST('projectid', 'int');
  854. // Creation invoice
  855. $object->socid = GETPOST('socid', 'int');
  856. $object->type = GETPOST('type');
  857. $object->ref = GETPOST('ref', 'nohtml');
  858. $object->ref_supplier = GETPOST('ref_supplier', 'nohtml');
  859. $object->socid = GETPOST('socid', 'int');
  860. $object->libelle = GETPOST('label', 'nohtml'); // deprecated
  861. $object->label = GETPOST('label', 'nohtml');
  862. $object->date = $dateinvoice;
  863. $object->date_echeance = $datedue;
  864. $object->note_public = GETPOST('note_public', 'restricthtml');
  865. $object->note_private = GETPOST('note_private', 'restricthtml');
  866. $object->cond_reglement_id = GETPOST('cond_reglement_id');
  867. $object->mode_reglement_id = GETPOST('mode_reglement_id');
  868. $object->fk_account = GETPOST('fk_account', 'int');
  869. $object->fk_project = ($tmpproject > 0) ? $tmpproject : null;
  870. $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  871. $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  872. $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  873. $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
  874. $object->transport_mode_id = GETPOST('transport_mode_id');
  875. // Auto calculation of date due if not filled by user
  876. if (empty($object->date_echeance)) {
  877. $object->date_echeance = $object->calculate_date_lim_reglement();
  878. }
  879. $object->fetch_thirdparty();
  880. // If creation from another object of another module
  881. if (!$error && GETPOST('origin', 'alpha') && GETPOST('originid')) {
  882. // Parse element/subelement (ex: project_task)
  883. $element = $subelement = GETPOST('origin', 'alpha');
  884. /*if (preg_match('/^([^_]+)_([^_]+)/i', GETPOST('origin'),$regs))
  885. {
  886. $element = $regs[1];
  887. $subelement = $regs[2];
  888. }*/
  889. // For compatibility
  890. if ($element == 'order') {
  891. $element = $subelement = 'commande';
  892. }
  893. if ($element == 'propal') {
  894. $element = 'comm/propal'; $subelement = 'propal';
  895. }
  896. if ($element == 'contract') {
  897. $element = $subelement = 'contrat';
  898. }
  899. if ($element == 'order_supplier') {
  900. $element = 'fourn'; $subelement = 'fournisseur.commande';
  901. }
  902. if ($element == 'project') {
  903. $element = 'projet';
  904. }
  905. $object->origin = GETPOST('origin', 'alpha');
  906. $object->origin_id = GETPOST('originid', 'int');
  907. require_once DOL_DOCUMENT_ROOT.'/'.$element.'/class/'.$subelement.'.class.php';
  908. $classname = ucfirst($subelement);
  909. if ($classname == 'Fournisseur.commande') {
  910. $classname = 'CommandeFournisseur';
  911. }
  912. $objectsrc = new $classname($db);
  913. $objectsrc->fetch($originid);
  914. $objectsrc->fetch_thirdparty();
  915. if (!empty($object->origin) && !empty($object->origin_id)) {
  916. $object->linkedObjectsIds[$object->origin] = $object->origin_id;
  917. }
  918. // Add also link with order if object is reception
  919. if ($object->origin == 'reception') {
  920. $objectsrc->fetchObjectLinked();
  921. if (count($objectsrc->linkedObjectsIds['order_supplier']) > 0) {
  922. foreach ($objectsrc->linkedObjectsIds['order_supplier'] as $key => $value) {
  923. $object->linkedObjectsIds['order_supplier'] = $value;
  924. }
  925. }
  926. }
  927. $id = $object->create($user);
  928. // Add lines
  929. if ($id > 0) {
  930. require_once DOL_DOCUMENT_ROOT.'/'.$element.'/class/'.$subelement.'.class.php';
  931. $classname = ucfirst($subelement);
  932. if ($classname == 'Fournisseur.commande') {
  933. $classname = 'CommandeFournisseur';
  934. }
  935. $srcobject = new $classname($db);
  936. $result = $srcobject->fetch(GETPOST('originid', 'int'));
  937. // If deposit invoice - down payment with 1 line (fixed amount or percent)
  938. $typeamount = GETPOST('typedeposit', 'alpha');
  939. if (GETPOST('type') == FactureFournisseur::TYPE_DEPOSIT && in_array($typeamount, array('amount', 'variable'))) {
  940. $valuedeposit = price2num(GETPOST('valuedeposit', 'alpha'), 'MU');
  941. // Define the array $amountdeposit
  942. $amountdeposit = array();
  943. if (!empty($conf->global->MAIN_DEPOSIT_MULTI_TVA)) {
  944. if ($typeamount == 'amount') {
  945. $amount = $valuedeposit;
  946. } else {
  947. $amount = $srcobject->total_ttc * ($valuedeposit / 100);
  948. }
  949. $TTotalByTva = array();
  950. foreach ($srcobject->lines as &$line) {
  951. if (!empty($line->special_code)) {
  952. continue;
  953. }
  954. $TTotalByTva[$line->tva_tx] += $line->total_ttc;
  955. }
  956. foreach ($TTotalByTva as $tva => &$total) {
  957. $coef = $total / $srcobject->total_ttc; // Calc coef
  958. $am = $amount * $coef;
  959. $amount_ttc_diff += $am;
  960. $amountdeposit[$tva] += $am / (1 + $tva / 100); // Convert into HT for the addline
  961. }
  962. } else {
  963. if ($typeamount == 'amount') {
  964. $amountdeposit[0] = $valuedeposit;
  965. } elseif ($typeamount == 'variable') {
  966. if ($result > 0) {
  967. $totalamount = 0;
  968. $lines = $srcobject->lines;
  969. $numlines = count($lines);
  970. for ($i = 0; $i < $numlines; $i++) {
  971. $qualified = 1;
  972. if (empty($lines[$i]->qty)) {
  973. $qualified = 0; // We discard qty=0, it is an option
  974. }
  975. if (!empty($lines[$i]->special_code)) {
  976. $qualified = 0; // We discard special_code (frais port, ecotaxe, option, ...)
  977. }
  978. if ($qualified) {
  979. $totalamount += $lines[$i]->total_ht; // Fixme : is it not for the customer ? Shouldn't we take total_ttc ?
  980. $tva_tx = $lines[$i]->tva_tx;
  981. $amountdeposit[$tva_tx] += ($lines[$i]->total_ht * $valuedeposit) / 100;
  982. }
  983. }
  984. if ($totalamount == 0) {
  985. $amountdeposit[0] = 0;
  986. }
  987. } else {
  988. setEventMessages($srcobject->error, $srcobject->errors, 'errors');
  989. $error++;
  990. }
  991. }
  992. $amount_ttc_diff = $amountdeposit[0];
  993. }
  994. foreach ($amountdeposit as $tva => $amount) {
  995. if (empty($amount)) {
  996. continue;
  997. }
  998. $arraylist = array(
  999. 'amount' => 'FixAmount',
  1000. 'variable' => 'VarAmount'
  1001. );
  1002. $descline = '(DEPOSIT)';
  1003. //$descline.= ' - '.$langs->trans($arraylist[$typeamount]);
  1004. if ($typeamount == 'amount') {
  1005. $descline .= ' ('.price($valuedeposit, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).')';
  1006. } elseif ($typeamount == 'variable') {
  1007. $descline .= ' ('.$valuedeposit.'%)';
  1008. }
  1009. $descline .= ' - '.$srcobject->ref;
  1010. $result = $object->addline(
  1011. $descline,
  1012. $amount, // subprice
  1013. $tva, // vat rate
  1014. 0, // localtax1_tx
  1015. 0, // localtax2_tx
  1016. 1, // quantity
  1017. (empty($conf->global->INVOICE_PRODUCTID_DEPOSIT) ? 0 : $conf->global->INVOICE_PRODUCTID_DEPOSIT), // fk_product
  1018. 0, // remise_percent
  1019. 0, // date_start
  1020. 0, // date_end
  1021. 0,
  1022. $lines[$i]->info_bits, // info_bits
  1023. 'HT',
  1024. 0, // product_type
  1025. 1,
  1026. 0,
  1027. 0,
  1028. null,
  1029. $object->origin,
  1030. 0,
  1031. '',
  1032. $lines[$i]->special_code,
  1033. 0,
  1034. 0
  1035. //,$langs->trans('Deposit') //Deprecated
  1036. );
  1037. }
  1038. $diff = $object->total_ttc - $amount_ttc_diff;
  1039. if (!empty($conf->global->MAIN_DEPOSIT_MULTI_TVA) && $diff != 0) {
  1040. $object->fetch_lines();
  1041. $subprice_diff = $object->lines[0]->subprice - $diff / (1 + $object->lines[0]->tva_tx / 100);
  1042. $object->updateline($object->lines[0]->id, $object->lines[0]->desc, $subprice_diff, $object->lines[0]->qty, $object->lines[0]->remise_percent, $object->lines[0]->date_start, $object->lines[0]->date_end, $object->lines[0]->tva_tx, 0, 0, 'HT', $object->lines[0]->info_bits, $object->lines[0]->product_type, 0, 0, 0, $object->lines[0]->pa_ht, $object->lines[0]->label, 0, array(), 100);
  1043. }
  1044. } elseif ($result > 0) {
  1045. $lines = $srcobject->lines;
  1046. if (empty($lines) && method_exists($srcobject, 'fetch_lines')) {
  1047. $srcobject->fetch_lines();
  1048. $lines = $srcobject->lines;
  1049. }
  1050. $num = count($lines);
  1051. for ($i = 0; $i < $num; $i++) { // TODO handle subprice < 0
  1052. if (!in_array($lines[$i]->id, $selectedLines)) {
  1053. continue; // Skip unselected lines
  1054. }
  1055. $desc = ($lines[$i]->desc ? $lines[$i]->desc : $lines[$i]->libelle);
  1056. $product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0);
  1057. // Extrafields
  1058. if (method_exists($lines[$i], 'fetch_optionals')) {
  1059. $lines[$i]->fetch_optionals();
  1060. }
  1061. // Dates
  1062. // TODO mutualiser
  1063. $date_start = $lines[$i]->date_debut_prevue;
  1064. if ($lines[$i]->date_debut_reel) {
  1065. $date_start = $lines[$i]->date_debut_reel;
  1066. }
  1067. if ($lines[$i]->date_start) {
  1068. $date_start = $lines[$i]->date_start;
  1069. }
  1070. $date_end = $lines[$i]->date_fin_prevue;
  1071. if ($lines[$i]->date_fin_reel) {
  1072. $date_end = $lines[$i]->date_fin_reel;
  1073. }
  1074. if ($lines[$i]->date_end) {
  1075. $date_end = $lines[$i]->date_end;
  1076. }
  1077. // FIXME Missing special_code into addline and updateline methods
  1078. $object->special_code = $lines[$i]->special_code;
  1079. // FIXME If currency different from main currency, take multicurrency price
  1080. if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) {
  1081. $pu = 0;
  1082. $pu_currency = $lines[$i]->multicurrency_subprice;
  1083. } else {
  1084. $pu = $lines[$i]->subprice;
  1085. $pu_currency = 0;
  1086. }
  1087. // FIXME Missing $lines[$i]->ref_supplier and $lines[$i]->label into addline and updateline methods. They are filled when coming from order for example.
  1088. $result = $object->addline(
  1089. $desc,
  1090. $pu,
  1091. $lines[$i]->tva_tx,
  1092. $lines[$i]->localtax1_tx,
  1093. $lines[$i]->localtax2_tx,
  1094. $lines[$i]->qty,
  1095. $lines[$i]->fk_product,
  1096. $lines[$i]->remise_percent,
  1097. $date_start,
  1098. $date_end,
  1099. 0,
  1100. $lines[$i]->info_bits,
  1101. 'HT',
  1102. $product_type,
  1103. $lines[$i]->rang,
  1104. 0,
  1105. $lines[$i]->array_options,
  1106. $lines[$i]->fk_unit,
  1107. $lines[$i]->id,
  1108. $pu_currency,
  1109. $lines[$i]->ref_supplier,
  1110. $lines[$i]->special_code
  1111. );
  1112. if ($result < 0) {
  1113. $error++;
  1114. break;
  1115. }
  1116. }
  1117. // Now reload line
  1118. $object->fetch_lines();
  1119. } else {
  1120. $error++;
  1121. }
  1122. } else {
  1123. $error++;
  1124. }
  1125. } elseif (!$error) {
  1126. $id = $object->create($user);
  1127. if ($id < 0) {
  1128. $error++;
  1129. }
  1130. }
  1131. }
  1132. }
  1133. if ($error) {
  1134. $langs->load("errors");
  1135. $db->rollback();
  1136. setEventMessages($object->error, $object->errors, 'errors');
  1137. $action = 'create';
  1138. $_GET['socid'] = $_POST['socid'];
  1139. } else {
  1140. $db->commit();
  1141. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  1142. $outputlangs = $langs;
  1143. $result = $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  1144. if ($result < 0) {
  1145. dol_print_error($db, $object->error, $object->errors);
  1146. exit;
  1147. }
  1148. }
  1149. header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
  1150. exit;
  1151. }
  1152. } elseif ($action == 'updateline' && $usercancreate) {
  1153. // Edit line
  1154. $db->begin();
  1155. if (! $object->fetch($id) > 0) dol_print_error($db);
  1156. $object->fetch_thirdparty();
  1157. $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0);
  1158. if (GETPOST('price_ht') != '' || GETPOST('multicurrency_subprice') != '') {
  1159. $up = price2num(GETPOST('price_ht'), '', 2);
  1160. $price_base_type = 'HT';
  1161. } else {
  1162. $up = price2num(GETPOST('price_ttc'), '', 2);
  1163. $price_base_type = 'TTC';
  1164. }
  1165. if (GETPOST('productid') > 0) {
  1166. $productsupplier = new ProductFournisseur($db);
  1167. if (!empty($conf->global->SUPPLIER_INVOICE_WITH_PREDEFINED_PRICES_ONLY)) {
  1168. if (GETPOST('productid') > 0 && $productsupplier->get_buyprice(0, price2num(GETPOST('qty')), GETPOST('productid', 'int'), 'restricthtml', GETPOST('socid', 'int')) < 0) {
  1169. setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'warnings');
  1170. }
  1171. }
  1172. $prod = new Product($db);
  1173. $prod->fetch(GETPOST('productid'));
  1174. $label = $prod->description;
  1175. if (trim(GETPOST('product_desc', 'restricthtml')) != trim($label)) {
  1176. $label = GETPOST('product_desc', 'restricthtml');
  1177. }
  1178. $type = $prod->type;
  1179. } else {
  1180. $label = GETPOST('product_desc', 'restricthtml');
  1181. $type = GETPOST("type") ? GETPOST("type") : 0;
  1182. }
  1183. $date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear'));
  1184. $date_end = dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear'));
  1185. // Define info_bits
  1186. $info_bits = 0;
  1187. if (preg_match('/\*/', $tva_tx)) {
  1188. $info_bits |= 0x01;
  1189. }
  1190. // Define vat_rate
  1191. $tva_tx = str_replace('*', '', $tva_tx);
  1192. $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $object->thirdparty);
  1193. $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $object->thirdparty);
  1194. $remise_percent = price2num(GETPOST('remise_percent'), '', 2);
  1195. $pu_devise = price2num(GETPOST('multicurrency_subprice'), 'MU', 2);
  1196. // Extrafields Lines
  1197. $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
  1198. $array_options = $extrafields->getOptionalsFromPost($object->table_element_line);
  1199. // Unset extrafield POST Data
  1200. if (is_array($extralabelsline)) {
  1201. foreach ($extralabelsline as $key => $value) {
  1202. unset($_POST["options_".$key]);
  1203. }
  1204. }
  1205. $result = $object->updateline(GETPOST('lineid', 'int'), $label, $up, $tva_tx, $localtax1_tx, $localtax2_tx, price2num(GETPOST('qty'), 'MS'), GETPOST('productid', 'int'), $price_base_type, $info_bits, $type, $remise_percent, 0, $date_start, $date_end, $array_options, GETPOST('units'), $pu_devise, GETPOST('fourn_ref', 'alpha'));
  1206. if ($result >= 0) {
  1207. unset($_POST['label']);
  1208. unset($_POST['fourn_ref']);
  1209. unset($_POST['date_starthour']);
  1210. unset($_POST['date_startmin']);
  1211. unset($_POST['date_startsec']);
  1212. unset($_POST['date_startday']);
  1213. unset($_POST['date_startmonth']);
  1214. unset($_POST['date_startyear']);
  1215. unset($_POST['date_endhour']);
  1216. unset($_POST['date_endmin']);
  1217. unset($_POST['date_endsec']);
  1218. unset($_POST['date_endday']);
  1219. unset($_POST['date_endmonth']);
  1220. unset($_POST['date_endyear']);
  1221. unset($_POST['price_ttc']);
  1222. unset($_POST['price_ht']);
  1223. $db->commit();
  1224. } else {
  1225. $db->rollback();
  1226. setEventMessages($object->error, $object->errors, 'errors');
  1227. }
  1228. } elseif ($action == 'addline' && $usercancreate) {
  1229. // Add a product line
  1230. $db->begin();
  1231. $ret = $object->fetch($id);
  1232. if ($ret < 0) {
  1233. dol_print_error($db, $object->error);
  1234. exit;
  1235. }
  1236. $ret = $object->fetch_thirdparty();
  1237. $langs->load('errors');
  1238. $error = 0;
  1239. // Set if we used free entry or predefined product
  1240. $predef = '';
  1241. $product_desc = (GETPOSTISSET('dp_desc') ? GETPOST('dp_desc', 'restricthtml') : '');
  1242. $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'));
  1243. $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'));
  1244. $prod_entry_mode = GETPOST('prod_entry_mode');
  1245. if ($prod_entry_mode == 'free') {
  1246. $idprod = 0;
  1247. } else {
  1248. $idprod = GETPOST('idprod', 'int');
  1249. }
  1250. $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); // Can be '1.2' or '1.2 (CODE)'
  1251. $price_ht = price2num(GETPOST('price_ht'), 'MU', 2);
  1252. $price_ht_devise = price2num(GETPOST('multicurrency_price_ht'), 'CU', 2);
  1253. $price_ttc = price2num(GETPOST('price_ttc'), 'MU', 2);
  1254. $price_ttc_devise = price2num(GETPOST('multicurrency_price_ttc'), 'CU', 2);
  1255. $qty = price2num(GETPOST('qty'.$predef, 'alpha'), 'MS');
  1256. $remise_percent = (GETPOSTISSET('remise_percent'.$predef) ? price2num(GETPOST('remise_percent'.$predef, 'alpha'), '', 2) : 0);
  1257. if (empty($remise_percent)) {
  1258. $remise_percent = 0;
  1259. }
  1260. // Extrafields
  1261. $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
  1262. $array_options = $extrafields->getOptionalsFromPost($object->table_element_line, $predef);
  1263. // Unset extrafield
  1264. if (is_array($extralabelsline)) {
  1265. // Get extra fields
  1266. foreach ($extralabelsline as $key => $value) {
  1267. unset($_POST["options_".$key]);
  1268. }
  1269. }
  1270. if ($prod_entry_mode == 'free' && GETPOST('price_ht') < 0 && $qty < 0) {
  1271. setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPrice'), $langs->transnoentitiesnoconv('Qty')), null, 'errors');
  1272. $error++;
  1273. }
  1274. if ($prod_entry_mode == 'free' && !GETPOST('idprodfournprice') && GETPOST('type') < 0) {
  1275. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors');
  1276. $error++;
  1277. }
  1278. if ($prod_entry_mode == 'free' && GETPOST('price_ht') === '' && GETPOST('price_ttc') === '' && $price_ht_devise === '') { // Unit price can be 0 but not ''
  1279. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('UnitPrice')), null, 'errors');
  1280. $error++;
  1281. }
  1282. if ($prod_entry_mode == 'free' && !GETPOST('dp_desc')) {
  1283. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors');
  1284. $error++;
  1285. }
  1286. if (!GETPOST('qty', 'alpha')) { // 0 is NOT allowed for invoices
  1287. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors');
  1288. $error++;
  1289. }
  1290. if (!$error && !empty($conf->variants->enabled) && $prod_entry_mode != 'free') {
  1291. if ($combinations = GETPOST('combinations', 'array')) {
  1292. //Check if there is a product with the given combination
  1293. $prodcomb = new ProductCombination($db);
  1294. if ($res = $prodcomb->fetchByProductCombination2ValuePairs($idprod, $combinations)) {
  1295. $idprod = $res->fk_product_child;
  1296. } else {
  1297. setEventMessages($langs->trans('ErrorProductCombinationNotFound'), null, 'errors');
  1298. $error++;
  1299. }
  1300. }
  1301. }
  1302. if ($prod_entry_mode != 'free' && empty($error)) { // With combolist mode idprodfournprice is > 0 or -1. With autocomplete, idprodfournprice is > 0 or ''
  1303. $productsupplier = new ProductFournisseur($db);
  1304. $idprod = 0;
  1305. if (GETPOST('idprodfournprice', 'alpha') == -1 || GETPOST('idprodfournprice', 'alpha') == '') {
  1306. $idprod = -99; // Same behaviour than with combolist. When not select idprodfournprice is now -99 (to avoid conflict with next action that may return -1, -2, ...)
  1307. }
  1308. $reg = array();
  1309. if (preg_match('/^idprod_([0-9]+)$/', GETPOST('idprodfournprice', 'alpha'), $reg)) {
  1310. $idprod = $reg[1];
  1311. $res = $productsupplier->fetch($idprod); // Load product from its id
  1312. // Call to init some price properties of $productsupplier
  1313. // So if a supplier price already exists for another thirdparty (first one found), we use it as reference price
  1314. if (!empty($conf->global->SUPPLIER_TAKE_FIRST_PRICE_IF_NO_PRICE_FOR_CURRENT_SUPPLIER)) {
  1315. $fksoctosearch = 0;
  1316. $productsupplier->get_buyprice(0, -1, $idprod, 'none', $fksoctosearch); // We force qty to -1 to be sure to find if a supplier price exist
  1317. if ($productsupplier->fourn_socid != $socid) { // The price we found is for another supplier, so we clear supplier price
  1318. $productsupplier->ref_supplier = '';
  1319. }
  1320. } else {
  1321. $fksoctosearch = $object->thirdparty->id;
  1322. $productsupplier->get_buyprice(0, -1, $idprod, 'none', $fksoctosearch); // We force qty to -1 to be sure to find if a supplier price exist
  1323. }
  1324. } elseif (GETPOST('idprodfournprice', 'alpha') > 0) {
  1325. $qtytosearch = $qty; // Just to see if a price exists for the quantity. Not used to found vat.
  1326. //$qtytosearch=-1; // We force qty to -1 to be sure to find if a supplier price exist
  1327. $idprod = $productsupplier->get_buyprice(GETPOST('idprodfournprice', 'alpha'), $qtytosearch);
  1328. $res = $productsupplier->fetch($idprod);
  1329. }
  1330. if ($idprod > 0) {
  1331. $label = $productsupplier->label;
  1332. // Define output language
  1333. if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
  1334. $outputlangs = $langs;
  1335. $newlang = '';
  1336. if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  1337. $newlang = GETPOST('lang_id', 'aZ09');
  1338. }
  1339. if (empty($newlang)) {
  1340. $newlang = $object->thirdparty->default_lang;
  1341. }
  1342. if (!empty($newlang)) {
  1343. $outputlangs = new Translate("", $conf);
  1344. $outputlangs->setDefaultLang($newlang);
  1345. }
  1346. $desc = (!empty($productsupplier->multilangs[$outputlangs->defaultlang]["description"])) ? $productsupplier->multilangs[$outputlangs->defaultlang]["description"] : $productsupplier->description;
  1347. } else {
  1348. $desc = $productsupplier->description;
  1349. }
  1350. // if we use supplier description of the products
  1351. if (!empty($productsupplier->desc_supplier) && !empty($conf->global->PRODUIT_FOURN_TEXTS)) {
  1352. $desc = $productsupplier->desc_supplier;
  1353. }
  1354. //If text set in desc is the same as product descpription (as now it's preloaded) whe add it only one time
  1355. if (trim($product_desc) == trim($desc) && !empty($conf->global->PRODUIT_AUTOFILL_DESC)) {
  1356. $product_desc = '';
  1357. }
  1358. if (!empty($product_desc) && !empty($conf->global->MAIN_NO_CONCAT_DESCRIPTION)) {
  1359. $desc = $product_desc;
  1360. }
  1361. if (!empty($product_desc) && trim($product_desc) != trim($desc)) {
  1362. $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION));
  1363. }
  1364. $ref_supplier = $productsupplier->ref_supplier;
  1365. // Get vat rate
  1366. if (!GETPOSTISSET('tva_tx')) { // If vat rate not provided from the form (the form has the priority)
  1367. $tva_tx = get_default_tva($object->thirdparty, $mysoc, $productsupplier->id, GETPOST('idprodfournprice', 'alpha'));
  1368. $tva_npr = get_default_npr($object->thirdparty, $mysoc, $productsupplier->id, GETPOST('idprodfournprice', 'alpha'));
  1369. }
  1370. if (empty($tva_tx)) {
  1371. $tva_npr = 0;
  1372. }
  1373. $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $object->thirdparty, $tva_npr);
  1374. $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $object->thirdparty, $tva_npr);
  1375. $type = $productsupplier->type;
  1376. if (GETPOST('price_ht') != '' || GETPOST('price_ht_devise') != '') {
  1377. $price_base_type = 'HT';
  1378. $pu = price2num($price_ht, 'MU');
  1379. $pu_devise = price2num($price_ht_devise, 'CU');
  1380. } elseif (GETPOST('price_ttc') != '' || GETPOST('price_ttc_devise') != '') {
  1381. $price_base_type = 'TTC';
  1382. $pu = price2num($price_ttc, 'MU');
  1383. $pu_devise = price2num($price_ttc_devise, 'CU');
  1384. } else {
  1385. $price_base_type = ($productsupplier->fourn_price_base_type ? $productsupplier->fourn_price_base_type : 'HT');
  1386. if (empty($object->multicurrency_code) || ($productsupplier->fourn_multicurrency_code != $object->multicurrency_code)) { // If object is in a different currency and price not in this currency
  1387. $pu = $productsupplier->fourn_pu;
  1388. $pu_devise = 0;
  1389. } else {
  1390. $pu = $productsupplier->fourn_pu;
  1391. $pu_devise = $productsupplier->fourn_multicurrency_unitprice;
  1392. }
  1393. }
  1394. if (empty($pu)) {
  1395. $pu = 0; // If pu is '' or null, we force to have a numeric value
  1396. }
  1397. $result = $object->addline(
  1398. $desc,
  1399. $pu,
  1400. $tva_tx,
  1401. $localtax1_tx,
  1402. $localtax2_tx,
  1403. $qty,
  1404. $idprod,
  1405. $remise_percent,
  1406. $date_start,
  1407. $date_end,
  1408. 0,
  1409. $tva_npr,
  1410. $price_base_type,
  1411. $type,
  1412. min($rank, count($object->lines) + 1),
  1413. 0,
  1414. $array_options,
  1415. $productsupplier->fk_unit,
  1416. 0,
  1417. $pu_devise,
  1418. $ref_supplier,
  1419. ''
  1420. );
  1421. }
  1422. if ($idprod == -99 || $idprod == 0) {
  1423. // Product not selected
  1424. $error++;
  1425. $langs->load("errors");
  1426. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ProductOrService")), null, 'errors');
  1427. }
  1428. if ($idprod == -1) {
  1429. // Quantity too low
  1430. $error++;
  1431. $langs->load("errors");
  1432. setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'errors');
  1433. }
  1434. } elseif (empty($error)) { // $price_ht is already set
  1435. $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0);
  1436. $tva_tx = str_replace('*', '', $tva_tx);
  1437. $label = (GETPOST('product_label') ? GETPOST('product_label') : '');
  1438. $desc = $product_desc;
  1439. $type = GETPOST('type');
  1440. $ref_supplier = GETPOST('fourn_ref', 'alpha');
  1441. $fk_unit = GETPOST('units', 'alpha');
  1442. if (!preg_match('/\((.*)\)/', $tva_tx)) {
  1443. $tva_tx = price2num($tva_tx); // $txtva can have format '5,1' or '5.1' or '5.1(XXX)', we must clean only if '5,1'
  1444. }
  1445. // Local Taxes
  1446. $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $object->thirdparty);
  1447. $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $object->thirdparty);
  1448. if (GETPOST('price_ht') != '' || GETPOST('price_ht_devise') != '') {
  1449. $pu_ht = price2num($price_ht, 'MU'); // $pu_ht must be rounded according to settings
  1450. } else {
  1451. $pu_ttc = price2num(GETPOST('price_ttc'), 'MU');
  1452. $pu_ht = price2num($pu_ttc / (1 + ($tva_tx / 100)), 'MU'); // $pu_ht must be rounded according to settings
  1453. }
  1454. $price_base_type = 'HT';
  1455. $pu_devise = price2num($price_devise, 'CU');
  1456. $result = $object->addline($product_desc, $pu_ht, $tva_tx, $localtax1_tx, $localtax2_tx, $qty, 0, $remise_percent, $date_start, $date_end, 0, $tva_npr, $price_base_type, $type, -1, 0, $array_options, $fk_unit, 0, $pu_devise, $ref_supplier);
  1457. }
  1458. //print "xx".$tva_tx; exit;
  1459. if (!$error && $result > 0) {
  1460. $db->commit();
  1461. // Define output language
  1462. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  1463. $outputlangs = $langs;
  1464. $newlang = '';
  1465. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  1466. $newlang = GETPOST('lang_id', 'aZ09');
  1467. }
  1468. if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
  1469. $newlang = $object->thirdparty->default_lang;
  1470. }
  1471. if (!empty($newlang)) {
  1472. $outputlangs = new Translate("", $conf);
  1473. $outputlangs->setDefaultLang($newlang);
  1474. }
  1475. $model = $object->model_pdf;
  1476. $ret = $object->fetch($id); // Reload to get new records
  1477. $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  1478. if ($result < 0) {
  1479. dol_print_error($db, $result);
  1480. }
  1481. }
  1482. unset($_POST ['prod_entry_mode']);
  1483. unset($_POST['qty']);
  1484. unset($_POST['type']);
  1485. unset($_POST['remise_percent']);
  1486. unset($_POST['pu']);
  1487. unset($_POST['price_ht']);
  1488. unset($_POST['multicurrency_price_ht']);
  1489. unset($_POST['price_ttc']);
  1490. unset($_POST['fourn_ref']);
  1491. unset($_POST['tva_tx']);
  1492. unset($_POST['label']);
  1493. unset($localtax1_tx);
  1494. unset($localtax2_tx);
  1495. unset($_POST['np_marginRate']);
  1496. unset($_POST['np_markRate']);
  1497. unset($_POST['dp_desc']);
  1498. unset($_POST['idprodfournprice']);
  1499. unset($_POST['units']);
  1500. unset($_POST['date_starthour']);
  1501. unset($_POST['date_startmin']);
  1502. unset($_POST['date_startsec']);
  1503. unset($_POST['date_startday']);
  1504. unset($_POST['date_startmonth']);
  1505. unset($_POST['date_startyear']);
  1506. unset($_POST['date_endhour']);
  1507. unset($_POST['date_endmin']);
  1508. unset($_POST['date_endsec']);
  1509. unset($_POST['date_endday']);
  1510. unset($_POST['date_endmonth']);
  1511. unset($_POST['date_endyear']);
  1512. } else {
  1513. $db->rollback();
  1514. setEventMessages($object->error, $object->errors, 'errors');
  1515. }
  1516. $action = '';
  1517. } elseif ($action == 'classin' && $usercancreate) {
  1518. $object->fetch($id);
  1519. $result = $object->setProject($projectid);
  1520. } elseif ($action == 'confirm_edit' && $confirm == 'yes' && $usercancreate) {
  1521. // Set invoice to draft status
  1522. $object->fetch($id);
  1523. $totalpaid = $object->getSommePaiement();
  1524. $resteapayer = $object->total_ttc - $totalpaid;
  1525. // We check that lines of invoices are exported in accountancy
  1526. $ventilExportCompta = $object->getVentilExportCompta();
  1527. if (!$ventilExportCompta) {
  1528. // On verifie si aucun paiement n'a ete effectue
  1529. if ($resteapayer == price2num($object->total_ttc, 'MT', 1) && $object->statut == FactureFournisseur::STATUS_VALIDATED) {
  1530. $idwarehouse = GETPOST('idwarehouse');
  1531. $object->fetch_thirdparty();
  1532. $qualified_for_stock_change = 0;
  1533. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  1534. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  1535. } else {
  1536. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  1537. }
  1538. // Check parameters
  1539. if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) {
  1540. $langs->load("stocks");
  1541. if (!$idwarehouse || $idwarehouse == -1) {
  1542. $error++;
  1543. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
  1544. $action = '';
  1545. }
  1546. }
  1547. $object->setDraft($user, $idwarehouse);
  1548. // Define output language
  1549. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  1550. $outputlangs = $langs;
  1551. $newlang = '';
  1552. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  1553. $newlang = GETPOST('lang_id', 'aZ09');
  1554. }
  1555. if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
  1556. $newlang = $object->thirdparty->default_lang;
  1557. }
  1558. if (!empty($newlang)) {
  1559. $outputlangs = new Translate("", $conf);
  1560. $outputlangs->setDefaultLang($newlang);
  1561. }
  1562. $model = $object->model_pdf;
  1563. $ret = $object->fetch($id); // Reload to get new records
  1564. $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  1565. if ($result < 0) {
  1566. dol_print_error($db, $result);
  1567. }
  1568. }
  1569. $action = '';
  1570. }
  1571. }
  1572. } elseif ($action == 'reopen' && $usercancreate) {
  1573. // Set invoice to validated/unpaid status
  1574. $result = $object->fetch($id);
  1575. if ($object->statut == FactureFournisseur::STATUS_CLOSED
  1576. || ($object->statut == FactureFournisseur::STATUS_ABANDONED && $object->close_code != 'replaced')) {
  1577. $result = $object->setUnpaid($user);
  1578. if ($result > 0) {
  1579. header('Location: '.$_SERVER["PHP_SELF"].'?id='.$id);
  1580. exit;
  1581. } else {
  1582. setEventMessages($object->error, $object->errors, 'errors');
  1583. }
  1584. }
  1585. }
  1586. // Actions when printing a doc from card
  1587. include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
  1588. // Actions to send emails
  1589. $triggersendname = 'BILL_SUPPLIER_SENTBYMAIL';
  1590. $paramname = 'id';
  1591. $autocopy = 'MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO';
  1592. $trackid = 'sinv'.$object->id;
  1593. include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
  1594. // Actions to build doc
  1595. $upload_dir = $conf->fournisseur->facture->dir_output;
  1596. $permissiontoadd = $usercancreate;
  1597. include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
  1598. // Make calculation according to calculationrule
  1599. if ($action == 'calculate') {
  1600. $calculationrule = GETPOST('calculationrule');
  1601. $object->fetch($id);
  1602. $object->fetch_thirdparty();
  1603. $result = $object->update_price(0, (($calculationrule == 'totalofround') ? '0' : '1'), 0, $object->thirdparty);
  1604. if ($result <= 0) {
  1605. dol_print_error($db, $result);
  1606. exit;
  1607. }
  1608. }
  1609. if ($action == 'update_extras') {
  1610. $object->oldcopy = dol_clone($object);
  1611. // Fill array 'array_options' with data from add form
  1612. $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml'));
  1613. if ($ret < 0) {
  1614. $error++;
  1615. }
  1616. if (!$error) {
  1617. // Actions on extra fields
  1618. if (!$error) {
  1619. $result = $object->insertExtraFields('BILL_SUPPLIER_MODIFY');
  1620. if ($result < 0) {
  1621. $error++;
  1622. }
  1623. }
  1624. }
  1625. if ($error) {
  1626. $action = 'edit_extras';
  1627. }
  1628. }
  1629. if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $usercancreate) {
  1630. if ($action == 'addcontact') {
  1631. $result = $object->fetch($id);
  1632. if ($result > 0 && $id > 0) {
  1633. $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid'));
  1634. $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type'));
  1635. $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09'));
  1636. }
  1637. if ($result >= 0) {
  1638. header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
  1639. exit;
  1640. } else {
  1641. if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1642. $langs->load("errors");
  1643. setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors');
  1644. } else {
  1645. setEventMessages($object->error, $object->errors, 'errors');
  1646. }
  1647. }
  1648. } elseif ($action == 'swapstatut') {
  1649. // bascule du statut d'un contact
  1650. if ($object->fetch($id)) {
  1651. $result = $object->swapContactStatus(GETPOST('ligne', 'int'));
  1652. } else {
  1653. dol_print_error($db);
  1654. }
  1655. } elseif ($action == 'deletecontact') {
  1656. // Efface un contact
  1657. $object->fetch($id);
  1658. $result = $object->delete_contact(GETPOST("lineid", 'int'));
  1659. if ($result >= 0) {
  1660. header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
  1661. exit;
  1662. } else {
  1663. dol_print_error($db);
  1664. }
  1665. }
  1666. }
  1667. }
  1668. /*
  1669. * View
  1670. */
  1671. $form = new Form($db);
  1672. $formfile = new FormFile($db);
  1673. $bankaccountstatic = new Account($db);
  1674. $paymentstatic = new PaiementFourn($db);
  1675. if (!empty($conf->projet->enabled)) {
  1676. $formproject = new FormProjets($db);
  1677. }
  1678. $now = dol_now();
  1679. $title = $langs->trans('SupplierInvoice')." - ".$langs->trans('Card');
  1680. $help_url = 'EN:Module_Suppliers_Invoices|FR:Module_Fournisseurs_Factures|ES:Módulo_Facturas_de_proveedores|DE:Modul_Lieferantenrechnungen';
  1681. llxHeader('', $title, $help_url);
  1682. // Mode creation
  1683. if ($action == 'create') {
  1684. $facturestatic = new FactureFournisseur($db);
  1685. print load_fiche_titre($langs->trans('NewBill'), '', 'supplier_invoice');
  1686. dol_htmloutput_events();
  1687. $currency_code = $conf->currency;
  1688. $societe = '';
  1689. if (GETPOST('socid', 'int') > 0) {
  1690. $societe = new Societe($db);
  1691. $societe->fetch(GETPOST('socid', 'int'));
  1692. if (!empty($conf->multicurrency->enabled) && !empty($societe->multicurrency_code)) {
  1693. $currency_code = $societe->multicurrency_code;
  1694. }
  1695. }
  1696. if (!empty($origin) && !empty($originid)) {
  1697. // Parse element/subelement (ex: project_task)
  1698. $element = $subelement = $origin;
  1699. if ($element == 'project') {
  1700. $projectid = $originid;
  1701. $element = 'projet';
  1702. }
  1703. // For compatibility
  1704. if ($element == 'order') {
  1705. $element = $subelement = 'commande';
  1706. }
  1707. if ($element == 'propal') {
  1708. $element = 'comm/propal'; $subelement = 'propal';
  1709. }
  1710. if ($element == 'contract') {
  1711. $element = $subelement = 'contrat';
  1712. }
  1713. if ($element == 'order_supplier') {
  1714. $element = 'fourn'; $subelement = 'fournisseur.commande';
  1715. }
  1716. require_once DOL_DOCUMENT_ROOT.'/'.$element.'/class/'.$subelement.'.class.php';
  1717. $classname = ucfirst($subelement);
  1718. if ($classname == 'Fournisseur.commande') {
  1719. $classname = 'CommandeFournisseur';
  1720. }
  1721. $objectsrc = new $classname($db);
  1722. $objectsrc->fetch($originid);
  1723. $objectsrc->fetch_thirdparty();
  1724. $projectid = (!empty($objectsrc->fk_project) ? $objectsrc->fk_project : '');
  1725. //$ref_client = (!empty($objectsrc->ref_client)?$object->ref_client:'');
  1726. $soc = $objectsrc->thirdparty;
  1727. $cond_reglement_id = (!empty($objectsrc->cond_reglement_id) ? $objectsrc->cond_reglement_id : (!empty($soc->cond_reglement_supplier_id) ? $soc->cond_reglement_supplier_id : 0)); // TODO maybe add default value option
  1728. $mode_reglement_id = (!empty($objectsrc->mode_reglement_id) ? $objectsrc->mode_reglement_id : (!empty($soc->mode_reglement_supplier_id) ? $soc->mode_reglement_supplier_id : 0));
  1729. $fk_account = (!empty($objectsrc->fk_account) ? $objectsrc->fk_account : (!empty($soc->fk_account) ? $soc->fk_account : 0));
  1730. $remise_percent = (!empty($objectsrc->remise_percent) ? $objectsrc->remise_percent : (!empty($soc->remise_supplier_percent) ? $soc->remise_supplier_percent : 0));
  1731. $remise_absolue = (!empty($objectsrc->remise_absolue) ? $objectsrc->remise_absolue : (!empty($soc->remise_absolue) ? $soc->remise_absolue : 0));
  1732. $dateinvoice = empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : '';
  1733. $transport_mode_id = (!empty($objectsrc->transport_mode_id) ? $objectsrc->transport_mode_id : (!empty($soc->transport_mode_id) ? $soc->transport_mode_id : 0));
  1734. if (!empty($conf->multicurrency->enabled)) {
  1735. if (!empty($objectsrc->multicurrency_code)) {
  1736. $currency_code = $objectsrc->multicurrency_code;
  1737. }
  1738. if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($objectsrc->multicurrency_tx)) {
  1739. $currency_tx = $objectsrc->multicurrency_tx;
  1740. }
  1741. }
  1742. $datetmp = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int'));
  1743. $dateinvoice = ($datetmp == '' ? (empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : '') : $datetmp);
  1744. $datetmp = dol_mktime(12, 0, 0, GETPOST('echmonth', 'int'), GETPOST('echday', 'int'), GETPOST('echyear', 'int'));
  1745. $datedue = ($datetmp == '' ?-1 : $datetmp);
  1746. // Replicate extrafields
  1747. $objectsrc->fetch_optionals();
  1748. $object->array_options = $objectsrc->array_options;
  1749. } else {
  1750. $cond_reglement_id = !empty($societe->cond_reglement_supplier_id) ? $societe->cond_reglement_supplier_id : 0;
  1751. $mode_reglement_id = !empty($societe->mode_reglement_supplier_id) ? $societe->mode_reglement_supplier_id : 0;
  1752. $transport_mode_id = !empty($societe->transport_mode_supplier_id) ? $societe->transport_mode_supplier_id : 0;
  1753. $fk_account = !empty($societe->fk_account) ? $societe->fk_account : 0;
  1754. $datetmp = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int'));
  1755. $dateinvoice = ($datetmp == '' ? (empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : '') : $datetmp);
  1756. $datetmp = dol_mktime(12, 0, 0, GETPOST('echmonth', 'int'), GETPOST('echday', 'int'), GETPOST('echyear', 'int'));
  1757. $datedue = ($datetmp == '' ?-1 : $datetmp);
  1758. if (!empty($conf->multicurrency->enabled) && !empty($soc->multicurrency_code)) {
  1759. $currency_code = $soc->multicurrency_code;
  1760. }
  1761. }
  1762. // when payment condition is empty (means not override by payment condition form a other object, like third-party), try to use default value
  1763. if (empty($cond_reglement_id)) {
  1764. $cond_reglement_id = GETPOST("cond_reglement_id");
  1765. }
  1766. // when payment mode is empty (means not override by payment condition form a other object, like third-party), try to use default value
  1767. if (empty($mode_reglement_id)) {
  1768. $mode_reglement_id = GETPOST("mode_reglement_id");
  1769. }
  1770. $note_public = $object->getDefaultCreateValueFor('note_public', ((!empty($origin) && !empty($originid) && is_object($objectsrc) && !empty($conf->global->FACTUREFOURN_REUSE_NOTES_ON_CREATE_FROM)) ? $objectsrc->note_public : null));
  1771. $note_private = $object->getDefaultCreateValueFor('note_private', ((!empty($origin) && !empty($originid) && is_object($objectsrc) && !empty($conf->global->FACTUREFOURN_REUSE_NOTES_ON_CREATE_FROM)) ? $objectsrc->note_private : null));
  1772. print '<form name="add" action="'.$_SERVER["PHP_SELF"].'" method="post">';
  1773. print '<input type="hidden" name="token" value="'.newToken().'">';
  1774. print '<input type="hidden" name="action" value="add">';
  1775. if (!empty($societe->id) && $societe->id > 0) {
  1776. print '<input type="hidden" name="socid" value="'.$societe->id.'">'."\n";
  1777. }
  1778. print '<input type="hidden" name="origin" value="'.$origin.'">';
  1779. print '<input type="hidden" name="originid" value="'.$originid.'">';
  1780. if (!empty($currency_tx)) {
  1781. print '<input type="hidden" name="originmulticurrency_tx" value="'.$currency_tx.'">';
  1782. }
  1783. print dol_get_fiche_head();
  1784. print '<table class="border centpercent">';
  1785. // Ref
  1786. print '<tr><td class="titlefieldcreate">'.$langs->trans('Ref').'</td><td>'.$langs->trans('Draft').'</td></tr>';
  1787. $exampletemplateinvoice = new FactureFournisseurRec($db);
  1788. $invoice_predefined = new FactureFournisseurRec($db);
  1789. if (empty($origin) && empty($originid) && $fac_recid > 0) {
  1790. $invoice_predefined->fetch($fac_recid);
  1791. }
  1792. // Third party
  1793. print '<tr><td class="fieldrequired">'.$langs->trans('Supplier').'</td>';
  1794. print '<td>';
  1795. if (!empty($societe->id) && $societe->id > 0 && ($fac_recid <= 0 || !empty($invoice_predefined->frequency))) {
  1796. $absolute_discount = $societe->getAvailableDiscounts('', '', 0, 1);
  1797. print $societe->getNomUrl(1, 'supplier');
  1798. print '<input type="hidden" name="socid" value="'.$societe->id.'">';
  1799. } else {
  1800. print img_picto('', 'company').$form->select_company(!empty($societe->id) ? $societe->id : 0, 'socid', 's.fournisseur=1', 'SelectThirdParty', 0, 0, null, 0, 'minwidth300 widthcentpercentminusxx maxwidth500');
  1801. // reload page to retrieve supplier informations
  1802. if (!empty($conf->global->RELOAD_PAGE_ON_SUPPLIER_CHANGE)) {
  1803. print '<script type="text/javascript">
  1804. $(document).ready(function() {
  1805. $("#socid").change(function() {
  1806. var socid = $(this).val();
  1807. var fac_rec = $(\'#fac_rec\').val();
  1808. window.location.href = "'.$_SERVER["PHP_SELF"].'?action=create&socid="+socid+"&fac_rec="+fac_rec;
  1809. });
  1810. });
  1811. </script>';
  1812. }
  1813. if ($fac_recid <= 0) {
  1814. print ' <a href="'.DOL_URL_ROOT.'/societe/card.php?action=create&client=0&fournisseur=1&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=create').'"><span class="fa fa-plus-circle valignmiddle paddingleft" title="'.$langs->trans("AddThirdParty").'"></span></a>';
  1815. }
  1816. }
  1817. print '</td></tr>';
  1818. // Overwrite some values if creation of invoice is from a predefined invoice
  1819. if (empty($origin) && empty($originid) && $fac_recid > 0) {
  1820. $invoice_predefined->fetch($fac_recid);
  1821. $dateinvoice = $invoice_predefined->date_when; // To use next gen date by default later
  1822. if (empty($projectid)) {
  1823. $projectid = $invoice_predefined->fk_project;
  1824. }
  1825. $cond_reglement_id = $invoice_predefined->cond_reglement_id;
  1826. $mode_reglement_id = $invoice_predefined->mode_reglement_id;
  1827. $fk_account = $invoice_predefined->fk_account;
  1828. $note_public = $invoice_predefined->note_public;
  1829. $note_private = $invoice_predefined->note_private;
  1830. if (!empty($invoice_predefined->multicurrency_code)) {
  1831. $currency_code = $invoice_predefined->multicurrency_code;
  1832. }
  1833. if (!empty($invoice_predefined->multicurrency_tx)) {
  1834. $currency_tx = $invoice_predefined->multicurrency_tx;
  1835. }
  1836. $sql = 'SELECT r.rowid, r.titre as title, r.total_ttc';
  1837. $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_fourn_rec as r';
  1838. $sql .= ' WHERE r.fk_soc = '. (int) $invoice_predefined->socid;
  1839. $resql = $db->query($sql);
  1840. if ($resql) {
  1841. $num = $db->num_rows($resql);
  1842. $i = 0;
  1843. if ($num > 0) {
  1844. print '<tr><td>'.$langs->trans('CreateFromRepeatableInvoice').'</td><td>';
  1845. //print '<input type="hidden" name="fac_rec" id="fac_rec" value="'.$fac_recid.'">';
  1846. print '<select class="flat" id="fac_rec" name="fac_rec">'; // We may want to change the template to use
  1847. print '<option value="0" selected></option>';
  1848. while ($i < $num) {
  1849. $objp = $db->fetch_object($resql);
  1850. print '<option value="'.$objp->rowid.'"';
  1851. if ($fac_recid == $objp->rowid) {
  1852. print ' selected';
  1853. $exampletemplateinvoice->fetch($fac_recid);
  1854. }
  1855. print '>'.$objp->title.' ('.price($objp->total_ttc).' '.$langs->trans("TTC").')</option>';
  1856. $i++;
  1857. }
  1858. print '</select>';
  1859. // Option to reload page to retrieve customer informations. Note, this clear other input
  1860. if (empty($conf->global->RELOAD_PAGE_ON_TEMPLATE_CHANGE_DISABLED)) {
  1861. print '<script type="text/javascript">
  1862. $(document).ready(function() {
  1863. $("#fac_rec").change(function() {
  1864. console.log("We have changed the template invoice - Reload page");
  1865. var fac_rec = $(this).val();
  1866. var socid = $(\'#socid\').val();
  1867. // For template invoice change, we must reuse data of template, not input already done, so we call a GET with action=create, not a POST submit.
  1868. window.location.href = "'.$_SERVER["PHP_SELF"].'?action=create&socid="+socid+"&fac_rec="+fac_rec;
  1869. });
  1870. });
  1871. </script>';
  1872. }
  1873. print '</td></tr>';
  1874. }
  1875. $db->free($resql);
  1876. } else {
  1877. dol_print_error($db);
  1878. }
  1879. }
  1880. // Ref supplier
  1881. print '<tr><td class="fieldrequired">'.$langs->trans('RefSupplier').'</td><td><input name="ref_supplier" value="'.(GETPOSTISSET('ref_supplier') ? GETPOST('ref_supplier') : (!empty($objectsrc->ref_supplier) ? $objectsrc->ref_supplier : '')).'" type="text"';
  1882. if (!empty($societe->id) && $societe->id > 0) {
  1883. print ' autofocus';
  1884. }
  1885. print '></td>';
  1886. print '</tr>';
  1887. print '<tr><td class="tdtop fieldrequired">'.$langs->trans('Type').'</td><td>';
  1888. print '<div class="tagtable">'."\n";
  1889. // Standard invoice
  1890. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  1891. $tmp = '<input type="radio" id="radio_standard" name="type" value="0"'.(GETPOST('type', 'int')? '' : 'checked').'> ';
  1892. $desc = $form->textwithpicto($tmp.$langs->trans("InvoiceStandardAsk"), $langs->transnoentities("InvoiceStandardDesc"), 1, 'help', '', 0, 3);
  1893. print $desc;
  1894. print '</div></div>';
  1895. if (empty($origin) || ($origin == 'order_supplier' && !empty($originid))) {
  1896. // Deposit - Down payment
  1897. if (empty($conf->global->INVOICE_DISABLE_DEPOSIT)) {
  1898. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  1899. $tmp='<input type="radio" id="radio_deposit" name="type" value="3"' . (GETPOST('type') == 3 ? ' checked' : '') . '> ';
  1900. print '<script type="text/javascript">
  1901. jQuery(document).ready(function() {
  1902. jQuery("#typestandardinvoice, #valuestandardinvoice").click(function() {
  1903. jQuery("#radio_standard").prop("checked", true);
  1904. });
  1905. jQuery("#typedeposit, #valuedeposit").click(function() {
  1906. jQuery("#radio_deposit").prop("checked", true);
  1907. });
  1908. jQuery("#typedeposit").change(function() {
  1909. console.log("We change type of down payment");
  1910. jQuery("#radio_deposit").prop("checked", true);
  1911. setRadioForTypeOfInvoice();
  1912. });
  1913. jQuery("#radio_standard, #radio_deposit, #radio_replacement, #radio_template").change(function() {
  1914. setRadioForTypeOfInvoice();
  1915. });
  1916. function setRadioForTypeOfInvoice() {
  1917. console.log("Change radio");
  1918. if (jQuery("#radio_deposit").prop("checked") && (jQuery("#typedeposit").val() == \'amount\' || jQuery("#typedeposit").val() == \'variable\')) {
  1919. jQuery(".checkforselect").prop("disabled", true);
  1920. jQuery(".checkforselect").prop("checked", false);
  1921. } else {
  1922. jQuery(".checkforselect").prop("disabled", false);
  1923. jQuery(".checkforselect").prop("checked", true);
  1924. }
  1925. };
  1926. });
  1927. </script>';
  1928. $tmp = $tmp.'<label for="radio_deposit" >'.$langs->trans("InvoiceDeposit").'</label>';
  1929. $desc = $form->textwithpicto($tmp, $langs->transnoentities("InvoiceDepositDesc"), 1, 'help', '', 0, 3);
  1930. print '<table class="nobordernopadding"><tr>';
  1931. print '<td>';
  1932. print $desc;
  1933. print '</td>';
  1934. if ($origin == 'order_supplier') {
  1935. print '<td class="nowrap" style="padding-left: 15px">';
  1936. $arraylist = array(
  1937. 'amount' => $langs->transnoentitiesnoconv('FixAmount', $langs->transnoentitiesnoconv('Deposit')),
  1938. 'variable' => $langs->transnoentitiesnoconv('VarAmountOneLine', $langs->transnoentitiesnoconv('Deposit')),
  1939. 'variablealllines' => $langs->transnoentitiesnoconv('VarAmountAllLines')
  1940. );
  1941. print $form->selectarray('typedeposit', $arraylist, GETPOST('typedeposit', 'aZ09'), 0, 0, 0, '', 1);
  1942. print '</td>';
  1943. print '<td class="nowrap" style="padding-left: 5px">';
  1944. print '<span class="opacitymedium paddingleft">'.$langs->trans("AmountOrPercent").'</span><input type="text" id="valuedeposit" name="valuedeposit" class="width75 right" value="' . GETPOST('valuedeposit', 'int') . '"/>';
  1945. print '</td>';
  1946. }
  1947. print '</tr></table>';
  1948. print '</div></div>';
  1949. }
  1950. }
  1951. /* Not yet supported for supplier
  1952. if ($societe->id > 0)
  1953. {
  1954. // Replacement
  1955. if (empty($conf->global->INVOICE_DISABLE_REPLACEMENT))
  1956. {
  1957. // Type invoice
  1958. $facids = $facturestatic->list_replacable_supplier_invoices($societe->id);
  1959. if ($facids < 0) {
  1960. dol_print_error($db, $facturestatic->error, $facturestatic->errors);
  1961. exit();
  1962. }
  1963. $options = "";
  1964. foreach ($facids as $facparam)
  1965. {
  1966. $options .= '<option value="' . $facparam ['id'] . '"';
  1967. if ($facparam ['id'] == GETPOST('fac_replacement') {
  1968. $options .= ' selected';
  1969. }
  1970. $options .= '>' . $facparam ['ref'];
  1971. $options .= ' (' . $facturestatic->LibStatut(0, $facparam ['status']) . ')';
  1972. $options .= '</option>';
  1973. }
  1974. print '<!-- replacement line -->';
  1975. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  1976. $tmp='<input type="radio" name="type" id="radio_replacement" value="1"' . (GETPOST('type') == 1 ? ' checked' : '');
  1977. if (! $options) $tmp.=' disabled';
  1978. $tmp.='> ';
  1979. print '<script type="text/javascript">
  1980. jQuery(document).ready(function() {
  1981. jQuery("#fac_replacement").change(function() {
  1982. jQuery("#radio_replacement").prop("checked", true);
  1983. });
  1984. });
  1985. </script>';
  1986. $text = $tmp.$langs->trans("InvoiceReplacementAsk") . ' ';
  1987. $text .= '<select class="flat" name="fac_replacement" id="fac_replacement"';
  1988. if (! $options)
  1989. $text .= ' disabled';
  1990. $text .= '>';
  1991. if ($options) {
  1992. $text .= '<option value="-1">&nbsp;</option>';
  1993. $text .= $options;
  1994. } else {
  1995. $text .= '<option value="-1">' . $langs->trans("NoReplacableInvoice") . '</option>';
  1996. }
  1997. $text .= '</select>';
  1998. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceReplacementDesc"), 1, 'help', '', 0, 3);
  1999. print $desc;
  2000. print '</div></div>';
  2001. }
  2002. }
  2003. else
  2004. {
  2005. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  2006. $tmp='<input type="radio" name="type" id="radio_replacement" value="0" disabled> ';
  2007. $text = $tmp.$langs->trans("InvoiceReplacement") . ' ';
  2008. $text.= '('.$langs->trans("YouMustCreateInvoiceFromSupplierThird").') ';
  2009. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceReplacementDesc"), 1, 'help', '', 0, 3);
  2010. print $desc;
  2011. print '</div></div>';
  2012. }
  2013. */
  2014. if (empty($origin)) {
  2015. if (!empty($societe->id) && $societe->id > 0) {
  2016. // Credit note
  2017. if (empty($conf->global->INVOICE_DISABLE_CREDIT_NOTE)) {
  2018. // Show link for credit note
  2019. $facids = $facturestatic->list_qualified_avoir_supplier_invoices($societe->id);
  2020. if ($facids < 0) {
  2021. dol_print_error($db, $facturestatic->error, $facturestatic->errors);
  2022. exit;
  2023. }
  2024. $optionsav = "";
  2025. $newinvoice_static = new FactureFournisseur($db);
  2026. foreach ($facids as $key => $valarray) {
  2027. $newinvoice_static->id = $key;
  2028. $newinvoice_static->ref = $valarray ['ref'];
  2029. $newinvoice_static->statut = $valarray ['status'];
  2030. $newinvoice_static->type = $valarray ['type'];
  2031. $newinvoice_static->paye = $valarray ['paye'];
  2032. $optionsav .= '<option value="'.$key.'"';
  2033. if ($key == GETPOST('fac_avoir', 'int')) {
  2034. $optionsav .= ' selected';
  2035. }
  2036. $optionsav .= '>';
  2037. $optionsav .= $newinvoice_static->ref;
  2038. $optionsav .= ' ('.$newinvoice_static->getLibStatut(1, $valarray ['paymentornot']).')';
  2039. $optionsav .= '</option>';
  2040. }
  2041. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  2042. $tmp = '<input type="radio" id="radio_creditnote" name="type" value="2"'.(GETPOST('type') == 2 ? ' checked' : '');
  2043. if (!$optionsav) {
  2044. $tmp .= ' disabled';
  2045. }
  2046. $tmp .= '> ';
  2047. // Show credit note options only if we checked credit note
  2048. print '<script type="text/javascript">
  2049. jQuery(document).ready(function() {
  2050. if (! jQuery("#radio_creditnote").is(":checked"))
  2051. {
  2052. jQuery("#credit_note_options").hide();
  2053. }
  2054. jQuery("#radio_creditnote").click(function() {
  2055. jQuery("#credit_note_options").show();
  2056. });
  2057. jQuery("#radio_standard, #radio_replacement, #radio_deposit").click(function() {
  2058. jQuery("#credit_note_options").hide();
  2059. });
  2060. });
  2061. </script>';
  2062. $text = $tmp.$langs->transnoentities("InvoiceAvoirAsk").' ';
  2063. // $text.='<input type="text" value="">';
  2064. $text .= '<select class="flat valignmiddle" name="fac_avoir" id="fac_avoir"';
  2065. if (!$optionsav) {
  2066. $text .= ' disabled';
  2067. }
  2068. $text .= '>';
  2069. if ($optionsav) {
  2070. $text .= '<option value="-1"></option>';
  2071. $text .= $optionsav;
  2072. } else {
  2073. $text .= '<option value="-1">'.$langs->trans("NoInvoiceToCorrect").'</option>';
  2074. }
  2075. $text .= '</select>';
  2076. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3);
  2077. print $desc;
  2078. print '<div id="credit_note_options" class="clearboth">';
  2079. print '&nbsp;&nbsp;&nbsp; <input type="checkbox" name="invoiceAvoirWithLines" id="invoiceAvoirWithLines" value="1" onclick="if($(this).is(\':checked\') ) { $(\'#radio_creditnote\').prop(\'checked\', true); $(\'#invoiceAvoirWithPaymentRestAmount\').removeAttr(\'checked\'); }" '.(GETPOST('invoiceAvoirWithLines', 'int') > 0 ? 'checked' : '').' /> ';
  2080. print '<label for="invoiceAvoirWithLines">'.$langs->trans('invoiceAvoirWithLines')."</label>";
  2081. print '<br>&nbsp;&nbsp;&nbsp; <input type="checkbox" name="invoiceAvoirWithPaymentRestAmount" id="invoiceAvoirWithPaymentRestAmount" value="1" onclick="if($(this).is(\':checked\') ) { $(\'#radio_creditnote\').prop(\'checked\', true); $(\'#invoiceAvoirWithLines\').removeAttr(\'checked\'); }" '.(GETPOST('invoiceAvoirWithPaymentRestAmount', 'int') > 0 ? 'checked' : '').' /> ';
  2082. print '<label for="invoiceAvoirWithPaymentRestAmount">'.$langs->trans('invoiceAvoirWithPaymentRestAmount')."</label>";
  2083. print '</div>';
  2084. print '</div></div>';
  2085. }
  2086. } else {
  2087. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  2088. $tmp = '<input type="radio" name="type" id="radio_creditnote" value="0" disabled> ';
  2089. $text = $tmp.$langs->trans("InvoiceAvoir").' ';
  2090. $text .= '<span class="opacitymedium">('.$langs->trans("YouMustCreateInvoiceFromSupplierThird").')</span> ';
  2091. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3);
  2092. print $desc;
  2093. print '</div></div>'."\n";
  2094. }
  2095. }
  2096. print '</div>';
  2097. print '</td></tr>';
  2098. if (!empty($societe->id) && $societe->id > 0) {
  2099. // Discounts for third party
  2100. print '<tr><td>'.$langs->trans('Discounts').'</td><td>';
  2101. $thirdparty = $societe;
  2102. $discount_type = 1;
  2103. $backtopage = urlencode($_SERVER["PHP_SELF"].'?socid='.$societe->id.'&action='.$action.'&origin='.GETPOST('origin').'&originid='.GETPOST('originid'));
  2104. include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php';
  2105. print '</td></tr>';
  2106. }
  2107. // Label
  2108. print '<tr><td>'.$langs->trans('Label').'</td><td><input class="minwidth200" name="label" value="'.dol_escape_htmltag(GETPOST('label')).'" type="text"></td></tr>';
  2109. // Date invoice
  2110. print '<tr><td class="fieldrequired">'.$langs->trans('DateInvoice').'</td><td>';
  2111. print $form->selectDate($dateinvoice, '', '', '', '', "add", 1, 1);
  2112. print '</td></tr>';
  2113. // Due date
  2114. print '<tr><td>'.$langs->trans('DateMaxPayment').'</td><td>';
  2115. print $form->selectDate($datedue, 'ech', '', '', '', "add", 1, 1);
  2116. print '</td></tr>';
  2117. // Payment term
  2118. print '<tr><td class="nowrap">'.$langs->trans('PaymentConditionsShort').'</td><td>';
  2119. $form->select_conditions_paiements(GETPOSTISSET('cond_reglement_id') ?GETPOST('cond_reglement_id', 'int') : $cond_reglement_id, 'cond_reglement_id');
  2120. print '</td></tr>';
  2121. // Payment mode
  2122. print '<tr><td>'.$langs->trans('PaymentMode').'</td><td>';
  2123. print img_picto('', 'bank', 'class="pictofixedwidth"');
  2124. $form->select_types_paiements(GETPOSTISSET('mode_reglement_id') ?GETPOST('mode_reglement_id', 'int') : $mode_reglement_id, 'mode_reglement_id', 'DBIT', 0, 1, 0, 0, 1, 'maxwidth200 widthcentpercentminusx');
  2125. print '</td></tr>';
  2126. // Bank Account
  2127. if (!empty($conf->banque->enabled)) {
  2128. print '<tr><td>'.$langs->trans('BankAccount').'</td><td>';
  2129. print img_picto('', 'bank_account', 'class="pictofixedwidth"').$form->select_comptes((GETPOSTISSET('fk_account') ?GETPOST('fk_account', 'alpha') : $fk_account), 'fk_account', 0, '', 1, '', 0, 'maxwidth200 widthcentpercentminusx', 1);
  2130. print '</td></tr>';
  2131. }
  2132. // Project
  2133. if (!empty($conf->projet->enabled)) {
  2134. $formproject = new FormProjets($db);
  2135. $langs->load('projects');
  2136. print '<tr><td>'.$langs->trans('Project').'</td><td>';
  2137. print img_picto('', 'project', 'class="pictofixedwidth"').$formproject->select_projects((empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS) ? $societe->id : -1), $projectid, 'projectid', 0, 0, 1, 1, 0, 0, 0, '', 1, 0, 'maxwidth500 widthcentpercentminusxx');
  2138. print ' <a href="'.DOL_URL_ROOT.'/projet/card.php?socid='.(!empty($soc->id) ? $soc->id : 0).'&action=create&status=1&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=create&socid='.(!empty($soc->id) ? $soc->id : 0).($fac_recid > 0 ? '&fac_rec='.$fac_recid : '')).'"><span class="fa fa-plus-circle valignmiddle" title="'.$langs->trans("AddProject").'"></span></a>';
  2139. print '</td></tr>';
  2140. }
  2141. // Incoterms
  2142. if (!empty($conf->incoterm->enabled)) {
  2143. print '<tr>';
  2144. print '<td><label for="incoterm_id">'.$form->textwithpicto($langs->trans("IncotermLabel"), !empty($objectsrc->label_incoterms) ? $objectsrc->label_incoterms : '', 1).'</label></td>';
  2145. print '<td colspan="3" class="maxwidthonsmartphone">';
  2146. print $form->select_incoterms(GETPOSTISSET('incoterm_id') ? GETPOST('incoterm_id', 'alphanohtml') : (!empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : ''), GETPOSTISSET('location_incoterms') ? GETPOST('location_incoterms', 'alphanohtml') : (!empty($objectsrc->location_incoterms) ? $objectsrc->location_incoterms : ''));
  2147. print '</td></tr>';
  2148. }
  2149. // Multicurrency
  2150. if (!empty($conf->multicurrency->enabled)) {
  2151. print '<tr>';
  2152. print '<td>'.$form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0).'</td>';
  2153. print '<td class="maxwidthonsmartphone">';
  2154. print $form->selectMultiCurrency((GETPOSTISSET('multicurrency_code') ?GETPOST('multicurrency_code', 'alpha') : $currency_code), 'multicurrency_code');
  2155. print '</td></tr>';
  2156. }
  2157. // Help of substitution key
  2158. $htmltext = '';
  2159. if ($fac_recid > 0) {
  2160. $dateexample = $newdateinvoice ? $newdateinvoice : $dateinvoice;
  2161. if (empty($dateexample)) {
  2162. $dateexample = dol_now();
  2163. }
  2164. $substitutionarray = array(
  2165. '__TOTAL_HT__' => $langs->trans("AmountHT").' ('.$langs->trans("Example").': '.price($exampletemplateinvoice->total_ht).')',
  2166. '__TOTAL_TTC__' => $langs->trans("AmountTTC").' ('.$langs->trans("Example").': '.price($exampletemplateinvoice->total_ttc).')',
  2167. '__INVOICE_PREVIOUS_MONTH__' => $langs->trans("PreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'), '%m').')',
  2168. '__INVOICE_MONTH__' => $langs->trans("MonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample, '%m').')',
  2169. '__INVOICE_NEXT_MONTH__' => $langs->trans("NextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'), '%m').')',
  2170. '__INVOICE_PREVIOUS_MONTH_TEXT__' => $langs->trans("TextPreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'), '%B').')',
  2171. '__INVOICE_MONTH_TEXT__' => $langs->trans("TextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample, '%B').')',
  2172. '__INVOICE_NEXT_MONTH_TEXT__' => $langs->trans("TextNextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'), '%B').')',
  2173. '__INVOICE_PREVIOUS_YEAR__' => $langs->trans("PreviousYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'y'), '%Y').')',
  2174. '__INVOICE_YEAR__' => $langs->trans("YearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample, '%Y').')',
  2175. '__INVOICE_NEXT_YEAR__' => $langs->trans("NextYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'y'), '%Y').')'
  2176. );
  2177. $htmltext = '<i>'.$langs->trans("FollowingConstantsWillBeSubstituted").':<br>';
  2178. foreach ($substitutionarray as $key => $val) {
  2179. $htmltext .= $key.' = '.$langs->trans($val).'<br>';
  2180. }
  2181. $htmltext .= '</i>';
  2182. }
  2183. // Intracomm report
  2184. if (!empty($conf->intracommreport->enabled)) {
  2185. $langs->loadLangs(array("intracommreport"));
  2186. print '<tr><td>'.$langs->trans('IntracommReportTransportMode').'</td><td>';
  2187. $form->selectTransportMode(GETPOSTISSET('transport_mode_id') ? GETPOST('transport_mode_id') : $transport_mode_id, 'transport_mode_id');
  2188. print '</td></tr>';
  2189. }
  2190. if (empty($reshook)) {
  2191. print $object->showOptionals($extrafields, 'create');
  2192. }
  2193. // Public note
  2194. print '<tr><td>'.$langs->trans('NotePublic').'</td>';
  2195. print '<td>';
  2196. $doleditor = new DolEditor('note_public', (GETPOSTISSET('note_public') ?GETPOST('note_public', 'restricthtml') : $note_public), '', 80, 'dolibarr_notes', 'In', 0, false, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PUBLIC) ? 0 : 1, ROWS_3, '90%');
  2197. print $doleditor->Create(1);
  2198. print '</td>';
  2199. // print '<td><textarea name="note" wrap="soft" cols="60" rows="'.ROWS_5.'"></textarea></td>';
  2200. print '</tr>';
  2201. // Private note
  2202. print '<tr><td>'.$langs->trans('NotePrivate').'</td>';
  2203. print '<td>';
  2204. $doleditor = new DolEditor('note_private', (GETPOSTISSET('note_private') ?GETPOST('note_private', 'restricthtml') : $note_private), '', 80, 'dolibarr_notes', 'In', 0, false, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PRIVATE) ? 0 : 1, ROWS_3, '90%');
  2205. print $doleditor->Create(1);
  2206. print '</td>';
  2207. // print '<td><textarea name="note" wrap="soft" cols="60" rows="'.ROWS_5.'"></textarea></td>';
  2208. print '</tr>';
  2209. if (!empty($objectsrc) && is_object($objectsrc)) {
  2210. print "\n<!-- ".$classname." info -->";
  2211. print "\n";
  2212. print '<input type="hidden" name="amount" value="'.$objectsrc->total_ht.'">'."\n";
  2213. print '<input type="hidden" name="total" value="'.$objectsrc->total_ttc.'">'."\n";
  2214. print '<input type="hidden" name="tva" value="'.$objectsrc->total_tva.'">'."\n";
  2215. print '<input type="hidden" name="origin" value="'.$objectsrc->element.'">';
  2216. print '<input type="hidden" name="originid" value="'.$objectsrc->id.'">';
  2217. $txt = $langs->trans($classname);
  2218. if ($classname == 'CommandeFournisseur') {
  2219. $langs->load('orders');
  2220. $txt = $langs->trans("SupplierOrder");
  2221. }
  2222. print '<tr><td>'.$txt.'</td><td>'.$objectsrc->getNomUrl(1);
  2223. // We check if Origin document (id and type is known) has already at least one invoice attached to it
  2224. $objectsrc->fetchObjectLinked($originid, $origin, '', 'invoice_supplier');
  2225. $invoice_supplier = $objectsrc->linkedObjects['invoice_supplier'];
  2226. // count function need a array as argument (Note: the array must implement Countable too)
  2227. if (is_array($invoice_supplier)) {
  2228. $cntinvoice = count($invoice_supplier);
  2229. if ($cntinvoice >= 1) {
  2230. setEventMessages('WarningBillExist', null, 'warnings');
  2231. echo ' ('.$langs->trans('LatestRelatedBill').end($invoice_supplier)->getNomUrl(1).')';
  2232. }
  2233. }
  2234. print '</td></tr>';
  2235. print '<tr><td>'.$langs->trans('AmountHT').'</td><td>'.price($objectsrc->total_ht).'</td></tr>';
  2236. print '<tr><td>'.$langs->trans('AmountVAT').'</td><td>'.price($objectsrc->total_tva)."</td></tr>";
  2237. if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) { //Localtax1
  2238. print '<tr><td>'.$langs->transcountry("AmountLT1", $mysoc->country_code).'</td><td>'.price($objectsrc->total_localtax1)."</td></tr>";
  2239. }
  2240. if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) { //Localtax2
  2241. print '<tr><td>'.$langs->transcountry("AmountLT2", $mysoc->country_code).'</td><td>'.price($objectsrc->total_localtax2)."</td></tr>";
  2242. }
  2243. print '<tr><td>'.$langs->trans('AmountTTC').'</td><td>'.price($objectsrc->total_ttc)."</td></tr>";
  2244. if (!empty($conf->multicurrency->enabled)) {
  2245. print '<tr><td>'.$langs->trans('MulticurrencyAmountHT').'</td><td>'.price($objectsrc->multicurrency_total_ht).'</td></tr>';
  2246. print '<tr><td>'.$langs->trans('MulticurrencyAmountVAT').'</td><td>'.price($objectsrc->multicurrency_total_tva)."</td></tr>";
  2247. print '<tr><td>'.$langs->trans('MulticurrencyAmountTTC').'</td><td>'.price($objectsrc->multicurrency_total_ttc)."</td></tr>";
  2248. }
  2249. }
  2250. // Other options
  2251. $parameters = array();
  2252. $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  2253. print $hookmanager->resPrint;
  2254. print "</table>\n";
  2255. print dol_get_fiche_end();
  2256. print $form->buttonsSaveCancel("CreateDraft");
  2257. // Show origin lines
  2258. if (!empty($objectsrc) && is_object($objectsrc)) {
  2259. print '<br>';
  2260. $title = $langs->trans('ProductsAndServices');
  2261. print load_fiche_titre($title);
  2262. print '<div class="div-table-responsive-no-min">';
  2263. print '<table class="noborder centpercent">';
  2264. $objectsrc->printOriginLinesList('', $selectedLines);
  2265. print '</table>';
  2266. print '</div>';
  2267. }
  2268. print "</form>\n";
  2269. } else {
  2270. if ($id > 0 || !empty($ref)) {
  2271. //
  2272. // View or edit mode
  2273. //
  2274. $now = dol_now();
  2275. $productstatic = new Product($db);
  2276. $result = $object->fetch($id, $ref);
  2277. if ($result <= 0) {
  2278. $langs->load("errors");
  2279. print $langs->trans("ErrorRecordNotFound");
  2280. llxFooter();
  2281. $db->close();
  2282. exit;
  2283. }
  2284. $result = $object->fetch_thirdparty();
  2285. if ($result < 0) {
  2286. dol_print_error($db, $object->error, $object->errors);
  2287. exit;
  2288. }
  2289. $societe = $object->thirdparty;
  2290. $totalpaid = $object->getSommePaiement();
  2291. $totalcreditnotes = $object->getSumCreditNotesUsed();
  2292. $totaldeposits = $object->getSumDepositsUsed();
  2293. // print "totalpaid=".$totalpaid." totalcreditnotes=".$totalcreditnotes." totaldeposts=".$totaldeposits."
  2294. // selleruserrevenuestamp=".$selleruserevenustamp;
  2295. // We can also use bcadd to avoid pb with floating points
  2296. // For example print 239.2 - 229.3 - 9.9; does not return 0.
  2297. // $resteapayer=bcadd($object->total_ttc,$totalpaid,$conf->global->MAIN_MAX_DECIMALS_TOT);
  2298. // $resteapayer=bcadd($resteapayer,$totalavoir,$conf->global->MAIN_MAX_DECIMALS_TOT);
  2299. $resteapayer = price2num($object->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
  2300. // Multicurrency
  2301. if (!empty($conf->multicurrency->enabled)) {
  2302. $multicurrency_totalpaid = $object->getSommePaiement(1);
  2303. $multicurrency_totalcreditnotes = $object->getSumCreditNotesUsed(1);
  2304. $multicurrency_totaldeposits = $object->getSumDepositsUsed(1);
  2305. $multicurrency_resteapayer = price2num($object->multicurrency_total_ttc - $multicurrency_totalpaid - $multicurrency_totalcreditnotes - $multicurrency_totaldeposits, 'MT');
  2306. // Code to fix case of corrupted data
  2307. if ($resteapayer == 0 && $multicurrency_resteapayer != 0) {
  2308. $resteapayer = price2num($multicurrency_resteapayer / $object->multicurrency_tx, 'MT');
  2309. }
  2310. }
  2311. if ($object->paye) {
  2312. $resteapayer = 0;
  2313. }
  2314. $resteapayeraffiche = $resteapayer;
  2315. if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { // Never use this
  2316. $filterabsolutediscount = "fk_invoice_supplier_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
  2317. $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
  2318. } else {
  2319. $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')";
  2320. $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS PAID)%')";
  2321. }
  2322. $absolute_discount = $societe->getAvailableDiscounts('', $filterabsolutediscount, 0, 1);
  2323. $absolute_creditnote = $societe->getAvailableDiscounts('', $filtercreditnote, 0, 1);
  2324. $absolute_discount = price2num($absolute_discount, 'MT');
  2325. $absolute_creditnote = price2num($absolute_creditnote, 'MT');
  2326. /*
  2327. * View card
  2328. */
  2329. $head = facturefourn_prepare_head($object);
  2330. $titre = $langs->trans('SupplierInvoice');
  2331. print dol_get_fiche_head($head, 'card', $titre, -1, 'supplier_invoice');
  2332. $formconfirm = '';
  2333. // Confirmation de la conversion de l'avoir en reduc
  2334. if ($action == 'converttoreduc') {
  2335. if ($object->type == FactureFournisseur::TYPE_STANDARD) {
  2336. $type_fac = 'ExcessPaid';
  2337. } elseif ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) {
  2338. $type_fac = 'CreditNote';
  2339. } elseif ($object->type == FactureFournisseur::TYPE_DEPOSIT) {
  2340. $type_fac = 'Deposit';
  2341. }
  2342. $text = $langs->trans('ConfirmConvertToReducSupplier', strtolower($langs->transnoentities($type_fac)));
  2343. $text .= '<br>'.$langs->trans('ConfirmConvertToReducSupplier2');
  2344. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id, $langs->trans('ConvertToReduc'), $text, 'confirm_converttoreduc', '', "yes", 2);
  2345. }
  2346. // Clone confirmation
  2347. if ($action == 'clone') {
  2348. // Create an array for form
  2349. $formquestion = array(
  2350. array('type' => 'text', 'name' => 'newsupplierref', 'label' => $langs->trans("RefSupplier"), 'value' => $langs->trans("CopyOf").' '.$object->ref_supplier),
  2351. array('type' => 'date', 'name' => 'newdate', 'label' => $langs->trans("Date"), 'value' => dol_now())
  2352. );
  2353. // Ask confirmation to clone
  2354. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneInvoice', $object->ref), 'confirm_clone', $formquestion, 'yes', 1, 250);
  2355. }
  2356. // Confirmation of validation
  2357. if ($action == 'valid') {
  2358. // We check if number is temporary number
  2359. if (preg_match('/^[\(]?PROV/i', $object->ref) || empty($object->ref)) {
  2360. // empty should not happened, but when it occurs, the test save life
  2361. $numref = $object->getNextNumRef($societe);
  2362. } else {
  2363. $numref = $object->ref;
  2364. }
  2365. if ($numref < 0) {
  2366. setEventMessages($object->error, $object->errors, 'errors');
  2367. $action = '';
  2368. } else {
  2369. $text = $langs->trans('ConfirmValidateBill', $numref);
  2370. /*if (! empty($conf->notification->enabled))
  2371. {
  2372. require_once DOL_DOCUMENT_ROOT .'/core/class/notify.class.php';
  2373. $notify=new Notify($db);
  2374. $text.='<br>';
  2375. $text.=$notify->confirmMessage('BILL_SUPPLIER_VALIDATE',$object->socid, $object);
  2376. }*/
  2377. $formquestion = array();
  2378. $qualified_for_stock_change = 0;
  2379. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  2380. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  2381. } else {
  2382. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  2383. }
  2384. if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) {
  2385. $langs->load("stocks");
  2386. require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
  2387. $formproduct = new FormProduct($db);
  2388. $warehouse = new Entrepot($db);
  2389. $warehouse_array = $warehouse->list_array();
  2390. if (count($warehouse_array) == 1) {
  2391. $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockDecrease", current($warehouse_array)) : $langs->trans("WarehouseForStockIncrease", current($warehouse_array));
  2392. $value = '<input type="hidden" id="idwarehouse" name="idwarehouse" value="'.key($warehouse_array).'">';
  2393. } else {
  2394. $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockDecrease") : $langs->trans("SelectWarehouseForStockIncrease");
  2395. $value = $formproduct->selectWarehouses(GETPOST('idwarehouse') ?GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1);
  2396. }
  2397. $formquestion = array(
  2398. array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $value)
  2399. );
  2400. }
  2401. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ValidateBill'), $text, 'confirm_valid', $formquestion, 1, 1);
  2402. }
  2403. }
  2404. // Confirmation edit (back to draft)
  2405. if ($action == 'edit') {
  2406. $formquestion = array();
  2407. $qualified_for_stock_change = 0;
  2408. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  2409. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  2410. } else {
  2411. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  2412. }
  2413. if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) {
  2414. $langs->load("stocks");
  2415. require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
  2416. $formproduct = new FormProduct($db);
  2417. $warehouse = new Entrepot($db);
  2418. $warehouse_array = $warehouse->list_array();
  2419. if (count($warehouse_array) == 1) {
  2420. $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockIncrease", current($warehouse_array)) : $langs->trans("WarehouseForStockDecrease", current($warehouse_array));
  2421. $value = '<input type="hidden" id="idwarehouse" name="idwarehouse" value="'.key($warehouse_array).'">';
  2422. } else {
  2423. $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockIncrease") : $langs->trans("SelectWarehouseForStockDecrease");
  2424. $value = $formproduct->selectWarehouses(GETPOST('idwarehouse') ?GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1);
  2425. }
  2426. $formquestion = array(
  2427. array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $value)
  2428. );
  2429. }
  2430. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('UnvalidateBill'), $langs->trans('ConfirmUnvalidateBill', $object->ref), 'confirm_edit', $formquestion, 1, 1);
  2431. }
  2432. // Confirmation set paid
  2433. if ($action == 'paid' && ($resteapayer <= 0 || (!empty($conf->global->SUPPLIER_INVOICE_CAN_SET_PAID_EVEN_IF_PARTIALLY_PAID) && $resteapayer == $object->total_ttc))) {
  2434. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ClassifyPaid'), $langs->trans('ConfirmClassifyPaidBill', $object->ref), 'confirm_paid', '', 0, 1);
  2435. }
  2436. if ($action == 'paid' && $resteapayer > 0 && (empty($conf->global->SUPPLIER_INVOICE_CAN_SET_PAID_EVEN_IF_PARTIALLY_PAID) || $resteapayer != $object->total_ttc)) {
  2437. $close = array();
  2438. // Code
  2439. $i = 0;
  2440. $close[$i]['code'] = 'discount_vat'; // escompte
  2441. $i++;
  2442. $close[$i]['code'] = 'badsupplier';
  2443. $i++;
  2444. $close[$i]['code'] = 'other';
  2445. $i++;
  2446. // Help
  2447. $i = 0;
  2448. $close[$i]['label'] = $langs->trans("HelpEscompte").'<br><br>'.$langs->trans("ConfirmClassifyPaidPartiallyReasonDiscountVatDesc");
  2449. $i++;
  2450. $close[$i]['label'] = $langs->trans("ConfirmClassifyPaidPartiallyReasonBadSupplierDesc");
  2451. $i++;
  2452. $close[$i]['label'] = $langs->trans("Other");
  2453. $i++;
  2454. // Text
  2455. $i = 0;
  2456. $close[$i]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonDiscount", $resteapayer, $langs->trans("Currency".$conf->currency)), $close[$i]['label'], 1);
  2457. $i++;
  2458. $close[$i]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBadCustomer", $resteapayer, $langs->trans("Currency".$conf->currency)), $close[$i]['label'], 1);
  2459. $i++;
  2460. $close[$i]['reason'] = $form->textwithpicto($langs->transnoentities("Other"), $close[$i]['label'], 1);
  2461. $i++;
  2462. // arrayreasons[code]=reason
  2463. foreach ($close as $key => $val) {
  2464. $arrayreasons[$close[$key]['code']] = $close[$key]['reason'];
  2465. }
  2466. // Create a form table
  2467. $formquestion = array('text' => $langs->trans("ConfirmClassifyPaidPartiallyQuestion"), array('type' => 'radio', 'name' => 'close_code', 'label' => $langs->trans("Reason"), 'values' => $arrayreasons), array('type' => 'text', 'name' => 'close_note', 'label' => $langs->trans("Comment"), 'value' => '', 'morecss' => 'minwidth300'));
  2468. // Incomplete payment. We ask if the reason is discount or other
  2469. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id, $langs->trans('ClassifyPaid'), $langs->trans('ConfirmClassifyPaidPartially', $object->ref), 'confirm_paid_partially', $formquestion, "yes", 1, 310);
  2470. }
  2471. // Confirmation of the abandoned classification
  2472. if ($action == 'canceled') {
  2473. // Code
  2474. $close[1]['code'] = 'badsupplier';
  2475. $close[2]['code'] = 'abandon';
  2476. // Help
  2477. $close[1]['label'] = $langs->trans("ConfirmClassifyPaidPartiallyReasonBadSupplierDesc");
  2478. $close[2]['label'] = $langs->trans("ConfirmClassifyAbandonReasonOtherDesc");
  2479. // Text
  2480. $close[1]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBadSupplier", $object->ref), $close[1]['label'], 1);
  2481. $close[2]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyAbandonReasonOther"), $close[2]['label'], 1);
  2482. // arrayreasons
  2483. $arrayreasons[$close[1]['code']] = $close[1]['reason'];
  2484. $arrayreasons[$close[2]['code']] = $close[2]['reason'];
  2485. // Create a form table
  2486. $formquestion = array('text' => $langs->trans("ConfirmCancelBillQuestion"), array('type' => 'radio', 'name' => 'close_code', 'label' => $langs->trans("Reason"), 'values' => $arrayreasons), array('type' => 'text', 'name' => 'close_note', 'label' => $langs->trans("Comment"), 'value' => '', 'morecss' => 'minwidth300'));
  2487. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id, $langs->trans('CancelBill'), $langs->trans('ConfirmCancelBill', $object->ref), 'confirm_canceled', $formquestion, "yes", 1, 250);
  2488. }
  2489. // Confirmation de la suppression de la facture fournisseur
  2490. if ($action == 'delete') {
  2491. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteBill'), $langs->trans('ConfirmDeleteBill'), 'confirm_delete', '', 0, 1);
  2492. }
  2493. if ($action == 'deletepayment') {
  2494. $payment_id = GETPOST('paiement_id');
  2495. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&paiement_id='.$payment_id, $langs->trans('DeletePayment'), $langs->trans('ConfirmDeletePayment'), 'confirm_delete_paiement', '', 0, 1);
  2496. }
  2497. // Confirmation to delete line
  2498. if ($action == 'ask_deleteline') {
  2499. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 0, 1);
  2500. }
  2501. if (!$formconfirm) {
  2502. $parameters = array('formConfirm' => $formconfirm, 'lineid'=>$lineid);
  2503. $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  2504. if (empty($reshook)) {
  2505. $formconfirm .= $hookmanager->resPrint;
  2506. } elseif ($reshook > 0) {
  2507. $formconfirm = $hookmanager->resPrint;
  2508. }
  2509. }
  2510. // Print form confirm
  2511. print $formconfirm;
  2512. // Supplier invoice card
  2513. $linkback = '<a href="'.DOL_URL_ROOT.'/fourn/facture/list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
  2514. $morehtmlref = '<div class="refidno">';
  2515. // Ref supplier
  2516. $morehtmlref .= $form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $usercancreate, 'string', '', 0, 1);
  2517. $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $usercancreate, 'string', '', null, null, '', 1);
  2518. // Thirdparty
  2519. $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1, 'supplier');
  2520. if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) {
  2521. $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/fourn/facture/list.php?socid='.$object->thirdparty->id.'&search_company='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherBills").'</a>)';
  2522. }
  2523. // Project
  2524. if (!empty($conf->projet->enabled)) {
  2525. $langs->load("projects");
  2526. $morehtmlref .= '<br>'.$langs->trans('Project').' ';
  2527. if ($usercancreate) {
  2528. if ($action != 'classify') {
  2529. $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : ';
  2530. }
  2531. if ($action == 'classify') {
  2532. //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
  2533. $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
  2534. $morehtmlref .= '<input type="hidden" name="action" value="classin">';
  2535. $morehtmlref .= '<input type="hidden" name="token" value="'.newToken().'">';
  2536. $morehtmlref .= $formproject->select_projects((empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS) ? $object->socid : -1), $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
  2537. $morehtmlref .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  2538. $morehtmlref .= '</form>';
  2539. } else {
  2540. $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
  2541. }
  2542. } else {
  2543. if (!empty($object->fk_project)) {
  2544. $proj = new Project($db);
  2545. $proj->fetch($object->fk_project);
  2546. $morehtmlref .= ' : '.$proj->getNomUrl(1);
  2547. if ($proj->title) {
  2548. $morehtmlref .= ' - '.$proj->title;
  2549. }
  2550. } else {
  2551. $morehtmlref .= '';
  2552. }
  2553. }
  2554. }
  2555. $morehtmlref .= '</div>';
  2556. $object->totalpaid = $totalpaid; // To give a chance to dol_banner_tab to use already paid amount to show correct status
  2557. dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
  2558. print '<div class="fichecenter">';
  2559. print '<div class="fichehalfleft">';
  2560. print '<div class="underbanner clearboth"></div>';
  2561. print '<table class="border tableforfield" width="100%">';
  2562. // Type
  2563. print '<tr><td class="titlefield">'.$langs->trans('Type').'</td><td>';
  2564. print '<span class="badgeneutral">';
  2565. print $object->getLibType();
  2566. print '</span>';
  2567. if ($object->type == FactureFournisseur::TYPE_REPLACEMENT) {
  2568. $facreplaced = new FactureFournisseur($db);
  2569. $facreplaced->fetch($object->fk_facture_source);
  2570. print ' ('.$langs->transnoentities("ReplaceInvoice", $facreplaced->getNomUrl(1)).')';
  2571. }
  2572. if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) {
  2573. $facusing = new FactureFournisseur($db);
  2574. if ($object->fk_facture_source > 0) {
  2575. $facusing->fetch($object->fk_facture_source);
  2576. print ' ('.$langs->transnoentities("CorrectInvoice", $facusing->getNomUrl(1)).')';
  2577. } else {
  2578. print ' ('.$langs->transnoentities("CorrectedInvoiceNotFound").')';
  2579. }
  2580. }
  2581. $facidavoir = $object->getListIdAvoirFromInvoice();
  2582. if (count($facidavoir) > 0) {
  2583. $invoicecredits = array();
  2584. foreach ($facidavoir as $id) {
  2585. $facavoir = new FactureFournisseur($db);
  2586. $facavoir->fetch($id);
  2587. $invoicecredits[] = $facavoir->getNomUrl(1);
  2588. }
  2589. print ' ('.$langs->transnoentities("InvoiceHasAvoir") . (count($invoicecredits) ? ' ' : '') . implode(',', $invoicecredits) . ')';
  2590. }
  2591. if (isset($facidnext) && $facidnext > 0) {
  2592. $facthatreplace = new FactureFournisseur($db);
  2593. $facthatreplace->fetch($facidnext);
  2594. print ' ('.$langs->transnoentities("ReplacedByInvoice", $facthatreplace->getNomUrl(1)).')';
  2595. }
  2596. if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) {
  2597. $discount = new DiscountAbsolute($db);
  2598. $result = $discount->fetch(0, 0, $object->id);
  2599. if ($result > 0) {
  2600. print ' <span class="opacitymediumbycolor paddingleft">';
  2601. $s = $langs->trans("CreditNoteConvertedIntoDiscount", '{s1}', '{s2}');
  2602. $s = str_replace('{s1}', $object->getLibType(1), $s);
  2603. $s = str_replace('{s2}', $discount->getNomUrl(1, 'discount'), $s);
  2604. print $s;
  2605. print '</span><br>';
  2606. }
  2607. }
  2608. if ($object->fk_fac_rec_source > 0) {
  2609. $tmptemplate = new FactureFournisseurRec($db);
  2610. $result = $tmptemplate->fetch($object->fk_fac_rec_source);
  2611. if ($result > 0) {
  2612. print ' <span class="opacitymediumbycolor paddingleft">';
  2613. $link = '<a href="'.DOL_URL_ROOT.'/fourn/facture/card-rec.php?facid='.$tmptemplate->id.'">'.dol_escape_htmltag($tmptemplate->titre).'</a>';
  2614. $s = $langs->transnoentities("GeneratedFromSupplierTemplate", $link);
  2615. print $s;
  2616. print '</span>';
  2617. }
  2618. }
  2619. print '</td></tr>';
  2620. // Relative and absolute discounts
  2621. print '<!-- Discounts --><tr><td>'.$langs->trans('Discounts');
  2622. print '</td><td>';
  2623. $thirdparty = $societe;
  2624. $discount_type = 1;
  2625. $backtopage = urlencode($_SERVER["PHP_SELF"].'?facid='.$object->id);
  2626. include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php';
  2627. print '</td></tr>';
  2628. // Label
  2629. print '<tr>';
  2630. print '<td>'.$form->editfieldkey("Label", 'label', $object->label, $object, $usercancreate).'</td>';
  2631. print '<td>'.$form->editfieldval("Label", 'label', $object->label, $object, $usercancreate).'</td>';
  2632. print '</tr>';
  2633. $form_permission = ($object->statut < FactureFournisseur::STATUS_CLOSED) && $usercancreate && ($object->getSommePaiement() <= 0);
  2634. $form_permission2 = ($object->statut < FactureFournisseur::STATUS_CLOSED) && $usercancreate;
  2635. // Date
  2636. print '<tr><td>';
  2637. print $form->editfieldkey("DateInvoice", 'datef', $object->datep, $object, $form_permission, 'datepicker');
  2638. print '</td><td colspan="3">';
  2639. print $form->editfieldval("Date", 'datef', $object->datep, $object, $form_permission, 'datepicker');
  2640. print '</td>';
  2641. // Default terms of the settlement
  2642. $langs->load('bills');
  2643. print '<tr><td class="nowrap">';
  2644. print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">';
  2645. print $langs->trans('PaymentConditions');
  2646. print '<td>';
  2647. if ($action != 'editconditions' && $form_permission) {
  2648. print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editconditions&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->trans('SetConditions'), 1).'</a></td>';
  2649. }
  2650. print '</tr></table>';
  2651. print '</td><td>';
  2652. if ($action == 'editconditions') {
  2653. $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->cond_reglement_id, 'cond_reglement_id');
  2654. } else {
  2655. $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->cond_reglement_id, 'none');
  2656. }
  2657. print "</td>";
  2658. print '</tr>';
  2659. // Due date
  2660. print '<tr><td>';
  2661. print $form->editfieldkey("DateMaxPayment", 'date_lim_reglement', $object->date_echeance, $object, $form_permission2, 'datepicker');
  2662. print '</td><td>';
  2663. print $form->editfieldval("DateMaxPayment", 'date_lim_reglement', $object->date_echeance, $object, $form_permission2, 'datepicker');
  2664. if ($action != 'editdate_lim_reglement' && $object->hasDelay()) {
  2665. print img_warning($langs->trans('Late'));
  2666. }
  2667. print '</td>';
  2668. // Mode of payment
  2669. $langs->load('bills');
  2670. print '<tr><td class="nowrap">';
  2671. print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">';
  2672. print $langs->trans('PaymentMode');
  2673. print '</td>';
  2674. if ($action != 'editmode' && $form_permission2) {
  2675. print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmode&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->trans('SetMode'), 1).'</a></td>';
  2676. }
  2677. print '</tr></table>';
  2678. print '</td><td>';
  2679. if ($action == 'editmode') {
  2680. $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'mode_reglement_id', 'DBIT', 1, 1);
  2681. } else {
  2682. $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'none');
  2683. }
  2684. print '</td></tr>';
  2685. // Multicurrency
  2686. if (!empty($conf->multicurrency->enabled)) {
  2687. // Multicurrency code
  2688. print '<tr>';
  2689. print '<td>';
  2690. print '<table class="nobordernopadding" width="100%"><tr><td>';
  2691. print $form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0);
  2692. print '</td>';
  2693. if ($action != 'editmulticurrencycode' && $object->statut == $object::STATUS_DRAFT) {
  2694. 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>';
  2695. }
  2696. print '</tr></table>';
  2697. print '</td><td>';
  2698. if ($action == 'editmulticurrencycode') {
  2699. $form->form_multicurrency_code($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_code, 'multicurrency_code');
  2700. } else {
  2701. $form->form_multicurrency_code($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_code, 'none');
  2702. }
  2703. print '</td></tr>';
  2704. // Multicurrency rate
  2705. if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) {
  2706. print '<tr>';
  2707. print '<td>';
  2708. print '<table class="nobordernopadding centpercent"><tr><td>';
  2709. print $form->editfieldkey('CurrencyRate', 'multicurrency_tx', '', $object, 0);
  2710. print '</td>';
  2711. if ($action != 'editmulticurrencyrate' && $object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) {
  2712. 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>';
  2713. }
  2714. print '</tr></table>';
  2715. print '</td><td>';
  2716. if ($action == 'editmulticurrencyrate' || $action == 'actualizemulticurrencyrate') {
  2717. if ($action == 'actualizemulticurrencyrate') {
  2718. list($object->fk_multicurrency, $object->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($object->db, $object->multicurrency_code);
  2719. }
  2720. $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_tx, 'multicurrency_tx', $object->multicurrency_code);
  2721. } else {
  2722. $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_tx, 'none', $object->multicurrency_code);
  2723. if ($object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) {
  2724. print '<div class="inline-block"> &nbsp; &nbsp; &nbsp; &nbsp; ';
  2725. print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=actualizemulticurrencyrate">'.$langs->trans("ActualizeCurrency").'</a>';
  2726. print '</div>';
  2727. }
  2728. }
  2729. print '</td></tr>';
  2730. }
  2731. }
  2732. // Bank Account
  2733. if (!empty($conf->banque->enabled)) {
  2734. print '<tr><td class="nowrap">';
  2735. print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">';
  2736. print $langs->trans('BankAccount');
  2737. print '<td>';
  2738. if ($action != 'editbankaccount' && $usercancreate) {
  2739. 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>';
  2740. }
  2741. print '</tr></table>';
  2742. print '</td><td>';
  2743. if ($action == 'editbankaccount') {
  2744. $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1);
  2745. } else {
  2746. $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none');
  2747. }
  2748. print "</td>";
  2749. print '</tr>';
  2750. }
  2751. // Incoterms
  2752. if (!empty($conf->incoterm->enabled)) {
  2753. print '<tr><td>';
  2754. print '<table width="100%" class="nobordernopadding"><tr><td>';
  2755. print $langs->trans('IncotermLabel');
  2756. print '<td><td class="right">';
  2757. if ($usercancreate) {
  2758. print '<a class="editfielda" href="'.DOL_URL_ROOT.'/fourn/facture/card.php?facid='.$object->id.'&action=editincoterm&token='.newToken().'">'.img_edit().'</a>';
  2759. } else {
  2760. print '&nbsp;';
  2761. }
  2762. print '</td></tr></table>';
  2763. print '</td>';
  2764. print '<td>';
  2765. if ($action != 'editincoterm') {
  2766. print $form->textwithpicto($object->display_incoterms(), $object->label_incoterms, 1);
  2767. } else {
  2768. print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : ''), $_SERVER['PHP_SELF'].'?id='.$object->id);
  2769. }
  2770. print '</td></tr>';
  2771. }
  2772. // Intracomm report
  2773. if (!empty($conf->intracommreport->enabled)) {
  2774. $langs->loadLangs(array("intracommreport"));
  2775. print '<tr><td>';
  2776. print '<table width="100%" class="nobordernopadding"><tr><td>';
  2777. print $langs->trans('IntracommReportTransportMode');
  2778. print '</td>';
  2779. if ($action != 'editmode' && ($user->rights->fournisseur->facture->creer || $user->rights->supplier_invoice->creer)) {
  2780. print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmode&token='.newToken().'&id='.$object->id.'">'.img_edit().'</a></td>';
  2781. }
  2782. print '</tr></table>';
  2783. print '</td>';
  2784. print '<td>';
  2785. if ($action == 'editmode') {
  2786. $form->formSelectTransportMode($_SERVER['PHP_SELF'].'?id='.$object->id, $object->transport_mode_id, 'transport_mode_id', 1, 1);
  2787. } else {
  2788. $form->formSelectTransportMode($_SERVER['PHP_SELF'].'?id='.$object->id, $object->transport_mode_id, 'none');
  2789. }
  2790. print '</td></tr>';
  2791. }
  2792. // Other attributes
  2793. $cols = 2;
  2794. include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
  2795. print '</table>';
  2796. print '</div>';
  2797. print '<div class="fichehalfright">';
  2798. print '<div class="underbanner clearboth"></div>';
  2799. print '<table class="border tableforfield centpercent">';
  2800. if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) {
  2801. // Multicurrency Amount HT
  2802. print '<tr><td class="titlefieldmiddle">'.$form->editfieldkey('MulticurrencyAmountHT', 'multicurrency_total_ht', '', $object, 0).'</td>';
  2803. print '<td class="nowrap">'.price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'</td>';
  2804. print '</tr>';
  2805. // Multicurrency Amount VAT
  2806. print '<tr><td>'.$form->editfieldkey('MulticurrencyAmountVAT', 'multicurrency_total_tva', '', $object, 0).'</td>';
  2807. print '<td>'.price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'</td>';
  2808. print '</tr>';
  2809. // Multicurrency Amount TTC
  2810. print '<tr><td>'.$form->editfieldkey('MulticurrencyAmountTTC', 'multicurrency_total_ttc', '', $object, 0).'</td>';
  2811. print '<td>'.price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'</td>';
  2812. print '</tr>';
  2813. }
  2814. // Amount
  2815. print '<tr><td class="titlefield">'.$langs->trans('AmountHT').'</td><td>'.price($object->total_ht, 1, $langs, 0, -1, -1, $conf->currency).'</td></tr>';
  2816. print '<tr><td>'.$langs->trans('AmountVAT').'</td><td>'.price($object->total_tva, 1, $langs, 0, -1, -1, $conf->currency);
  2817. if (GETPOST('calculationrule')) {
  2818. $calculationrule = GETPOST('calculationrule', 'alpha');
  2819. } else {
  2820. $calculationrule = (empty($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND) ? 'totalofround' : 'roundoftotal');
  2821. }
  2822. if ($calculationrule == 'totalofround') {
  2823. $calculationrulenum = 1;
  2824. } else {
  2825. $calculationrulenum = 2;
  2826. }
  2827. // Show link for "recalculate"
  2828. if ($object->getVentilExportCompta() == 0) {
  2829. $s = '<span class="hideonsmartphone opacitymedium">'.$langs->trans("ReCalculate").' </span>';
  2830. $s .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=calculate&calculationrule=totalofround">'.$langs->trans("Mode1").'</a>';
  2831. $s .= ' / ';
  2832. $s .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=calculate&calculationrule=roundoftotal">'.$langs->trans("Mode2").'</a>';
  2833. print '<div class="inline-block">';
  2834. print ' &nbsp; &nbsp; &nbsp; &nbsp; ';
  2835. print $form->textwithtooltip($s, $langs->trans("CalculationRuleDesc", $calculationrulenum).'<br>'.$langs->trans("CalculationRuleDescSupplier"), 2, 1, img_picto('', 'help'), '', 3, '', 0, 'recalculate');
  2836. print '</div>';
  2837. }
  2838. print '</td></tr>';
  2839. // Amount Local Taxes
  2840. //TODO: Place into a function to control showing by country or study better option
  2841. if ($societe->localtax1_assuj == "1") { //Localtax1
  2842. print '<tr><td>'.$langs->transcountry("AmountLT1", $societe->country_code).'</td>';
  2843. print '<td>'.price($object->total_localtax1, 1, $langs, 0, -1, -1, $conf->currency).'</td>';
  2844. print '</tr>';
  2845. }
  2846. if ($societe->localtax2_assuj == "1") { //Localtax2
  2847. print '<tr><td>'.$langs->transcountry("AmountLT2", $societe->country_code).'</td>';
  2848. print '<td>'.price($object->total_localtax2, 1, $langs, 0, -1, -1, $conf->currency).'</td>';
  2849. print '</tr>';
  2850. }
  2851. print '<tr><td>'.$langs->trans('AmountTTC').'</td><td colspan="3">'.price($object->total_ttc, 1, $langs, 0, -1, -1, $conf->currency).'</td></tr>';
  2852. print '</table>';
  2853. // List of payments
  2854. $totalpaid = 0;
  2855. $sign = 1;
  2856. if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) {
  2857. $sign = - 1;
  2858. }
  2859. $nbrows = 9; $nbcols = 3;
  2860. if (!empty($conf->projet->enabled)) {
  2861. $nbrows++;
  2862. }
  2863. if (!empty($conf->banque->enabled)) {
  2864. $nbrows++; $nbcols++;
  2865. }
  2866. if (!empty($conf->incoterm->enabled)) {
  2867. $nbrows++;
  2868. }
  2869. if (!empty($conf->multicurrency->enabled)) {
  2870. $nbrows += 5;
  2871. }
  2872. // Local taxes
  2873. if ($societe->localtax1_assuj == "1") {
  2874. $nbrows++;
  2875. }
  2876. if ($societe->localtax2_assuj == "1") {
  2877. $nbrows++;
  2878. }
  2879. $sql = 'SELECT p.datep as dp, p.ref, p.num_paiement as num_payment, p.rowid, p.fk_bank,';
  2880. $sql .= ' c.id as paiement_type,';
  2881. $sql .= ' pf.amount,';
  2882. $sql .= ' ba.rowid as baid, ba.ref as baref, ba.label, ba.number as banumber, ba.account_number, ba.fk_accountancy_journal';
  2883. $sql .= ' FROM '.MAIN_DB_PREFIX.'paiementfourn as p';
  2884. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid';
  2885. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank_account as ba ON b.fk_account = ba.rowid';
  2886. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id';
  2887. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf ON pf.fk_paiementfourn = p.rowid';
  2888. $sql .= ' WHERE pf.fk_facturefourn = '.((int) $object->id);
  2889. $sql .= ' ORDER BY p.datep, p.tms';
  2890. $result = $db->query($sql);
  2891. if ($result) {
  2892. $num = $db->num_rows($result);
  2893. $i = 0;
  2894. print '<div class="div-table-responsive-no-min">';
  2895. print '<table class="noborder paymenttable" width="100%">';
  2896. print '<tr class="liste_titre">';
  2897. print '<td class="liste_titre">'.($object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("PaymentsBack") : $langs->trans('Payments')).'</td>';
  2898. print '<td>'.$langs->trans('Date').'</td>';
  2899. print '<td>'.$langs->trans('Type').'</td>';
  2900. if (!empty($conf->banque->enabled)) {
  2901. print '<td class="right">'.$langs->trans('BankAccount').'</td>';
  2902. }
  2903. print '<td class="right">'.$langs->trans('Amount').'</td>';
  2904. print '<td width="18">&nbsp;</td>';
  2905. print '</tr>';
  2906. if ($num > 0) {
  2907. while ($i < $num) {
  2908. $objp = $db->fetch_object($result);
  2909. $paymentstatic->id = $objp->rowid;
  2910. $paymentstatic->datepaye = $db->jdate($objp->dp);
  2911. $paymentstatic->ref = ($objp->ref ? $objp->ref : $objp->rowid);
  2912. $paymentstatic->num_payment = $objp->num_payment;
  2913. $paymentstatic->payment_code = $objp->payment_code;
  2914. print '<tr class="oddeven">';
  2915. print '<td>';
  2916. print $paymentstatic->getNomUrl(1);
  2917. print '</td>';
  2918. print '<td>'.dol_print_date($db->jdate($objp->dp), 'day').'</td>';
  2919. print '<td>';
  2920. print $form->form_modes_reglement(null, $objp->paiement_type, 'none').' '.$objp->num_payment;
  2921. print '</td>';
  2922. if (!empty($conf->banque->enabled)) {
  2923. $bankaccountstatic->id = $objp->baid;
  2924. $bankaccountstatic->ref = $objp->baref;
  2925. $bankaccountstatic->label = $objp->baref;
  2926. $bankaccountstatic->number = $objp->banumber;
  2927. if (!empty($conf->accounting->enabled)) {
  2928. $bankaccountstatic->account_number = $objp->account_number;
  2929. $accountingjournal = new AccountingJournal($db);
  2930. $accountingjournal->fetch($objp->fk_accountancy_journal);
  2931. $bankaccountstatic->accountancy_journal = $accountingjournal->getNomUrl(0, 1, 1, '', 1);
  2932. }
  2933. print '<td class="right">';
  2934. if ($objp->baid > 0) {
  2935. print $bankaccountstatic->getNomUrl(1, 'transactions');
  2936. }
  2937. print '</td>';
  2938. }
  2939. print '<td class="right">'.price($sign * $objp->amount).'</td>';
  2940. print '<td class="center">';
  2941. if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->socid == 0) {
  2942. print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=deletepayment&token='.newToken().'&paiement_id='.$objp->rowid.'">';
  2943. print img_delete();
  2944. print '</a>';
  2945. }
  2946. print '</td>';
  2947. print '</tr>';
  2948. $totalpaid += $objp->amount;
  2949. $i++;
  2950. }
  2951. } else {
  2952. print '<tr class="oddeven"><td colspan="'.$nbcols.'"><span class="opacitymedium">'.$langs->trans("None").'</span></td><td></td><td></td></tr>';
  2953. }
  2954. /*
  2955. if ($object->paye == 0)
  2956. {
  2957. print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans('AlreadyPaid').' :</td><td class="right">'.price($totalpaid).'</td><td></td></tr>';
  2958. print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans("Billed").' :</td><td class="right">'.price($object->total_ttc).'</td><td></td></tr>';
  2959. $resteapayer = $object->total_ttc - $totalpaid;
  2960. print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans('RemainderToPay').' :</td>';
  2961. print '<td class="right'.($resteapayer?' amountremaintopay':'').'">'.price($resteapayer).'</td><td></td></tr>';
  2962. }
  2963. */
  2964. $db->free($result);
  2965. } else {
  2966. dol_print_error($db);
  2967. }
  2968. if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE) {
  2969. // Total already paid
  2970. print '<tr><td colspan="'.$nbcols.'" class="right">';
  2971. print '<span class="opacitymedium">';
  2972. if ($object->type != FactureFournisseur::TYPE_DEPOSIT) {
  2973. print $langs->trans('AlreadyPaidNoCreditNotesNoDeposits');
  2974. } else {
  2975. print $langs->trans('AlreadyPaid');
  2976. }
  2977. print '</span>';
  2978. print '</td><td class="right"'.(($totalpaid > 0) ? ' class="amountalreadypaid"' : '').'>'.price($totalpaid).'</td><td>&nbsp;</td></tr>';
  2979. //$resteapayer = $object->total_ttc - $totalpaid;
  2980. $resteapayeraffiche = $resteapayer;
  2981. $cssforamountpaymentcomplete = 'amountpaymentcomplete';
  2982. // Loop on each credit note or deposit amount applied
  2983. $creditnoteamount = 0;
  2984. $depositamount = 0;
  2985. $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
  2986. $sql .= " re.description, re.fk_invoice_supplier_source";
  2987. $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re";
  2988. $sql .= " WHERE fk_invoice_supplier = ".((int) $object->id);
  2989. $resql = $db->query($sql);
  2990. if ($resql) {
  2991. $num = $db->num_rows($resql);
  2992. $i = 0;
  2993. $invoice = new FactureFournisseur($db);
  2994. while ($i < $num) {
  2995. $obj = $db->fetch_object($resql);
  2996. $invoice->fetch($obj->fk_invoice_supplier_source);
  2997. print '<tr><td colspan="'.$nbcols.'" class="right">';
  2998. if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) {
  2999. print $langs->trans("CreditNote").' ';
  3000. }
  3001. if ($invoice->type == FactureFournisseur::TYPE_DEPOSIT) {
  3002. print $langs->trans("Deposit").' ';
  3003. }
  3004. print $invoice->getNomUrl(0);
  3005. print ' :</td>';
  3006. print '<td class="right">'.price($obj->amount_ttc).'</td>';
  3007. print '<td class="right">';
  3008. print '<a href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&action=unlinkdiscount&discountid='.$obj->rowid.'">'.img_delete().'</a>';
  3009. print '</td></tr>';
  3010. $i++;
  3011. if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) {
  3012. $creditnoteamount += $obj->amount_ttc;
  3013. }
  3014. if ($invoice->type == FactureFournisseur::TYPE_DEPOSIT) {
  3015. $depositamount += $obj->amount_ttc;
  3016. }
  3017. }
  3018. } else {
  3019. dol_print_error($db);
  3020. }
  3021. // Paye partiellement 'escompte'
  3022. if (($object->statut == FactureFournisseur::STATUS_CLOSED || $object->statut == FactureFournisseur::STATUS_ABANDONED) && $object->close_code == 'discount_vat') {
  3023. print '<tr><td colspan="'.$nbcols.'" class="right nowrap">';
  3024. print '<span class="opacitymedium">';
  3025. print $form->textwithpicto($langs->trans("Discount"), $langs->trans("HelpEscompte"), - 1);
  3026. print '</span>';
  3027. print '</td><td class="right">'.price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaid).'</td><td>&nbsp;</td></tr>';
  3028. $resteapayeraffiche = 0;
  3029. $cssforamountpaymentcomplete = 'amountpaymentneutral';
  3030. }
  3031. // Paye partiellement ou Abandon 'badsupplier'
  3032. if (($object->statut == FactureFournisseur::STATUS_CLOSED || $object->statut == FactureFournisseur::STATUS_ABANDONED) && $object->close_code == 'badsupplier') {
  3033. print '<tr><td colspan="'.$nbcols.'" class="right nowrap">';
  3034. print '<span class="opacitymedium">';
  3035. print $form->textwithpicto($langs->trans("Abandoned"), $langs->trans("HelpAbandonBadCustomer"), - 1);
  3036. print '</span>';
  3037. print '</td><td class="right">'.price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaid).'</td><td>&nbsp;</td></tr>';
  3038. // $resteapayeraffiche=0;
  3039. $cssforamountpaymentcomplete = 'amountpaymentneutral';
  3040. }
  3041. // Paye partiellement ou Abandon 'product_returned'
  3042. if (($object->statut == FactureFournisseur::STATUS_CLOSED || $object->statut == FactureFournisseur::STATUS_ABANDONED) && $object->close_code == 'product_returned') {
  3043. print '<tr><td colspan="'.$nbcols.'" class="right nowrap">';
  3044. print '<span class="opacitymedium">';
  3045. print $form->textwithpicto($langs->trans("ProductReturned"), $langs->trans("HelpAbandonProductReturned"), - 1);
  3046. print '</span>';
  3047. print '</td><td class="right">'.price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaid).'</td><td>&nbsp;</td></tr>';
  3048. $resteapayeraffiche = 0;
  3049. $cssforamountpaymentcomplete = 'amountpaymentneutral';
  3050. }
  3051. // Paye partiellement ou Abandon 'abandon'
  3052. if (($object->statut == FactureFournisseur::STATUS_CLOSED || $object->statut == FactureFournisseur::STATUS_ABANDONED) && $object->close_code == 'abandon') {
  3053. print '<tr><td colspan="'.$nbcols.'" class="right nowrap">';
  3054. $text = $langs->trans("HelpAbandonOther");
  3055. if ($object->close_note) {
  3056. $text .= '<br><br><b>'.$langs->trans("Reason").'</b>:'.$object->close_note;
  3057. }
  3058. print '<span class="opacitymedium">';
  3059. print $form->textwithpicto($langs->trans("Abandoned"), $text, - 1);
  3060. print '</span>';
  3061. print '</td><td class="right">'.price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaid).'</td><td>&nbsp;</td></tr>';
  3062. $resteapayeraffiche = 0;
  3063. $cssforamountpaymentcomplete = 'amountpaymentneutral';
  3064. }
  3065. // Billed
  3066. print '<tr><td colspan="'.$nbcols.'" class="right">';
  3067. print '<span class="opacitymedium">';
  3068. print $langs->trans("Billed");
  3069. print '</span>';
  3070. print '</td><td class="right">'.price($object->total_ttc).'</td><td>&nbsp;</td></tr>';
  3071. // Remainder to pay
  3072. print '<tr><td colspan="'.$nbcols.'" class="right">';
  3073. print '<span class="opacitymedium">';
  3074. print $langs->trans('RemainderToPay');
  3075. if ($resteapayeraffiche < 0) {
  3076. print ' ('.$langs->trans('NegativeIfExcessPaid').')';
  3077. }
  3078. print '</span>';
  3079. print '</td>';
  3080. print '<td class="right'.($resteapayeraffiche ? ' amountremaintopay' : (' '.$cssforamountpaymentcomplete)).'">'.price($resteapayeraffiche).'</td><td>&nbsp;</td></tr>';
  3081. // Remainder to pay Multicurrency
  3082. if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) {
  3083. print '<tr><td colspan="'.$nbcols.'" class="right">';
  3084. print '<span class="opacitymedium">';
  3085. print $langs->trans('RemainderToPayMulticurrency');
  3086. if ($resteapayeraffiche < 0) {
  3087. print ' ('.$langs->trans('NegativeIfExcessPaid').')';
  3088. }
  3089. print '</span>';
  3090. print '</td>';
  3091. print '<td class="right'.($resteapayeraffiche ? ' amountremaintopay' : (' '.$cssforamountpaymentcomplete)).'">'.(!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency).' '.price(price2num($object->multicurrency_tx*$resteapayeraffiche, 'MT')).'</td><td>&nbsp;</td></tr>';
  3092. }
  3093. } else // Credit note
  3094. {
  3095. $cssforamountpaymentcomplete = 'amountpaymentneutral';
  3096. // Total already paid back
  3097. print '<tr><td colspan="'.$nbcols.'" class="right">';
  3098. print $langs->trans('AlreadyPaidBack');
  3099. print ' :</td><td class="right">'.price($sign * $totalpaid).'</td><td>&nbsp;</td></tr>';
  3100. // Billed
  3101. print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans("Billed").' :</td><td class="right">'.price($sign * $object->total_ttc).'</td><td>&nbsp;</td></tr>';
  3102. // Remainder to pay back
  3103. print '<tr><td colspan="'.$nbcols.'" class="right">';
  3104. print '<span class="opacitymedium">';
  3105. print $langs->trans('RemainderToPayBack');
  3106. if ($resteapayeraffiche > 0) {
  3107. print ' ('.$langs->trans('NegativeIfExcessRefunded').')';
  3108. }
  3109. print '</td>';
  3110. print '</span>';
  3111. print '<td class="right'.($resteapayeraffiche ? ' amountremaintopay' : (' '.$cssforamountpaymentcomplete)).'">'.price($sign * $resteapayeraffiche).'</td><td>&nbsp;</td></tr>';
  3112. // Remainder to pay back Multicurrency
  3113. if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) {
  3114. print '<tr><td colspan="'.$nbcols.'" class="right">';
  3115. print '<span class="opacitymedium">';
  3116. print $langs->trans('RemainderToPayBackMulticurrency');
  3117. if ($resteapayeraffiche> 0) {
  3118. print ' ('.$langs->trans('NegativeIfExcessRefunded').')';
  3119. }
  3120. print '</span>';
  3121. print '</td>';
  3122. print '<td class="right'.($resteapayeraffiche ? ' amountremaintopay' : (' '.$cssforamountpaymentcomplete)).'">'.(!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency).' '.price(price2num($sign * $object->multicurrency_tx * $resteapayeraffiche, 'MT')).'</td><td>&nbsp;</td></tr>';
  3123. }
  3124. // Sold credit note
  3125. // print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans('TotalTTC').' :</td>';
  3126. // print '<td class="right" style="border: 1px solid;" bgcolor="#f0f0f0"><b>'.price($sign *
  3127. // $object->total_ttc).'</b></td><td>&nbsp;</td></tr>';
  3128. }
  3129. print '</table>';
  3130. print '</div>';
  3131. print '</div>';
  3132. print '</div>';
  3133. print '<div class="clearboth"></div><br>';
  3134. if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) {
  3135. $blocname = 'contacts';
  3136. $title = $langs->trans('ContactsAddresses');
  3137. include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
  3138. }
  3139. if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) {
  3140. $colwidth = 20;
  3141. $blocname = 'notes';
  3142. $title = $langs->trans('Notes');
  3143. include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
  3144. }
  3145. /*
  3146. * Lines
  3147. */
  3148. print '<form name="addproduct" id="addproduct" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.(($action != 'editline') ? '' : '#line_'.GETPOST('lineid', 'int')).'" method="POST">';
  3149. print '<input type="hidden" name="token" value="'.newToken().'">';
  3150. print '<input type="hidden" name="action" value="'.(($action != 'editline') ? 'addline' : 'updateline').'">';
  3151. print '<input type="hidden" name="mode" value="">';
  3152. print '<input type="hidden" name="page_y" value="">';
  3153. print '<input type="hidden" name="id" value="'.$object->id.'">';
  3154. print '<input type="hidden" name="socid" value="'.$societe->id.'">';
  3155. if (!empty($conf->use_javascript_ajax) && $object->statut == FactureFournisseur::STATUS_DRAFT) {
  3156. include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php';
  3157. }
  3158. print '<div class="div-table-responsive-no-min">';
  3159. print '<table id="tablelines" class="noborder noshadow centpercent">';
  3160. global $forceall, $senderissupplier, $dateSelector, $inputalsopricewithtax;
  3161. $forceall = 1; $dateSelector = 0; $inputalsopricewithtax = 1;
  3162. $senderissupplier = 2; // $senderissupplier=2 is same than 1 but disable test on minimum qty and disable autofill qty with minimum.
  3163. //if (! empty($conf->global->SUPPLIER_INVOICE_WITH_NOPRICEDEFINED)) $senderissupplier=2;
  3164. if (!empty($conf->global->SUPPLIER_INVOICE_WITH_PREDEFINED_PRICES_ONLY)) {
  3165. $senderissupplier = 1;
  3166. }
  3167. // Show object lines
  3168. if (!empty($object->lines)) {
  3169. $ret = $object->printObjectLines($action, $societe, $mysoc, $lineid, 1);
  3170. }
  3171. $num = count($object->lines);
  3172. // Form to add new line
  3173. if ($object->statut == FactureFournisseur::STATUS_DRAFT && $usercancreate) {
  3174. if ($action != 'editline') {
  3175. // Add free products/services
  3176. $parameters = array();
  3177. $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  3178. if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  3179. if (empty($reshook))
  3180. $object->formAddObjectLine(1, $societe, $mysoc);
  3181. }
  3182. }
  3183. print '</table>';
  3184. print '</div>';
  3185. print '</form>';
  3186. print dol_get_fiche_end();
  3187. if ($action != 'presend') {
  3188. /*
  3189. * Buttons actions
  3190. */
  3191. print '<div class="tabsAction">';
  3192. $parameters = array();
  3193. $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been
  3194. // modified by hook
  3195. if (empty($reshook)) {
  3196. // Modify a validated invoice with no payments
  3197. if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $action != 'confirm_edit' && $object->getSommePaiement() == 0 && $usercancreate) {
  3198. // We check if lines of invoice are not already transfered into accountancy
  3199. $ventilExportCompta = $object->getVentilExportCompta(); // Should be 0 since the sum of payments are zero. But we keep the protection.
  3200. if ($ventilExportCompta == 0) {
  3201. print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=edit&token='.newToken().'">'.$langs->trans('Modify').'</a>';
  3202. } else {
  3203. print '<span class="butActionRefused classfortooltip" title="'.$langs->trans("DisabledBecauseDispatchedInBookkeeping").'">'.$langs->trans('Modify').'</span>';
  3204. }
  3205. }
  3206. $discount = new DiscountAbsolute($db);
  3207. $result = $discount->fetch(0, 0, $object->id);
  3208. // Reopen a standard paid invoice
  3209. if (($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_REPLACEMENT
  3210. || ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE && empty($discount->id))
  3211. || ($object->type == FactureFournisseur::TYPE_DEPOSIT && empty($discount->id)))
  3212. && ($object->statut == FactureFournisseur::STATUS_CLOSED || $object->statut == FactureFournisseur::STATUS_ABANDONED)) { // A paid invoice (partially or completely)
  3213. if (!$facidnext && $object->close_code != 'replaced' && $usercancreate) { // Not replaced by another invoice
  3214. print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=reopen&token='.newToken().'">'.$langs->trans('ReOpen').'</a>';
  3215. } else {
  3216. if ($usercancreate) {
  3217. print '<span class="butActionRefused classfortooltip" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('ReOpen').'</span>';
  3218. } elseif (empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED)) {
  3219. print '<span class="butActionRefused classfortooltip">'.$langs->trans('ReOpen').'</span>';
  3220. }
  3221. }
  3222. }
  3223. // Validate
  3224. if ($action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_DRAFT) {
  3225. if (count($object->lines)) {
  3226. if ($usercanvalidate) {
  3227. print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=valid"';
  3228. print '>'.$langs->trans('Validate').'</a>';
  3229. } else {
  3230. print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotAllowed")).'"';
  3231. print '>'.$langs->trans('Validate').'</a>';
  3232. }
  3233. }
  3234. }
  3235. // Send by mail
  3236. if (empty($user->socid)) {
  3237. if (($object->statut == FactureFournisseur::STATUS_VALIDATED || $object->statut == FactureFournisseur::STATUS_CLOSED)) {
  3238. if ($usercansend) {
  3239. print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=presend&mode=init#formmailbeforetitle">'.$langs->trans('SendMail').'</a>';
  3240. } else {
  3241. print '<span class="butActionRefused classfortooltip">'.$langs->trans('SendMail').'</span>';
  3242. }
  3243. }
  3244. }
  3245. // Create payment
  3246. if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0) {
  3247. print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.DOL_URL_ROOT.'/fourn/facture/paiement.php?facid='.$object->id.'&amp;action=create'.($object->fk_account > 0 ? '&amp;accountid='.$object->fk_account : '').'">'.$langs->trans('DoPayment').'</a>'; // must use facid because id is for payment id not invoice
  3248. }
  3249. // Reverse back money or convert to reduction
  3250. if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT || $object->type == FactureFournisseur::TYPE_STANDARD) {
  3251. // For credit note only
  3252. if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE && $object->statut == 1 && $object->paye == 0) {
  3253. if ($resteapayer == 0) {
  3254. print '<span class="butActionRefused classfortooltip" title="'.$langs->trans("DisabledBecauseRemainderToPayIsZero").'">'.$langs->trans('DoPaymentBack').'</span>';
  3255. } else {
  3256. print '<a class="butAction" href="'.DOL_URL_ROOT.'/fourn/facture/paiement.php?facid='.$object->id.'&amp;action=create&amp;accountid='.$object->fk_account.'">'.$langs->trans('DoPaymentBack').'</a>';
  3257. }
  3258. }
  3259. // For standard invoice with excess paid
  3260. if ($object->type == FactureFournisseur::TYPE_STANDARD && empty($object->paye) && ($object->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits) < 0 && $usercancreate && empty($discount->id)) {
  3261. print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=converttoreduc">'.$langs->trans('ConvertExcessPaidToReduc').'</a>';
  3262. }
  3263. // For credit note
  3264. if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE && $object->statut == 1 && $object->paye == 0 && $usercancreate
  3265. && (!empty($conf->global->SUPPLIER_INVOICE_ALLOW_REUSE_OF_CREDIT_WHEN_PARTIALLY_REFUNDED) || $object->getSommePaiement() == 0)
  3266. ) {
  3267. print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=converttoreduc" title="'.dol_escape_htmltag($langs->trans("ConfirmConvertToReducSupplier2")).'">'.$langs->trans('ConvertToReduc').'</a>';
  3268. }
  3269. // For deposit invoice
  3270. if ($object->type == FactureFournisseur::TYPE_DEPOSIT && $usercancreate && $object->statut > 0 && empty($discount->id)) {
  3271. print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=converttoreduc">'.$langs->trans('ConvertToReduc').'</a>';
  3272. }
  3273. }
  3274. // Classify paid
  3275. if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && (
  3276. ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $object->type != FactureFournisseur::TYPE_DEPOSIT && ($resteapayer <= 0 || (!empty($conf->global->SUPPLIER_INVOICE_CAN_SET_PAID_EVEN_IF_PARTIALLY_PAID) && $object->total_ttc == $resteapayer))) ||
  3277. ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE && $resteapayer >= 0) ||
  3278. ($object->type == FactureFournisseur::TYPE_DEPOSIT && $object->total_ttc > 0 && ($resteapayer == 0 || (!empty($conf->global->SUPPLIER_INVOICE_CAN_SET_PAID_EVEN_IF_PARTIALLY_PAID) && $object->total_ttc == $resteapayer)))
  3279. )
  3280. ) {
  3281. print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=paid">'.$langs->trans('ClassifyPaid').'</a>';
  3282. }
  3283. // Classify 'closed not completely paid' (possible if validated and not yet filed paid)
  3284. if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $resteapayer > 0 && (empty($conf->global->SUPPLIER_INVOICE_CAN_SET_PAID_EVEN_IF_PARTIALLY_PAID) || $object->total_ttc != $resteapayer)) {
  3285. if ($totalpaid > 0 || $totalcreditnotes > 0) {
  3286. // If one payment or one credit note was linked to this invoice
  3287. print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=paid">'.$langs->trans('ClassifyPaidPartially').'</a>';
  3288. } else {
  3289. if (empty($conf->global->INVOICE_CAN_NEVER_BE_CANCELED)) {
  3290. print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=canceled">'.$langs->trans('ClassifyCanceled').'</a>';
  3291. }
  3292. }
  3293. }
  3294. // Create event
  3295. /*if ($conf->agenda->enabled && ! empty($conf->global->MAIN_ADD_EVENT_ON_ELEMENT_CARD)) // Add hidden condition because this is not a "workflow" action so should appears somewhere else on page.
  3296. {
  3297. print '<div class="inline-block divButAction"><a class="butAction" href="' . DOL_URL_ROOT . '/comm/action/card.php?action=create&amp;origin=' . $object->element . '&amp;originid=' . $object->id . '&amp;socid=' . $object->socid . '">' . $langs->trans("AddAction") . '</a></div>';
  3298. }*/
  3299. // Create a credit note
  3300. if (($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_DEPOSIT) && $object->statut > 0 && $usercancreate) {
  3301. if (!$objectidnext) {
  3302. print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?socid='.$object->socid.'&amp;fac_avoir='.$object->id.'&amp;action=create&amp;type=2'.($object->fk_project > 0 ? '&amp;projectid='.$object->fk_project : '').'">'.$langs->trans("CreateCreditNote").'</a>';
  3303. }
  3304. }
  3305. // Clone
  3306. if ($action != 'edit' && $usercancreate) {
  3307. print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=clone&amp;socid='.$object->socid.'">'.$langs->trans('ToClone').'</a>';
  3308. }
  3309. // Clone as predefined / Create template
  3310. if (($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_DEPOSIT) && $object->statut == 0 && $usercancreate) {
  3311. if (!$objectidnext && count($object->lines) > 0) {
  3312. print '<a class="butAction" href="'.DOL_URL_ROOT.'/fourn/facture/card-rec.php?facid='.$object->id.'&amp;action=create">'.$langs->trans("ChangeIntoRepeatableInvoice").'</a>';
  3313. }
  3314. }
  3315. // Delete
  3316. $isErasable = $object->is_erasable();
  3317. if ($action != 'confirm_edit' && ($user->rights->fournisseur->facture->supprimer || ($usercancreate && $isErasable == 1))) { // isErasable = 1 means draft with temporary ref (draft can always be deleted with no need of permissions)
  3318. //var_dump($isErasable);
  3319. if ($isErasable == -4) {
  3320. print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecausePayments").'">'.$langs->trans('Delete').'</a>';
  3321. } elseif ($isErasable == -3) { // Should never happen with supplier invoice
  3322. print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecauseNotLastSituationInvoice").'">'.$langs->trans('Delete').'</a>';
  3323. } elseif ($isErasable == -2) { // Should never happen with supplier invoice
  3324. print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecauseNotLastInvoice").'">'.$langs->trans('Delete').'</a>';
  3325. } elseif ($isErasable == -1) {
  3326. print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecauseDispatchedInBookkeeping").'">'.$langs->trans('Delete').'</a>';
  3327. } elseif ($isErasable <= 0) { // Any other cases
  3328. print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecauseNotErasable").'">'.$langs->trans('Delete').'</a>';
  3329. } else {
  3330. print '<a class="butActionDelete'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=delete&token='.newToken().'">'.$langs->trans('Delete').'</a>';
  3331. }
  3332. }
  3333. print '</div>';
  3334. if ($action != 'confirm_edit') {
  3335. print '<div class="fichecenter"><div class="fichehalfleft">';
  3336. /*
  3337. * Generated documents
  3338. */
  3339. $ref = dol_sanitizeFileName($object->ref);
  3340. $subdir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').$ref;
  3341. $filedir = $conf->fournisseur->facture->dir_output.'/'.$subdir;
  3342. $urlsource = $_SERVER['PHP_SELF'].'?id='.$object->id;
  3343. $genallowed = $usercanread;
  3344. $delallowed = $usercancreate;
  3345. $modelpdf = (!empty($object->model_pdf) ? $object->model_pdf : (empty($conf->global->INVOICE_SUPPLIER_ADDON_PDF) ? '' : $conf->global->INVOICE_SUPPLIER_ADDON_PDF));
  3346. print $formfile->showdocuments('facture_fournisseur', $subdir, $filedir, $urlsource, $genallowed, $delallowed, $modelpdf, 1, 0, 0, 40, 0, '', '', '', $societe->default_lang);
  3347. $somethingshown = $formfile->numoffiles;
  3348. // Show links to link elements
  3349. $linktoelem = $form->showLinkToObjectBlock($object, null, array('invoice_supplier'));
  3350. $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem);
  3351. print '</div><div class="fichehalfright">';
  3352. // List of actions on element
  3353. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
  3354. $formactions = new FormActions($db);
  3355. $somethingshown = $formactions->showactions($object, 'invoice_supplier', $socid, 1, 'listaction'.($genallowed ? 'largetitle' : ''));
  3356. print '</div></div>';
  3357. }
  3358. }
  3359. }
  3360. // Select mail models is same action as presend
  3361. if (GETPOST('modelselected')) {
  3362. $action = 'presend';
  3363. }
  3364. // Presend form
  3365. $modelmail = 'invoice_supplier_send';
  3366. $defaulttopic = 'SendBillRef';
  3367. $diroutput = $conf->fournisseur->facture->dir_output;
  3368. $autocopy = 'MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO';
  3369. $trackid = 'sinv'.$object->id;
  3370. include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php';
  3371. }
  3372. }
  3373. // End of page
  3374. llxFooter();
  3375. $db->close();