card.php 208 KB

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