card.php 206 KB

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