facture.php 182 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302
  1. <?php
  2. /* Copyright (C) 2002-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
  4. * Copyright (C) 2004-2016 Laurent Destailleur <eldy@users.sourceforge.net>
  5. * Copyright (C) 2005 Marc Barilley / Ocebo <marc@ocebo.com>
  6. * Copyright (C) 2005-2015 Regis Houssin <regis.houssin@capnetworks.com>
  7. * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
  8. * Copyright (C) 2010-2015 Juanjo Menent <jmenent@2byte.es>
  9. * Copyright (C) 2012-2013 Christophe Battarel <christophe.battarel@altairis.fr>
  10. * Copyright (C) 2012-2013 Cédric Salvador <csalvador@gpcsolutions.fr>
  11. * Copyright (C) 2012-2014 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
  12. * Copyright (C) 2013 Jean-Francois FERRY <jfefe@aternatik.fr>
  13. * Copyright (C) 2013-2014 Florian Henry <florian.henry@open-concept.pro>
  14. * Copyright (C) 2013 Cédric Salvador <csalvador@gpcsolutions.fr>
  15. * Copyright (C) 2014 Ferran Marcet <fmarcet@2byte.es>
  16. * Copyright (C) 2015 Marcos García <marcosgdf@gmail.com>
  17. *
  18. * This program is free software; you can redistribute it and/or modify
  19. * it under the terms of the GNU General Public License as published by
  20. * the Free Software Foundation; either version 3 of the License, or
  21. * (at your option) any later version.
  22. *
  23. * This program is distributed in the hope that it will be useful,
  24. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  25. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  26. * GNU General Public License for more details.
  27. *
  28. * You should have received a copy of the GNU General Public License
  29. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  30. */
  31. /**
  32. * \file htdocs/compta/facture.php
  33. * \ingroup facture
  34. * \brief Page to create/see an invoice
  35. */
  36. require '../main.inc.php';
  37. require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
  38. require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture-rec.class.php';
  39. require_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php';
  40. require_once DOL_DOCUMENT_ROOT . '/core/modules/facture/modules_facture.php';
  41. require_once DOL_DOCUMENT_ROOT . '/core/class/discount.class.php';
  42. require_once DOL_DOCUMENT_ROOT . '/core/class/html.formfile.class.php';
  43. require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.php';
  44. require_once DOL_DOCUMENT_ROOT . '/core/class/html.formmargin.class.php';
  45. require_once DOL_DOCUMENT_ROOT . '/core/lib/invoice.lib.php';
  46. require_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php';
  47. require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
  48. require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php';
  49. if (! empty($conf->commande->enabled))
  50. require_once DOL_DOCUMENT_ROOT . '/commande/class/commande.class.php';
  51. if (! empty($conf->projet->enabled)) {
  52. require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
  53. require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php';
  54. }
  55. require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
  56. $langs->load('bills');
  57. $langs->load('companies');
  58. $langs->load('compta');
  59. $langs->load('products');
  60. $langs->load('banks');
  61. $langs->load('main');
  62. if (!empty($conf->incoterm->enabled)) $langs->load('incoterm');
  63. if (! empty($conf->margin->enabled))
  64. $langs->load('margins');
  65. $projectid = (GETPOST('projectid') ? GETPOST('projectid', 'int') : 0);
  66. $id = (GETPOST('id', 'int') ? GETPOST('id', 'int') : GETPOST('facid', 'int')); // For backward compatibility
  67. $ref = GETPOST('ref', 'alpha');
  68. $socid = GETPOST('socid', 'int');
  69. $action = GETPOST('action', 'alpha');
  70. $confirm = GETPOST('confirm', 'alpha');
  71. $cancel = GETPOST('cancel', 'alpha');
  72. $lineid = GETPOST('lineid', 'int');
  73. $userid = GETPOST('userid', 'int');
  74. $search_ref = GETPOST('sf_ref') ? GETPOST('sf_ref', 'alpha') : GETPOST('search_ref', 'alpha');
  75. $search_societe = GETPOST('search_societe', 'alpha');
  76. $search_montant_ht = GETPOST('search_montant_ht', 'alpha');
  77. $search_montant_ttc = GETPOST('search_montant_ttc', 'alpha');
  78. $origin = GETPOST('origin', 'alpha');
  79. $originid = (GETPOST('originid', 'int') ? GETPOST('originid', 'int') : GETPOST('origin_id', 'int')); // For backward compatibility
  80. $fac_rec=GETPOST('fac_rec','int');
  81. // PDF
  82. $hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0));
  83. $hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc', 'int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0));
  84. $hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref', 'int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0));
  85. // Security check
  86. $fieldid = (! empty($ref) ? 'facnumber' : 'rowid');
  87. if ($user->societe_id) $socid = $user->societe_id;
  88. $result = restrictedArea($user, 'facture', $id, '', '', 'fk_soc', $fieldid);
  89. // Nombre de ligne pour choix de produit/service predefinis
  90. $NBLINES = 4;
  91. $usehm = (! empty($conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE) ? $conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE : 0);
  92. $object = new Facture($db);
  93. $extrafields = new ExtraFields($db);
  94. // Load object
  95. if ($id > 0 || ! empty($ref)) {
  96. $ret = $object->fetch($id, $ref, '', '', $conf->global->INVOICE_USE_SITUATION);
  97. }
  98. // Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array
  99. $hookmanager->initHooks(array('invoicecard','globalcard'));
  100. $permissionnote = $user->rights->facture->creer; // Used by the include of actions_setnotes.inc.php
  101. $permissiondellink=$user->rights->facture->creer; // Used by the include of actions_dellink.inc.php
  102. $permissiontoedit = $user->rights->facture->creer; // Used by the include of actions_lineupdonw.inc.php
  103. /*
  104. * Actions
  105. */
  106. $parameters = array('socid' => $socid);
  107. $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  108. if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  109. if (empty($reshook))
  110. {
  111. if ($cancel) $action='';
  112. include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once
  113. include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once
  114. include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once
  115. // Action clone object
  116. if ($action == 'confirm_clone' && $confirm == 'yes' && $user->rights->facture->creer) {
  117. // if (1 == 0 && empty($_REQUEST["clone_content"]) && empty($_REQUEST["clone_receivers"])) {
  118. // $mesgs [] = '<div class="error">' . $langs->trans("NoCloneOptionsSpecified") . '</div>';
  119. // } else {
  120. if ($object->fetch($id) > 0) {
  121. $result = $object->createFromClone($socid);
  122. if ($result > 0) {
  123. header("Location: " . $_SERVER['PHP_SELF'] . '?facid=' . $result);
  124. exit();
  125. } else {
  126. setEventMessages($object->error, $object->errors, 'errors');
  127. $action = '';
  128. }
  129. }
  130. // }
  131. }
  132. // Change status of invoice
  133. else if ($action == 'reopen' && $user->rights->facture->creer) {
  134. $result = $object->fetch($id);
  135. if ($object->statut == 2 || ($object->statut == 3 && $object->close_code != 'replaced') || ($object->statut == 1 && $object->paye == 1)) { // ($object->statut == 1 && $object->paye == 1) should not happened but can be found when data are corrupted
  136. $result = $object->set_unpaid($user);
  137. if ($result > 0) {
  138. header('Location: ' . $_SERVER["PHP_SELF"] . '?facid=' . $id);
  139. exit();
  140. } else {
  141. setEventMessages($object->error, $object->errors, 'errors');
  142. }
  143. }
  144. }
  145. // Delete invoice
  146. else if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->facture->supprimer) {
  147. $result = $object->fetch($id);
  148. $object->fetch_thirdparty();
  149. $idwarehouse = GETPOST('idwarehouse');
  150. $qualified_for_stock_change = 0;
  151. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  152. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  153. } else {
  154. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  155. }
  156. $result = $object->delete($user, 0, $idwarehouse);
  157. if ($result > 0) {
  158. header('Location: ' . DOL_URL_ROOT . '/compta/facture/list.php');
  159. exit();
  160. } else {
  161. setEventMessages($object->error, $object->errors, 'errors');
  162. $action='';
  163. }
  164. }
  165. // Delete line
  166. else if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->facture->creer)
  167. {
  168. $object->fetch($id);
  169. $object->fetch_thirdparty();
  170. $result = $object->deleteline(GETPOST('lineid'));
  171. if ($result > 0) {
  172. // Define output language
  173. $outputlangs = $langs;
  174. $newlang = '';
  175. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id']))
  176. $newlang = $_REQUEST['lang_id'];
  177. if ($conf->global->MAIN_MULTILANGS && empty($newlang))
  178. $newlang = $object->thirdparty->default_lang;
  179. if (! empty($newlang)) {
  180. $outputlangs = new Translate("", $conf);
  181. $outputlangs->setDefaultLang($newlang);
  182. }
  183. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  184. $ret = $object->fetch($id); // Reload to get new records
  185. $result = $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  186. }
  187. if ($result >= 0) {
  188. header('Location: ' . $_SERVER["PHP_SELF"] . '?facid=' . $id);
  189. exit();
  190. }
  191. } else {
  192. setEventMessages($object->error, $object->errors, 'errors');
  193. $action = '';
  194. }
  195. }
  196. // Delete link of credit note to invoice
  197. else if ($action == 'unlinkdiscount' && $user->rights->facture->creer)
  198. {
  199. $discount = new DiscountAbsolute($db);
  200. $result = $discount->fetch(GETPOST("discountid"));
  201. $discount->unlink_invoice();
  202. }
  203. // Validation
  204. else if ($action == 'valid' && $user->rights->facture->creer)
  205. {
  206. $object->fetch($id);
  207. // On verifie signe facture
  208. if ($object->type == Facture::TYPE_CREDIT_NOTE) {
  209. // Si avoir, le signe doit etre negatif
  210. if ($object->total_ht >= 0) {
  211. setEventMessages($langs->trans("ErrorInvoiceAvoirMustBeNegative"), null, 'errors');
  212. $action = '';
  213. }
  214. } else {
  215. // Si non avoir, le signe doit etre positif
  216. if (empty($conf->global->FACTURE_ENABLE_NEGATIVE) && $object->total_ht < 0) {
  217. setEventMessages($langs->trans("ErrorInvoiceOfThisTypeMustBePositive"), null, 'errors');
  218. $action = '';
  219. }
  220. }
  221. }
  222. else if ($action == 'set_thirdparty' && $user->rights->facture->creer)
  223. {
  224. $object->fetch($id);
  225. $object->setValueFrom('fk_soc', $socid, '', null, 'int', '', $user, 'BILL_MODIFY');
  226. header('Location: ' . $_SERVER["PHP_SELF"] . '?facid=' . $id);
  227. exit();
  228. }
  229. else if ($action == 'classin' && $user->rights->facture->creer)
  230. {
  231. $object->fetch($id);
  232. $object->setProject($_POST['projectid']);
  233. }
  234. else if ($action == 'setmode' && $user->rights->facture->creer)
  235. {
  236. $object->fetch($id);
  237. $result = $object->setPaymentMethods(GETPOST('mode_reglement_id', 'int'));
  238. if ($result < 0)
  239. dol_print_error($db, $object->error);
  240. }
  241. // Multicurrency Code
  242. else if ($action == 'setmulticurrencycode' && $user->rights->facture->creer) {
  243. $result = $object->setMulticurrencyCode(GETPOST('multicurrency_code', 'alpha'));
  244. }
  245. // Multicurrency rate
  246. else if ($action == 'setmulticurrencyrate' && $user->rights->facture->creer) {
  247. $result = $object->setMulticurrencyRate(price2num(GETPOST('multicurrency_tx')), GETPOST('calculation_mode', 'int'));
  248. }
  249. else if ($action == 'setinvoicedate' && $user->rights->facture->creer)
  250. {
  251. $object->fetch($id);
  252. $old_date_lim_reglement = $object->date_lim_reglement;
  253. $date = dol_mktime(12, 0, 0, $_POST['invoicedatemonth'], $_POST['invoicedateday'], $_POST['invoicedateyear']);
  254. if (empty($date))
  255. {
  256. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
  257. header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$id.'&action=editinvoicedate');
  258. exit;
  259. }
  260. $object->date=$date;
  261. $new_date_lim_reglement = $object->calculate_date_lim_reglement();
  262. if ($new_date_lim_reglement > $old_date_lim_reglement) $object->date_lim_reglement = $new_date_lim_reglement;
  263. if ($object->date_lim_reglement < $object->date) $object->date_lim_reglement = $object->date;
  264. $result = $object->update($user);
  265. if ($result < 0) dol_print_error($db, $object->error);
  266. }
  267. else if ($action == 'setdate_pointoftax' && $user->rights->facture->creer)
  268. {
  269. $object->fetch($id);
  270. $date_pointoftax = dol_mktime(12, 0, 0, $_POST['date_pointoftaxmonth'], $_POST['date_pointoftaxday'], $_POST['date_pointoftaxyear']);
  271. $object->date_pointoftax=$date_pointoftax;
  272. $result = $object->update($user);
  273. if ($result < 0) dol_print_error($db, $object->error);
  274. }
  275. else if ($action == 'setconditions' && $user->rights->facture->creer)
  276. {
  277. $object->fetch($id);
  278. $object->cond_reglement_code = 0; // To clean property
  279. $object->cond_reglement_id = 0; // To clean property
  280. $result = $object->setPaymentTerms(GETPOST('cond_reglement_id', 'int'));
  281. if ($result < 0) dol_print_error($db, $object->error);
  282. $old_date_lim_reglement = $object->date_lim_reglement;
  283. $new_date_lim_reglement = $object->calculate_date_lim_reglement();
  284. if ($new_date_lim_reglement > $old_date_lim_reglement) $object->date_lim_reglement = $new_date_lim_reglement;
  285. if ($object->date_lim_reglement < $object->date) $object->date_lim_reglement = $object->date;
  286. $result = $object->update($user);
  287. if ($result < 0) dol_print_error($db, $object->error);
  288. }
  289. else if ($action == 'setpaymentterm' && $user->rights->facture->creer)
  290. {
  291. $object->fetch($id);
  292. $object->date_lim_reglement = dol_mktime(12, 0, 0, $_POST['paymenttermmonth'], $_POST['paymenttermday'], $_POST['paymenttermyear']);
  293. if ($object->date_lim_reglement < $object->date) {
  294. $object->date_lim_reglement = $object->calculate_date_lim_reglement();
  295. setEventMessages($langs->trans("DatePaymentTermCantBeLowerThanObjectDate"), null, 'warnings');
  296. }
  297. $result = $object->update($user);
  298. if ($result < 0)
  299. dol_print_error($db, $object->error);
  300. }
  301. else if ($action == 'setrevenuestamp' && $user->rights->facture->creer)
  302. {
  303. $object->fetch($id);
  304. $object->revenuestamp = GETPOST('revenuestamp');
  305. $result = $object->update($user);
  306. $object->update_price(1);
  307. if ($result < 0)
  308. dol_print_error($db, $object->error);
  309. }
  310. // Set incoterm
  311. elseif ($action == 'set_incoterms' && !empty($conf->incoterm->enabled))
  312. {
  313. $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha'));
  314. }
  315. // bank account
  316. else if ($action == 'setbankaccount' && $user->rights->facture->creer)
  317. {
  318. $result=$object->setBankAccount(GETPOST('fk_account', 'int'));
  319. }
  320. else if ($action == 'setremisepercent' && $user->rights->facture->creer)
  321. {
  322. $object->fetch($id);
  323. $result = $object->set_remise($user, $_POST['remise_percent']);
  324. }
  325. else if ($action == "setabsolutediscount" && $user->rights->facture->creer)
  326. {
  327. // POST[remise_id] ou POST[remise_id_for_payment]
  328. if (! empty($_POST["remise_id"])) {
  329. $ret = $object->fetch($id);
  330. if ($ret > 0) {
  331. $result = $object->insert_discount($_POST["remise_id"]);
  332. if ($result < 0) {
  333. setEventMessages($object->error, $object->errors, 'errors');
  334. }
  335. } else {
  336. dol_print_error($db, $object->error);
  337. }
  338. }
  339. if (! empty($_POST["remise_id_for_payment"])) {
  340. require_once DOL_DOCUMENT_ROOT . '/core/class/discount.class.php';
  341. $discount = new DiscountAbsolute($db);
  342. $discount->fetch($_POST["remise_id_for_payment"]);
  343. $result = $discount->link_to_invoice(0, $id);
  344. if ($result < 0) {
  345. setEventMessages($discount->error, $discount->errors, 'errors');
  346. }
  347. }
  348. }
  349. else if ($action == 'setref_client' && $user->rights->facture->creer)
  350. {
  351. $object->fetch($id);
  352. $object->set_ref_client(GETPOST('ref_client'));
  353. }
  354. // Classify to validated
  355. else if ($action == 'confirm_valid' && $confirm == 'yes' &&
  356. ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer))
  357. || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->validate)))
  358. )
  359. {
  360. $idwarehouse = GETPOST('idwarehouse');
  361. $object->fetch($id);
  362. $object->fetch_thirdparty();
  363. // Check parameters
  364. // Check for mandatory prof id (but only if country is than than ours)
  365. if ($mysoc->country_id > 0 && $object->thirdparty->country_id == $mysoc->country_id)
  366. {
  367. for ($i = 1; $i <= 6; $i++)
  368. {
  369. $idprof_mandatory = 'SOCIETE_IDPROF' . ($i) . '_INVOICE_MANDATORY';
  370. $idprof = 'idprof' . $i;
  371. if (! $object->thirdparty->$idprof && ! empty($conf->global->$idprof_mandatory))
  372. {
  373. if (! $error) $langs->load("errors");
  374. $error++;
  375. setEventMessages($langs->trans('ErrorProdIdIsMandatory', $langs->transcountry('ProfId' . $i, $object->thirdparty->country_code)), null, 'errors');
  376. }
  377. }
  378. }
  379. $qualified_for_stock_change = 0;
  380. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  381. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  382. } else {
  383. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  384. }
  385. // Check for warehouse
  386. if ($object->type != Facture::TYPE_DEPOSIT && ! empty($conf->global->STOCK_CALCULATE_ON_BILL) && $qualified_for_stock_change)
  387. {
  388. if (! $idwarehouse || $idwarehouse == - 1) {
  389. $error ++;
  390. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
  391. $action = '';
  392. }
  393. }
  394. if (! $error)
  395. {
  396. $result = $object->validate($user, '', $idwarehouse);
  397. if ($result >= 0)
  398. {
  399. // Define output language
  400. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
  401. {
  402. $outputlangs = $langs;
  403. $newlang = '';
  404. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id','alpha');
  405. if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
  406. if (! empty($newlang)) {
  407. $outputlangs = new Translate("", $conf);
  408. $outputlangs->setDefaultLang($newlang);
  409. }
  410. $model=$object->modelpdf;
  411. $ret = $object->fetch($id); // Reload to get new records
  412. $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  413. if ($result < 0) setEventMessages($object->error, $object->errors, 'errors');
  414. }
  415. }
  416. else
  417. {
  418. if (count($object->errors)) setEventMessages(null, $object->errors, 'errors');
  419. else setEventMessages($object->error, $object->errors, 'errors');
  420. }
  421. }
  422. }
  423. // Go back to draft status (unvalidate)
  424. else if ($action == 'confirm_modif' &&
  425. ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer))
  426. || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->unvalidate)))
  427. )
  428. {
  429. $idwarehouse = GETPOST('idwarehouse');
  430. $object->fetch($id);
  431. $object->fetch_thirdparty();
  432. $qualified_for_stock_change = 0;
  433. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  434. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  435. } else {
  436. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  437. }
  438. // Check parameters
  439. if ($object->type != Facture::TYPE_DEPOSIT && ! empty($conf->global->STOCK_CALCULATE_ON_BILL) && $qualified_for_stock_change)
  440. {
  441. if (! $idwarehouse || $idwarehouse == - 1) {
  442. $error ++;
  443. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
  444. $action = '';
  445. }
  446. }
  447. if (! $error) {
  448. // On verifie si la facture a des paiements
  449. $sql = 'SELECT pf.amount';
  450. $sql .= ' FROM ' . MAIN_DB_PREFIX . 'paiement_facture as pf';
  451. $sql .= ' WHERE pf.fk_facture = ' . $object->id;
  452. $result = $db->query($sql);
  453. if ($result) {
  454. $i = 0;
  455. $num = $db->num_rows($result);
  456. while ($i < $num) {
  457. $objp = $db->fetch_object($result);
  458. $totalpaye += $objp->amount;
  459. $i ++;
  460. }
  461. } else {
  462. dol_print_error($db, '');
  463. }
  464. $resteapayer = $object->total_ttc - $totalpaye;
  465. // On verifie si les lignes de factures ont ete exportees en compta et/ou ventilees
  466. $ventilExportCompta = $object->getVentilExportCompta();
  467. // On verifie si aucun paiement n'a ete effectue
  468. if ($resteapayer == $object->total_ttc && $object->paye == 0 && $ventilExportCompta == 0)
  469. {
  470. $result=$object->set_draft($user, $idwarehouse);
  471. if ($result<0) setEventMessages($object->error, $object->errors, 'errors');
  472. // Define output language
  473. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
  474. {
  475. $outputlangs = $langs;
  476. $newlang = '';
  477. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id','alpha');
  478. if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
  479. if (! empty($newlang)) {
  480. $outputlangs = new Translate("", $conf);
  481. $outputlangs->setDefaultLang($newlang);
  482. }
  483. $model=$object->modelpdf;
  484. $ret = $object->fetch($id); // Reload to get new records
  485. $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  486. }
  487. }
  488. }
  489. }
  490. // Classify "paid"
  491. else if ($action == 'confirm_paid' && $confirm == 'yes' && $user->rights->facture->paiement)
  492. {
  493. $object->fetch($id);
  494. $result = $object->set_paid($user);
  495. if ($result<0) setEventMessages($object->error, $object->errors, 'errors');
  496. } // Classif "paid partialy"
  497. else if ($action == 'confirm_paid_partially' && $confirm == 'yes' && $user->rights->facture->paiement)
  498. {
  499. $object->fetch($id);
  500. $close_code = $_POST["close_code"];
  501. $close_note = $_POST["close_note"];
  502. if ($close_code) {
  503. $result = $object->set_paid($user, $close_code, $close_note);
  504. if ($result<0) setEventMessages($object->error, $object->errors, 'errors');
  505. } else {
  506. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Reason")), null, 'errors');
  507. }
  508. } // Classify "abandoned"
  509. else if ($action == 'confirm_canceled' && $confirm == 'yes') {
  510. $object->fetch($id);
  511. $close_code = $_POST["close_code"];
  512. $close_note = $_POST["close_note"];
  513. if ($close_code) {
  514. $result = $object->set_canceled($user, $close_code, $close_note);
  515. if ($result<0) setEventMessages($object->error, $object->errors, 'errors');
  516. } else {
  517. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Reason")), null, 'errors');
  518. }
  519. }
  520. // Convertir en reduc
  521. else if ($action == 'confirm_converttoreduc' && $confirm == 'yes' && $user->rights->facture->creer)
  522. {
  523. $object->fetch($id);
  524. $object->fetch_thirdparty();
  525. //$object->fetch_lines(); // Already done into fetch
  526. // Check if there is already a discount (protection to avoid duplicate creation when resubmit post)
  527. $discountcheck=new DiscountAbsolute($db);
  528. $result=$discountcheck->fetch(0,$object->id);
  529. $canconvert=0;
  530. if ($object->type == Facture::TYPE_DEPOSIT && $object->paye == 1 && empty($discountcheck->id)) $canconvert=1; // we can convert deposit into discount if deposit is payed completely and not already converted (see real condition into condition used to show button converttoreduc)
  531. if ($object->type == Facture::TYPE_CREDIT_NOTE && $object->paye == 0 && empty($discountcheck->id)) $canconvert=1; // we can convert credit note into discount if credit note is not payed back and not already converted and amount of payment is 0 (see real condition into condition used to show button converttoreduc)
  532. if ($canconvert)
  533. {
  534. $db->begin();
  535. // Boucle sur chaque taux de tva
  536. $i = 0;
  537. foreach ($object->lines as $line)
  538. {
  539. if ($line->total_ht!=0)
  540. { // no need to create discount if amount is null
  541. $amount_ht[$line->tva_tx] += $line->total_ht;
  542. $amount_tva[$line->tva_tx] += $line->total_tva;
  543. $amount_ttc[$line->tva_tx] += $line->total_ttc;
  544. $i ++;
  545. }
  546. }
  547. // Insert one discount by VAT rate category
  548. $discount = new DiscountAbsolute($db);
  549. if ($object->type == Facture::TYPE_CREDIT_NOTE)
  550. $discount->description = '(CREDIT_NOTE)';
  551. elseif ($object->type == Facture::TYPE_DEPOSIT)
  552. $discount->description = '(DEPOSIT)';
  553. else {
  554. setEventMessages($langs->trans('CantConvertToReducAnInvoiceOfThisType'), null, 'errors');
  555. }
  556. $discount->tva_tx = abs($object->total_ttc);
  557. $discount->fk_soc = $object->socid;
  558. $discount->fk_facture_source = $object->id;
  559. $error = 0;
  560. foreach ($amount_ht as $tva_tx => $xxx)
  561. {
  562. $discount->amount_ht = abs($amount_ht[$tva_tx]);
  563. $discount->amount_tva = abs($amount_tva[$tva_tx]);
  564. $discount->amount_ttc = abs($amount_ttc[$tva_tx]);
  565. $discount->tva_tx = abs($tva_tx);
  566. $result = $discount->create($user);
  567. if ($result < 0)
  568. {
  569. $error++;
  570. break;
  571. }
  572. }
  573. if (empty($error))
  574. {
  575. // Classe facture
  576. $result = $object->set_paid($user);
  577. if ($result >= 0)
  578. {
  579. $db->commit();
  580. }
  581. else
  582. {
  583. setEventMessages($object->error, $object->errors, 'errors');
  584. $db->rollback();
  585. }
  586. }
  587. else
  588. {
  589. setEventMessages($discount->error, $discount->errors, 'errors');
  590. $db->rollback();
  591. }
  592. }
  593. }
  594. /*
  595. * Insert new invoice in database
  596. */
  597. else if ($action == 'add' && $user->rights->facture->creer)
  598. {
  599. if ($socid > 0) $object->socid = GETPOST('socid', 'int');
  600. $db->begin();
  601. $error = 0;
  602. // Fill array 'array_options' with data from add form
  603. $extralabels = $extrafields->fetch_name_optionals_label($object->table_element);
  604. $ret = $extrafields->setOptionalsFromPost($extralabels, $object);
  605. if ($ret < 0) $error++;
  606. // Replacement invoice
  607. if ($_POST['type'] == Facture::TYPE_REPLACEMENT)
  608. {
  609. $dateinvoice = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']);
  610. if (empty($dateinvoice))
  611. {
  612. $error++;
  613. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
  614. }
  615. if (! ($_POST['fac_replacement'] > 0)) {
  616. $error ++;
  617. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ReplaceInvoice")), null, 'errors');
  618. }
  619. $date_pointoftax = dol_mktime(12, 0, 0, $_POST['date_pointoftaxmonth'], $_POST['date_pointoftaxday'], $_POST['date_pointoftaxyear']);
  620. if (! $error) {
  621. // This is a replacement invoice
  622. $result = $object->fetch($_POST['fac_replacement']);
  623. $object->fetch_thirdparty();
  624. $object->date = $dateinvoice;
  625. $object->date_pointoftax = $date_pointoftax;
  626. $object->note_public = trim($_POST['note_public']);
  627. $object->note = trim($_POST['note']);
  628. $object->ref_client = $_POST['ref_client'];
  629. $object->ref_int = $_POST['ref_int'];
  630. $object->modelpdf = $_POST['model'];
  631. $object->fk_project = $_POST['projectid'];
  632. $object->cond_reglement_id = $_POST['cond_reglement_id'];
  633. $object->mode_reglement_id = $_POST['mode_reglement_id'];
  634. $object->fk_account = GETPOST('fk_account', 'int');
  635. $object->remise_absolue = $_POST['remise_absolue'];
  636. $object->remise_percent = $_POST['remise_percent'];
  637. $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  638. $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  639. $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  640. $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
  641. // Proprietes particulieres a facture de remplacement
  642. $object->fk_facture_source = $_POST['fac_replacement'];
  643. $object->type = Facture::TYPE_REPLACEMENT;
  644. $id = $object->createFromCurrent($user);
  645. if ($id <= 0) {
  646. setEventMessages($object->error, $object->errors, 'errors');
  647. }
  648. }
  649. }
  650. // Credit note invoice
  651. if ($_POST['type'] == Facture::TYPE_CREDIT_NOTE)
  652. {
  653. $sourceinvoice = GETPOST('fac_avoir');
  654. if (! ($sourceinvoice > 0) && empty($conf->global->INVOICE_CREDIT_NOTE_STANDALONE))
  655. {
  656. $error ++;
  657. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CorrectInvoice")), null, 'errors');
  658. }
  659. $dateinvoice = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']);
  660. if (empty($dateinvoice))
  661. {
  662. $error ++;
  663. setEventMessages($langs->trans("ErrorFieldRequired", $langs->trans("Date")), null, 'errors');
  664. }
  665. $date_pointoftax = dol_mktime(12, 0, 0, $_POST['date_pointoftaxmonth'], $_POST['date_pointoftaxday'], $_POST['date_pointoftaxyear']);
  666. if (! $error)
  667. {
  668. $object->socid = GETPOST('socid','int');
  669. $object->number = $_POST['facnumber'];
  670. $object->date = $dateinvoice;
  671. $object->date_pointoftax = $date_pointoftax;
  672. $object->note_public = trim($_POST['note_public']);
  673. $object->note = trim($_POST['note']);
  674. $object->ref_client = $_POST['ref_client'];
  675. $object->ref_int = $_POST['ref_int'];
  676. $object->modelpdf = $_POST['model'];
  677. $object->fk_project = $_POST['projectid'];
  678. $object->cond_reglement_id = 0;
  679. $object->mode_reglement_id = $_POST['mode_reglement_id'];
  680. $object->fk_account = GETPOST('fk_account', 'int');
  681. $object->remise_absolue = $_POST['remise_absolue'];
  682. $object->remise_percent = $_POST['remise_percent'];
  683. $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  684. $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  685. $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  686. $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
  687. // Proprietes particulieres a facture avoir
  688. $object->fk_facture_source = $sourceinvoice > 0 ? $sourceinvoice : '';
  689. $object->type = Facture::TYPE_CREDIT_NOTE;
  690. $id = $object->create($user);
  691. if (GETPOST('invoiceAvoirWithLines', 'int')==1 && $id>0)
  692. {
  693. $facture_source = new Facture($db); // fetch origin object
  694. if ($facture_source->fetch($object->fk_facture_source)>0)
  695. {
  696. $fk_parent_line = 0;
  697. foreach($facture_source->lines as $line)
  698. {
  699. // Reset fk_parent_line for no child products and special product
  700. if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
  701. $fk_parent_line = 0;
  702. }
  703. $line->fk_facture = $object->id;
  704. $line->fk_parent_line = $fk_parent_line;
  705. $line->subprice =-$line->subprice; // invert price for object
  706. $line->pa_ht = $line->pa_ht; // we choosed to have buy/cost price always positive, so no revert of sign here
  707. $line->total_ht=-$line->total_ht;
  708. $line->total_tva=-$line->total_tva;
  709. $line->total_ttc=-$line->total_ttc;
  710. $line->total_localtax1=-$line->total_localtax1;
  711. $line->total_localtax2=-$line->total_localtax2;
  712. $result = $line->insert(0, 1); // When creating credit note with same lines than source, we must ignore error if discount alreayd linked
  713. $object->lines[] = $line; // insert new line in current object
  714. // Defined the new fk_parent_line
  715. if ($result > 0 && $line->product_type == 9) {
  716. $fk_parent_line = $result;
  717. }
  718. }
  719. $object->update_price(1);
  720. }
  721. }
  722. if(GETPOST('invoiceAvoirWithPaymentRestAmount', 'int')==1 && $id>0)
  723. {
  724. $facture_source = new Facture($db); // fetch origin object if not previously defined
  725. if ($facture_source->fetch($object->fk_facture_source)>0)
  726. {
  727. $totalpaye = $facture_source->getSommePaiement();
  728. $totalcreditnotes = $facture_source->getSumCreditNotesUsed();
  729. $totaldeposits = $facture_source->getSumDepositsUsed();
  730. $remain_to_pay = abs($facture_source->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits);
  731. $object->addline($langs->trans('invoiceAvoirLineWithPaymentRestAmount'),$remain_to_pay,1,0,0,0,0,0,'','','TTC');
  732. }
  733. }
  734. // Add predefined lines
  735. /*
  736. TODO delete
  737. for($i = 1; $i <= $NBLINES; $i ++) {
  738. if ($_POST['idprod' . $i]) {
  739. $product = new Product($db);
  740. $product->fetch($_POST['idprod' . $i]);
  741. $startday = dol_mktime(12, 0, 0, $_POST['date_start' . $i . 'month'], $_POST['date_start' . $i . 'day'], $_POST['date_start' . $i . 'year']);
  742. $endday = dol_mktime(12, 0, 0, $_POST['date_end' . $i . 'month'], $_POST['date_end' . $i . 'day'], $_POST['date_end' . $i . 'year']);
  743. $result = $object->addline($product->description, $product->price, $_POST['qty' . $i], $product->tva_tx, $product->localtax1_tx, $product->localtax2_tx, $_POST['idprod' . $i], $_POST['remise_percent' . $i], $startday, $endday, 0, 0, '', $product->price_base_type, $product->price_ttc, $product->type);
  744. }
  745. }*/
  746. }
  747. }
  748. // Standard invoice or Deposit invoice, created from a Predefined template invoice
  749. if (($_POST['type'] == Facture::TYPE_STANDARD || $_POST['type'] == Facture::TYPE_DEPOSIT) && GETPOST('fac_rec') > 0)
  750. {
  751. $dateinvoice = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']);
  752. if (empty($dateinvoice))
  753. {
  754. $error++;
  755. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
  756. }
  757. $date_pointoftax = dol_mktime(12, 0, 0, $_POST['date_pointoftaxmonth'], $_POST['date_pointoftaxday'], $_POST['date_pointoftaxyear']);
  758. if (! $error)
  759. {
  760. $object->socid = GETPOST('socid','int');
  761. $object->type = $_POST['type'];
  762. $object->number = $_POST['facnumber'];
  763. $object->date = $dateinvoice;
  764. $object->date_pointoftax = $date_pointoftax;
  765. $object->note_public = trim($_POST['note_public']);
  766. $object->note_private = trim($_POST['note_private']);
  767. $object->ref_client = $_POST['ref_client'];
  768. $object->ref_int = $_POST['ref_int'];
  769. $object->modelpdf = $_POST['model'];
  770. $object->fk_project = $_POST['projectid'];
  771. $object->cond_reglement_id = ($_POST['type'] == 3?1:$_POST['cond_reglement_id']);
  772. $object->mode_reglement_id = $_POST['mode_reglement_id'];
  773. $object->fk_account = GETPOST('fk_account', 'int');
  774. $object->amount = $_POST['amount'];
  775. $object->remise_absolue = $_POST['remise_absolue'];
  776. $object->remise_percent = $_POST['remise_percent'];
  777. $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  778. $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  779. $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  780. $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
  781. // Source facture
  782. $object->fac_rec = GETPOST('fac_rec');
  783. $id = $object->create($user); // This include recopy of links from recurring invoice
  784. }
  785. }
  786. // Standard or deposit or proforma invoice, not from a Predefined template invoice
  787. if (($_POST['type'] == Facture::TYPE_STANDARD || $_POST['type'] == Facture::TYPE_DEPOSIT || $_POST['type'] == Facture::TYPE_PROFORMA || ($_POST['type'] == Facture::TYPE_SITUATION && empty($_POST['situations']))) && GETPOST('fac_rec') <= 0)
  788. {
  789. if (GETPOST('socid', 'int') < 1)
  790. {
  791. $error ++;
  792. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Customer")), null, 'errors');
  793. }
  794. $dateinvoice = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']);
  795. if (empty($dateinvoice))
  796. {
  797. $error++;
  798. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
  799. }
  800. $date_pointoftax = dol_mktime(12, 0, 0, $_POST['date_pointoftaxmonth'], $_POST['date_pointoftaxday'], $_POST['date_pointoftaxyear']);
  801. if (! $error)
  802. {
  803. // Si facture standard
  804. $object->socid = GETPOST('socid','int');
  805. $object->type = GETPOST('type');
  806. $object->number = $_POST['facnumber'];
  807. $object->date = $dateinvoice;
  808. $object->date_pointoftax = $date_pointoftax;
  809. $object->note_public = trim($_POST['note_public']);
  810. $object->note_private = trim($_POST['note_private']);
  811. $object->ref_client = $_POST['ref_client'];
  812. $object->ref_int = $_POST['ref_int'];
  813. $object->modelpdf = $_POST['model'];
  814. $object->fk_project = $_POST['projectid'];
  815. $object->cond_reglement_id = ($_POST['type'] == 3?1:$_POST['cond_reglement_id']);
  816. $object->mode_reglement_id = $_POST['mode_reglement_id'];
  817. $object->fk_account = GETPOST('fk_account', 'int');
  818. $object->amount = $_POST['amount'];
  819. $object->remise_absolue = $_POST['remise_absolue'];
  820. $object->remise_percent = $_POST['remise_percent'];
  821. $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  822. $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  823. $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  824. $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
  825. if (GETPOST('type') == Facture::TYPE_SITUATION)
  826. {
  827. $object->situation_counter = 1;
  828. $object->situation_final = 0;
  829. $object->situation_cycle_ref = $object->newCycle();
  830. }
  831. $object->fetch_thirdparty();
  832. // If creation from another object of another module (Example: origin=propal, originid=1)
  833. if (! empty($origin) && ! empty($originid))
  834. {
  835. // Parse element/subelement (ex: project_task)
  836. $element = $subelement = $origin;
  837. if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs)) {
  838. $element = $regs [1];
  839. $subelement = $regs [2];
  840. }
  841. // For compatibility
  842. if ($element == 'order') {
  843. $element = $subelement = 'commande';
  844. }
  845. if ($element == 'propal') {
  846. $element = 'comm/propal';
  847. $subelement = 'propal';
  848. }
  849. if ($element == 'contract') {
  850. $element = $subelement = 'contrat';
  851. }
  852. if ($element == 'inter') {
  853. $element = $subelement = 'ficheinter';
  854. }
  855. if ($element == 'shipping') {
  856. $element = $subelement = 'expedition';
  857. }
  858. $object->origin = $origin;
  859. $object->origin_id = $originid;
  860. // Possibility to add external linked objects with hooks
  861. $object->linked_objects[$object->origin] = $object->origin_id;
  862. // link with order if it is a shipping invoice
  863. if ($object->origin == 'shipping')
  864. {
  865. require_once DOL_DOCUMENT_ROOT . '/expedition/class/expedition.class.php';
  866. $exp = new Expedition($db);
  867. $exp->fetch($object->origin_id);
  868. $exp->fetchObjectLinked();
  869. if (count($exp->linkedObjectsIds['commande']) > 0) {
  870. foreach ($exp->linkedObjectsIds['commande'] as $key => $value){
  871. $object->linked_objects['commande'] = $value;
  872. }
  873. }
  874. }
  875. if (is_array($_POST['other_linked_objects']) && ! empty($_POST['other_linked_objects']))
  876. {
  877. $object->linked_objects = array_merge($object->linked_objects, $_POST['other_linked_objects']);
  878. }
  879. $id = $object->create($user); // This include class to add_object_linked() and add add_contact()
  880. if ($id > 0)
  881. {
  882. dol_include_once('/' . $element . '/class/' . $subelement . '.class.php');
  883. $classname = ucfirst($subelement);
  884. $srcobject = new $classname($db);
  885. dol_syslog("Try to find source object origin=" . $object->origin . " originid=" . $object->origin_id . " to add lines or deposit lines");
  886. $result = $srcobject->fetch($object->origin_id);
  887. // If deposit invoice
  888. if ($_POST['type'] == Facture::TYPE_DEPOSIT)
  889. {
  890. $typeamount = GETPOST('typedeposit', 'alpha');
  891. $valuedeposit = GETPOST('valuedeposit', 'int');
  892. if ($typeamount == 'amount')
  893. {
  894. $amountdeposit = $valuedeposit;
  895. }
  896. else
  897. {
  898. $amountdeposit = 0;
  899. if ($result > 0)
  900. {
  901. $totalamount = 0;
  902. $lines = $srcobject->lines;
  903. $numlines=count($lines);
  904. for ($i=0; $i<$numlines; $i++)
  905. {
  906. $qualified=1;
  907. if (empty($lines[$i]->qty)) $qualified=0; // We discard qty=0, it is an option
  908. if (! empty($lines[$i]->special_code)) $qualified=0; // We discard special_code (frais port, ecotaxe, option, ...)
  909. if ($qualified) $totalamount += $lines[$i]->total_ht;
  910. }
  911. if ($totalamount != 0) {
  912. $amountdeposit = ($totalamount * $valuedeposit) / 100;
  913. }
  914. } else {
  915. setEventMessages($srcobject->error, $srcobject->errors, 'errors');
  916. $error ++;
  917. }
  918. }
  919. $tva_tx = $lines[$i]->tva_tx;
  920. if (! empty($lines[$i]->vat_src_code) && ! preg_match('/\(/', $tva_tx)) $tva_tx .= ' ('.$lines[$i]->vat_src_code.')';
  921. $result = $object->addline(
  922. $langs->trans('Deposit'),
  923. $amountdeposit, // subprice
  924. 1, // quantity
  925. $tva_tx, // vat rate
  926. 0, // localtax1_tx
  927. 0, // localtax2_tx
  928. (empty($conf->global->INVOICE_PRODUCTID_DEPOSIT)?0:$conf->global->INVOICE_PRODUCTID_DEPOSIT), // fk_product
  929. 0, // remise_percent
  930. 0, // date_start
  931. 0, // date_end
  932. 0, $lines[$i]->info_bits, // info_bits
  933. 0, // info_bits
  934. 'HT',
  935. 0,
  936. 0, // product_type
  937. 1,
  938. $lines[$i]->special_code,
  939. $object->origin,
  940. 0,
  941. 0,
  942. 0,
  943. 0,
  944. $langs->trans('Deposit')
  945. );
  946. }
  947. else
  948. {
  949. if ($result > 0)
  950. {
  951. $lines = $srcobject->lines;
  952. if (empty($lines) && method_exists($srcobject, 'fetch_lines'))
  953. {
  954. $srcobject->fetch_lines();
  955. $lines = $srcobject->lines;
  956. }
  957. $fk_parent_line=0;
  958. $num=count($lines);
  959. for ($i=0;$i<$num;$i++)
  960. {
  961. // Don't add lines with qty 0 when coming from a shipment including all order lines
  962. if($srcobject->element == 'shipping' && $conf->global->SHIPMENT_GETS_ALL_ORDER_PRODUCTS && $lines[$i]->qty == 0) continue;
  963. $label=(! empty($lines[$i]->label)?$lines[$i]->label:'');
  964. $desc=(! empty($lines[$i]->desc)?$lines[$i]->desc:$lines[$i]->libelle);
  965. if ($object->situation_counter == 1) $lines[$i]->situation_percent = 0;
  966. if ($lines[$i]->subprice < 0)
  967. {
  968. // Negative line, we create a discount line
  969. $discount = new DiscountAbsolute($db);
  970. $discount->fk_soc = $object->socid;
  971. $discount->amount_ht = abs($lines[$i]->total_ht);
  972. $discount->amount_tva = abs($lines[$i]->total_tva);
  973. $discount->amount_ttc = abs($lines[$i]->total_ttc);
  974. $discount->tva_tx = $lines[$i]->tva_tx;
  975. $discount->fk_user = $user->id;
  976. $discount->description = $desc;
  977. $discountid = $discount->create($user);
  978. if ($discountid > 0) {
  979. $result = $object->insert_discount($discountid); // This include link_to_invoice
  980. } else {
  981. setEventMessages($discount->error, $discount->errors, 'errors');
  982. $error ++;
  983. break;
  984. }
  985. } else {
  986. // Positive line
  987. $product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0);
  988. // Date start
  989. $date_start = false;
  990. if ($lines[$i]->date_debut_prevue)
  991. $date_start = $lines[$i]->date_debut_prevue;
  992. if ($lines[$i]->date_debut_reel)
  993. $date_start = $lines[$i]->date_debut_reel;
  994. if ($lines[$i]->date_start)
  995. $date_start = $lines[$i]->date_start;
  996. // Date end
  997. $date_end = false;
  998. if ($lines[$i]->date_fin_prevue)
  999. $date_end = $lines[$i]->date_fin_prevue;
  1000. if ($lines[$i]->date_fin_reel)
  1001. $date_end = $lines[$i]->date_fin_reel;
  1002. if ($lines[$i]->date_end)
  1003. $date_end = $lines[$i]->date_end;
  1004. // Reset fk_parent_line for no child products and special product
  1005. if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) {
  1006. $fk_parent_line = 0;
  1007. }
  1008. // Extrafields
  1009. if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && method_exists($lines[$i], 'fetch_optionals')) {
  1010. $lines[$i]->fetch_optionals($lines[$i]->rowid);
  1011. $array_options = $lines[$i]->array_options;
  1012. }
  1013. $tva_tx = $lines[$i]->tva_tx;
  1014. if (! empty($lines[$i]->vat_src_code) && ! preg_match('/\(/', $tva_tx)) $tva_tx .= ' ('.$lines[$i]->vat_src_code.')';
  1015. // View third's localtaxes for NOW and do not use value from origin.
  1016. // TODO Is this really what we want ? Yes if source if template invoice but what if proposal or order ?
  1017. $localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty);
  1018. $localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty);
  1019. $result = $object->addline($desc, $lines[$i]->subprice, $lines[$i]->qty, $tva_tx, $localtax1_tx, $localtax2_tx, $lines[$i]->fk_product, $lines[$i]->remise_percent, $date_start, $date_end, 0, $lines[$i]->info_bits, $lines[$i]->fk_remise_except, 'HT', 0, $product_type, $lines[$i]->rang, $lines[$i]->special_code, $object->origin, $lines[$i]->rowid, $fk_parent_line, $lines[$i]->fk_fournprice, $lines[$i]->pa_ht, $label, $array_options, $lines[$i]->situation_percent, $lines[$i]->fk_prev_id, $lines[$i]->fk_unit);
  1020. if ($result > 0) {
  1021. $lineid = $result;
  1022. } else {
  1023. $lineid = 0;
  1024. $error ++;
  1025. break;
  1026. }
  1027. // Defined the new fk_parent_line
  1028. if ($result > 0 && $lines[$i]->product_type == 9) {
  1029. $fk_parent_line = $result;
  1030. }
  1031. }
  1032. }
  1033. } else {
  1034. setEventMessages($srcobject->error, $srcobject->errors, 'errors');
  1035. $error ++;
  1036. }
  1037. }
  1038. // Now we create same links to contact than the ones found on origin object
  1039. if (! empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN))
  1040. {
  1041. $originforcontact = $object->origin;
  1042. $originidforcontact = $object->origin_id;
  1043. if ($originforcontact == 'shipping') // shipment and order share the same contacts. If creating from shipment we take data of order
  1044. {
  1045. $originforcontact=$srcobject->origin;
  1046. $originidforcontact=$srcobject->origin_id;
  1047. }
  1048. $sqlcontact = "SELECT code, fk_socpeople FROM ".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as ctc";
  1049. $sqlcontact.= " WHERE element_id = ".$originidforcontact." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$originforcontact."'";
  1050. $resqlcontact = $db->query($sqlcontact);
  1051. if ($resqlcontact)
  1052. {
  1053. while($objcontact = $db->fetch_object($resqlcontact))
  1054. {
  1055. //print $objcontact->code.'-'.$objcontact->fk_socpeople."\n";
  1056. $object->add_contact($objcontact->fk_socpeople, $objcontact->code);
  1057. }
  1058. }
  1059. else dol_print_error($resqlcontact);
  1060. }
  1061. // Hooks
  1062. $parameters = array('objFrom' => $srcobject);
  1063. $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been
  1064. // modified by hook
  1065. if ($reshook < 0)
  1066. {
  1067. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  1068. $error++;
  1069. }
  1070. } else {
  1071. setEventMessages($object->error, $object->errors, 'errors');
  1072. $error++;
  1073. }
  1074. }
  1075. else
  1076. { // If some invoice's lines coming from page
  1077. $id = $object->create($user);
  1078. for ($i = 1; $i <= $NBLINES; $i ++) {
  1079. if ($_POST['idprod' . $i]) {
  1080. $product = new Product($db);
  1081. $product->fetch($_POST['idprod' . $i]);
  1082. $startday = dol_mktime(12, 0, 0, $_POST['date_start' . $i . 'month'], $_POST['date_start' . $i . 'day'], $_POST['date_start' . $i . 'year']);
  1083. $endday = dol_mktime(12, 0, 0, $_POST['date_end' . $i . 'month'], $_POST['date_end' . $i . 'day'], $_POST['date_end' . $i . 'year']);
  1084. $result = $object->addline($product->description, $product->price, $_POST['qty' . $i], $product->tva_tx, $product->localtax1_tx, $product->localtax2_tx, $_POST['idprod' . $i], $_POST['remise_percent' . $i], $startday, $endday, 0, 0, '', $product->price_base_type, $product->price_ttc, $product->type, -1, 0, '', 0, 0, null, 0, '', 0, 100, '', $product->fk_unit);
  1085. }
  1086. }
  1087. }
  1088. }
  1089. }
  1090. if (GETPOST('type') == Facture::TYPE_SITUATION && (!empty($_POST['situations'])))
  1091. {
  1092. $datefacture = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']);
  1093. if (empty($datefacture)) {
  1094. $error++;
  1095. $mesg = '<div class="error">' . $langs->trans("ErrorFieldRequired", $langs->trans("Date")) . '</div>';
  1096. }
  1097. $date_pointoftax = dol_mktime(12, 0, 0, $_POST['date_pointoftaxmonth'], $_POST['date_pointoftaxday'], $_POST['date_pointoftaxyear']);
  1098. if (!($_POST['situations'] > 0)) {
  1099. $error++;
  1100. $mesg = '<div class="error">' . $langs->trans("ErrorFieldRequired", $langs->trans("InvoiceSituation")) . '</div>';
  1101. }
  1102. if (!$error) {
  1103. $result = $object->fetch($_POST['situations']);
  1104. $object->fk_facture_source = $_POST['situations'];
  1105. $object->type = Facture::TYPE_SITUATION;
  1106. if (!empty($origin) && !empty($originid))
  1107. {
  1108. $object->origin = $origin;
  1109. $object->origin_id = $originid;
  1110. foreach ($object->lines as &$line)
  1111. {
  1112. $line->origin = $object->origin;
  1113. $line->origin_id = $line->id;
  1114. }
  1115. }
  1116. $object->fetch_thirdparty();
  1117. $object->date = $datefacture;
  1118. $object->date_pointoftax = $date_pointoftax;
  1119. $object->note_public = trim($_POST['note_public']);
  1120. $object->note = trim($_POST['note']);
  1121. $object->ref_client = $_POST['ref_client'];
  1122. $object->ref_int = $_POST['ref_int'];
  1123. $object->modelpdf = $_POST['model'];
  1124. $object->fk_project = $_POST['projectid'];
  1125. $object->cond_reglement_id = $_POST['cond_reglement_id'];
  1126. $object->mode_reglement_id = $_POST['mode_reglement_id'];
  1127. $object->remise_absolue = $_POST['remise_absolue'];
  1128. $object->remise_percent = $_POST['remise_percent'];
  1129. // Proprietes particulieres a facture de remplacement
  1130. $object->situation_counter = $object->situation_counter + 1;
  1131. $id = $object->createFromCurrent($user);
  1132. if ($id <= 0) $mesg = $object->error;
  1133. }
  1134. }
  1135. // End of object creation, we show it
  1136. if ($id > 0 && ! $error)
  1137. {
  1138. $db->commit();
  1139. header('Location: ' . $_SERVER["PHP_SELF"] . '?facid=' . $id);
  1140. exit();
  1141. }
  1142. else
  1143. {
  1144. $db->rollback();
  1145. $action = 'create';
  1146. $_GET["origin"] = $_POST["origin"];
  1147. $_GET["originid"] = $_POST["originid"];
  1148. setEventMessages($object->error, $object->errors, 'errors');
  1149. }
  1150. }
  1151. // Add a new line
  1152. else if ($action == 'addline' && $user->rights->facture->creer)
  1153. {
  1154. $langs->load('errors');
  1155. $error = 0;
  1156. // Set if we used free entry or predefined product
  1157. $predef='';
  1158. $product_desc=(GETPOST('dp_desc')?GETPOST('dp_desc'):'');
  1159. $price_ht = GETPOST('price_ht');
  1160. $price_ht_devise = GETPOST('multicurrency_price_ht');
  1161. if (GETPOST('prod_entry_mode') == 'free')
  1162. {
  1163. $idprod=0;
  1164. $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0);
  1165. }
  1166. else
  1167. {
  1168. $idprod=GETPOST('idprod', 'int');
  1169. $tva_tx = '';
  1170. }
  1171. $qty = GETPOST('qty' . $predef);
  1172. $remise_percent = GETPOST('remise_percent' . $predef);
  1173. // Extrafields
  1174. $extrafieldsline = new ExtraFields($db);
  1175. $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line);
  1176. $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef);
  1177. // Unset extrafield
  1178. if (is_array($extralabelsline)) {
  1179. // Get extra fields
  1180. foreach ($extralabelsline as $key => $value) {
  1181. unset($_POST["options_" . $key . $predef]);
  1182. }
  1183. }
  1184. if (empty($idprod) && ($price_ht < 0) && ($qty < 0)) {
  1185. setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPriceHT'), $langs->transnoentitiesnoconv('Qty')), null, 'errors');
  1186. $error ++;
  1187. }
  1188. if (! GETPOST('prod_entry_mode'))
  1189. {
  1190. if (GETPOST('type') < 0 && ! GETPOST('search_idprod'))
  1191. {
  1192. setEventMessages($langs->trans('ErrorChooseBetweenFreeAntryOrPredefinedProduct'), null, 'errors');
  1193. $error ++;
  1194. }
  1195. }
  1196. if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && GETPOST('type') < 0) {
  1197. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors');
  1198. $error ++;
  1199. }
  1200. if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && (! ($price_ht >= 0) || $price_ht == '') && $price_ht_devise == '') // Unit price can be 0 but not ''
  1201. {
  1202. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("UnitPriceHT")), null, 'errors');
  1203. $error ++;
  1204. }
  1205. if ($qty == '') {
  1206. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors');
  1207. $error ++;
  1208. }
  1209. if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && empty($product_desc)) {
  1210. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors');
  1211. $error ++;
  1212. }
  1213. if ($qty < 0) {
  1214. $langs->load("errors");
  1215. setEventMessages($langs->trans('ErrorQtyForCustomerInvoiceCantBeNegative'), null, 'errors');
  1216. $error ++;
  1217. }
  1218. if (! $error && ($qty >= 0) && (! empty($product_desc) || ! empty($idprod))) {
  1219. $ret = $object->fetch($id);
  1220. if ($ret < 0) {
  1221. dol_print_error($db, $object->error);
  1222. exit();
  1223. }
  1224. $ret = $object->fetch_thirdparty();
  1225. // Clean parameters
  1226. $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'));
  1227. $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'));
  1228. $price_base_type = (GETPOST('price_base_type', 'alpha') ? GETPOST('price_base_type', 'alpha') : 'HT');
  1229. // Define special_code for special lines
  1230. $special_code = 0;
  1231. // if (empty($_POST['qty'])) $special_code=3; // Options should not exists on invoices
  1232. // Ecrase $pu par celui du produit
  1233. // Ecrase $desc par celui du produit
  1234. // Ecrase $tva_tx par celui du produit
  1235. // Ecrase $base_price_type par celui du produit
  1236. // Replaces $fk_unit with the product's
  1237. if (! empty($idprod))
  1238. {
  1239. $prod = new Product($db);
  1240. $prod->fetch($idprod);
  1241. $label = ((GETPOST('product_label') && GETPOST('product_label') != $prod->label) ? GETPOST('product_label') : '');
  1242. // Update if prices fields are defined
  1243. $tva_tx = get_default_tva($mysoc, $object->thirdparty, $prod->id);
  1244. $tva_npr = get_default_npr($mysoc, $object->thirdparty, $prod->id);
  1245. if (empty($tva_tx)) $tva_npr=0;
  1246. $pu_ht = $prod->price;
  1247. $pu_ttc = $prod->price_ttc;
  1248. $price_min = $prod->price_min;
  1249. $price_base_type = $prod->price_base_type;
  1250. // We define price for product
  1251. if (! empty($conf->global->PRODUIT_MULTIPRICES) && ! empty($object->thirdparty->price_level))
  1252. {
  1253. $pu_ht = $prod->multiprices[$object->thirdparty->price_level];
  1254. $pu_ttc = $prod->multiprices_ttc[$object->thirdparty->price_level];
  1255. $price_min = $prod->multiprices_min[$object->thirdparty->price_level];
  1256. $price_base_type = $prod->multiprices_base_type[$object->thirdparty->price_level];
  1257. if (! empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) // using this option is a bug. kept for backward compatibility
  1258. {
  1259. if (isset($prod->multiprices_tva_tx[$object->thirdparty->price_level])) $tva_tx=$prod->multiprices_tva_tx[$object->thirdparty->price_level];
  1260. if (isset($prod->multiprices_recuperableonly[$object->thirdparty->price_level])) $tva_npr=$prod->multiprices_recuperableonly[$object->thirdparty->price_level];
  1261. if (empty($tva_tx)) $tva_npr=0;
  1262. }
  1263. }
  1264. elseif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES))
  1265. {
  1266. require_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php';
  1267. $prodcustprice = new Productcustomerprice($db);
  1268. $filter = array('t.fk_product' => $prod->id,'t.fk_soc' => $object->thirdparty->id);
  1269. $result = $prodcustprice->fetch_all('', '', 0, 0, $filter);
  1270. if ($result) {
  1271. if (count($prodcustprice->lines) > 0) {
  1272. $pu_ht = price($prodcustprice->lines[0]->price);
  1273. $pu_ttc = price($prodcustprice->lines[0]->price_ttc);
  1274. $price_base_type = $prodcustprice->lines[0]->price_base_type;
  1275. $tva_tx = $prodcustprice->lines[0]->tva_tx;
  1276. }
  1277. }
  1278. }
  1279. $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $tva_tx));
  1280. $tmpprodvat = price2num(preg_replace('/\s*\(.*\)/', '', $prod->tva_tx));
  1281. // if price ht was forced (ie: from gui when calculated by margin rate and cost price). TODO Why this ?
  1282. if (! empty($price_ht))
  1283. {
  1284. $pu_ht = price2num($price_ht, 'MU');
  1285. $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU');
  1286. }
  1287. // On reevalue prix selon taux tva car taux tva transaction peut etre different
  1288. // de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur).
  1289. elseif ($tmpvat != $tmpprodvat)
  1290. {
  1291. if ($price_base_type != 'HT')
  1292. {
  1293. $pu_ht = price2num($pu_ttc / (1 + ($tmpvat / 100)), 'MU');
  1294. }
  1295. else
  1296. {
  1297. $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU');
  1298. }
  1299. }
  1300. $desc = '';
  1301. // Define output language
  1302. if (! empty($conf->global->MAIN_MULTILANGS) && ! empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
  1303. $outputlangs = $langs;
  1304. $newlang = '';
  1305. if (empty($newlang) && GETPOST('lang_id'))
  1306. $newlang = GETPOST('lang_id');
  1307. if (empty($newlang))
  1308. $newlang = $object->thirdparty->default_lang;
  1309. if (! empty($newlang)) {
  1310. $outputlangs = new Translate("", $conf);
  1311. $outputlangs->setDefaultLang($newlang);
  1312. }
  1313. $desc = (! empty($prod->multilangs [$outputlangs->defaultlang] ["description"])) ? $prod->multilangs [$outputlangs->defaultlang] ["description"] : $prod->description;
  1314. } else {
  1315. $desc = $prod->description;
  1316. }
  1317. $desc = dol_concatdesc($desc, $product_desc);
  1318. // Add custom code and origin country into description
  1319. if (empty($conf->global->MAIN_PRODUCT_DISABLE_CUSTOMCOUNTRYCODE) && (! empty($prod->customcode) || ! empty($prod->country_code))) {
  1320. $tmptxt = '(';
  1321. if (! empty($prod->customcode))
  1322. $tmptxt .= $langs->transnoentitiesnoconv("CustomCode") . ': ' . $prod->customcode;
  1323. if (! empty($prod->customcode) && ! empty($prod->country_code))
  1324. $tmptxt .= ' - ';
  1325. if (! empty($prod->country_code))
  1326. $tmptxt .= $langs->transnoentitiesnoconv("CountryOrigin") . ': ' . getCountry($prod->country_code, 0, $db, $langs, 0);
  1327. $tmptxt .= ')';
  1328. $desc = dol_concatdesc($desc, $tmptxt);
  1329. }
  1330. $type = $prod->type;
  1331. $fk_unit = $prod->fk_unit;
  1332. } else {
  1333. $pu_ht = price2num($price_ht, 'MU');
  1334. $pu_ttc = price2num(GETPOST('price_ttc'), 'MU');
  1335. $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0);
  1336. $tva_tx = str_replace('*', '', $tva_tx);
  1337. if (empty($tva_tx)) $tva_npr=0;
  1338. $label = (GETPOST('product_label') ? GETPOST('product_label') : '');
  1339. $desc = $product_desc;
  1340. $type = GETPOST('type');
  1341. $fk_unit= GETPOST('units', 'alpha');
  1342. $pu_ht_devise = price2num($price_ht_devise, 'MU');
  1343. }
  1344. // Margin
  1345. $fournprice = price2num(GETPOST('fournprice' . $predef) ? GETPOST('fournprice' . $predef) : '');
  1346. $buyingprice = price2num(GETPOST('buying_price' . $predef) != '' ? GETPOST('buying_price' . $predef) : ''); // If buying_price is '0', we must keep this value
  1347. // Local Taxes
  1348. $localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty, $mysoc, $tva_npr);
  1349. $localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty, $mysoc, $tva_npr);
  1350. $info_bits = 0;
  1351. if ($tva_npr)
  1352. $info_bits |= 0x01;
  1353. if (! empty($price_min) && (price2num($pu_ht) * (1 - price2num($remise_percent) / 100) < price2num($price_min))) {
  1354. $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, - 1, $conf->currency));
  1355. setEventMessages($mesg, null, 'errors');
  1356. } else {
  1357. // Insert line
  1358. $result = $object->addline($desc, $pu_ht, $qty, $tva_tx, $localtax1_tx, $localtax2_tx, $idprod, $remise_percent, $date_start, $date_end, 0, $info_bits, '', $price_base_type, $pu_ttc, $type, - 1, $special_code, '', 0, GETPOST('fk_parent_line'), $fournprice, $buyingprice, $label, $array_options, $_POST['progress'], '', $fk_unit, $pu_ht_devise);
  1359. if ($result > 0)
  1360. {
  1361. // Define output language
  1362. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
  1363. {
  1364. $outputlangs = $langs;
  1365. $newlang = '';
  1366. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id','alpha');
  1367. if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
  1368. if (! empty($newlang)) {
  1369. $outputlangs = new Translate("", $conf);
  1370. $outputlangs->setDefaultLang($newlang);
  1371. }
  1372. $model=$object->modelpdf;
  1373. $ret = $object->fetch($id); // Reload to get new records
  1374. $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  1375. if ($result < 0) setEventMessages($object->error, $object->errors, 'errors');
  1376. }
  1377. unset($_POST['prod_entry_mode']);
  1378. unset($_POST['qty']);
  1379. unset($_POST['type']);
  1380. unset($_POST['remise_percent']);
  1381. unset($_POST['price_ht']);
  1382. unset($_POST['multicurrency_price_ht']);
  1383. unset($_POST['price_ttc']);
  1384. unset($_POST['tva_tx']);
  1385. unset($_POST['product_ref']);
  1386. unset($_POST['product_label']);
  1387. unset($_POST['product_desc']);
  1388. unset($_POST['fournprice']);
  1389. unset($_POST['buying_price']);
  1390. unset($_POST['np_marginRate']);
  1391. unset($_POST['np_markRate']);
  1392. unset($_POST['dp_desc']);
  1393. unset($_POST['idprod']);
  1394. unset($_POST['units']);
  1395. unset($_POST['date_starthour']);
  1396. unset($_POST['date_startmin']);
  1397. unset($_POST['date_startsec']);
  1398. unset($_POST['date_startday']);
  1399. unset($_POST['date_startmonth']);
  1400. unset($_POST['date_startyear']);
  1401. unset($_POST['date_endhour']);
  1402. unset($_POST['date_endmin']);
  1403. unset($_POST['date_endsec']);
  1404. unset($_POST['date_endday']);
  1405. unset($_POST['date_endmonth']);
  1406. unset($_POST['date_endyear']);
  1407. unset($_POST['situations']);
  1408. unset($_POST['progress']);
  1409. } else {
  1410. setEventMessages($object->error, $object->errors, 'errors');
  1411. }
  1412. $action = '';
  1413. }
  1414. }
  1415. }
  1416. elseif ($action == 'updateligne' && $user->rights->facture->creer && ! GETPOST('cancel'))
  1417. {
  1418. if (! $object->fetch($id) > 0) dol_print_error($db);
  1419. $object->fetch_thirdparty();
  1420. // Clean parameters
  1421. $date_start = '';
  1422. $date_end = '';
  1423. $date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear'));
  1424. $date_end = dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear'));
  1425. $description = dol_htmlcleanlastbr(GETPOST('product_desc') ? GETPOST('product_desc') : GETPOST('desc'));
  1426. $pu_ht = GETPOST('price_ht');
  1427. $vat_rate = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0);
  1428. $qty = GETPOST('qty');
  1429. $pu_ht_devise = GETPOST('multicurrency_subprice');
  1430. // Define info_bits
  1431. $info_bits = 0;
  1432. if (preg_match('/\*/', $vat_rate))
  1433. $info_bits |= 0x01;
  1434. // Define vat_rate
  1435. $vat_rate = str_replace('*', '', $vat_rate);
  1436. $localtax1_rate = get_localtax($vat_rate, 1, $object->thirdparty);
  1437. $localtax2_rate = get_localtax($vat_rate, 2, $object->thirdparty);
  1438. // Add buying price
  1439. $fournprice = price2num(GETPOST('fournprice') ? GETPOST('fournprice') : '');
  1440. $buyingprice = price2num(GETPOST('buying_price') != '' ? GETPOST('buying_price') : ''); // If buying_price is '0', we muste keep this value
  1441. // Extrafields
  1442. $extrafieldsline = new ExtraFields($db);
  1443. $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line);
  1444. $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline);
  1445. // Unset extrafield
  1446. if (is_array($extralabelsline)) {
  1447. // Get extra fields
  1448. foreach ($extralabelsline as $key => $value) {
  1449. unset($_POST["options_" . $key]);
  1450. }
  1451. }
  1452. // Define special_code for special lines
  1453. $special_code=GETPOST('special_code');
  1454. if (! GETPOST('qty')) $special_code=3;
  1455. $line = new FactureLigne($db);
  1456. $line->fetch(GETPOST('lineid'));
  1457. $percent = $line->get_prev_progress($object->id);
  1458. if (GETPOST('progress') < $percent)
  1459. {
  1460. $mesg = '<div class="warning">' . $langs->trans("CantBeLessThanMinPercent") . '</div>';
  1461. setEventMessages($mesg, null, 'warnings');
  1462. $error++;
  1463. $result = -1;
  1464. }
  1465. // Check minimum price
  1466. $productid = GETPOST('productid', 'int');
  1467. if (! empty($productid))
  1468. {
  1469. $product = new Product($db);
  1470. $product->fetch($productid);
  1471. $type = $product->type;
  1472. $price_min = $product->price_min;
  1473. if (! empty($conf->global->PRODUIT_MULTIPRICES) && ! empty($object->thirdparty->price_level))
  1474. $price_min = $product->multiprices_min [$object->thirdparty->price_level];
  1475. $label = ((GETPOST('update_label') && GETPOST('product_label')) ? GETPOST('product_label') : '');
  1476. // Check price is not lower than minimum (check is done only for standard or replacement invoices)
  1477. if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT) && $price_min && (price2num($pu_ht) * (1 - price2num(GETPOST('remise_percent')) / 100) < price2num($price_min))) {
  1478. setEventMessages($langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, - 1, $conf->currency)), null, 'errors');
  1479. $error ++;
  1480. }
  1481. } else {
  1482. $type = GETPOST('type');
  1483. $label = (GETPOST('product_label') ? GETPOST('product_label') : '');
  1484. // Check parameters
  1485. if (GETPOST('type') < 0) {
  1486. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
  1487. $error ++;
  1488. }
  1489. }
  1490. if ($qty < 0) {
  1491. $langs->load("errors");
  1492. setEventMessages($langs->trans('ErrorQtyForCustomerInvoiceCantBeNegative'), null, 'errors');
  1493. $error ++;
  1494. }
  1495. // Update line
  1496. if (! $error) {
  1497. if (empty($user->rights->margins->creer))
  1498. {
  1499. foreach ($object->lines as &$line)
  1500. {
  1501. if ($line->id == GETPOST('lineid'))
  1502. {
  1503. $fournprice = $line->fk_fournprice;
  1504. $buyingprice = $line->pa_ht;
  1505. break;
  1506. }
  1507. }
  1508. }
  1509. $result = $object->updateline(GETPOST('lineid'), $description, $pu_ht, $qty, GETPOST('remise_percent'),
  1510. $date_start, $date_end, $vat_rate, $localtax1_rate, $localtax2_rate, 'HT', $info_bits, $type,
  1511. GETPOST('fk_parent_line'), 0, $fournprice, $buyingprice, $label, $special_code, $array_options, GETPOST('progress'),
  1512. $_POST['units'],$pu_ht_devise);
  1513. if ($result >= 0) {
  1514. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  1515. // Define output language
  1516. $outputlangs = $langs;
  1517. $newlang = '';
  1518. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id'))
  1519. $newlang = GETPOST('lang_id');
  1520. if ($conf->global->MAIN_MULTILANGS && empty($newlang))
  1521. $newlang = $object->thirdparty->default_lang;
  1522. if (! empty($newlang)) {
  1523. $outputlangs = new Translate("", $conf);
  1524. $outputlangs->setDefaultLang($newlang);
  1525. }
  1526. $ret = $object->fetch($id); // Reload to get new records
  1527. $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  1528. }
  1529. unset($_POST['qty']);
  1530. unset($_POST['type']);
  1531. unset($_POST['productid']);
  1532. unset($_POST['remise_percent']);
  1533. unset($_POST['price_ht']);
  1534. unset($_POST['multicurrency_price_ht']);
  1535. unset($_POST['price_ttc']);
  1536. unset($_POST['tva_tx']);
  1537. unset($_POST['product_ref']);
  1538. unset($_POST['product_label']);
  1539. unset($_POST['product_desc']);
  1540. unset($_POST['fournprice']);
  1541. unset($_POST['buying_price']);
  1542. unset($_POST['np_marginRate']);
  1543. unset($_POST['np_markRate']);
  1544. unset($_POST['dp_desc']);
  1545. unset($_POST['idprod']);
  1546. unset($_POST['units']);
  1547. unset($_POST['date_starthour']);
  1548. unset($_POST['date_startmin']);
  1549. unset($_POST['date_startsec']);
  1550. unset($_POST['date_startday']);
  1551. unset($_POST['date_startmonth']);
  1552. unset($_POST['date_startyear']);
  1553. unset($_POST['date_endhour']);
  1554. unset($_POST['date_endmin']);
  1555. unset($_POST['date_endsec']);
  1556. unset($_POST['date_endday']);
  1557. unset($_POST['date_endmonth']);
  1558. unset($_POST['date_endyear']);
  1559. unset($_POST['situations']);
  1560. unset($_POST['progress']);
  1561. } else {
  1562. setEventMessages($object->error, $object->errors, 'errors');
  1563. }
  1564. }
  1565. }
  1566. else if ($action == 'updatealllines' && $user->rights->facture->creer && $_POST['all_percent'] == $langs->trans('Modifier'))
  1567. {
  1568. if (!$object->fetch($id) > 0) dol_print_error($db);
  1569. if (!is_null(GETPOST('all_progress')) && GETPOST('all_progress') != "")
  1570. {
  1571. foreach ($object->lines as $line)
  1572. {
  1573. $percent = $line->get_prev_progress($object->id);
  1574. if (GETPOST('all_progress') < $percent) {
  1575. $mesg = '<div class="warning">' . $langs->trans("CantBeLessThanMinPercent") . '</div>';
  1576. $result = -1;
  1577. } else
  1578. $object->update_percent($line, $_POST['all_progress']);
  1579. }
  1580. }
  1581. }
  1582. else if ($action == 'updateligne' && $user->rights->facture->creer && $_POST['cancel'] == $langs->trans('Cancel')) {
  1583. header('Location: ' . $_SERVER["PHP_SELF"] . '?facid=' . $id); // Pour reaffichage de la fiche en cours d'edition
  1584. exit();
  1585. }
  1586. /*
  1587. * Send mail
  1588. */
  1589. // Actions to send emails
  1590. if (empty($id)) $id=$facid;
  1591. $actiontypecode='AC_FAC';
  1592. $trigger_name='BILL_SENTBYMAIL';
  1593. $paramname='id';
  1594. $mode='emailfrominvoice';
  1595. $trackid='inv'.$object->id;
  1596. include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
  1597. // Actions to build doc
  1598. $upload_dir = $conf->facture->dir_output;
  1599. $permissioncreate=$user->rights->facture->creer;
  1600. include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
  1601. if ($action == 'update_extras') {
  1602. // Fill array 'array_options' with data from add form
  1603. $extralabels = $extrafields->fetch_name_optionals_label($object->table_element);
  1604. $ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute'));
  1605. if ($ret < 0) $error++;
  1606. if (! $error) {
  1607. // Actions on extra fields (by external module or standard code)
  1608. // TODO le hook fait double emploi avec le trigger !!
  1609. $hookmanager->initHooks(array('invoicedao'));
  1610. $parameters = array('id' => $object->id);
  1611. $reshook = $hookmanager->executeHooks('insertExtraFields', $parameters, $object, $action); // Note that $action and $object may have been modified by
  1612. // some hooks
  1613. if (empty($reshook)) {
  1614. $result = $object->insertExtraFields();
  1615. if ($result < 0) {
  1616. $error ++;
  1617. }
  1618. } else if ($reshook < 0)
  1619. $error ++;
  1620. }
  1621. if ($error)
  1622. $action = 'edit_extras';
  1623. }
  1624. include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
  1625. if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->facture->creer) {
  1626. if ($action == 'addcontact') {
  1627. $result = $object->fetch($id);
  1628. if ($result > 0 && $id > 0) {
  1629. $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid'));
  1630. $result = $object->add_contact($contactid, $_POST["type"], $_POST["source"]);
  1631. }
  1632. if ($result >= 0) {
  1633. header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
  1634. exit();
  1635. } else {
  1636. if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1637. $langs->load("errors");
  1638. setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors');
  1639. } else {
  1640. setEventMessages($object->error, $object->errors, 'errors');
  1641. }
  1642. }
  1643. } // bascule du statut d'un contact
  1644. elseif ($action == 'swapstatut') {
  1645. if ($object->fetch($id)) {
  1646. $result = $object->swapContactStatus(GETPOST('ligne'));
  1647. } else {
  1648. dol_print_error($db);
  1649. }
  1650. } // Efface un contact
  1651. elseif ($action == 'deletecontact') {
  1652. $object->fetch($id);
  1653. $result = $object->delete_contact($lineid);
  1654. if ($result >= 0) {
  1655. header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
  1656. exit();
  1657. } else {
  1658. dol_print_error($db);
  1659. }
  1660. }
  1661. if ($error)
  1662. $action = 'edit_extras';
  1663. }
  1664. }
  1665. /*
  1666. * View
  1667. */
  1668. $form = new Form($db);
  1669. $formother = new FormOther($db);
  1670. $formfile = new FormFile($db);
  1671. $formmargin = new FormMargin($db);
  1672. $paymentstatic=new Paiement($db);
  1673. $bankaccountstatic = new Account($db);
  1674. if (! empty($conf->projet->enabled)) { $formproject = new FormProjets($db); }
  1675. $now = dol_now();
  1676. $title = $langs->trans('InvoiceCustomer') . " - " . $langs->trans('Card');
  1677. $helpurl = "EN:Customers_Invoices|FR:Factures_Clients|ES:Facturas_a_clientes";
  1678. llxHeader('', $title, $helpurl);
  1679. // Mode creation
  1680. if ($action == 'create')
  1681. {
  1682. $facturestatic = new Facture($db);
  1683. $extralabels = $extrafields->fetch_name_optionals_label($facturestatic->table_element);
  1684. print load_fiche_titre($langs->trans('NewBill'));
  1685. $soc = new Societe($db);
  1686. if ($socid > 0)
  1687. $res = $soc->fetch($socid);
  1688. $currency_code = $conf->currency;
  1689. // Load objectsrc
  1690. $remise_absolue = 0;
  1691. if (! empty($origin) && ! empty($originid))
  1692. {
  1693. // Parse element/subelement (ex: project_task)
  1694. $element = $subelement = $origin;
  1695. if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs)) {
  1696. $element = $regs [1];
  1697. $subelement = $regs [2];
  1698. }
  1699. if ($element == 'project') {
  1700. $projectid = $originid;
  1701. if (!$cond_reglement_id) {
  1702. $cond_reglement_id = $soc->cond_reglement_id;
  1703. }
  1704. if (!$mode_reglement_id) {
  1705. $mode_reglement_id = $soc->mode_reglement_id;
  1706. }
  1707. if (!$remise_percent) {
  1708. $remise_percent = $soc->remise_percent;
  1709. }
  1710. if (!$dateinvoice) {
  1711. // Do not set 0 here (0 for a date is 1970)
  1712. $dateinvoice = (empty($dateinvoice)?(empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''):$dateinvoice);
  1713. }
  1714. } else {
  1715. // For compatibility
  1716. if ($element == 'order' || $element == 'commande') {
  1717. $element = $subelement = 'commande';
  1718. }
  1719. if ($element == 'propal') {
  1720. $element = 'comm/propal';
  1721. $subelement = 'propal';
  1722. }
  1723. if ($element == 'contract') {
  1724. $element = $subelement = 'contrat';
  1725. }
  1726. if ($element == 'shipping') {
  1727. $element = $subelement = 'expedition';
  1728. }
  1729. dol_include_once('/' . $element . '/class/' . $subelement . '.class.php');
  1730. $classname = ucfirst($subelement);
  1731. $objectsrc = new $classname($db);
  1732. $objectsrc->fetch($originid);
  1733. if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines'))
  1734. $objectsrc->fetch_lines();
  1735. $objectsrc->fetch_thirdparty();
  1736. $projectid = (! empty($projectid) ? $projectid : $objectsrc->fk_project);
  1737. $ref_client = (! empty($objectsrc->ref_client) ? $objectsrc->ref_client : (! empty($objectsrc->ref_customer) ? $objectsrc->ref_customer:''));
  1738. $ref_int = (! empty($objectsrc->ref_int) ? $objectsrc->ref_int : '');
  1739. // only if socid not filled else it's allready done upper
  1740. if (empty($socid))
  1741. $soc = $objectsrc->thirdparty;
  1742. $cond_reglement_id = (! empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(! empty($soc->cond_reglement_id)?$soc->cond_reglement_id:0));
  1743. $mode_reglement_id = (! empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(! empty($soc->mode_reglement_id)?$soc->mode_reglement_id:0));
  1744. $fk_account = (! empty($objectsrc->fk_account)?$objectsrc->fk_account:(! empty($soc->fk_account)?$soc->fk_account:0));
  1745. $remise_percent = (! empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(! empty($soc->remise_percent)?$soc->remise_percent:0));
  1746. $remise_absolue = (! empty($objectsrc->remise_absolue)?$objectsrc->remise_absolue:(! empty($soc->remise_absolue)?$soc->remise_absolue:0));
  1747. $dateinvoice = (empty($dateinvoice)?(empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''):$dateinvoice);
  1748. if (!empty($conf->multicurrency->enabled))
  1749. {
  1750. if (!empty($objectsrc->multicurrency_code)) $currency_code = $objectsrc->multicurrency_code;
  1751. if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($objectsrc->multicurrency_tx)) $currency_tx = $objectsrc->multicurrency_tx;
  1752. }
  1753. // Replicate extrafields
  1754. $objectsrc->fetch_optionals($originid);
  1755. $object->array_options = $objectsrc->array_options;
  1756. }
  1757. }
  1758. else
  1759. {
  1760. $cond_reglement_id = $soc->cond_reglement_id;
  1761. $mode_reglement_id = $soc->mode_reglement_id;
  1762. $fk_account = $soc->fk_account;
  1763. $remise_percent = $soc->remise_percent;
  1764. $remise_absolue = 0;
  1765. $dateinvoice = (empty($dateinvoice)?(empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''):$dateinvoice); // Do not set 0 here (0 for a date is 1970)
  1766. if (!empty($conf->multicurrency->enabled) && !empty($soc->multicurrency_code)) $currency_code = $soc->multicurrency_code;
  1767. }
  1768. if (!empty($soc->id)) $absolute_discount = $soc->getAvailableDiscounts();
  1769. $note_public = $object->getDefaultCreateValueFor('note_public', (is_object($objectsrc)?$objectsrc->note_public:null));
  1770. $note_private = $object->getDefaultCreateValueFor('note_private', ((! empty($origin) && ! empty($originid) && is_object($objectsrc))?$objectsrc->note_private:null));
  1771. if (! empty($conf->use_javascript_ajax))
  1772. {
  1773. require_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1774. print ajax_combobox('fac_replacement');
  1775. print ajax_combobox('fac_avoir');
  1776. print ajax_combobox('situations');
  1777. }
  1778. if ($origin == 'contrat')
  1779. {
  1780. $langs->load("admin");
  1781. $text=$langs->trans("ToCreateARecurringInvoice");
  1782. $text.=' '.$langs->trans("ToCreateARecurringInvoiceGene", $langs->transnoentitiesnoconv("MenuFinancial"), $langs->transnoentitiesnoconv("BillsCustomers"), $langs->transnoentitiesnoconv("ListOfTemplates"));
  1783. if (empty($conf->global->INVOICE_DISABLE_AUTOMATIC_RECURRING_INVOICE))
  1784. {
  1785. $text.=' '.$langs->trans("ToCreateARecurringInvoiceGeneAuto", $langs->transnoentitiesnoconv('Module2300Name'));
  1786. }
  1787. print info_admin($text, 0, 0, 0).'<br>';
  1788. }
  1789. print '<form name="add" action="' . $_SERVER["PHP_SELF"] . '" method="POST">';
  1790. print '<input type="hidden" name="token" value="' . $_SESSION ['newtoken'] . '">';
  1791. print '<input type="hidden" name="action" value="add">';
  1792. if ($soc->id > 0) print '<input type="hidden" name="socid" value="' . $soc->id . '">' . "\n";
  1793. print '<input name="facnumber" type="hidden" value="provisoire">';
  1794. print '<input name="ref_client" type="hidden" value="' . $ref_client . '">';
  1795. print '<input name="ref_int" type="hidden" value="' . $ref_int . '">';
  1796. print '<input type="hidden" name="origin" value="' . $origin . '">';
  1797. print '<input type="hidden" name="originid" value="' . $originid . '">';
  1798. if (!empty($currency_tx)) print '<input type="hidden" name="originmulticurrency_tx" value="' . $currency_tx . '">';
  1799. dol_fiche_head('');
  1800. print '<table class="border" width="100%">';
  1801. // Ref
  1802. print '<tr><td class="titlefieldcreate fieldrequired">' . $langs->trans('Ref') . '</td><td colspan="2">' . $langs->trans('Draft') . '</td></tr>';
  1803. // Thirdparty
  1804. print '<td class="fieldrequired">' . $langs->trans('Customer') . '</td>';
  1805. if ($soc->id > 0 && ! GETPOST('fac_rec'))
  1806. {
  1807. print '<td colspan="2">';
  1808. print $soc->getNomUrl(1);
  1809. print '<input type="hidden" name="socid" value="' . $soc->id . '">';
  1810. // Outstanding Bill
  1811. $outstandingBills = $soc->get_OutstandingBill();
  1812. print ' (' . $langs->trans('CurrentOutstandingBill') . ': ';
  1813. print price($outstandingBills, '', $langs, 0, 0, -1, $conf->currency);
  1814. if ($soc->outstanding_limit != '')
  1815. {
  1816. if ($outstandingBills > $soc->outstanding_limit) print img_warning($langs->trans("OutstandingBillReached"));
  1817. print ' / ' . price($soc->outstanding_limit, '', $langs, 0, 0, -1, $conf->currency);
  1818. }
  1819. print ')';
  1820. print '</td>';
  1821. }
  1822. else
  1823. {
  1824. print '<td colspan="2">';
  1825. print $form->select_company($soc->id, 'socid', '(s.client = 1 OR s.client = 3) AND status=1', 'SelectThirdParty');
  1826. // Option to reload page to retrieve customer informations. Note, this clear other input
  1827. if (!empty($conf->global->RELOAD_PAGE_ON_CUSTOMER_CHANGE))
  1828. {
  1829. print '<script type="text/javascript">
  1830. $(document).ready(function() {
  1831. $("#socid").change(function() {
  1832. var socid = $(this).val();
  1833. var fac_rec = $(\'#fac_rec\').val();
  1834. // reload page
  1835. window.location.href = "'.$_SERVER["PHP_SELF"].'?action=create&socid="+socid+"&fac_rec="+fac_rec;
  1836. });
  1837. });
  1838. </script>';
  1839. }
  1840. print '</td>';
  1841. }
  1842. print '</tr>' . "\n";
  1843. $exampletemplateinvoice=new FactureRec($db);
  1844. // Overwrite value if creation of invoice is from a predefined invoice
  1845. if (empty($origin) && empty($originid) && GETPOST('fac_rec','int') > 0)
  1846. {
  1847. $invoice_predefined = new FactureRec($db);
  1848. $invoice_predefined->fetch(GETPOST('fac_rec','int'));
  1849. $dateinvoice = $invoice_predefined->date_when; // To use next gen date by default later
  1850. if (empty($projectid)) $projectid = $invoice_predefined->fk_project;
  1851. $cond_reglement_id = $invoice_predefined->cond_reglement_id;
  1852. $mode_reglement_id = $invoice_predefined->mode_reglement_id;
  1853. $fk_account = $invoice_predefined->fk_account;
  1854. $note_public = $invoice_predefined->note_public;
  1855. $note_private = $invoice_predefined->note_private;
  1856. $sql = 'SELECT r.rowid, r.titre, r.total_ttc';
  1857. $sql .= ' FROM ' . MAIN_DB_PREFIX . 'facture_rec as r';
  1858. $sql .= ' WHERE r.fk_soc = ' . $invoice_predefined->socid;
  1859. $resql = $db->query($sql);
  1860. if ($resql)
  1861. {
  1862. $num = $db->num_rows($resql);
  1863. $i = 0;
  1864. if ($num > 0)
  1865. {
  1866. print '<tr><td>' . $langs->trans('CreateFromRepeatableInvoice') . '</td><td>';
  1867. print '<select class="flat" id="fac_rec" name="fac_rec">';
  1868. print '<option value="0" selected></option>';
  1869. while ($i < $num)
  1870. {
  1871. $objp = $db->fetch_object($resql);
  1872. print '<option value="' . $objp->rowid . '"';
  1873. if (GETPOST('fac_rec') == $objp->rowid)
  1874. {
  1875. print ' selected';
  1876. $exampletemplateinvoice->fetch(GETPOST('fac_rec'));
  1877. }
  1878. print '>' . $objp->titre . ' (' . price($objp->total_ttc) . ' ' . $langs->trans("TTC") . ')</option>';
  1879. $i ++;
  1880. }
  1881. print '</select>';
  1882. // Option to reload page to retrieve customer informations. Note, this clear other input
  1883. if (!empty($conf->global->RELOAD_PAGE_ON_TEMPLATE_CHANGE))
  1884. {
  1885. print '<script type="text/javascript">
  1886. $(document).ready(function() {
  1887. $("#fac_rec").change(function() {
  1888. var fac_rec = $(this).val();
  1889. var socid = $(\'#socid\').val();
  1890. // reload page
  1891. window.location.href = "'.$_SERVER["PHP_SELF"].'?action=create&socid="+socid+"&fac_rec="+fac_rec;
  1892. });
  1893. });
  1894. </script>';
  1895. }
  1896. print '</td></tr>';
  1897. }
  1898. $db->free($resql);
  1899. } else {
  1900. dol_print_error($db);
  1901. }
  1902. }
  1903. // Type de facture
  1904. $facids = $facturestatic->list_replacable_invoices($soc->id);
  1905. if ($facids < 0) {
  1906. dol_print_error($db, $facturestatic);
  1907. exit();
  1908. }
  1909. $options = "";
  1910. foreach ($facids as $facparam)
  1911. {
  1912. $options .= '<option value="' . $facparam ['id'] . '"';
  1913. if ($facparam ['id'] == $_POST['fac_replacement'])
  1914. $options .= ' selected';
  1915. $options .= '>' . $facparam ['ref'];
  1916. $options .= ' (' . $facturestatic->LibStatut(0, $facparam ['status']) . ')';
  1917. $options .= '</option>';
  1918. }
  1919. // Show link for credit note
  1920. $facids=$facturestatic->list_qualified_avoir_invoices($soc->id);
  1921. if ($facids < 0)
  1922. {
  1923. dol_print_error($db,$facturestatic);
  1924. exit;
  1925. }
  1926. $optionsav = "";
  1927. $newinvoice_static = new Facture($db);
  1928. foreach ($facids as $key => $valarray)
  1929. {
  1930. $newinvoice_static->id = $key;
  1931. $newinvoice_static->ref = $valarray ['ref'];
  1932. $newinvoice_static->statut = $valarray ['status'];
  1933. $newinvoice_static->type = $valarray ['type'];
  1934. $newinvoice_static->paye = $valarray ['paye'];
  1935. $optionsav .= '<option value="' . $key . '"';
  1936. if ($key == GETPOST('fac_avoir'))
  1937. $optionsav .= ' selected';
  1938. $optionsav .= '>';
  1939. $optionsav .= $newinvoice_static->ref;
  1940. $optionsav .= ' (' . $newinvoice_static->getLibStatut(1, $valarray ['paymentornot']) . ')';
  1941. $optionsav .= '</option>';
  1942. }
  1943. print '<tr><td class="tdtop fieldrequired">' . $langs->trans('Type') . '</td><td colspan="2">';
  1944. print '<div class="tagtable">' . "\n";
  1945. // Standard invoice
  1946. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  1947. $tmp='<input type="radio" id="radio_standard" name="type" value="0"' . (GETPOST('type') == 0 ? ' checked' : '') . '> ';
  1948. $desc = $form->textwithpicto($tmp.$langs->trans("InvoiceStandardAsk"), $langs->transnoentities("InvoiceStandardDesc"), 1, 'help', '', 0, 3);
  1949. print $desc;
  1950. print '</div></div>';
  1951. if ((empty($origin)) || ((($origin == 'propal') || ($origin == 'commande')) && (! empty($originid))))
  1952. {
  1953. // Deposit
  1954. if (empty($conf->global->INVOICE_DISABLE_DEPOSIT))
  1955. {
  1956. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  1957. $tmp='<input type="radio" id="radio_deposit" name="type" value="3"' . (GETPOST('type') == 3 ? ' checked' : '') . '> ';
  1958. print '<script type="text/javascript" language="javascript">
  1959. jQuery(document).ready(function() {
  1960. jQuery("#typedeposit, #valuedeposit").click(function() {
  1961. jQuery("#radio_deposit").prop("checked", true);
  1962. });
  1963. });
  1964. </script>';
  1965. $desc = $form->textwithpicto($tmp.$langs->trans("InvoiceDeposit"), $langs->transnoentities("InvoiceDepositDesc"), 1, 'help', '', 0, 3);
  1966. print '<table class="nobordernopadding"><tr><td>';
  1967. print $desc;
  1968. print '</td>';
  1969. if (($origin == 'propal') || ($origin == 'commande'))
  1970. {
  1971. print '<td class="nowrap" style="padding-left: 5px">';
  1972. $arraylist = array('amount' => 'FixAmount','variable' => 'VarAmount');
  1973. print $form->selectarray('typedeposit', $arraylist, GETPOST('typedeposit'), 0, 0, 0, '', 1);
  1974. print '</td>';
  1975. print '<td class="nowrap" style="padding-left: 5px">' . $langs->trans('Value') . ':<input type="text" id="valuedeposit" name="valuedeposit" size="3" value="' . GETPOST('valuedeposit', 'int') . '"/>';
  1976. }
  1977. print '</td></tr></table>';
  1978. print '</div></div>';
  1979. }
  1980. }
  1981. if ($socid > 0)
  1982. {
  1983. if (! empty($conf->global->INVOICE_USE_SITUATION))
  1984. {
  1985. // First situation invoice
  1986. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  1987. $tmp='<input type="radio" name="type" value="5"' . (GETPOST('type') == 5 ? ' checked' : '') . '> ';
  1988. $desc = $form->textwithpicto($tmp.$langs->trans("InvoiceFirstSituationAsk"), $langs->transnoentities("InvoiceFirstSituationDesc"), 1, 'help', '', 0, 3);
  1989. print $desc;
  1990. print '</div></div>';
  1991. // Next situation invoice
  1992. $opt = $form->selectSituationInvoices(GETPOST('originid'), $socid);
  1993. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  1994. $tmp='<input type="radio" name="type" value="5"' . (GETPOST('type') == 5 && GETPOST('originid') ? ' checked' : '');
  1995. if ($opt == ('<option value ="0" selected>' . $langs->trans('NoSituations') . '</option>') || (GETPOST('origin') && GETPOST('origin') != 'facture' && GETPOST('origin') != 'commande')) $tmp.=' disabled';
  1996. $tmp.= '> ';
  1997. $text = $tmp.$langs->trans("InvoiceSituationAsk") . ' ';
  1998. $text .= '<select class="flat" id="situations" name="situations">';
  1999. $text .= $opt;
  2000. $text .= '</select>';
  2001. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceSituationDesc"), 1, 'help', '', 0, 3);
  2002. print $desc;
  2003. print '</div></div>';
  2004. }
  2005. // Replacement
  2006. if (empty($conf->global->INVOICE_DISABLE_REPLACEMENT))
  2007. {
  2008. print '<!-- replacement line -->';
  2009. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  2010. $tmp='<input type="radio" name="type" id="radio_replacement" value="1"' . (GETPOST('type') == 1 ? ' checked' : '');
  2011. if (! $options) $tmp.=' disabled';
  2012. $tmp.='> ';
  2013. print '<script type="text/javascript" language="javascript">
  2014. jQuery(document).ready(function() {
  2015. jQuery("#fac_replacement").change(function() {
  2016. jQuery("#radio_replacement").prop("checked", true);
  2017. });
  2018. });
  2019. </script>';
  2020. $text = $tmp.$langs->trans("InvoiceReplacementAsk") . ' ';
  2021. $text .= '<select class="flat" name="fac_replacement" id="fac_replacement"';
  2022. if (! $options)
  2023. $text .= ' disabled';
  2024. $text .= '>';
  2025. if ($options) {
  2026. $text .= '<option value="-1">&nbsp;</option>';
  2027. $text .= $options;
  2028. } else {
  2029. $text .= '<option value="-1">' . $langs->trans("NoReplacableInvoice") . '</option>';
  2030. }
  2031. $text .= '</select>';
  2032. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceReplacementDesc"), 1, 'help', '', 0, 3);
  2033. print $desc;
  2034. print '</div></div>';
  2035. }
  2036. }
  2037. else
  2038. {
  2039. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  2040. $tmp='<input type="radio" name="type" id="radio_replacement" value="0" disabled> ';
  2041. $text = $tmp.$langs->trans("InvoiceReplacement") . ' ';
  2042. $text.= '('.$langs->trans("YouMustCreateInvoiceFromThird").') ';
  2043. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceReplacementDesc"), 1, 'help', '', 0, 3);
  2044. print $desc;
  2045. print '</div></div>';
  2046. }
  2047. if (empty($origin))
  2048. {
  2049. if ($socid > 0)
  2050. {
  2051. // Credit note
  2052. if (empty($conf->global->INVOICE_DISABLE_CREDIT_NOTE))
  2053. {
  2054. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  2055. $tmp='<input type="radio" id="radio_creditnote" name="type" value="2"' . (GETPOST('type') == 2 ? ' checked' : '');
  2056. if (! $optionsav) $tmp.=' disabled';
  2057. $tmp.= '> ';
  2058. // Show credit note options only if we checked credit note
  2059. print '<script type="text/javascript" language="javascript">
  2060. jQuery(document).ready(function() {
  2061. if (! jQuery("#radio_creditnote").is(":checked"))
  2062. {
  2063. jQuery("#credit_note_options").hide();
  2064. }
  2065. jQuery("#radio_creditnote").click(function() {
  2066. jQuery("#credit_note_options").show();
  2067. });
  2068. jQuery("#radio_standard, #radio_replacement, #radio_deposit").click(function() {
  2069. jQuery("#credit_note_options").hide();
  2070. });
  2071. });
  2072. </script>';
  2073. $text = $tmp.$langs->transnoentities("InvoiceAvoirAsk") . ' ';
  2074. // $text.='<input type="text" value="">';
  2075. $text .= '<select class="flat valignmiddle" name="fac_avoir" id="fac_avoir"';
  2076. if (! $optionsav)
  2077. $text .= ' disabled';
  2078. $text .= '>';
  2079. if ($optionsav) {
  2080. $text .= '<option value="-1"></option>';
  2081. $text .= $optionsav;
  2082. } else {
  2083. $text .= '<option value="-1">' . $langs->trans("NoInvoiceToCorrect") . '</option>';
  2084. }
  2085. $text .= '</select>';
  2086. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3);
  2087. print $desc;
  2088. print '<div id="credit_note_options" class="clearboth">';
  2089. print '&nbsp;&nbsp;&nbsp; <input data-role="none" 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':'').' /> <label for="invoiceAvoirWithLines">'.$langs->trans('invoiceAvoirWithLines')."</label>";
  2090. print '<br>&nbsp;&nbsp;&nbsp; <input data-role="none" 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':'').' /> <label for="invoiceAvoirWithPaymentRestAmount">'.$langs->trans('invoiceAvoirWithPaymentRestAmount')."</label>";
  2091. print '</div>';
  2092. print '</div></div>';
  2093. }
  2094. }
  2095. else
  2096. {
  2097. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  2098. $tmp='<input type="radio" name="type" id="radio_creditnote" value="0" disabled> ';
  2099. $text = $tmp.$langs->trans("InvoiceAvoir") . ' ';
  2100. $text.= '('.$langs->trans("YouMustCreateInvoiceFromThird").') ';
  2101. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3);
  2102. print $desc;
  2103. print '</div></div>' . "\n";
  2104. }
  2105. }
  2106. // Template invoice
  2107. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  2108. $tmp='<input type="radio" name="type" id="radio_template" value="0" disabled> ';
  2109. $text = $tmp.$langs->trans("RepeatableInvoice") . ' ';
  2110. //$text.= '('.$langs->trans("YouMustCreateStandardInvoiceFirst").') ';
  2111. $desc = $form->textwithpicto($text, $langs->transnoentities("YouMustCreateStandardInvoiceFirstDesc"), 1, 'help', '', 0, 3);
  2112. print $desc;
  2113. print '</div></div>';
  2114. print '</div>';
  2115. print '</td></tr>';
  2116. if ($socid > 0)
  2117. {
  2118. // Discounts for third party
  2119. print '<tr><td>' . $langs->trans('Discounts') . '</td><td colspan="2">';
  2120. if ($soc->remise_percent)
  2121. print $langs->trans("CompanyHasRelativeDiscount", '<a href="' . DOL_URL_ROOT . '/comm/remise.php?id=' . $soc->id . '&backtopage=' . urlencode($_SERVER["PHP_SELF"] . '?socid=' . $soc->id . '&action=' . $action . '&origin=' . GETPOST('origin') . '&originid=' . GETPOST('originid')) . '">' . $soc->remise_percent . '</a>');
  2122. else
  2123. print $langs->trans("CompanyHasNoRelativeDiscount");
  2124. print ' <a href="' . DOL_URL_ROOT . '/comm/remise.php?id=' . $soc->id . '&backtopage=' . urlencode($_SERVER["PHP_SELF"] . '?socid=' . $soc->id . '&action=' . $action . '&origin=' . GETPOST('origin') . '&originid=' . GETPOST('originid')) . '">(' . $langs->trans("EditRelativeDiscount") . ')</a>';
  2125. print '. ';
  2126. print '<br>';
  2127. if ($absolute_discount)
  2128. print $langs->trans("CompanyHasAbsoluteDiscount", '<a href="' . DOL_URL_ROOT . '/comm/remx.php?id=' . $soc->id . '&backtopage=' . urlencode($_SERVER["PHP_SELF"] . '?socid=' . $soc->id . '&action=' . $action . '&origin=' . GETPOST('origin') . '&originid=' . GETPOST('originid')) . '">' . price($absolute_discount) . '</a>', $langs->trans("Currency" . $conf->currency));
  2129. else
  2130. print $langs->trans("CompanyHasNoAbsoluteDiscount");
  2131. print ' <a href="' . DOL_URL_ROOT . '/comm/remx.php?id=' . $soc->id . '&backtopage=' . urlencode($_SERVER["PHP_SELF"] . '?socid=' . $soc->id . '&action=' . $action . '&origin=' . GETPOST('origin') . '&originid=' . GETPOST('originid')) . '">(' . $langs->trans("EditGlobalDiscounts") . ')</a>';
  2132. print '.';
  2133. print '</td></tr>';
  2134. }
  2135. $datefacture = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']);
  2136. // Date invoice
  2137. print '<tr><td class="fieldrequired">' . $langs->trans('DateInvoice') . '</td><td colspan="2">';
  2138. print $form->select_date($datefacture?$datefacture:$dateinvoice, '', '', '', '', "add", 1, 1, 1);
  2139. print '</td></tr>';
  2140. // Date point of tax
  2141. if (! empty($conf->global->INVOICE_POINTOFTAX_DATE))
  2142. {
  2143. print '<tr><td class="fieldrequired">' . $langs->trans('DatePointOfTax') . '</td><td colspan="2">';
  2144. $date_pointoftax = dol_mktime(12, 0, 0, $_POST['date_pointoftaxmonth'], $_POST['date_pointoftaxday'], $_POST['date_pointoftaxyear']);
  2145. print $form->select_date($date_pointoftax?$date_pointoftax:-1, 'date_pointoftax', '', '', '', "add", 1, 1, 1);
  2146. print '</td></tr>';
  2147. }
  2148. // Payment term
  2149. print '<tr><td class="nowrap fieldrequired">' . $langs->trans('PaymentConditionsShort') . '</td><td colspan="2">';
  2150. $form->select_conditions_paiements(isset($_POST['cond_reglement_id']) ? $_POST['cond_reglement_id'] : $cond_reglement_id, 'cond_reglement_id');
  2151. print '</td></tr>';
  2152. // Payment mode
  2153. print '<tr><td>' . $langs->trans('PaymentMode') . '</td><td colspan="2">';
  2154. $form->select_types_paiements(isset($_POST['mode_reglement_id']) ? $_POST['mode_reglement_id'] : $mode_reglement_id, 'mode_reglement_id', 'CRDT');
  2155. print '</td></tr>';
  2156. // Bank Account
  2157. if (isset($_POST['fk_account'])) {
  2158. $fk_account = $_POST['fk_account'];
  2159. }
  2160. print '<tr><td>' . $langs->trans('BankAccount') . '</td><td colspan="2">';
  2161. $form->select_comptes($fk_account, 'fk_account', 0, '', 1);
  2162. print '</td></tr>';
  2163. // Project
  2164. if (! empty($conf->projet->enabled) && $socid > 0)
  2165. {
  2166. $langs->load('projects');
  2167. print '<tr><td>' . $langs->trans('Project') . '</td><td colspan="2">';
  2168. $numprojet = $formproject->select_projects($socid, $projectid, 'projectid', 0);
  2169. print ' &nbsp; <a href="'.DOL_URL_ROOT.'/projet/card.php?socid=' . $soc->id . '&action=create&status=1&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=create&socid='.$soc->id.($fac_rec?'&fac_rec='.$fac_rec:'')).'">' . $langs->trans("AddProject") . '</a>';
  2170. print '</td></tr>';
  2171. }
  2172. // Incoterms
  2173. if (!empty($conf->incoterm->enabled))
  2174. {
  2175. print '<tr>';
  2176. print '<td><label for="incoterm_id">'.$form->textwithpicto($langs->trans("IncotermLabel"), $objectsrc->libelle_incoterms, 1).'</label></td>';
  2177. print '<td colspan="2" class="maxwidthonsmartphone">';
  2178. $incoterm_id = GETPOST('incoterm_id');
  2179. $incoterm_location = GETPOST('location_incoterms');
  2180. if (empty($incoterm_id))
  2181. {
  2182. $incoterm_id = (!empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : $soc->fk_incoterms);
  2183. $incoterm_location = (!empty($objectsrc->location_incoterms) ? $objectsrc->location_incoterms : $soc->location_incoterms);
  2184. }
  2185. print $form->select_incoterms($incoterm_id, $incoterm_location);
  2186. print '</td></tr>';
  2187. }
  2188. // Other attributes
  2189. $parameters = array('objectsrc' => $objectsrc,'colspan' => ' colspan="3"');
  2190. $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by
  2191. // hook
  2192. if (empty($reshook) && ! empty($extrafields->attribute_label)) {
  2193. print $object->showOptionals($extrafields, 'edit');
  2194. }
  2195. // Template to use by default
  2196. print '<tr><td>' . $langs->trans('Model') . '</td>';
  2197. print '<td colspan="2">';
  2198. include_once DOL_DOCUMENT_ROOT . '/core/modules/facture/modules_facture.php';
  2199. $liste = ModelePDFFactures::liste_modeles($db);
  2200. print $form->selectarray('model', $liste, $conf->global->FACTURE_ADDON_PDF);
  2201. print "</td></tr>";
  2202. // Multicurrency
  2203. if (! empty($conf->multicurrency->enabled))
  2204. {
  2205. print '<tr>';
  2206. print '<td>'.fieldLabel('Currency','multicurrency_code').'</td>';
  2207. print '<td colspan="2" class="maxwidthonsmartphone">';
  2208. print $form->selectMultiCurrency($currency_code, 'multicurrency_code');
  2209. print '</td></tr>';
  2210. }
  2211. // Help of substitution key
  2212. $htmltext='';
  2213. if (GETPOST('fac_rec','int') > 0)
  2214. {
  2215. $dateexample=($datefacture ? $datefacture : $dateinvoice);
  2216. if (empty($dateexample)) $dateexample=dol_now();
  2217. $substitutionarray=array(
  2218. '__TOTAL_HT__' => $langs->trans("AmountHT").' ('.$langs->trans("Example").': '.price($exampletemplateinvoice->total_ht).')',
  2219. '__TOTAL_TTC__' => $langs->trans("AmountTTC").' ('.$langs->trans("Example").': '.price($exampletemplateinvoice->total_ttc).')',
  2220. '__INVOICE_PREVIOUS_MONTH__' => $langs->trans("PreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'),'%m').')',
  2221. '__INVOICE_MONTH__' => $langs->trans("MonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample,'%m').')',
  2222. '__INVOICE_NEXT_MONTH__' => $langs->trans("NextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'),'%m').')',
  2223. '__INVOICE_PREVIOUS_MONTH_TEXT__' => $langs->trans("TextPreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'),'%B').')',
  2224. '__INVOICE_MONTH_TEXT__' => $langs->trans("TextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample,'%B').')',
  2225. '__INVOICE_NEXT_MONTH_TEXT__' => $langs->trans("TextNextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'), '%B').')',
  2226. '__INVOICE_PREVIOUS_YEAR__' => $langs->trans("YearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'y'),'%Y').')',
  2227. '__INVOICE_YEAR__' => $langs->trans("PreviousYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample,'%Y').')',
  2228. '__INVOICE_NEXT_YEAR__' => $langs->trans("NextYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'y'),'%Y').')'
  2229. );
  2230. $htmltext = '<i>'.$langs->trans("FollowingConstantsWillBeSubstituted").':<br>';
  2231. foreach($substitutionarray as $key => $val)
  2232. {
  2233. $htmltext.=$key.' = '.$langs->trans($val).'<br>';
  2234. }
  2235. $htmltext.='</i>';
  2236. }
  2237. // Public note
  2238. print '<tr>';
  2239. print '<td class="border tdtop">';
  2240. print $form->textwithpicto($langs->trans('NotePublic'), $htmltext);
  2241. print '</td>';
  2242. print '<td valign="top" colspan="2">';
  2243. $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%');
  2244. print $doleditor->Create(1);
  2245. // Private note
  2246. if (empty($user->societe_id))
  2247. {
  2248. print '<tr>';
  2249. print '<td class="border tdtop">';
  2250. print $form->textwithpicto($langs->trans('NotePrivate'), $htmltext);
  2251. print '</td>';
  2252. print '<td valign="top" colspan="2">';
  2253. $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%');
  2254. print $doleditor->Create(1);
  2255. // print '<textarea name="note_private" wrap="soft" cols="70" rows="'.ROWS_3.'">'.$note_private.'.</textarea>
  2256. print '</td></tr>';
  2257. }
  2258. // Lines from source
  2259. if (! empty($origin) && ! empty($originid) && is_object($objectsrc))
  2260. {
  2261. // TODO for compatibility
  2262. if ($origin == 'contrat') {
  2263. // Calcul contrat->price (HT), contrat->total (TTC), contrat->tva
  2264. $objectsrc->remise_absolue = $remise_absolue;
  2265. $objectsrc->remise_percent = $remise_percent;
  2266. $objectsrc->update_price(1, - 1, 1);
  2267. }
  2268. print "\n<!-- " . $classname . " info -->";
  2269. print "\n";
  2270. print '<input type="hidden" name="amount" value="' . $objectsrc->total_ht . '">' . "\n";
  2271. print '<input type="hidden" name="total" value="' . $objectsrc->total_ttc . '">' . "\n";
  2272. print '<input type="hidden" name="tva" value="' . $objectsrc->total_tva . '">' . "\n";
  2273. print '<input type="hidden" name="origin" value="' . $objectsrc->element . '">';
  2274. print '<input type="hidden" name="originid" value="' . $objectsrc->id . '">';
  2275. switch ($classname) {
  2276. case 'Propal':
  2277. $newclassname = 'CommercialProposal';
  2278. break;
  2279. case 'Commande':
  2280. $newclassname = 'Order';
  2281. break;
  2282. case 'Expedition':
  2283. $newclassname = 'Sending';
  2284. break;
  2285. case 'Contrat':
  2286. $newclassname = 'Contract';
  2287. break;
  2288. case 'Fichinter':
  2289. $newclassname = 'Intervention';
  2290. break;
  2291. default:
  2292. $newclassname = $classname;
  2293. }
  2294. print '<tr><td>' . $langs->trans($newclassname) . '</td><td colspan="2">' . $objectsrc->getNomUrl(1);
  2295. // We check if Origin document (id and type is known) has already at least one invoice attached to it
  2296. $objectsrc->fetchObjectLinked($originid,$origin,'','facture');
  2297. $cntinvoice=count($objectsrc->linkedObjects['facture']);
  2298. if ($cntinvoice>=1)
  2299. {
  2300. setEventMessages('WarningBillExist', null, 'warnings');
  2301. echo ' ('.$langs->trans('LatestRelatedBill').end($objectsrc->linkedObjects['facture'])->getNomUrl(1).')';
  2302. }
  2303. echo '</td></tr>';
  2304. print '<tr><td>' . $langs->trans('TotalHT') . '</td><td colspan="2">' . price($objectsrc->total_ht) . '</td></tr>';
  2305. print '<tr><td>' . $langs->trans('TotalVAT') . '</td><td colspan="2">' . price($objectsrc->total_tva) . "</td></tr>";
  2306. if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) // Localtax1
  2307. {
  2308. print '<tr><td>' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '</td><td colspan="2">' . price($objectsrc->total_localtax1) . "</td></tr>";
  2309. }
  2310. if ($mysoc->localtax2_assuj == "1" || $objectsrc->total_localtax2 != 0) // Localtax2
  2311. {
  2312. print '<tr><td>' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '</td><td colspan="2">' . price($objectsrc->total_localtax2) . "</td></tr>";
  2313. }
  2314. print '<tr><td>' . $langs->trans('TotalTTC') . '</td><td colspan="2">' . price($objectsrc->total_ttc) . "</td></tr>";
  2315. if (!empty($conf->multicurrency->enabled))
  2316. {
  2317. print '<tr><td>' . $langs->trans('MulticurrencyTotalHT') . '</td><td colspan="2">' . price($objectsrc->multicurrency_total_ht) . '</td></tr>';
  2318. print '<tr><td>' . $langs->trans('MulticurrencyTotalVAT') . '</td><td colspan="2">' . price($objectsrc->multicurrency_total_tva) . "</td></tr>";
  2319. print '<tr><td>' . $langs->trans('MulticurrencyTotalTTC') . '</td><td colspan="2">' . price($objectsrc->multicurrency_total_ttc) . "</td></tr>";
  2320. }
  2321. }
  2322. print "</table>\n";
  2323. dol_fiche_end();
  2324. // Button "Create Draft"
  2325. print '<div class="center">';
  2326. print '<input type="submit" class="button" name="bouton" value="' . $langs->trans('CreateDraft') . '">';
  2327. print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  2328. print '<input type="button" class="button" value="' . $langs->trans("Cancel") . '" onClick="javascript:history.go(-1)">';
  2329. print '</div>';
  2330. print "</form>\n";
  2331. // Show origin lines
  2332. if (! empty($origin) && ! empty($originid) && is_object($objectsrc)) {
  2333. print '<br>';
  2334. $title = $langs->trans('ProductsAndServices');
  2335. print load_fiche_titre($title);
  2336. print '<table class="noborder" width="100%">';
  2337. $objectsrc->printOriginLinesList();
  2338. print '</table>';
  2339. }
  2340. print '<br>';
  2341. }
  2342. else if ($id > 0 || ! empty($ref))
  2343. {
  2344. /*
  2345. * Show object in view mode
  2346. */
  2347. $result = $object->fetch($id, $ref);
  2348. if ($result <= 0) {
  2349. dol_print_error($db, $object->error);
  2350. exit();
  2351. }
  2352. // fetch optionals attributes and labels
  2353. $extralabels = $extrafields->fetch_name_optionals_label($object->table_element);
  2354. if ($user->societe_id > 0 && $user->societe_id != $object->socid)
  2355. accessforbidden('', 0);
  2356. $result = $object->fetch_thirdparty();
  2357. $soc = new Societe($db);
  2358. $result=$soc->fetch($object->socid);
  2359. if ($result < 0) dol_print_error($db);
  2360. $selleruserevenustamp = $mysoc->useRevenueStamp();
  2361. $totalpaye = $object->getSommePaiement();
  2362. $totalcreditnotes = $object->getSumCreditNotesUsed();
  2363. $totaldeposits = $object->getSumDepositsUsed();
  2364. // print "totalpaye=".$totalpaye." totalcreditnotes=".$totalcreditnotes." totaldeposts=".$totaldeposits."
  2365. // selleruserrevenuestamp=".$selleruserevenustamp;
  2366. // We can also use bcadd to avoid pb with floating points
  2367. // For example print 239.2 - 229.3 - 9.9; does not return 0.
  2368. // $resteapayer=bcadd($object->total_ttc,$totalpaye,$conf->global->MAIN_MAX_DECIMALS_TOT);
  2369. // $resteapayer=bcadd($resteapayer,$totalavoir,$conf->global->MAIN_MAX_DECIMALS_TOT);
  2370. $resteapayer = price2num($object->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits, 'MT');
  2371. if ($object->paye)
  2372. $resteapayer = 0;
  2373. $resteapayeraffiche = $resteapayer;
  2374. if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
  2375. $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
  2376. $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
  2377. } else {
  2378. $filterabsolutediscount = "fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND description LIKE '(DEPOSIT)%')";
  2379. $filtercreditnote = "fk_facture_source IS NOT NULL AND description NOT LIKE '(DEPOSIT)%'";
  2380. }
  2381. $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount);
  2382. $absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote);
  2383. $absolute_discount = price2num($absolute_discount, 'MT');
  2384. $absolute_creditnote = price2num($absolute_creditnote, 'MT');
  2385. $author = new User($db);
  2386. if ($object->user_author) {
  2387. $author->fetch($object->user_author);
  2388. }
  2389. $objectidnext = $object->getIdReplacingInvoice();
  2390. $head = facture_prepare_head($object);
  2391. dol_fiche_head($head, 'compta', $langs->trans('InvoiceCustomer'), 0, 'bill');
  2392. $formconfirm = '';
  2393. // Confirmation de la conversion de l'avoir en reduc
  2394. if ($action == 'converttoreduc') {
  2395. $text = $langs->trans('ConfirmConvertToReduc');
  2396. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $langs->trans('ConvertToReduc'), $text, 'confirm_converttoreduc', '', "yes", 2);
  2397. }
  2398. // Confirmation to delete invoice
  2399. if ($action == 'delete') {
  2400. $text = $langs->trans('ConfirmDeleteBill', $object->ref);
  2401. $formquestion = array();
  2402. $qualified_for_stock_change = 0;
  2403. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  2404. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  2405. } else {
  2406. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  2407. }
  2408. if ($object->type != Facture::TYPE_DEPOSIT && ! empty($conf->global->STOCK_CALCULATE_ON_BILL) && $qualified_for_stock_change && $object->statut >= 1)
  2409. {
  2410. $langs->load("stocks");
  2411. require_once DOL_DOCUMENT_ROOT . '/product/class/html.formproduct.class.php';
  2412. $formproduct = new FormProduct($db);
  2413. $label = $object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockDecrease") : $langs->trans("SelectWarehouseForStockIncrease");
  2414. $formquestion = array(
  2415. // 'text' => $langs->trans("ConfirmClone"),
  2416. // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' =>
  2417. // 1),
  2418. // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value'
  2419. // => 1),
  2420. array('type' => 'other','name' => 'idwarehouse','label' => $label,'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse')?GETPOST('idwarehouse'):'ifone', 'idwarehouse', '', 1, 0, 0, $langs->trans("NoStockAction"))));
  2421. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $langs->trans('DeleteBill'), $text, 'confirm_delete', $formquestion, "yes", 1);
  2422. } else {
  2423. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $langs->trans('DeleteBill'), $text, 'confirm_delete', '', '', 1);
  2424. }
  2425. }
  2426. // Confirmation de la validation
  2427. if ($action == 'valid')
  2428. {
  2429. // on verifie si l'objet est en numerotation provisoire
  2430. $objectref = substr($object->ref, 1, 4);
  2431. if ($objectref == 'PROV') {
  2432. $savdate = $object->date;
  2433. if (! empty($conf->global->FAC_FORCE_DATE_VALIDATION)) {
  2434. $object->date = dol_now();
  2435. $object->date_lim_reglement = $object->calculate_date_lim_reglement();
  2436. }
  2437. $numref = $object->getNextNumRef($soc);
  2438. // $object->date=$savdate;
  2439. } else {
  2440. $numref = $object->ref;
  2441. }
  2442. $text = $langs->trans('ConfirmValidateBill', $numref);
  2443. if (! empty($conf->notification->enabled)) {
  2444. require_once DOL_DOCUMENT_ROOT . '/core/class/notify.class.php';
  2445. $notify = new Notify($db);
  2446. $text .= '<br>';
  2447. $text .= $notify->confirmMessage('BILL_VALIDATE', $object->socid, $object);
  2448. }
  2449. $formquestion = array();
  2450. $qualified_for_stock_change = 0;
  2451. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  2452. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  2453. } else {
  2454. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  2455. }
  2456. if ($object->type != Facture::TYPE_DEPOSIT && ! empty($conf->global->STOCK_CALCULATE_ON_BILL) && $qualified_for_stock_change)
  2457. {
  2458. $langs->load("stocks");
  2459. require_once DOL_DOCUMENT_ROOT . '/product/class/html.formproduct.class.php';
  2460. require_once DOL_DOCUMENT_ROOT . '/product/stock/class/entrepot.class.php';
  2461. $formproduct = new FormProduct($db);
  2462. $warehouse = new Entrepot($db);
  2463. $warehouse_array = $warehouse->list_array();
  2464. if (count($warehouse_array) == 1) {
  2465. $label = $object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockIncrease", current($warehouse_array)) : $langs->trans("WarehouseForStockDecrease", current($warehouse_array));
  2466. $value = '<input type="hidden" id="idwarehouse" name="idwarehouse" value="' . key($warehouse_array) . '">';
  2467. } else {
  2468. $label = $object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockIncrease") : $langs->trans("SelectWarehouseForStockDecrease");
  2469. $value = $formproduct->selectWarehouses(GETPOST('idwarehouse')?GETPOST('idwarehouse'):'ifone', 'idwarehouse', '', 1);
  2470. }
  2471. $formquestion = array(
  2472. // 'text' => $langs->trans("ConfirmClone"),
  2473. // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' =>
  2474. // 1),
  2475. // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value'
  2476. // => 1),
  2477. array('type' => 'other','name' => 'idwarehouse','label' => $label,'value' => $value));
  2478. }
  2479. if ($object->type != Facture::TYPE_CREDIT_NOTE && $object->total_ttc < 0) // Can happen only if $conf->global->FACTURE_ENABLE_NEGATIVE is on
  2480. {
  2481. $text .= '<br>' . img_warning() . ' ' . $langs->trans("ErrorInvoiceOfThisTypeMustBePositive");
  2482. }
  2483. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?facid=' . $object->id, $langs->trans('ValidateBill'), $text, 'confirm_valid', $formquestion, (($object->type != Facture::TYPE_CREDIT_NOTE && $object->total_ttc < 0) ? "no" : "yes"), 2);
  2484. }
  2485. // Confirm back to draft status
  2486. if ($action == 'modif') {
  2487. $text = $langs->trans('ConfirmUnvalidateBill', $object->ref);
  2488. $formquestion = array();
  2489. $qualified_for_stock_change = 0;
  2490. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  2491. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  2492. } else {
  2493. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  2494. }
  2495. if ($object->type != Facture::TYPE_DEPOSIT && ! empty($conf->global->STOCK_CALCULATE_ON_BILL) && $qualified_for_stock_change) {
  2496. $langs->load("stocks");
  2497. require_once DOL_DOCUMENT_ROOT . '/product/class/html.formproduct.class.php';
  2498. require_once DOL_DOCUMENT_ROOT . '/product/stock/class/entrepot.class.php';
  2499. $formproduct = new FormProduct($db);
  2500. $warehouse = new Entrepot($db);
  2501. $warehouse_array = $warehouse->list_array();
  2502. if (count($warehouse_array) == 1) {
  2503. $label = $object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockDecrease", current($warehouse_array)) : $langs->trans("WarehouseForStockIncrease", current($warehouse_array));
  2504. $value = '<input type="hidden" id="idwarehouse" name="idwarehouse" value="' . key($warehouse_array) . '">';
  2505. } else {
  2506. $label = $object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockDecrease") : $langs->trans("SelectWarehouseForStockIncrease");
  2507. $value = $formproduct->selectWarehouses(GETPOST('idwarehouse')?GETPOST('idwarehouse'):'ifone', 'idwarehouse', '', 1);
  2508. }
  2509. $formquestion = array(
  2510. // 'text' => $langs->trans("ConfirmClone"),
  2511. // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' =>
  2512. // 1),
  2513. // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value'
  2514. // => 1),
  2515. array('type' => 'other','name' => 'idwarehouse','label' => $label,'value' => $value));
  2516. }
  2517. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?facid=' . $object->id, $langs->trans('UnvalidateBill'), $text, 'confirm_modif', $formquestion, "yes", 1);
  2518. }
  2519. // Confirmation du classement paye
  2520. if ($action == 'paid' && $resteapayer <= 0) {
  2521. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?facid=' . $object->id, $langs->trans('ClassifyPaid'), $langs->trans('ConfirmClassifyPaidBill', $object->ref), 'confirm_paid', '', "yes", 1);
  2522. }
  2523. if ($action == 'paid' && $resteapayer > 0) {
  2524. // Code
  2525. $i = 0;
  2526. $close [$i] ['code'] = 'discount_vat';
  2527. $i ++;
  2528. $close [$i] ['code'] = 'badcustomer';
  2529. $i ++;
  2530. // Help
  2531. $i = 0;
  2532. $close [$i] ['label'] = $langs->trans("HelpEscompte") . '<br><br>' . $langs->trans("ConfirmClassifyPaidPartiallyReasonDiscountVatDesc");
  2533. $i ++;
  2534. $close [$i] ['label'] = $langs->trans("ConfirmClassifyPaidPartiallyReasonBadCustomerDesc");
  2535. $i ++;
  2536. // Texte
  2537. $i = 0;
  2538. $close [$i] ['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonDiscountVat", $resteapayer, $langs->trans("Currency" . $conf->currency)), $close [$i] ['label'], 1);
  2539. $i ++;
  2540. $close [$i] ['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBadCustomer", $resteapayer, $langs->trans("Currency" . $conf->currency)), $close [$i] ['label'], 1);
  2541. $i ++;
  2542. // arrayreasons[code]=reason
  2543. foreach ($close as $key => $val) {
  2544. $arrayreasons [$close [$key] ['code']] = $close [$key] ['reason'];
  2545. }
  2546. // Cree un tableau formulaire
  2547. $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' => '','size' => '100'));
  2548. // Paiement incomplet. On demande si motif = escompte ou autre
  2549. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?facid=' . $object->id, $langs->trans('ClassifyPaid'), $langs->trans('ConfirmClassifyPaidPartially', $object->ref), 'confirm_paid_partially', $formquestion, "yes");
  2550. }
  2551. // Confirmation du classement abandonne
  2552. if ($action == 'canceled') {
  2553. // S'il y a une facture de remplacement pas encore validee (etat brouillon),
  2554. // on ne permet pas de classer abandonner la facture.
  2555. if ($objectidnext) {
  2556. $facturereplacement = new Facture($db);
  2557. $facturereplacement->fetch($objectidnext);
  2558. $statusreplacement = $facturereplacement->statut;
  2559. }
  2560. if ($objectidnext && $statusreplacement == 0) {
  2561. print '<div class="error">' . $langs->trans("ErrorCantCancelIfReplacementInvoiceNotValidated") . '</div>';
  2562. } else {
  2563. // Code
  2564. $close [1] ['code'] = 'badcustomer';
  2565. $close [2] ['code'] = 'abandon';
  2566. // Help
  2567. $close [1] ['label'] = $langs->trans("ConfirmClassifyPaidPartiallyReasonBadCustomerDesc");
  2568. $close [2] ['label'] = $langs->trans("ConfirmClassifyAbandonReasonOtherDesc");
  2569. // Texte
  2570. $close [1] ['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBadCustomer", $object->ref), $close [1] ['label'], 1);
  2571. $close [2] ['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyAbandonReasonOther"), $close [2] ['label'], 1);
  2572. // arrayreasons
  2573. $arrayreasons [$close [1] ['code']] = $close [1] ['reason'];
  2574. $arrayreasons [$close [2] ['code']] = $close [2] ['reason'];
  2575. // Cree un tableau formulaire
  2576. $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' => '','size' => '100'));
  2577. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $langs->trans('CancelBill'), $langs->trans('ConfirmCancelBill', $object->ref), 'confirm_canceled', $formquestion, "yes");
  2578. }
  2579. }
  2580. // Confirmation de la suppression d'une ligne produit
  2581. if ($action == 'ask_deleteline') {
  2582. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?facid=' . $object->id . '&lineid=' . $lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 'no', 1);
  2583. }
  2584. // Clone confirmation
  2585. if ($action == 'clone')
  2586. {
  2587. // Create an array for form
  2588. $formquestion = array(
  2589. // 'text' => $langs->trans("ConfirmClone"),
  2590. // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1)
  2591. array('type' => 'other','name' => 'socid','label' => $langs->trans("SelectThirdParty"),'value' => $form->select_company($object->socid, 'socid', '(s.client=1 OR s.client=2 OR s.client=3)', 1)));
  2592. // Paiement incomplet. On demande si motif = escompte ou autre
  2593. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?facid=' . $object->id, $langs->trans('CloneInvoice'), $langs->trans('ConfirmCloneInvoice', $object->ref), 'confirm_clone', $formquestion, 'yes', 1);
  2594. }
  2595. if (! $formconfirm)
  2596. {
  2597. $parameters = array('lineid' => $lineid);
  2598. $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  2599. if (empty($reshook)) $formconfirm.=$hookmanager->resPrint;
  2600. elseif ($reshook > 0) $formconfirm=$hookmanager->resPrint;
  2601. }
  2602. // Print form confirm
  2603. print $formconfirm;
  2604. // Invoice content
  2605. $linkback = '<a href="' . DOL_URL_ROOT . '/compta/facture/list.php' . (! empty($socid) ? '?socid=' . $socid : '') . '">' . $langs->trans("BackToList") . '</a>';
  2606. $morehtmlref='<div class="refidno">';
  2607. // Ref customer
  2608. $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->facture->creer, 'string', '', 0, 1);
  2609. $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->facture->creer, 'string', '', null, null, '', 1);
  2610. // Thirdparty
  2611. $morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1);
  2612. // Project
  2613. if (! empty($conf->projet->enabled))
  2614. {
  2615. $langs->load("projects");
  2616. $morehtmlref.='<br>'.$langs->trans('Project') . ' ';
  2617. if ($user->rights->facture->creer)
  2618. {
  2619. if ($action != 'classify')
  2620. $morehtmlref.='<a href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : ';
  2621. if ($action == 'classify') {
  2622. //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
  2623. $morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
  2624. $morehtmlref.='<input type="hidden" name="action" value="classin">';
  2625. $morehtmlref.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  2626. $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
  2627. $morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  2628. $morehtmlref.='</form>';
  2629. } else {
  2630. $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
  2631. }
  2632. } else {
  2633. if (! empty($object->fk_project)) {
  2634. $proj = new Project($db);
  2635. $proj->fetch($object->fk_project);
  2636. $morehtmlref.='<a href="'.DOL_URL_ROOT.'/projet/card.php?id=' . $object->fk_project . '" title="' . $langs->trans('ShowProject') . '">';
  2637. $morehtmlref.=$proj->ref;
  2638. $morehtmlref.='</a>';
  2639. } else {
  2640. $morehtmlref.='';
  2641. }
  2642. }
  2643. }
  2644. $morehtmlref.='</div>';
  2645. $object->totalpaye = $totalpaye; // To give a chance to dol_banner_tab to use already paid amount to show correct status
  2646. dol_banner_tab($object, 'ref', $linkback, 1, 'facnumber', 'ref', $morehtmlref, '', 0, '', '');
  2647. print '<div class="fichecenter">';
  2648. print '<div class="fichehalfleft">';
  2649. print '<div class="underbanner clearboth"></div>';
  2650. print '<table class="border" width="100%">';
  2651. // Type
  2652. print '<tr><td class="titlefield">' . $langs->trans('Type') . '</td><td>';
  2653. print $object->getLibType();
  2654. if ($object->type == Facture::TYPE_REPLACEMENT) {
  2655. $facreplaced = new Facture($db);
  2656. $facreplaced->fetch($object->fk_facture_source);
  2657. print ' (' . $langs->transnoentities("ReplaceInvoice", $facreplaced->getNomUrl(1)) . ')';
  2658. }
  2659. if ($object->type == Facture::TYPE_CREDIT_NOTE && !empty($object->fk_facture_source)) {
  2660. $facusing = new Facture($db);
  2661. $facusing->fetch($object->fk_facture_source);
  2662. print ' (' . $langs->transnoentities("CorrectInvoice", $facusing->getNomUrl(1)) . ')';
  2663. }
  2664. $facidavoir = $object->getListIdAvoirFromInvoice();
  2665. if (count($facidavoir) > 0) {
  2666. print ' (' . $langs->transnoentities("InvoiceHasAvoir");
  2667. $i = 0;
  2668. foreach ($facidavoir as $id) {
  2669. if ($i == 0)
  2670. print ' ';
  2671. else
  2672. print ',';
  2673. $facavoir = new Facture($db);
  2674. $facavoir->fetch($id);
  2675. print $facavoir->getNomUrl(1);
  2676. }
  2677. print ')';
  2678. }
  2679. if ($objectidnext > 0) {
  2680. $facthatreplace = new Facture($db);
  2681. $facthatreplace->fetch($objectidnext);
  2682. print ' (' . $langs->transnoentities("ReplacedByInvoice", $facthatreplace->getNomUrl(1)) . ')';
  2683. }
  2684. print '</td></tr>';
  2685. // Relative and absolute discounts
  2686. $addrelativediscount = '<a href="' . DOL_URL_ROOT . '/comm/remise.php?id=' . $soc->id . '&backtopage=' . urlencode($_SERVER["PHP_SELF"]) . '?facid=' . $object->id . '">' . $langs->trans("EditRelativeDiscounts") . '</a>';
  2687. $addabsolutediscount = '<a href="' . DOL_URL_ROOT . '/comm/remx.php?id=' . $soc->id . '&backtopage=' . urlencode($_SERVER["PHP_SELF"]) . '?facid=' . $object->id . '">' . $langs->trans("EditGlobalDiscounts") . '</a>';
  2688. $addcreditnote = '<a href="' . DOL_URL_ROOT . '/compta/facture.php?action=create&socid=' . $soc->id . '&type=2&backtopage=' . urlencode($_SERVER["PHP_SELF"]) . '?facid=' . $object->id . '">' . $langs->trans("AddCreditNote") . '</a>';
  2689. print '<tr><td>' . $langs->trans('Discounts');
  2690. print '</td><td>';
  2691. if ($soc->remise_percent)
  2692. print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent);
  2693. else
  2694. print $langs->trans("CompanyHasNoRelativeDiscount");
  2695. // print ' ('.$addrelativediscount.')';
  2696. if ($absolute_discount > 0) {
  2697. print '. ';
  2698. if ($object->statut > 0 || $object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT) {
  2699. if ($object->statut == 0) {
  2700. print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency));
  2701. print '. ';
  2702. } else {
  2703. if ($object->statut < 1 || $object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT) {
  2704. $text = $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency));
  2705. print '<br>' . $text . '.<br>';
  2706. } else {
  2707. $text = $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency));
  2708. $text2 = $langs->trans("AbsoluteDiscountUse");
  2709. print $form->textwithpicto($text, $text2);
  2710. }
  2711. }
  2712. } else {
  2713. // Discount available of type fixed amount (not credit note)
  2714. print '<br>';
  2715. $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, GETPOST('discountid'), 'remise_id', $soc->id, $absolute_discount, $filterabsolutediscount, $resteapayer, ' (' . $addabsolutediscount . ')');
  2716. }
  2717. } else {
  2718. if ($absolute_creditnote > 0) // If not, link will be added later
  2719. {
  2720. if ($object->statut == 0 && $object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_DEPOSIT)
  2721. print ' (' . $addabsolutediscount . ')<br>';
  2722. else
  2723. print '. ';
  2724. } else
  2725. print '. ';
  2726. }
  2727. if ($absolute_creditnote > 0)
  2728. {
  2729. // If validated, we show link "add credit note to payment"
  2730. if ($object->statut != 1 || $object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT) {
  2731. if ($object->statut == 0 && $object->type != Facture::TYPE_DEPOSIT) {
  2732. $text = $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency));
  2733. print $form->textwithpicto($text, $langs->trans("CreditNoteDepositUse"));
  2734. } else {
  2735. print $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)) . '.';
  2736. }
  2737. } else {
  2738. // Remise dispo de type avoir
  2739. if (! $absolute_discount)
  2740. print '<br>';
  2741. // $form->form_remise_dispo($_SERVER["PHP_SELF"].'?facid='.$object->id, 0, 'remise_id_for_payment', $soc->id, $absolute_creditnote, $filtercreditnote, $resteapayer
  2742. $more=' ('.$addcreditnote.')';
  2743. $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, 0, 'remise_id_for_payment', $soc->id, $absolute_creditnote, $filtercreditnote, 0, $more); // We allow credit note even if amount is higher
  2744. }
  2745. }
  2746. if (! $absolute_discount && ! $absolute_creditnote) {
  2747. print $langs->trans("CompanyHasNoAbsoluteDiscount");
  2748. if ($object->statut == 0 && $object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_DEPOSIT)
  2749. print ' (' . $addabsolutediscount . ')<br>';
  2750. else
  2751. print '. ';
  2752. }
  2753. // if ($object->statut == 0 && $object->type != 2 && $object->type != 3)
  2754. // {
  2755. // if (! $absolute_discount && ! $absolute_creditnote) print '<br>';
  2756. // print ' &nbsp; - &nbsp; ';
  2757. // print $addabsolutediscount;
  2758. // print ' &nbsp; - &nbsp; '.$addcreditnote; // We disbale link to credit note
  2759. // }
  2760. print '</td></tr>';
  2761. // Date invoice
  2762. print '<tr><td>';
  2763. print '<table class="nobordernopadding" width="100%"><tr><td>';
  2764. print $langs->trans('DateInvoice');
  2765. print '</td>';
  2766. if ($object->type != Facture::TYPE_CREDIT_NOTE && $action != 'editinvoicedate' && ! empty($object->brouillon) && $user->rights->facture->creer && empty($conf->global->FAC_FORCE_DATE_VALIDATION))
  2767. print '<td align="right"><a href="' . $_SERVER["PHP_SELF"] . '?action=editinvoicedate&amp;facid=' . $object->id . '">' . img_edit($langs->trans('SetDate'), 1) . '</a></td>';
  2768. print '</tr></table>';
  2769. print '</td><td>';
  2770. if ($object->type != Facture::TYPE_CREDIT_NOTE) {
  2771. if ($action == 'editinvoicedate') {
  2772. $form->form_date($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->date, 'invoicedate');
  2773. } else {
  2774. print dol_print_date($object->date, 'day');
  2775. }
  2776. } else {
  2777. print dol_print_date($object->date, 'day');
  2778. }
  2779. print '</td>';
  2780. print '</tr>';
  2781. if (! empty($conf->global->INVOICE_POINTOFTAX_DATE))
  2782. {
  2783. // Date invoice
  2784. print '<tr><td>';
  2785. print '<table class="nobordernopadding" width="100%"><tr><td>';
  2786. print $langs->trans('DatePointOfTax');
  2787. print '</td>';
  2788. print '<td align="right"><a href="' . $_SERVER["PHP_SELF"] . '?action=editdate_pointoftax&amp;facid=' . $object->id . '">' . img_edit($langs->trans('SetDate'), 1) . '</a></td>';
  2789. print '</tr></table>';
  2790. print '</td><td>';
  2791. if ($action == 'editdate_pointoftax') {
  2792. $form->form_date($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->date_pointoftax, 'date_pointoftax');
  2793. } else {
  2794. print dol_print_date($object->date_pointoftax, 'day');
  2795. }
  2796. print '</td></tr>';
  2797. }
  2798. // Payment term
  2799. print '<tr><td>';
  2800. print '<table class="nobordernopadding" width="100%"><tr><td>';
  2801. print $langs->trans('PaymentConditionsShort');
  2802. print '</td>';
  2803. if ($object->type != Facture::TYPE_CREDIT_NOTE && $action != 'editconditions' && ! empty($object->brouillon) && $user->rights->facture->creer)
  2804. print '<td align="right"><a href="' . $_SERVER["PHP_SELF"] . '?action=editconditions&amp;facid=' . $object->id . '">' . img_edit($langs->trans('SetConditions'), 1) . '</a></td>';
  2805. print '</tr></table>';
  2806. print '</td><td>';
  2807. if ($object->type != Facture::TYPE_CREDIT_NOTE)
  2808. {
  2809. if ($action == 'editconditions') {
  2810. $form->form_conditions_reglement($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->cond_reglement_id, 'cond_reglement_id');
  2811. } else {
  2812. $form->form_conditions_reglement($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->cond_reglement_id, 'none');
  2813. }
  2814. } else {
  2815. print '&nbsp;';
  2816. }
  2817. print '</td></tr>';
  2818. // Date payment term
  2819. print '<tr><td>';
  2820. print '<table class="nobordernopadding" width="100%"><tr><td>';
  2821. print $langs->trans('DateMaxPayment');
  2822. print '</td>';
  2823. if ($object->type != Facture::TYPE_CREDIT_NOTE && $action != 'editpaymentterm' && ! empty($object->brouillon) && $user->rights->facture->creer)
  2824. print '<td align="right"><a href="' . $_SERVER["PHP_SELF"] . '?action=editpaymentterm&amp;facid=' . $object->id . '">' . img_edit($langs->trans('SetDate'), 1) . '</a></td>';
  2825. print '</tr></table>';
  2826. print '</td><td>';
  2827. if ($object->type != Facture::TYPE_CREDIT_NOTE)
  2828. {
  2829. if ($action == 'editpaymentterm') {
  2830. $form->form_date($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->date_lim_reglement, 'paymentterm');
  2831. } else {
  2832. print dol_print_date($object->date_lim_reglement, 'day');
  2833. if ($object->hasDelay()) {
  2834. print img_warning($langs->trans('Late'));
  2835. }
  2836. }
  2837. } else {
  2838. print '&nbsp;';
  2839. }
  2840. print '</td></tr>';
  2841. // Payment mode
  2842. print '<tr><td>';
  2843. print '<table class="nobordernopadding" width="100%"><tr><td>';
  2844. print $langs->trans('PaymentMode');
  2845. print '</td>';
  2846. if ($action != 'editmode' && ! empty($object->brouillon) && $user->rights->facture->creer)
  2847. print '<td align="right"><a href="' . $_SERVER["PHP_SELF"] . '?action=editmode&amp;facid=' . $object->id . '">' . img_edit($langs->trans('SetMode'), 1) . '</a></td>';
  2848. print '</tr></table>';
  2849. print '</td><td>';
  2850. if ($action == 'editmode')
  2851. {
  2852. $form->form_modes_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->mode_reglement_id, 'mode_reglement_id', 'CRDT');
  2853. }
  2854. else
  2855. {
  2856. $form->form_modes_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->mode_reglement_id, 'none', 'CRDT');
  2857. }
  2858. print '</td></tr>';
  2859. // Multicurrency
  2860. if (! empty($conf->multicurrency->enabled))
  2861. {
  2862. // Multicurrency code
  2863. print '<tr>';
  2864. print '<td>';
  2865. print '<table class="nobordernopadding" width="100%"><tr><td>';
  2866. print fieldLabel('Currency','multicurrency_code');
  2867. print '</td>';
  2868. if ($action != 'editmulticurrencycode' && ! empty($object->brouillon))
  2869. print '<td align="right"><a href="' . $_SERVER["PHP_SELF"] . '?action=editmulticurrencycode&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1) . '</a></td>';
  2870. print '</tr></table>';
  2871. print '</td><td>';
  2872. if ($action == 'editmulticurrencycode') {
  2873. $form->form_multicurrency_code($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_code, 'multicurrency_code');
  2874. } else {
  2875. $form->form_multicurrency_code($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_code, 'none');
  2876. }
  2877. print '</td></tr>';
  2878. // Multicurrency rate
  2879. //if ($object->multicurrency_code != $conf->currency)
  2880. //{
  2881. print '<tr>';
  2882. print '<td>';
  2883. print '<table class="nobordernopadding" width="100%"><tr><td>';
  2884. print fieldLabel('CurrencyRate','multicurrency_tx');
  2885. print '</td>';
  2886. if ($action != 'editmulticurrencyrate' && ! empty($object->brouillon) && $object->multicurrency_code && $object->multicurrency_code != $conf->currency)
  2887. print '<td align="right"><a href="' . $_SERVER["PHP_SELF"] . '?action=editmulticurrencyrate&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1) . '</a></td>';
  2888. print '</tr></table>';
  2889. print '</td><td>';
  2890. if ($action == 'editmulticurrencyrate' || $action == 'actualizemulticurrencyrate') {
  2891. if($action == 'actualizemulticurrencyrate') {
  2892. list($object->fk_multicurrency, $object->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($object->db, $object->multicurrency_code);
  2893. }
  2894. $form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_tx, 'multicurrency_tx', $object->multicurrency_code);
  2895. } else {
  2896. $form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_tx, 'none', $object->multicurrency_code);
  2897. if($object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) {
  2898. print '<div class="inline-block"> &nbsp; &nbsp; &nbsp; &nbsp; ';
  2899. print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=actualizemulticurrencyrate">'.$langs->trans("ActualizeCurrency").'</a>';
  2900. print '</div>';
  2901. }
  2902. }
  2903. print '</td></tr>';
  2904. //}
  2905. }
  2906. // Bank Account
  2907. print '<tr><td class="nowrap">';
  2908. print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">';
  2909. print $langs->trans('BankAccount');
  2910. print '<td>';
  2911. if (($action != 'editbankaccount') && $user->rights->facture->creer && ! empty($object->brouillon))
  2912. print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editbankaccount&amp;id='.$object->id.'">'.img_edit($langs->trans('SetBankAccount'),1).'</a></td>';
  2913. print '</tr></table>';
  2914. print '</td><td>';
  2915. if ($action == 'editbankaccount')
  2916. {
  2917. $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1);
  2918. }
  2919. else
  2920. {
  2921. $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none');
  2922. }
  2923. print "</td>";
  2924. print '</tr>';
  2925. // Situations
  2926. if (! empty($conf->global->INVOICE_USE_SITUATION))
  2927. {
  2928. if ($object->type == 5 && ($object->situation_counter > 1))
  2929. {
  2930. $prevsits = $object->get_prev_sits();
  2931. print '<tr><td>';
  2932. print $langs->trans('SituationAmount');
  2933. print ' ';
  2934. print $prevsits[0]->situation_counter;
  2935. $cprevsits = count($prevsits);
  2936. for ($i = 1; $i < $cprevsits; $i++) {
  2937. print ' + ';
  2938. print $prevsits[$i]->situation_counter;
  2939. }
  2940. print ' + ';
  2941. print $object->situation_counter;
  2942. print '</td>';
  2943. print '<td align="right" class="nowrap">';
  2944. $prevsits_total_amount = 0;
  2945. foreach ($prevsits as $situation) {
  2946. $prevsits_total_amount += $situation->total_ht;
  2947. }
  2948. $prevsits_total_amount += $object->total_ht;
  2949. print price($prevsits_total_amount);
  2950. print '</td>';
  2951. print '<td>' . $langs->trans('Currency' . $conf->currency) . '</td></tr>';
  2952. // Previous situation(s) deduction(s)
  2953. for ($i = 0; $i < $cprevsits; $i++) {
  2954. print '<tr><td>';
  2955. print '<a href="' . $_SERVER['PHP_SELF'] . '?facid=' . $prevsits[$i]->id . '">';
  2956. print $langs->trans('SituationDeduction');
  2957. print ' ';
  2958. print $prevsits[$i]->situation_counter;
  2959. print '</a></td>';
  2960. print '<td align="right" class="nowrap">';
  2961. print '- ' . price($prevsits[$i]->total_ht);
  2962. print '</td>';
  2963. print '<td>' . $langs->trans('Currency' . $conf->currency) . '</td></tr>';
  2964. }
  2965. }
  2966. }
  2967. // Incoterms
  2968. if (!empty($conf->incoterm->enabled))
  2969. {
  2970. print '<tr><td>';
  2971. print '<table width="100%" class="nobordernopadding"><tr><td>';
  2972. print $langs->trans('IncotermLabel');
  2973. print '<td><td align="right">';
  2974. if ($user->rights->facture->creer) print '<a href="'.DOL_URL_ROOT.'/compta/facture.php?facid='.$object->id.'&action=editincoterm">'.img_edit().'</a>';
  2975. else print '&nbsp;';
  2976. print '</td></tr></table>';
  2977. print '</td>';
  2978. print '<td>';
  2979. if ($action != 'editincoterm')
  2980. {
  2981. print $form->textwithpicto($object->display_incoterms(), $object->libelle_incoterms, 1);
  2982. }
  2983. else
  2984. {
  2985. print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms)?$object->location_incoterms:''), $_SERVER['PHP_SELF'].'?id='.$object->id);
  2986. }
  2987. print '</td></tr>';
  2988. }
  2989. // Other attributes
  2990. $cols = 2;
  2991. include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php';
  2992. print '</table>';
  2993. print '</div>';
  2994. print '<div class="fichehalfright">';
  2995. print '<div class="ficheaddleft">';
  2996. print '<div class="underbanner clearboth"></div>';
  2997. print '<table class="border centpercent">';
  2998. if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency))
  2999. {
  3000. // Multicurrency Amount HT
  3001. print '<tr><td class="titlefieldmiddle">' . fieldLabel('MulticurrencyAmountHT','multicurrency_total_ht') . '</td>';
  3002. print '<td class="nowrap">' . price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '</td>';
  3003. print '</tr>';
  3004. // Multicurrency Amount VAT
  3005. print '<tr><td>' . fieldLabel('MulticurrencyAmountVAT','multicurrency_total_tva') . '</td>';
  3006. print '<td class="nowrap">' . price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '</td>';
  3007. print '</tr>';
  3008. // Multicurrency Amount TTC
  3009. print '<tr><td>' . fieldLabel('MulticurrencyAmountTTC','multicurrency_total_ttc') . '</td>';
  3010. print '<td class="nowrap">' . price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '</td>';
  3011. print '</tr>';
  3012. }
  3013. // Amount
  3014. print '<tr><td class="titlefield">' . $langs->trans('AmountHT') . '</td>';
  3015. print '<td class="nowrap">' . price($object->total_ht, 1, '', 1, - 1, - 1, $conf->currency) . '</td></tr>';
  3016. // Vat
  3017. print '<tr><td>' . $langs->trans('AmountVAT') . '</td><td colspan="3" class="nowrap">' . price($object->total_tva, 1, '', 1, - 1, - 1, $conf->currency) . '</td></tr>';
  3018. print '</tr>';
  3019. // Amount Local Taxes
  3020. if (($mysoc->localtax1_assuj == "1" && $mysoc->useLocalTax(1)) || $object->total_localtax1 != 0) // Localtax1
  3021. {
  3022. print '<tr><td>' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '</td>';
  3023. print '<td class="nowrap">' . price($object->total_localtax1, 1, '', 1, - 1, - 1, $conf->currency) . '</td></tr>';
  3024. }
  3025. if (($mysoc->localtax2_assuj == "1" && $mysoc->useLocalTax(2)) || $object->total_localtax2 != 0) // Localtax2
  3026. {
  3027. print '<tr><td>' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '</td>';
  3028. print '<td class=nowrap">' . price($object->total_localtax2, 1, '', 1, - 1, - 1, $conf->currency) . '</td></tr>';
  3029. }
  3030. // Revenue stamp
  3031. if ($selleruserevenustamp) // Test company use revenue stamp
  3032. {
  3033. print '<tr><td>';
  3034. print '<table class="nobordernopadding" width="100%"><tr><td>';
  3035. print $langs->trans('RevenueStamp');
  3036. print '</td>';
  3037. if ($action != 'editrevenuestamp' && ! empty($object->brouillon) && $user->rights->facture->creer)
  3038. {
  3039. print '<td align="right"><a href="' . $_SERVER["PHP_SELF"] . '?action=editrevenuestamp&amp;facid=' . $object->id . '">' . img_edit($langs->trans('SetRevenuStamp'), 1) . '</a></td>';
  3040. }
  3041. print '</tr></table>';
  3042. print '</td><td>';
  3043. if ($action == 'editrevenuestamp') {
  3044. print '<form action="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '" method="post">';
  3045. print '<input type="hidden" name="token" value="' . $_SESSION ['newtoken'] . '">';
  3046. print '<input type="hidden" name="action" value="setrevenuestamp">';
  3047. print $formother->select_revenue_stamp(GETPOST('revenuestamp'), 'revenuestamp', $mysoc->country_code);
  3048. // print '<input type="text" class="flat" size="4" name="revenuestamp" value="'.price2num($object->revenuestamp).'">';
  3049. print ' <input type="submit" class="button" value="' . $langs->trans('Modify') . '">';
  3050. print '</form>';
  3051. } else {
  3052. print price($object->revenuestamp, 1, '', 1, - 1, - 1, $conf->currency);
  3053. }
  3054. print '</td></tr>';
  3055. }
  3056. // Total with tax
  3057. print '<tr><td>' . $langs->trans('AmountTTC') . '</td><td class="nowrap">' . price($object->total_ttc, 1, '', 1, - 1, - 1, $conf->currency) . '</td></tr>';
  3058. print '</table>';
  3059. // List of previous situation invoices
  3060. $sign = 1;
  3061. if ($object->type == Facture::TYPE_CREDIT_NOTE) $sign = - 1;
  3062. $nbrows = 8;
  3063. $nbcols = 3;
  3064. if (! empty($conf->projet->enabled))
  3065. $nbrows ++;
  3066. if (! empty($conf->banque->enabled)) {
  3067. $nbrows ++;
  3068. $nbcols ++;
  3069. }
  3070. if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0)
  3071. $nbrows ++;
  3072. if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0)
  3073. $nbrows ++;
  3074. if ($selleruserevenustamp)
  3075. $nbrows ++;
  3076. if (! empty($conf->multicurrency->enabled))
  3077. $nbrows += 5;
  3078. if (! empty($conf->incoterm->enabled))
  3079. $nbrows += 1;
  3080. if ($object->type == Facture::TYPE_SITUATION && ! empty($conf->global->INVOICE_USE_SITUATION))
  3081. {
  3082. if (count($object->tab_previous_situation_invoice) > 0 || count($object->tab_next_situation_invoice) > 0)
  3083. print '<table class="nobordernopadding paymenttable" width="100%">';
  3084. if (count($object->tab_previous_situation_invoice) > 0) {
  3085. // List of previous invoices
  3086. print '<tr class="liste_titre">';
  3087. print '<td>' . $langs->trans('ListOfPreviousSituationInvoices') . '</td>';
  3088. print '<td></td>';
  3089. if (! empty($conf->banque->enabled))
  3090. print '<td align="right"></td>';
  3091. print '<td align="right">' . $langs->trans('AmountHT') . '</td>';
  3092. print '<td align="right">' . $langs->trans('AmountTTC') . '</td>';
  3093. print '<td width="18">&nbsp;</td>';
  3094. print '</tr>';
  3095. $total_prev_ht = $total_prev_ttc = 0;
  3096. $var = true;
  3097. foreach ($object->tab_previous_situation_invoice as $prev_invoice) {
  3098. $totalpaye = $prev_invoice->getSommePaiement();
  3099. $total_prev_ht += $prev_invoice->total_ht;
  3100. $total_prev_ttc += $prev_invoice->total_ttc;
  3101. print '<tr ' . $bc[$var] . '>';
  3102. print '<td>' . $prev_invoice->getNomUrl(1) . '</td>';
  3103. print '<td></td>';
  3104. if (! empty($conf->banque->enabled))
  3105. print '<td align="right"></td>';
  3106. print '<td align="right">' . price($prev_invoice->total_ht) . '</td>';
  3107. print '<td align="right">' . price($prev_invoice->total_ttc) . '</td>';
  3108. print '<td align="right">' . $prev_invoice->getLibStatut(3, $totalpaye) . '</td>';
  3109. print '</tr>';
  3110. $var = ! $var;
  3111. }
  3112. print '<tr ' . $bc[$var] . '>';
  3113. print '<td colspan="2" align="right"></td>';
  3114. print '<td align="right"><b>' . price($total_prev_ht) . '</b></td>';
  3115. print '<td align="right"><b>' . price($total_prev_ttc) . '</b></td>';
  3116. print '<td width="18">&nbsp;</td>';
  3117. print '</tr>';
  3118. }
  3119. if (count($object->tab_next_situation_invoice) > 0) {
  3120. // List of next invoices
  3121. print '<tr class="liste_titre">';
  3122. print '<td>' . $langs->trans('ListOfNextSituationInvoices') . '</td>';
  3123. print '<td></td>';
  3124. if (! empty($conf->banque->enabled))
  3125. print '<td align="right"></td>';
  3126. print '<td align="right">' . $langs->trans('AmountHT') . '</td>';
  3127. print '<td align="right">' . $langs->trans('AmountTTC') . '</td>';
  3128. print '<td width="18">&nbsp;</td>';
  3129. print '</tr>';
  3130. $total_next_ht = $total_next_ttc = 0;
  3131. $var = true;
  3132. foreach ($object->tab_next_situation_invoice as $next_invoice) {
  3133. $totalpaye = $next_invoice->getSommePaiement();
  3134. $total_next_ht += $next_invoice->total_ht;
  3135. $total_next_ttc += $next_invoice->total_ttc;
  3136. print '<tr ' . $bc[$var] . '>';
  3137. print '<td>' . $next_invoice->getNomUrl(1) . '</td>';
  3138. print '<td></td>';
  3139. if (! empty($conf->banque->enabled))
  3140. print '<td align="right"></td>';
  3141. print '<td align="right">' . price($next_invoice->total_ht) . '</td>';
  3142. print '<td align="right">' . price($next_invoice->total_ttc) . '</td>';
  3143. print '<td align="right">' . $next_invoice->getLibStatut(3, $totalpaye) . '</td>';
  3144. print '</tr>';
  3145. $var = ! $var;
  3146. }
  3147. print '<tr ' . $bc[$var] . '>';
  3148. print '<td colspan="2" align="right"></td>';
  3149. print '<td align="right"><b>' . price($total_next_ht) . '</b></td>';
  3150. print '<td align="right"><b>' . price($total_next_ttc) . '</b></td>';
  3151. print '<td width="18">&nbsp;</td>';
  3152. print '</tr>';
  3153. }
  3154. if (count($object->tab_previous_situation_invoice) > 0 || count($object->tab_next_situation_invoice) > 0)
  3155. print '</table>';
  3156. }
  3157. // List of payments already done
  3158. print '<table class="noborder paymenttable" width="100%">';
  3159. print '<tr class="liste_titre">';
  3160. print '<td class="liste_titre">' . ($object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("PaymentsBack") : $langs->trans('Payments')) . '</td>';
  3161. print '<td class="liste_titre">' . $langs->trans('Date') . '</td>';
  3162. print '<td class="liste_titre">' . $langs->trans('Type') . '</td>';
  3163. if (! empty($conf->banque->enabled)) {
  3164. print '<td class="liste_titre" align="right">' . $langs->trans('BankAccount') . '</td>';
  3165. }
  3166. print '<td class="liste_titre" align="right">' . $langs->trans('Amount') . '</td>';
  3167. print '<td class="liste_titre" width="18">&nbsp;</td>';
  3168. print '</tr>';
  3169. $var = true;
  3170. // Payments already done (from payment on this invoice)
  3171. $sql = 'SELECT p.datep as dp, p.ref, p.num_paiement, p.rowid, p.fk_bank,';
  3172. $sql .= ' c.code as payment_code, c.libelle as payment_label,';
  3173. $sql .= ' pf.amount,';
  3174. $sql .= ' ba.rowid as baid, ba.ref as baref, ba.label';
  3175. $sql .= ' FROM ' . MAIN_DB_PREFIX . 'c_paiement as c, ' . MAIN_DB_PREFIX . 'paiement_facture as pf, ' . MAIN_DB_PREFIX . 'paiement as p';
  3176. $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'bank as b ON p.fk_bank = b.rowid';
  3177. $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'bank_account as ba ON b.fk_account = ba.rowid';
  3178. $sql .= ' WHERE pf.fk_facture = ' . $object->id . ' AND p.fk_paiement = c.id AND pf.fk_paiement = p.rowid';
  3179. $sql .= ' ORDER BY p.datep, p.tms';
  3180. $result = $db->query($sql);
  3181. if ($result) {
  3182. $num = $db->num_rows($result);
  3183. $i = 0;
  3184. // if ($object->type != 2)
  3185. // {
  3186. if ($num > 0) {
  3187. while ($i < $num) {
  3188. $objp = $db->fetch_object($result);
  3189. $var = ! $var;
  3190. print '<tr ' . $bc[$var] . '><td>';
  3191. $paymentstatic->id = $objp->rowid;
  3192. $paymentstatic->datepaye = $db->jdate($objp->dp);
  3193. $paymentstatic->ref = $objp->ref;
  3194. $paymentstatic->num_paiement = $objp->num_paiement;
  3195. $paymentstatic->payment_code = $objp->payment_code;
  3196. print $paymentstatic->getNomUrl(1);
  3197. print '</td>';
  3198. print '<td>' . dol_print_date($db->jdate($objp->dp), 'day') . '</td>';
  3199. $label = ($langs->trans("PaymentType" . $objp->payment_code) != ("PaymentType" . $objp->payment_code)) ? $langs->trans("PaymentType" . $objp->payment_code) : $objp->payment_label;
  3200. print '<td>' . $label . ' ' . $objp->num_paiement . '</td>';
  3201. if (! empty($conf->banque->enabled)) {
  3202. $bankaccountstatic->id = $objp->baid;
  3203. $bankaccountstatic->ref = $objp->baref;
  3204. $bankaccountstatic->label = $objp->baref;
  3205. print '<td align="right">';
  3206. if ($bankaccountstatic->id)
  3207. print $bankaccountstatic->getNomUrl(1, 'transactions');
  3208. print '</td>';
  3209. }
  3210. print '<td align="right">' . price($sign * $objp->amount) . '</td>';
  3211. print '<td>&nbsp;</td>';
  3212. print '</tr>';
  3213. $i ++;
  3214. }
  3215. } else {
  3216. print '<tr ' . $bc[false] . '><td colspan="' . $nbcols . '" class="opacitymedium">' . $langs->trans("None") . '</td><td></td><td></td></tr>';
  3217. }
  3218. // }
  3219. $db->free($result);
  3220. } else {
  3221. dol_print_error($db);
  3222. }
  3223. if ($object->type != Facture::TYPE_CREDIT_NOTE) {
  3224. // Total already paid
  3225. print '<tr><td colspan="' . $nbcols . '" align="right">';
  3226. if ($object->type != Facture::TYPE_DEPOSIT)
  3227. print $langs->trans('AlreadyPaidNoCreditNotesNoDeposits');
  3228. else
  3229. print $langs->trans('AlreadyPaid');
  3230. print ' :</td><td align="right"'.(($totalpaye > 0)?' class="amountalreadypaid"':'').'>' . price($totalpaye) . '</td><td>&nbsp;</td></tr>';
  3231. $resteapayeraffiche = $resteapayer;
  3232. $cssforamountpaymentcomplete = 'amountpaymentcomplete';
  3233. // Loop on each credit note or deposit amount applied
  3234. $creditnoteamount = 0;
  3235. $depositamount = 0;
  3236. $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
  3237. $sql .= " re.description, re.fk_facture_source";
  3238. $sql .= " FROM " . MAIN_DB_PREFIX . "societe_remise_except as re";
  3239. $sql .= " WHERE fk_facture = " . $object->id;
  3240. $resql = $db->query($sql);
  3241. if ($resql) {
  3242. $num = $db->num_rows($resql);
  3243. $i = 0;
  3244. $invoice = new Facture($db);
  3245. while ($i < $num) {
  3246. $obj = $db->fetch_object($resql);
  3247. $invoice->fetch($obj->fk_facture_source);
  3248. print '<tr><td colspan="' . $nbcols . '" align="right">';
  3249. if ($invoice->type == Facture::TYPE_CREDIT_NOTE)
  3250. print $langs->trans("CreditNote") . ' ';
  3251. if ($invoice->type == Facture::TYPE_DEPOSIT)
  3252. print $langs->trans("Deposit") . ' ';
  3253. print $invoice->getNomUrl(0);
  3254. print ' :</td>';
  3255. print '<td align="right">' . price($obj->amount_ttc) . '</td>';
  3256. print '<td align="right">';
  3257. print '<a href="' . $_SERVER["PHP_SELF"] . '?facid=' . $object->id . '&action=unlinkdiscount&discountid=' . $obj->rowid . '">' . img_delete() . '</a>';
  3258. print '</td></tr>';
  3259. $i ++;
  3260. if ($invoice->type == Facture::TYPE_CREDIT_NOTE)
  3261. $creditnoteamount += $obj->amount_ttc;
  3262. if ($invoice->type == Facture::TYPE_DEPOSIT)
  3263. $depositamount += $obj->amount_ttc;
  3264. }
  3265. } else {
  3266. dol_print_error($db);
  3267. }
  3268. // Paye partiellement 'escompte'
  3269. if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'discount_vat') {
  3270. print '<tr><td colspan="' . $nbcols . '" align="right" class="nowrap">';
  3271. print $form->textwithpicto($langs->trans("Discount") . ':', $langs->trans("HelpEscompte"), - 1);
  3272. print '</td><td align="right">' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . '</td><td>&nbsp;</td></tr>';
  3273. $resteapayeraffiche = 0;
  3274. $cssforamountpaymentcomplete = '';
  3275. }
  3276. // Paye partiellement ou Abandon 'badcustomer'
  3277. if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'badcustomer') {
  3278. print '<tr><td colspan="' . $nbcols . '" align="right" class="nowrap">';
  3279. print $form->textwithpicto($langs->trans("Abandoned") . ':', $langs->trans("HelpAbandonBadCustomer"), - 1);
  3280. print '</td><td align="right">' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . '</td><td>&nbsp;</td></tr>';
  3281. // $resteapayeraffiche=0;
  3282. $cssforamountpaymentcomplete = '';
  3283. }
  3284. // Paye partiellement ou Abandon 'product_returned'
  3285. if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'product_returned') {
  3286. print '<tr><td colspan="' . $nbcols . '" align="right" class="nowrap">';
  3287. print $form->textwithpicto($langs->trans("ProductReturned") . ':', $langs->trans("HelpAbandonProductReturned"), - 1);
  3288. print '</td><td align="right">' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . '</td><td>&nbsp;</td></tr>';
  3289. $resteapayeraffiche = 0;
  3290. $cssforamountpaymentcomplete = '';
  3291. }
  3292. // Paye partiellement ou Abandon 'abandon'
  3293. if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'abandon') {
  3294. print '<tr><td colspan="' . $nbcols . '" align="right" class="nowrap">';
  3295. $text = $langs->trans("HelpAbandonOther");
  3296. if ($object->close_note)
  3297. $text .= '<br><br><b>' . $langs->trans("Reason") . '</b>:' . $object->close_note;
  3298. print $form->textwithpicto($langs->trans("Abandoned") . ':', $text, - 1);
  3299. print '</td><td align="right">' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . '</td><td>&nbsp;</td></tr>';
  3300. $resteapayeraffiche = 0;
  3301. $cssforamountpaymentcomplete = '';
  3302. }
  3303. // Billed
  3304. print '<tr><td colspan="' . $nbcols . '" align="right">' . $langs->trans("Billed") . ' :</td><td align="right">' . price($object->total_ttc) . '</td><td>&nbsp;</td></tr>';
  3305. // Remainder to pay
  3306. print '<tr><td colspan="' . $nbcols . '" align="right">';
  3307. if ($resteapayeraffiche >= 0)
  3308. print $langs->trans('RemainderToPay');
  3309. else
  3310. print $langs->trans('ExcessReceived');
  3311. print ' :</td>';
  3312. print '<td align="right"'.($resteapayeraffiche?' class="amountremaintopay"':(' class="'.$cssforamountpaymentcomplete.'"')).'>' . price($resteapayeraffiche) . '</td>';
  3313. print '<td class="nowrap">&nbsp;</td></tr>';
  3314. }
  3315. else // Credit note
  3316. {
  3317. $cssforamountpaymentcomplete='';
  3318. // Total already paid back
  3319. print '<tr><td colspan="' . $nbcols . '" align="right">';
  3320. print $langs->trans('AlreadyPaidBack');
  3321. print ' :</td><td align="right">' . price($sign * $totalpaye) . '</td><td>&nbsp;</td></tr>';
  3322. // Billed
  3323. print '<tr><td colspan="' . $nbcols . '" align="right">' . $langs->trans("Billed") . ' :</td><td align="right">' . price($sign * $object->total_ttc) . '</td><td>&nbsp;</td></tr>';
  3324. // Remainder to pay back
  3325. print '<tr><td colspan="' . $nbcols . '" align="right">';
  3326. if ($resteapayeraffiche <= 0)
  3327. print $langs->trans('RemainderToPayBack');
  3328. else
  3329. print $langs->trans('ExcessPaydBack');
  3330. print ' :</td>';
  3331. print '<td align="right"'.($resteapayeraffiche?' class="amountremaintopayback"':(' class="'.$cssforamountpaymentcomplete.'"')).'>' . price($sign * $resteapayeraffiche) . '</td>';
  3332. print '<td class="nowrap">&nbsp;</td></tr>';
  3333. // Sold credit note
  3334. // print '<tr><td colspan="'.$nbcols.'" align="right">'.$langs->trans('TotalTTC').' :</td>';
  3335. // print '<td align="right" style="border: 1px solid;" bgcolor="#f0f0f0"><b>'.price($sign *
  3336. // $object->total_ttc).'</b></td><td>&nbsp;</td></tr>';
  3337. }
  3338. print '</table>';
  3339. // Margin Infos
  3340. if (! empty($conf->margin->enabled)) {
  3341. $formmargin->displayMarginInfos($object);
  3342. }
  3343. print '</div>';
  3344. print '</div>';
  3345. print '</div>';
  3346. print '<div class="clearboth"></div><br>';
  3347. if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) {
  3348. $blocname = 'contacts';
  3349. $title = $langs->trans('ContactsAddresses');
  3350. include DOL_DOCUMENT_ROOT . '/core/tpl/bloc_showhide.tpl.php';
  3351. }
  3352. if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB)) {
  3353. $blocname = 'notes';
  3354. $title = $langs->trans('Notes');
  3355. include DOL_DOCUMENT_ROOT . '/core/tpl/bloc_showhide.tpl.php';
  3356. }
  3357. // Lines
  3358. $result = $object->getLinesArray();
  3359. // Show global modifiers
  3360. if (! empty($conf->global->INVOICE_USE_SITUATION))
  3361. {
  3362. if ($object->situation_cycle_ref && $object->statut == 0) {
  3363. print '<div class="div-table-responsive">';
  3364. print '<form name="updatealllines" id="updatealllines" action="' . $_SERVER['PHP_SELF'] . '?id=' . $object->id . '#updatealllines" method="POST">';
  3365. print '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '" />';
  3366. print '<input type="hidden" name="action" value="updatealllines" />';
  3367. print '<input type="hidden" name="id" value="' . $object->id . '" />';
  3368. print '<table id="tablelines_all_progress" class="noborder noshadow" width="100%">';
  3369. print '<tr class="liste_titre nodrag nodrop">';
  3370. if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) {
  3371. print '<td align="center" width="5">&nbsp;</td>';
  3372. }
  3373. print '<td>' . $langs->trans('ModifyAllLines') . '</td>';
  3374. print '<td align="right" width="50">&nbsp;</td>';
  3375. print '<td align="right" width="80">&nbsp;</td>';
  3376. if ($inputalsopricewithtax) print '<td align="right" width="80">&nbsp;</td>';
  3377. print '<td align="right" width="50">&nbsp</td>';
  3378. print '<td align="right" width="50">&nbsp</td>';
  3379. print '<td align="right" width="50">' . $langs->trans('Progress') . '</td>';
  3380. if (! empty($conf->margin->enabled) && empty($user->societe_id))
  3381. {
  3382. print '<td align="right" class="margininfos" width="80">&nbsp;</td>';
  3383. if ((! empty($conf->global->DISPLAY_MARGIN_RATES) || ! empty($conf->global->DISPLAY_MARK_RATES)) && $user->rights->margins->liretous) {
  3384. print '<td align="right" class="margininfos" width="50">&nbsp;</td>';
  3385. }
  3386. }
  3387. print '<td align="right" width="50">&nbsp;</td>';
  3388. print '<td>&nbsp;</td>';
  3389. print '<td width="10">&nbsp;</td>';
  3390. print '<td width="10">&nbsp;</td>';
  3391. print "</tr>\n";
  3392. if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) {
  3393. print '<td align="center" width="5">&nbsp;</td>';
  3394. }
  3395. print '<tr width="100%" class="nodrag nodrop">';
  3396. print '<td>&nbsp;</td>';
  3397. print '<td width="50">&nbsp;</td>';
  3398. print '<td width="80">&nbsp;</td>';
  3399. print '<td width="50">&nbsp;</td>';
  3400. print '<td width="50">&nbsp;</td>';
  3401. print '<td align="right" class="nowrap"><input type="text" size="1" value="" name="all_progress">%</td>';
  3402. print '<td colspan="4" align="right"><input class="button" type="submit" name="all_percent" value="Modifier" /></td>';
  3403. print '</tr>';
  3404. print '</table>';
  3405. print '</form>';
  3406. print '</div>';
  3407. }
  3408. }
  3409. print ' <form name="addproduct" id="addproduct" action="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . (($action != 'editline') ? '#add' : '#line_' . GETPOST('lineid')) . '" method="POST">
  3410. <input type="hidden" name="token" value="' . $_SESSION ['newtoken'] . '">
  3411. <input type="hidden" name="action" value="' . (($action != 'editline') ? 'addline' : 'updateligne') . '">
  3412. <input type="hidden" name="mode" value="">
  3413. <input type="hidden" name="id" value="' . $object->id . '">
  3414. ';
  3415. if (! empty($conf->use_javascript_ajax) && $object->statut == 0) {
  3416. include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php';
  3417. }
  3418. print '<div class="div-table-responsive">';
  3419. print '<table id="tablelines" class="noborder noshadow" width="100%">';
  3420. // Show object lines
  3421. if (! empty($object->lines))
  3422. $ret = $object->printObjectLines($action, $mysoc, $soc, $lineid, 1);
  3423. // Form to add new line
  3424. if ($object->statut == 0 && $user->rights->facture->creer && $action != 'valid' && $action != 'editline' && ($object->is_first() || !$object->situation_cycle_ref))
  3425. {
  3426. if ($action != 'editline')
  3427. {
  3428. $var = true;
  3429. // Add free products/services
  3430. $object->formAddObjectLine(1, $mysoc, $soc);
  3431. $parameters = array();
  3432. $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  3433. }
  3434. }
  3435. print "</table>\n";
  3436. print "</div>";
  3437. print "</form>\n";
  3438. dol_fiche_end();
  3439. // Actions buttons
  3440. if ($action != 'prerelance' && $action != 'presend' && $action != 'valid' && $action != 'editline')
  3441. {
  3442. print '<div class="tabsAction">';
  3443. $parameters = array();
  3444. $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  3445. if (empty($reshook)) {
  3446. // Editer une facture deja validee, sans paiement effectue et pas exporte en compta
  3447. if ($object->statut == 1)
  3448. {
  3449. // On verifie si les lignes de factures ont ete exportees en compta et/ou ventilees
  3450. $ventilExportCompta = $object->getVentilExportCompta();
  3451. if ($resteapayer == $object->total_ttc && empty($object->paye) && $ventilExportCompta == 0)
  3452. {
  3453. if (! $objectidnext && $object->is_last_in_cycle())
  3454. {
  3455. if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer))
  3456. || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->unvalidate)))
  3457. {
  3458. print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '&amp;action=modif">' . $langs->trans('Modify') . '</a></div>';
  3459. } else {
  3460. print '<div class="inline-block divButAction"><span class="butActionRefused" title="' . $langs->trans("NotEnoughPermissions") . '">' . $langs->trans('Modify') . '</span></div>';
  3461. }
  3462. } else if (!$object->is_last_in_cycle()) {
  3463. print '<div class="inline-block divButAction"><span class="butActionRefused" title="' . $langs->trans("NotLastInCycle") . '">' . $langs->trans('Modify') . '</span></div>';
  3464. } else {
  3465. print '<div class="inline-block divButAction"><span class="butActionRefused" title="' . $langs->trans("DisabledBecauseReplacedInvoice") . '">' . $langs->trans('Modify') . '</span></div>';
  3466. }
  3467. }
  3468. }
  3469. // Reopen a standard paid invoice
  3470. if ((($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT)
  3471. || ($object->type == Facture::TYPE_CREDIT_NOTE && empty($discount->id))
  3472. || ($object->type == Facture::TYPE_DEPOSIT && empty($discount->id)))
  3473. && ($object->statut == 2 || $object->statut == 3 || ($object->statut == 1 && $object->paye == 1)) // Condition ($object->statut == 1 && $object->paye == 1) should not happened but can be found due to corrupted data
  3474. && ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->facture->creer) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->facture->invoice_advance->reopen))) // A paid invoice (partially or completely)
  3475. {
  3476. if (! $objectidnext && $object->close_code != 'replaced') // Not replaced by another invoice
  3477. {
  3478. print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '&amp;action=reopen">' . $langs->trans('ReOpen') . '</a></div>';
  3479. } else {
  3480. print '<div class="inline-block divButAction"><span class="butActionRefused" title="' . $langs->trans("DisabledBecauseReplacedInvoice") . '">' . $langs->trans('ReOpen') . '</span></div>';
  3481. }
  3482. }
  3483. // Validate
  3484. if ($object->statut == 0 && count($object->lines) > 0 && ((($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA || $object->type == Facture::TYPE_SITUATION) && (! empty($conf->global->FACTURE_ENABLE_NEGATIVE) || $object->total_ttc >= 0)) || ($object->type == Facture::TYPE_CREDIT_NOTE && $object->total_ttc <= 0))) {
  3485. if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer))
  3486. || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->validate)))
  3487. {
  3488. print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER["PHP_SELF"] . '?facid=' . $object->id . '&amp;action=valid">' . $langs->trans('Validate') . '</a></div>';
  3489. }
  3490. }
  3491. // Send by mail
  3492. if (($object->statut == Facture::STATUS_VALIDATED || $object->statut == Facture::STATUS_CLOSED) || ! empty($conf->global->FACTURE_SENDBYEMAIL_FOR_ALL_STATUS)) {
  3493. if ($objectidnext) {
  3494. print '<div class="inline-block divButAction"><span class="butActionRefused" title="' . $langs->trans("DisabledBecauseReplacedInvoice") . '">' . $langs->trans('SendByMail') . '</span></div>';
  3495. } else {
  3496. if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->facture->invoice_advance->send) {
  3497. print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '&amp;action=presend&amp;mode=init">' . $langs->trans('SendByMail') . '</a></div>';
  3498. } else
  3499. print '<div class="inline-block divButAction"><a class="butActionRefused" href="#">' . $langs->trans('SendByMail') . '</a></div>';
  3500. }
  3501. }
  3502. // Request a direct debit order
  3503. if ($object->statut > Facture::STATUS_DRAFT && $object->paye == 0 && $num == 0)
  3504. {
  3505. if ($resteapayer > 0)
  3506. {
  3507. if ($user->rights->prelevement->bons->creer)
  3508. {
  3509. $langs->load("withdrawals");
  3510. print '<a class="butAction" href="'.DOL_URL_ROOT.'/compta/facture/prelevement.php?facid='.$object->id.'" title="'.dol_escape_htmltag($langs->trans("MakeWithdrawRequest")).'">'.$langs->trans("MakeWithdrawRequest").'</a>';
  3511. }
  3512. else
  3513. {
  3514. //print '<a class="butActionRefused" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans("MakeWithdrawRequest").'</a>';
  3515. }
  3516. }
  3517. else
  3518. {
  3519. //print '<a class="butActionRefused" href="#" title="'.dol_escape_htmltag($langs->trans("AmountMustBePositive")).'">'.$langs->trans("MakeWithdrawRequest").'</a>';
  3520. }
  3521. }
  3522. // Create payment
  3523. if ($object->type != Facture::TYPE_CREDIT_NOTE && $object->statut == 1 && $object->paye == 0 && $user->rights->facture->paiement) {
  3524. if ($objectidnext) {
  3525. print '<div class="inline-block divButAction"><span class="butActionRefused" title="' . $langs->trans("DisabledBecauseReplacedInvoice") . '">' . $langs->trans('DoPayment') . '</span></div>';
  3526. } else {
  3527. if ($resteapayer == 0) {
  3528. print '<div class="inline-block divButAction"><span class="butActionRefused" title="' . $langs->trans("DisabledBecauseRemainderToPayIsZero") . '">' . $langs->trans('DoPayment') . '</span></div>';
  3529. } else {
  3530. print '<div class="inline-block divButAction"><a class="butAction" href="paiement.php?facid=' . $object->id . '&amp;action=create&amp;accountid='.$object->fk_account.'">' . $langs->trans('DoPayment') . '</a></div>';
  3531. }
  3532. }
  3533. }
  3534. // Reverse back money or convert to reduction
  3535. if ($object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT) {
  3536. // For credit note only
  3537. if ($object->type == Facture::TYPE_CREDIT_NOTE && $object->statut == 1 && $object->paye == 0 && $user->rights->facture->paiement)
  3538. {
  3539. if ($resteapayer == 0)
  3540. {
  3541. print '<div class="inline-block divButAction"><span class="butActionRefused" title="'.$langs->trans("DisabledBecauseRemainderToPayIsZero").'">'.$langs->trans('DoPaymentBack').'</span></div>';
  3542. }
  3543. else
  3544. {
  3545. print '<div class="inline-block divButAction"><a class="butAction" href="paiement.php?facid='.$object->id.'&amp;action=create&amp;accountid='.$object->fk_account.'">'.$langs->trans('DoPaymentBack').'</a></div>';
  3546. }
  3547. }
  3548. // For credit note
  3549. if ($object->type == Facture::TYPE_CREDIT_NOTE && $object->statut == 1 && $object->paye == 0 && $user->rights->facture->creer && $object->getSommePaiement() == 0) {
  3550. print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER["PHP_SELF"] . '?facid=' . $object->id . '&amp;action=converttoreduc">' . $langs->trans('ConvertToReduc') . '</a></div>';
  3551. }
  3552. // For deposit invoice
  3553. if ($object->type == Facture::TYPE_DEPOSIT && $object->paye == 1 && $resteapayer == 0 && $user->rights->facture->creer && empty($discount->id))
  3554. {
  3555. print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=converttoreduc">'.$langs->trans('ConvertToReduc').'</a></div>';
  3556. }
  3557. }
  3558. // Classify paid
  3559. if ($object->statut == 1 && $object->paye == 0 && $user->rights->facture->paiement && (($object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_DEPOSIT && $resteapayer <= 0) || ($object->type == Facture::TYPE_CREDIT_NOTE && $resteapayer >= 0))
  3560. || ($object->type == Facture::TYPE_DEPOSIT && $object->paye == 0 && $object->total_ttc > 0 && $resteapayer == 0 && $user->rights->facture->paiement && empty($discount->id))
  3561. )
  3562. {
  3563. print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=paid">'.$langs->trans('ClassifyPaid').'</a></div>';
  3564. }
  3565. // Classify 'closed not completely paid' (possible si validee et pas encore classee payee)
  3566. if ($object->statut == 1 && $object->paye == 0 && $resteapayer > 0 && $user->rights->facture->paiement)
  3567. {
  3568. if ($totalpaye > 0 || $totalcreditnotes > 0)
  3569. {
  3570. // If one payment or one credit note was linked to this invoice
  3571. print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '&amp;action=paid">' . $langs->trans('ClassifyPaidPartially') . '</a></div>';
  3572. }
  3573. else
  3574. {
  3575. if ( empty($conf->global->INVOICE_CAN_NEVER_BE_CANCELED))
  3576. {
  3577. if ($objectidnext)
  3578. {
  3579. print '<div class="inline-block divButAction"><span class="butActionRefused" title="' . $langs->trans("DisabledBecauseReplacedInvoice") . '">' . $langs->trans('ClassifyCanceled') . '</span></div>';
  3580. }
  3581. else
  3582. {
  3583. print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '&amp;action=canceled">' . $langs->trans('ClassifyCanceled') . '</a></div>';
  3584. }
  3585. }
  3586. }
  3587. }
  3588. // Clone
  3589. if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA) && $user->rights->facture->creer)
  3590. {
  3591. print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '&amp;action=clone&amp;object=invoice">' . $langs->trans("ToClone") . '</a></div>';
  3592. }
  3593. // Clone as predefined / Create template
  3594. if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA) && $object->statut == 0 && $user->rights->facture->creer)
  3595. {
  3596. if (! $objectidnext && count($object->lines) > 0)
  3597. {
  3598. print '<div class="inline-block divButAction"><a class="butAction" href="facture/fiche-rec.php?facid=' . $object->id . '&amp;action=create">' . $langs->trans("ChangeIntoRepeatableInvoice") . '</a></div>';
  3599. }
  3600. }
  3601. // Create a credit note
  3602. if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA) && $object->statut > 0 && $user->rights->facture->creer)
  3603. {
  3604. if (! $objectidnext)
  3605. {
  3606. print '<div class="inline-block divButAction"><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></div>';
  3607. }
  3608. }
  3609. // Create next situation invoice
  3610. if ($user->rights->facture->creer && ($object->type == 5) && ($object->statut == 1 || $object->statut == 2)) {
  3611. if ($object->is_last_in_cycle() && $object->situation_final != 1) {
  3612. print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?action=create&amp;type=5&amp;origin=facture&amp;originid=' . $object->id . '&amp;socid=' . $object->socid . '" >' . $langs->trans('CreateNextSituationInvoice') . '</a></div>';
  3613. } else if (!$object->is_last_in_cycle()) {
  3614. print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="' . $langs->trans("DisabledBecauseNotLastInCycle") . '">' . $langs->trans('CreateNextSituationInvoice') . '</a></div>';
  3615. } else {
  3616. print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="' . $langs->trans("DisabledBecauseFinal") . '">' . $langs->trans('CreateNextSituationInvoice') . '</a></div>';
  3617. }
  3618. }
  3619. // Delete
  3620. if ($user->rights->facture->supprimer)
  3621. {
  3622. if (! $object->is_erasable()) {
  3623. print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="' . $langs->trans("DisabledBecauseNotErasable") . '">' . $langs->trans('Delete') . '</a></div>';
  3624. } else if ($objectidnext) {
  3625. print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="' . $langs->trans("DisabledBecauseReplacedInvoice") . '">' . $langs->trans('Delete') . '</a></div>';
  3626. } elseif ($object->getSommePaiement()) {
  3627. print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="' . $langs->trans("DisabledBecausePayments") . '">' . $langs->trans('Delete') . '</a></div>';
  3628. } else {
  3629. print '<div class="inline-block divButAction"><a class="butActionDelete" href="' . $_SERVER["PHP_SELF"] . '?facid=' . $object->id . '&amp;action=delete">' . $langs->trans('Delete') . '</a></div>';
  3630. }
  3631. } else {
  3632. print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="' . $langs->trans("NotAllowed") . '">' . $langs->trans('Delete') . '</a></div>';
  3633. }
  3634. print '</div>';
  3635. }
  3636. }
  3637. print '<br>';
  3638. // Select mail models is same action as presend
  3639. if (GETPOST('modelselected')) {
  3640. $action = 'presend';
  3641. }
  3642. if ($action != 'prerelance' && $action != 'presend')
  3643. {
  3644. print '<div class="fichecenter"><div class="fichehalfleft">';
  3645. print '<a name="builddoc"></a>'; // ancre
  3646. // Documents generes
  3647. $filename = dol_sanitizeFileName($object->ref);
  3648. $filedir = $conf->facture->dir_output . '/' . dol_sanitizeFileName($object->ref);
  3649. $urlsource = $_SERVER['PHP_SELF'] . '?facid=' . $object->id;
  3650. $genallowed = $user->rights->facture->creer;
  3651. $delallowed = $user->rights->facture->supprimer;
  3652. print $formfile->showdocuments('facture', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang);
  3653. $somethingshown = $formfile->numoffiles;
  3654. // Show links to link elements
  3655. $linktoelem = $form->showLinkToObjectBlock($object, null, array('invoice'));
  3656. $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem);
  3657. // Link for paypal payment
  3658. if (! empty($conf->paypal->enabled) && $object->statut != 0) {
  3659. include_once DOL_DOCUMENT_ROOT . '/paypal/lib/paypal.lib.php';
  3660. print showPaypalPaymentUrl('invoice', $object->ref);
  3661. }
  3662. print '</div><div class="fichehalfright"><div class="ficheaddleft">';
  3663. // List of actions on element
  3664. include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php';
  3665. $formactions = new FormActions($db);
  3666. $somethingshown = $formactions->showactions($object, 'invoice', $socid);
  3667. print '</div></div></div>';
  3668. }
  3669. else
  3670. {
  3671. /*
  3672. * Action presend (or prerelance)
  3673. */
  3674. $object->fetch_projet();
  3675. // By default if $action=='presend'
  3676. $titreform = 'SendBillByMail';
  3677. $topicmail = 'SendBillRef';
  3678. $modelmail = 'facture_send';
  3679. if ($action == 'prerelance') // For backward compatibility
  3680. {
  3681. $titrefrom = 'SendReminderBillByMail';
  3682. $topicmail = 'SendReminderBillRef';
  3683. $modelmail = 'facture_relance';
  3684. $action = 'relance';
  3685. } else
  3686. $action = 'send';
  3687. $ref = dol_sanitizeFileName($object->ref);
  3688. include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
  3689. $fileparams = dol_most_recent_file($conf->facture->dir_output . '/' . $ref, preg_quote($ref, '/').'[^\-]+');
  3690. $file = $fileparams['fullname'];
  3691. // Define output language
  3692. $outputlangs = $langs;
  3693. $newlang = '';
  3694. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id']))
  3695. $newlang = $_REQUEST['lang_id'];
  3696. if ($conf->global->MAIN_MULTILANGS && empty($newlang))
  3697. $newlang = $object->thirdparty->default_lang;
  3698. if (!empty($newlang))
  3699. {
  3700. $outputlangs = new Translate('', $conf);
  3701. $outputlangs->setDefaultLang($newlang);
  3702. $outputlangs->load('bills');
  3703. }
  3704. // Build document if it not exists
  3705. if (! $file || ! is_readable($file)) {
  3706. $result = $object->generateDocument(GETPOST('model') ? GETPOST('model') : $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  3707. if ($result <= 0) {
  3708. dol_print_error($db, $object->error, $object->errors);
  3709. exit();
  3710. }
  3711. $fileparams = dol_most_recent_file($conf->facture->dir_output . '/' . $ref, preg_quote($ref, '/').'[^\-]+');
  3712. $file = $fileparams['fullname'];
  3713. }
  3714. print '<div class="clearboth"></div>';
  3715. print '<br>';
  3716. print load_fiche_titre($langs->trans($titreform));
  3717. // Cree l'objet formulaire mail
  3718. dol_fiche_head();
  3719. include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php';
  3720. $formmail = new FormMail($db);
  3721. $formmail->param['langsmodels']=(empty($newlang)?$langs->defaultlang:$newlang);
  3722. $formmail->fromtype = (GETPOST('fromtype')?GETPOST('fromtype'):(!empty($conf->global->MAIN_MAIL_DEFAULT_FROMTYPE)?$conf->global->MAIN_MAIL_DEFAULT_FROMTYPE:'user'));
  3723. if($formmail->fromtype === 'user'){
  3724. $formmail->fromid = $user->id;
  3725. }
  3726. $formmail->trackid='inv'.$object->id;
  3727. if (! empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 2)) // If bit 2 is set
  3728. {
  3729. include DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  3730. $formmail->frommail=dolAddEmailTrackId($formmail->frommail, 'inv'.$object->id);
  3731. }
  3732. $formmail->withfrom = 1;
  3733. $liste = array();
  3734. foreach ($object->thirdparty->thirdparty_and_contact_email_array(1) as $key => $value) {
  3735. $liste [$key] = $value;
  3736. }
  3737. $formmail->withto = GETPOST('sendto') ? GETPOST('sendto') : $liste; // List suggested for send to
  3738. $formmail->withtocc = $liste; // List suggested for CC
  3739. $formmail->withtoccc = $conf->global->MAIN_EMAIL_USECCC;
  3740. if (empty($object->ref_client)) {
  3741. $formmail->withtopic = $outputlangs->transnoentities($topicmail, '__REF__');
  3742. } else if (! empty($object->ref_client)) {
  3743. $formmail->withtopic = $outputlangs->transnoentities($topicmail, '__REF__ (__REFCLIENT__)');
  3744. }
  3745. $formmail->withfile = 2;
  3746. $formmail->withbody = 1;
  3747. $formmail->withdeliveryreceipt = 1;
  3748. $formmail->withcancel = 1;
  3749. // Tableau des substitutions
  3750. $formmail->setSubstitFromObject($object, $outputlangs);
  3751. $formmail->substit['__INVREF__'] = $object->ref;
  3752. // Find the good contact adress
  3753. $custcontact = '';
  3754. $contactarr = array();
  3755. $contactarr = $object->liste_contact(- 1, 'external');
  3756. if (is_array($contactarr) && count($contactarr) > 0) {
  3757. foreach ($contactarr as $contact) {
  3758. if ($contact['libelle'] == $langs->trans('TypeContact_facture_external_BILLING')) { // TODO Use code and not label
  3759. require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
  3760. $contactstatic = new Contact($db);
  3761. $contactstatic->fetch($contact ['id']);
  3762. $custcontact = $contactstatic->getFullName($langs, 1);
  3763. }
  3764. }
  3765. if (! empty($custcontact)) {
  3766. $formmail->substit['__CONTACTCIVNAME__'] = $custcontact;
  3767. }
  3768. }
  3769. // Tableau des parametres complementaires du post
  3770. $formmail->param['action'] = $action;
  3771. $formmail->param['models'] = $modelmail;
  3772. $formmail->param['models_id']=GETPOST('modelmailselected','int');
  3773. $formmail->param['facid'] = $object->id;
  3774. $formmail->param['returnurl'] = $_SERVER["PHP_SELF"] . '?id=' . $object->id;
  3775. // Init list of files
  3776. if (GETPOST("mode") == 'init') {
  3777. $formmail->clear_attached_files();
  3778. $formmail->add_attached_files($file, basename($file), dol_mimetype($file));
  3779. }
  3780. print $formmail->get_form();
  3781. dol_fiche_end();
  3782. }
  3783. }
  3784. llxFooter();
  3785. $db->close();