card.php 319 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122
  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-2020 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-2019 Ferran Marcet <fmarcet@2byte.es>
  16. * Copyright (C) 2015-2016 Marcos García <marcosgdf@gmail.com>
  17. * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
  18. * Copyright (C) 2022 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
  19. *
  20. * This program is free software; you can redistribute it and/or modify
  21. * it under the terms of the GNU General Public License as published by
  22. * the Free Software Foundation; either version 3 of the License, or
  23. * (at your option) any later version.
  24. *
  25. * This program is distributed in the hope that it will be useful,
  26. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  27. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  28. * GNU General Public License for more details.
  29. *
  30. * You should have received a copy of the GNU General Public License
  31. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  32. */
  33. /**
  34. * \file htdocs/compta/facture/card.php
  35. * \ingroup facture
  36. * \brief Page to create/see an invoice
  37. */
  38. // Libraries
  39. require '../../main.inc.php';
  40. require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
  41. require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture-rec.class.php';
  42. require_once DOL_DOCUMENT_ROOT . '/compta/bank/class/account.class.php';
  43. require_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php';
  44. require_once DOL_DOCUMENT_ROOT . '/core/modules/facture/modules_facture.php';
  45. require_once DOL_DOCUMENT_ROOT . '/core/class/discount.class.php';
  46. require_once DOL_DOCUMENT_ROOT . '/core/class/html.formfile.class.php';
  47. require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.php';
  48. require_once DOL_DOCUMENT_ROOT . '/core/class/html.formmargin.class.php';
  49. require_once DOL_DOCUMENT_ROOT . '/core/lib/invoice.lib.php';
  50. require_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php';
  51. require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
  52. require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php';
  53. require_once DOL_DOCUMENT_ROOT . '/custom/financialreport/class/userinvoice.class.php';
  54. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/commissionhandler.class.php';
  55. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/bbticketcounter.class.php';
  56. if (isModEnabled('commande')) {
  57. require_once DOL_DOCUMENT_ROOT . '/commande/class/commande.class.php';
  58. }
  59. if (isModEnabled('project')) {
  60. require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
  61. require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php';
  62. }
  63. require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
  64. if (isModEnabled('variants')) {
  65. require_once DOL_DOCUMENT_ROOT . '/variants/class/ProductCombination.class.php';
  66. }
  67. if (isModEnabled('accounting')) {
  68. require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingjournal.class.php';
  69. }
  70. // Load translation files required by the page
  71. $langs->loadLangs(array('bills', 'companies', 'compta', 'products', 'banks', 'main', 'withdrawals'));
  72. if (isModEnabled('incoterm')) {
  73. $langs->load('incoterm');
  74. }
  75. if (isModEnabled('margin')) {
  76. $langs->load('margins');
  77. }
  78. // General $Variables
  79. $id = (GETPOST('id', 'int') ? GETPOST('id', 'int') : GETPOST('facid', 'int')); // For backward compatibility
  80. $ref = GETPOST('ref', 'alpha');
  81. $socid = GETPOST('socid', 'int');
  82. $action = GETPOST('action', 'aZ09');
  83. $confirm = GETPOST('confirm', 'alpha');
  84. $cancel = GETPOST('cancel', 'alpha');
  85. $lineid = GETPOST('lineid', 'int');
  86. $userid = GETPOST('userid', 'int');
  87. $search_ref = GETPOST('sf_ref', 'alpha') ? GETPOST('sf_ref', 'alpha') : GETPOST('search_ref', 'alpha');
  88. $search_societe = GETPOST('search_societe', 'alpha');
  89. $search_montant_ht = GETPOST('search_montant_ht', 'alpha');
  90. $search_montant_ttc = GETPOST('search_montant_ttc', 'alpha');
  91. $origin = GETPOST('origin', 'alpha');
  92. $originid = (GETPOST('originid', 'int') ? GETPOST('originid', 'int') : GETPOST('origin_id', 'int')); // For backward compatibility
  93. $fac_rec = GETPOST('fac_rec', 'int');
  94. $facid = GETPOST('facid', 'int');
  95. $ref_client = GETPOST('ref_client', 'int');
  96. $rank = (GETPOST('rank', 'int') > 0) ? GETPOST('rank', 'int') : -1;
  97. $projectid = (GETPOST('projectid', 'int') ? GETPOST('projectid', 'int') : 0);
  98. // Customer Change button
  99. $customerchange = GETPOST('customerchange', 'int');
  100. // PDF
  101. $hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0));
  102. $hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0));
  103. $hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0));
  104. // Number of lines for predefined product/service choices
  105. $NBLINES = 4;
  106. $usehm = (!empty($conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE) ? $conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE : 0);
  107. $object = new Facture($db);
  108. $extrafields = new ExtraFields($db);
  109. // Fetch optionals attributes and labels
  110. $extrafields->fetch_name_optionals_label($object->table_element);
  111. // Load object
  112. if ($id > 0 || !empty($ref)) {
  113. if ($action != 'add') {
  114. if (empty($conf->global->INVOICE_USE_SITUATION)) {
  115. $fetch_situation = false;
  116. } else {
  117. $fetch_situation = true;
  118. }
  119. $ret = $object->fetch($id, $ref, '', '', $fetch_situation);
  120. }
  121. }
  122. if ($object->statut == 2) {
  123. $Bbticketcounter = new Bbticketcounter();
  124. }
  125. // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
  126. $hookmanager->initHooks(array('invoicecard', 'globalcard'));
  127. // Permissions
  128. $usercanread = $user->hasRight("facture", "lire");
  129. $usercancreate = $user->hasRight("facture", "creer");
  130. $usercanissuepayment = $user->hasRight("facture", "paiement");
  131. $usercandelete = $user->hasRight("facture", "supprimer");
  132. $usercancreatecontract = $user->hasRight("contrat", "creer");
  133. // Advanced Permissions
  134. $usercanvalidate = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $usercancreate) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->facture->invoice_advance->validate)));
  135. $usercansend = (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->facture->invoice_advance->send)));
  136. $usercanreopen = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $usercancreate) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->facture->invoice_advance->reopen)));
  137. if (!empty($conf->global->INVOICE_DISALLOW_REOPEN)) {
  138. $usercanreopen = false;
  139. }
  140. $usercanunvalidate = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($usercancreate)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->facture->invoice_advance->unvalidate)));
  141. $usermustrespectpricemin = ((!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->produit->ignore_price_min_advance)) || empty($conf->global->MAIN_USE_ADVANCED_PERMS));
  142. $usercancreatemargin = (!empty($user->rights->margins->creer) ? $user->rights->margins->creer : 0);
  143. $usercanreadallmargin = (!empty($user->rights->margins->liretous) ? $user->rights->margins->liretous : 0);
  144. $usercancreatewithdrarequest = (!empty($user->rights->prelevement->bons->creer) ? $user->rights->prelevement->bons->creer : 0);
  145. $permissionnote = $usercancreate; // Used by the include of actions_setnotes.inc.php
  146. $permissiondellink = $usercancreate; // Used by the include of actions_dellink.inc.php
  147. $permissiontoedit = $usercancreate; // Used by the include of actions_lineupdonw.inc.php
  148. $permissiontoadd = $usercancreate; // Used by the include of actions_addupdatedelete.inc.php
  149. // retained warranty invoice available type
  150. $retainedWarrantyInvoiceAvailableType = array();
  151. if (!empty($conf->global->INVOICE_USE_RETAINED_WARRANTY)) {
  152. $retainedWarrantyInvoiceAvailableType = explode('+', $conf->global->INVOICE_USE_RETAINED_WARRANTY);
  153. }
  154. // Security check
  155. if ($user->socid) {
  156. $socid = $user->socid;
  157. }
  158. $isdraft = (($object->statut == Facture::STATUS_DRAFT) ? 1 : 0);
  159. $result = restrictedArea($user, 'facture', $object->id, '', '', 'fk_soc', 'rowid', $isdraft);
  160. /*
  161. * Actions
  162. */
  163. $parameters = array('socid' => $socid);
  164. $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  165. if ($reshook < 0) {
  166. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  167. }
  168. if (empty($reshook)) {
  169. // send invoice to ntak
  170. if ($conf->ntak->enabled) {
  171. require_once DOL_DOCUMENT_ROOT . '/custom/ntak/class/ntaksender.class.php';
  172. require_once DOL_DOCUMENT_ROOT . '/custom/ntak/class/ntaksendresult.class.php';
  173. require_once DOL_DOCUMENT_ROOT . '/custom/ntak/class/ntakconnector/ntak_const.class.php';
  174. if ($action == 'sendntak') {
  175. $ntakSendResult = (new NtakSender)->sendByInvoice($object);
  176. if (empty($ntakSendResult->error) && !empty($ntakSendResult->ntakId)) {
  177. $object->array_options['options_ntak_id'] = $ntakSendResult->ntakId;
  178. $object->array_options['options_ntak_status'] = $ntakSendResult->ntakStatus;
  179. $object->updateExtraField('ntak_id');
  180. $object->updateExtraField('ntak_status');
  181. setEventMessages($langs->trans('NtakSuccessSend', $ntakSendResult->ntakId), null, 'mesgs');
  182. } else {
  183. setEventMessages($langs->trans('NtakSendFailure'), null, 'errors');
  184. }
  185. header('Location: ' . DOL_URL_ROOT . '/compta/facture/card.php?id=' . $id);
  186. exit;
  187. }
  188. if ($action == 'getntakstatus') {
  189. $ntakResult = (new NtakSender)->checkSentInvoice($object->array_options['options_ntak_id'], $object->id);
  190. if (!empty($ntakResult['uzenetValaszok'][0]['statusz'])) {
  191. $object->array_options['options_ntak_status'] = $ntakResult['uzenetValaszok'][0]['statusz'];
  192. $object->updateExtraField('ntak_status');
  193. setEventMessages($langs->trans('NtakStatusChecked', $ntakResult['uzenetValaszok'][0]['statusz']), null, 'mesgs');
  194. } else {
  195. setEventMessages($langs->trans('NtakStatusCheckFailure'), null, 'errors');
  196. }
  197. header('Location: ' . DOL_URL_ROOT . '/compta/facture/card.php?id=' . $id);
  198. exit;
  199. }
  200. }
  201. $backurlforlist = DOL_URL_ROOT . '/compta/facture/list.php';
  202. if (empty($backtopage) || ($cancel && empty($id))) {
  203. if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) {
  204. if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) {
  205. $backtopage = $backurlforlist;
  206. } else {
  207. $backtopage = DOL_URL_ROOT . '/compta/facture/card.php?id=' . ((!empty($id) && $id > 0) ? $id : '__ID__');
  208. }
  209. }
  210. }
  211. if ($cancel) {
  212. if (!empty($backtopageforcancel)) {
  213. header("Location: " . $backtopageforcancel);
  214. exit;
  215. } elseif (!empty($backtopage)) {
  216. header("Location: " . $backtopage);
  217. exit;
  218. }
  219. $action = '';
  220. }
  221. include DOL_DOCUMENT_ROOT . '/core/actions_setnotes.inc.php'; // Must be include, not include_once
  222. include DOL_DOCUMENT_ROOT . '/core/actions_dellink.inc.php'; // Must be include, not include_once
  223. include DOL_DOCUMENT_ROOT . '/core/actions_lineupdown.inc.php'; // Must be include, not include_once
  224. // Action clone object
  225. if ($action == 'confirm_clone' && $confirm == 'yes' && $permissiontoadd) {
  226. $objectutil = dol_clone($object, 1); // To avoid to denaturate loaded object when setting some properties for clone. We use native clone to keep this->db valid.
  227. $objectutil->date = dol_mktime(12, 0, 0, GETPOST('newdatemonth', 'int'), GETPOST('newdateday', 'int'), GETPOST('newdateyear', 'int'));
  228. $objectutil->socid = $socid;
  229. $result = $objectutil->createFromClone($user, $id);
  230. if ($result > 0) {
  231. header("Location: " . $_SERVER['PHP_SELF'] . '?facid=' . $result);
  232. exit();
  233. } else {
  234. $langs->load("errors");
  235. setEventMessages($objectutil->error, $objectutil->errors, 'errors');
  236. $action = '';
  237. }
  238. } elseif ($action == 'reopen' && $usercanreopen) {
  239. $result = $object->fetch($id);
  240. if ($object->statut == Facture::STATUS_CLOSED || ($object->statut == Facture::STATUS_ABANDONED && ($object->close_code != 'replaced' || $object->getIdReplacingInvoice() == 0)) || ($object->statut == Facture::STATUS_VALIDATED && $object->paye == 1)) { // ($object->statut == 1 && $object->paye == 1) should not happened but can be found when data are corrupted
  241. $result = $object->setUnpaid($user);
  242. if ($result > 0) {
  243. header('Location: ' . $_SERVER["PHP_SELF"] . '?facid=' . $id);
  244. exit();
  245. } else {
  246. setEventMessages($object->error, $object->errors, 'errors');
  247. }
  248. }
  249. } elseif ($action == 'confirm_delete' && $confirm == 'yes') {
  250. // Delete invoice
  251. $result = $object->fetch($id);
  252. $object->fetch_thirdparty();
  253. $idwarehouse = GETPOST('idwarehouse');
  254. $qualified_for_stock_change = 0;
  255. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  256. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  257. } else {
  258. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  259. }
  260. $isErasable = $object->is_erasable();
  261. if (
  262. ($usercandelete && $isErasable > 0)
  263. || ($usercancreate && $isErasable == 1)
  264. ) {
  265. $result = $object->delete($user, 0, $idwarehouse);
  266. if ($result > 0) {
  267. header('Location: ' . DOL_URL_ROOT . '/compta/facture/list.php?restore_lastsearch_values=1');
  268. exit();
  269. } else {
  270. setEventMessages($object->error, $object->errors, 'errors');
  271. $action = '';
  272. }
  273. }
  274. } elseif ($action == 'confirm_deleteline' && $confirm == 'yes' && $usercancreate) {
  275. // Delete line
  276. $object->fetch($id);
  277. $object->fetch_thirdparty();
  278. $result = $object->deleteline(GETPOST('lineid', 'int'));
  279. if ($result > 0) {
  280. // reorder lines
  281. $object->line_order(true);
  282. // Define output language
  283. $outputlangs = $langs;
  284. $newlang = '';
  285. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id')) {
  286. $newlang = GETPOST('lang_id');
  287. }
  288. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
  289. $newlang = $object->thirdparty->default_lang;
  290. }
  291. if (!empty($newlang)) {
  292. $outputlangs = new Translate("", $conf);
  293. $outputlangs->setDefaultLang($newlang);
  294. $outputlangs->load('products');
  295. }
  296. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  297. $ret = $object->fetch($id); // Reload to get new records
  298. $result = $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  299. }
  300. if ($result >= 0) {
  301. header('Location: ' . $_SERVER["PHP_SELF"] . '?facid=' . $id);
  302. exit();
  303. }
  304. } else {
  305. setEventMessages($object->error, $object->errors, 'errors');
  306. $action = '';
  307. }
  308. } elseif ($action == 'unlinkdiscount' && $usercancreate) {
  309. // Delete link of credit note to invoice
  310. $discount = new DiscountAbsolute($db);
  311. $result = $discount->fetch(GETPOST("discountid"));
  312. $discount->unlink_invoice();
  313. } elseif ($action == 'valid' && $usercancreate) {
  314. // Validation
  315. $object->fetch($id);
  316. if (!empty($conf->global->INVOICE_CHECK_POSTERIOR_DATE)) {
  317. $last_of_type = $object->willBeLastOfSameType(true);
  318. if (empty($object->date_validation) && !$last_of_type[0]) {
  319. setEventMessages($langs->transnoentities("ErrorInvoiceIsNotLastOfSameType", $object->ref, dol_print_date($object->date, 'day'), dol_print_date($last_of_type[1], 'day')), null, 'errors');
  320. $action = '';
  321. }
  322. }
  323. // On verifie signe facture
  324. if ($object->type == Facture::TYPE_CREDIT_NOTE) {
  325. // Si avoir, le signe doit etre negatif
  326. if ($object->total_ht >= 0) {
  327. setEventMessages($langs->trans("ErrorInvoiceAvoirMustBeNegative"), null, 'errors');
  328. $action = '';
  329. }
  330. } elseif ($object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE) {
  331. // Si avoir, le signe doit etre negatif
  332. if ($object->total_ht >= 0) {
  333. setEventMessages($langs->trans("ErrorInvoiceAvoirMustBeNegative"), null, 'errors');
  334. $action = '';
  335. }
  336. } else {
  337. // If not a credit note, amount with tax must be positive or nul.
  338. // Note that amount excluding tax can be negative because you can have a invoice of 100 with vat of 20 that
  339. // consumes a credit note of 100 with vat 0 (total with tax is 0 but without tax is -20).
  340. // For some cases, credit notes can have a vat of 0 (for example when selling goods in France).
  341. if (empty($conf->global->FACTURE_ENABLE_NEGATIVE) && $object->total_ttc < 0) {
  342. setEventMessages($langs->trans("ErrorInvoiceOfThisTypeMustBePositive"), null, 'errors');
  343. $action = '';
  344. }
  345. // Also negative lines should not be allowed on 'non Credit notes' invoices. A test is done when adding or updating lines but we must
  346. // do it again in validation to avoid cases where invoice is created from another object that allow negative lines.
  347. // Note that we can accept the negative line if sum with other lines with same vat makes total positive: Because all the lines will be merged together
  348. // when converted into 'available credit' and we will get a positive available credit line.
  349. // Note: Other solution if you want to add a negative line on invoice, is to create a discount for customer and consumme it (but this is possible on standard invoice only).
  350. $array_of_total_ht_per_vat_rate = array();
  351. $array_of_total_ht_devise_per_vat_rate = array();
  352. foreach ($object->lines as $line) {
  353. //$vat_src_code_for_line = $line->vat_src_code; // TODO We chek sign of total per vat without taking into account the vat code because for the moment the vat code is lost/unknown when we add a down payment.
  354. $vat_src_code_for_line = '';
  355. if (empty($array_of_total_ht_per_vat_rate[$line->tva_tx . '_' . $vat_src_code_for_line])) {
  356. $array_of_total_ht_per_vat_rate[$line->tva_tx . '_' . $vat_src_code_for_line] = 0;
  357. }
  358. if (empty($array_of_total_ht_devise_per_vat_rate[$line->tva_tx . '_' . $vat_src_code_for_line])) {
  359. $array_of_total_ht_devise_per_vat_rate[$line->tva_tx . '_' . $vat_src_code_for_line] = 0;
  360. }
  361. $array_of_total_ht_per_vat_rate[$line->tva_tx . '_' . $vat_src_code_for_line] += $line->total_ht;
  362. $array_of_total_ht_devise_per_vat_rate[$line->tva_tx . '_' . $vat_src_code_for_line] += $line->multicurrency_total_ht;
  363. }
  364. //var_dump($array_of_total_ht_per_vat_rate);exit;
  365. foreach ($array_of_total_ht_per_vat_rate as $vatrate => $tmpvalue) {
  366. $tmp_total_ht = price2num($array_of_total_ht_per_vat_rate[$vatrate]);
  367. $tmp_total_ht_devise = price2num($array_of_total_ht_devise_per_vat_rate[$vatrate]);
  368. if (($tmp_total_ht < 0 || $tmp_total_ht_devise < 0) && empty($conf->global->FACTURE_ENABLE_NEGATIVE_LINES)) {
  369. if ($object->type == $object::TYPE_DEPOSIT) {
  370. $langs->load("errors");
  371. // Using negative lines on deposit lead to headach and blocking problems when you want to consume them.
  372. setEventMessages($langs->trans("ErrorLinesCantBeNegativeOnDeposits"), null, 'errors');
  373. $error++;
  374. $action = '';
  375. } else {
  376. $tmpvatratetoshow = explode('_', $vatrate);
  377. $tmpvatratetoshow[0] = round($tmpvatratetoshow[0], 2);
  378. if ($tmpvatratetoshow[0] != 0) {
  379. $langs->load("errors");
  380. setEventMessages($langs->trans("ErrorLinesCantBeNegativeForOneVATRate", $tmpvatratetoshow[0]), null, 'errors');
  381. $error++;
  382. $action = '';
  383. }
  384. }
  385. }
  386. }
  387. }
  388. } elseif ($action == 'classin' && $usercancreate) {
  389. $object->fetch($id);
  390. $object->setProject(GETPOST('projectid', 'int'));
  391. } elseif ($action == 'setmode' && $usercancreate) {
  392. $object->fetch($id);
  393. $result = $object->setPaymentMethods(GETPOST('mode_reglement_id', 'int'));
  394. if ($result < 0) {
  395. dol_print_error($db, $object->error);
  396. }
  397. } elseif ($action == 'setretainedwarrantyconditions' && $user->rights->facture->creer) {
  398. $object->fetch($id);
  399. $object->retained_warranty_fk_cond_reglement = 0; // To clean property
  400. $result = $object->setRetainedWarrantyPaymentTerms(GETPOST('retained_warranty_fk_cond_reglement', 'int'));
  401. if ($result < 0) {
  402. dol_print_error($db, $object->error);
  403. }
  404. $old_rw_date_lim_reglement = $object->retained_warranty_date_limit;
  405. $new_rw_date_lim_reglement = $object->calculate_date_lim_reglement($object->retained_warranty_fk_cond_reglement);
  406. if ($new_rw_date_lim_reglement > $old_rw_date_lim_reglement) {
  407. $object->retained_warranty_date_limit = $new_rw_date_lim_reglement;
  408. }
  409. if ($object->retained_warranty_date_limit < $object->date) {
  410. $object->retained_warranty_date_limit = $object->date;
  411. }
  412. $result = $object->update($user);
  413. if ($result < 0) {
  414. dol_print_error($db, $object->error);
  415. }
  416. } elseif ($action == 'setretainedwarranty' && $user->rights->facture->creer) {
  417. $object->fetch($id);
  418. $result = $object->setRetainedWarranty(GETPOST('retained_warranty', 'float'));
  419. if ($result < 0) {
  420. dol_print_error($db, $object->error);
  421. }
  422. } elseif ($action == 'setretainedwarrantydatelimit' && $user->rights->facture->creer) {
  423. $object->fetch($id);
  424. $result = $object->setRetainedWarrantyDateLimit(GETPOST('retained_warranty_date_limit', 'float'));
  425. if ($result < 0) {
  426. dol_print_error($db, $object->error);
  427. }
  428. } elseif ($action == 'setmulticurrencycode' && $usercancreate) { // Multicurrency Code
  429. $result = $object->setMulticurrencyCode(GETPOST('multicurrency_code', 'alpha'));
  430. } elseif ($action == 'setmulticurrencyrate' && $usercancreate) { // Multicurrency rate
  431. $result = $object->setMulticurrencyRate(price2num(GETPOST('multicurrency_tx')), GETPOST('calculation_mode', 'int'));
  432. } elseif ($action == 'setinvoicedate' && $usercancreate) {
  433. $object->fetch($id);
  434. $old_date_lim_reglement = $object->date_lim_reglement;
  435. $newdate = dol_mktime(0, 0, 0, GETPOST('invoicedatemonth', 'int'), GETPOST('invoicedateday', 'int'), GETPOST('invoicedateyear', 'int'), 'tzserver');
  436. if (empty($newdate)) {
  437. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
  438. header('Location: ' . $_SERVER["PHP_SELF"] . '?facid=' . $id . '&action=editinvoicedate&token=' . newToken());
  439. exit;
  440. }
  441. if ($newdate > (dol_now('tzuserrel') + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
  442. if (empty($conf->global->INVOICE_MAX_FUTURE_DELAY)) {
  443. setEventMessages($langs->trans("WarningInvoiceDateInFuture"), null, 'warnings');
  444. } else {
  445. setEventMessages($langs->trans("WarningInvoiceDateTooFarInFuture"), null, 'warnings');
  446. }
  447. }
  448. $object->date = $newdate;
  449. $new_date_lim_reglement = $object->calculate_date_lim_reglement();
  450. if ($new_date_lim_reglement > $old_date_lim_reglement) {
  451. $object->date_lim_reglement = $new_date_lim_reglement;
  452. }
  453. if ($object->date_lim_reglement < $object->date) {
  454. $object->date_lim_reglement = $object->date;
  455. }
  456. $result = $object->update($user);
  457. if ($result < 0) {
  458. dol_print_error($db, $object->error);
  459. }
  460. } elseif ($action == 'setdate_pointoftax' && $usercancreate) {
  461. $object->fetch($id);
  462. $date_pointoftax = dol_mktime(0, 0, 0, GETPOST('date_pointoftaxmonth', 'int'), GETPOST('date_pointoftaxday', 'int'), GETPOST('date_pointoftaxyear', 'int'), 'tzserver');
  463. $object->date_pointoftax = $date_pointoftax;
  464. $result = $object->update($user);
  465. if ($result < 0) {
  466. dol_print_error($db, $object->error);
  467. }
  468. } elseif ($action == 'setconditions' && $usercancreate) {
  469. $object->fetch($id);
  470. $object->cond_reglement_code = 0; // To clean property
  471. $object->cond_reglement_id = 0; // To clean property
  472. $error = 0;
  473. $db->begin();
  474. if (!$error) {
  475. $result = $object->setPaymentTerms(GETPOST('cond_reglement_id', 'int'));
  476. if ($result < 0) {
  477. $error++;
  478. setEventMessages($object->error, $object->errors, 'errors');
  479. }
  480. }
  481. if (!$error) {
  482. $old_date_lim_reglement = $object->date_lim_reglement;
  483. $new_date_lim_reglement = $object->calculate_date_lim_reglement();
  484. if ($new_date_lim_reglement > $old_date_lim_reglement) {
  485. $object->date_lim_reglement = $new_date_lim_reglement;
  486. }
  487. if ($object->date_lim_reglement < $object->date) {
  488. $object->date_lim_reglement = $object->date;
  489. }
  490. $result = $object->update($user);
  491. if ($result < 0) {
  492. $error++;
  493. setEventMessages($object->error, $object->errors, 'errors');
  494. }
  495. }
  496. if ($error) {
  497. $db->rollback();
  498. } else {
  499. $db->commit();
  500. }
  501. } elseif ($action == 'setpaymentterm' && $usercancreate) {
  502. $object->fetch($id);
  503. $object->date_lim_reglement = dol_mktime(12, 0, 0, GETPOST('paymenttermmonth', 'int'), GETPOST('paymenttermday', 'int'), GETPOST('paymenttermyear', 'int'));
  504. if ($object->date_lim_reglement < $object->date) {
  505. $object->date_lim_reglement = $object->calculate_date_lim_reglement();
  506. setEventMessages($langs->trans("DatePaymentTermCantBeLowerThanObjectDate"), null, 'warnings');
  507. }
  508. $result = $object->update($user);
  509. if ($result < 0) {
  510. dol_print_error($db, $object->error);
  511. }
  512. } elseif ($action == 'setrevenuestamp' && $usercancreate) {
  513. $object->fetch($id);
  514. $object->revenuestamp = GETPOST('revenuestamp');
  515. $result = $object->update($user);
  516. $object->update_price(1);
  517. if ($result < 0) {
  518. dol_print_error($db, $object->error);
  519. } else {
  520. // Define output language
  521. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  522. $outputlangs = $langs;
  523. $newlang = '';
  524. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  525. $newlang = GETPOST('lang_id', 'aZ09');
  526. }
  527. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
  528. $newlang = $object->thirdparty->default_lang;
  529. }
  530. if (!empty($newlang)) {
  531. $outputlangs = new Translate("", $conf);
  532. $outputlangs->setDefaultLang($newlang);
  533. $outputlangs->load('products');
  534. }
  535. $model = $object->model_pdf;
  536. $ret = $object->fetch($id); // Reload to get new records
  537. $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  538. if ($result < 0) {
  539. setEventMessages($object->error, $object->errors, 'errors');
  540. }
  541. }
  542. }
  543. } elseif ($action == 'set_incoterms' && isModEnabled('incoterm')) { // Set incoterm
  544. $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha'));
  545. } elseif ($action == 'setbankaccount' && $usercancreate) { // bank account
  546. $result = $object->setBankAccount(GETPOST('fk_account', 'int'));
  547. } elseif ($action == 'setremisepercent' && $usercancreate) {
  548. $object->fetch($id);
  549. $result = $object->setDiscount($user, price2num(GETPOST('remise_percent'), '', 2));
  550. } elseif ($action == "setabsolutediscount" && $usercancreate) {
  551. // We have POST[remise_id] or POST[remise_id_for_payment]
  552. $db->begin();
  553. // We use the credit to reduce amount of invoice
  554. if (GETPOST("remise_id", 'int') > 0) {
  555. $ret = $object->fetch($id);
  556. if ($ret > 0) {
  557. $result = $object->insert_discount(GETPOST("remise_id", 'int'));
  558. if ($result < 0) {
  559. setEventMessages($object->error, $object->errors, 'errors');
  560. }
  561. } else {
  562. $error++;
  563. setEventMessages($object->error, $object->errors, 'errors');
  564. }
  565. }
  566. // We use the credit to reduce remain to pay
  567. if (GETPOST("remise_id_for_payment", 'int') > 0) {
  568. require_once DOL_DOCUMENT_ROOT . '/core/class/discount.class.php';
  569. $discount = new DiscountAbsolute($db);
  570. $discount->fetch(GETPOST("remise_id_for_payment", 'int'));
  571. //var_dump($object->getRemainToPay(0));
  572. //var_dump($discount->amount_ttc);exit;
  573. $remaintopay = $object->getRemainToPay(0);
  574. if (price2num($discount->amount_ttc) > price2num($remaintopay)) {
  575. // TODO Split the discount in 2 automatically
  576. $error++;
  577. setEventMessages($langs->trans("ErrorDiscountLargerThanRemainToPaySplitItBefore"), null, 'errors');
  578. }
  579. if (!$error) {
  580. $result = $discount->link_to_invoice(0, $id);
  581. if ($result < 0) {
  582. $error++;
  583. setEventMessages($discount->error, $discount->errors, 'errors');
  584. }
  585. }
  586. if (!$error) {
  587. $newremaintopay = $object->getRemainToPay(0);
  588. if ($newremaintopay == 0) {
  589. $object->setPaid($user);
  590. }
  591. }
  592. }
  593. if (!$error) {
  594. $db->commit();
  595. } else {
  596. $db->rollback();
  597. }
  598. if (empty($error) && empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  599. $outputlangs = $langs;
  600. $newlang = '';
  601. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  602. $newlang = GETPOST('lang_id', 'aZ09');
  603. }
  604. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
  605. $newlang = $object->thirdparty->default_lang;
  606. }
  607. if (!empty($newlang)) {
  608. $outputlangs = new Translate("", $conf);
  609. $outputlangs->setDefaultLang($newlang);
  610. }
  611. $ret = $object->fetch($id); // Reload to get new records
  612. $result = $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  613. if ($result < 0) {
  614. setEventMessages($object->error, $object->errors, 'errors');
  615. }
  616. }
  617. } elseif ($action == 'setref' && $usercancreate) {
  618. $object->fetch($id);
  619. $object->setValueFrom('ref', GETPOST('ref'), '', null, '', '', $user, 'BILL_MODIFY');
  620. } elseif ($action == 'setref_client' && $usercancreate) {
  621. $object->fetch($id);
  622. $object->set_ref_client(GETPOST('ref_client'));
  623. } elseif ($action == 'confirm_valid' && $confirm == 'yes' && $usercanvalidate) {
  624. // Classify to validated
  625. $idwarehouse = GETPOST('idwarehouse', 'int');
  626. $object->fetch($id);
  627. $object->fetch_thirdparty();
  628. // Check for warehouse
  629. if ($object->type != Facture::TYPE_DEPOSIT && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
  630. $qualified_for_stock_change = 0;
  631. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  632. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  633. } else {
  634. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  635. }
  636. if ($qualified_for_stock_change) {
  637. if (!$idwarehouse || $idwarehouse == -1) {
  638. $error++;
  639. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
  640. $action = '';
  641. }
  642. }
  643. }
  644. if (!$error) {
  645. $result = $object->validate($user, '', $idwarehouse);
  646. if ($result >= 0) {
  647. // Define output language
  648. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  649. $outputlangs = $langs;
  650. $newlang = '';
  651. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  652. $newlang = GETPOST('lang_id', 'aZ09');
  653. }
  654. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
  655. $newlang = $object->thirdparty->default_lang;
  656. }
  657. if (!empty($newlang)) {
  658. $outputlangs = new Translate("", $conf);
  659. $outputlangs->setDefaultLang($newlang);
  660. $outputlangs->load('products');
  661. }
  662. $model = $object->model_pdf;
  663. $ret = $object->fetch($id); // Reload to get new records
  664. $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  665. if ($result < 0) {
  666. setEventMessages($object->error, $object->errors, 'errors');
  667. }
  668. }
  669. } else {
  670. if (count($object->errors)) {
  671. setEventMessages(null, $object->errors, 'errors');
  672. } else {
  673. setEventMessages($object->error, $object->errors, 'errors');
  674. }
  675. }
  676. }
  677. } elseif ($action == 'confirm_modif' && $usercanunvalidate) {
  678. // Go back to draft status (unvalidate)
  679. $idwarehouse = GETPOST('idwarehouse', 'int');
  680. $object->fetch($id);
  681. $object->fetch_thirdparty();
  682. // Check parameters
  683. if ($object->type != Facture::TYPE_DEPOSIT && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
  684. $qualified_for_stock_change = 0;
  685. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  686. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  687. } else {
  688. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  689. }
  690. if ($qualified_for_stock_change) {
  691. if (!$idwarehouse || $idwarehouse == -1) {
  692. $error++;
  693. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
  694. $action = '';
  695. }
  696. }
  697. }
  698. if (!$error) {
  699. // We check if invoice has payments
  700. $sql = 'SELECT pf.amount';
  701. $sql .= ' FROM ' . MAIN_DB_PREFIX . 'paiement_facture as pf';
  702. $sql .= ' WHERE pf.fk_facture = ' . ((int) $object->id);
  703. $result = $db->query($sql);
  704. if ($result) {
  705. $i = 0;
  706. $num = $db->num_rows($result);
  707. while ($i < $num) {
  708. $objp = $db->fetch_object($result);
  709. $totalpaid += $objp->amount;
  710. $i++;
  711. }
  712. } else {
  713. dol_print_error($db, '');
  714. }
  715. $resteapayer = $object->total_ttc - $totalpaid;
  716. // We check that invlice lines are transferred into accountancy
  717. $ventilExportCompta = $object->getVentilExportCompta();
  718. // On verifie si aucun paiement n'a ete effectue
  719. if ($ventilExportCompta == 0) {
  720. if (!empty($conf->global->INVOICE_CAN_BE_EDITED_EVEN_IF_PAYMENT_DONE) || ($resteapayer == $object->total_ttc && empty($object->paye))) {
  721. $result = $object->setDraft($user, $idwarehouse);
  722. if ($result < 0) {
  723. setEventMessages($object->error, $object->errors, 'errors');
  724. }
  725. // Define output language
  726. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  727. $outputlangs = $langs;
  728. $newlang = '';
  729. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  730. $newlang = GETPOST('lang_id', 'aZ09');
  731. }
  732. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
  733. $newlang = $object->thirdparty->default_lang;
  734. }
  735. if (!empty($newlang)) {
  736. $outputlangs = new Translate("", $conf);
  737. $outputlangs->setDefaultLang($newlang);
  738. $outputlangs->load('products');
  739. }
  740. $model = $object->model_pdf;
  741. $ret = $object->fetch($id); // Reload to get new records
  742. $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  743. }
  744. }
  745. }
  746. }
  747. } elseif ($action == 'confirm_paid' && $confirm == 'yes' && $usercanissuepayment) {
  748. // Classify "paid"
  749. $object->fetch($id);
  750. $result = $object->setPaid($user);
  751. if ($result < 0) {
  752. setEventMessages($object->error, $object->errors, 'errors');
  753. }
  754. } elseif ($action == 'confirm_paid_partially' && $confirm == 'yes' && $usercanissuepayment) {
  755. // Classif "paid partialy"
  756. $object->fetch($id);
  757. $close_code = GETPOST("close_code", 'restricthtml');
  758. $close_note = GETPOST("close_note", 'restricthtml');
  759. if ($close_code) {
  760. $result = $object->setPaid($user, $close_code, $close_note);
  761. if ($result < 0) {
  762. setEventMessages($object->error, $object->errors, 'errors');
  763. }
  764. } else {
  765. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Reason")), null, 'errors');
  766. }
  767. } elseif ($action == 'confirm_canceled' && $confirm == 'yes') {
  768. // Classify "abandoned"
  769. $object->fetch($id);
  770. $close_code = GETPOST("close_code", 'restricthtml');
  771. $close_note = GETPOST("close_note", 'restricthtml');
  772. if ($close_code) {
  773. $result = $object->setCanceled($user, $close_code, $close_note);
  774. if ($result < 0) {
  775. setEventMessages($object->error, $object->errors, 'errors');
  776. }
  777. } else {
  778. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Reason")), null, 'errors');
  779. }
  780. } elseif ($action == 'confirm_converttoreduc' && $confirm == 'yes' && $usercancreate) {
  781. // Convertir en reduc
  782. $object->fetch($id);
  783. $object->fetch_thirdparty();
  784. //$object->fetch_lines(); // Already done into fetch
  785. // Check if there is already a discount (protection to avoid duplicate creation when resubmit post)
  786. $discountcheck = new DiscountAbsolute($db);
  787. $result = $discountcheck->fetch(0, $object->id);
  788. $canconvert = 0;
  789. if ($object->type == Facture::TYPE_DEPOSIT && empty($discountcheck->id)) {
  790. $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)
  791. }
  792. if (($object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE || $object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_RECEIPT || $object->type == Facture::TYPE_SITUATION) && $object->paye == 0 && empty($discountcheck->id)) {
  793. $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)
  794. }
  795. if ($canconvert) {
  796. $db->begin();
  797. $amount_ht = $amount_tva = $amount_ttc = array();
  798. $multicurrency_amount_ht = $multicurrency_amount_tva = $multicurrency_amount_ttc = array();
  799. // Loop on each vat rate
  800. $i = 0;
  801. foreach ($object->lines as $line) {
  802. if ($line->product_type < 9 && $line->total_ht != 0) { // Remove lines with product_type greater than or equal to 9 and no need to create discount if amount is null
  803. $keyforvatrate = $line->tva_tx . ($line->vat_src_code ? ' (' . $line->vat_src_code . ')' : '');
  804. $amount_ht[$keyforvatrate] += $line->total_ht;
  805. $amount_tva[$keyforvatrate] += $line->total_tva;
  806. $amount_ttc[$keyforvatrate] += $line->total_ttc;
  807. $multicurrency_amount_ht[$keyforvatrate] += $line->multicurrency_total_ht;
  808. $multicurrency_amount_tva[$keyforvatrate] += $line->multicurrency_total_tva;
  809. $multicurrency_amount_ttc[$keyforvatrate] += $line->multicurrency_total_ttc;
  810. $i++;
  811. }
  812. }
  813. // If some payments were already done, we change the amount to pay using same prorate
  814. if (!empty($conf->global->INVOICE_ALLOW_REUSE_OF_CREDIT_WHEN_PARTIALLY_REFUNDED) && $object->type == Facture::TYPE_CREDIT_NOTE && $object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE) {
  815. $alreadypaid = $object->getSommePaiement(); // This can be not 0 if we allow to create credit to reuse from credit notes partially refunded.
  816. if ($alreadypaid && abs($alreadypaid) < abs($object->total_ttc)) {
  817. $ratio = abs(($object->total_ttc - $alreadypaid) / $object->total_ttc);
  818. foreach ($amount_ht as $vatrate => $val) {
  819. $amount_ht[$vatrate] = price2num($amount_ht[$vatrate] * $ratio, 'MU');
  820. $amount_tva[$vatrate] = price2num($amount_tva[$vatrate] * $ratio, 'MU');
  821. $amount_ttc[$vatrate] = price2num($amount_ttc[$vatrate] * $ratio, 'MU');
  822. $multicurrency_amount_ht[$vatrate] = price2num($multicurrency_amount_ht[$vatrate] * $ratio, 'MU');
  823. $multicurrency_amount_tva[$vatrate] = price2num($multicurrency_amount_tva[$vatrate] * $ratio, 'MU');
  824. $multicurrency_amount_ttc[$vatrate] = price2num($multicurrency_amount_ttc[$vatrate] * $ratio, 'MU');
  825. }
  826. }
  827. }
  828. //var_dump($amount_ht);var_dump($amount_tva);var_dump($amount_ttc);exit;
  829. // Insert one discount by VAT rate category
  830. $discount = new DiscountAbsolute($db);
  831. if ($object->type == Facture::TYPE_CREDIT_NOTE) {
  832. $discount->description = '(CREDIT_NOTE)';
  833. } elseif ($object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE) {
  834. $discount->description = '(CREDIT_NOTE_RECEIPT)';
  835. } elseif ($object->type == Facture::TYPE_DEPOSIT) {
  836. $discount->description = '(DEPOSIT)';
  837. } elseif ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_SITUATION || $object->type == Facture::TYPE_RECEIPT) {
  838. $discount->description = '(EXCESS RECEIVED)';
  839. } else {
  840. setEventMessages($langs->trans('CantConvertToReducAnInvoiceOfThisType'), null, 'errors');
  841. }
  842. $discount->fk_soc = $object->socid;
  843. $discount->fk_facture_source = $object->id;
  844. $error = 0;
  845. if ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_SITUATION || $object->type == Facture::TYPE_RECEIPT) {
  846. // If we're on a standard invoice, we have to get excess received to create a discount in TTC without VAT
  847. // Total payments
  848. $sql = 'SELECT SUM(pf.amount) as total_paiements';
  849. $sql .= ' FROM ' . MAIN_DB_PREFIX . 'paiement_facture as pf, ' . MAIN_DB_PREFIX . 'paiement as p';
  850. $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'c_paiement as c ON p.fk_paiement = c.id';
  851. $sql .= ' WHERE pf.fk_facture = ' . ((int) $object->id);
  852. $sql .= ' AND pf.fk_paiement = p.rowid';
  853. $sql .= ' AND p.entity IN (' . getEntity('invoice') . ')';
  854. $resql = $db->query($sql);
  855. if (!$resql) {
  856. dol_print_error($db);
  857. }
  858. $res = $db->fetch_object($resql);
  859. $total_paiements = $res->total_paiements;
  860. // Total credit note and deposit
  861. $total_creditnote_and_deposit = 0;
  862. $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
  863. $sql .= " re.description, re.fk_facture_source";
  864. $sql .= " FROM " . MAIN_DB_PREFIX . "societe_remise_except as re";
  865. $sql .= " WHERE fk_facture = " . ((int) $object->id);
  866. $resql = $db->query($sql);
  867. if (!empty($resql)) {
  868. while ($obj = $db->fetch_object($resql)) {
  869. $total_creditnote_and_deposit += $obj->amount_ttc;
  870. }
  871. } else {
  872. dol_print_error($db);
  873. }
  874. $discount->amount_ht = $discount->amount_ttc = $total_paiements + $total_creditnote_and_deposit - $object->total_ttc;
  875. $discount->amount_tva = 0;
  876. $discount->tva_tx = 0;
  877. $discount->vat_src_code = '';
  878. $result = $discount->create($user);
  879. if ($result < 0) {
  880. $error++;
  881. }
  882. }
  883. if ($object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT) {
  884. foreach ($amount_ht as $tva_tx => $xxx) {
  885. $discount->amount_ht = abs($amount_ht[$tva_tx]);
  886. $discount->amount_tva = abs($amount_tva[$tva_tx]);
  887. $discount->amount_ttc = abs($amount_ttc[$tva_tx]);
  888. $discount->multicurrency_amount_ht = abs($multicurrency_amount_ht[$tva_tx]);
  889. $discount->multicurrency_amount_tva = abs($multicurrency_amount_tva[$tva_tx]);
  890. $discount->multicurrency_amount_ttc = abs($multicurrency_amount_ttc[$tva_tx]);
  891. // Clean vat code
  892. $reg = array();
  893. $vat_src_code = '';
  894. if (preg_match('/\((.*)\)/', $tva_tx, $reg)) {
  895. $vat_src_code = $reg[1];
  896. $tva_tx = preg_replace('/\s*\(.*\)/', '', $tva_tx); // Remove code into vatrate.
  897. }
  898. $discount->tva_tx = abs($tva_tx);
  899. $discount->vat_src_code = $vat_src_code;
  900. $result = $discount->create($user);
  901. if ($result < 0) {
  902. $error++;
  903. break;
  904. }
  905. }
  906. }
  907. if (empty($error)) {
  908. if ($object->type != Facture::TYPE_DEPOSIT) {
  909. // Classe facture
  910. $result = $object->setPaid($user);
  911. if ($result >= 0) {
  912. $db->commit();
  913. } else {
  914. setEventMessages($object->error, $object->errors, 'errors');
  915. $db->rollback();
  916. }
  917. } else {
  918. $db->commit();
  919. }
  920. } else {
  921. setEventMessages($discount->error, $discount->errors, 'errors');
  922. $db->rollback();
  923. }
  924. }
  925. } elseif ($action == 'confirm_delete_paiement' && $confirm == 'yes' && $usercanissuepayment) {
  926. // Delete payment
  927. $object->fetch($id);
  928. if ($object->statut == Facture::STATUS_VALIDATED && $object->paye == 0) {
  929. $paiement = new Paiement($db);
  930. $result = $paiement->fetch(GETPOST('paiement_id', 'int'));
  931. if ($result > 0) {
  932. $result = $paiement->delete(); // If fetch ok and found
  933. if ($result >= 0) {
  934. header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id);
  935. exit;
  936. }
  937. }
  938. if ($result < 0) {
  939. setEventMessages($paiement->error, $paiement->errors, 'errors');
  940. }
  941. }
  942. } elseif ($action == 'add' && $usercancreate) {
  943. // Insert new invoice in database
  944. if ($socid > 0) {
  945. $object->socid = GETPOST('socid', 'int');
  946. }
  947. $selectedLines = GETPOST('toselect', 'array');
  948. if (GETPOST('type', 'int') === '') {
  949. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
  950. }
  951. $db->begin();
  952. $error = 0;
  953. $originentity = GETPOST('originentity');
  954. // Fill array 'array_options' with data from add form
  955. $ret = $extrafields->setOptionalsFromPost(null, $object);
  956. if ($ret < 0) {
  957. $error++;
  958. }
  959. $dateinvoice = dol_mktime(0, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int'), 'tzserver'); // If we enter the 02 january, we need to save the 02 january for server
  960. $date_pointoftax = dol_mktime(0, 0, 0, GETPOST('date_pointoftaxmonth', 'int'), GETPOST('date_pointoftaxday', 'int'), GETPOST('date_pointoftaxyear', 'int'), 'tzserver');
  961. // Replacement invoice
  962. if (GETPOST('type') == Facture::TYPE_REPLACEMENT) {
  963. if (empty($dateinvoice)) {
  964. $error++;
  965. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
  966. $action = 'create';
  967. } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
  968. $error++;
  969. setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
  970. $action = 'create';
  971. }
  972. if (!(GETPOST('fac_replacement', 'int') > 0)) {
  973. $error++;
  974. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ReplaceInvoice")), null, 'errors');
  975. $action = 'create';
  976. }
  977. if (!$error) {
  978. // This is a replacement invoice
  979. $result = $object->fetch(GETPOST('fac_replacement', 'int'));
  980. $object->fetch_thirdparty();
  981. $object->date = $dateinvoice;
  982. $object->date_pointoftax = $date_pointoftax;
  983. $object->note_public = trim(GETPOST('note_public', 'restricthtml'));
  984. $object->note_private = trim(GETPOST('note_private', 'restricthtml'));
  985. $object->ref_client = GETPOST('ref_client', 'alphanohtml');
  986. $object->model_pdf = GETPOST('model', 'alphanohtml');
  987. $object->fk_project = GETPOST('projectid', 'int');
  988. $object->cond_reglement_id = GETPOST('cond_reglement_id', 'int');
  989. $object->mode_reglement_id = GETPOST('mode_reglement_id', 'int');
  990. $object->fk_account = GETPOST('fk_account', 'int');
  991. $object->remise_absolue = price2num(GETPOST('remise_absolue'), 'MU', 2);
  992. $object->remise_percent = price2num(GETPOST('remise_percent'), '', 2);
  993. $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  994. $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  995. $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  996. $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
  997. // Proprietes particulieres a facture de remplacement
  998. $object->fk_facture_source = GETPOST('fac_replacement', 'int');
  999. $object->type = Facture::TYPE_REPLACEMENT;
  1000. $id = $object->createFromCurrent($user);
  1001. if ($id <= 0) {
  1002. setEventMessages($object->error, $object->errors, 'errors');
  1003. }
  1004. }
  1005. }
  1006. // Credit note invoice
  1007. if (GETPOST('type') == Facture::TYPE_CREDIT_NOTE) {
  1008. if ($object->array_options['options_commission_deduction']) {
  1009. $factureObj = new Facture($db);
  1010. $userinvoiceObj = new UserInvoice($db);
  1011. $commmissionhandler = new CommissionHandler();
  1012. $productObj = new Product($db);
  1013. $productObjHUF = new Product($db);
  1014. $fk_facture_resource = GETPOST('fac_avoir', 'int');
  1015. $result_source_facture = $factureObj->fetch($fk_facture_resource);
  1016. if ($factureObj->fk_multicurrency == 2) {
  1017. $fk_product = $factureObj->lines[0]->fk_product;
  1018. $assignedProduct = $productObj->fetch($fk_product);
  1019. $relatedService = $productObj->array_options['options_related_service'];
  1020. $productToCount = $productObjHUF->fetch($relatedService);
  1021. $price_ttc = $productObjHUF->price_ttc;
  1022. $commissionValue = $productObjHUF->array_options['options_commission_value'];
  1023. $type = $productObjHUF->array_options['options_commission_type'] == 1 ? '%' : 'Forint';
  1024. $row['total_ttc'] = $price_ttc;
  1025. $row['commission'] = $commissionValue . '_' . $type;
  1026. ;
  1027. $amount = $commmissionhandler->getAmountOfCommission($row);
  1028. } else {
  1029. $row['total_ttc'] = $factureObj->total_ttc;
  1030. $row['commission'] = $factureObj->array_options['options_commission'];
  1031. $amount = $commmissionhandler->getAmountOfCommission($row);
  1032. }
  1033. $resultUserinvoiceObj = $userinvoiceObj->fetchAll('', '', 0, 0, ["customsql" => "invoices LIKE '%{$factureObj->id}%'"]);
  1034. $usersArray = [];
  1035. foreach ($resultUserinvoiceObj as $userObj) {
  1036. $usersArray[] = $userObj->user_id;
  1037. }
  1038. $numberOfUsers = count($usersArray);
  1039. if ($numberOfUsers > 0) {
  1040. $amountOfOneUser = $amount / $numberOfUsers;
  1041. foreach ($usersArray as $userid) {
  1042. if ($amountOfOneUser > 0) {
  1043. $userinvoiceObj2 = new UserInvoice($db);
  1044. $userinvoiceObj2->ref = 'Withhold_' . dol_now() . '_' . rand(1000000, 9999999);
  1045. ;
  1046. $userinvoiceObj2->label = 'Visszatartás / Withholding ' . date('Y-m-d');
  1047. $userinvoiceObj2->description = 'Összeg / Amount: ' . $amountOfOneUser . ' HUF. Commission deduction. (CREDIT NOTE)';
  1048. $userinvoiceObj2->user_id = $userid;
  1049. $userinvoiceObj2->payment_type = 1;
  1050. $userinvoiceObj2->amount = $amountOfOneUser;
  1051. $userinvoiceObj2->currency = 0;
  1052. $userinvoiceObj2->individual = 1;
  1053. $userinvoiceObj2->invoices = $factureObj->id;
  1054. $result = $userinvoiceObj2->create($user);
  1055. if ($result < 0) {
  1056. $error++;
  1057. }
  1058. }
  1059. }
  1060. } else {
  1061. if ($amount > 0) {
  1062. $userinvoiceObj2 = new UserInvoice($db);
  1063. $userinvoiceObj2->ref = 'Withhold_' . dol_now() . '_' . rand(1000000, 9999999);
  1064. ;
  1065. $userinvoiceObj2->label = 'Visszatartás / Withholding ' . date('Y-m-d');
  1066. $userinvoiceObj2->description = 'Összeg / Amount: ' . $amount . ' HUF. Commission deduction. (CREDIT NOTE)';
  1067. $userinvoiceObj2->user_id = $factureObj->fk_user_valid;
  1068. $userinvoiceObj2->payment_type = 1;
  1069. $userinvoiceObj2->amount = $amount;
  1070. $userinvoiceObj2->currency = 0;
  1071. $userinvoiceObj2->individual = 1;
  1072. $userinvoiceObj2->invoices = $factureObj->id;
  1073. $result = $userinvoiceObj2->create($user);
  1074. if ($result < 0) {
  1075. $error++;
  1076. }
  1077. }
  1078. }
  1079. }
  1080. $sourceinvoice = GETPOST('fac_avoir', 'int');
  1081. if (!($sourceinvoice > 0) && empty($conf->global->INVOICE_CREDIT_NOTE_STANDALONE)) {
  1082. $error++;
  1083. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CorrectInvoice")), null, 'errors');
  1084. $action = 'create';
  1085. }
  1086. if (empty($dateinvoice)) {
  1087. $error++;
  1088. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
  1089. $action = 'create';
  1090. } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
  1091. $error++;
  1092. setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
  1093. $action = 'create';
  1094. }
  1095. if (!$error) {
  1096. if (!empty($originentity)) {
  1097. $object->entity = $originentity;
  1098. }
  1099. $object->socid = GETPOST('socid', 'int');
  1100. $object->ref = GETPOST('ref');
  1101. $object->date = $dateinvoice;
  1102. $object->date_pointoftax = $date_pointoftax;
  1103. $object->note_public = trim(GETPOST('note_public', 'restricthtml'));
  1104. $object->note_private = trim(GETPOST('note_private', 'restricthtml'));
  1105. $object->ref_client = GETPOST('ref_client');
  1106. $object->model_pdf = GETPOST('model');
  1107. $object->fk_project = GETPOST('projectid', 'int');
  1108. $object->cond_reglement_id = 0; // No payment term for a credit note
  1109. $object->mode_reglement_id = GETPOST('mode_reglement_id', 'int');
  1110. $object->fk_account = GETPOST('fk_account', 'int');
  1111. $object->remise_absolue = price2num(GETPOST('remise_absolue'), 'MU');
  1112. $object->remise_percent = price2num(GETPOST('remise_percent'), '', 2);
  1113. $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  1114. $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  1115. $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  1116. $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
  1117. // Proprietes particulieres a facture avoir
  1118. $object->fk_facture_source = $sourceinvoice > 0 ? $sourceinvoice : '';
  1119. $object->type = Facture::TYPE_CREDIT_NOTE;
  1120. $facture_source = new Facture($db); // fetch origin object
  1121. if ($facture_source->fetch($object->fk_facture_source) > 0) {
  1122. if ($facture_source->type == Facture::TYPE_SITUATION) {
  1123. $object->situation_counter = $facture_source->situation_counter;
  1124. $object->situation_cycle_ref = $facture_source->situation_cycle_ref;
  1125. $facture_source->fetchPreviousNextSituationInvoice();
  1126. }
  1127. }
  1128. $id = $object->create($user);
  1129. if ($id < 0) {
  1130. $error++;
  1131. } else {
  1132. // copy internal contacts
  1133. if ($object->copy_linked_contact($facture_source, 'internal') < 0) {
  1134. $error++;
  1135. } elseif ($facture_source->socid == $object->socid) {
  1136. // copy external contacts if same company
  1137. if ($object->copy_linked_contact($facture_source, 'external') < 0) {
  1138. $error++;
  1139. }
  1140. }
  1141. }
  1142. // NOTE: Pb with situation invoice
  1143. // NOTE: fields total on situation invoice are stored as cumulative values on total of lines (bad) but delta on invoice total
  1144. // NOTE: fields total on credit note are stored as delta both on total of lines and on invoice total (good)
  1145. // NOTE: fields situation_percent on situation invoice are stored as cumulative values on lines (bad)
  1146. // NOTE: fields situation_percent on credit note are stored as delta on lines (good)
  1147. if (GETPOST('invoiceAvoirWithLines', 'int') == 1 && $id > 0) {
  1148. if (!empty($facture_source->lines)) {
  1149. $fk_parent_line = 0;
  1150. foreach ($facture_source->lines as $line) {
  1151. // Extrafields
  1152. if (method_exists($line, 'fetch_optionals')) {
  1153. // load extrafields
  1154. $line->fetch_optionals();
  1155. }
  1156. // Reset fk_parent_line for no child products and special product
  1157. if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
  1158. $fk_parent_line = 0;
  1159. }
  1160. if ($facture_source->type == Facture::TYPE_SITUATION) {
  1161. $source_fk_prev_id = $line->fk_prev_id; // temporary storing situation invoice fk_prev_id
  1162. $line->fk_prev_id = $line->id; // The new line of the new credit note we are creating must be linked to the situation invoice line it is created from
  1163. if (!empty($facture_source->tab_previous_situation_invoice)) {
  1164. // search the last standard invoice in cycle and the possible credit note between this last and facture_source
  1165. // TODO Move this out of loop of $facture_source->lines
  1166. $tab_jumped_credit_notes = array();
  1167. $lineIndex = count($facture_source->tab_previous_situation_invoice) - 1;
  1168. $searchPreviousInvoice = true;
  1169. while ($searchPreviousInvoice) {
  1170. if ($facture_source->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_SITUATION || $lineIndex < 1) {
  1171. $searchPreviousInvoice = false; // find, exit;
  1172. break;
  1173. } else {
  1174. if ($facture_source->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_CREDIT_NOTE) {
  1175. $tab_jumped_credit_notes[$lineIndex] = $facture_source->tab_previous_situation_invoice[$lineIndex]->id;
  1176. }
  1177. $lineIndex--; // go to previous invoice in cycle
  1178. }
  1179. }
  1180. $maxPrevSituationPercent = 0;
  1181. foreach ($facture_source->tab_previous_situation_invoice[$lineIndex]->lines as $prevLine) {
  1182. if ($prevLine->id == $source_fk_prev_id) {
  1183. $maxPrevSituationPercent = max($maxPrevSituationPercent, $prevLine->situation_percent);
  1184. //$line->subprice = $line->subprice - $prevLine->subprice;
  1185. $line->total_ht = $line->total_ht - $prevLine->total_ht;
  1186. $line->total_tva = $line->total_tva - $prevLine->total_tva;
  1187. $line->total_ttc = $line->total_ttc - $prevLine->total_ttc;
  1188. $line->total_localtax1 = $line->total_localtax1 - $prevLine->total_localtax1;
  1189. $line->total_localtax2 = $line->total_localtax2 - $prevLine->total_localtax2;
  1190. $line->multicurrency_subprice = $line->multicurrency_subprice - $prevLine->multicurrency_subprice;
  1191. $line->multicurrency_total_ht = $line->multicurrency_total_ht - $prevLine->multicurrency_total_ht;
  1192. $line->multicurrency_total_tva = $line->multicurrency_total_tva - $prevLine->multicurrency_total_tva;
  1193. $line->multicurrency_total_ttc = $line->multicurrency_total_ttc - $prevLine->multicurrency_total_ttc;
  1194. }
  1195. }
  1196. // prorata
  1197. $line->situation_percent = $maxPrevSituationPercent - $line->situation_percent;
  1198. //print 'New line based on invoice id '.$facture_source->tab_previous_situation_invoice[$lineIndex]->id.' fk_prev_id='.$source_fk_prev_id.' will be fk_prev_id='.$line->fk_prev_id.' '.$line->total_ht.' '.$line->situation_percent.'<br>';
  1199. // If there is some credit note between last situation invoice and invoice used for credit note generation (note: credit notes are stored as delta)
  1200. $maxPrevSituationPercent = 0;
  1201. foreach ($tab_jumped_credit_notes as $index => $creditnoteid) {
  1202. foreach ($facture_source->tab_previous_situation_invoice[$index]->lines as $prevLine) {
  1203. if ($prevLine->fk_prev_id == $source_fk_prev_id) {
  1204. $maxPrevSituationPercent = $prevLine->situation_percent;
  1205. $line->total_ht -= $prevLine->total_ht;
  1206. $line->total_tva -= $prevLine->total_tva;
  1207. $line->total_ttc -= $prevLine->total_ttc;
  1208. $line->total_localtax1 -= $prevLine->total_localtax1;
  1209. $line->total_localtax2 -= $prevLine->total_localtax2;
  1210. $line->multicurrency_subprice -= $prevLine->multicurrency_subprice;
  1211. $line->multicurrency_total_ht -= $prevLine->multicurrency_total_ht;
  1212. $line->multicurrency_total_tva -= $prevLine->multicurrency_total_tva;
  1213. $line->multicurrency_total_ttc -= $prevLine->multicurrency_total_ttc;
  1214. }
  1215. }
  1216. }
  1217. // prorata
  1218. $line->situation_percent += $maxPrevSituationPercent;
  1219. //print 'New line based on invoice id '.$facture_source->tab_previous_situation_invoice[$lineIndex]->id.' fk_prev_id='.$source_fk_prev_id.' will be fk_prev_id='.$line->fk_prev_id.' '.$line->total_ht.' '.$line->situation_percent.'<br>';
  1220. }
  1221. }
  1222. $line->fk_facture = $object->id;
  1223. $line->fk_parent_line = $fk_parent_line;
  1224. $line->subprice = -$line->subprice; // invert price for object
  1225. $line->pa_ht = $line->pa_ht; // we choosed to have buy/cost price always positive, so no revert of sign here
  1226. $line->total_ht = -$line->total_ht;
  1227. $line->total_tva = -$line->total_tva;
  1228. $line->total_ttc = -$line->total_ttc;
  1229. $line->total_localtax1 = -$line->total_localtax1;
  1230. $line->total_localtax2 = -$line->total_localtax2;
  1231. $line->multicurrency_subprice = -$line->multicurrency_subprice;
  1232. $line->multicurrency_total_ht = -$line->multicurrency_total_ht;
  1233. $line->multicurrency_total_tva = -$line->multicurrency_total_tva;
  1234. $line->multicurrency_total_ttc = -$line->multicurrency_total_ttc;
  1235. $line->context['createcreditnotefrominvoice'] = 1;
  1236. $result = $line->insert(0, 1); // When creating credit note with same lines than source, we must ignore error if discount alreayd linked
  1237. $object->lines[] = $line; // insert new line in current object
  1238. // Defined the new fk_parent_line
  1239. if ($result > 0 && $line->product_type == 9) {
  1240. $fk_parent_line = $result;
  1241. }
  1242. }
  1243. $object->update_price(1);
  1244. }
  1245. }
  1246. if (GETPOST('invoiceAvoirWithPaymentRestAmount', 'int') == 1 && $id > 0) {
  1247. if ($facture_source->fetch($object->fk_facture_source) > 0) {
  1248. $totalpaid = $facture_source->getSommePaiement();
  1249. $totalcreditnotes = $facture_source->getSumCreditNotesUsed();
  1250. $totaldeposits = $facture_source->getSumDepositsUsed();
  1251. $remain_to_pay = abs($facture_source->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits);
  1252. $object->addline($langs->trans('invoiceAvoirLineWithPaymentRestAmount'), $remain_to_pay, 1, 0, 0, 0, 0, 0, '', '', 'TTC');
  1253. }
  1254. }
  1255. // Add link between credit note and origin
  1256. if (!empty($object->fk_facture_source) && $id > 0) {
  1257. $facture_source->fetch($object->fk_facture_source);
  1258. $facture_source->fetchObjectLinked();
  1259. if (!empty($facture_source->linkedObjectsIds)) {
  1260. foreach ($facture_source->linkedObjectsIds as $sourcetype => $TIds) {
  1261. $object->add_object_linked($sourcetype, current($TIds));
  1262. }
  1263. }
  1264. }
  1265. }
  1266. }
  1267. // Receipt Credit note invoice
  1268. if (GETPOST('type') == Facture::TYPE_RECEIPT_CREDIT_NOTE) {
  1269. if ($object->array_options['options_commission_deduction']) {
  1270. $factureObj = new Facture($db);
  1271. $userinvoiceObj = new UserInvoice($db);
  1272. $commmissionhandler = new CommissionHandler();
  1273. $productObj = new Product($db);
  1274. $productObjHUF = new Product($db);
  1275. $fk_facture_resource = GETPOST('fac_avoir', 'int');
  1276. $result_source_facture = $factureObj->fetch($fk_facture_resource);
  1277. if ($factureObj->fk_multicurrency == 2) {
  1278. $fk_product = $factureObj->lines[0]->fk_product;
  1279. $assignedProduct = $productObj->fetch($fk_product);
  1280. $relatedService = $productObj->array_options['options_related_service'];
  1281. $productToCount = $productObjHUF->fetch($relatedService);
  1282. $price_ttc = $productObjHUF->price_ttc;
  1283. $commissionValue = $productObjHUF->array_options['options_commission_value'];
  1284. $type = $productObjHUF->array_options['options_commission_type'] == 1 ? '%' : 'Forint';
  1285. $row['total_ttc'] = $price_ttc;
  1286. $row['commission'] = $commissionValue . '_' . $type;
  1287. ;
  1288. $amount = $commmissionhandler->getAmountOfCommission($row);
  1289. } else {
  1290. $row['total_ttc'] = $factureObj->total_ttc;
  1291. $row['commission'] = $factureObj->array_options['options_commission'];
  1292. $amount = $commmissionhandler->getAmountOfCommission($row);
  1293. }
  1294. $resultUserinvoiceObj = $userinvoiceObj->fetchAll('', '', 0, 0, ["customsql" => "invoices LIKE '%{$factureObj->id}%'"]);
  1295. $usersArray = [];
  1296. foreach ($resultUserinvoiceObj as $userObj) {
  1297. $usersArray[] = $userObj->user_id;
  1298. }
  1299. $numberOfUsers = count($usersArray);
  1300. if ($numberOfUsers > 0) {
  1301. $amountOfOneUser = $amount / $numberOfUsers;
  1302. foreach ($usersArray as $userid) {
  1303. if ($amountOfOneUser > 0) {
  1304. $userinvoiceObj2 = new UserInvoice($db);
  1305. $userinvoiceObj2->ref = 'Withhold_' . dol_now() . '_' . rand(1000000, 9999999);
  1306. ;
  1307. $userinvoiceObj2->label = 'Visszatartás / Withholding ' . date('Y-m-d');
  1308. $userinvoiceObj2->description = 'Összeg / Amount: ' . $amountOfOneUser . ' HUF. Commission deduction. (CREDIT NOTE)';
  1309. $userinvoiceObj2->user_id = $userid;
  1310. $userinvoiceObj2->payment_type = 1;
  1311. $userinvoiceObj2->amount = $amountOfOneUser;
  1312. $userinvoiceObj2->currency = 0;
  1313. $userinvoiceObj2->individual = 1;
  1314. $userinvoiceObj2->invoices = $factureObj->id;
  1315. $result = $userinvoiceObj2->create($user);
  1316. if ($result < 0) {
  1317. $error++;
  1318. }
  1319. }
  1320. }
  1321. } else {
  1322. if ($amount > 0) {
  1323. $userinvoiceObj2 = new UserInvoice($db);
  1324. $userinvoiceObj2->ref = 'Withhold_' . dol_now() . '_' . rand(1000000, 9999999);
  1325. ;
  1326. $userinvoiceObj2->label = 'Visszatartás / Withholding ' . date('Y-m-d');
  1327. $userinvoiceObj2->description = 'Összeg / Amount: ' . $amount . ' HUF. Commission deduction. (CREDIT NOTE)';
  1328. $userinvoiceObj2->user_id = $factureObj->fk_user_valid;
  1329. $userinvoiceObj2->payment_type = 1;
  1330. $userinvoiceObj2->amount = $amount;
  1331. $userinvoiceObj2->currency = 0;
  1332. $userinvoiceObj2->individual = 1;
  1333. $userinvoiceObj2->invoices = $factureObj->id;
  1334. $result = $userinvoiceObj2->create($user);
  1335. if ($result < 0) {
  1336. $error++;
  1337. }
  1338. }
  1339. }
  1340. }
  1341. $sourceinvoice = GETPOST('fac_avoir', 'int');
  1342. if (!($sourceinvoice > 0) && empty($conf->global->INVOICE_CREDIT_NOTE_STANDALONE)) {
  1343. $error++;
  1344. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CorrectInvoice")), null, 'errors');
  1345. $action = 'create';
  1346. }
  1347. if (empty($dateinvoice)) {
  1348. $error++;
  1349. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
  1350. $action = 'create';
  1351. } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
  1352. $error++;
  1353. setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
  1354. $action = 'create';
  1355. }
  1356. if (!$error) {
  1357. if (!empty($originentity)) {
  1358. $object->entity = $originentity;
  1359. }
  1360. $object->socid = GETPOST('socid', 'int');
  1361. $object->ref = GETPOST('ref');
  1362. $object->date = $dateinvoice;
  1363. $object->date_pointoftax = $date_pointoftax;
  1364. $object->note_public = trim(GETPOST('note_public', 'restricthtml'));
  1365. $object->note_private = trim(GETPOST('note_private', 'restricthtml'));
  1366. $object->ref_client = GETPOST('ref_client');
  1367. $object->model_pdf = GETPOST('model');
  1368. $object->fk_project = GETPOST('projectid', 'int');
  1369. $object->cond_reglement_id = 0; // No payment term for a credit note
  1370. $object->mode_reglement_id = GETPOST('mode_reglement_id', 'int');
  1371. $object->fk_account = GETPOST('fk_account', 'int');
  1372. $object->remise_absolue = price2num(GETPOST('remise_absolue'), 'MU');
  1373. $object->remise_percent = price2num(GETPOST('remise_percent'), '', 2);
  1374. $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  1375. $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  1376. $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  1377. $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
  1378. // Proprietes particulieres a facture avoir
  1379. $object->fk_facture_source = $sourceinvoice > 0 ? $sourceinvoice : '';
  1380. $object->type = Facture::TYPE_RECEIPT_CREDIT_NOTE;
  1381. $facture_source = new Facture($db); // fetch origin object
  1382. if ($facture_source->fetch($object->fk_facture_source) > 0) {
  1383. if ($facture_source->type == Facture::TYPE_SITUATION) {
  1384. $object->situation_counter = $facture_source->situation_counter;
  1385. $object->situation_cycle_ref = $facture_source->situation_cycle_ref;
  1386. $facture_source->fetchPreviousNextSituationInvoice();
  1387. }
  1388. }
  1389. $id = $object->create($user);
  1390. if ($id < 0) {
  1391. $error++;
  1392. } else {
  1393. // copy internal contacts
  1394. if ($object->copy_linked_contact($facture_source, 'internal') < 0) {
  1395. $error++;
  1396. } elseif ($facture_source->socid == $object->socid) {
  1397. // copy external contacts if same company
  1398. if ($object->copy_linked_contact($facture_source, 'external') < 0) {
  1399. $error++;
  1400. }
  1401. }
  1402. }
  1403. // NOTE: Pb with situation invoice
  1404. // NOTE: fields total on situation invoice are stored as cumulative values on total of lines (bad) but delta on invoice total
  1405. // NOTE: fields total on credit note are stored as delta both on total of lines and on invoice total (good)
  1406. // NOTE: fields situation_percent on situation invoice are stored as cumulative values on lines (bad)
  1407. // NOTE: fields situation_percent on credit note are stored as delta on lines (good)
  1408. if (GETPOST('invoiceAvoirWithLines', 'int') == 1 && $id > 0) {
  1409. if (!empty($facture_source->lines)) {
  1410. $fk_parent_line = 0;
  1411. foreach ($facture_source->lines as $line) {
  1412. // Extrafields
  1413. if (method_exists($line, 'fetch_optionals')) {
  1414. // load extrafields
  1415. $line->fetch_optionals();
  1416. }
  1417. // Reset fk_parent_line for no child products and special product
  1418. if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
  1419. $fk_parent_line = 0;
  1420. }
  1421. if ($facture_source->type == Facture::TYPE_SITUATION) {
  1422. $source_fk_prev_id = $line->fk_prev_id; // temporary storing situation invoice fk_prev_id
  1423. $line->fk_prev_id = $line->id; // The new line of the new credit note we are creating must be linked to the situation invoice line it is created from
  1424. if (!empty($facture_source->tab_previous_situation_invoice)) {
  1425. // search the last standard invoice in cycle and the possible credit note between this last and facture_source
  1426. // TODO Move this out of loop of $facture_source->lines
  1427. $tab_jumped_credit_notes = array();
  1428. $lineIndex = count($facture_source->tab_previous_situation_invoice) - 1;
  1429. $searchPreviousInvoice = true;
  1430. while ($searchPreviousInvoice) {
  1431. if ($facture_source->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_SITUATION || $lineIndex < 1) {
  1432. $searchPreviousInvoice = false; // find, exit;
  1433. break;
  1434. } else {
  1435. if ($facture_source->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_RECEIPT_CREDIT_NOTE) {
  1436. $tab_jumped_credit_notes[$lineIndex] = $facture_source->tab_previous_situation_invoice[$lineIndex]->id;
  1437. }
  1438. $lineIndex--; // go to previous invoice in cycle
  1439. }
  1440. }
  1441. $maxPrevSituationPercent = 0;
  1442. foreach ($facture_source->tab_previous_situation_invoice[$lineIndex]->lines as $prevLine) {
  1443. if ($prevLine->id == $source_fk_prev_id) {
  1444. $maxPrevSituationPercent = max($maxPrevSituationPercent, $prevLine->situation_percent);
  1445. //$line->subprice = $line->subprice - $prevLine->subprice;
  1446. $line->total_ht = $line->total_ht - $prevLine->total_ht;
  1447. $line->total_tva = $line->total_tva - $prevLine->total_tva;
  1448. $line->total_ttc = $line->total_ttc - $prevLine->total_ttc;
  1449. $line->total_localtax1 = $line->total_localtax1 - $prevLine->total_localtax1;
  1450. $line->total_localtax2 = $line->total_localtax2 - $prevLine->total_localtax2;
  1451. $line->multicurrency_subprice = $line->multicurrency_subprice - $prevLine->multicurrency_subprice;
  1452. $line->multicurrency_total_ht = $line->multicurrency_total_ht - $prevLine->multicurrency_total_ht;
  1453. $line->multicurrency_total_tva = $line->multicurrency_total_tva - $prevLine->multicurrency_total_tva;
  1454. $line->multicurrency_total_ttc = $line->multicurrency_total_ttc - $prevLine->multicurrency_total_ttc;
  1455. }
  1456. }
  1457. // prorata
  1458. $line->situation_percent = $maxPrevSituationPercent - $line->situation_percent;
  1459. //print 'New line based on invoice id '.$facture_source->tab_previous_situation_invoice[$lineIndex]->id.' fk_prev_id='.$source_fk_prev_id.' will be fk_prev_id='.$line->fk_prev_id.' '.$line->total_ht.' '.$line->situation_percent.'<br>';
  1460. // If there is some credit note between last situation invoice and invoice used for credit note generation (note: credit notes are stored as delta)
  1461. $maxPrevSituationPercent = 0;
  1462. foreach ($tab_jumped_credit_notes as $index => $creditnoteid) {
  1463. foreach ($facture_source->tab_previous_situation_invoice[$index]->lines as $prevLine) {
  1464. if ($prevLine->fk_prev_id == $source_fk_prev_id) {
  1465. $maxPrevSituationPercent = $prevLine->situation_percent;
  1466. $line->total_ht -= $prevLine->total_ht;
  1467. $line->total_tva -= $prevLine->total_tva;
  1468. $line->total_ttc -= $prevLine->total_ttc;
  1469. $line->total_localtax1 -= $prevLine->total_localtax1;
  1470. $line->total_localtax2 -= $prevLine->total_localtax2;
  1471. $line->multicurrency_subprice -= $prevLine->multicurrency_subprice;
  1472. $line->multicurrency_total_ht -= $prevLine->multicurrency_total_ht;
  1473. $line->multicurrency_total_tva -= $prevLine->multicurrency_total_tva;
  1474. $line->multicurrency_total_ttc -= $prevLine->multicurrency_total_ttc;
  1475. }
  1476. }
  1477. }
  1478. // prorata
  1479. $line->situation_percent += $maxPrevSituationPercent;
  1480. //print 'New line based on invoice id '.$facture_source->tab_previous_situation_invoice[$lineIndex]->id.' fk_prev_id='.$source_fk_prev_id.' will be fk_prev_id='.$line->fk_prev_id.' '.$line->total_ht.' '.$line->situation_percent.'<br>';
  1481. }
  1482. }
  1483. $line->fk_facture = $object->id;
  1484. $line->fk_parent_line = $fk_parent_line;
  1485. $line->subprice = -$line->subprice; // invert price for object
  1486. $line->pa_ht = $line->pa_ht; // we choosed to have buy/cost price always positive, so no revert of sign here
  1487. $line->total_ht = -$line->total_ht;
  1488. $line->total_tva = -$line->total_tva;
  1489. $line->total_ttc = -$line->total_ttc;
  1490. $line->total_localtax1 = -$line->total_localtax1;
  1491. $line->total_localtax2 = -$line->total_localtax2;
  1492. $line->multicurrency_subprice = -$line->multicurrency_subprice;
  1493. $line->multicurrency_total_ht = -$line->multicurrency_total_ht;
  1494. $line->multicurrency_total_tva = -$line->multicurrency_total_tva;
  1495. $line->multicurrency_total_ttc = -$line->multicurrency_total_ttc;
  1496. $line->context['createcreditnotefrominvoice'] = 1;
  1497. $result = $line->insert(0, 1); // When creating credit note with same lines than source, we must ignore error if discount alreayd linked
  1498. $object->lines[] = $line; // insert new line in current object
  1499. // Defined the new fk_parent_line
  1500. if ($result > 0 && $line->product_type == 9) {
  1501. $fk_parent_line = $result;
  1502. }
  1503. }
  1504. $object->update_price(1);
  1505. }
  1506. }
  1507. if (GETPOST('invoiceAvoirWithPaymentRestAmount', 'int') == 1 && $id > 0) {
  1508. if ($facture_source->fetch($object->fk_facture_source) > 0) {
  1509. $totalpaid = $facture_source->getSommePaiement();
  1510. $totalcreditnotes = $facture_source->getSumCreditNotesUsed();
  1511. $totaldeposits = $facture_source->getSumDepositsUsed();
  1512. $remain_to_pay = abs($facture_source->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits);
  1513. $object->addline($langs->trans('invoiceAvoirLineWithPaymentRestAmount'), $remain_to_pay, 1, 0, 0, 0, 0, 0, '', '', 'TTC');
  1514. }
  1515. }
  1516. // Add link between credit note and origin
  1517. if (!empty($object->fk_facture_source) && $id > 0) {
  1518. $facture_source->fetch($object->fk_facture_source);
  1519. $facture_source->fetchObjectLinked();
  1520. if (!empty($facture_source->linkedObjectsIds)) {
  1521. foreach ($facture_source->linkedObjectsIds as $sourcetype => $TIds) {
  1522. $object->add_object_linked($sourcetype, current($TIds));
  1523. }
  1524. }
  1525. }
  1526. }
  1527. }
  1528. // Standard invoice or Deposit invoice, created from a Predefined template invoice
  1529. if ((GETPOST('type') == Facture::TYPE_STANDARD || GETPOST('type') == Facture::TYPE_DEPOSIT || GETPOST('type') == Facture::TYPE_RECEIPT) && GETPOST('fac_rec', 'int') > 0) {
  1530. if (empty($dateinvoice)) {
  1531. $error++;
  1532. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
  1533. $action = 'create';
  1534. } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
  1535. $error++;
  1536. setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
  1537. $action = 'create';
  1538. }
  1539. if (!$error) {
  1540. $object->socid = GETPOST('socid', 'int');
  1541. $object->type = GETPOST('type');
  1542. $object->ref = GETPOST('ref');
  1543. $object->date = $dateinvoice;
  1544. $object->date_pointoftax = $date_pointoftax;
  1545. $object->note_public = trim(GETPOST('note_public', 'restricthtml'));
  1546. $object->note_private = trim(GETPOST('note_private', 'restricthtml'));
  1547. $object->ref_customer = GETPOST('ref_client');
  1548. $object->ref_client = $object->ref_customer;
  1549. $object->model_pdf = GETPOST('model');
  1550. $object->fk_project = GETPOST('projectid', 'int');
  1551. $object->cond_reglement_id = (GETPOST('type') == 3 ? 1 : GETPOST('cond_reglement_id'));
  1552. $object->mode_reglement_id = GETPOST('mode_reglement_id', 'int');
  1553. $object->fk_account = GETPOST('fk_account', 'int');
  1554. $object->amount = price2num(GETPOST('amount'));
  1555. $object->remise_absolue = price2num(GETPOST('remise_absolue'), 'MU');
  1556. $object->remise_percent = price2num(GETPOST('remise_percent'), '', 2);
  1557. $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  1558. $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  1559. $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  1560. $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
  1561. // Source facture
  1562. $object->fac_rec = GETPOST('fac_rec', 'int');
  1563. $id = $object->create($user); // This include recopy of links from recurring invoice and recurring invoice lines
  1564. }
  1565. }
  1566. // Standard or deposit invoice, not from a Predefined template invoice
  1567. if ((GETPOST('type') == Facture::TYPE_STANDARD || GETPOST('type') == Facture::TYPE_DEPOSIT || GETPOST('type') == Facture::TYPE_PROFORMA || (GETPOST('type') == Facture::TYPE_SITUATION || GETPOST('type') == Facture::TYPE_RECEIPT && !GETPOST('situations'))) && GETPOST('fac_rec') <= 0) {
  1568. $typeamount = GETPOST('typedeposit', 'aZ09');
  1569. $valuestandardinvoice = price2num(str_replace('%', '', GETPOST('valuestandardinvoice', 'alpha')), 'MU');
  1570. $valuepeceipt = price2num(str_replace('%', '', GETPOST('valuepeceipt', 'alpha')), 'MU');
  1571. $valuedeposit = price2num(str_replace('%', '', GETPOST('valuedeposit', 'alpha')), 'MU');
  1572. if (GETPOST('socid', 'int') < 1) {
  1573. $error++;
  1574. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Customer")), null, 'errors');
  1575. $action = 'create';
  1576. }
  1577. if (empty($dateinvoice)) {
  1578. $error++;
  1579. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
  1580. $action = 'create';
  1581. } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
  1582. $error++;
  1583. setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
  1584. $action = 'create';
  1585. }
  1586. if (GETPOST('type') == Facture::TYPE_STANDARD) {
  1587. if ($valuestandardinvoice < 0 || $valuestandardinvoice > 100) {
  1588. setEventMessages($langs->trans("ErrorAPercentIsRequired"), null, 'errors');
  1589. $error++;
  1590. $action = 'create';
  1591. }
  1592. } elseif (GETPOST('type') == Facture::TYPE_RECEIPT) {
  1593. if ($valuepeceipt < 0 || $valuepeceipt > 100) {
  1594. setEventMessages($langs->trans("ErrorAPercentIsRequired"), null, 'errors');
  1595. $error++;
  1596. $action = 'create';
  1597. }
  1598. } elseif (GETPOST('type') == Facture::TYPE_DEPOSIT) {
  1599. if ($typeamount && !empty($origin) && !empty($originid)) {
  1600. if ($typeamount == 'amount' && $valuedeposit <= 0) {
  1601. setEventMessages($langs->trans("ErrorAnAmountWithoutTaxIsRequired"), null, 'errors');
  1602. $error++;
  1603. $action = 'create';
  1604. }
  1605. if ($typeamount == 'variable' && $valuedeposit <= 0) {
  1606. setEventMessages($langs->trans("ErrorAPercentIsRequired"), null, 'errors');
  1607. $error++;
  1608. $action = 'create';
  1609. }
  1610. if ($typeamount == 'variablealllines' && $valuedeposit <= 0) {
  1611. setEventMessages($langs->trans("ErrorAPercentIsRequired"), null, 'errors');
  1612. $error++;
  1613. $action = 'create';
  1614. }
  1615. }
  1616. }
  1617. if (!$error) {
  1618. // Si facture standard
  1619. $object->socid = GETPOST('socid', 'int');
  1620. $object->type = GETPOST('type');
  1621. $object->ref = GETPOST('ref');
  1622. $object->date = $dateinvoice;
  1623. $object->date_pointoftax = $date_pointoftax;
  1624. $object->note_public = trim(GETPOST('note_public', 'restricthtml'));
  1625. $object->note_private = trim(GETPOST('note_private', 'restricthtml'));
  1626. $object->ref_client = GETPOST('ref_client');
  1627. $object->ref_customer = GETPOST('ref_client');
  1628. $object->model_pdf = GETPOST('model');
  1629. $object->fk_project = GETPOST('projectid', 'int');
  1630. $object->cond_reglement_id = (GETPOST('type') == 3 ? 1 : GETPOST('cond_reglement_id'));
  1631. $object->mode_reglement_id = GETPOST('mode_reglement_id');
  1632. $object->fk_account = GETPOST('fk_account', 'int');
  1633. $object->amount = price2num(GETPOST('amount'));
  1634. $object->remise_absolue = price2num(GETPOST('remise_absolue'), 'MU');
  1635. $object->remise_percent = price2num(GETPOST('remise_percent'), '', 2);
  1636. $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  1637. $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  1638. $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  1639. $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
  1640. if (GETPOST('type') == Facture::TYPE_SITUATION) {
  1641. $object->situation_counter = 1;
  1642. $object->situation_final = 0;
  1643. $object->situation_cycle_ref = $object->newCycle();
  1644. }
  1645. if (in_array($object->type, $retainedWarrantyInvoiceAvailableType)) {
  1646. $object->retained_warranty = GETPOST('retained_warranty', 'int');
  1647. $object->retained_warranty_fk_cond_reglement = GETPOST('retained_warranty_fk_cond_reglement', 'int');
  1648. } else {
  1649. $object->retained_warranty = 0;
  1650. $object->retained_warranty_fk_cond_reglement = 0;
  1651. }
  1652. $retained_warranty_date_limit = GETPOST('retained_warranty_date_limit');
  1653. if (!empty($retained_warranty_date_limit) && dol_stringtotime($retained_warranty_date_limit)) {
  1654. $object->retained_warranty_date_limit = dol_stringtotime($retained_warranty_date_limit);
  1655. }
  1656. $object->retained_warranty_date_limit = !empty($object->retained_warranty_date_limit) ? $object->retained_warranty_date_limit : $object->calculate_date_lim_reglement($object->retained_warranty_fk_cond_reglement);
  1657. $object->fetch_thirdparty();
  1658. // If creation from another object of another module (Example: origin=propal, originid=1)
  1659. if (!empty($origin) && !empty($originid)) {
  1660. $regs = array();
  1661. // Parse element/subelement (ex: project_task)
  1662. $element = $subelement = $origin;
  1663. if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs)) {
  1664. $element = $regs[1];
  1665. $subelement = $regs[2];
  1666. }
  1667. // For compatibility
  1668. if ($element == 'order') {
  1669. $element = $subelement = 'commande';
  1670. }
  1671. if ($element == 'propal') {
  1672. $element = 'comm/propal';
  1673. $subelement = 'propal';
  1674. }
  1675. if ($element == 'contract') {
  1676. $element = $subelement = 'contrat';
  1677. }
  1678. if ($element == 'inter') {
  1679. $element = $subelement = 'ficheinter';
  1680. }
  1681. if ($element == 'shipping') {
  1682. $element = $subelement = 'expedition';
  1683. }
  1684. $object->origin = $origin;
  1685. $object->origin_id = $originid;
  1686. // Possibility to add external linked objects with hooks
  1687. $object->linked_objects[$object->origin] = $object->origin_id;
  1688. // link with order if it is a shipping invoice
  1689. if ($object->origin == 'shipping') {
  1690. require_once DOL_DOCUMENT_ROOT . '/expedition/class/expedition.class.php';
  1691. $exp = new Expedition($db);
  1692. $exp->fetch($object->origin_id);
  1693. $exp->fetchObjectLinked();
  1694. if (is_array($exp->linkedObjectsIds['commande']) && count($exp->linkedObjectsIds['commande']) > 0) {
  1695. foreach ($exp->linkedObjectsIds['commande'] as $key => $value) {
  1696. $object->linked_objects['commande'] = $value;
  1697. }
  1698. }
  1699. }
  1700. if (is_array($_POST['other_linked_objects']) && !empty($_POST['other_linked_objects'])) {
  1701. $object->linked_objects = array_merge($object->linked_objects, $_POST['other_linked_objects']);
  1702. }
  1703. $id = $object->create($user); // This include class to add_object_linked() and add add_contact()
  1704. if ($id > 0) {
  1705. dol_include_once('/' . $element . '/class/' . $subelement . '.class.php');
  1706. $classname = ucfirst($subelement);
  1707. $srcobject = new $classname($db);
  1708. dol_syslog("Try to find source object origin=" . $object->origin . " originid=" . $object->origin_id . " to add lines or deposit lines");
  1709. $result = $srcobject->fetch($object->origin_id);
  1710. // If deposit invoice - down payment with 1 line (fixed amount or percent)
  1711. if (GETPOST('type') == Facture::TYPE_DEPOSIT && in_array($typeamount, array('amount', 'variable'))) {
  1712. // Define the array $amountdeposit
  1713. $amountdeposit = array();
  1714. if (!empty($conf->global->MAIN_DEPOSIT_MULTI_TVA)) {
  1715. if ($typeamount == 'amount') {
  1716. $amount = $valuedeposit;
  1717. } else {
  1718. $amount = $srcobject->total_ttc * ($valuedeposit / 100);
  1719. }
  1720. $TTotalByTva = array();
  1721. foreach ($srcobject->lines as &$line) {
  1722. if (!empty($line->special_code)) {
  1723. continue;
  1724. }
  1725. $TTotalByTva[$line->tva_tx] += $line->total_ttc;
  1726. }
  1727. foreach ($TTotalByTva as $tva => &$total) {
  1728. $coef = $total / $srcobject->total_ttc; // Calc coef
  1729. $am = $amount * $coef;
  1730. $amount_ttc_diff += $am;
  1731. $amountdeposit[$tva] += $am / (1 + $tva / 100); // Convert into HT for the addline
  1732. }
  1733. } else {
  1734. if ($typeamount == 'amount') {
  1735. $amountdeposit[0] = $valuedeposit;
  1736. } elseif ($typeamount == 'variable') {
  1737. if ($result > 0) {
  1738. $totalamount = 0;
  1739. $lines = $srcobject->lines;
  1740. $numlines = count($lines);
  1741. for ($i = 0; $i < $numlines; $i++) {
  1742. $qualified = 1;
  1743. if (empty($lines[$i]->qty)) {
  1744. $qualified = 0; // We discard qty=0, it is an option
  1745. }
  1746. if (!empty($lines[$i]->special_code)) {
  1747. $qualified = 0; // We discard special_code (frais port, ecotaxe, option, ...)
  1748. }
  1749. if ($qualified) {
  1750. $totalamount += $lines[$i]->total_ht; // Fixme : is it not for the customer ? Shouldn't we take total_ttc ?
  1751. $tva_tx = $lines[$i]->tva_tx;
  1752. $amountdeposit[$tva_tx] += ($lines[$i]->total_ht * $valuedeposit) / 100;
  1753. }
  1754. }
  1755. if ($totalamount == 0) {
  1756. $amountdeposit[0] = 0;
  1757. }
  1758. } else {
  1759. setEventMessages($srcobject->error, $srcobject->errors, 'errors');
  1760. $error++;
  1761. }
  1762. }
  1763. $amount_ttc_diff = $amountdeposit[0];
  1764. }
  1765. foreach ($amountdeposit as $tva => $amount) {
  1766. if (empty($amount)) {
  1767. continue;
  1768. }
  1769. $arraylist = array(
  1770. 'amount' => 'FixAmount',
  1771. 'variable' => 'VarAmount'
  1772. );
  1773. $descline = '(DEPOSIT)';
  1774. //$descline.= ' - '.$langs->trans($arraylist[$typeamount]);
  1775. if ($typeamount == 'amount') {
  1776. $descline .= ' (' . price($valuedeposit, '', $langs, 0, -1, -1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ')';
  1777. } elseif ($typeamount == 'variable') {
  1778. $descline .= ' (' . $valuedeposit . '%)';
  1779. }
  1780. $descline .= ' - ' . $srcobject->ref;
  1781. $result = $object->addline(
  1782. $descline,
  1783. $amount, // subprice
  1784. 1, // quantity
  1785. $tva, // vat rate
  1786. 0, // localtax1_tx
  1787. 0, // localtax2_tx
  1788. (empty($conf->global->INVOICE_PRODUCTID_DEPOSIT) ? 0 : $conf->global->INVOICE_PRODUCTID_DEPOSIT), // fk_product
  1789. 0, // remise_percent
  1790. 0, // date_start
  1791. 0, // date_end
  1792. 0,
  1793. $lines[$i]->info_bits, // info_bits
  1794. 0,
  1795. 'HT',
  1796. 0,
  1797. 0, // product_type
  1798. 1,
  1799. $lines[$i]->special_code,
  1800. $object->origin,
  1801. 0,
  1802. 0,
  1803. 0,
  1804. 0,
  1805. '',
  1806. 0,
  1807. 100,
  1808. 0,
  1809. null,
  1810. 0,
  1811. '',
  1812. 1
  1813. );
  1814. }
  1815. $diff = $object->total_ttc - $amount_ttc_diff;
  1816. if (!empty($conf->global->MAIN_DEPOSIT_MULTI_TVA) && $diff != 0) {
  1817. $object->fetch_lines();
  1818. $subprice_diff = $object->lines[0]->subprice - $diff / (1 + $object->lines[0]->tva_tx / 100);
  1819. $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);
  1820. }
  1821. }
  1822. // standard invoice, credit note, or down payment from a percent of all lines
  1823. if (GETPOST('type') != Facture::TYPE_DEPOSIT || (GETPOST('type') == Facture::TYPE_DEPOSIT && $typeamount == 'variablealllines')) {
  1824. if ($result > 0) {
  1825. $lines = $srcobject->lines;
  1826. if (empty($lines) && method_exists($srcobject, 'fetch_lines')) {
  1827. $srcobject->fetch_lines();
  1828. $lines = $srcobject->lines;
  1829. }
  1830. // If we create a standard invoice with a percent, we change amount by changing the qty
  1831. if (GETPOST('type') == Facture::TYPE_STANDARD && $valuestandardinvoice > 0 && $valuestandardinvoice < 100) {
  1832. if (is_array($lines)) {
  1833. foreach ($lines as $line) {
  1834. // We keep ->subprice and ->pa_ht, but we change the qty
  1835. $line->qty = price2num($line->qty * $valuestandardinvoice / 100, 'MS');
  1836. }
  1837. }
  1838. }
  1839. // If we create a receipt with a percent, we change amount by changing the qty
  1840. if (GETPOST('type') == Facture::TYPE_RECEIPT && $valuepeceipt > 0 && $valuepeceipt < 100) {
  1841. if (is_array($lines)) {
  1842. foreach ($lines as $line) {
  1843. // We keep ->subprice and ->pa_ht, but we change the qty
  1844. $line->qty = price2num($line->qty * $valuepeceipt / 100, 'MS');
  1845. }
  1846. }
  1847. }
  1848. // If we create a down payment with a percent on all lines, we change amount by changing the qty
  1849. if (GETPOST('type') == Facture::TYPE_DEPOSIT && $typeamount == 'variablealllines') {
  1850. if (is_array($lines)) {
  1851. foreach ($lines as $line) {
  1852. // We keep ->subprice and ->pa_ht, but we change the qty
  1853. $line->qty = price2num($line->qty * $valuedeposit / 100, 'MS');
  1854. }
  1855. }
  1856. }
  1857. $fk_parent_line = 0;
  1858. $num = count($lines);
  1859. for ($i = 0; $i < $num; $i++) {
  1860. if (!in_array($lines[$i]->id, $selectedLines)) {
  1861. continue; // Skip unselected lines
  1862. }
  1863. // Don't add lines with qty 0 when coming from a shipment including all order lines
  1864. if ($srcobject->element == 'shipping' && $conf->global->SHIPMENT_GETS_ALL_ORDER_PRODUCTS && $lines[$i]->qty == 0) {
  1865. continue;
  1866. }
  1867. // Don't add closed lines when coming from a contract (Set constant to '0,5' to exclude also inactive lines)
  1868. if (!isset($conf->global->CONTRACT_EXCLUDE_SERVICES_STATUS_FOR_INVOICE)) {
  1869. $conf->global->CONTRACT_EXCLUDE_SERVICES_STATUS_FOR_INVOICE = '5';
  1870. }
  1871. if ($srcobject->element == 'contrat' && in_array($lines[$i]->statut, explode(',', $conf->global->CONTRACT_EXCLUDE_SERVICES_STATUS_FOR_INVOICE))) {
  1872. continue;
  1873. }
  1874. $label = (!empty($lines[$i]->label) ? $lines[$i]->label : '');
  1875. $desc = (!empty($lines[$i]->desc) ? $lines[$i]->desc : $lines[$i]->libelle);
  1876. if ($object->situation_counter == 1) {
  1877. $lines[$i]->situation_percent = 0;
  1878. }
  1879. if ($lines[$i]->subprice < 0 && empty($conf->global->INVOICE_KEEP_DISCOUNT_LINES_AS_IN_ORIGIN)) {
  1880. // Negative line, we create a discount line
  1881. $discount = new DiscountAbsolute($db);
  1882. $discount->fk_soc = $object->socid;
  1883. $discount->amount_ht = abs($lines[$i]->total_ht);
  1884. $discount->amount_tva = abs($lines[$i]->total_tva);
  1885. $discount->amount_ttc = abs($lines[$i]->total_ttc);
  1886. $discount->tva_tx = $lines[$i]->tva_tx;
  1887. $discount->fk_user = $user->id;
  1888. $discount->description = $desc;
  1889. $discount->multicurrency_subprice = abs($lines[$i]->multicurrency_subprice);
  1890. $discount->multicurrency_amount_ht = abs($lines[$i]->multicurrency_total_ht);
  1891. $discount->multicurrency_amount_tva = abs($lines[$i]->multicurrency_total_tva);
  1892. $discount->multicurrency_amount_ttc = abs($lines[$i]->multicurrency_total_ttc);
  1893. $discountid = $discount->create($user);
  1894. if ($discountid > 0) {
  1895. $result = $object->insert_discount($discountid); // This include link_to_invoice
  1896. } else {
  1897. setEventMessages($discount->error, $discount->errors, 'errors');
  1898. $error++;
  1899. break;
  1900. }
  1901. } else {
  1902. // Positive line
  1903. $product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0);
  1904. // Date start
  1905. $date_start = false;
  1906. if ($lines[$i]->date_debut_prevue) {
  1907. $date_start = $lines[$i]->date_debut_prevue;
  1908. }
  1909. if ($lines[$i]->date_debut_reel) {
  1910. $date_start = $lines[$i]->date_debut_reel;
  1911. }
  1912. if ($lines[$i]->date_start) {
  1913. $date_start = $lines[$i]->date_start;
  1914. }
  1915. // Date end
  1916. $date_end = false;
  1917. if ($lines[$i]->date_fin_prevue) {
  1918. $date_end = $lines[$i]->date_fin_prevue;
  1919. }
  1920. if ($lines[$i]->date_fin_reel) {
  1921. $date_end = $lines[$i]->date_fin_reel;
  1922. }
  1923. if ($lines[$i]->date_end) {
  1924. $date_end = $lines[$i]->date_end;
  1925. }
  1926. // Reset fk_parent_line for no child products and special product
  1927. if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) {
  1928. $fk_parent_line = 0;
  1929. }
  1930. // Extrafields
  1931. if (method_exists($lines[$i], 'fetch_optionals')) {
  1932. $lines[$i]->fetch_optionals();
  1933. $array_options = $lines[$i]->array_options;
  1934. }
  1935. $tva_tx = $lines[$i]->tva_tx;
  1936. if (!empty($lines[$i]->vat_src_code) && !preg_match('/\(/', $tva_tx)) {
  1937. $tva_tx .= ' (' . $lines[$i]->vat_src_code . ')';
  1938. }
  1939. // View third's localtaxes for NOW and do not use value from origin.
  1940. // TODO Is this really what we want ? Yes if source is template invoice but what if proposal or order ?
  1941. $localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty);
  1942. $localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty);
  1943. $result = $object->addline(
  1944. $desc,
  1945. $lines[$i]->subprice,
  1946. $lines[$i]->qty,
  1947. $tva_tx,
  1948. $localtax1_tx,
  1949. $localtax2_tx,
  1950. $lines[$i]->fk_product,
  1951. $lines[$i]->remise_percent,
  1952. $date_start,
  1953. $date_end,
  1954. 0,
  1955. $lines[$i]->info_bits,
  1956. $lines[$i]->fk_remise_except,
  1957. 'HT',
  1958. 0,
  1959. $product_type,
  1960. $lines[$i]->rang,
  1961. $lines[$i]->special_code,
  1962. $object->origin,
  1963. $lines[$i]->rowid,
  1964. $fk_parent_line,
  1965. $lines[$i]->fk_fournprice,
  1966. $lines[$i]->pa_ht,
  1967. $label,
  1968. $array_options,
  1969. $lines[$i]->situation_percent,
  1970. $lines[$i]->fk_prev_id,
  1971. $lines[$i]->fk_unit,
  1972. 0,
  1973. '',
  1974. 1
  1975. );
  1976. if ($result > 0) {
  1977. $lineid = $result;
  1978. } else {
  1979. $lineid = 0;
  1980. $error++;
  1981. break;
  1982. }
  1983. // Defined the new fk_parent_line
  1984. if ($result > 0 && $lines[$i]->product_type == 9) {
  1985. $fk_parent_line = $result;
  1986. }
  1987. }
  1988. }
  1989. } else {
  1990. setEventMessages($srcobject->error, $srcobject->errors, 'errors');
  1991. $error++;
  1992. }
  1993. }
  1994. $object->update_price(1, 'auto', 0, $mysoc);
  1995. // Now we create same links to contact than the ones found on origin object
  1996. /* Useless, already into the create
  1997. if (!empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN))
  1998. {
  1999. $originforcontact = $object->origin;
  2000. $originidforcontact = $object->origin_id;
  2001. if ($originforcontact == 'shipping') // shipment and order share the same contacts. If creating from shipment we take data of order
  2002. {
  2003. $originforcontact=$srcobject->origin;
  2004. $originidforcontact=$srcobject->origin_id;
  2005. }
  2006. $sqlcontact = "SELECT code, fk_socpeople FROM ".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as ctc";
  2007. $sqlcontact.= " WHERE element_id = ".((int) $originidforcontact)." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$db->escape($originforcontact)."'";
  2008. $resqlcontact = $db->query($sqlcontact);
  2009. if ($resqlcontact)
  2010. {
  2011. while($objcontact = $db->fetch_object($resqlcontact))
  2012. {
  2013. //print $objcontact->code.'-'.$objcontact->fk_socpeople."\n";
  2014. $object->add_contact($objcontact->fk_socpeople, $objcontact->code);
  2015. }
  2016. }
  2017. else dol_print_error($resqlcontact);
  2018. }*/
  2019. // Hooks
  2020. $parameters = array('objFrom' => $srcobject);
  2021. $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been
  2022. // modified by hook
  2023. if ($reshook < 0) {
  2024. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  2025. $error++;
  2026. }
  2027. } else {
  2028. setEventMessages($object->error, $object->errors, 'errors');
  2029. $error++;
  2030. }
  2031. } else { // If some invoice's lines coming from page
  2032. $id = $object->create($user);
  2033. for ($i = 1; $i <= $NBLINES; $i++) {
  2034. if (GETPOST('idprod' . $i, 'int')) {
  2035. $product = new Product($db);
  2036. $product->fetch(GETPOST('idprod' . $i, 'int'));
  2037. $startday = dol_mktime(12, 0, 0, GETPOST('date_start' . $i . 'month'), GETPOST('date_start' . $i . 'day'), GETPOST('date_start' . $i . 'year'));
  2038. $endday = dol_mktime(12, 0, 0, GETPOST('date_end' . $i . 'month'), GETPOST('date_end' . $i . 'day'), GETPOST('date_end' . $i . 'year'));
  2039. $result = $object->addline($product->description, $product->price, price2num(GETPOST('qty' . $i), 'MS'), $product->tva_tx, $product->localtax1_tx, $product->localtax2_tx, GETPOST('idprod' . $i, 'int'), price2num(GETPOST('remise_percent' . $i), '', 2), $startday, $endday, 0, 0, '', $product->price_base_type, $product->price_ttc, $product->type, -1, 0, '', 0, 0, null, 0, '', 0, 100, '', $product->fk_unit, 0, '', 1);
  2040. }
  2041. }
  2042. $object->update_price(1, 'auto', 0, $mysoc);
  2043. }
  2044. }
  2045. }
  2046. // Situation invoices
  2047. if (GETPOST('type') == Facture::TYPE_SITUATION && GETPOST('situations')) {
  2048. if (empty($dateinvoice)) {
  2049. $error++;
  2050. $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date"));
  2051. setEventMessages($mesg, null, 'errors');
  2052. } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
  2053. $error++;
  2054. setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
  2055. $action = 'create';
  2056. }
  2057. if (!(GETPOST('situations', 'int') > 0)) {
  2058. $error++;
  2059. $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("InvoiceSituation"));
  2060. setEventMessages($mesg, null, 'errors');
  2061. $action = 'create';
  2062. }
  2063. if (!$error) {
  2064. $result = $object->fetch(GETPOST('situations', 'int'));
  2065. $object->fk_facture_source = GETPOST('situations', 'int');
  2066. $object->type = Facture::TYPE_SITUATION;
  2067. if (!empty($origin) && !empty($originid)) {
  2068. include_once DOL_DOCUMENT_ROOT . '/core/lib/price.lib.php';
  2069. $object->origin = $origin;
  2070. $object->origin_id = $originid;
  2071. // retained warranty
  2072. if (!empty($conf->global->INVOICE_USE_RETAINED_WARRANTY)) {
  2073. $retained_warranty = GETPOST('retained_warranty', 'int');
  2074. if (price2num($retained_warranty) > 0) {
  2075. $object->retained_warranty = price2num($retained_warranty);
  2076. }
  2077. if (GETPOST('retained_warranty_fk_cond_reglement', 'int') > 0) {
  2078. $object->retained_warranty_fk_cond_reglement = GETPOST('retained_warranty_fk_cond_reglement', 'int');
  2079. }
  2080. $retained_warranty_date_limit = GETPOST('retained_warranty_date_limit');
  2081. if (!empty($retained_warranty_date_limit) && $db->jdate($retained_warranty_date_limit)) {
  2082. $object->retained_warranty_date_limit = $db->jdate($retained_warranty_date_limit);
  2083. }
  2084. $object->retained_warranty_date_limit = !empty($object->retained_warranty_date_limit) ? $object->retained_warranty_date_limit : $object->calculate_date_lim_reglement($object->retained_warranty_fk_cond_reglement);
  2085. }
  2086. foreach ($object->lines as $i => &$line) {
  2087. $line->origin = $object->origin;
  2088. $line->origin_id = $line->id;
  2089. $line->fk_prev_id = $line->id;
  2090. $line->fetch_optionals();
  2091. $line->situation_percent = $line->get_prev_progress($object->id); // get good progress including credit note
  2092. // The $line->situation_percent has been modified, so we must recalculate all amounts
  2093. $tabprice = calcul_price_total($line->qty, $line->subprice, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 0, 'HT', 0, $line->product_type, $mysoc, '', $line->situation_percent);
  2094. $line->total_ht = $tabprice[0];
  2095. $line->total_tva = $tabprice[1];
  2096. $line->total_ttc = $tabprice[2];
  2097. $line->total_localtax1 = $tabprice[9];
  2098. $line->total_localtax2 = $tabprice[10];
  2099. $line->multicurrency_total_ht = $tabprice[16];
  2100. $line->multicurrency_total_tva = $tabprice[17];
  2101. $line->multicurrency_total_ttc = $tabprice[18];
  2102. // Si fk_remise_except defini on vérifie si la réduction à déjà été appliquée
  2103. if ($line->fk_remise_except) {
  2104. $discount = new DiscountAbsolute($line->db);
  2105. $result = $discount->fetch($line->fk_remise_except);
  2106. if ($result > 0) {
  2107. // Check if discount not already affected to another invoice
  2108. if ($discount->fk_facture_line > 0) {
  2109. $line->fk_remise_except = 0;
  2110. }
  2111. }
  2112. }
  2113. }
  2114. }
  2115. $object->fetch_thirdparty();
  2116. $object->date = $dateinvoice;
  2117. $object->date_pointoftax = $date_pointoftax;
  2118. $object->note_public = trim(GETPOST('note_public', 'restricthtml'));
  2119. $object->note = trim(GETPOST('note', 'restricthtml'));
  2120. $object->note_private = trim(GETPOST('note', 'restricthtml'));
  2121. $object->ref_client = GETPOST('ref_client', 'alpha');
  2122. $object->model_pdf = GETPOST('model', 'alpha');
  2123. $object->fk_project = GETPOST('projectid', 'int');
  2124. $object->cond_reglement_id = GETPOST('cond_reglement_id', 'int');
  2125. $object->mode_reglement_id = GETPOST('mode_reglement_id', 'int');
  2126. $object->remise_absolue = price2num(GETPOST('remise_absolue'), 'MU', 2);
  2127. $object->remise_percent = price2num(GETPOST('remise_percent'), '', 2);
  2128. // Proprietes particulieres a facture de remplacement
  2129. $object->situation_counter = $object->situation_counter + 1;
  2130. $id = $object->createFromCurrent($user);
  2131. if ($id <= 0) {
  2132. $mesg = $object->error;
  2133. } else {
  2134. $nextSituationInvoice = new Facture($db);
  2135. $nextSituationInvoice->fetch($id);
  2136. // create extrafields with data from create form
  2137. $extrafields->fetch_name_optionals_label($nextSituationInvoice->table_element);
  2138. $ret = $extrafields->setOptionalsFromPost(null, $nextSituationInvoice);
  2139. if ($ret > 0) {
  2140. $nextSituationInvoice->insertExtraFields();
  2141. }
  2142. }
  2143. }
  2144. }
  2145. #-------------------------------------------------------------------
  2146. # CUSTOMER CHANGE
  2147. #-------------------------------------------------------------------*/
  2148. if (GETPOST('type') == Facture::TYPE_CUSTOMERCHANGE) {
  2149. if ($object->array_options['options_commission_deduction']) {
  2150. $factureObj = new Facture($db);
  2151. $userinvoiceObj = new UserInvoice($db);
  2152. $commmissionhandler = new CommissionHandler();
  2153. $productObj = new Product($db);
  2154. $productObjHUF = new Product($db);
  2155. $fk_facture_resource = GETPOST('fac_avoir', 'int');
  2156. $result_source_facture = $factureObj->fetch($fk_facture_resource);
  2157. if ($factureObj->fk_multicurrency == 2) {
  2158. $fk_product = $factureObj->lines[0]->fk_product;
  2159. $assignedProduct = $productObj->fetch($fk_product);
  2160. $relatedService = $productObj->array_options['options_related_service'];
  2161. $productToCount = $productObjHUF->fetch($relatedService);
  2162. $price_ttc = $productObjHUF->price_ttc;
  2163. $commissionValue = $productObjHUF->array_options['options_commission_value'];
  2164. $type = $productObjHUF->array_options['options_commission_type'] == 1 ? '%' : 'Forint';
  2165. $row['total_ttc'] = $price_ttc;
  2166. $row['commission'] = $commissionValue . '_' . $type;
  2167. ;
  2168. $amount = $commmissionhandler->getAmountOfCommission($row);
  2169. } else {
  2170. $row['total_ttc'] = $factureObj->total_ttc;
  2171. $row['commission'] = $factureObj->array_options['options_commission'];
  2172. $amount = $commmissionhandler->getAmountOfCommission($row);
  2173. }
  2174. $resultUserinvoiceObj = $userinvoiceObj->fetchAll('', '', 0, 0, ["customsql" => "invoices LIKE '%{$factureObj->id}%'"]);
  2175. $usersArray = [];
  2176. foreach ($resultUserinvoiceObj as $userObj) {
  2177. $usersArray[] = $userObj->user_id;
  2178. }
  2179. $numberOfUsers = count($usersArray);
  2180. if ($numberOfUsers > 0) {
  2181. $amountOfOneUser = $amount / $numberOfUsers;
  2182. foreach ($usersArray as $userid) {
  2183. if ($amountOfOneUser > 0) {
  2184. $userinvoiceObj2 = new UserInvoice($db);
  2185. $userinvoiceObj2->ref = 'Withhold_' . dol_now() . '_' . rand(1000000, 9999999);
  2186. ;
  2187. $userinvoiceObj2->label = 'Visszatartás/Withholding ' . date('Y.m.d');
  2188. $userinvoiceObj2->description = 'Összeg / Amount: ' . $amountOfOneUser . ' HUF. Commission deduction.(Customer Change)';
  2189. $userinvoiceObj2->user_id = $userid;
  2190. $userinvoiceObj2->payment_type = 1;
  2191. $userinvoiceObj2->amount = $amountOfOneUser;
  2192. $userinvoiceObj2->currency = 0;
  2193. $userinvoiceObj2->individual = 1;
  2194. $userinvoiceObj2->invoices = $factureObj->id;
  2195. $result = $userinvoiceObj2->create($user);
  2196. if ($result < 0) {
  2197. $error++;
  2198. }
  2199. }
  2200. }
  2201. } else {
  2202. if ($amount > 0) {
  2203. $userinvoiceObj2 = new UserInvoice($db);
  2204. $userinvoiceObj2->ref = 'Withhold_' . dol_now() . '_' . rand(1000000, 9999999);
  2205. ;
  2206. $userinvoiceObj2->label = 'Visszatartás/Withholding ' . date('Y.m.d');
  2207. $userinvoiceObj2->description = 'Összeg / Amount: ' . $amount . ' HUF. Commission deduction.(Customer Change)';
  2208. $userinvoiceObj2->user_id = $factureObj->fk_user_valid;
  2209. $userinvoiceObj2->payment_type = 1;
  2210. $userinvoiceObj2->amount = $amount;
  2211. $userinvoiceObj2->currency = 0;
  2212. $userinvoiceObj2->individual = 1;
  2213. $userinvoiceObj2->invoices = $factureObj->id;
  2214. $result = $userinvoiceObj2->create($user);
  2215. if ($result < 0) {
  2216. $error++;
  2217. }
  2218. }
  2219. }
  2220. }
  2221. $sourceinvoice = GETPOST('fac_avoir', 'int');
  2222. if (!($sourceinvoice > 0) && empty($conf->global->INVOICE_CREDIT_NOTE_STANDALONE)) {
  2223. $error++;
  2224. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CorrectInvoice")), null, 'errors');
  2225. $action = 'create';
  2226. }
  2227. if (empty($dateinvoice)) {
  2228. $error++;
  2229. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
  2230. $action = 'create';
  2231. } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
  2232. $error++;
  2233. setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
  2234. $action = 'create';
  2235. }
  2236. #-------------------------------------------------------------------
  2237. # CREATE CREDIT NOTE INVOICE BEFORE NEW CUSTOMER'S STANDARD INVOICE
  2238. #-------------------------------------------------------------------
  2239. $factureObj = new Facture($db);
  2240. $factureObj->fetch(GETPOST('fac_avoir'));
  2241. if ($factureObj->type == 0) {
  2242. $CreditNoteType = Facture::TYPE_CREDIT_NOTE;
  2243. }
  2244. if ($factureObj->type == 7) {
  2245. $CreditNoteType = Facture::TYPE_RECEIPT_CREDIT_NOTE;
  2246. }
  2247. //print_r($object);
  2248. if (!$error) {
  2249. if (!empty($originentity)) {
  2250. $object->entity = $originentity;
  2251. }
  2252. //$object->socid = GETPOST('socid', 'int');
  2253. $object->ref = GETPOST('ref');
  2254. $object->date = $dateinvoice;
  2255. $object->date_pointoftax = $date_pointoftax;
  2256. $object->note_public = trim(GETPOST('note_public', 'restricthtml'));
  2257. $object->note_private = trim(GETPOST('note_private', 'restricthtml'));
  2258. $object->ref_client = GETPOST('ref_client');
  2259. $object->model_pdf = GETPOST('model');
  2260. $object->fk_project = GETPOST('projectid', 'int');
  2261. $object->cond_reglement_id = 0; // No payment term for a credit note
  2262. $object->mode_reglement_id = GETPOST('mode_reglement_id', 'int');
  2263. $object->fk_account = GETPOST('fk_account', 'int');
  2264. $object->remise_absolue = price2num(GETPOST('remise_absolue'), 'MU');
  2265. $object->remise_percent = price2num(GETPOST('remise_percent'), '', 2);
  2266. $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  2267. $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  2268. $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  2269. $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
  2270. // Proprietes particulieres a facture avoir
  2271. $object->fk_facture_source = $sourceinvoice > 0 ? $sourceinvoice : '';
  2272. $object->type = $CreditNoteType;
  2273. $facture_source = new Facture($db); // fetch origin object
  2274. if ($facture_source->fetch($object->fk_facture_source) > 0) {
  2275. if ($facture_source->type == Facture::TYPE_SITUATION) {
  2276. $object->situation_counter = $facture_source->situation_counter;
  2277. $object->situation_cycle_ref = $facture_source->situation_cycle_ref;
  2278. $facture_source->fetchPreviousNextSituationInvoice();
  2279. }
  2280. }
  2281. // We have to add the facture_source socid to the credit note invoice fk_socid
  2282. $object->socid = $facture_source->socid;
  2283. $id = $object->create($user);
  2284. if ($id < 0) {
  2285. $error++;
  2286. } else {
  2287. // copy internal contacts
  2288. if ($object->copy_linked_contact($facture_source, 'internal') < 0) {
  2289. $error++;
  2290. } elseif ($facture_source->socid == $object->socid) {
  2291. // copy external contacts if same company
  2292. if ($object->copy_linked_contact($facture_source, 'external') < 0) {
  2293. $error++;
  2294. }
  2295. }
  2296. }
  2297. // NOTE: Pb with situation invoice
  2298. // NOTE: fields total on situation invoice are stored as cumulative values on total of lines (bad) but delta on invoice total
  2299. // NOTE: fields total on credit note are stored as delta both on total of lines and on invoice total (good)
  2300. // NOTE: fields situation_percent on situation invoice are stored as cumulative values on lines (bad)
  2301. // NOTE: fields situation_percent on credit note are stored as delta on lines (good)
  2302. if (($factureObj->type == 0 || $factureObj->type == 7) && $id > 0) {
  2303. if (!empty($facture_source->lines)) {
  2304. $fk_parent_line = 0;
  2305. foreach ($facture_source->lines as $line) {
  2306. // Extrafields
  2307. if (method_exists($line, 'fetch_optionals')) {
  2308. // load extrafields
  2309. $line->fetch_optionals();
  2310. }
  2311. // Reset fk_parent_line for no child products and special product
  2312. if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
  2313. $fk_parent_line = 0;
  2314. }
  2315. if ($facture_source->type == Facture::TYPE_SITUATION) {
  2316. $source_fk_prev_id = $line->fk_prev_id; // temporary storing situation invoice fk_prev_id
  2317. $line->fk_prev_id = $line->id; // The new line of the new credit note we are creating must be linked to the situation invoice line it is created from
  2318. if (!empty($facture_source->tab_previous_situation_invoice)) {
  2319. // search the last standard invoice in cycle and the possible credit note between this last and facture_source
  2320. // TODO Move this out of loop of $facture_source->lines
  2321. $tab_jumped_credit_notes = array();
  2322. $lineIndex = count($facture_source->tab_previous_situation_invoice) - 1;
  2323. $searchPreviousInvoice = true;
  2324. while ($searchPreviousInvoice) {
  2325. if ($facture_source->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_SITUATION || $lineIndex < 1) {
  2326. $searchPreviousInvoice = false; // find, exit;
  2327. break;
  2328. } else {
  2329. if ($facture_source->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_CREDIT_NOTE) {
  2330. $tab_jumped_credit_notes[$lineIndex] = $facture_source->tab_previous_situation_invoice[$lineIndex]->id;
  2331. }
  2332. $lineIndex--; // go to previous invoice in cycle
  2333. }
  2334. }
  2335. $maxPrevSituationPercent = 0;
  2336. foreach ($facture_source->tab_previous_situation_invoice[$lineIndex]->lines as $prevLine) {
  2337. if ($prevLine->id == $source_fk_prev_id) {
  2338. $maxPrevSituationPercent = max($maxPrevSituationPercent, $prevLine->situation_percent);
  2339. //$line->subprice = $line->subprice - $prevLine->subprice;
  2340. $line->total_ht = $line->total_ht - $prevLine->total_ht;
  2341. $line->total_tva = $line->total_tva - $prevLine->total_tva;
  2342. $line->total_ttc = $line->total_ttc - $prevLine->total_ttc;
  2343. $line->total_localtax1 = $line->total_localtax1 - $prevLine->total_localtax1;
  2344. $line->total_localtax2 = $line->total_localtax2 - $prevLine->total_localtax2;
  2345. $line->multicurrency_subprice = $line->multicurrency_subprice - $prevLine->multicurrency_subprice;
  2346. $line->multicurrency_total_ht = $line->multicurrency_total_ht - $prevLine->multicurrency_total_ht;
  2347. $line->multicurrency_total_tva = $line->multicurrency_total_tva - $prevLine->multicurrency_total_tva;
  2348. $line->multicurrency_total_ttc = $line->multicurrency_total_ttc - $prevLine->multicurrency_total_ttc;
  2349. }
  2350. }
  2351. // prorata
  2352. $line->situation_percent = $maxPrevSituationPercent - $line->situation_percent;
  2353. //print 'New line based on invoice id '.$facture_source->tab_previous_situation_invoice[$lineIndex]->id.' fk_prev_id='.$source_fk_prev_id.' will be fk_prev_id='.$line->fk_prev_id.' '.$line->total_ht.' '.$line->situation_percent.'<br>';
  2354. // If there is some credit note between last situation invoice and invoice used for credit note generation (note: credit notes are stored as delta)
  2355. $maxPrevSituationPercent = 0;
  2356. foreach ($tab_jumped_credit_notes as $index => $creditnoteid) {
  2357. foreach ($facture_source->tab_previous_situation_invoice[$index]->lines as $prevLine) {
  2358. if ($prevLine->fk_prev_id == $source_fk_prev_id) {
  2359. $maxPrevSituationPercent = $prevLine->situation_percent;
  2360. $line->total_ht -= $prevLine->total_ht;
  2361. $line->total_tva -= $prevLine->total_tva;
  2362. $line->total_ttc -= $prevLine->total_ttc;
  2363. $line->total_localtax1 -= $prevLine->total_localtax1;
  2364. $line->total_localtax2 -= $prevLine->total_localtax2;
  2365. $line->multicurrency_subprice -= $prevLine->multicurrency_subprice;
  2366. $line->multicurrency_total_ht -= $prevLine->multicurrency_total_ht;
  2367. $line->multicurrency_total_tva -= $prevLine->multicurrency_total_tva;
  2368. $line->multicurrency_total_ttc -= $prevLine->multicurrency_total_ttc;
  2369. }
  2370. }
  2371. }
  2372. // prorata
  2373. $line->situation_percent += $maxPrevSituationPercent;
  2374. //print 'New line based on invoice id '.$facture_source->tab_previous_situation_invoice[$lineIndex]->id.' fk_prev_id='.$source_fk_prev_id.' will be fk_prev_id='.$line->fk_prev_id.' '.$line->total_ht.' '.$line->situation_percent.'<br>';
  2375. }
  2376. }
  2377. $line->fk_facture = $object->id;
  2378. $line->fk_parent_line = $fk_parent_line;
  2379. $line->subprice = -$line->subprice; // invert price for object
  2380. $line->pa_ht = $line->pa_ht; // we choosed to have buy/cost price always positive, so no revert of sign here
  2381. $line->total_ht = -$line->total_ht;
  2382. $line->total_tva = -$line->total_tva;
  2383. $line->total_ttc = -$line->total_ttc;
  2384. $line->total_localtax1 = -$line->total_localtax1;
  2385. $line->total_localtax2 = -$line->total_localtax2;
  2386. $line->multicurrency_subprice = -$line->multicurrency_subprice;
  2387. $line->multicurrency_total_ht = -$line->multicurrency_total_ht;
  2388. $line->multicurrency_total_tva = -$line->multicurrency_total_tva;
  2389. $line->multicurrency_total_ttc = -$line->multicurrency_total_ttc;
  2390. $line->context['createcustomernamefrominvoice'] = 1;
  2391. $result = $line->insert(0, 1); // When creating credit note with same lines than source, we must ignore error if discount alreayd linked
  2392. $object->lines[] = $line; // insert new line in current object
  2393. // Defined the new fk_parent_line
  2394. if ($result > 0 && $line->product_type == 9) {
  2395. $fk_parent_line = $result;
  2396. }
  2397. }
  2398. $object->update_price(1);
  2399. }
  2400. }
  2401. if (GETPOST('invoiceAvoirWithPaymentRestAmount', 'int') == 1 && $id > 0) {
  2402. if ($facture_source->fetch($object->fk_facture_source) > 0) {
  2403. $totalpaid = $facture_source->getSommePaiement();
  2404. $totalcreditnotes = $facture_source->getSumCreditNotesUsed();
  2405. $totaldeposits = $facture_source->getSumDepositsUsed();
  2406. $remain_to_pay = abs($facture_source->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits);
  2407. $object->addline($langs->trans('invoiceAvoirLineWithPaymentRestAmount'), $remain_to_pay, 1, 0, 0, 0, 0, 0, '', '', 'TTC');
  2408. }
  2409. }
  2410. // Add link between credit note and origin
  2411. if (!empty($object->fk_facture_source) && $id > 0) {
  2412. $facture_source->fetch($object->fk_facture_source);
  2413. $facture_source->fetchObjectLinked();
  2414. if (!empty($facture_source->linkedObjectsIds)) {
  2415. foreach ($facture_source->linkedObjectsIds as $sourcetype => $TIds) {
  2416. $object->add_object_linked($sourcetype, current($TIds));
  2417. }
  2418. }
  2419. }
  2420. }
  2421. #-------------------------------------------------------------------
  2422. # VALIDATE CREDITNOTE
  2423. #-------------------------------------------------------------------
  2424. $object->fetch($id);
  2425. $object->fetch_thirdparty();
  2426. $result = $object->validate($user, '', $idwarehouse);
  2427. #-------------------------------------------------------------------
  2428. # CREATE NEW CUSTOMER'S INVOICE AFTER CREDIT NOTE INVOICE
  2429. #-------------------------------------------------------------------
  2430. // Need to set empty the lines, because the array containes the minus lines from the credit note invoice
  2431. $object->lines = [];
  2432. if (!$error) {
  2433. if (GETPOST('invoiceAvoirWithLinesCustomerChange') == 0) {
  2434. $FactureType = Facture::TYPE_STANDARD;
  2435. }
  2436. if (GETPOST('invoiceAvoirWithLinesReceiptCustomerChange') == 7) {
  2437. $FactureType = Facture::TYPE_RECEIPT;
  2438. }
  2439. if (!empty($originentity)) {
  2440. $object->entity = $originentity;
  2441. }
  2442. $object->socid = GETPOST('socid', 'int');
  2443. $object->ref = GETPOST('ref');
  2444. $object->date = $dateinvoice;
  2445. $object->date_pointoftax = $date_pointoftax;
  2446. $object->note_public = trim(GETPOST('note_public', 'restricthtml'));
  2447. $object->note_private = trim(GETPOST('note_private', 'restricthtml'));
  2448. $object->ref_client = GETPOST('ref_client');
  2449. $object->model_pdf = GETPOST('model');
  2450. $object->fk_project = GETPOST('projectid', 'int');
  2451. $object->cond_reglement_id = 0; // No payment term for a credit note
  2452. $object->mode_reglement_id = GETPOST('mode_reglement_id', 'int');
  2453. $object->fk_account = GETPOST('fk_account', 'int');
  2454. $object->remise_absolue = price2num(GETPOST('remise_absolue'), 'MU');
  2455. $object->remise_percent = price2num(GETPOST('remise_percent'), '', 2);
  2456. $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  2457. $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  2458. $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  2459. $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
  2460. // Proprietes particulieres a facture avoir
  2461. $object->fk_facture_source = $sourceinvoice > 0 ? $sourceinvoice : '';
  2462. $object->type = $FactureType;
  2463. $facture_source = new Facture($db); // fetch origin object
  2464. if ($facture_source->fetch($object->fk_facture_source) > 0) {
  2465. if ($facture_source->type == Facture::TYPE_SITUATION) {
  2466. $object->situation_counter = $facture_source->situation_counter;
  2467. $object->situation_cycle_ref = $facture_source->situation_cycle_ref;
  2468. $facture_source->fetchPreviousNextSituationInvoice();
  2469. }
  2470. }
  2471. $id = $object->create($user);
  2472. if ($id < 0) {
  2473. $error++;
  2474. } else {
  2475. // copy internal contacts
  2476. if ($object->copy_linked_contact($facture_source, 'internal') < 0) {
  2477. $error++;
  2478. } elseif ($facture_source->socid == $object->socid) {
  2479. // copy external contacts if same company
  2480. if ($object->copy_linked_contact($facture_source, 'external') < 0) {
  2481. $error++;
  2482. }
  2483. }
  2484. }
  2485. //print GETPOST('invoiceAvoirWithLinesCustomerChange', 'int');exit;
  2486. // NOTE: Pb with situation invoice
  2487. // NOTE: fields total on situation invoice are stored as cumulative values on total of lines (bad) but delta on invoice total
  2488. // NOTE: fields total on credit note are stored as delta both on total of lines and on invoice total (good)
  2489. // NOTE: fields situation_percent on situation invoice are stored as cumulative values on lines (bad)
  2490. // NOTE: fields situation_percent on credit note are stored as delta on lines (good)
  2491. if (($factureObj->type == 0 || $factureObj->type == 7) && $id > 0) {
  2492. if (!empty($facture_source->lines)) {
  2493. $fk_parent_line = 0;
  2494. foreach ($facture_source->lines as $line) {
  2495. // Extrafields
  2496. if (method_exists($line, 'fetch_optionals')) {
  2497. // load extrafields
  2498. $line->fetch_optionals();
  2499. }
  2500. // Reset fk_parent_line for no child products and special product
  2501. if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
  2502. $fk_parent_line = 0;
  2503. }
  2504. if ($facture_source->type == Facture::TYPE_SITUATION) {
  2505. $source_fk_prev_id = $line->fk_prev_id; // temporary storing situation invoice fk_prev_id
  2506. $line->fk_prev_id = $line->id; // The new line of the new credit note we are creating must be linked to the situation invoice line it is created from
  2507. if (!empty($facture_source->tab_previous_situation_invoice)) {
  2508. // search the last standard invoice in cycle and the possible credit note between this last and facture_source
  2509. // TODO Move this out of loop of $facture_source->lines
  2510. $tab_jumped_credit_notes = array();
  2511. $lineIndex = count($facture_source->tab_previous_situation_invoice) - 1;
  2512. $searchPreviousInvoice = true;
  2513. while ($searchPreviousInvoice) {
  2514. if ($facture_source->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_SITUATION || $lineIndex < 1) {
  2515. $searchPreviousInvoice = false; // find, exit;
  2516. break;
  2517. } else {
  2518. if ($facture_source->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_CREDIT_NOTE) {
  2519. $tab_jumped_credit_notes[$lineIndex] = $facture_source->tab_previous_situation_invoice[$lineIndex]->id;
  2520. }
  2521. $lineIndex--; // go to previous invoice in cycle
  2522. }
  2523. }
  2524. $maxPrevSituationPercent = 0;
  2525. foreach ($facture_source->tab_previous_situation_invoice[$lineIndex]->lines as $prevLine) {
  2526. if ($prevLine->id == $source_fk_prev_id) {
  2527. $maxPrevSituationPercent = max($maxPrevSituationPercent, $prevLine->situation_percent);
  2528. }
  2529. }
  2530. // prorata
  2531. $line->situation_percent = $maxPrevSituationPercent - $line->situation_percent;
  2532. //print 'New line based on invoice id '.$facture_source->tab_previous_situation_invoice[$lineIndex]->id.' fk_prev_id='.$source_fk_prev_id.' will be fk_prev_id='.$line->fk_prev_id.' '.$line->total_ht.' '.$line->situation_percent.'<br>';
  2533. // If there is some credit note between last situation invoice and invoice used for credit note generation (note: credit notes are stored as delta)
  2534. $maxPrevSituationPercent = 0;
  2535. foreach ($tab_jumped_credit_notes as $index => $creditnoteid) {
  2536. foreach ($facture_source->tab_previous_situation_invoice[$index]->lines as $prevLine) {
  2537. if ($prevLine->fk_prev_id == $source_fk_prev_id) {
  2538. $maxPrevSituationPercent = $prevLine->situation_percent;
  2539. }
  2540. }
  2541. }
  2542. // prorata
  2543. $line->situation_percent += $maxPrevSituationPercent;
  2544. //print 'New line based on invoice id '.$facture_source->tab_previous_situation_invoice[$lineIndex]->id.' fk_prev_id='.$source_fk_prev_id.' will be fk_prev_id='.$line->fk_prev_id.' '.$line->total_ht.' '.$line->situation_percent.'<br>';
  2545. }
  2546. }
  2547. $line->fk_facture = $object->id;
  2548. $line->fk_parent_line = $fk_parent_line;
  2549. //$line->subprice = -$line->subprice; // invert price for object
  2550. $line->pa_ht = $line->pa_ht; // we choosed to have buy/cost price always positive, so no revert of sign here
  2551. $line->context['createcreditnotefrominvoice'] = 1;
  2552. $result = $line->insert(0, 1); // When creating credit note with same lines than source, we must ignore error if discount alreayd linked
  2553. $object->lines[] = $line; // insert new line in current object
  2554. // Defined the new fk_parent_line
  2555. if ($result > 0 && $line->product_type == 9) {
  2556. $fk_parent_line = $result;
  2557. }
  2558. }
  2559. $object->update_price(1);
  2560. }
  2561. }
  2562. // Add link between credit note and origin
  2563. if (!empty($object->fk_facture_source) && $id > 0) {
  2564. $facture_source->fetch($object->fk_facture_source);
  2565. $facture_source->fetchObjectLinked();
  2566. if (!empty($facture_source->linkedObjectsIds)) {
  2567. foreach ($facture_source->linkedObjectsIds as $sourcetype => $TIds) {
  2568. $object->add_object_linked($sourcetype, current($TIds));
  2569. }
  2570. }
  2571. }
  2572. }
  2573. }
  2574. #-------------------------------------------------------------------
  2575. # Commission deduction (add Withholding)
  2576. #-------------------------------------------------------------------
  2577. // End of object creation, we show it
  2578. if ($id > 0 && !$error) {
  2579. $db->commit();
  2580. // Define output language
  2581. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE) && count($object->lines)) {
  2582. $outputlangs = $langs;
  2583. $newlang = '';
  2584. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  2585. $newlang = GETPOST('lang_id', 'aZ09');
  2586. }
  2587. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
  2588. $newlang = $object->thirdparty->default_lang;
  2589. }
  2590. if (!empty($newlang)) {
  2591. $outputlangs = new Translate("", $conf);
  2592. $outputlangs->setDefaultLang($newlang);
  2593. $outputlangs->load('products');
  2594. }
  2595. $model = $object->model_pdf;
  2596. $ret = $object->fetch($id); // Reload to get new records
  2597. $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  2598. if ($result < 0) {
  2599. setEventMessages($object->error, $object->errors, 'errors');
  2600. }
  2601. }
  2602. header('Location: ' . $_SERVER["PHP_SELF"] . '?facid=' . $id);
  2603. exit();
  2604. } else {
  2605. $db->rollback();
  2606. $action = 'create';
  2607. $_GET["origin"] = $_POST["origin"];
  2608. $_GET["originid"] = $_POST["originid"];
  2609. setEventMessages($object->error, $object->errors, 'errors');
  2610. }
  2611. } elseif ($action == 'addline' && GETPOST('submitforalllines', 'alpha') && GETPOST('vatforalllines', 'alpha') !== '') {
  2612. // Define vat_rate
  2613. $vat_rate = (GETPOST('vatforalllines') ? GETPOST('vatforalllines') : 0);
  2614. $vat_rate = str_replace('*', '', $vat_rate);
  2615. $localtax1_rate = get_localtax($vat_rate, 1, $object->thirdparty, $mysoc);
  2616. $localtax2_rate = get_localtax($vat_rate, 2, $object->thirdparty, $mysoc);
  2617. foreach ($object->lines as $line) {
  2618. $result = $object->updateline($line->id, $line->desc, $line->subprice, $line->qty, $line->remise_percent, $line->date_start, $line->date_end, $vat_rate, $localtax1_rate, $localtax2_rate, 'HT', $line->info_bits, $line->product_type, $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit, $line->multicurrency_subprice);
  2619. }
  2620. } elseif ($action == 'addline' && GETPOST('submitforalllines', 'alpha') && GETPOST('remiseforalllines', 'alpha') !== '' && $usercancreate) {
  2621. // Define vat_rate
  2622. $remise_percent = (GETPOST('remiseforalllines') ? GETPOST('remiseforalllines') : 0);
  2623. $remise_percent = str_replace('*', '', $remise_percent);
  2624. foreach ($object->lines as $line) {
  2625. $result = $object->updateline($line->id, $line->desc, $line->subprice, $line->qty, $remise_percent, $line->date_start, $line->date_end, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->product_type, $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit, $line->multicurrency_subprice);
  2626. }
  2627. } elseif ($action == 'addline' && $usercancreate) { // Add a new line
  2628. $langs->load('errors');
  2629. $error = 0;
  2630. // Set if we used free entry or predefined product
  2631. $predef = '';
  2632. $product_desc = (GETPOSTISSET('dp_desc') ? GETPOST('dp_desc', 'restricthtml') : '');
  2633. $price_ht = '';
  2634. $price_ht_devise = '';
  2635. $price_ttc = '';
  2636. $price_ttc_devise = '';
  2637. if (GETPOST('price_ht') !== '') {
  2638. $price_ht = price2num(GETPOST('price_ht'), 'MU', 2);
  2639. }
  2640. if (GETPOST('multicurrency_price_ht') !== '') {
  2641. $price_ht_devise = price2num(GETPOST('multicurrency_price_ht'), 'CU', 2);
  2642. }
  2643. if (GETPOST('price_ttc') !== '') {
  2644. $price_ttc = price2num(GETPOST('price_ttc'), 'MU', 2);
  2645. }
  2646. if (GETPOST('multicurrency_price_ttc') !== '') {
  2647. $price_ttc_devise = price2num(GETPOST('multicurrency_price_ttc'), 'CU', 2);
  2648. }
  2649. $prod_entry_mode = GETPOST('prod_entry_mode', 'aZ09');
  2650. if ($prod_entry_mode == 'free') {
  2651. $idprod = 0;
  2652. $tva_tx = (GETPOSTISSET('tva_tx') ? GETPOST('tva_tx', 'alpha') : 0);
  2653. } else {
  2654. $idprod = GETPOST('idprod', 'int');
  2655. $tva_tx = '';
  2656. }
  2657. $qty = price2num(GETPOST('qty' . $predef, 'alpha'), 'MS', 2);
  2658. $remise_percent = (GETPOSTISSET('remise_percent' . $predef) ? price2num(GETPOST('remise_percent' . $predef, 'alpha'), '', 2) : 0);
  2659. if (empty($remise_percent)) {
  2660. $remise_percent = 0;
  2661. }
  2662. // Extrafields
  2663. $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
  2664. $array_options = $extrafields->getOptionalsFromPost($object->table_element_line, $predef);
  2665. // Unset extrafield
  2666. if (is_array($extralabelsline)) {
  2667. // Get extra fields
  2668. foreach ($extralabelsline as $key => $value) {
  2669. unset($_POST["options_" . $key . $predef]);
  2670. }
  2671. }
  2672. if ((empty($idprod) || $idprod < 0) && ($price_ht < 0) && ($qty < 0)) {
  2673. setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPriceHT'), $langs->transnoentitiesnoconv('Qty')), null, 'errors');
  2674. $error++;
  2675. }
  2676. if (!$prod_entry_mode) {
  2677. if (GETPOST('type') < 0 && !GETPOST('search_idprod')) {
  2678. setEventMessages($langs->trans('ErrorChooseBetweenFreeEntryOrPredefinedProduct'), null, 'errors');
  2679. $error++;
  2680. }
  2681. }
  2682. if ($prod_entry_mode == 'free' && (empty($idprod) || $idprod < 0) && GETPOST('type') < 0) {
  2683. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors');
  2684. $error++;
  2685. }
  2686. if (($prod_entry_mode == 'free' && (empty($idprod) || $idprod < 0) && (($price_ht < 0 && empty($conf->global->FACTURE_ENABLE_NEGATIVE_LINES)) || $price_ht == '') && $price_ht_devise == '') && $object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_RECEIPT_CREDIT_NOTE) { // Unit price can be 0 but not ''
  2687. if (($price_ht < 0 || $price_ttc < 0) && empty($conf->global->FACTURE_ENABLE_NEGATIVE_LINES)) {
  2688. $langs->load("errors");
  2689. if ($object->type == $object::TYPE_DEPOSIT) {
  2690. // Using negative lines on deposit lead to headach and blocking problems when you want to consume them.
  2691. setEventMessages($langs->trans("ErrorLinesCantBeNegativeOnDeposits"), null, 'errors');
  2692. } else {
  2693. setEventMessages($langs->trans("ErrorFieldCantBeNegativeOnInvoice", $langs->transnoentitiesnoconv("UnitPriceHT"), $langs->transnoentitiesnoconv("CustomerAbsoluteDiscountShort")), null, 'errors');
  2694. }
  2695. $error++;
  2696. } else {
  2697. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("UnitPriceHT")), null, 'errors');
  2698. $error++;
  2699. }
  2700. }
  2701. if ($qty == '') {
  2702. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors');
  2703. $error++;
  2704. }
  2705. if ($prod_entry_mode == 'free' && empty($idprod) && empty($product_desc)) {
  2706. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors');
  2707. $error++;
  2708. }
  2709. if ($qty < 0) {
  2710. $langs->load("errors");
  2711. setEventMessages($langs->trans('ErrorQtyForCustomerInvoiceCantBeNegative'), null, 'errors');
  2712. $error++;
  2713. }
  2714. if (!$error && isModEnabled('variants') && $prod_entry_mode != 'free') {
  2715. if ($combinations = GETPOST('combinations', 'array')) {
  2716. //Check if there is a product with the given combination
  2717. $prodcomb = new ProductCombination($db);
  2718. if ($res = $prodcomb->fetchByProductCombination2ValuePairs($idprod, $combinations)) {
  2719. $idprod = $res->fk_product_child;
  2720. } else {
  2721. setEventMessages($langs->trans('ErrorProductCombinationNotFound'), null, 'errors');
  2722. $error++;
  2723. }
  2724. }
  2725. }
  2726. if (!$error && ($qty >= 0) && (!empty($product_desc) || (!empty($idprod) && $idprod > 0))) {
  2727. $ret = $object->fetch($id);
  2728. if ($ret < 0) {
  2729. dol_print_error($db, $object->error);
  2730. exit();
  2731. }
  2732. $ret = $object->fetch_thirdparty();
  2733. // Clean parameters
  2734. $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'));
  2735. $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'));
  2736. $price_base_type = (GETPOST('price_base_type', 'alpha') ? GETPOST('price_base_type', 'alpha') : 'HT');
  2737. // Define special_code for special lines
  2738. $special_code = 0;
  2739. // if (!GETPOST(qty)) $special_code=3; // Options should not exists on invoices
  2740. // Ecrase $pu par celui du produit
  2741. // Ecrase $desc par celui du produit
  2742. // Ecrase $tva_tx par celui du produit
  2743. // Ecrase $base_price_type par celui du produit
  2744. // Replaces $fk_unit with the product's
  2745. if (!empty($idprod) && $idprod > 0) {
  2746. $prod = new Product($db);
  2747. $prod->fetch($idprod);
  2748. $label = ((GETPOST('product_label') && GETPOST('product_label') != $prod->label) ? GETPOST('product_label') : '');
  2749. // Search the correct price into loaded array product_price_by_qty using id of array retrieved into POST['pqp'].
  2750. $pqp = (GETPOST('pbq', 'int') ? GETPOST('pbq', 'int') : 0);
  2751. $datapriceofproduct = $prod->getSellPrice($mysoc, $object->thirdparty, $pqp);
  2752. $pu_ht = $datapriceofproduct['pu_ht'];
  2753. $pu_ttc = $datapriceofproduct['pu_ttc'];
  2754. $price_min = $datapriceofproduct['price_min'];
  2755. $price_min_ttc = (isset($datapriceofproduct['price_min_ttc'])) ? $datapriceofproduct['price_min_ttc'] : null;
  2756. $price_base_type = $datapriceofproduct['price_base_type'];
  2757. $tva_tx = $datapriceofproduct['tva_tx'];
  2758. $tva_npr = $datapriceofproduct['tva_npr'];
  2759. $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $tva_tx));
  2760. $tmpprodvat = price2num(preg_replace('/\s*\(.*\)/', '', $prod->tva_tx));
  2761. // Set unit price to use
  2762. if (!empty($price_ht) || $price_ht === '0') {
  2763. $pu_ht = price2num($price_ht, 'MU');
  2764. $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU');
  2765. } elseif (!empty($price_ttc) || $price_ttc === '0') {
  2766. $pu_ttc = price2num($price_ttc, 'MU');
  2767. $pu_ht = price2num($pu_ttc / (1 + ($tmpvat / 100)), 'MU');
  2768. } elseif ($tmpvat != $tmpprodvat) {
  2769. // Is this still used ?
  2770. if ($price_base_type != 'HT') {
  2771. $pu_ht = price2num($pu_ttc / (1 + ($tmpvat / 100)), 'MU');
  2772. } else {
  2773. $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU');
  2774. }
  2775. }
  2776. $desc = '';
  2777. // Define output language
  2778. if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
  2779. $outputlangs = $langs;
  2780. $newlang = '';
  2781. if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  2782. $newlang = GETPOST('lang_id', 'aZ09');
  2783. }
  2784. if (empty($newlang)) {
  2785. $newlang = $object->thirdparty->default_lang;
  2786. }
  2787. if (!empty($newlang)) {
  2788. $outputlangs = new Translate("", $conf);
  2789. $outputlangs->setDefaultLang($newlang);
  2790. $outputlangs->load('products');
  2791. }
  2792. $desc = (!empty($prod->multilangs[$outputlangs->defaultlang]["description"])) ? $prod->multilangs[$outputlangs->defaultlang]["description"] : $prod->description;
  2793. } else {
  2794. $desc = $prod->description;
  2795. }
  2796. //If text set in desc is the same as product descpription (as now it's preloaded) whe add it only one time
  2797. if ($product_desc == $desc && !empty($conf->global->PRODUIT_AUTOFILL_DESC)) {
  2798. $product_desc = '';
  2799. }
  2800. if (!empty($product_desc) && !empty($conf->global->MAIN_NO_CONCAT_DESCRIPTION)) {
  2801. $desc = $product_desc;
  2802. } else {
  2803. $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION));
  2804. }
  2805. // Add custom code and origin country into description
  2806. if (empty($conf->global->MAIN_PRODUCT_DISABLE_CUSTOMCOUNTRYCODE) && (!empty($prod->customcode) || !empty($prod->country_code))) {
  2807. $tmptxt = '(';
  2808. // Define output language
  2809. if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
  2810. $outputlangs = $langs;
  2811. $newlang = '';
  2812. if (empty($newlang) && GETPOST('lang_id', 'alpha')) {
  2813. $newlang = GETPOST('lang_id', 'alpha');
  2814. }
  2815. if (empty($newlang)) {
  2816. $newlang = $object->thirdparty->default_lang;
  2817. }
  2818. if (!empty($newlang)) {
  2819. $outputlangs = new Translate("", $conf);
  2820. $outputlangs->setDefaultLang($newlang);
  2821. $outputlangs->load('products');
  2822. }
  2823. if (!empty($prod->customcode)) {
  2824. $tmptxt .= $outputlangs->transnoentitiesnoconv("CustomCode") . ': ' . $prod->customcode;
  2825. }
  2826. if (!empty($prod->customcode) && !empty($prod->country_code)) {
  2827. $tmptxt .= ' - ';
  2828. }
  2829. if (!empty($prod->country_code)) {
  2830. $tmptxt .= $outputlangs->transnoentitiesnoconv("CountryOrigin") . ': ' . getCountry($prod->country_code, 0, $db, $outputlangs, 0);
  2831. }
  2832. } else {
  2833. if (!empty($prod->customcode)) {
  2834. $tmptxt .= $langs->transnoentitiesnoconv("CustomCode") . ': ' . $prod->customcode;
  2835. }
  2836. if (!empty($prod->customcode) && !empty($prod->country_code)) {
  2837. $tmptxt .= ' - ';
  2838. }
  2839. if (!empty($prod->country_code)) {
  2840. $tmptxt .= $langs->transnoentitiesnoconv("CountryOrigin") . ': ' . getCountry($prod->country_code, 0, $db, $langs, 0);
  2841. }
  2842. }
  2843. $tmptxt .= ')';
  2844. $desc = dol_concatdesc($desc, $tmptxt);
  2845. }
  2846. $type = $prod->type;
  2847. $fk_unit = $prod->fk_unit;
  2848. } else {
  2849. $pu_ht = price2num($price_ht, 'MU');
  2850. $pu_ttc = price2num($price_ttc, 'MU');
  2851. $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0);
  2852. $tva_tx = str_replace('*', '', $tva_tx);
  2853. if (empty($tva_tx)) {
  2854. $tva_npr = 0;
  2855. }
  2856. $label = (GETPOST('product_label') ? GETPOST('product_label') : '');
  2857. $desc = $product_desc;
  2858. $type = GETPOST('type');
  2859. $fk_unit = GETPOST('units', 'alpha');
  2860. $pu_ht_devise = price2num($price_ht_devise, 'MU');
  2861. $pu_ttc_devise = price2num($price_ttc_devise, 'MU');
  2862. if ($pu_ttc && !$pu_ht) {
  2863. $price_base_type = 'TTC';
  2864. }
  2865. }
  2866. $pu_ht_devise = price2num($price_ht_devise, 'MU');
  2867. // Margin
  2868. $fournprice = price2num(GETPOST('fournprice' . $predef) ? GETPOST('fournprice' . $predef) : '');
  2869. $buyingprice = price2num(GETPOST('buying_price' . $predef) != '' ? GETPOST('buying_price' . $predef) : ''); // If buying_price is '0', we must keep this value
  2870. // Local Taxes
  2871. $localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty, $mysoc, $tva_npr);
  2872. $localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty, $mysoc, $tva_npr);
  2873. $info_bits = 0;
  2874. if ($tva_npr) {
  2875. $info_bits |= 0x01;
  2876. }
  2877. $price2num_pu_ht = price2num($pu_ht);
  2878. $price2num_remise_percent = price2num($remise_percent);
  2879. $price2num_price_min = price2num($price_min);
  2880. $price2num_price_min_ttc = price2num($price_min_ttc);
  2881. if (empty($price2num_pu_ht)) {
  2882. $price2num_pu_ht = 0;
  2883. }
  2884. if (empty($price2num_remise_percent)) {
  2885. $price2num_remise_percent = 0;
  2886. }
  2887. if (empty($price2num_price_min)) {
  2888. $price2num_price_min = 0;
  2889. }
  2890. if (empty($price2num_price_min_ttc)) {
  2891. $price2num_price_min_ttc = 0;
  2892. }
  2893. // Check price is not lower than minimum (check is done only for standard or replacement invoices)
  2894. if ($usermustrespectpricemin && ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT)) {
  2895. if ($pu_ht && $price_min && ((price2num($pu_ht) * (1 - $remise_percent / 100)) < price2num($price_min))) {
  2896. $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, -1, $conf->currency));
  2897. setEventMessages($mesg, null, 'errors');
  2898. $error++;
  2899. } elseif ($pu_ttc && $price_min_ttc && ((price2num($pu_ttc) * (1 - $remise_percent / 100)) < price2num($price_min_ttc))) {
  2900. $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min_ttc, 'MU'), 0, $langs, 0, 0, -1, $conf->currency));
  2901. setEventMessages($mesg, null, 'errors');
  2902. $error++;
  2903. }
  2904. }
  2905. if (!$error) {
  2906. // Add batchinfo if the detail_batch array is defined
  2907. if (isModEnabled('productbatch') && !empty($lines[$i]->detail_batch) && is_array($lines[$i]->detail_batch) && !empty($conf->global->INVOICE_INCUDE_DETAILS_OF_LOTS_SERIALS)) {
  2908. $langs->load('productbatch');
  2909. foreach ($lines[$i]->detail_batch as $batchline) {
  2910. $desc .= ' ' . $langs->trans('Batch') . ' ' . $batchline->batch . ' ' . $langs->trans('printQty', $batchline->qty) . ' ';
  2911. }
  2912. }
  2913. // Insert line
  2914. $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, min($rank, count($object->lines) + 1), $special_code, '', 0, GETPOST('fk_parent_line'), $fournprice, $buyingprice, $label, $array_options, GETPOST('progress'), '', $fk_unit, $pu_ht_devise);
  2915. if ($result > 0) {
  2916. // Define output language and generate document
  2917. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  2918. $outputlangs = $langs;
  2919. $newlang = '';
  2920. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  2921. $newlang = GETPOST('lang_id', 'aZ09');
  2922. }
  2923. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
  2924. $newlang = $object->thirdparty->default_lang;
  2925. }
  2926. if (!empty($newlang)) {
  2927. $outputlangs = new Translate("", $conf);
  2928. $outputlangs->setDefaultLang($newlang);
  2929. $outputlangs->load('products');
  2930. }
  2931. $model = $object->model_pdf;
  2932. $ret = $object->fetch($id); // Reload to get new records
  2933. $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  2934. if ($result < 0) {
  2935. setEventMessages($object->error, $object->errors, 'errors');
  2936. }
  2937. }
  2938. unset($_POST['prod_entry_mode']);
  2939. unset($_POST['qty']);
  2940. unset($_POST['type']);
  2941. unset($_POST['remise_percent']);
  2942. unset($_POST['price_ht']);
  2943. unset($_POST['multicurrency_price_ht']);
  2944. unset($_POST['price_ttc']);
  2945. unset($_POST['tva_tx']);
  2946. unset($_POST['product_ref']);
  2947. unset($_POST['product_label']);
  2948. unset($_POST['product_desc']);
  2949. unset($_POST['fournprice']);
  2950. unset($_POST['buying_price']);
  2951. unset($_POST['np_marginRate']);
  2952. unset($_POST['np_markRate']);
  2953. unset($_POST['dp_desc']);
  2954. unset($_POST['idprod']);
  2955. unset($_POST['units']);
  2956. unset($_POST['date_starthour']);
  2957. unset($_POST['date_startmin']);
  2958. unset($_POST['date_startsec']);
  2959. unset($_POST['date_startday']);
  2960. unset($_POST['date_startmonth']);
  2961. unset($_POST['date_startyear']);
  2962. unset($_POST['date_endhour']);
  2963. unset($_POST['date_endmin']);
  2964. unset($_POST['date_endsec']);
  2965. unset($_POST['date_endday']);
  2966. unset($_POST['date_endmonth']);
  2967. unset($_POST['date_endyear']);
  2968. unset($_POST['situations']);
  2969. unset($_POST['progress']);
  2970. } else {
  2971. setEventMessages($object->error, $object->errors, 'errors');
  2972. }
  2973. $action = '';
  2974. }
  2975. }
  2976. } elseif ($action == 'updateline' && $usercancreate && !GETPOST('cancel', 'alpha')) {
  2977. if (!$object->fetch($id) > 0) {
  2978. dol_print_error($db);
  2979. }
  2980. $object->fetch_thirdparty();
  2981. // Clean parameters
  2982. $date_start = '';
  2983. $date_end = '';
  2984. $date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear'));
  2985. $date_end = dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear'));
  2986. $description = dol_htmlcleanlastbr(GETPOST('product_desc', 'restricthtml') ? GETPOST('product_desc', 'restricthtml') : GETPOST('desc', 'restricthtml'));
  2987. $vat_rate = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0);
  2988. $vat_rate = str_replace('*', '', $vat_rate);
  2989. $pu_ht = price2num(GETPOST('price_ht'), '', 2);
  2990. $pu_ttc = price2num(GETPOST('price_ttc'), '', 2);
  2991. $pu_ht_devise = price2num(GETPOST('multicurrency_subprice'), '', 2);
  2992. $pu_ttc_devise = price2num(GETPOST('multicurrency_subprice_ttc'), '', 2);
  2993. $qty = price2num(GETPOST('qty', 'alpha'), 'MS');
  2994. // Define info_bits
  2995. $info_bits = 0;
  2996. if (preg_match('/\*/', $vat_rate)) {
  2997. $info_bits |= 0x01;
  2998. }
  2999. // Define vat_rate
  3000. $vat_rate = str_replace('*', '', $vat_rate);
  3001. $localtax1_rate = get_localtax($vat_rate, 1, $object->thirdparty);
  3002. $localtax2_rate = get_localtax($vat_rate, 2, $object->thirdparty);
  3003. // Add buying price
  3004. $fournprice = price2num(GETPOST('fournprice') ? GETPOST('fournprice') : '');
  3005. $buyingprice = price2num(GETPOST('buying_price') != '' ? GETPOST('buying_price') : ''); // If buying_price is '0', we muste keep this value
  3006. // Extrafields
  3007. $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
  3008. $array_options = $extrafields->getOptionalsFromPost($object->table_element_line);
  3009. // Unset extrafield
  3010. if (is_array($extralabelsline)) {
  3011. // Get extra fields
  3012. foreach ($extralabelsline as $key => $value) {
  3013. unset($_POST["options_" . $key]);
  3014. }
  3015. }
  3016. // Define special_code for special lines
  3017. $special_code = GETPOST('special_code', 'int');
  3018. if ($special_code == 3) {
  3019. $special_code = 0; // Options should not exists on invoices
  3020. }
  3021. $line = new FactureLigne($db);
  3022. $line->fetch(GETPOST('lineid', 'int'));
  3023. $percent = $line->get_prev_progress($object->id);
  3024. $progress = price2num(GETPOST('progress', 'alpha'));
  3025. if ($object->type == Facture::TYPE_CREDIT_NOTE && $object->situation_cycle_ref > 0) {
  3026. // in case of situation credit note
  3027. if ($progress >= 0) {
  3028. $mesg = $langs->trans("CantBeNullOrPositive");
  3029. setEventMessages($mesg, null, 'warnings');
  3030. $error++;
  3031. $result = -1;
  3032. } elseif ($progress < $line->situation_percent) { // TODO : use a modified $line->get_prev_progress($object->id) result
  3033. $mesg = $langs->trans("CantBeLessThanMinPercent");
  3034. setEventMessages($mesg, null, 'warnings');
  3035. $error++;
  3036. $result = -1;
  3037. } elseif ($progress < $percent) {
  3038. $mesg = '<div class="warning">' . $langs->trans("CantBeLessThanMinPercent") . '</div>';
  3039. setEventMessages($mesg, null, 'warnings');
  3040. $error++;
  3041. $result = -1;
  3042. }
  3043. }
  3044. if ($object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE && $object->situation_cycle_ref > 0) {
  3045. // in case of situation credit note
  3046. if ($progress >= 0) {
  3047. $mesg = $langs->trans("CantBeNullOrPositive");
  3048. setEventMessages($mesg, null, 'warnings');
  3049. $error++;
  3050. $result = -1;
  3051. } elseif ($progress < $line->situation_percent) { // TODO : use a modified $line->get_prev_progress($object->id) result
  3052. $mesg = $langs->trans("CantBeLessThanMinPercent");
  3053. setEventMessages($mesg, null, 'warnings');
  3054. $error++;
  3055. $result = -1;
  3056. } elseif ($progress < $percent) {
  3057. $mesg = '<div class="warning">' . $langs->trans("CantBeLessThanMinPercent") . '</div>';
  3058. setEventMessages($mesg, null, 'warnings');
  3059. $error++;
  3060. $result = -1;
  3061. }
  3062. }
  3063. $remise_percent = price2num(GETPOST('remise_percent'), '', 2);
  3064. // Check minimum price
  3065. $productid = GETPOST('productid', 'int');
  3066. if (!empty($productid)) {
  3067. $product = new Product($db);
  3068. $product->fetch($productid);
  3069. $type = $product->type;
  3070. $price_min = $product->price_min;
  3071. if ((!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && !empty($object->thirdparty->price_level)) {
  3072. $price_min = $product->multiprices_min[$object->thirdparty->price_level];
  3073. }
  3074. $price_min_ttc = $product->price_min_ttc;
  3075. if ((!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && !empty($object->thirdparty->price_level)) {
  3076. $price_min_ttc = $product->multiprices_min_ttc[$object->thirdparty->price_level];
  3077. }
  3078. $label = ((GETPOST('update_label') && GETPOST('product_label')) ? GETPOST('product_label') : '');
  3079. // Check price is not lower than minimum (check is done only for standard or replacement invoices)
  3080. if ($usermustrespectpricemin && ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_RECEIPT)) {
  3081. if ($pu_ht && $price_min && (((float) price2num($pu_ht) * (1 - (float) $remise_percent / 100)) < (float) price2num($price_min))) {
  3082. $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, -1, $conf->currency));
  3083. setEventMessages($mesg, null, 'errors');
  3084. $error++;
  3085. $action = 'editline';
  3086. } elseif ($pu_ttc && $price_min_ttc && ((price2num($pu_ttc) * (1 - (float) $remise_percent / 100)) < price2num($price_min_ttc))) {
  3087. $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min_ttc, 'MU'), 0, $langs, 0, 0, -1, $conf->currency));
  3088. setEventMessages($mesg, null, 'errors');
  3089. $error++;
  3090. $action = 'editline';
  3091. }
  3092. }
  3093. } else {
  3094. $type = GETPOST('type');
  3095. $label = (GETPOST('product_label') ? GETPOST('product_label') : '');
  3096. // Check parameters
  3097. if (GETPOST('type') < 0) {
  3098. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
  3099. $error++;
  3100. }
  3101. }
  3102. if ($qty < 0) {
  3103. $langs->load("errors");
  3104. setEventMessages($langs->trans('ErrorQtyForCustomerInvoiceCantBeNegative'), null, 'errors');
  3105. $error++;
  3106. }
  3107. if (empty($productid) && (($pu_ht < 0 && empty($conf->global->FACTURE_ENABLE_NEGATIVE_LINES)) || $pu_ht == '') && (($pu_ht_devise < 0 && empty($conf->global->FACTURE_ENABLE_NEGATIVE_LINES)) || $pu_ht_devise == '') && $pu_ttc === '' && $pu_ttc_devise === '' && $object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_RECEIPT_CREDIT_NOTE) { // Unit price can be 0 but not ''
  3108. if (($pu_ht < 0 || $pu_ttc < 0) && empty($conf->global->FACTURE_ENABLE_NEGATIVE_LINES)) {
  3109. $langs->load("errors");
  3110. if ($object->type == $object::TYPE_DEPOSIT) {
  3111. // Using negative lines on deposit lead to headach and blocking problems when you want to consume them.
  3112. setEventMessages($langs->trans("ErrorLinesCantBeNegativeOnDeposits"), null, 'errors');
  3113. } else {
  3114. setEventMessages($langs->trans("ErrorFieldCantBeNegativeOnInvoice", $langs->transnoentitiesnoconv("UnitPriceHT"), $langs->transnoentitiesnoconv("CustomerAbsoluteDiscountShort")), null, 'errors');
  3115. }
  3116. $error++;
  3117. } else {
  3118. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("UnitPriceHT")), null, 'errors');
  3119. $error++;
  3120. }
  3121. }
  3122. // Update line
  3123. if (!$error) {
  3124. if (empty($usercancreatemargin)) {
  3125. foreach ($object->lines as &$line) {
  3126. if ($line->id == GETPOST('lineid', 'int')) {
  3127. $fournprice = $line->fk_fournprice;
  3128. $buyingprice = $line->pa_ht;
  3129. break;
  3130. }
  3131. }
  3132. }
  3133. $price_base_type = 'HT';
  3134. $pu = $pu_ht;
  3135. if (empty($pu) && !empty($pu_ttc)) {
  3136. $pu = $pu_ttc;
  3137. $price_base_type = 'TTC';
  3138. }
  3139. $result = $object->updateline(
  3140. GETPOST('lineid', 'int'),
  3141. $description,
  3142. $pu,
  3143. $qty,
  3144. $remise_percent,
  3145. $date_start,
  3146. $date_end,
  3147. $vat_rate,
  3148. $localtax1_rate,
  3149. $localtax2_rate,
  3150. $price_base_type,
  3151. $info_bits,
  3152. $type,
  3153. GETPOST('fk_parent_line', 'int'),
  3154. 0,
  3155. $fournprice,
  3156. $buyingprice,
  3157. $label,
  3158. $special_code,
  3159. $array_options,
  3160. price2num(GETPOST('progress', 'alpha')),
  3161. GETPOST('units', 'alpha'),
  3162. $pu_ht_devise
  3163. );
  3164. if ($result >= 0) {
  3165. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  3166. // Define output language
  3167. $outputlangs = $langs;
  3168. $newlang = '';
  3169. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  3170. $newlang = GETPOST('lang_id', 'aZ09');
  3171. }
  3172. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
  3173. $newlang = $object->thirdparty->default_lang;
  3174. }
  3175. if (!empty($newlang)) {
  3176. $outputlangs = new Translate("", $conf);
  3177. $outputlangs->setDefaultLang($newlang);
  3178. $outputlangs->load('products');
  3179. }
  3180. $ret = $object->fetch($id); // Reload to get new records
  3181. $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  3182. }
  3183. unset($_POST['qty']);
  3184. unset($_POST['type']);
  3185. unset($_POST['productid']);
  3186. unset($_POST['remise_percent']);
  3187. unset($_POST['price_ht']);
  3188. unset($_POST['multicurrency_price_ht']);
  3189. unset($_POST['price_ttc']);
  3190. unset($_POST['tva_tx']);
  3191. unset($_POST['product_ref']);
  3192. unset($_POST['product_label']);
  3193. unset($_POST['product_desc']);
  3194. unset($_POST['fournprice']);
  3195. unset($_POST['buying_price']);
  3196. unset($_POST['np_marginRate']);
  3197. unset($_POST['np_markRate']);
  3198. unset($_POST['dp_desc']);
  3199. unset($_POST['idprod']);
  3200. unset($_POST['units']);
  3201. unset($_POST['date_starthour']);
  3202. unset($_POST['date_startmin']);
  3203. unset($_POST['date_startsec']);
  3204. unset($_POST['date_startday']);
  3205. unset($_POST['date_startmonth']);
  3206. unset($_POST['date_startyear']);
  3207. unset($_POST['date_endhour']);
  3208. unset($_POST['date_endmin']);
  3209. unset($_POST['date_endsec']);
  3210. unset($_POST['date_endday']);
  3211. unset($_POST['date_endmonth']);
  3212. unset($_POST['date_endyear']);
  3213. unset($_POST['situations']);
  3214. unset($_POST['progress']);
  3215. } else {
  3216. setEventMessages($object->error, $object->errors, 'errors');
  3217. }
  3218. }
  3219. } elseif ($action == 'updatealllines' && $usercancreate && GETPOST('all_percent') == $langs->trans('Modifier')) { // Update all lines of situation invoice
  3220. if (!$object->fetch($id) > 0) {
  3221. dol_print_error($db);
  3222. }
  3223. if (GETPOST('all_progress') != "") {
  3224. $all_progress = GETPOST('all_progress', 'int');
  3225. foreach ($object->lines as $line) {
  3226. $percent = $line->get_prev_progress($object->id);
  3227. if (floatval($all_progress) < floatval($percent)) {
  3228. $mesg = $langs->trans("Line") . ' ' . $i . ' : ' . $langs->trans("CantBeLessThanMinPercent");
  3229. setEventMessages($mesg, null, 'warnings');
  3230. $result = -1;
  3231. } else {
  3232. $object->update_percent($line, GETPOST('all_progress'), false);
  3233. }
  3234. }
  3235. $object->update_price(1);
  3236. }
  3237. } elseif ($action == 'updateline' && $usercancreate && !$cancel) {
  3238. header('Location: ' . $_SERVER["PHP_SELF"] . '?facid=' . $id); // To show again edited page
  3239. exit();
  3240. } elseif ($action == 'confirm_situationout' && $confirm == 'yes' && $usercancreate) {
  3241. // Outing situation invoice from cycle
  3242. $object->fetch($id, '', '', '', true);
  3243. if (
  3244. in_array($object->statut, array(Facture::STATUS_CLOSED, Facture::STATUS_VALIDATED))
  3245. && $object->type == Facture::TYPE_SITUATION
  3246. && $usercancreate
  3247. && !$objectidnext
  3248. && $object->is_last_in_cycle()
  3249. && $usercanunvalidate
  3250. ) {
  3251. $outingError = 0;
  3252. $newCycle = $object->newCycle(); // we need to keep the "situation behavior" so we place it on a new situation cycle
  3253. if ($newCycle > 1) {
  3254. // Search credit notes
  3255. $lastCycle = $object->situation_cycle_ref;
  3256. $lastSituationCounter = $object->situation_counter;
  3257. $linkedCreditNotesList = array();
  3258. if (count($object->tab_next_situation_invoice) > 0) {
  3259. foreach ($object->tab_next_situation_invoice as $next_invoice) {
  3260. if (
  3261. ($next_invoice->type == Facture::TYPE_CREDIT_NOTE || $next_invoice->type == Facture::TYPE_RECEIPT_CREDIT_NOTE)
  3262. && $next_invoice->situation_counter == $object->situation_counter
  3263. && $next_invoice->fk_facture_source == $object->id
  3264. ) {
  3265. $linkedCreditNotesList[] = $next_invoice->id;
  3266. }
  3267. }
  3268. }
  3269. $object->situation_cycle_ref = $newCycle;
  3270. $object->situation_counter = 1;
  3271. $object->situation_final = 0;
  3272. if ($object->update($user) > 0) {
  3273. $errors = 0;
  3274. if (count($linkedCreditNotesList) > 0) {
  3275. // now, credit note must follow
  3276. $sql = 'UPDATE ' . MAIN_DB_PREFIX . 'facture';
  3277. $sql .= ' SET situation_cycle_ref = ' . ((int) $newCycle);
  3278. $sql .= ' , situation_final=0';
  3279. $sql .= ' , situation_counter=' . ((int) $object->situation_counter);
  3280. $sql .= ' WHERE rowid IN (' . $db->sanitize(implode(',', $linkedCreditNotesList)) . ')';
  3281. $resql = $db->query($sql);
  3282. if (!$resql) {
  3283. $errors++;
  3284. }
  3285. // Change each progression persent on each lines
  3286. foreach ($object->lines as $line) {
  3287. // no traitement for special product
  3288. if ($line->product_type == 9) {
  3289. continue;
  3290. }
  3291. if (!empty($object->tab_previous_situation_invoice)) {
  3292. // search the last invoice in cycle
  3293. $lineIndex = count($object->tab_previous_situation_invoice) - 1;
  3294. $searchPreviousInvoice = true;
  3295. while ($searchPreviousInvoice) {
  3296. if ($object->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_SITUATION || $lineIndex < 1) {
  3297. $searchPreviousInvoice = false; // find, exit;
  3298. break;
  3299. } else {
  3300. $lineIndex--; // go to previous invoice in cycle
  3301. }
  3302. }
  3303. $maxPrevSituationPercent = 0;
  3304. foreach ($object->tab_previous_situation_invoice[$lineIndex]->lines as $prevLine) {
  3305. if ($prevLine->id == $line->fk_prev_id) {
  3306. $maxPrevSituationPercent = max($maxPrevSituationPercent, $prevLine->situation_percent);
  3307. }
  3308. }
  3309. $line->situation_percent = $line->situation_percent - $maxPrevSituationPercent;
  3310. if ($line->update() < 0) {
  3311. $errors++;
  3312. }
  3313. }
  3314. }
  3315. }
  3316. if (!$errors) {
  3317. setEventMessages($langs->trans('Updated'), '', 'mesgs');
  3318. header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id);
  3319. } else {
  3320. setEventMessages($langs->trans('ErrorOutingSituationInvoiceCreditNote'), array(), 'errors');
  3321. }
  3322. } else {
  3323. setEventMessages($langs->trans('ErrorOutingSituationInvoiceOnUpdate'), array(), 'errors');
  3324. }
  3325. } else {
  3326. setEventMessages($langs->trans('ErrorFindNextSituationInvoice'), array(), 'errors');
  3327. }
  3328. }
  3329. } elseif (
  3330. $action == 'import_lines_from_object'
  3331. && $usercancreate
  3332. && $object->statut == Facture::STATUS_DRAFT
  3333. && ($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 || $object->type == Facture::TYPE_RECEIPT)
  3334. ) {
  3335. // add lines from objectlinked
  3336. $fromElement = GETPOST('fromelement');
  3337. $fromElementid = GETPOST('fromelementid');
  3338. $importLines = GETPOST('line_checkbox');
  3339. if (!empty($importLines) && is_array($importLines) && !empty($fromElement) && ctype_alpha($fromElement) && !empty($fromElementid)) {
  3340. if ($fromElement == 'commande') {
  3341. dol_include_once('/' . $fromElement . '/class/' . $fromElement . '.class.php');
  3342. $lineClassName = 'OrderLine';
  3343. } elseif ($fromElement == 'propal') {
  3344. dol_include_once('/comm/' . $fromElement . '/class/' . $fromElement . '.class.php');
  3345. $lineClassName = 'PropaleLigne';
  3346. }
  3347. $nextRang = count($object->lines) + 1;
  3348. $importCount = 0;
  3349. $error = 0;
  3350. foreach ($importLines as $lineId) {
  3351. $lineId = intval($lineId);
  3352. $originLine = new $lineClassName($db);
  3353. if (intval($fromElementid) > 0 && $originLine->fetch($lineId) > 0) {
  3354. $originLine->fetch_optionals();
  3355. $desc = $originLine->desc;
  3356. $pu_ht = $originLine->subprice;
  3357. $qty = $originLine->qty;
  3358. $txtva = $originLine->tva_tx;
  3359. $txlocaltax1 = $originLine->localtax1_tx;
  3360. $txlocaltax2 = $originLine->localtax2_tx;
  3361. $fk_product = $originLine->fk_product;
  3362. $remise_percent = $originLine->remise_percent;
  3363. $date_start = $originLine->date_start;
  3364. $date_end = $originLine->date_end;
  3365. $ventil = 0;
  3366. $info_bits = $originLine->info_bits;
  3367. $fk_remise_except = $originLine->fk_remise_except;
  3368. $price_base_type = 'HT';
  3369. $pu_ttc = 0;
  3370. $type = $originLine->product_type;
  3371. $rang = $nextRang++;
  3372. $special_code = $originLine->special_code;
  3373. $origin = $originLine->element;
  3374. $origin_id = $originLine->id;
  3375. $fk_parent_line = 0;
  3376. $fk_fournprice = $originLine->fk_fournprice;
  3377. $pa_ht = $originLine->pa_ht;
  3378. $label = $originLine->label;
  3379. $array_options = $originLine->array_options;
  3380. if ($object->type == Facture::TYPE_SITUATION) {
  3381. $situation_percent = 0;
  3382. } else {
  3383. $situation_percent = 100;
  3384. }
  3385. $fk_prev_id = '';
  3386. $fk_unit = $originLine->fk_unit;
  3387. $pu_ht_devise = $originLine->multicurrency_subprice;
  3388. $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);
  3389. if ($res > 0) {
  3390. $importCount++;
  3391. } else {
  3392. $error++;
  3393. }
  3394. } else {
  3395. $error++;
  3396. }
  3397. }
  3398. if ($error) {
  3399. setEventMessages($langs->trans('ErrorsOnXLines', $error), null, 'errors');
  3400. }
  3401. }
  3402. }
  3403. // Actions when printing a doc from card
  3404. include DOL_DOCUMENT_ROOT . '/core/actions_printing.inc.php';
  3405. // Actions to send emails
  3406. if (empty($id)) {
  3407. $id = $facid;
  3408. }
  3409. $triggersendname = 'BILL_SENTBYMAIL';
  3410. $paramname = 'id';
  3411. $autocopy = 'MAIN_MAIL_AUTOCOPY_INVOICE_TO';
  3412. $trackid = 'inv' . $object->id;
  3413. include DOL_DOCUMENT_ROOT . '/core/actions_sendmails.inc.php';
  3414. // Actions to build doc
  3415. $upload_dir = $conf->facture->multidir_output[!empty($object->entity) ? $object->entity : $conf->entity];
  3416. $permissiontoadd = $usercancreate;
  3417. include DOL_DOCUMENT_ROOT . '/core/actions_builddoc.inc.php';
  3418. if ($action == 'update_extras') {
  3419. $object->oldcopy = dol_clone($object);
  3420. // Fill array 'array_options' with data from add form
  3421. $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml'));
  3422. if ($ret < 0) {
  3423. $error++;
  3424. }
  3425. if (!$error) {
  3426. // Actions on extra fields
  3427. $result = $object->insertExtraFields('BILL_MODIFY');
  3428. if ($result < 0) {
  3429. setEventMessages($object->error, $object->errors, 'errors');
  3430. $error++;
  3431. }
  3432. }
  3433. if ($error) {
  3434. $action = 'edit_extras';
  3435. }
  3436. }
  3437. if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $usercancreate) {
  3438. if ($action == 'addcontact') {
  3439. $result = $object->fetch($id);
  3440. if ($result > 0 && $id > 0) {
  3441. $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid'));
  3442. $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type'));
  3443. $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09'));
  3444. }
  3445. if ($result >= 0) {
  3446. header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $object->id);
  3447. exit();
  3448. } else {
  3449. if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  3450. $langs->load("errors");
  3451. setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors');
  3452. } else {
  3453. setEventMessages($object->error, $object->errors, 'errors');
  3454. }
  3455. }
  3456. } elseif ($action == 'swapstatut') {
  3457. // bascule du statut d'un contact
  3458. if ($object->fetch($id)) {
  3459. $result = $object->swapContactStatus(GETPOST('ligne', 'int'));
  3460. } else {
  3461. dol_print_error($db);
  3462. }
  3463. } elseif ($action == 'deletecontact') {
  3464. // Efface un contact
  3465. $object->fetch($id);
  3466. $result = $object->delete_contact($lineid);
  3467. if ($result >= 0) {
  3468. header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $object->id);
  3469. exit();
  3470. } else {
  3471. dol_print_error($db);
  3472. }
  3473. }
  3474. if ($error) {
  3475. $action = 'edit_extras';
  3476. }
  3477. }
  3478. }
  3479. /*
  3480. * View
  3481. */
  3482. $form = new Form($db);
  3483. $formother = new FormOther($db);
  3484. $formfile = new FormFile($db);
  3485. $formmargin = new FormMargin($db);
  3486. $soc = new Societe($db);
  3487. $paymentstatic = new Paiement($db);
  3488. $bankaccountstatic = new Account($db);
  3489. if (isModEnabled('project')) {
  3490. $formproject = new FormProjets($db);
  3491. }
  3492. $now = dol_now();
  3493. $title = $object->ref . " - " . $langs->trans('Card');
  3494. if ($action == 'create') {
  3495. $title = $langs->trans("NewBill");
  3496. }
  3497. $help_url = "EN:Customers_Invoices|FR:Factures_Clients|ES:Facturas_a_clientes";
  3498. llxHeader('', $title, $help_url);
  3499. // Mode creation
  3500. if ($action == 'create') {
  3501. $facturestatic = new Facture($db);
  3502. $extrafields->fetch_name_optionals_label($facturestatic->table_element);
  3503. print load_fiche_titre($langs->trans('NewBill'), '', 'bill');
  3504. if ($socid > 0 && !$customerchange) {
  3505. $res = $soc->fetch($socid);
  3506. }
  3507. $currency_code = $conf->currency;
  3508. $fk_account = 0;
  3509. // Load objectsrc
  3510. $remise_absolue = 0;
  3511. if (!empty($origin) && !empty($originid)) {
  3512. // Parse element/subelement (ex: project_task)
  3513. $element = $subelement = $origin;
  3514. $regs = array();
  3515. if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs)) {
  3516. $element = $regs[1];
  3517. $subelement = $regs[2];
  3518. }
  3519. if ($element == 'project') {
  3520. $projectid = $originid;
  3521. if (empty($cond_reglement_id)) {
  3522. $cond_reglement_id = $soc->cond_reglement_id;
  3523. }
  3524. if (empty($mode_reglement_id)) {
  3525. $mode_reglement_id = $soc->mode_reglement_id;
  3526. }
  3527. if (empty($fk_account)) {
  3528. $fk_account = $soc->fk_account;
  3529. }
  3530. if (!$remise_percent) {
  3531. $remise_percent = $soc->remise_percent;
  3532. }
  3533. if (!$dateinvoice) {
  3534. // Do not set 0 here (0 for a date is 1970)
  3535. $dateinvoice = (empty($dateinvoice) ? (empty($conf->global->MAIN_AUTOFILL_DATE) ? -1 : '') : $dateinvoice);
  3536. }
  3537. } else {
  3538. // For compatibility
  3539. if ($element == 'order' || $element == 'commande') {
  3540. $element = $subelement = 'commande';
  3541. }
  3542. if ($element == 'propal') {
  3543. $element = 'comm/propal';
  3544. $subelement = 'propal';
  3545. }
  3546. if ($element == 'contract') {
  3547. $element = $subelement = 'contrat';
  3548. }
  3549. if ($element == 'shipping') {
  3550. $element = $subelement = 'expedition';
  3551. }
  3552. dol_include_once('/' . $element . '/class/' . $subelement . '.class.php');
  3553. $classname = ucfirst($subelement);
  3554. $objectsrc = new $classname($db);
  3555. $objectsrc->fetch($originid);
  3556. if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines')) {
  3557. $objectsrc->fetch_lines();
  3558. }
  3559. $objectsrc->fetch_thirdparty();
  3560. $projectid = (!empty($projectid) ? $projectid : $objectsrc->fk_project);
  3561. $ref_client = (!empty($objectsrc->ref_client) ? $objectsrc->ref_client : (!empty($objectsrc->ref_customer) ? $objectsrc->ref_customer : ''));
  3562. // only if socid not filled else it's allready done upper
  3563. if (empty($socid)) {
  3564. $soc = $objectsrc->thirdparty;
  3565. }
  3566. $dateinvoice = (empty($dateinvoice) ? (empty($conf->global->MAIN_AUTOFILL_DATE) ? -1 : '') : $dateinvoice);
  3567. if ($element == 'expedition') {
  3568. $ref_client = (!empty($objectsrc->ref_customer) ? $objectsrc->ref_customer : '');
  3569. $elem = $subelem = $objectsrc->origin;
  3570. $expeoriginid = $objectsrc->origin_id;
  3571. dol_include_once('/' . $elem . '/class/' . $subelem . '.class.php');
  3572. $classname = ucfirst($subelem);
  3573. $expesrc = new $classname($db);
  3574. $expesrc->fetch($expeoriginid);
  3575. $cond_reglement_id = (!empty($expesrc->cond_reglement_id) ? $expesrc->cond_reglement_id : (!empty($soc->cond_reglement_id) ? $soc->cond_reglement_id : 1));
  3576. $mode_reglement_id = (!empty($expesrc->mode_reglement_id) ? $expesrc->mode_reglement_id : (!empty($soc->mode_reglement_id) ? $soc->mode_reglement_id : 0));
  3577. $fk_account = (!empty($expesrc->fk_account) ? $expesrc->fk_account : (!empty($soc->fk_account) ? $soc->fk_account : 0));
  3578. $remise_percent = (!empty($expesrc->remise_percent) ? $expesrc->remise_percent : (!empty($soc->remise_percent) ? $soc->remise_percent : 0));
  3579. $remise_absolue = (!empty($expesrc->remise_absolue) ? $expesrc->remise_absolue : (!empty($soc->remise_absolue) ? $soc->remise_absolue : 0));
  3580. if (!empty($conf->multicurrency->enabled)) {
  3581. $currency_code = (!empty($expesrc->multicurrency_code) ? $expesrc->multicurrency_code : (!empty($soc->multicurrency_code) ? $soc->multicurrency_code : $objectsrc->multicurrency_code));
  3582. $currency_tx = (!empty($expesrc->multicurrency_tx) ? $expesrc->multicurrency_tx : (!empty($soc->multicurrency_tx) ? $soc->multicurrency_tx : $objectsrc->multicurrency_tx));
  3583. }
  3584. //Replicate extrafields
  3585. $expesrc->fetch_optionals();
  3586. $object->array_options = $expesrc->array_options;
  3587. } else {
  3588. $cond_reglement_id = (!empty($objectsrc->cond_reglement_id) ? $objectsrc->cond_reglement_id : (!empty($soc->cond_reglement_id) ? $soc->cond_reglement_id : 0));
  3589. $mode_reglement_id = (!empty($objectsrc->mode_reglement_id) ? $objectsrc->mode_reglement_id : (!empty($soc->mode_reglement_id) ? $soc->mode_reglement_id : 0));
  3590. $fk_account = (!empty($objectsrc->fk_account) ? $objectsrc->fk_account : (!empty($soc->fk_account) ? $soc->fk_account : 0));
  3591. $remise_percent = (!empty($objectsrc->remise_percent) ? $objectsrc->remise_percent : (!empty($soc->remise_percent) ? $soc->remise_percent : 0));
  3592. $remise_absolue = (!empty($objectsrc->remise_absolue) ? $objectsrc->remise_absolue : (!empty($soc->remise_absolue) ? $soc->remise_absolue : 0));
  3593. if (isModEnabled('multicurrency')) {
  3594. if (!empty($objectsrc->multicurrency_code)) {
  3595. $currency_code = $objectsrc->multicurrency_code;
  3596. }
  3597. if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($objectsrc->multicurrency_tx)) {
  3598. $currency_tx = $objectsrc->multicurrency_tx;
  3599. }
  3600. }
  3601. // Replicate extrafields
  3602. $objectsrc->fetch_optionals();
  3603. $object->array_options = $objectsrc->array_options;
  3604. }
  3605. }
  3606. } else {
  3607. $cond_reglement_id = $soc->cond_reglement_id;
  3608. $mode_reglement_id = $soc->mode_reglement_id;
  3609. $fk_account = $soc->fk_account;
  3610. $remise_percent = $soc->remise_percent;
  3611. $remise_absolue = 0;
  3612. $dateinvoice = (empty($dateinvoice) ? (empty($conf->global->MAIN_AUTOFILL_DATE) ? -1 : '') : $dateinvoice); // Do not set 0 here (0 for a date is 1970)
  3613. if (isModEnabled('multicurrency') && !empty($soc->multicurrency_code)) {
  3614. $currency_code = $soc->multicurrency_code;
  3615. }
  3616. }
  3617. // when payment condition is empty (means not override by payment condition form a other object, like third-party), try to use default value
  3618. if (empty($cond_reglement_id)) {
  3619. $cond_reglement_id = GETPOST("cond_reglement_id", 'int');
  3620. }
  3621. // when payment mode is empty (means not override by payment mode form a other object, like third-party), try to use default value
  3622. if (empty($mode_reglement_id)) {
  3623. $mode_reglement_id = GETPOST("mode_reglement_id", 'int');
  3624. }
  3625. // when bank account is empty (means not override by payment mode form a other object, like third-party), try to use default value
  3626. if ($socid > 0 && $fk_account) { // A company has already been set and it has a default fk_account
  3627. $fk_account = GETPOSTISSET('fk_account') ? GETPOST("fk_account", 'int') : $fk_account; // The GETPOST is used only if form was posted to avoid to take default value, because in such case, the default must be the one of the company
  3628. } else { // No company forced
  3629. $fk_account = GETPOST("fk_account", 'int');
  3630. }
  3631. if (!empty($soc->id)) {
  3632. $absolute_discount = $soc->getAvailableDiscounts();
  3633. }
  3634. $note_public = $object->getDefaultCreateValueFor('note_public', ((!empty($origin) && !empty($originid) && is_object($objectsrc) && !empty($conf->global->FACTURE_REUSE_NOTES_ON_CREATE_FROM)) ? $objectsrc->note_public : null));
  3635. $note_private = $object->getDefaultCreateValueFor('note_private', ((!empty($origin) && !empty($originid) && is_object($objectsrc) && !empty($conf->global->FACTURE_REUSE_NOTES_ON_CREATE_FROM)) ? $objectsrc->note_private : null));
  3636. if (!empty($conf->use_javascript_ajax)) {
  3637. require_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  3638. print ajax_combobox('fac_replacement');
  3639. print ajax_combobox('fac_avoir');
  3640. print ajax_combobox('situations');
  3641. }
  3642. if ($origin == 'contrat') {
  3643. $langs->load("admin");
  3644. $text = $langs->trans("ToCreateARecurringInvoice");
  3645. $text .= ' ' . $langs->trans("ToCreateARecurringInvoiceGene", $langs->transnoentitiesnoconv("MenuFinancial"), $langs->transnoentitiesnoconv("BillsCustomers"), $langs->transnoentitiesnoconv("ListOfTemplates"));
  3646. if (empty($conf->global->INVOICE_DISABLE_AUTOMATIC_RECURRING_INVOICE)) {
  3647. $text .= ' ' . $langs->trans("ToCreateARecurringInvoiceGeneAuto", $langs->transnoentitiesnoconv('Module2300Name'));
  3648. }
  3649. print info_admin($text, 0, 0, 0, 'opacitymedium') . '<br>';
  3650. }
  3651. print '<form name="add" action="' . $_SERVER["PHP_SELF"] . '" method="POST" id="formtocreate" name="formtocreate">';
  3652. print '<input type="hidden" name="token" value="' . newToken() . '">';
  3653. print '<input type="hidden" name="action" id="formtocreateaction" value="add">';
  3654. if ($soc->id > 0) {
  3655. print '<input type="hidden" name="socid" value="' . $soc->id . '">' . "\n";
  3656. }
  3657. if ($customerchange) {
  3658. print '<input type="hidden" name="customerchange" value="' . $customerchange . '">' . "\n";
  3659. }
  3660. print '<input name="ref" type="hidden" value="provisoire">';
  3661. print '<input name="ref_client" type="hidden" value="' . $ref_client . '">';
  3662. print '<input name="force_cond_reglement_id" type="hidden" value="0">';
  3663. print '<input name="force_mode_reglement_id" type="hidden" value="0">';
  3664. print '<input name="force_fk_account" type="hidden" value="0">';
  3665. print '<input type="hidden" name="origin" value="' . $origin . '">';
  3666. print '<input type="hidden" name="originid" value="' . $originid . '">';
  3667. print '<input type="hidden" name="originentity" value="' . GETPOST('originentity') . '">';
  3668. if (!empty($currency_tx)) {
  3669. print '<input type="hidden" name="originmulticurrency_tx" value="' . $currency_tx . '">';
  3670. }
  3671. print dol_get_fiche_head('');
  3672. print '<table class="border centpercent">';
  3673. // Ref
  3674. //print '<tr><td class="titlefieldcreate fieldrequired">'.$langs->trans('Ref').'</td><td colspan="2">'.$langs->trans('Draft').'</td></tr>';
  3675. $exampletemplateinvoice = new FactureRec($db);
  3676. $invoice_predefined = new FactureRec($db);
  3677. if (empty($origin) && empty($originid) && GETPOST('fac_rec', 'int') > 0) {
  3678. $invoice_predefined->fetch(GETPOST('fac_rec', 'int'));
  3679. }
  3680. // Thirdparty
  3681. if ($soc->id > 0 && (!GETPOST('fac_rec', 'int') || !empty($invoice_predefined->frequency))) {
  3682. // If thirdparty known and not a predefined invoiced without a recurring rule
  3683. print '<tr><td class="fieldrequired">' . $langs->trans('Customer') . '</td>';
  3684. print '<td colspan="2">';
  3685. print $soc->getNomUrl(1, 'customer');
  3686. print '<input type="hidden" name="socid" value="' . $soc->id . '">';
  3687. // Outstanding Bill
  3688. $arrayoutstandingbills = $soc->getOutstandingBills();
  3689. $outstandingBills = $arrayoutstandingbills['opened'];
  3690. print ' - <span class="opacitymedium">' . $langs->trans('CurrentOutstandingBill') . ':</span> ';
  3691. print '<span class="amount">' . price($outstandingBills, '', $langs, 0, 0, -1, $conf->currency) . '</span>';
  3692. if ($soc->outstanding_limit != '') {
  3693. if ($outstandingBills > $soc->outstanding_limit) {
  3694. print img_warning($langs->trans("OutstandingBillReached"));
  3695. }
  3696. print ' / ' . price($soc->outstanding_limit, '', $langs, 0, 0, -1, $conf->currency);
  3697. }
  3698. print '</td>';
  3699. print '</tr>' . "\n";
  3700. } elseif ($customerchange) {
  3701. print '<tr><td class="fieldrequired">' . $langs->trans('Customer') . '</td>';
  3702. print '<td colspan="2">';
  3703. print img_picto('', 'company') . $form->select_company($soc->id, 'socid', '((s.client = 1 OR s.client = 3) AND s.status = 1)', 'SelectThirdParty', 0, 0, null, 0, 'minwidth300 widthcentpercentminusxx maxwidth500');
  3704. print '</td>';
  3705. print '</tr>' . "\n";
  3706. } else {
  3707. print '<tr><td class="fieldrequired">' . $langs->trans('Customer') . '</td>';
  3708. print '<td colspan="2">';
  3709. print img_picto('', 'company') . $form->select_company($soc->id, 'socid', '((s.client = 1 OR s.client = 3) AND s.status = 1)', 'SelectThirdParty', 1, 0, null, 0, 'minwidth300 widthcentpercentminusxx maxwidth500');
  3710. // Option to reload page to retrieve customer informations.
  3711. if (empty($conf->global->RELOAD_PAGE_ON_CUSTOMER_CHANGE_DISABLED)) {
  3712. print '<script type="text/javascript">
  3713. $(document).ready(function() {
  3714. $("#socid").change(function() {
  3715. /*
  3716. console.log("Submit page");
  3717. $(\'input[name="action"]\').val(\'create\');
  3718. $(\'input[name="force_cond_reglement_id"]\').val(\'1\');
  3719. $(\'input[name="force_mode_reglement_id"]\').val(\'1\');
  3720. $(\'input[name="force_fk_account"]\').val(\'1\');
  3721. $("#formtocreate").submit(); */
  3722. // For company change, we must submit page with action=create instead of action=add
  3723. console.log("We have changed the company - Resubmit page");
  3724. jQuery("#formtocreateaction").val("create");
  3725. jQuery("#formtocreate").submit();
  3726. });
  3727. });
  3728. </script>';
  3729. }
  3730. if (!GETPOST('fac_rec', 'int')) {
  3731. print ' <a href="' . DOL_URL_ROOT . '/societe/card.php?action=create&client=3&fournisseur=0&backtopage=' . urlencode($_SERVER["PHP_SELF"] . '?action=create') . '"><span class="fa fa-plus-circle valignmiddle paddingleft" title="' . $langs->trans("AddThirdParty") . '"></span></a>';
  3732. }
  3733. print '</td>';
  3734. print '</tr>' . "\n";
  3735. }
  3736. // Overwrite some values if creation of invoice is from a predefined invoice
  3737. if (empty($origin) && empty($originid) && GETPOST('fac_rec', 'int') > 0) {
  3738. $invoice_predefined->fetch(GETPOST('fac_rec', 'int'));
  3739. $dateinvoice = $invoice_predefined->date_when; // To use next gen date by default later
  3740. if (empty($projectid)) {
  3741. $projectid = $invoice_predefined->fk_project;
  3742. }
  3743. $cond_reglement_id = $invoice_predefined->cond_reglement_id;
  3744. $mode_reglement_id = $invoice_predefined->mode_reglement_id;
  3745. $fk_account = $invoice_predefined->fk_account;
  3746. $note_public = $invoice_predefined->note_public;
  3747. $note_private = $invoice_predefined->note_private;
  3748. if (!empty($invoice_predefined->multicurrency_code)) {
  3749. $currency_code = $invoice_predefined->multicurrency_code;
  3750. }
  3751. if (!empty($invoice_predefined->multicurrency_tx)) {
  3752. $currency_tx = $invoice_predefined->multicurrency_tx;
  3753. }
  3754. $sql = 'SELECT r.rowid, r.titre as title, r.total_ttc';
  3755. $sql .= ' FROM ' . MAIN_DB_PREFIX . 'facture_rec as r';
  3756. $sql .= ' WHERE r.fk_soc = ' . ((int) $invoice_predefined->socid);
  3757. $resql = $db->query($sql);
  3758. if ($resql) {
  3759. $num = $db->num_rows($resql);
  3760. $i = 0;
  3761. if ($num > 0) {
  3762. print '<tr><td>' . $langs->trans('CreateFromRepeatableInvoice') . '</td><td>';
  3763. //print '<input type="hidden" name="fac_rec" id="fac_rec" value="'.GETPOST('fac_rec', 'int').'">';
  3764. print '<select class="flat" id="fac_rec" name="fac_rec">'; // We may want to change the template to use
  3765. print '<option value="0" selected></option>';
  3766. while ($i < $num) {
  3767. $objp = $db->fetch_object($resql);
  3768. print '<option value="' . $objp->rowid . '"';
  3769. if (GETPOST('fac_rec', 'int') == $objp->rowid) {
  3770. print ' selected';
  3771. $exampletemplateinvoice->fetch(GETPOST('fac_rec', 'int'));
  3772. }
  3773. print '>' . $objp->title . ' (' . price($objp->total_ttc) . ' ' . $langs->trans("TTC") . ')</option>';
  3774. $i++;
  3775. }
  3776. print '</select>';
  3777. print ajax_combobox("fac_rec");
  3778. // Option to reload page to retrieve customer informations. Note, this clear other input
  3779. if (empty($conf->global->RELOAD_PAGE_ON_TEMPLATE_CHANGE_DISABLED)) {
  3780. print '<script type="text/javascript">
  3781. $(document).ready(function() {
  3782. $("#fac_rec").change(function() {
  3783. console.log("We have changed the template invoice - Reload page");
  3784. var fac_rec = $(this).val();
  3785. var socid = $(\'#socid\').val();
  3786. // For template invoice change, we must reuse data of template, not input already done, so we call a GET with action=create, not a POST submit.
  3787. window.location.href = "' . $_SERVER["PHP_SELF"] . '?action=create&socid="+socid+"&fac_rec="+fac_rec;
  3788. });
  3789. });
  3790. </script>';
  3791. }
  3792. print '</td></tr>';
  3793. }
  3794. $db->free($resql);
  3795. } else {
  3796. dol_print_error($db);
  3797. }
  3798. }
  3799. print '<tr><td class="tdtop fieldrequired">' . $langs->trans('Type') . '</td><td colspan="2">';
  3800. print '<div class="tagtable">' . "\n";
  3801. // Standard invoice
  3802. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  3803. $tmp = '<input type="radio" id="radio_standard" name="type" value="0"' . (GETPOST('type', 'int') ? '' : ' checked') . '> ';
  3804. $tmp = $tmp . '<label for="radio_standard" >' . $langs->trans("InvoiceStandardAsk") . '</label>';
  3805. $desc = $form->textwithpicto($tmp, $langs->transnoentities("InvoiceStandardDesc"), 1, 'help', '', 0, 3, 'standardonsmartphone');
  3806. print '<table class="nobordernopadding"><tr>';
  3807. print '<td>';
  3808. print $desc;
  3809. print '</td>';
  3810. if ((($origin == 'propal') || ($origin == 'commande')) && (!empty($originid))) {
  3811. /*print '<td class="nowrap" style="padding-left: 5px">';
  3812. $arraylist = array(
  3813. //'amount' => $langs->transnoentitiesnoconv('FixAmount', $langs->transnoentitiesnoconv('Deposit')),
  3814. //'variable' => $langs->transnoentitiesnoconv('VarAmountOneLine', $langs->transnoentitiesnoconv('Deposit')),
  3815. 'variablealllines' => $langs->transnoentitiesnoconv('VarAmountAllLines')
  3816. );
  3817. print $form->selectarray('typestandard', $arraylist, GETPOST('typestandard', 'aZ09'), 0, 0, 0, '', 1);
  3818. print '</td>';*/
  3819. print '<td class="nowrap" style="padding-left: 15px">';
  3820. print '<span class="opacitymedium">' . $langs->trans('PercentOfOriginalObject') . '</span>:<input class="right" placeholder="100%" type="text" id="valuestandardinvoice" name="valuestandardinvoice" size="3" value="' . (GETPOSTISSET('valuestandardinvoice') ? GETPOST('valuestandardinvoice', 'alpha') : '100%') . '"/>';
  3821. print '</td>';
  3822. }
  3823. print '</tr></table>';
  3824. print '</div></div>';
  3825. #########################################
  3826. # Receipt
  3827. #########################################
  3828. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  3829. $tmp = '<input type="radio" id="radio_receipt" name="type" value="7")> ';
  3830. $tmp = $tmp . '<label for="radio_receipt" >' . $langs->trans("receiptAsk") . '</label>';
  3831. $desc = $form->textwithpicto($tmp, $langs->transnoentities("receiptDesc"), 1, 'help', '', 0, 3);
  3832. print '<table class="nobordernopadding"><tr>';
  3833. print '<td>';
  3834. print $desc;
  3835. print '</td>';
  3836. if ((($origin == 'propal') || ($origin == 'commande')) && (!empty($originid))) {
  3837. print '<td class="nowrap" style="padding-left: 15px">';
  3838. print '<span class="opacitymedium">' . $langs->trans('PercentOfOriginalObject') . '</span>:<input class="right" placeholder="100%" type="text" id="valuepeceipt" name="valuepeceipt" size="3" value="' . (GETPOSTISSET('valuepeceipt') ? GETPOST('valuepeceipt', 'alpha') : '100%') . '"/>';
  3839. print '</td>';
  3840. }
  3841. print '</tr></table>';
  3842. print '</div></div>';
  3843. if ((empty($origin)) || ((($origin == 'propal') || ($origin == 'commande')) && (!empty($originid)))) {
  3844. // Deposit - Down payment
  3845. if (empty($conf->global->INVOICE_DISABLE_DEPOSIT)) {
  3846. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  3847. $tmp = '<input type="radio" id="radio_deposit" name="type" value="3"' . (GETPOST('type') == 3 ? ' checked' : '') . '> ';
  3848. print '<script type="text/javascript">
  3849. jQuery(document).ready(function() {
  3850. jQuery("#typestandardinvoice, #valuestandardinvoice").click(function() {
  3851. jQuery("#radio_standard").prop("checked", true);
  3852. });
  3853. jQuery("#typereceipt, #valuereceipt").click(function() {
  3854. jQuery("#radio_receipt").prop("checked", true);
  3855. });
  3856. jQuery("#typedeposit, #valuedeposit").click(function() {
  3857. jQuery("#radio_deposit").prop("checked", true);
  3858. });
  3859. jQuery("#typedeposit").change(function() {
  3860. console.log("We change type of down payment");
  3861. jQuery("#radio_deposit").prop("checked", true);
  3862. setRadioForTypeOfIncoice();
  3863. });
  3864. jQuery("#radio_standard, #radio_deposit, #radio_replacement, #radio_creditnote, #radio_template", #radio_receipt".change(function() {
  3865. setRadioForTypeOfIncoice();
  3866. });
  3867. function setRadioForTypeOfIncoice() {
  3868. console.log("Change radio");
  3869. if (jQuery("#radio_deposit").prop("checked") && (jQuery("#typedeposit").val() == \'amount\' || jQuery("#typedeposit").val() == \'variable\')) {
  3870. jQuery(".checkforselect").prop("disabled", true);
  3871. jQuery(".checkforselect").prop("checked", false);
  3872. } else {
  3873. jQuery(".checkforselect").prop("disabled", false);
  3874. jQuery(".checkforselect").prop("checked", true);
  3875. }
  3876. };
  3877. });
  3878. </script>';
  3879. print '<table class="nobordernopadding"><tr>';
  3880. print '<td>';
  3881. $tmp = $tmp . '<label for="radio_deposit">' . $langs->trans("InvoiceDeposit") . '</label>';
  3882. $desc = $form->textwithpicto($tmp, $langs->transnoentities("InvoiceDepositDesc"), 1, 'help', '', 0, 3, 'depositonsmartphone');
  3883. print $desc;
  3884. print '</td>';
  3885. if (($origin == 'propal') || ($origin == 'commande')) {
  3886. print '<td class="nowrap" style="padding-left: 15px">';
  3887. $arraylist = array(
  3888. 'amount' => $langs->transnoentitiesnoconv('FixAmount', $langs->transnoentitiesnoconv('Deposit')),
  3889. 'variable' => $langs->transnoentitiesnoconv('VarAmountOneLine', $langs->transnoentitiesnoconv('Deposit')),
  3890. 'variablealllines' => $langs->transnoentitiesnoconv('VarAmountAllLines')
  3891. );
  3892. $typedeposit = GETPOST('typedeposit', 'aZ09');
  3893. $valuedeposit = GETPOST('valuedeposit', 'int');
  3894. if (empty($typedeposit) && !empty($objectsrc->deposit_percent)) {
  3895. $origin_payment_conditions_deposit_percent = getDictionaryValue('c_payment_term', 'deposit_percent', $objectsrc->cond_reglement_id);
  3896. if (!empty($origin_payment_conditions_deposit_percent)) {
  3897. $typedeposit = 'variable';
  3898. }
  3899. }
  3900. if (empty($valuedeposit) && $typedeposit == 'variable' && !empty($objectsrc->deposit_percent)) {
  3901. $valuedeposit = $objectsrc->deposit_percent;
  3902. }
  3903. print $form->selectarray('typedeposit', $arraylist, $typedeposit, 0, 0, 0, '', 1);
  3904. print '</td>';
  3905. print '<td class="nowrap" style="padding-left: 5px">';
  3906. print '<span class="opacitymedium paddingleft">' . $langs->trans("AmountOrPercent") . '</span><input type="text" id="valuedeposit" name="valuedeposit" class="width75 right" value="' . $valuedeposit . '"/>';
  3907. print '</td>';
  3908. }
  3909. print '</tr></table>';
  3910. print '</div></div>';
  3911. }
  3912. }
  3913. if ($socid > 0) {
  3914. if (!empty($conf->global->INVOICE_USE_SITUATION)) {
  3915. // First situation invoice
  3916. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  3917. $tmp = '<input id="radio_situation" type="radio" name="type" value="5"' . (GETPOST('type') == 5 ? ' checked' : '') . '> ';
  3918. $tmp = $tmp . '<label for="radio_situation" >' . $langs->trans("InvoiceFirstSituationAsk") . '</label>';
  3919. $desc = $form->textwithpicto($tmp, $langs->transnoentities("InvoiceFirstSituationDesc"), 1, 'help', '', 0, 3, 'firstsituationonsmartphone');
  3920. print $desc;
  3921. print '</div></div>';
  3922. // Next situation invoice
  3923. $opt = $form->selectSituationInvoices(GETPOST('originid', 'int'), $socid);
  3924. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  3925. $tmp = '<input type="radio" name="type" value="5"' . (GETPOST('type') == 5 && GETPOST('originid', 'int') ? ' checked' : '');
  3926. if ($opt == ('<option value ="0" selected>' . $langs->trans('NoSituations') . '</option>') || (GETPOST('origin') && GETPOST('origin') != 'facture' && GETPOST('origin') != 'commande')) {
  3927. $tmp .= ' disabled';
  3928. }
  3929. $tmp .= '> ';
  3930. $text = $tmp . '<label>' . $langs->trans("InvoiceSituationAsk") . '</label> ';
  3931. $text .= '<select class="flat" id="situations" name="situations"';
  3932. if ($opt == ('<option value ="0" selected>' . $langs->trans('NoSituations') . '</option>') || (GETPOST('origin') && GETPOST('origin') != 'facture' && GETPOST('origin') != 'commande')) {
  3933. $text .= ' disabled';
  3934. }
  3935. $text .= '>';
  3936. $text .= $opt;
  3937. $text .= '</select>';
  3938. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceSituationDesc"), 1, 'help', '', 0, 3);
  3939. print $desc;
  3940. print '</div></div>';
  3941. }
  3942. // Replacement
  3943. if (empty($conf->global->INVOICE_DISABLE_REPLACEMENT)) {
  3944. // Type de facture
  3945. $facids = $facturestatic->list_replacable_invoices($soc->id);
  3946. if ($facids < 0) {
  3947. dol_print_error($db, $facturestatic->error, $facturestatic->errors);
  3948. exit();
  3949. }
  3950. $options = "";
  3951. if (is_array($facids)) {
  3952. foreach ($facids as $facparam) {
  3953. $options .= '<option value="' . $facparam['id'] . '"';
  3954. if ($facparam['id'] == GETPOST('fac_replacement', 'int')) {
  3955. $options .= ' selected';
  3956. }
  3957. $options .= '>' . $facparam['ref'];
  3958. $options .= ' (' . $facturestatic->LibStatut($facparam['paid'], $facparam['status'], 0, $facparam['alreadypaid']) . ')';
  3959. $options .= '</option>';
  3960. }
  3961. }
  3962. print '<!-- replacement line -->';
  3963. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  3964. $tmp = '<input type="radio" name="type" id="radio_replacement" value="1"' . (GETPOST('type') == 1 ? ' checked' : '');
  3965. if (!$options || $invoice_predefined->id > 0) {
  3966. $tmp .= ' disabled';
  3967. }
  3968. $tmp .= '> ';
  3969. print '<script type="text/javascript">
  3970. jQuery(document).ready(function() {
  3971. jQuery("#fac_replacement").change(function() {
  3972. jQuery("#radio_replacement").prop("checked", true);
  3973. });
  3974. });
  3975. </script>';
  3976. $text = $tmp . '<label for="radio_replacement">' . $langs->trans("InvoiceReplacementAsk") . '</label>';
  3977. $text .= '<select class="flat" name="fac_replacement" id="fac_replacement"';
  3978. if (!$options || $invoice_predefined->id > 0) {
  3979. $text .= ' disabled';
  3980. }
  3981. $text .= '>';
  3982. if ($options) {
  3983. $text .= '<option value="-1">&nbsp;</option>';
  3984. $text .= $options;
  3985. } else {
  3986. $text .= '<option value="-1">' . $langs->trans("NoReplacableInvoice") . '</option>';
  3987. }
  3988. $text .= '</select>';
  3989. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceReplacementDesc"), 1, 'help', '', 0, 3);
  3990. print $desc;
  3991. print '</div></div>';
  3992. }
  3993. } else {
  3994. if (!empty($conf->global->INVOICE_USE_SITUATION)) {
  3995. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  3996. $tmp = '<input type="radio" name="type" id="radio_situation" value="0" disabled> ';
  3997. $text = $tmp . '<label>' . $langs->trans("InvoiceSituationAsk") . '</label> ';
  3998. $text .= '<span class="opacitymedium">(' . $langs->trans("YouMustCreateInvoiceFromThird") . ')</span> ';
  3999. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceFirstSituationDesc"), 1, 'help', '', 0, 3, 'firstsituationonsmartphone');
  4000. print $desc;
  4001. print '</div></div>';
  4002. }
  4003. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  4004. $tmp = '<input type="radio" name="type" id="radio_replacement" value="0" disabled> ';
  4005. $text = $tmp . '<label for="radio_replacement" class="opacitymedium">' . $langs->trans("InvoiceReplacement") . '</label> ';
  4006. //$text .= '<span class="opacitymedium hideonsmartphone">('.$langs->trans("YouMustCreateInvoiceFromThird").')</span> ';
  4007. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceReplacementDesc") . '<br><br>' . $langs->trans("YouMustCreateInvoiceFromThird"), 1, 'help', '', 0, 3, 'replacementonsmartphone');
  4008. print $desc;
  4009. print '</div></div>';
  4010. }
  4011. if (empty($origin)) {
  4012. if ($socid > 0) {
  4013. // Credit note
  4014. if (GETPOST('type', 'int') == 8) {
  4015. // Show link for credit note
  4016. $facids = $facturestatic->list_qualified_avoir_invoices($soc->id);
  4017. if ($facids < 0) {
  4018. dol_print_error($db, $facturestatic->error, $facturestatic->errors);
  4019. exit;
  4020. }
  4021. $optionsav = "";
  4022. $newinvoice_static = new Facture($db);
  4023. foreach ($facids as $key => $valarray) {
  4024. $newinvoice_static->id = $key;
  4025. $newinvoice_static->ref = $valarray['ref'];
  4026. $newinvoice_static->statut = $valarray['status'];
  4027. $newinvoice_static->type = $valarray['type'];
  4028. $newinvoice_static->paye = $valarray['paye'];
  4029. $optionsav .= '<option value="' . $key . '"';
  4030. if ($key == GETPOST('fac_avoir')) {
  4031. $optionsav .= ' selected';
  4032. // pre-filled extra fields with selected credit note
  4033. $newinvoice_static->fetch_optionals($key);
  4034. $object->array_options = $newinvoice_static->array_options;
  4035. }
  4036. $optionsav .= '>';
  4037. $optionsav .= $newinvoice_static->ref;
  4038. $optionsav .= ' (' . $newinvoice_static->getLibStatut(1, $valarray['paymentornot']) . ')';
  4039. $optionsav .= '</option>';
  4040. }
  4041. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  4042. $tmp = '<input type="radio" id="radio_creditnote_receipt" name="type" value="8"'.(GETPOST('type') == 8 ? ' checked' : '');
  4043. if ((!$optionsav && empty($conf->global->INVOICE_CREDIT_NOTE_STANDALONE)) || $invoice_predefined->id > 0) {
  4044. $tmp .= ' disabled';
  4045. }
  4046. $tmp .= '> ';
  4047. // Show credit note options only if we checked credit note
  4048. print '<script type="text/javascript">
  4049. jQuery(document).ready(function() {
  4050. if (! jQuery("#radio_creditnote_receipt").is(":checked"))
  4051. {
  4052. jQuery("#credit_note_receipt_options").hide();
  4053. }
  4054. jQuery("#radio_creditnote_receipt").click(function() {
  4055. jQuery("#credit_note_receipt_options").show();
  4056. });
  4057. jQuery("#radio_standard, #radio_replacement, #radio_deposit, #radio_receipt").click(function() {
  4058. jQuery("#credit_note_receipt_options").hide();
  4059. });
  4060. });
  4061. </script>';
  4062. $text = '<label>'.$tmp.$langs->transnoentities("ReceiptAvoirAsk").'</label> ';
  4063. // $text.='<input type="text" value="">';
  4064. $text .= '<select class="flat valignmiddle" name="fac_avoir" id="fac_avoir"';
  4065. if (!$optionsav || $invoice_predefined->id > 0) {
  4066. $text .= ' disabled';
  4067. }
  4068. $text .= '>';
  4069. if ($optionsav) {
  4070. $text .= '<option value="-1"></option>';
  4071. $text .= $optionsav;
  4072. } else {
  4073. $text .= '<option value="-1">'.$langs->trans("NoInvoiceToCorrect").'</option>';
  4074. }
  4075. $text .= '</select>';
  4076. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3);
  4077. print $desc;
  4078. print '<div id="credit_note_receipt_options" class="clearboth">';
  4079. print '&nbsp;&nbsp;&nbsp; <input type="checkbox" name="invoiceAvoirWithLines" id="invoiceAvoirWithLines" value="1" onclick="$(\'#credit_note_receipt_options input[type=checkbox]\').not(this).prop(\'checked\', false);" '.(GETPOST('invoiceAvoirWithLines', 'int') > 0 ? 'checked' : '').' /> <label for="ReceiptinvoiceAvoirWithLines">'.$langs->trans('ReceiptinvoiceAvoirWithLines')."</label>";
  4080. //print '<br>&nbsp;&nbsp;&nbsp; <input type="checkbox" name="invoiceAvoirWithPaymentRestAmount" id="invoiceAvoirWithPaymentRestAmount" value="1" onclick="$(\'#credit_note_receipt_options input[type=checkbox]\').not(this).prop(\'checked\', false);" '.(GETPOST('invoiceAvoirWithPaymentRestAmount', 'int') > 0 ? 'checked' : '').' /> <label for="invoiceAvoirWithPaymentRestAmount">'.$langs->trans('invoiceAvoirWithPaymentRestAmount')."</label>";
  4081. print '</div>';
  4082. print '</div></div>';
  4083. }
  4084. elseif (empty($conf->global->INVOICE_DISABLE_CREDIT_NOTE)) {
  4085. // Show link for credit note
  4086. $facids = $facturestatic->list_qualified_avoir_invoices($soc->id);
  4087. if ($facids < 0) {
  4088. dol_print_error($db, $facturestatic->error, $facturestatic->errors);
  4089. exit;
  4090. }
  4091. $optionsav = "";
  4092. $newinvoice_static = new Facture($db);
  4093. foreach ($facids as $key => $valarray) {
  4094. $newinvoice_static->id = $key;
  4095. $newinvoice_static->ref = $valarray['ref'];
  4096. $newinvoice_static->statut = $valarray['status'];
  4097. $newinvoice_static->type = $valarray['type'];
  4098. $newinvoice_static->paye = $valarray['paye'];
  4099. $optionsav .= '<option value="'.$key.'"';
  4100. if ($key == GETPOST('fac_avoir') && !$customerchange) {
  4101. $optionsav .= ' selected';
  4102. // pre-filled extra fields with selected credit note
  4103. $newinvoice_static->fetch_optionals($key);
  4104. $object->array_options = $newinvoice_static->array_options;
  4105. }
  4106. $optionsav .= '>';
  4107. $optionsav .= $newinvoice_static->ref;
  4108. $optionsav .= ' ('.$newinvoice_static->getLibStatut(1, $valarray['paymentornot']).')';
  4109. $optionsav .= '</option>';
  4110. }
  4111. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  4112. $tmp = '<input type="radio" id="radio_creditnote" name="type" value="2"' . (GETPOST('type') == 2 ? ' checked' : '');
  4113. if ((!$optionsav && empty($conf->global->INVOICE_CREDIT_NOTE_STANDALONE)) || $invoice_predefined->id > 0) {
  4114. $tmp .= ' disabled';
  4115. }
  4116. $tmp .= '> ';
  4117. // Show credit note options only if we checked credit note
  4118. print '<script type="text/javascript">
  4119. jQuery(document).ready(function() {
  4120. if (! jQuery("#radio_creditnote").is(":checked"))
  4121. {
  4122. jQuery("#credit_note_options").hide();
  4123. }
  4124. jQuery("#radio_creditnote").click(function() {
  4125. jQuery("#credit_note_options").show();
  4126. });
  4127. jQuery("#radio_standard, #radio_replacement, #radio_deposit, #radio_receipt").click(function() {
  4128. jQuery("#credit_note_options").hide();
  4129. });
  4130. });
  4131. </script>';
  4132. $text = '<label>' . $tmp . $langs->transnoentities("InvoiceAvoirAsk") . '</label> ';
  4133. $text .= '<select class="flat valignmiddle" name="fac_avoir" id="fac_avoir"';
  4134. if (!$optionsav || $invoice_predefined->id > 0) {
  4135. $text .= ' disabled';
  4136. }
  4137. $text .= '>';
  4138. if ($optionsav) {
  4139. $text .= '<option value="-1"></option>';
  4140. $text .= $optionsav;
  4141. } else {
  4142. $text .= '<option value="-1">' . $langs->trans("NoInvoiceToCorrect") . '</option>';
  4143. }
  4144. $text .= '</select>';
  4145. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3);
  4146. print $desc;
  4147. print '<div id="credit_note_options" class="clearboth paddingtop marginbottomonly">';
  4148. 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>";
  4149. 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>";
  4150. print '</div>';
  4151. print '</div></div>';
  4152. }
  4153. } else {
  4154. //-------------------------------------
  4155. //
  4156. // Change Customername
  4157. //
  4158. //-------------------------------------
  4159. if ($customerchange) {
  4160. $facidsCC = $facturestatic->list_qualified_avoir_invoices($soc->id);
  4161. if ($facidsCC < 0) {
  4162. dol_print_error($db, $facturestatic->error, $facturestatic->errors);
  4163. exit;
  4164. }
  4165. $optionsav = "";
  4166. $newinvoice_staticCC = new Facture($db);
  4167. foreach ($facidsCC as $key => $valarray) {
  4168. $newinvoice_staticCC->id = $key;
  4169. $newinvoice_staticCC->ref = $valarray['ref'];
  4170. $newinvoice_staticCC->statut = $valarray['status'];
  4171. $newinvoice_staticCC->type = $valarray['type'];
  4172. $newinvoice_staticCC->paye = $valarray['paye'];
  4173. $optionsav .= '<option value="'.$key.'"';
  4174. if ($key == GETPOST('fac_avoir')) {
  4175. $optionsav .= ' selected';
  4176. // pre-filled extra fields with selected credit note
  4177. $newinvoice_staticCC->fetch_optionals($key);
  4178. $object->array_options = $newinvoice_staticCC->array_options;
  4179. }
  4180. $optionsav .= '>';
  4181. $optionsav .= $newinvoice_staticCC->ref;
  4182. $optionsav .= ' ('.$newinvoice_staticCC->getLibStatut(1, $valarray['paymentornot']).')';
  4183. $optionsav .= '</option>';
  4184. }
  4185. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  4186. $tmp = '<input type="radio" id="radio_creditnoteCustomerchange" name="type" value="6" checked';
  4187. if ((!$optionsav && empty($conf->global->INVOICE_CREDIT_NOTE_STANDALONE)) || $invoice_predefined->id > 0) {
  4188. $tmp .= ' disabled';
  4189. }
  4190. $tmp .= '> ';
  4191. // Show credit note options only if we checked credit note
  4192. print '<script type="text/javascript">
  4193. jQuery(document).ready(function() {
  4194. if (! jQuery("#radio_creditnoteCustomerchange").is(":checked"))
  4195. {
  4196. jQuery("#credit_note_options").hide();
  4197. }
  4198. $("#radio_standard, #radio_deposit, #radio_replacement, #radio_creditnote, #fac_replacement, #radio_receipt").prop("disabled", true);
  4199. jQuery("#radio_creditnoteCustomerchange").click(function() {
  4200. jQuery("#credit_note_options").show();
  4201. });
  4202. jQuery("#radio_standard, #radio_replacement, #radio_deposit, #radio_receipt").click(function() {
  4203. jQuery("#credit_note_options").hide();
  4204. });
  4205. });
  4206. </script>';
  4207. $text = '<label>'.$tmp.$langs->trans("customerchangeLabel").'</label> ';
  4208. // $text.='<input type="text" value="">';
  4209. $text .= '<select class="flat valignmiddle" name="fac_avoir" id="fac_avoir"';
  4210. if (!$optionsav || $invoice_predefined->id > 0) {
  4211. $text .= ' disabled';
  4212. }
  4213. $text .= '>';
  4214. if ($optionsav) {
  4215. $text .= '<option value="-1"></option>';
  4216. $text .= $optionsav;
  4217. } else {
  4218. $text .= '<option value="-1">'.$langs->trans("NoInvoiceToCorrect").'</option>';
  4219. }
  4220. $text .= '</select>';
  4221. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3);
  4222. print $desc;
  4223. print '<div id="credit_note_options" class="clearboth">';
  4224. $invoiceAvoirWithLinesCustomerChangeString = $langs->trans('invoiceAvoirWithLinesCustomerChange');
  4225. if(GETPOST('type') == 7){
  4226. $invoiceAvoirWithLinesCustomerChangeString = $langs->trans('invoiceAvoirWithLinesCustomerChangeReceipt');
  4227. }
  4228. print '&nbsp;&nbsp;&nbsp; <input type="checkbox" name="invoiceAvoirWithLinesCustomerChange" id="invoiceAvoirWithLinesCustomerChange" value="'.GETPOST('type').'" '.((GETPOST('type') == 0 || GETPOST('type') == 7) ? 'checked' : '').' /> <label for="invoiceAvoirWithLinesCustomerChange">'.$invoiceAvoirWithLinesCustomerChangeString."</label>";
  4229. //print '<br>&nbsp;&nbsp;&nbsp; <input type="checkbox" name="invoiceAvoirWithLinesReceiptCustomerChange" id="invoiceAvoirWithLinesReceiptCustomerChange" value="'.GETPOST('type').'" '.(GETPOST('type') == 7 ? 'checked' : '').' /> <label for="invoiceAvoirWithLinesReceiptCustomerChange">'.$langs->trans('invoiceAvoirWithLinesReceiptCustomerChange')."</label>";
  4230. //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>";
  4231. print '</div>';
  4232. print '</div></div>';
  4233. }
  4234. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  4235. if (empty($conf->global->INVOICE_CREDIT_NOTE_STANDALONE)) {
  4236. $tmp = '<input type="radio" name="type" id="radio_creditnote" value="0" disabled> ';
  4237. } else {
  4238. $tmp = '<input type="radio" name="type" id="radio_creditnote" value="2" > ';
  4239. }
  4240. $text = $tmp . '<label class="opacitymedium" for="radio_creditnote">' . $langs->trans("InvoiceAvoir") . '</label> ';
  4241. //$text .= '<span class="opacitymedium hideonsmartphone">('.$langs->trans("YouMustCreateInvoiceFromThird").')</span> ';
  4242. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc") . '<br><br>' . $langs->trans("YouMustCreateInvoiceFromThird"), 1, 'help', '', 0, 3, 'creditnoteonsmartphone');
  4243. print $desc;
  4244. print '</div></div>' . "\n";
  4245. }
  4246. }
  4247. // Template invoice
  4248. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  4249. $tmp = '<input type="radio" name="type" id="radio_template" value="0" disabled> ';
  4250. $text = $tmp . '<label class="opacitymedium" for="radio_template">' . $langs->trans("RepeatableInvoice") . '</label> ';
  4251. $desc = $form->textwithpicto($text, $langs->transnoentities("YouMustCreateStandardInvoiceFirstDesc"), 1, 'help', '', 0, 3, 'templateonsmartphone');
  4252. print $desc;
  4253. print '</div></div>';
  4254. print '</div>';
  4255. if (!empty($conf->global->INVOICE_USE_DEFAULT_DOCUMENT)) { // Hidden conf
  4256. // Add auto select default document model
  4257. $listtType = array(Facture::TYPE_STANDARD, Facture::TYPE_REPLACEMENT, Facture::TYPE_CREDIT_NOTE, Facture::TYPE_RECEIPT_CREDIT_NOTE, Facture::TYPE_DEPOSIT, Facture::TYPE_SITUATION);
  4258. $jsListType = '';
  4259. foreach ($listtType as $type) {
  4260. $thisTypeConfName = 'FACTURE_ADDON_PDF_' . $type;
  4261. $curent = !empty($conf->global->{$thisTypeConfName}) ? $conf->global->{$thisTypeConfName} : $conf->global->FACTURE_ADDON_PDF;
  4262. $jsListType .= (!empty($jsListType) ? ',' : '') . '"' . $type . '":"' . $curent . '"';
  4263. }
  4264. print '<script type="text/javascript">
  4265. $(document).ready(function() {
  4266. var listType = {' . $jsListType . '};
  4267. $("[name=\'type\'").change(function() {
  4268. console.log("change name=type");
  4269. if ($( this ).prop("checked"))
  4270. {
  4271. if(($( this ).val() in listType))
  4272. {
  4273. $("#model").val(listType[$( this ).val()]);
  4274. }
  4275. else
  4276. {
  4277. $("#model").val("' . $conf->global->FACTURE_ADDON_PDF . '");
  4278. }
  4279. }
  4280. });
  4281. });
  4282. </script>';
  4283. }
  4284. print '</td></tr>';
  4285. if ($socid > 0) {
  4286. // Discounts for third party
  4287. print '<tr><td>' . $langs->trans('DiscountStillRemaining') . '</td><td colspan="2">';
  4288. $thirdparty = $soc;
  4289. $discount_type = 0;
  4290. $backtopage = urlencode($_SERVER["PHP_SELF"] . '?socid=' . $thirdparty->id . '&action=' . $action . '&origin=' . GETPOST('origin', 'alpha') . '&originid=' . GETPOST('originid', 'int'));
  4291. include DOL_DOCUMENT_ROOT . '/core/tpl/object_discounts.tpl.php';
  4292. print '</td></tr>';
  4293. }
  4294. $newdateinvoice = dol_mktime(0, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int'), 'tzserver');
  4295. $date_pointoftax = dol_mktime(0, 0, 0, GETPOST('date_pointoftaxmonth', 'int'), GETPOST('date_pointoftaxday', 'int'), GETPOST('date_pointoftaxyear', 'int'), 'tzserver');
  4296. // Date invoice
  4297. print '<tr><td class="fieldrequired">' . $langs->trans('DateInvoice') . '</td><td colspan="2">';
  4298. print $form->selectDate($newdateinvoice ? $newdateinvoice : $dateinvoice, '', '', '', '', "add", 1, 1);
  4299. print '</td></tr>';
  4300. // Date point of tax
  4301. if (!empty($conf->global->INVOICE_POINTOFTAX_DATE)) {
  4302. print '<tr><td class="fieldrequired">' . $langs->trans('DatePointOfTax') . '</td><td colspan="2">';
  4303. print $form->selectDate($date_pointoftax ? $date_pointoftax : -1, 'date_pointoftax', '', '', '', "add", 1, 1);
  4304. print '</td></tr>';
  4305. }
  4306. // Payment term
  4307. print '<tr><td class="nowrap fieldrequired">' . $langs->trans('PaymentConditionsShort') . '</td><td colspan="2">';
  4308. print $form->getSelectConditionsPaiements(GETPOSTISSET('cond_reglement_id') ? GETPOST('cond_reglement_id', 'int') : $cond_reglement_id, 'cond_reglement_id');
  4309. print '</td></tr>';
  4310. if (!empty($conf->global->INVOICE_USE_RETAINED_WARRANTY)) {
  4311. $rwStyle = 'display:none;';
  4312. if (in_array(GETPOST('type', 'int'), $retainedWarrantyInvoiceAvailableType)) {
  4313. $rwStyle = '';
  4314. }
  4315. $retained_warranty = GETPOST('retained_warranty', 'int');
  4316. if (empty($retained_warranty)) {
  4317. if (!empty($objectsrc->retained_warranty)) { // use previous situation value
  4318. $retained_warranty = $objectsrc->retained_warranty;
  4319. }
  4320. }
  4321. $retained_warranty_js_default = !empty($retained_warranty) ? $retained_warranty : $conf->global->INVOICE_SITUATION_DEFAULT_RETAINED_WARRANTY_PERCENT;
  4322. print '<tr class="retained-warranty-line" style="' . $rwStyle . '" ><td class="nowrap">' . $langs->trans('RetainedWarranty') . '</td><td colspan="2">';
  4323. print '<input id="new-situation-invoice-retained-warranty" name="retained_warranty" type="number" value="' . $retained_warranty . '" step="0.01" min="0" max="100" />%';
  4324. // Retained warranty payment term
  4325. print '<tr class="retained-warranty-line" style="' . $rwStyle . '" ><td class="nowrap">' . $langs->trans('PaymentConditionsShortRetainedWarranty') . '</td><td colspan="2">';
  4326. $retained_warranty_fk_cond_reglement = GETPOST('retained_warranty_fk_cond_reglement', 'int');
  4327. if (empty($retained_warranty_fk_cond_reglement)) {
  4328. $retained_warranty_fk_cond_reglement = $conf->global->INVOICE_SITUATION_DEFAULT_RETAINED_WARRANTY_COND_ID;
  4329. if (!empty($objectsrc->retained_warranty_fk_cond_reglement)) { // use previous situation value
  4330. $retained_warranty_fk_cond_reglement = $objectsrc->retained_warranty_fk_cond_reglement;
  4331. } else {
  4332. $retained_warranty_fk_cond_reglement = $conf->global->INVOICE_SITUATION_DEFAULT_RETAINED_WARRANTY_COND_ID;
  4333. }
  4334. }
  4335. print $form->getSelectConditionsPaiements($retained_warranty_fk_cond_reglement, 'retained_warranty_fk_cond_reglement', -1, 1);
  4336. print '</td></tr>';
  4337. print '<script type="text/javascript">
  4338. $(document).ready(function() {
  4339. $("[name=\'type\']").change(function() {
  4340. if($( this ).prop("checked") && $.inArray($( this ).val(), ' . json_encode($retainedWarrantyInvoiceAvailableType) . ' ) !== -1)
  4341. {
  4342. $(".retained-warranty-line").show();
  4343. $("#new-situation-invoice-retained-warranty").val("' . floatval($retained_warranty_js_default) . '");
  4344. }
  4345. else{
  4346. $(".retained-warranty-line").hide();
  4347. $("#new-situation-invoice-retained-warranty").val("");
  4348. }
  4349. });
  4350. $("[name=\'type\']:checked").trigger("change");
  4351. });
  4352. </script>';
  4353. }
  4354. // Payment mode
  4355. print '<tr><td class="fieldrequired">' . $langs->trans('PaymentMode') . '</td><td colspan="2">';
  4356. print img_picto('', 'payment', 'class="pictofixedwidth"');
  4357. $factureTMPOBJ = new Facture($db);
  4358. $factureTMPOBJ->fetch(GETPOST('fac_avoir'));
  4359. if(isset($factureTMPOBJ->mode_reglement_id)){
  4360. $mode_reglement_id = $factureTMPOBJ->mode_reglement_id;
  4361. }
  4362. print $form->select_types_paiements(GETPOSTISSET('mode_reglement_id') ? GETPOST('mode_reglement_id') : $mode_reglement_id, 'mode_reglement_id', 'CRDT', 0, 1, 0, 0, 1, 'maxwidth200 widthcentpercentminusx', 1);
  4363. print '</td></tr>';
  4364. $alert = $langs->trans('ReglementAlert');
  4365. print '<div class="jnotify-container payementmethodAlert" style="display:none;"><div class="jnotify-notification jnotify-notification-error"><div class="jnotify-background"></div><a class="jnotify-close" onclick="closePayementMethodAlert()">×</a><div class="jnotify-message"><div>'.$alert.'</div></div></div></div>';
  4366. print '<script type="text/javascript">
  4367. function closePayementMethodAlert(){
  4368. $(".payementmethodAlert").css({\'display\':\'none\'})
  4369. }
  4370. $(document).ready(function() {
  4371. $("#formtocreate").submit(function(event) {
  4372. event.preventDefault();
  4373. var selectedValue = $("#selectmode_reglement_id").val();
  4374. if (selectedValue === "") {
  4375. $(".payementmethodAlert").css({\'display\':\'block\'});
  4376. } else {
  4377. $("#formtocreate").off("submit").submit();
  4378. }
  4379. });
  4380. });
  4381. </script>';
  4382. // Bank Account
  4383. if (isModEnabled("banque")) {
  4384. if(isset($factureTMPOBJ->fk_account)){
  4385. $fk_account = $factureTMPOBJ->fk_account;
  4386. }
  4387. print '<tr><td>' . $langs->trans('BankAccount') . '</td><td colspan="2">';
  4388. print img_picto('', 'bank_account', 'class="pictofixedwidth"');
  4389. print $form->select_comptes(($fk_account < 0 ? '' : $fk_account), 'fk_account', 0, '', 1, '', 0, 'maxwidth200 widthcentpercentminusx', 1);
  4390. print '</td></tr>';
  4391. }
  4392. // Project
  4393. if (isModEnabled('project')) {
  4394. $langs->load('projects');
  4395. print '<tr><td>' . $langs->trans('Project') . '</td><td colspan="2">';
  4396. print img_picto('', 'project') . $formproject->select_projects(($socid > 0 ? $socid : -1), $projectid, 'projectid', 0, 0, 1, 1, 0, 0, 0, '', 1, 0, 'maxwidth500 widthcentpercentminusxx');
  4397. print ' <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 : '')) . '"><span class="fa fa-plus-circle valignmiddle" title="' . $langs->trans("AddProject") . '"></span></a>';
  4398. print '</td></tr>';
  4399. }
  4400. // Incoterms
  4401. if (isModEnabled('incoterm')) {
  4402. print '<tr>';
  4403. print '<td><label for="incoterm_id">' . $form->textwithpicto($langs->trans("IncotermLabel"), !empty($objectsrc->label_incoterms) ? $objectsrc->label_incoterms : '', 1) . '</label></td>';
  4404. print '<td colspan="2" class="maxwidthonsmartphone">';
  4405. $incoterm_id = GETPOST('incoterm_id');
  4406. $incoterm_location = GETPOST('location_incoterms');
  4407. if (empty($incoterm_id)) {
  4408. $incoterm_id = (!empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : $soc->fk_incoterms);
  4409. $incoterm_location = (!empty($objectsrc->location_incoterms) ? $objectsrc->location_incoterms : $soc->location_incoterms);
  4410. }
  4411. print $form->select_incoterms($incoterm_id, $incoterm_location);
  4412. print '</td></tr>';
  4413. }
  4414. // Other attributes
  4415. $parameters = array('objectsrc' => !empty($objectsrc) ? $objectsrc : 0, 'colspan' => ' colspan="2"', 'cols' => '2', 'socid' => $socid);
  4416. $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  4417. print $hookmanager->resPrint;
  4418. if (empty($reshook)) {
  4419. if (!empty($conf->global->THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_INVOICE) && !empty($soc->id)) {
  4420. // copy from thirdparty
  4421. $tpExtrafields = new Extrafields($db);
  4422. $tpExtrafieldLabels = $tpExtrafields->fetch_name_optionals_label($soc->table_element);
  4423. if ($soc->fetch_optionals() > 0) {
  4424. $object->array_options = array_merge($object->array_options, $soc->array_options);
  4425. }
  4426. }
  4427. ;
  4428. print $object->showOptionals($extrafields, 'create', $parameters);
  4429. }
  4430. // Template to use by default
  4431. print '<tr><td>' . $langs->trans('Model') . '</td>';
  4432. print '<td colspan="2">';
  4433. print img_picto('', 'pdf', 'class="pictofixedwidth"');
  4434. include_once DOL_DOCUMENT_ROOT . '/core/modules/facture/modules_facture.php';
  4435. $liste = ModelePDFFactures::liste_modeles($db);
  4436. if (!empty($conf->global->INVOICE_USE_DEFAULT_DOCUMENT)) {
  4437. // Hidden conf
  4438. $paramkey = 'FACTURE_ADDON_PDF_' . $object->type;
  4439. $preselected = !empty($conf->global->$paramkey) ? $conf->global->$paramkey : $conf->global->FACTURE_ADDON_PDF;
  4440. } else {
  4441. $preselected = $conf->global->FACTURE_ADDON_PDF;
  4442. }
  4443. print $form->selectarray('model', $liste, $preselected, 0, 0, 0, '', 0, 0, 0, '', 'maxwidth200 widthcentpercentminusx', 1);
  4444. print "</td></tr>";
  4445. // Multicurrency
  4446. if (isModEnabled('multicurrency')) {
  4447. $currency_code = $factureTMPOBJ->multicurrency_code;
  4448. print '<tr>';
  4449. print '<td>' . $form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0) . '</td>';
  4450. print '<td colspan="2" class="maxwidthonsmartphone">';
  4451. print img_picto('', 'currency', 'class="pictofixedwidth"');
  4452. print $form->selectMultiCurrency($currency_code, 'multicurrency_code');
  4453. print '</td></tr>';
  4454. }
  4455. // Help of substitution key
  4456. $htmltext = '';
  4457. if (GETPOST('fac_rec', 'int') > 0) {
  4458. $dateexample = ($newdateinvoice ? $newdateinvoice : $dateinvoice);
  4459. if (empty($dateexample)) {
  4460. $dateexample = dol_now();
  4461. }
  4462. $substitutionarray = array(
  4463. '__TOTAL_HT__' => $langs->trans("AmountHT") . ' (' . $langs->trans("Example") . ': ' . price($exampletemplateinvoice->total_ht) . ')',
  4464. '__TOTAL_TTC__' => $langs->trans("AmountTTC") . ' (' . $langs->trans("Example") . ': ' . price($exampletemplateinvoice->total_ttc) . ')',
  4465. '__INVOICE_PREVIOUS_MONTH__' => $langs->trans("PreviousMonthOfInvoice") . ' (' . $langs->trans("Example") . ': ' . dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'), '%m') . ')',
  4466. '__INVOICE_MONTH__' => $langs->trans("MonthOfInvoice") . ' (' . $langs->trans("Example") . ': ' . dol_print_date($dateexample, '%m') . ')',
  4467. '__INVOICE_NEXT_MONTH__' => $langs->trans("NextMonthOfInvoice") . ' (' . $langs->trans("Example") . ': ' . dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'), '%m') . ')',
  4468. '__INVOICE_PREVIOUS_MONTH_TEXT__' => $langs->trans("TextPreviousMonthOfInvoice") . ' (' . $langs->trans("Example") . ': ' . dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'), '%B') . ')',
  4469. '__INVOICE_MONTH_TEXT__' => $langs->trans("TextMonthOfInvoice") . ' (' . $langs->trans("Example") . ': ' . dol_print_date($dateexample, '%B') . ')',
  4470. '__INVOICE_NEXT_MONTH_TEXT__' => $langs->trans("TextNextMonthOfInvoice") . ' (' . $langs->trans("Example") . ': ' . dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'), '%B') . ')',
  4471. '__INVOICE_PREVIOUS_YEAR__' => $langs->trans("PreviousYearOfInvoice") . ' (' . $langs->trans("Example") . ': ' . dol_print_date(dol_time_plus_duree($dateexample, -1, 'y'), '%Y') . ')',
  4472. '__INVOICE_YEAR__' => $langs->trans("YearOfInvoice") . ' (' . $langs->trans("Example") . ': ' . dol_print_date($dateexample, '%Y') . ')',
  4473. '__INVOICE_NEXT_YEAR__' => $langs->trans("NextYearOfInvoice") . ' (' . $langs->trans("Example") . ': ' . dol_print_date(dol_time_plus_duree($dateexample, 1, 'y'), '%Y') . ')'
  4474. );
  4475. $htmltext = '<i>' . $langs->trans("FollowingConstantsWillBeSubstituted") . ':<br>';
  4476. foreach ($substitutionarray as $key => $val) {
  4477. $htmltext .= $key . ' = ' . $langs->trans($val) . '<br>';
  4478. }
  4479. $htmltext .= '</i>';
  4480. }
  4481. // Public note
  4482. print '<tr>';
  4483. print '<td class="tdtop">';
  4484. print $form->textwithpicto($langs->trans('NotePublic'), $htmltext);
  4485. print '</td>';
  4486. print '<td valign="top" colspan="2">';
  4487. $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PUBLIC) ? 0 : 1, ROWS_3, '90%');
  4488. print $doleditor->Create(1);
  4489. // Private note
  4490. if (empty($user->socid)) {
  4491. print '<tr>';
  4492. print '<td class="tdtop">';
  4493. print $form->textwithpicto($langs->trans('NotePrivate'), $htmltext);
  4494. print '</td>';
  4495. print '<td valign="top" colspan="2">';
  4496. $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PRIVATE) ? 0 : 1, ROWS_3, '90%');
  4497. print $doleditor->Create(1);
  4498. // print '<textarea name="note_private" wrap="soft" cols="70" rows="'.ROWS_3.'">'.$note_private.'.</textarea>
  4499. print '</td></tr>';
  4500. }
  4501. // Lines from source (TODO Show them also when creating invoice from template invoice)
  4502. if (!empty($origin) && !empty($originid) && is_object($objectsrc)) {
  4503. $langs->loadLangs(array('orders', 'propal'));
  4504. // TODO for compatibility
  4505. if ($origin == 'contrat') {
  4506. // Calcul contrat->price (HT), contrat->total (TTC), contrat->tva
  4507. $objectsrc->remise_absolue = $remise_absolue;
  4508. $objectsrc->remise_percent = $remise_percent;
  4509. $objectsrc->update_price(1, 'auto', 1);
  4510. }
  4511. print "\n<!-- Show ref of origin " . $classname . " -->\n";
  4512. print '<input type="hidden" name="amount" value="' . $objectsrc->total_ht . '">' . "\n";
  4513. print '<input type="hidden" name="total" value="' . $objectsrc->total_ttc . '">' . "\n";
  4514. print '<input type="hidden" name="tva" value="' . $objectsrc->total_tva . '">' . "\n";
  4515. // The commented lines below are fields already added as hidden parameters before
  4516. //print '<input type="hidden" name="origin" value="'.$objectsrc->element.'">';
  4517. //print '<input type="hidden" name="originid" value="'.$objectsrc->id.'">';
  4518. switch (get_class($objectsrc)) {
  4519. case 'Propal':
  4520. $newclassname = 'CommercialProposal';
  4521. break;
  4522. case 'Commande':
  4523. $newclassname = 'Order';
  4524. break;
  4525. case 'Expedition':
  4526. $newclassname = 'Sending';
  4527. break;
  4528. case 'Contrat':
  4529. $newclassname = 'Contract';
  4530. break;
  4531. case 'Fichinter':
  4532. $newclassname = 'Intervention';
  4533. break;
  4534. default:
  4535. $newclassname = get_class($objectsrc);
  4536. }
  4537. // Ref of origin
  4538. print '<tr><td>' . $langs->trans($newclassname) . '</td>';
  4539. print '<td colspan="2">';
  4540. print $objectsrc->getNomUrl(1);
  4541. // We check if Origin document (id and type is known) has already at least one invoice attached to it
  4542. $objectsrc->fetchObjectLinked($originid, $origin, '', 'facture');
  4543. if (is_array($objectsrc->linkedObjects['facture']) && count($objectsrc->linkedObjects['facture']) >= 1) {
  4544. setEventMessages('WarningBillExist', null, 'warnings');
  4545. echo ' - ' . $langs->trans('LatestRelatedBill') . ' ' . end($objectsrc->linkedObjects['facture'])->getNomUrl(1);
  4546. }
  4547. echo '</td></tr>';
  4548. print '<tr><td>' . $langs->trans('AmountHT') . '</td><td colspan="2">' . price($objectsrc->total_ht) . '</td></tr>';
  4549. print '<tr><td>' . $langs->trans('AmountVAT') . '</td><td colspan="2">' . price($objectsrc->total_tva) . "</td></tr>";
  4550. if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) { // Localtax1
  4551. print '<tr><td>' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '</td><td colspan="2">' . price($objectsrc->total_localtax1) . "</td></tr>";
  4552. }
  4553. if ($mysoc->localtax2_assuj == "1" || $objectsrc->total_localtax2 != 0) { // Localtax2
  4554. print '<tr><td>' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '</td><td colspan="2">' . price($objectsrc->total_localtax2) . "</td></tr>";
  4555. }
  4556. print '<tr><td>' . $langs->trans('AmountTTC') . '</td><td colspan="2">' . price($objectsrc->total_ttc) . "</td></tr>";
  4557. if (isModEnabled('multicurrency')) {
  4558. print '<tr><td>' . $langs->trans('MulticurrencyAmountHT') . '</td><td colspan="2">' . price($objectsrc->multicurrency_total_ht) . '</td></tr>';
  4559. print '<tr><td>' . $langs->trans('MulticurrencyAmountVAT') . '</td><td colspan="2">' . price($objectsrc->multicurrency_total_tva) . "</td></tr>";
  4560. print '<tr><td>' . $langs->trans('MulticurrencyAmountTTC') . '</td><td colspan="2">' . price($objectsrc->multicurrency_total_ttc) . "</td></tr>";
  4561. }
  4562. }
  4563. print "</table>\n";
  4564. print dol_get_fiche_end();
  4565. print $form->buttonsSaveCancel("CreateDraft");
  4566. // Show origin lines
  4567. if (!empty($origin) && !empty($originid) && is_object($objectsrc)) {
  4568. print '<br>';
  4569. $title = $langs->trans('ProductsAndServices');
  4570. print load_fiche_titre($title);
  4571. print '<div class="div-table-responsive-no-min">';
  4572. print '<table class="noborder centpercent">';
  4573. $objectsrc->printOriginLinesList('', $selectedLines);
  4574. print '</table>';
  4575. print '</div>';
  4576. }
  4577. print "</form>\n";
  4578. } elseif ($id > 0 || !empty($ref)) {
  4579. if (empty($object->id)) {
  4580. $langs->load('errors');
  4581. echo '<div class="error">' . $langs->trans("ErrorRecordNotFound") . '</div>';
  4582. llxFooter();
  4583. exit;
  4584. }
  4585. /*
  4586. * Show object in view mode
  4587. */
  4588. $result = $object->fetch($id, $ref);
  4589. if ($result <= 0) {
  4590. dol_print_error($db, $object->error, $object->errors);
  4591. exit();
  4592. }
  4593. // fetch optionals attributes and labels
  4594. $extrafields->fetch_name_optionals_label($object->table_element);
  4595. if ($user->socid > 0 && $user->socid != $object->socid) {
  4596. accessforbidden('', 0, 1);
  4597. }
  4598. $result = $object->fetch_thirdparty();
  4599. $result = $soc->fetch($object->socid);
  4600. if ($result < 0) {
  4601. dol_print_error($db);
  4602. }
  4603. $selleruserevenustamp = $mysoc->useRevenueStamp();
  4604. $totalpaid = $object->getSommePaiement();
  4605. $totalcreditnotes = $object->getSumCreditNotesUsed();
  4606. $totaldeposits = $object->getSumDepositsUsed();
  4607. //print "totalpaid=".$totalpaid." totalcreditnotes=".$totalcreditnotes." totaldeposts=".$totaldeposits."
  4608. // selleruserrevenuestamp=".$selleruserevenustamp;
  4609. // We can also use bcadd to avoid pb with floating points
  4610. // For example print 239.2 - 229.3 - 9.9; does not return 0.
  4611. // $resteapayer=bcadd($object->total_ttc,$totalpaid,$conf->global->MAIN_MAX_DECIMALS_TOT);
  4612. // $resteapayer=bcadd($resteapayer,$totalavoir,$conf->global->MAIN_MAX_DECIMALS_TOT);
  4613. $resteapayer = price2num($object->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
  4614. // Multicurrency
  4615. if (isModEnabled('multicurrency')) {
  4616. $multicurrency_totalpaid = $object->getSommePaiement(1);
  4617. $multicurrency_totalcreditnotes = $object->getSumCreditNotesUsed(1);
  4618. $multicurrency_totaldeposits = $object->getSumDepositsUsed(1);
  4619. $multicurrency_resteapayer = price2num($object->multicurrency_total_ttc - $multicurrency_totalpaid - $multicurrency_totalcreditnotes - $multicurrency_totaldeposits, 'MT');
  4620. // Code to fix case of corrupted data
  4621. // TODO We should not need this. Also data comes from a not reliable value of $object->multicurrency_total_ttc that may be wrong if it was
  4622. // calculated by summing lines that were in a currency for some of them and into another for others (lines from discount/down payment into another currency for example)
  4623. if ($resteapayer == 0 && $multicurrency_resteapayer != 0 && $object->multicurrency_code != $conf->currency) {
  4624. $resteapayer = price2num($multicurrency_resteapayer / $object->multicurrency_tx, 'MT');
  4625. }
  4626. }
  4627. if ($object->paye) {
  4628. $resteapayer = 0;
  4629. }
  4630. $resteapayer = round($resteapayer, 2);
  4631. $resteapayeraffiche = $resteapayer;
  4632. if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { // Never use this
  4633. $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
  4634. $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
  4635. } else {
  4636. $filterabsolutediscount = "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')";
  4637. $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')";
  4638. }
  4639. $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount);
  4640. $absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote);
  4641. $absolute_discount = price2num($absolute_discount, 'MT');
  4642. $absolute_creditnote = price2num($absolute_creditnote, 'MT');
  4643. $author = new User($db);
  4644. if ($object->user_author) {
  4645. $author->fetch($object->user_author);
  4646. }
  4647. $objectidnext = $object->getIdReplacingInvoice();
  4648. $head = facture_prepare_head($object);
  4649. print dol_get_fiche_head($head, 'compta', $langs->trans('InvoiceCustomer'), -1, 'bill');
  4650. $formconfirm = '';
  4651. // Confirmation de la conversion de l'avoir en reduc
  4652. if ($action == 'converttoreduc') {
  4653. if ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_SITUATION || $object->type == Facture::TYPE_RECEIPT) {
  4654. $type_fac = 'ExcessReceived';
  4655. } elseif ($object->type == Facture::TYPE_CREDIT_NOTE) {
  4656. $type_fac = 'CreditNote';
  4657. } elseif ($object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE) {
  4658. $type_fac = 'CreditNote';
  4659. } elseif ($object->type == Facture::TYPE_DEPOSIT) {
  4660. $type_fac = 'Deposit';
  4661. }
  4662. $text = $langs->trans('ConfirmConvertToReduc', strtolower($langs->transnoentities($type_fac)));
  4663. $text .= '<br>' . $langs->trans('ConfirmConvertToReduc2');
  4664. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $langs->trans('ConvertToReduc'), $text, 'confirm_converttoreduc', '', "yes", 2);
  4665. }
  4666. // Confirmation to delete invoice
  4667. if ($action == 'delete') {
  4668. $text = $langs->trans('ConfirmDeleteBill', $object->ref);
  4669. $formquestion = array();
  4670. if ($object->type != Facture::TYPE_DEPOSIT && !empty($conf->global->STOCK_CALCULATE_ON_BILL) && $object->statut >= 1) {
  4671. $qualified_for_stock_change = 0;
  4672. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  4673. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  4674. } else {
  4675. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  4676. }
  4677. if ($qualified_for_stock_change) {
  4678. $langs->load("stocks");
  4679. require_once DOL_DOCUMENT_ROOT . '/product/class/html.formproduct.class.php';
  4680. $formproduct = new FormProduct($db);
  4681. $label = $object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockDecrease") : $langs->trans("SelectWarehouseForStockIncrease");
  4682. $forcecombo = 0;
  4683. if ($conf->browser->name == 'ie') {
  4684. $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy
  4685. }
  4686. $formquestion = array(
  4687. // 'text' => $langs->trans("ConfirmClone"),
  4688. // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1),
  4689. // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => 1),
  4690. array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse') ? GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1, 0, 0, $langs->trans("NoStockAction"), 0, $forcecombo))
  4691. );
  4692. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $langs->trans('DeleteBill'), $text, 'confirm_delete', $formquestion, "yes", 1);
  4693. } else {
  4694. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $langs->trans('DeleteBill'), $text, 'confirm_delete', '', 'no', 1);
  4695. }
  4696. } else {
  4697. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $langs->trans('DeleteBill'), $text, 'confirm_delete', '', 'no', 1);
  4698. }
  4699. }
  4700. // Confirmation to remove invoice from cycle
  4701. if ($action == 'situationout') {
  4702. $text = $langs->trans('ConfirmRemoveSituationFromCycle', $object->ref);
  4703. $label = $langs->trans("ConfirmOuting");
  4704. $formquestion = array();
  4705. // remove situation from cycle
  4706. if (
  4707. in_array($object->statut, array(Facture::STATUS_CLOSED, Facture::STATUS_VALIDATED))
  4708. && $usercancreate
  4709. && !$objectidnext
  4710. && $object->is_last_in_cycle()
  4711. && $usercanunvalidate
  4712. ) {
  4713. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $label, $text, 'confirm_situationout', $formquestion, "yes", 1);
  4714. }
  4715. }
  4716. // Confirmation of validation
  4717. if ($action == 'valid') {
  4718. // we check object has a draft number
  4719. $objectref = substr($object->ref, 1, 4);
  4720. if ($objectref == 'PROV') {
  4721. $savdate = $object->date;
  4722. if (!empty($conf->global->FAC_FORCE_DATE_VALIDATION)) {
  4723. $object->date = dol_now();
  4724. $object->date_lim_reglement = $object->calculate_date_lim_reglement();
  4725. }
  4726. $numref = $object->getNextNumRef($soc);
  4727. // $object->date=$savdate;
  4728. } else {
  4729. $numref = $object->ref;
  4730. }
  4731. $text = $langs->trans('ConfirmValidateBill', $numref);
  4732. if (isModEnabled('notification')) {
  4733. require_once DOL_DOCUMENT_ROOT . '/core/class/notify.class.php';
  4734. $notify = new Notify($db);
  4735. $text .= '<br>';
  4736. $text .= $notify->confirmMessage('BILL_VALIDATE', $object->socid, $object);
  4737. }
  4738. $formquestion = array();
  4739. if ($object->type != Facture::TYPE_DEPOSIT && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
  4740. $qualified_for_stock_change = 0;
  4741. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  4742. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  4743. } else {
  4744. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  4745. }
  4746. if ($qualified_for_stock_change) {
  4747. $langs->load("stocks");
  4748. require_once DOL_DOCUMENT_ROOT . '/product/class/html.formproduct.class.php';
  4749. require_once DOL_DOCUMENT_ROOT . '/product/stock/class/entrepot.class.php';
  4750. $formproduct = new FormProduct($db);
  4751. $warehouse = new Entrepot($db);
  4752. $warehouse_array = $warehouse->list_array();
  4753. if (count($warehouse_array) == 1) {
  4754. $label = $object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE ? $langs->trans("WarehouseForStockIncrease", current($warehouse_array)) : $langs->trans("WarehouseForStockDecrease", current($warehouse_array));
  4755. $value = '<input type="hidden" id="idwarehouse" name="idwarehouse" value="' . key($warehouse_array) . '">';
  4756. } else {
  4757. $label = $object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockIncrease") : $langs->trans("SelectWarehouseForStockDecrease");
  4758. $value = $formproduct->selectWarehouses(GETPOST('idwarehouse') ? GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1);
  4759. }
  4760. $formquestion = array(
  4761. // 'text' => $langs->trans("ConfirmClone"),
  4762. // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' =>
  4763. // 1),
  4764. // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value'
  4765. // => 1),
  4766. array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $value)
  4767. );
  4768. }
  4769. }
  4770. if ($object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_RECEIPT_CREDIT_NOTE && $object->total_ttc < 0) { // Can happen only if $conf->global->FACTURE_ENABLE_NEGATIVE is on
  4771. $text .= '<br>' . img_warning() . ' ' . $langs->trans("ErrorInvoiceOfThisTypeMustBePositive");
  4772. }
  4773. // mandatoryPeriod
  4774. $nbMandated = 0;
  4775. foreach ($object->lines as $line) {
  4776. $res = $line->fetch_product();
  4777. if ($res > 0) {
  4778. if ($line->product->isService() && $line->product->isMandatoryPeriod() && (empty($line->date_start) || empty($line->date_end))) {
  4779. $nbMandated++;
  4780. break;
  4781. }
  4782. }
  4783. }
  4784. if ($nbMandated > 0)
  4785. $text .= '<div><span class="clearboth nowraponall warning">' . $langs->trans("mandatoryPeriodNeedTobeSetMsgValidate") . '</span></div>';
  4786. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?facid=' . $object->id, $langs->trans('ValidateBill'), $text, 'confirm_valid', $formquestion, (($object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_RECEIPT_CREDIT_NOTE && $object->total_ttc < 0) ? "no" : "yes"), 2);
  4787. }
  4788. // Confirm back to draft status
  4789. if ($action == 'modif') {
  4790. $text = $langs->trans('ConfirmUnvalidateBill', $object->ref);
  4791. $formquestion = array();
  4792. if ($object->type != Facture::TYPE_DEPOSIT && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
  4793. $qualified_for_stock_change = 0;
  4794. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  4795. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  4796. } else {
  4797. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  4798. }
  4799. if ($qualified_for_stock_change) {
  4800. $langs->load("stocks");
  4801. require_once DOL_DOCUMENT_ROOT . '/product/class/html.formproduct.class.php';
  4802. require_once DOL_DOCUMENT_ROOT . '/product/stock/class/entrepot.class.php';
  4803. $formproduct = new FormProduct($db);
  4804. $warehouse = new Entrepot($db);
  4805. $warehouse_array = $warehouse->list_array();
  4806. if (count($warehouse_array) == 1) {
  4807. $label = $object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE ? $langs->trans("WarehouseForStockDecrease", current($warehouse_array)) : $langs->trans("WarehouseForStockIncrease", current($warehouse_array));
  4808. $value = '<input type="hidden" id="idwarehouse" name="idwarehouse" value="' . key($warehouse_array) . '">';
  4809. } else {
  4810. $label = $object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockDecrease") : $langs->trans("SelectWarehouseForStockIncrease");
  4811. $value = $formproduct->selectWarehouses(GETPOST('idwarehouse') ? GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1);
  4812. }
  4813. $formquestion = array(
  4814. // 'text' => $langs->trans("ConfirmClone"),
  4815. // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' =>
  4816. // 1),
  4817. // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value'
  4818. // => 1),
  4819. array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $value)
  4820. );
  4821. }
  4822. }
  4823. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?facid=' . $object->id, $langs->trans('UnvalidateBill'), $text, 'confirm_modif', $formquestion, "yes", 1);
  4824. }
  4825. // Confirmation du classement paye
  4826. if ($action == 'paid' && ($resteapayer <= 0 || (!empty($conf->global->INVOICE_CAN_SET_PAID_EVEN_IF_PARTIALLY_PAID) && $resteapayer == $object->total_ttc))) {
  4827. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?facid=' . $object->id, $langs->trans('ClassifyPaid'), $langs->trans('ConfirmClassifyPaidBill', $object->ref), 'confirm_paid', '', "yes", 1);
  4828. }
  4829. if ($action == 'paid' && $resteapayer > 0 && (empty($conf->global->INVOICE_CAN_SET_PAID_EVEN_IF_PARTIALLY_PAID) || $resteapayer != $object->total_ttc)) {
  4830. $close = array();
  4831. // Code
  4832. $i = 0;
  4833. $close[$i]['code'] = 'discount_vat'; // escompte
  4834. $i++;
  4835. $close[$i]['code'] = 'badcustomer';
  4836. $i++;
  4837. $close[$i]['code'] = 'bankcharge';
  4838. $i++;
  4839. $close[$i]['code'] = 'other';
  4840. $i++;
  4841. // Help
  4842. $i = 0;
  4843. $close[$i]['label'] = $langs->trans("HelpEscompte") . '<br><br>' . $langs->trans("ConfirmClassifyPaidPartiallyReasonDiscountVatDesc");
  4844. $i++;
  4845. $close[$i]['label'] = $langs->trans("ConfirmClassifyPaidPartiallyReasonBadCustomerDesc");
  4846. $i++;
  4847. $close[$i]['label'] = $langs->trans("ConfirmClassifyPaidPartiallyReasonBankChargeDesc");
  4848. $i++;
  4849. $close[$i]['label'] = $langs->trans("Other");
  4850. $i++;
  4851. // Texte
  4852. $i = 0;
  4853. $close[$i]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonDiscount", $resteapayer, $langs->trans("Currency" . $conf->currency)), $close[$i]['label'], 1);
  4854. $i++;
  4855. $close[$i]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBadCustomer", $resteapayer, $langs->trans("Currency" . $conf->currency)), $close[$i]['label'], 1);
  4856. $i++;
  4857. $close[$i]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBankCharge", $resteapayer, $langs->trans("Currency" . $conf->currency)), $close[$i]['label'], 1);
  4858. $i++;
  4859. $close[$i]['reason'] = $form->textwithpicto($langs->transnoentities("Other"), $close[$i]['label'], 1);
  4860. $i++;
  4861. // arrayreasons[code]=reason
  4862. foreach ($close as $key => $val) {
  4863. $arrayreasons[$close[$key]['code']] = $close[$key]['reason'];
  4864. }
  4865. // Cree un tableau formulaire
  4866. $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'));
  4867. // Paiement incomplet. On demande si motif = escompte ou autre
  4868. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?facid=' . $object->id, $langs->trans('ClassifyPaid'), $langs->trans('ConfirmClassifyPaidPartially', $object->ref), 'confirm_paid_partially', $formquestion, "yes", 1, 340, 600);
  4869. }
  4870. // Confirmation du classement abandonne
  4871. if ($action == 'canceled') {
  4872. // S'il y a une facture de remplacement pas encore validee (etat brouillon),
  4873. // on ne permet pas de classer abandonner la facture.
  4874. if ($objectidnext) {
  4875. $facturereplacement = new Facture($db);
  4876. $facturereplacement->fetch($objectidnext);
  4877. $statusreplacement = $facturereplacement->statut;
  4878. }
  4879. if ($objectidnext && $statusreplacement == 0) {
  4880. print '<div class="error">' . $langs->trans("ErrorCantCancelIfReplacementInvoiceNotValidated") . '</div>';
  4881. } else {
  4882. // Code
  4883. $close[1]['code'] = 'badcustomer';
  4884. $close[2]['code'] = 'abandon';
  4885. // Help
  4886. $close[1]['label'] = $langs->trans("ConfirmClassifyPaidPartiallyReasonBadCustomerDesc");
  4887. $close[2]['label'] = $langs->trans("ConfirmClassifyAbandonReasonOtherDesc");
  4888. // Texte
  4889. $close[1]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBadCustomer", $object->ref), $close[1]['label'], 1);
  4890. $close[2]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyAbandonReasonOther"), $close[2]['label'], 1);
  4891. // arrayreasons
  4892. $arrayreasons[$close[1]['code']] = $close[1]['reason'];
  4893. $arrayreasons[$close[2]['code']] = $close[2]['reason'];
  4894. // Cree un tableau formulaire
  4895. $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'));
  4896. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $langs->trans('CancelBill'), $langs->trans('ConfirmCancelBill', $object->ref), 'confirm_canceled', $formquestion, "yes", 1, 270);
  4897. }
  4898. }
  4899. if ($action == 'deletepayment') {
  4900. $payment_id = GETPOST('paiement_id');
  4901. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id . '&paiement_id=' . $payment_id, $langs->trans('DeletePayment'), $langs->trans('ConfirmDeletePayment'), 'confirm_delete_paiement', '', 'no', 1);
  4902. }
  4903. // Confirmation de la suppression d'une ligne produit
  4904. if ($action == 'ask_deleteline') {
  4905. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?facid=' . $object->id . '&lineid=' . $lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 'no', 1);
  4906. }
  4907. // Clone confirmation
  4908. if ($action == 'clone') {
  4909. // Create an array for form
  4910. $formquestion = array(
  4911. 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)),
  4912. array('type' => 'date', 'name' => 'newdate', 'label' => $langs->trans("Date"), 'value' => dol_now())
  4913. );
  4914. // Request confirmation to clone
  4915. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?facid=' . $object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneInvoice', $object->ref), 'confirm_clone', $formquestion, 'yes', 1, 250);
  4916. }
  4917. if ($action == "remove_file_comfirm") {
  4918. $file = GETPOST('file', 'alpha');
  4919. $formconfirm = $form->formconfirm(
  4920. $_SERVER["PHP_SELF"] . '?facid=' . $object->id . '&file=' . $file,
  4921. $langs->trans('DeleteFileHeader'),
  4922. $langs->trans('DeleteFileText') . "<br><br>" . $file,
  4923. 'remove_file',
  4924. '',
  4925. 'no',
  4926. 2
  4927. );
  4928. }
  4929. // Call Hook formConfirm
  4930. $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid, 'remainingtopay' => &$resteapayer);
  4931. $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  4932. if (empty($reshook)) {
  4933. $formconfirm .= $hookmanager->resPrint;
  4934. } elseif ($reshook > 0) {
  4935. $formconfirm = $hookmanager->resPrint;
  4936. }
  4937. // Print form confirm
  4938. print $formconfirm;
  4939. // Invoice content
  4940. $linkback = '<a href="' . DOL_URL_ROOT . '/compta/facture/list.php?restore_lastsearch_values=1' . (!empty($socid) ? '&socid=' . $socid : '') . '">' . $langs->trans("BackToList") . '</a>';
  4941. $morehtmlref = '<div class="refidno">';
  4942. // Ref invoice
  4943. if ($object->status == $object::STATUS_DRAFT && !$mysoc->isInEEC() && !empty($conf->global->INVOICE_ALLOW_FREE_REF)) {
  4944. $morehtmlref .= $form->editfieldkey("Ref", 'ref', $object->ref, $object, $usercancreate, 'string', '', 0, 1);
  4945. $morehtmlref .= $form->editfieldval("Ref", 'ref', $object->ref, $object, $usercancreate, 'string', '', null, null, '', 1);
  4946. $morehtmlref .= '<br>';
  4947. }
  4948. // Ref customer
  4949. $morehtmlref .= $form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $usercancreate, 'string', '', 0, 1);
  4950. $morehtmlref .= $form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $usercancreate, 'string' . (isset($conf->global->THIRDPARTY_REF_INPUT_SIZE) ? ':' . $conf->global->THIRDPARTY_REF_INPUT_SIZE : ''), '', null, null, '', 1);
  4951. // Thirdparty
  4952. $morehtmlref .= '<br>' . $object->thirdparty->getNomUrl(1, 'customer');
  4953. if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) {
  4954. $morehtmlref .= ' (<a href="' . DOL_URL_ROOT . '/compta/facture/list.php?socid=' . $object->thirdparty->id . '&search_societe=' . urlencode($object->thirdparty->name) . '">' . $langs->trans("OtherBills") . '</a>)';
  4955. }
  4956. // Project
  4957. if (isModEnabled('project')) {
  4958. $langs->load("projects");
  4959. $morehtmlref .= '<br>';
  4960. if ($usercancreate) {
  4961. $morehtmlref .= img_picto($langs->trans("Project"), 'project', 'class="pictofixedwidth"');
  4962. if ($action != 'classify') {
  4963. $morehtmlref .= '<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&token=' . newToken() . '&id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> ';
  4964. }
  4965. $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, ($action == 'classify' ? 'projectid' : 'none'), 0, 0, 0, 1, '', 'maxwidth300');
  4966. } else {
  4967. if (!empty($object->fk_project)) {
  4968. $proj = new Project($db);
  4969. $proj->fetch($object->fk_project);
  4970. $morehtmlref .= $proj->getNomUrl(1);
  4971. if ($proj->title) {
  4972. $morehtmlref .= '<span class="opacitymedium"> - ' . dol_escape_htmltag($proj->title) . '</span>';
  4973. }
  4974. }
  4975. }
  4976. }
  4977. $morehtmlref .= '</div>';
  4978. $object->totalpaid = $totalpaid; // To give a chance to dol_banner_tab to use already paid amount to show correct status
  4979. dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0, '', '');
  4980. print '<div class="fichecenter">';
  4981. print '<div class="fichehalfleft">';
  4982. print '<div class="underbanner clearboth"></div>';
  4983. print '<input type="hidden" id="printedTicketsNumber" name="printedticketsnumber" value="'.$Bbticketcounter->numberOfPrintedTickets.'">';
  4984. print '<table class="border centpercent tableforfield">';
  4985. // Type
  4986. print '<tr><td class="titlefield fieldname_type">' . $langs->trans('Type') . '</td><td class="valuefield fieldname_type">';
  4987. print $object->getLibType(2);
  4988. if ($object->module_source) {
  4989. print ' <span class="opacitymediumbycolor paddingleft">(' . $langs->trans("POS") . ' ' . ucfirst($object->module_source) . ' - ' . $langs->trans("Terminal") . ' ' . $object->pos_source . ')</span>';
  4990. }
  4991. if ($object->type == Facture::TYPE_REPLACEMENT) {
  4992. $facreplaced = new Facture($db);
  4993. $facreplaced->fetch($object->fk_facture_source);
  4994. print ' <span class="opacitymediumbycolor paddingleft">' . $langs->transnoentities("ReplaceInvoice", $facreplaced->getNomUrl(1)) . '</span>';
  4995. }
  4996. if ($object->type == Facture::TYPE_CREDIT_NOTE && !empty($object->fk_facture_source)) {
  4997. $facusing = new Facture($db);
  4998. $facusing->fetch($object->fk_facture_source);
  4999. print ' <span class="opacitymediumbycolor paddingleft">' . $langs->transnoentities("CorrectInvoice", $facusing->getNomUrl(1)) . '</span>';
  5000. }
  5001. if ($object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE && !empty($object->fk_facture_source)) {
  5002. $facusing = new Facture($db);
  5003. $facusing->fetch($object->fk_facture_source);
  5004. print ' <span class="opacitymediumbycolor paddingleft">'.$langs->transnoentities("CorrectReceipt", $facusing->getNomUrl(1)).'</span>';
  5005. }
  5006. if ($object->type == 0 && !empty($object->fk_facture_source)) {
  5007. $facusing = new Facture($db);
  5008. $facusing->fetch($object->fk_facture_source);
  5009. print ' <span class="opacitymediumbycolor paddingleft">'.$langs->transnoentities("ReplaceInvoice", $facusing->getNomUrl(1)).'</span>';
  5010. }
  5011. $facidavoir = $object->getListIdAvoirFromInvoice();
  5012. if (count($facidavoir) > 0) {
  5013. print ' <span class="opacitymediumbycolor paddingleft">' . $langs->transnoentities("InvoiceHasAvoir");
  5014. $i = 0;
  5015. foreach ($facidavoir as $id) {
  5016. if ($i == 0) {
  5017. print ' ';
  5018. } else {
  5019. print ',';
  5020. }
  5021. $facavoir = new Facture($db);
  5022. $facavoir->fetch($id);
  5023. print $facavoir->getNomUrl(1);
  5024. }
  5025. print '</span>';
  5026. }
  5027. if ($objectidnext > 0) {
  5028. $facthatreplace = new Facture($db);
  5029. $facthatreplace->fetch($objectidnext);
  5030. print ' <span class="opacitymediumbycolor paddingleft">' . str_replace('{s1}', $facthatreplace->getNomUrl(1), $langs->transnoentities("ReplacedByInvoice", '{s1}')) . '</span>';
  5031. }
  5032. if ($object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE) {
  5033. $discount = new DiscountAbsolute($db);
  5034. $result = $discount->fetch(0, $object->id);
  5035. if ($result > 0) {
  5036. print ' <span class="opacitymediumbycolor paddingleft">';
  5037. $s = $langs->trans("CreditNoteConvertedIntoDiscount", '{s1}', '{s2}');
  5038. $s = str_replace('{s1}', $object->getLibType(0), $s);
  5039. $s = str_replace('{s2}', $discount->getNomUrl(1, 'discount'), $s);
  5040. print $s;
  5041. print '</span><br>';
  5042. }
  5043. }
  5044. if ($object->fk_fac_rec_source > 0) {
  5045. $tmptemplate = new FactureRec($db);
  5046. $result = $tmptemplate->fetch($object->fk_fac_rec_source);
  5047. if ($result > 0) {
  5048. print ' <span class="opacitymediumbycolor paddingleft">';
  5049. $s = $langs->transnoentities("GeneratedFromTemplate", '{s1}');
  5050. $s = str_replace('{s1}', '<a href="' . DOL_URL_ROOT . '/compta/facture/card-rec.php?facid=' . $tmptemplate->id . '">' . dol_escape_htmltag($tmptemplate->ref) . '</a>', $s);
  5051. print $s;
  5052. print '</span>';
  5053. }
  5054. }
  5055. print '</td></tr>';
  5056. // Relative and absolute discounts
  5057. print '<!-- Discounts -->' . "\n";
  5058. print '<tr><td>' . $langs->trans('DiscountStillRemaining') . '</td>';
  5059. print '<td>';
  5060. $thirdparty = $soc;
  5061. $discount_type = 0;
  5062. $backtopage = urlencode($_SERVER["PHP_SELF"] . '?facid=' . $object->id);
  5063. include DOL_DOCUMENT_ROOT . '/core/tpl/object_discounts.tpl.php';
  5064. print '</td></tr>';
  5065. // Date invoice
  5066. print '<tr><td>';
  5067. print '<table class="nobordernopadding centpercent"><tr><td>';
  5068. print $langs->trans('DateInvoice');
  5069. print '</td>';
  5070. if ($action != 'editinvoicedate' && !empty($object->brouillon) && $usercancreate && empty($conf->global->FAC_FORCE_DATE_VALIDATION)) {
  5071. print '<td class="right"><a class="editfielda" href="' . $_SERVER["PHP_SELF"] . '?action=editinvoicedate&token=' . newToken() . '&facid=' . $object->id . '">' . img_edit($langs->trans('SetDate'), 1) . '</a></td>';
  5072. }
  5073. print '</tr></table>';
  5074. print '</td><td>';
  5075. if ($action == 'editinvoicedate') {
  5076. $form->form_date($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->date, 'invoicedate');
  5077. } else {
  5078. print '<span class="valuedate">' . dol_print_date($object->date, 'day') . '</span>';
  5079. }
  5080. print '</td>';
  5081. print '</tr>';
  5082. if (!empty($conf->global->INVOICE_POINTOFTAX_DATE)) {
  5083. // Date invoice point of tax
  5084. print '<tr><td>';
  5085. print '<table class="nobordernopadding centpercent"><tr><td>';
  5086. print $langs->trans('DatePointOfTax');
  5087. print '</td>';
  5088. print '<td class="right"><a class="editfielda" href="' . $_SERVER["PHP_SELF"] . '?action=editdate_pointoftax&token=' . newToken() . '&facid=' . $object->id . '">' . img_edit($langs->trans('SetDate'), 1) . '</a></td>';
  5089. print '</tr></table>';
  5090. print '</td><td>';
  5091. if ($action == 'editdate_pointoftax') {
  5092. $form->form_date($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->date_pointoftax, 'date_pointoftax');
  5093. } else {
  5094. print '<span class="valuedate">' . dol_print_date($object->date_pointoftax, 'day') . '</span>';
  5095. }
  5096. print '</td></tr>';
  5097. }
  5098. // Payment term
  5099. print '<tr><td>';
  5100. print '<table class="nobordernopadding centpercent"><tr><td>';
  5101. print $langs->trans('PaymentConditionsShort');
  5102. print '</td>';
  5103. if ($object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_RECEIPT_CREDIT_NOTE && $action != 'editconditions' && $usercancreate) {
  5104. print '<td class="right"><a class="editfielda" href="' . $_SERVER["PHP_SELF"] . '?action=editconditions&token=' . newToken() . '&facid=' . $object->id . '">' . img_edit($langs->trans('SetConditions'), 1) . '</a></td>';
  5105. }
  5106. print '</tr></table>';
  5107. print '</td><td>';
  5108. if ($object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_RECEIPT_CREDIT_NOTE) {
  5109. if ($action == 'editconditions') {
  5110. $form->form_conditions_reglement($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->cond_reglement_id, 'cond_reglement_id');
  5111. } else {
  5112. $form->form_conditions_reglement($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->cond_reglement_id, 'none');
  5113. }
  5114. } else {
  5115. print '&nbsp;';
  5116. }
  5117. print '</td></tr>';
  5118. // Date payment term
  5119. print '<tr><td>';
  5120. print '<table class="nobordernopadding centpercent"><tr><td>';
  5121. print $langs->trans('DateMaxPayment');
  5122. print '</td>';
  5123. if ($object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_RECEIPT_CREDIT_NOTE && $action != 'editpaymentterm' && $usercancreate) {
  5124. print '<td class="right"><a class="editfielda" href="' . $_SERVER["PHP_SELF"] . '?action=editpaymentterm&token=' . newToken() . '&facid=' . $object->id . '">' . img_edit($langs->trans('SetDate'), 1) . '</a></td>';
  5125. }
  5126. print '</tr></table>';
  5127. print '</td><td>';
  5128. if ($object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_RECEIPT_CREDIT_NOTE) {
  5129. if ($action == 'editpaymentterm') {
  5130. $form->form_date($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->date_lim_reglement, 'paymentterm');
  5131. } else {
  5132. print '<span class="valuedate">' . dol_print_date($object->date_lim_reglement, 'day') . '</span>';
  5133. if ($object->hasDelay()) {
  5134. print img_warning($langs->trans('Late'));
  5135. }
  5136. }
  5137. } else {
  5138. print '&nbsp;';
  5139. }
  5140. print '</td></tr>';
  5141. // Payment mode
  5142. print '<tr><td>';
  5143. print '<table class="nobordernopadding centpercent"><tr><td>';
  5144. print $langs->trans('PaymentMode');
  5145. print '</td>';
  5146. if ($action != 'editmode' && $usercancreate) {
  5147. print '<td class="right"><a class="editfielda" href="' . $_SERVER["PHP_SELF"] . '?action=editmode&token=' . newToken() . '&facid=' . $object->id . '">' . img_edit($langs->trans('SetMode'), 1) . '</a></td>';
  5148. }
  5149. print '</tr></table>';
  5150. print '</td><td>';
  5151. if ($action == 'editmode') {
  5152. $form->form_modes_reglement($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->mode_reglement_id, 'mode_reglement_id', 'CRDT', 1, 1);
  5153. } else {
  5154. $form->form_modes_reglement($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->mode_reglement_id, 'none', 'CRDT');
  5155. }
  5156. print '</td></tr>';
  5157. // Multicurrency
  5158. if (isModEnabled('multicurrency')) {
  5159. // Multicurrency code
  5160. print '<tr>';
  5161. print '<td>';
  5162. print '<table class="nobordernopadding centpercent"><tr><td>';
  5163. print $form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0);
  5164. print '</td>';
  5165. if ($usercancreate && $action != 'editmulticurrencycode' && !empty($object->brouillon)) {
  5166. print '<td class="right"><a class="editfielda" href="' . $_SERVER["PHP_SELF"] . '?action=editmulticurrencycode&token=' . newToken() . '&id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1) . '</a></td>';
  5167. }
  5168. print '</tr></table>';
  5169. print '</td><td>';
  5170. $htmlname = (($usercancreate && $action == 'editmulticurrencycode') ? 'multicurrency_code' : 'none');
  5171. $form->form_multicurrency_code($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_code, $htmlname);
  5172. print '</td></tr>';
  5173. // Multicurrency rate
  5174. if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) {
  5175. print '<tr>';
  5176. print '<td>';
  5177. print '<table class="nobordernopadding" width="100%"><tr><td>';
  5178. print $form->editfieldkey('CurrencyRate', 'multicurrency_tx', '', $object, 0);
  5179. print '</td>';
  5180. if ($usercancreate && $action != 'editmulticurrencyrate' && !empty($object->brouillon) && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) {
  5181. print '<td class="right"><a class="editfielda" href="' . $_SERVER["PHP_SELF"] . '?action=editmulticurrencyrate&token=' . newToken() . '&id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1) . '</a></td>';
  5182. }
  5183. print '</tr></table>';
  5184. print '</td><td>';
  5185. if ($action == 'editmulticurrencyrate' || $action == 'actualizemulticurrencyrate') {
  5186. if ($action == 'actualizemulticurrencyrate') {
  5187. list($object->fk_multicurrency, $object->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($object->db, $object->multicurrency_code);
  5188. }
  5189. $form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_tx, ($usercancreate ? 'multicurrency_tx' : 'none'), $object->multicurrency_code);
  5190. } else {
  5191. $form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_tx, 'none', $object->multicurrency_code);
  5192. if ($object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) {
  5193. print '<div class="inline-block"> &nbsp; &nbsp; &nbsp; &nbsp; ';
  5194. print '<a href="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&action=actualizemulticurrencyrate">' . $langs->trans("ActualizeCurrency") . '</a>';
  5195. print '</div>';
  5196. }
  5197. }
  5198. print '</td></tr>';
  5199. }
  5200. }
  5201. // Bank Account
  5202. if (isModEnabled("banque")) {
  5203. print '<tr><td class="nowrap">';
  5204. print '<table class="nobordernopadding centpercent"><tr><td class="nowrap">';
  5205. print $langs->trans('BankAccount');
  5206. print '<td>';
  5207. if (($action != 'editbankaccount') && $usercancreate) {
  5208. print '<td class="right"><a class="editfielda" href="' . $_SERVER["PHP_SELF"] . '?action=editbankaccount&token=' . newToken() . '&id=' . $object->id . '">' . img_edit($langs->trans('SetBankAccount'), 1) . '</a></td>';
  5209. }
  5210. print '</tr></table>';
  5211. print '</td><td>';
  5212. if ($action == 'editbankaccount') {
  5213. $form->formSelectAccount($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->fk_account, 'fk_account', 1);
  5214. } else {
  5215. $form->formSelectAccount($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->fk_account, 'none');
  5216. }
  5217. print "</td>";
  5218. print '</tr>';
  5219. }
  5220. // Incoterms
  5221. if (isModEnabled('incoterm')) {
  5222. print '<tr><td>';
  5223. print '<table class="nobordernopadding centpercent"><tr><td>';
  5224. print $langs->trans('IncotermLabel');
  5225. print '<td><td class="right">';
  5226. if ($usercancreate) {
  5227. print '<a class="editfielda" href="' . DOL_URL_ROOT . '/compta/facture/card.php?facid=' . $object->id . '&action=editincoterm&token=' . newToken() . '">' . img_edit() . '</a>';
  5228. } else {
  5229. print '&nbsp;';
  5230. }
  5231. print '</td></tr></table>';
  5232. print '</td>';
  5233. print '<td>';
  5234. if ($action != 'editincoterm') {
  5235. print $form->textwithpicto($object->display_incoterms(), $object->label_incoterms, 1);
  5236. } else {
  5237. print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : ''), $_SERVER['PHP_SELF'] . '?id=' . $object->id);
  5238. }
  5239. print '</td></tr>';
  5240. }
  5241. if (!empty($object->retained_warranty) || !empty($conf->global->INVOICE_USE_RETAINED_WARRANTY)) {
  5242. $displayWarranty = true;
  5243. if (!in_array($object->type, $retainedWarrantyInvoiceAvailableType) && empty($object->retained_warranty)) {
  5244. $displayWarranty = false;
  5245. }
  5246. if ($displayWarranty) {
  5247. // Retained Warranty
  5248. print '<tr class="retained-warranty-lines" ><td>';
  5249. print '<table id="retained-warranty-table" class="nobordernopadding centpercent"><tr><td>';
  5250. print $langs->trans('RetainedWarranty');
  5251. print '</td>';
  5252. if ($action != 'editretainedwarranty' && $user->rights->facture->creer && $object->statut == Facture::STATUS_DRAFT) {
  5253. print '<td align="right"><a class="editfielda" href="' . $_SERVER["PHP_SELF"] . '?action=editretainedwarranty&token=' . newToken() . '&facid=' . $object->id . '">' . img_edit($langs->trans('setretainedwarranty'), 1) . '</a></td>';
  5254. }
  5255. print '</tr></table>';
  5256. print '</td><td>';
  5257. if ($action == 'editretainedwarranty' && $object->statut == Facture::STATUS_DRAFT) {
  5258. print '<form id="retained-warranty-form" method="POST" action="' . $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '">';
  5259. print '<input type="hidden" name="action" value="setretainedwarranty">';
  5260. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5261. print '<input name="retained_warranty" type="number" step="0.01" min="0" max="100" value="' . $object->retained_warranty . '" >';
  5262. print '<input type="submit" class="button valignmiddle" value="' . $langs->trans("Modify") . '">';
  5263. print '</form>';
  5264. } else {
  5265. print price($object->retained_warranty) . '%';
  5266. }
  5267. print '</td></tr>';
  5268. // Retained warranty payment term
  5269. print '<tr class="retained-warranty-lines" ><td>';
  5270. print '<table id="retained-warranty-cond-reglement-table" class="nobordernopadding" width="100%"><tr><td>';
  5271. print $langs->trans('PaymentConditionsShortRetainedWarranty');
  5272. print '</td>';
  5273. if ($action != 'editretainedwarrantypaymentterms' && $user->rights->facture->creer && $object->statut == Facture::STATUS_DRAFT) {
  5274. print '<td align="right"><a class="editfielda" href="' . $_SERVER["PHP_SELF"] . '?action=editretainedwarrantypaymentterms&token=' . newToken() . '&facid=' . $object->id . '">' . img_edit($langs->trans('setPaymentConditionsShortRetainedWarranty'), 1) . '</a></td>';
  5275. }
  5276. print '</tr></table>';
  5277. print '</td><td>';
  5278. $defaultDate = !empty($object->retained_warranty_date_limit) ? $object->retained_warranty_date_limit : strtotime('-1 years', $object->date_lim_reglement);
  5279. if ($object->date > $defaultDate) {
  5280. $defaultDate = $object->date;
  5281. }
  5282. if ($action == 'editretainedwarrantypaymentterms' && $object->statut == Facture::STATUS_DRAFT) {
  5283. //date('Y-m-d',$object->date_lim_reglement)
  5284. print '<form method="POST" action="' . $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '">';
  5285. print '<input type="hidden" name="action" value="setretainedwarrantyconditions">';
  5286. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5287. $retained_warranty_fk_cond_reglement = GETPOST('retained_warranty_fk_cond_reglement', 'int');
  5288. $retained_warranty_fk_cond_reglement = !empty($retained_warranty_fk_cond_reglement) ? $retained_warranty_fk_cond_reglement : $object->retained_warranty_fk_cond_reglement;
  5289. $retained_warranty_fk_cond_reglement = !empty($retained_warranty_fk_cond_reglement) ? $retained_warranty_fk_cond_reglement : $conf->global->INVOICE_SITUATION_DEFAULT_RETAINED_WARRANTY_COND_ID;
  5290. print $form->getSelectConditionsPaiements($retained_warranty_fk_cond_reglement, 'retained_warranty_fk_cond_reglement', -1, 1);
  5291. print '<input type="submit" class="button valignmiddle" value="' . $langs->trans("Modify") . '">';
  5292. print '</form>';
  5293. } else {
  5294. $form->form_conditions_reglement($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->retained_warranty_fk_cond_reglement, 'none');
  5295. if (!$displayWarranty) {
  5296. print img_picto($langs->trans('RetainedWarrantyNeed100Percent'), 'warning.png', 'class="pictowarning valignmiddle" ');
  5297. }
  5298. }
  5299. print '</td></tr>';
  5300. // Retained Warranty payment date limit
  5301. print '<tr class="retained-warranty-lines" ><td>';
  5302. print '<table id="retained-warranty-date-limit-table" class="nobordernopadding" width="100%"><tr><td>';
  5303. print $langs->trans('RetainedWarrantyDateLimit');
  5304. print '</td>';
  5305. if ($action != 'editretainedwarrantydatelimit' && $user->rights->facture->creer && $object->statut == Facture::STATUS_DRAFT) {
  5306. print '<td align="right"><a class="editfielda" href="' . $_SERVER["PHP_SELF"] . '?action=editretainedwarrantydatelimit&token=' . newToken() . '&facid=' . $object->id . '">' . img_edit($langs->trans('setretainedwarrantyDateLimit'), 1) . '</a></td>';
  5307. }
  5308. print '</tr></table>';
  5309. print '</td><td>';
  5310. $defaultDate = !empty($object->retained_warranty_date_limit) ? $object->retained_warranty_date_limit : strtotime('-1 years', $object->date_lim_reglement);
  5311. if ($object->date > $defaultDate) {
  5312. $defaultDate = $object->date;
  5313. }
  5314. if ($action == 'editretainedwarrantydatelimit' && $object->statut == Facture::STATUS_DRAFT) {
  5315. //date('Y-m-d',$object->date_lim_reglement)
  5316. print '<form method="POST" action="' . $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '">';
  5317. print '<input type="hidden" name="action" value="setretainedwarrantydatelimit">';
  5318. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5319. print '<input name="retained_warranty_date_limit" type="date" step="1" min="' . dol_print_date($object->date, '%Y-%m-%d') . '" value="' . dol_print_date($defaultDate, '%Y-%m-%d') . '" >';
  5320. print '<input type="submit" class="button valignmiddle" value="' . $langs->trans("Modify") . '">';
  5321. print '</form>';
  5322. } else {
  5323. print dol_print_date($object->retained_warranty_date_limit, 'day');
  5324. }
  5325. print '</td></tr>';
  5326. }
  5327. }
  5328. // Other attributes
  5329. $cols = 2;
  5330. include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php';
  5331. print '</table>';
  5332. print '</div>';
  5333. print '<div class="fichehalfright">';
  5334. print '<!-- amounts -->' . "\n";
  5335. print '<div class="underbanner clearboth"></div>' . "\n";
  5336. print '<table class="border tableforfield centpercent">';
  5337. $sign = 1;
  5338. if (!empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE_SCREEN) && $object->type == $object::TYPE_CREDIT_NOTE) {
  5339. $sign = -1; // We invert sign for output
  5340. }
  5341. if (!empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE_SCREEN) && $object->type == $object::TYPE_RECEIPT_CREDIT_NOTE) {
  5342. $sign = -1; // We invert sign for output
  5343. }
  5344. if (isModEnabled('multicurrency') && ($object->multicurrency_code != $conf->currency)) {
  5345. // Multicurrency Amount HT
  5346. print '<tr><td class="titlefieldmiddle">' . $form->editfieldkey('MulticurrencyAmountHT', 'multicurrency_total_ht', '', $object, 0) . '</td>';
  5347. print '<td class="nowrap right amountcard">' . price($sign * $object->multicurrency_total_ht, '', $langs, 0, -1, -1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '</td>';
  5348. print '</tr>';
  5349. // Multicurrency Amount VAT
  5350. print '<tr><td>' . $form->editfieldkey('MulticurrencyAmountVAT', 'multicurrency_total_tva', '', $object, 0) . '</td>';
  5351. print '<td class="nowrap right amountcard">' . price($sign * $object->multicurrency_total_tva, '', $langs, 0, -1, -1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '</td>';
  5352. print '</tr>';
  5353. // Multicurrency Amount TTC
  5354. print '<tr><td>' . $form->editfieldkey('MulticurrencyAmountTTC', 'multicurrency_total_ttc', '', $object, 0) . '</td>';
  5355. print '<td class="nowrap right amountcard">' . price($sign * $object->multicurrency_total_ttc, '', $langs, 0, -1, -1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '</td>';
  5356. print '</tr>';
  5357. }
  5358. // Amount
  5359. print '<tr><td class="titlefieldmiddle">' . $langs->trans('AmountHT') . '</td>';
  5360. print '<td class="nowrap right amountcard">' . price($sign * $object->total_ht, 1, '', 1, -1, -1, $conf->currency) . '</td></tr>';
  5361. // Vat
  5362. print '<tr><td>' . $langs->trans('AmountVAT') . '</td><td colspan="3" class="nowrap right amountcard">' . price($sign * $object->total_tva, 1, '', 1, -1, -1, $conf->currency) . '</td></tr>';
  5363. print '</tr>';
  5364. // Amount Local Taxes
  5365. if (($mysoc->localtax1_assuj == "1" && $mysoc->useLocalTax(1)) || $object->total_localtax1 != 0) { // Localtax1
  5366. print '<tr><td>' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '</td>';
  5367. print '<td class="nowrap right amountcard">' . price($sign * $object->total_localtax1, 1, '', 1, -1, -1, $conf->currency) . '</td></tr>';
  5368. }
  5369. if (($mysoc->localtax2_assuj == "1" && $mysoc->useLocalTax(2)) || $object->total_localtax2 != 0) { // Localtax2
  5370. print '<tr><td>' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '</td>';
  5371. print '<td class="nowrap right amountcard">' . price($sign * $object->total_localtax2, 1, '', 1, -1, -1, $conf->currency) . '</td></tr>';
  5372. }
  5373. // Revenue stamp
  5374. if ($selleruserevenustamp) { // Test company use revenue stamp
  5375. print '<tr><td>';
  5376. print '<table class="nobordernopadding" width="100%"><tr><td>';
  5377. print $langs->trans('RevenueStamp');
  5378. print '</td>';
  5379. if ($action != 'editrevenuestamp' && !empty($object->brouillon) && $usercancreate) {
  5380. print '<td class="right"><a class="editfielda" href="' . $_SERVER["PHP_SELF"] . '?action=editrevenuestamp&token=' . newToken() . '&facid=' . $object->id . '">' . img_edit($langs->trans('SetRevenuStamp'), 1) . '</a></td>';
  5381. }
  5382. print '</tr></table>';
  5383. print '</td><td>';
  5384. if ($action == 'editrevenuestamp') {
  5385. print '<form action="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '" method="post">';
  5386. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5387. print '<input type="hidden" name="action" value="setrevenuestamp">';
  5388. print '<input type="hidden" name="revenuestamp" id="revenuestamp_val" value="' . price2num($object->revenuestamp) . '">';
  5389. print $formother->select_revenue_stamp('', 'revenuestamp_type', $mysoc->country_code);
  5390. print ' &rarr; <span id="revenuestamp_span"></span>';
  5391. print ' <input type="submit" class="button buttongen button-save" value="' . $langs->trans('Modify') . '">';
  5392. print '</form>';
  5393. print " <script>
  5394. $(document).ready(function(){
  5395. js_recalculate_revenuestamp();
  5396. $('select[name=revenuestamp_type]').on('change',function(){
  5397. js_recalculate_revenuestamp();
  5398. });
  5399. });
  5400. function js_recalculate_revenuestamp(){
  5401. var valselected = $('select[name=revenuestamp_type]').val();
  5402. console.log('Calculate revenue stamp from '+valselected);
  5403. var revenue = 0;
  5404. if (valselected.indexOf('%') == -1)
  5405. {
  5406. revenue = valselected;
  5407. }
  5408. else
  5409. {
  5410. var revenue_type = parseFloat(valselected);
  5411. var amount_net = " . round($object->total_ht, 2) . ";
  5412. revenue = revenue_type * amount_net / 100;
  5413. revenue = revenue.toFixed(2);
  5414. }
  5415. $('#revenuestamp_val').val(revenue);
  5416. $('#revenuestamp_span').html(revenue);
  5417. }
  5418. </script>";
  5419. } else {
  5420. print price($object->revenuestamp, 1, '', 1, -1, -1, $conf->currency);
  5421. }
  5422. print '</td></tr>';
  5423. }
  5424. // Total with tax
  5425. print '<tr><td>' . $langs->trans('AmountTTC') . '</td><td class="nowrap right amountcard">' . price($sign * $object->total_ttc, 1, '', 1, -1, -1, $conf->currency) . '</td></tr>';
  5426. print '</table>';
  5427. $nbrows = 8;
  5428. $nbcols = 3;
  5429. if (isModEnabled('project')) {
  5430. $nbrows++;
  5431. }
  5432. if (isModEnabled("banque")) {
  5433. $nbrows++;
  5434. $nbcols++;
  5435. }
  5436. if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) {
  5437. $nbrows++;
  5438. }
  5439. if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) {
  5440. $nbrows++;
  5441. }
  5442. if ($selleruserevenustamp) {
  5443. $nbrows++;
  5444. }
  5445. if (isModEnabled('multicurrency')) {
  5446. $nbrows += 5;
  5447. }
  5448. if (isModEnabled('incoterm')) {
  5449. $nbrows += 1;
  5450. }
  5451. // List of previous situation invoices
  5452. if (($object->situation_cycle_ref > 0) && !empty($conf->global->INVOICE_USE_SITUATION)) {
  5453. print '<!-- List of situation invoices -->';
  5454. print '<table class="noborder situationstable" width="100%">';
  5455. print '<tr class="liste_titre">';
  5456. print '<td>' . $langs->trans('ListOfSituationInvoices') . '</td>';
  5457. print '<td></td>';
  5458. print '<td class="center">' . $langs->trans('Situation') . '</td>';
  5459. if (isModEnabled("banque")) {
  5460. print '<td class="right"></td>';
  5461. }
  5462. print '<td class="right">' . $langs->trans('AmountHT') . '</td>';
  5463. print '<td class="right">' . $langs->trans('AmountTTC') . '</td>';
  5464. print '<td width="18">&nbsp;</td>';
  5465. print '</tr>';
  5466. $total_prev_ht = $total_prev_ttc = 0;
  5467. $total_global_ht = $total_global_ttc = 0;
  5468. if (count($object->tab_previous_situation_invoice) > 0) {
  5469. // List of previous invoices
  5470. $current_situation_counter = array();
  5471. foreach ($object->tab_previous_situation_invoice as $prev_invoice) {
  5472. $tmptotalpaidforthisinvoice = $prev_invoice->getSommePaiement();
  5473. $total_prev_ht += $prev_invoice->total_ht;
  5474. $total_prev_ttc += $prev_invoice->total_ttc;
  5475. $current_situation_counter[] = (($prev_invoice->type == Facture::TYPE_CREDIT_NOTE || $prev_invoice->type == Facture::TYPE_RECEIPT_CREDIT_NOTE) ? -1 : 1) * $prev_invoice->situation_counter;
  5476. print '<tr class="oddeven">';
  5477. print '<td>' . $prev_invoice->getNomUrl(1) . '</td>';
  5478. print '<td></td>';
  5479. print '<td align="center" >' . (($prev_invoice->type == Facture::TYPE_CREDIT_NOTE || $prev_invoice->type == Facture::TYPE_RECEIPT_CREDIT_NOTE) ? $langs->trans('situationInvoiceShortcode_AS') : $langs->trans('situationInvoiceShortcode_S')) . $prev_invoice->situation_counter . '</td>';
  5480. if (isModEnabled("banque")) {
  5481. print '<td class="right"></td>';
  5482. }
  5483. print '<td class="right"><span class="amount">' . price($prev_invoice->total_ht) . '</span></td>';
  5484. print '<td class="right"><span class="amount">' . price($prev_invoice->total_ttc) . '</span></td>';
  5485. print '<td class="right">' . $prev_invoice->getLibStatut(3, $tmptotalpaidforthisinvoice) . '</td>';
  5486. print '</tr>';
  5487. }
  5488. }
  5489. $total_global_ht += $total_prev_ht;
  5490. $total_global_ttc += $total_prev_ttc;
  5491. $total_global_ht += $object->total_ht;
  5492. $total_global_ttc += $object->total_ttc;
  5493. $current_situation_counter[] = (($object->type == Facture::TYPE_CREDIT_NOTE || $prev_invoice->type == Facture::TYPE_RECEIPT_CREDIT_NOTE) ? -1 : 1) * $object->situation_counter;
  5494. print '<tr class="oddeven">';
  5495. print '<td>' . $object->getNomUrl(1) . '</td>';
  5496. print '<td></td>';
  5497. print '<td class="center">' . (($object->type == Facture::TYPE_CREDIT_NOTE || $prev_invoice->type == Facture::TYPE_RECEIPT_CREDIT_NOTE) ? $langs->trans('situationInvoiceShortcode_AS') : $langs->trans('situationInvoiceShortcode_S')) . $object->situation_counter . '</td>';
  5498. if (isModEnabled("banque")) {
  5499. print '<td class="right"></td>';
  5500. }
  5501. print '<td class="right"><span class="amount">' . price($object->total_ht) . '</span></td>';
  5502. print '<td class="right"><span class="amount">' . price($object->total_ttc) . '</span></td>';
  5503. print '<td class="right">' . $object->getLibStatut(3, $object->getSommePaiement()) . '</td>';
  5504. print '</tr>';
  5505. print '<tr class="oddeven">';
  5506. print '<td colspan="2" class="left"><b>' . $langs->trans('CurrentSituationTotal') . '</b></td>';
  5507. print '<td>';
  5508. $i = 0;
  5509. foreach ($current_situation_counter as $sit) {
  5510. $curSign = $sit > 0 ? '+' : '-';
  5511. $curType = $sit > 0 ? $langs->trans('situationInvoiceShortcode_S') : $langs->trans('situationInvoiceShortcode_AS');
  5512. if ($i > 0) {
  5513. print ' ' . $curSign . ' ';
  5514. }
  5515. print $curType . abs($sit);
  5516. $i++;
  5517. }
  5518. print '</td>';
  5519. if (isModEnabled("banque")) {
  5520. print '<td></td>';
  5521. }
  5522. print '<td class="right"><b>' . price($total_global_ht) . '</b></td>';
  5523. print '<td class="right"><b>' . price($total_global_ttc) . '</b></td>';
  5524. print '<td width="18">&nbsp;</td>';
  5525. print '</tr>';
  5526. if (count($object->tab_next_situation_invoice) > 0) {
  5527. // List of next invoices
  5528. /*print '<tr class="liste_titre">';
  5529. print '<td>' . $langs->trans('ListOfNextSituationInvoices') . '</td>';
  5530. print '<td></td>';
  5531. print '<td></td>';
  5532. if (isModEnabled('banque')) print '<td class="right"></td>';
  5533. print '<td class="right">' . $langs->trans('AmountHT') . '</td>';
  5534. print '<td class="right">' . $langs->trans('AmountTTC') . '</td>';
  5535. print '<td width="18">&nbsp;</td>';
  5536. print '</tr>';*/
  5537. $total_next_ht = $total_next_ttc = 0;
  5538. foreach ($object->tab_next_situation_invoice as $next_invoice) {
  5539. $totalpaid = $next_invoice->getSommePaiement();
  5540. $total_next_ht += $next_invoice->total_ht;
  5541. $total_next_ttc += $next_invoice->total_ttc;
  5542. print '<tr class="oddeven">';
  5543. print '<td>' . $next_invoice->getNomUrl(1) . '</td>';
  5544. print '<td></td>';
  5545. print '<td class="center">' . (($next_invoice->type == Facture::TYPE_CREDIT_NOTE || $next_invoice->type == Facture::TYPE_RECEIPT_CREDIT_NOTE) ? $langs->trans('situationInvoiceShortcode_AS') : $langs->trans('situationInvoiceShortcode_S')) . $next_invoice->situation_counter . '</td>';
  5546. if (isModEnabled("banque")) {
  5547. print '<td class="right"></td>';
  5548. }
  5549. print '<td class="right"><span class="amount">' . price($next_invoice->total_ht) . '</span></td>';
  5550. print '<td class="right"><span class="amount">' . price($next_invoice->total_ttc) . '</span></td>';
  5551. print '<td class="right">' . $next_invoice->getLibStatut(3, $totalpaid) . '</td>';
  5552. print '</tr>';
  5553. }
  5554. $total_global_ht += $total_next_ht;
  5555. $total_global_ttc += $total_next_ttc;
  5556. print '<tr class="oddeven">';
  5557. print '<td colspan="3" class="right"></td>';
  5558. if (isModEnabled("banque")) {
  5559. print '<td class="right"></td>';
  5560. }
  5561. print '<td class="right"><b>' . price($total_global_ht) . '</b></td>';
  5562. print '<td class="right"><b>' . price($total_global_ttc) . '</b></td>';
  5563. print '<td width="18">&nbsp;</td>';
  5564. print '</tr>';
  5565. }
  5566. print '</table>';
  5567. }
  5568. $sign = 1;
  5569. if ($object->type == $object::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE) {
  5570. $sign = -1;
  5571. }
  5572. // List of payments already done
  5573. print '<!-- List of payments already done -->';
  5574. print '<div class="div-table-responsive-no-min">';
  5575. print '<table class="noborder paymenttable centpercent">';
  5576. print '<tr class="liste_titre">';
  5577. print '<td class="liste_titre">' . ($object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE ? $langs->trans("PaymentsBack") : $langs->trans('Payments')) . '</td>';
  5578. print '<td class="liste_titre"><span class="hideonsmartphone">' . $langs->trans('Date') . '</span></td>';
  5579. print '<td class="liste_titre"><span class="hideonsmartphone">' . $langs->trans('Type') . '</span></td>';
  5580. if (isModEnabled("banque")) {
  5581. print '<td class="liste_titre"><span class="hideonsmartphone">' . $langs->trans('BankAccount') . '</span></td>';
  5582. }
  5583. print '<td class="liste_titre right">' . $langs->trans('Amount') . '</td>';
  5584. print '<td class="liste_titre" width="18">&nbsp;</td>';
  5585. print '</tr>';
  5586. // Payments already done (from payment on this invoice)
  5587. $sql = 'SELECT p.datep as dp, p.ref, p.num_paiement as num_payment, p.rowid, p.fk_bank,';
  5588. $sql .= ' c.code as payment_code, c.libelle as payment_label,';
  5589. $sql .= ' pf.amount,';
  5590. $sql .= ' ba.rowid as baid, ba.ref as baref, ba.label, ba.number as banumber, ba.account_number, ba.fk_accountancy_journal, ba.currency_code as bacurrency_code';
  5591. $sql .= ' FROM ' . MAIN_DB_PREFIX . 'paiement_facture as pf, ' . MAIN_DB_PREFIX . 'paiement as p';
  5592. $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'c_paiement as c ON p.fk_paiement = c.id';
  5593. $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'bank as b ON p.fk_bank = b.rowid';
  5594. $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'bank_account as ba ON b.fk_account = ba.rowid';
  5595. $sql .= ' WHERE pf.fk_facture = ' . ((int) $object->id) . ' AND pf.fk_paiement = p.rowid';
  5596. $sql .= ' AND p.entity IN (' . getEntity('invoice') . ')';
  5597. $sql .= ' ORDER BY p.datep, p.tms';
  5598. $result = $db->query($sql);
  5599. if ($result) {
  5600. $num = $db->num_rows($result);
  5601. $i = 0;
  5602. if ($num > 0) {
  5603. while ($i < $num) {
  5604. $objp = $db->fetch_object($result);
  5605. $paymentstatic->id = $objp->rowid;
  5606. $paymentstatic->datepaye = $db->jdate($objp->dp);
  5607. $paymentstatic->ref = $objp->ref;
  5608. $paymentstatic->num_payment = $objp->num_payment;
  5609. $paymentstatic->paiementcode = $objp->payment_code;
  5610. print '<tr class="oddeven"><td class="nowraponall">';
  5611. print $paymentstatic->getNomUrl(1);
  5612. print '</td>';
  5613. print '<td>';
  5614. $dateofpayment = $db->jdate($objp->dp);
  5615. $tmparray = dol_getdate($dateofpayment);
  5616. if ($tmparray['seconds'] == 0 && $tmparray['minutes'] == 0 && ($tmparray['hours'] == 0 || $tmparray['hours'] == 12)) { // We set hours to 0:00 or 12:00 because we don't know it
  5617. print dol_print_date($dateofpayment, 'day');
  5618. } else { // Hours was set to real date of payment (special case for POS for example)
  5619. print dol_print_date($dateofpayment, 'dayhour', 'tzuser');
  5620. }
  5621. print '</td>';
  5622. $label = ($langs->trans("PaymentType" . $objp->payment_code) != ("PaymentType" . $objp->payment_code)) ? $langs->trans("PaymentType" . $objp->payment_code) : $objp->payment_label;
  5623. print '<td>' . $label . ' ' . $objp->num_payment . '</td>';
  5624. if (isModEnabled("banque")) {
  5625. $bankaccountstatic->id = $objp->baid;
  5626. $bankaccountstatic->ref = $objp->baref;
  5627. $bankaccountstatic->label = $objp->baref;
  5628. $bankaccountstatic->number = $objp->banumber;
  5629. $bankaccountstatic->currency_code = $objp->bacurrency_code;
  5630. if (isModEnabled('accounting')) {
  5631. $bankaccountstatic->account_number = $objp->account_number;
  5632. $accountingjournal = new AccountingJournal($db);
  5633. $accountingjournal->fetch($objp->fk_accountancy_journal);
  5634. $bankaccountstatic->accountancy_journal = $accountingjournal->getNomUrl(0, 1, 1, '', 1);
  5635. }
  5636. print '<td class="nowraponall">';
  5637. if ($bankaccountstatic->id) {
  5638. print $bankaccountstatic->getNomUrl(1, 'transactions');
  5639. }
  5640. print '</td>';
  5641. }
  5642. print '<td class="right"><span class="amount">' . price($sign * $objp->amount) . '</span></td>';
  5643. print '<td class="center">';
  5644. if ($object->statut == Facture::STATUS_VALIDATED && $object->paye == 0 && $user->socid == 0) {
  5645. print '<a href="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&action=deletepayment&token=' . newToken() . '&paiement_id=' . $objp->rowid . '">';
  5646. print img_delete();
  5647. print '</a>';
  5648. }
  5649. print '</td>';
  5650. print '</tr>';
  5651. $i++;
  5652. }
  5653. }
  5654. $db->free($result);
  5655. } else {
  5656. dol_print_error($db);
  5657. }
  5658. if ($object->type != Facture::TYPE_CREDIT_NOTE || $object->type != Facture::TYPE_RECEIPT_CREDIT_NOTE) {
  5659. // Total already paid
  5660. print '<tr><td colspan="' . $nbcols . '" class="right">';
  5661. print '<span class="opacitymedium">';
  5662. if ($object->type != Facture::TYPE_DEPOSIT) {
  5663. print $langs->trans('AlreadyPaidNoCreditNotesNoDeposits');
  5664. } else {
  5665. print $langs->trans('AlreadyPaid');
  5666. }
  5667. print '</span></td><td class="right' . (($totalpaid > 0) ? ' amountalreadypaid' : '') . '">' . price($totalpaid) . '</td><td>&nbsp;</td></tr>';
  5668. $resteapayeraffiche = $resteapayer;
  5669. $cssforamountpaymentcomplete = 'amountpaymentcomplete';
  5670. // Loop on each credit note or deposit amount applied
  5671. $creditnoteamount = 0;
  5672. $depositamount = 0;
  5673. $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
  5674. $sql .= " re.description, re.fk_facture_source";
  5675. $sql .= " FROM " . MAIN_DB_PREFIX . "societe_remise_except as re";
  5676. $sql .= " WHERE fk_facture = " . ((int) $object->id);
  5677. $resql = $db->query($sql);
  5678. if ($resql) {
  5679. $num = $db->num_rows($resql);
  5680. $i = 0;
  5681. $invoice = new Facture($db);
  5682. while ($i < $num) {
  5683. $obj = $db->fetch_object($resql);
  5684. $invoice->fetch($obj->fk_facture_source);
  5685. print '<tr><td colspan="' . $nbcols . '" class="right">';
  5686. print '<span class="opacitymedium">';
  5687. if ($invoice->type == Facture::TYPE_CREDIT_NOTE) {
  5688. print $langs->trans("CreditNote") . ' ';
  5689. }
  5690. if ($invoice->type == Facture::TYPE_RECEIPT_CREDIT_NOTE) {
  5691. print $langs->trans("ReceiptCreditNote").' ';
  5692. }
  5693. if ($invoice->type == Facture::TYPE_DEPOSIT) {
  5694. print $langs->trans("Deposit") . ' ';
  5695. }
  5696. print $invoice->getNomUrl(0);
  5697. print '</span>';
  5698. print '</td>';
  5699. print '<td class="right"><span class="amount">' . price($obj->amount_ttc) . '</span></td>';
  5700. print '<td class="right">';
  5701. print '<a href="' . $_SERVER["PHP_SELF"] . '?facid=' . $object->id . '&action=unlinkdiscount&token=' . newToken() . '&discountid=' . $obj->rowid . '">' . img_delete() . '</a>';
  5702. print '</td></tr>';
  5703. $i++;
  5704. if ($invoice->type == Facture::TYPE_CREDIT_NOTE || $invoice->type == Facture::TYPE_RECEIPT_CREDIT_NOTE) {
  5705. $creditnoteamount += $obj->amount_ttc;
  5706. }
  5707. if ($invoice->type == Facture::TYPE_DEPOSIT) {
  5708. $depositamount += $obj->amount_ttc;
  5709. }
  5710. }
  5711. } else {
  5712. dol_print_error($db);
  5713. }
  5714. // Paye partiellement 'escompte'
  5715. if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'discount_vat') {
  5716. print '<tr><td colspan="' . $nbcols . '" class="nowrap right">';
  5717. print '<span class="opacitymedium">';
  5718. print $form->textwithpicto($langs->trans("Discount"), $langs->trans("HelpEscompte"), -1);
  5719. print '</span>';
  5720. print '</td><td class="right"><span class="amount">' . price(price2num($object->total_ttc - $creditnoteamount - $depositamount - $totalpaid, 'MT')) . '</span></td><td>&nbsp;</td></tr>';
  5721. $resteapayeraffiche = 0;
  5722. $cssforamountpaymentcomplete = 'amountpaymentneutral';
  5723. }
  5724. // Paye partiellement ou Abandon 'badcustomer'
  5725. if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'badcustomer') {
  5726. print '<tr><td colspan="' . $nbcols . '" class="nowrap right">';
  5727. print '<span class="opacitymedium">';
  5728. print $form->textwithpicto($langs->trans("Abandoned"), $langs->trans("HelpAbandonBadCustomer"), -1);
  5729. print '</span>';
  5730. print '</td><td class="right">' . price(price2num($object->total_ttc - $creditnoteamount - $depositamount - $totalpaid, 'MT')) . '</td><td>&nbsp;</td></tr>';
  5731. // $resteapayeraffiche=0;
  5732. $cssforamountpaymentcomplete = 'amountpaymentneutral';
  5733. }
  5734. // Paye partiellement ou Abandon 'product_returned'
  5735. if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'product_returned') {
  5736. print '<tr><td colspan="' . $nbcols . '" class="nowrap right">';
  5737. print '<span class="opacitymedium">';
  5738. print $form->textwithpicto($langs->trans("ProductReturned"), $langs->trans("HelpAbandonProductReturned"), -1);
  5739. print '</span>';
  5740. print '</td><td class="right"><span class="amount">' . price(price2num($object->total_ttc - $creditnoteamount - $depositamount - $totalpaid, 'MT')) . '</span></td><td>&nbsp;</td></tr>';
  5741. $resteapayeraffiche = 0;
  5742. $cssforamountpaymentcomplete = 'amountpaymentneutral';
  5743. }
  5744. // Paye partiellement ou Abandon 'abandon'
  5745. if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'abandon') {
  5746. print '<tr><td colspan="' . $nbcols . '" class="nowrap right">';
  5747. $text = $langs->trans("HelpAbandonOther");
  5748. if ($object->close_note) {
  5749. $text .= '<br><br><b>' . $langs->trans("Reason") . '</b>:' . $object->close_note;
  5750. }
  5751. print '<span class="opacitymedium">';
  5752. print $form->textwithpicto($langs->trans("Abandoned"), $text, -1);
  5753. print '</span>';
  5754. print '</td><td class="right"><span class="amount">' . price(price2num($object->total_ttc - $creditnoteamount - $depositamount - $totalpaid, 'MT')) . '</span></td><td>&nbsp;</td></tr>';
  5755. $resteapayeraffiche = 0;
  5756. $cssforamountpaymentcomplete = 'amountpaymentneutral';
  5757. }
  5758. // Billed
  5759. print '<tr><td colspan="' . $nbcols . '" class="right">';
  5760. print '<span class="opacitymedium">';
  5761. print $langs->trans("Billed");
  5762. print '</td><td class="right">' . price($object->total_ttc) . '</td><td>&nbsp;</td></tr>';
  5763. // Remainder to pay
  5764. print '<tr><td colspan="' . $nbcols . '" class="right">';
  5765. print '<span class="opacitymedium">';
  5766. print $langs->trans('RemainderToPay');
  5767. if ($resteapayeraffiche < 0) {
  5768. print ' (' . $langs->trans('NegativeIfExcessReceived') . ')';
  5769. }
  5770. print '</span>';
  5771. print '</td>';
  5772. print '<td class="right' . ($resteapayeraffiche ? ' amountremaintopay' : (' ' . $cssforamountpaymentcomplete)) . '">' . price($resteapayeraffiche) . '</td><td>&nbsp;</td></tr>';
  5773. // Remainder to pay Multicurrency
  5774. if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) {
  5775. print '<tr><td colspan="' . $nbcols . '" class="right">';
  5776. print '<span class="opacitymedium">';
  5777. print $langs->trans('RemainderToPayMulticurrency');
  5778. if ($resteapayeraffiche < 0) {
  5779. print ' (' . $langs->trans('NegativeIfExcessReceived') . ')';
  5780. }
  5781. print '</span>';
  5782. print '</td>';
  5783. print '<td class="right' . ($resteapayeraffiche ? ' amountremaintopay' : (' ' . $cssforamountpaymentcomplete)) . '">';
  5784. //print (empty($object->multicurrency_code) ? $conf->currency : $object->multicurrency_code).' ';
  5785. print price(price2num($object->multicurrency_tx * $resteapayeraffiche, 'MT'), 1, $langs, 1, -1, -1, (empty($object->multicurrency_code) ? $conf->currency : $object->multicurrency_code)) . '</td><td>&nbsp;</td></tr>';
  5786. }
  5787. // Retained warranty : usualy use on construction industry
  5788. if (!empty($object->situation_final) && !empty($object->retained_warranty) && $displayWarranty) {
  5789. // Billed - retained warranty
  5790. if ($object->type == Facture::TYPE_SITUATION) {
  5791. $retainedWarranty = $total_global_ttc * $object->retained_warranty / 100;
  5792. } else {
  5793. // Because one day retained warranty could be used on standard invoices
  5794. $retainedWarranty = $object->total_ttc * $object->retained_warranty / 100;
  5795. }
  5796. $billedWithRetainedWarranty = $object->total_ttc - $retainedWarranty;
  5797. print '<tr><td colspan="' . $nbcols . '" align="right">' . $langs->trans("ToPayOn", dol_print_date($object->date_lim_reglement, 'day')) . ' :</td><td align="right">' . price($billedWithRetainedWarranty) . '</td><td>&nbsp;</td></tr>';
  5798. // retained warranty
  5799. print '<tr><td colspan="' . $nbcols . '" align="right">';
  5800. print $langs->trans("RetainedWarranty") . ' (' . $object->retained_warranty . '%)';
  5801. print !empty($object->retained_warranty_date_limit) ? ' ' . $langs->trans("ToPayOn", dol_print_date($object->retained_warranty_date_limit, 'day')) : '';
  5802. print ' :</td><td align="right">' . price($retainedWarranty) . '</td><td>&nbsp;</td></tr>';
  5803. }
  5804. } else { // Credit note
  5805. $resteapayeraffiche = $resteapayer;
  5806. $cssforamountpaymentcomplete = 'amountpaymentneutral';
  5807. // Total already paid back
  5808. print '<tr><td colspan="' . $nbcols . '" class="right">';
  5809. print '<span class="opacitymedium">' . $langs->trans('AlreadyPaidBack') . '</span>';
  5810. print '</td><td class="right"><span class="amount">' . price($sign * $totalpaid) . '</span></td><td>&nbsp;</td></tr>';
  5811. // Billed
  5812. print '<tr><td colspan="' . $nbcols . '" class="right"><span class="opacitymedium">' . $langs->trans("Billed") . '</span></td><td class="right">' . price($sign * $object->total_ttc) . '</td><td>&nbsp;</td></tr>';
  5813. // Remainder to pay back
  5814. print '<tr><td colspan="' . $nbcols . '" class="right">';
  5815. print '<span class="opacitymedium">' . $langs->trans('RemainderToPayBack');
  5816. if ($resteapayeraffiche > 0) {
  5817. print ' (' . $langs->trans('NegativeIfExcessRefunded') . ')';
  5818. }
  5819. print '</span></td>';
  5820. print '<td class="right' . ($resteapayeraffiche ? ' amountremaintopayback' : (' ' . $cssforamountpaymentcomplete)) . '">' . price($sign * $resteapayeraffiche) . '</td>';
  5821. print '<td class="nowrap">&nbsp;</td></tr>';
  5822. // Remainder to pay back Multicurrency
  5823. if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) {
  5824. print '<tr><td colspan="' . $nbcols . '" class="right">';
  5825. print '<span class="opacitymedium">' . $langs->trans('RemainderToPayBackMulticurrency');
  5826. if ($resteapayeraffiche > 0) {
  5827. print ' (' . $langs->trans('NegativeIfExcessRefunded') . ')';
  5828. }
  5829. print '</span>';
  5830. print '</td>';
  5831. print '<td class="right' . ($resteapayeraffiche ? ' amountremaintopayback' : (' ' . $cssforamountpaymentcomplete)) . '">' . (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency) . ' ' . price(price2num($sign * $object->multicurrency_tx * $resteapayeraffiche, 'MT')) . '</td><td>&nbsp;</td></tr>';
  5832. }
  5833. // Sold credit note
  5834. // print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans('TotalTTC').' :</td>';
  5835. // print '<td class="right" style="border: 1px solid;" bgcolor="#f0f0f0"><b>'.price($sign *
  5836. // $object->total_ttc).'</b></td><td>&nbsp;</td></tr>';
  5837. }
  5838. print '</table>';
  5839. print '</div>';
  5840. // Margin Infos
  5841. if (isModEnabled('margin')) {
  5842. $formmargin->displayMarginInfos($object);
  5843. }
  5844. print '</div>';
  5845. print '</div>';
  5846. print '<div class="clearboth"></div><br><br>';
  5847. if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) {
  5848. $blocname = 'contacts';
  5849. $title = $langs->trans('ContactsAddresses');
  5850. include DOL_DOCUMENT_ROOT . '/core/tpl/bloc_showhide.tpl.php';
  5851. }
  5852. if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) {
  5853. $blocname = 'notes';
  5854. $title = $langs->trans('Notes');
  5855. include DOL_DOCUMENT_ROOT . '/core/tpl/bloc_showhide.tpl.php';
  5856. }
  5857. // Get object lines
  5858. $result = $object->getLinesArray();
  5859. // Add products/services form
  5860. //$forceall = 1;
  5861. global $inputalsopricewithtax;
  5862. $inputalsopricewithtax = 1;
  5863. // Show global modifiers for situation invoices
  5864. if (!empty($conf->global->INVOICE_USE_SITUATION)) {
  5865. if ($object->situation_cycle_ref && $object->statut == 0) {
  5866. print '<!-- Area to change globally the situation percent -->' . "\n";
  5867. print '<div class="div-table-responsive">';
  5868. print '<form name="updatealllines" id="updatealllines" action="' . $_SERVER['PHP_SELF'] . '?id=' . $object->id . '#updatealllines" method="POST">';
  5869. print '<input type="hidden" name="token" value="' . newToken() . '" />';
  5870. print '<input type="hidden" name="action" value="updatealllines" />';
  5871. print '<input type="hidden" name="id" value="' . $object->id . '" />';
  5872. print '<table id="tablelines_all_progress" class="noborder noshadow" width="100%">';
  5873. print '<tr class="liste_titre nodrag nodrop">';
  5874. // Adds a line numbering column
  5875. if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) {
  5876. print '<td align="center" width="5">&nbsp;</td>';
  5877. }
  5878. print '<td class="minwidth500imp">' . $langs->trans('ModifyAllLines') . '</td>';
  5879. print '<td class="right">' . $langs->trans('Progress') . '</td>';
  5880. print '<td>&nbsp;</td>';
  5881. print "</tr>\n";
  5882. print '<tr class="nodrag nodrop">';
  5883. // Adds a line numbering column
  5884. if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) {
  5885. print '<td align="center" width="5">&nbsp;</td>';
  5886. }
  5887. print '<td>&nbsp;</td>';
  5888. print '<td class="nowrap right"><input type="text" size="1" value="" name="all_progress">%</td>';
  5889. print '<td class="right"><input type="submit" class="button" name="all_percent" value="Modifier" /></td>';
  5890. print '</tr>';
  5891. print '</table>';
  5892. print '</form>';
  5893. print '</div>';
  5894. }
  5895. }
  5896. print ' <form name="addproduct" id="addproduct" action="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '" method="POST">
  5897. <input type="hidden" name="token" value="' . newToken() . '">
  5898. <input type="hidden" name="action" value="' . (($action != 'editline') ? 'addline' : 'updateline') . '">
  5899. <input type="hidden" name="mode" value="">
  5900. <input type="hidden" name="page_y" value="">
  5901. <input type="hidden" name="id" value="' . $object->id . '">
  5902. ';
  5903. if (!empty($conf->use_javascript_ajax) && $object->statut == 0) {
  5904. include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php';
  5905. }
  5906. print '<div class="div-table-responsive-no-min">';
  5907. print '<table id="tablelines" class="noborder noshadow" width="100%">';
  5908. // Show object lines
  5909. $objectCount = count($object->lines);
  5910. if (!empty($object->lines)) {
  5911. $object->printObjectLines($action, $mysoc, $soc, $lineid, 1);
  5912. }
  5913. //if ($objectCount < 1) {
  5914. // Form to add new line
  5915. if ($object->statut == 0 && $usercancreate && $action != 'valid' && $action != 'editline') {
  5916. if ($action != 'editline' && $action != 'selectlines') {
  5917. // Add free products/services
  5918. $parameters = array();
  5919. $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  5920. if ($reshook < 0)
  5921. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  5922. if (empty($reshook))
  5923. $object->formAddObjectLine(1, $mysoc, $soc);
  5924. }
  5925. }
  5926. //}
  5927. print "</table>\n";
  5928. print "</div>";
  5929. print "</form>\n";
  5930. print dol_get_fiche_end();
  5931. // Actions buttons
  5932. if ($action != 'prerelance' && $action != 'presend' && $action != 'valid' && $action != 'editline') {
  5933. print '<div class="tabsAction">';
  5934. $parameters = array();
  5935. $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  5936. if (empty($reshook)) {
  5937. $params = array(
  5938. 'attr' => array(
  5939. 'class' => 'classfortooltip'
  5940. )
  5941. );
  5942. // Editer une facture deja validee, sans paiement effectue et pas exporte en compta
  5943. if ($object->statut == Facture::STATUS_VALIDATED) {
  5944. // We check if lines of invoice are not already transfered into accountancy
  5945. $ventilExportCompta = $object->getVentilExportCompta();
  5946. if ($ventilExportCompta == 0) {
  5947. if (!empty($conf->global->INVOICE_CAN_BE_EDITED_EVEN_IF_PAYMENT_DONE) || ($resteapayer == price2num($object->total_ttc, 'MT', 1) && empty($object->paye))) {
  5948. if (!$objectidnext && $object->is_last_in_cycle()) {
  5949. if ($usercanunvalidate) {
  5950. print dolGetButtonAction($langs->trans('Modify'), '', 'default', $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '&action=modif&token=' . newToken(), '', true, $params);
  5951. } else {
  5952. $params['attr']['title'] = $langs->trans('NotEnoughPermissions');
  5953. print dolGetButtonAction($langs->trans('Modify'), '', 'default', $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '&action=modif&token=' . newToken(), '', false, $params);
  5954. }
  5955. } elseif (!$object->is_last_in_cycle()) {
  5956. $params['attr']['title'] = $langs->trans('NotLastInCycle');
  5957. print dolGetButtonAction($langs->trans('Modify'), '', 'default', '#', '', false, $params);
  5958. } else {
  5959. $params['attr']['title'] = $langs->trans('DisabledBecauseReplacedInvoice');
  5960. print dolGetButtonAction($langs->trans('Modify'), '', 'default', '#', '', false, $params);
  5961. }
  5962. }
  5963. } else {
  5964. $params['attr']['title'] = $langs->trans('DisabledBecauseDispatchedInBookkeeping');
  5965. print dolGetButtonAction($langs->trans('Modify'), '', 'default', '#', '', false, $params);
  5966. }
  5967. }
  5968. $discount = new DiscountAbsolute($db);
  5969. $result = $discount->fetch(0, $object->id);
  5970. /** **************************************************************************************
  5971. *
  5972. * NTAK BUTTONS
  5973. *
  5974. ************************************************************************************** */
  5975. if ($conf->ntak->enabled && $object->statut == Facture::STATUS_CLOSED) {
  5976. // send ntak button
  5977. if (empty($object->array_options['options_ntak_id']) || $object->array_options['options_ntak_status'] == NtakConst::INVOICE_SENDING_RESPONSE_STATUS_SEND_AGAIN) {
  5978. print dolGetButtonAction($langs->trans('NtakSendBtn'), '', 'default', $_SERVER['PHP_SELF'].'?facid='.$object->id.'&action=sendntak&token='.newToken(), '', true, $params);
  5979. }
  5980. // get ntak status button
  5981. if (in_array($object->array_options['options_ntak_status'], [NtakConst::INVOICE_SENDING_RESPONSE_STATUS_ACCEPTED, NtakConst::INVOICE_SENDING_RESPONSE_STATUS_SEND_AGAIN])) {
  5982. print dolGetButtonAction($langs->trans('NtakGetStatusBtn'), '', 'default', $_SERVER['PHP_SELF'].'?facid='.$object->id.'&action=getntakstatus&token='.newToken(), '', true, $params);
  5983. }
  5984. }
  5985. /** **************************************************************************************
  5986. *
  5987. * /NTAK BUTTONS
  5988. *
  5989. ************************************************************************************** */
  5990. // Reopen an invoice
  5991. if (
  5992. (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_RECEIPT)
  5993. || ($object->type == Facture::TYPE_CREDIT_NOTE && empty($discount->id))
  5994. || ($object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE && empty($discount->id))
  5995. || ($object->type == Facture::TYPE_DEPOSIT && empty($discount->id))
  5996. || ($object->type == Facture::TYPE_SITUATION && empty($discount->id)))
  5997. && ($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED || ($object->statut == 1 && $object->paye == 1)) // Condition ($object->statut == 1 && $object->paye == 1) should not happened but can be found due to corrupted data
  5998. && ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $usercancreate) || $usercanreopen)
  5999. ) { // A paid invoice (partially or completely)
  6000. if ($object->close_code != 'replaced' || (!$objectidnext)) { // Not replaced by another invoice or replaced but the replacement invoice has been deleted
  6001. print dolGetButtonAction($langs->trans('ReOpen'), '', 'default', $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '&action=reopen&token=' . newToken(), '', true, $params);
  6002. } else {
  6003. $params['attr']['title'] = $langs->trans("DisabledBecauseReplacedInvoice");
  6004. print dolGetButtonAction($langs->trans('ReOpen'), '', 'default', '#', '', false, $params);
  6005. }
  6006. }
  6007. // Create contract
  6008. if (!empty($conf->global->CONTRACT_CREATE_FROM_INVOICE)) {
  6009. if (isModEnabled('contrat') && $object->statut == Facture::STATUS_VALIDATED) {
  6010. $langs->load("contracts");
  6011. if ($usercancreatecontract) {
  6012. print '<a class="butAction" href="' . DOL_URL_ROOT . '/contrat/card.php?action=create&amp;origin=' . $object->element . '&amp;originid=' . $object->id . '&amp;socid=' . $object->socid . '">' . $langs->trans('AddContract') . '</a>';
  6013. }
  6014. }
  6015. }
  6016. // Validate
  6017. 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) || ($object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE && $object->total_ttc <= 0))) {
  6018. if ($usercanvalidate) {
  6019. print dolGetButtonAction($langs->trans('Validate'), '', 'default', $_SERVER["PHP_SELF"] . '?facid=' . $object->id . '&action=valid&token=' . newToken(), '', true, $params);
  6020. }
  6021. }
  6022. // Send by mail
  6023. if (empty($user->socid)) {
  6024. if (($object->statut == Facture::STATUS_VALIDATED || $object->statut == Facture::STATUS_CLOSED) || !empty($conf->global->FACTURE_SENDBYEMAIL_FOR_ALL_STATUS)) {
  6025. if ($objectidnext) {
  6026. print '<span class="butActionRefused classfortooltip" title="' . $langs->trans("DisabledBecauseReplacedInvoice") . '">' . $langs->trans('SendMail') . '</span>';
  6027. } else {
  6028. if ($usercansend) {
  6029. print dolGetButtonAction('', $langs->trans('SendMail'), 'default', $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '&action=presend&mode=init#formmailbeforetitle', '', true, $params);
  6030. } else {
  6031. print dolGetButtonAction('', $langs->trans('SendMail'), 'default', '#', '', false, $params);
  6032. }
  6033. }
  6034. }
  6035. }
  6036. // Request a direct debit order
  6037. if ($object->statut > Facture::STATUS_DRAFT && $object->paye == 0 && $num == 0) {
  6038. if ($resteapayer > 0) {
  6039. if ($usercancreatewithdrarequest) {
  6040. if (!$objectidnext && $object->close_code != 'replaced') { // Not replaced by another invoice
  6041. 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>';
  6042. } else {
  6043. print '<span class="butActionRefused classfortooltip" title="' . $langs->trans("DisabledBecauseReplacedInvoice") . '">' . $langs->trans('MakeWithdrawRequest') . '</span>';
  6044. }
  6045. } else {
  6046. //print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans("MakeWithdrawRequest").'</a>';
  6047. }
  6048. } else {
  6049. //print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("AmountMustBePositive")).'">'.$langs->trans("MakeWithdrawRequest").'</a>';
  6050. }
  6051. }
  6052. // POS Ticket
  6053. if (isModEnabled('takepos') && $object->module_source == 'takepos') {
  6054. $langs->load("cashdesk");
  6055. $receipt_url = DOL_URL_ROOT . "/takepos/receipt.php";
  6056. print '<a target="_blank" rel="noopener noreferrer" class="butAction" href="' . $receipt_url . '?facid=' . ((int) $object->id) . '">' . $langs->trans('POSTicket') . '</a>';
  6057. }
  6058. // Create payment
  6059. if ($object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_RECEIPT_CREDIT_NOTE && $object->statut == 1 && $object->paye == 0 && $usercanissuepayment) {
  6060. if ($objectidnext) {
  6061. print '<span class="butActionRefused classfortooltip" title="' . $langs->trans("DisabledBecauseReplacedInvoice") . '">' . $langs->trans('DoPayment') . '</span>';
  6062. } else {
  6063. if ($object->type == Facture::TYPE_DEPOSIT && $resteapayer == 0) {
  6064. // For down payment, we refuse to receive more than amount to pay.
  6065. $params['attr']['title'] = $langs->trans('DisabledBecauseRemainderToPayIsZero');
  6066. print dolGetButtonAction($langs->trans('DoPayment'), '', 'default', '#', '', false, $params);
  6067. } else {
  6068. // 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)
  6069. //print '<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>';
  6070. print dolGetButtonAction($langs->trans('DoPayment'), '', 'default', DOL_URL_ROOT . '/compta/paiement.php?facid=' . $object->id . '&amp;action=create&amp;accountid=' . $object->fk_account, '', true, $params);
  6071. }
  6072. }
  6073. }
  6074. $sumofpayment = $totalpaid;
  6075. $sumofpaymentall = $totalpaid + $totalcreditnotes + $totaldeposits;
  6076. // Reverse back money or convert to reduction
  6077. if ($object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_SITUATION) {
  6078. // For credit note only
  6079. if ($object->type == Facture::TYPE_CREDIT_NOTE && $object->statut == Facture::STATUS_VALIDATED && $object->paye == 0 && $usercanissuepayment) {
  6080. if ($resteapayer == 0) {
  6081. print '<span class="butActionRefused classfortooltip" title="' . $langs->trans("DisabledBecauseRemainderToPayIsZero") . '">' . $langs->trans('DoPaymentBack') . '</span>';
  6082. } else {
  6083. print '<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>';
  6084. }
  6085. }
  6086. if ($object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE && $object->statut == Facture::STATUS_VALIDATED && $object->paye == 0 && $usercanissuepayment) {
  6087. if ($resteapayer == 0) {
  6088. print '<span class="butActionRefused classfortooltip" title="'.$langs->trans("DisabledBecauseRemainderToPayIsZero").'">'.$langs->trans('DoPaymentBack').'</span>';
  6089. } else {
  6090. print '<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>';
  6091. }
  6092. }
  6093. // For standard invoice with excess received
  6094. if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_SITUATION || $object->type == Facture::TYPE_RECEIPT) && $object->statut == Facture::STATUS_VALIDATED && empty($object->paye) && $resteapayer < 0 && $usercancreate && empty($discount->id)) {
  6095. print '<a class="butAction' . ($conf->use_javascript_ajax ? ' reposition' : '') . '" href="' . $_SERVER["PHP_SELF"] . '?facid=' . $object->id . '&amp;action=converttoreduc">' . $langs->trans('ConvertExcessReceivedToReduc') . '</a>';
  6096. }
  6097. // For credit note
  6098. if (
  6099. $object->type == Facture::TYPE_CREDIT_NOTE && $object->statut == Facture::STATUS_VALIDATED && $object->paye == 0 && $usercancreate
  6100. && (!empty($conf->global->INVOICE_ALLOW_REUSE_OF_CREDIT_WHEN_PARTIALLY_REFUNDED) || $sumofpayment == 0)
  6101. ) {
  6102. print '<a class="butAction' . ($conf->use_javascript_ajax ? ' reposition' : '') . '" href="' . $_SERVER["PHP_SELF"] . '?facid=' . $object->id . '&amp;action=converttoreduc" title="' . dol_escape_htmltag($langs->trans("ConfirmConvertToReduc2")) . '">' . $langs->trans('ConvertToReduc') . '</a>';
  6103. }
  6104. // For Receipt Credit Note
  6105. if (
  6106. $object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE && $object->statut == Facture::STATUS_VALIDATED && $object->paye == 0 && $usercancreate
  6107. && (!empty($conf->global->INVOICE_ALLOW_REUSE_OF_CREDIT_WHEN_PARTIALLY_REFUNDED) || $sumofpayment == 0)
  6108. ) {
  6109. print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=converttoreduc" title="'.dol_escape_htmltag($langs->trans("ConfirmConvertToReduc2")).'">'.$langs->trans('ConvertToReduc').'</a>';
  6110. }
  6111. // For down payment invoice (deposit)
  6112. if ($object->type == Facture::TYPE_DEPOSIT && $usercancreate && $object->statut > Facture::STATUS_DRAFT && empty($discount->id)) {
  6113. if (price2num($object->total_ttc, 'MT') == price2num($sumofpaymentall, 'MT') || ($object->type == Facture::STATUS_ABANDONED && in_array($object->close_code, array('bankcharge', 'discount_vat', 'other')))) {
  6114. // We can close a down payment only if paid amount is same than amount of down payment (by definition)
  6115. print '<a class="butAction' . ($conf->use_javascript_ajax ? ' reposition' : '') . '" href="' . $_SERVER["PHP_SELF"] . '?facid=' . $object->id . '&amp;action=converttoreduc">' . $langs->trans('ConvertToReduc') . '</a>';
  6116. } else {
  6117. print '<span class="butActionRefused" title="' . $langs->trans("AmountPaidMustMatchAmountOfDownPayment") . '">' . $langs->trans('ConvertToReduc') . '</span>';
  6118. }
  6119. }
  6120. }
  6121. // Classify paid
  6122. if (
  6123. $object->statut == Facture::STATUS_VALIDATED && $object->paye == 0 && $usercanissuepayment && (
  6124. ($object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_RECEIPT_CREDIT_NOTE && $object->type != Facture::TYPE_DEPOSIT && ($resteapayer <= 0 || (!empty($conf->global->INVOICE_CAN_SET_PAID_EVEN_IF_PARTIALLY_PAID) && $object->total_ttc == $resteapayer))) ||
  6125. ($object->type == Facture::TYPE_CREDIT_NOTE && $resteapayer >= 0) ||
  6126. ($object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE && $resteapayer >= 0) ||
  6127. ($object->type == Facture::TYPE_DEPOSIT && $object->total_ttc > 0)
  6128. )
  6129. ) {
  6130. if ($object->type == Facture::TYPE_DEPOSIT && price2num($object->total_ttc, 'MT') != price2num($sumofpaymentall, 'MT')) {
  6131. // We can close a down payment only if paid amount is same than amount of down payment (by definition)
  6132. $params['attr']['title'] = $langs->trans('AmountPaidMustMatchAmountOfDownPayment');
  6133. print dolGetButtonAction($langs->trans('ClassifyPaid'), '', 'default', '#', '', false, $params);
  6134. } else {
  6135. print dolGetButtonAction($langs->trans('ClassifyPaid'), '', 'default', $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '&amp;action=paid', '', true, $params);
  6136. }
  6137. }
  6138. // Classify 'closed not completely paid' (possible if validated and not yet filed paid)
  6139. if ($object->statut == Facture::STATUS_VALIDATED && $object->paye == 0 && $resteapayer > 0 && (empty($conf->global->INVOICE_CAN_SET_PAID_EVEN_IF_PARTIALLY_PAID) || $resteapayer != $object->total_ttc) && $usercanissuepayment) {
  6140. if ($totalpaid > 0 || $totalcreditnotes > 0) {
  6141. // If one payment or one credit note was linked to this invoice
  6142. print '<a class="butAction' . ($conf->use_javascript_ajax ? ' reposition' : '') . '" href="' . $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '&amp;action=paid">' . $langs->trans('ClassifyPaidPartially') . '</a>';
  6143. } else {
  6144. if (empty($conf->global->INVOICE_CAN_NEVER_BE_CANCELED)) {
  6145. if ($objectidnext) {
  6146. print '<span class="butActionRefused classfortooltip" title="' . $langs->trans("DisabledBecauseReplacedInvoice") . '">' . $langs->trans('ClassifyCanceled') . '</span>';
  6147. } else {
  6148. print '<a class="butAction' . ($conf->use_javascript_ajax ? ' reposition' : '') . '" href="' . $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '&amp;action=canceled">' . $langs->trans('ClassifyCanceled') . '</a>';
  6149. }
  6150. }
  6151. }
  6152. }
  6153. // Create a credit note
  6154. if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_RECEIPT || ($object->type == Facture::TYPE_DEPOSIT && empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) || $object->type == Facture::TYPE_PROFORMA) && $object->statut > 0 && $usercancreate) {
  6155. if (!$objectidnext) {
  6156. print '<a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?socid=' . $object->socid . '&amp;fac_avoir=' . $object->id . '&amp;action=create&amp;type=2' . ($object->fk_project > 0 ? '&amp;projectid=' . $object->fk_project : '') . ($object->entity > 0 ? '&amp;originentity=' . $object->entity : '') . '">' . $langs->trans("CreateCreditNote") . '</a>';
  6157. }
  6158. }
  6159. // Create Receipt Credit Note
  6160. if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_RECEIPT || ($object->type == Facture::TYPE_DEPOSIT && empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) || $object->type == Facture::TYPE_PROFORMA) && $object->statut > 0 && $usercancreate) {
  6161. if (!$objectidnext) {
  6162. print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?socid='.$object->socid.'&amp;fac_avoir='.$object->id.'&amp;invoiceAvoirWithLines=1&amp;action=create&amp;type=8'.($object->fk_project > 0 ? '&amp;projectid='.$object->fk_project : '').($object->entity > 0 ? '&amp;originentity='.$object->entity : '').'">'.$langs->trans("CreateReceiptCreditNote").'</a>';
  6163. }
  6164. }
  6165. // Customer name change
  6166. if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_RECEIPT || ($object->type == Facture::TYPE_DEPOSIT && empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) || $object->type == Facture::TYPE_PROFORMA) && $object->statut > 0 && $usercancreate) {
  6167. if (!$objectidnext) {
  6168. print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?socid=-1&amp;fac_avoir='.$object->id.'&amp;action=create&amp;type='. $object->type .''.($object->fk_project > 0 ? '&amp;projectid='.$object->fk_project : '').($object->entity > 0 ? '&amp;originentity='.$object->entity : '').'&amp;customerchange=1">'.$langs->trans("ChangeCustomer").'</a>';
  6169. }
  6170. }
  6171. // For situation invoice with excess received
  6172. if (
  6173. $object->statut > Facture::STATUS_DRAFT
  6174. && $object->type == Facture::TYPE_SITUATION
  6175. && ($object->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits) > 0
  6176. && $usercancreate
  6177. && !$objectidnext
  6178. && $object->is_last_in_cycle()
  6179. && getDolGlobalInt('INVOICE_USE_SITUATION_CREDIT_NOTE')
  6180. ) {
  6181. if ($usercanunvalidate) {
  6182. print '<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>';
  6183. } else {
  6184. print '<span class="butActionRefused classfortooltip" title="' . $langs->trans("NotEnoughPermissions") . '">' . $langs->trans("CreateCreditNote") . '</span>';
  6185. }
  6186. }
  6187. // Clone
  6188. if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA || $object->type == Facture::TYPE_RECEIPT) && $usercancreate) {
  6189. print dolGetButtonAction($langs->trans('ToClone'), '', 'default', $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '&amp;action=clone&amp;object=invoice', '', true, $params);
  6190. }
  6191. // Clone as predefined / Create template
  6192. if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA || $object->type == Facture::TYPE_RECEIPT) && $object->statut == 0 && $usercancreate) {
  6193. if (!$objectidnext && count($object->lines) > 0) {
  6194. print dolGetButtonAction($langs->trans('ChangeIntoRepeatableInvoice'), '', 'default', DOL_URL_ROOT . '/compta/facture/card-rec.php?facid=' . $object->id . '&amp;action=create', '', true, $params);
  6195. }
  6196. }
  6197. // Remove situation from cycle
  6198. if (
  6199. in_array($object->statut, array(Facture::STATUS_CLOSED, Facture::STATUS_VALIDATED))
  6200. && $object->type == Facture::TYPE_SITUATION
  6201. && $usercancreate
  6202. && !$objectidnext
  6203. && $object->situation_counter > 1
  6204. && $object->is_last_in_cycle()
  6205. && $usercanunvalidate
  6206. ) {
  6207. if (($object->total_ttc - $totalcreditnotes) == 0) {
  6208. print '<a id="butSituationOut" class="butAction" href="' . $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '&amp;action=situationout">' . $langs->trans("RemoveSituationFromCycle") . '</a>';
  6209. } else {
  6210. print '<a id="butSituationOutRefused" class="butActionRefused classfortooltip" href="#" title="' . $langs->trans("DisabledBecauseNotEnouthCreditNote") . '" >' . $langs->trans("RemoveSituationFromCycle") . '</a>';
  6211. }
  6212. }
  6213. // Create next situation invoice
  6214. if ($usercancreate && ($object->type == 5) && ($object->statut == 1 || $object->statut == 2)) {
  6215. if ($object->is_last_in_cycle() && $object->situation_final != 1) {
  6216. print '<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>';
  6217. } elseif (!$object->is_last_in_cycle()) {
  6218. print '<a class="butActionRefused classfortooltip" href="#" title="' . $langs->trans("DisabledBecauseNotLastInCycle") . '">' . $langs->trans('CreateNextSituationInvoice') . '</a>';
  6219. } else {
  6220. print '<a class="butActionRefused classfortooltip" href="#" title="' . $langs->trans("DisabledBecauseFinal") . '">' . $langs->trans('CreateNextSituationInvoice') . '</a>';
  6221. }
  6222. }
  6223. // Delete
  6224. $isErasable = $object->is_erasable();
  6225. $params = array(
  6226. 'attr' => array(
  6227. 'class' => 'classfortooltip'
  6228. )
  6229. );
  6230. if ($usercandelete || ($usercancreate && $isErasable == 1)) { // isErasable = 1 means draft with temporary ref (draft can always be deleted with no need of permissions)
  6231. $enableDelete = false;
  6232. $deleteHref = '#';
  6233. $htmltooltip = '';
  6234. if ($isErasable == -4) {
  6235. $htmltooltip = $langs->trans('DisabledBecausePayments');
  6236. } elseif ($isErasable == -3) {
  6237. $htmltooltip = $langs->trans('DisabledBecauseNotLastSituationInvoice');
  6238. } elseif ($isErasable == -2) {
  6239. $htmltooltip = $langs->trans('DisabledBecauseNotLastInvoice');
  6240. } elseif ($isErasable == -1) {
  6241. $htmltooltip = $langs->trans('DisabledBecauseDispatchedInBookkeeping');
  6242. } elseif ($isErasable <= 0) { // Any other cases
  6243. $htmltooltip = $langs->trans('DisabledBecauseNotErasable');
  6244. } elseif ($objectidnext) {
  6245. $htmltooltip = $langs->trans('DisabledBecauseReplacedInvoice');
  6246. } else {
  6247. $deleteHref = $_SERVER["PHP_SELF"] . '?facid=' . $object->id . '&action=delete&token=' . newToken();
  6248. $enableDelete = true;
  6249. }
  6250. print dolGetButtonAction($htmltooltip, $langs->trans('Delete'), 'delete', $deleteHref, '', $enableDelete, $params);
  6251. } else {
  6252. print dolGetButtonAction($langs->trans('Delete'), $langs->trans('Delete'), 'delete', '#', '', false);
  6253. }
  6254. }
  6255. print '</div>';
  6256. }
  6257. // Select mail models is same action as presend
  6258. if (GETPOST('modelselected', 'alpha')) {
  6259. $action = 'presend';
  6260. }
  6261. if ($action != 'prerelance' && $action != 'presend') {
  6262. print '<div class="fichecenter"><div class="fichehalfleft">';
  6263. print '<a name="builddoc"></a>'; // ancre
  6264. // Generated documents
  6265. $filename = dol_sanitizeFileName($object->ref);
  6266. $filedir = $conf->facture->multidir_output[$object->entity] . '/' . dol_sanitizeFileName($object->ref);
  6267. $urlsource = $_SERVER['PHP_SELF'] . '?facid=' . $object->id;
  6268. $genallowed = $usercanread;
  6269. $delallowed = $usercancreate;
  6270. print $formfile->showdocuments(
  6271. 'facture',
  6272. $filename,
  6273. $filedir,
  6274. $urlsource,
  6275. $genallowed,
  6276. $delallowed,
  6277. $object->model_pdf,
  6278. 1,
  6279. 0,
  6280. 0,
  6281. 28,
  6282. 0,
  6283. '',
  6284. '',
  6285. '',
  6286. $soc->default_lang,
  6287. '',
  6288. $object,
  6289. 0,
  6290. 'remove_file_comfirm'
  6291. );
  6292. $somethingshown = $formfile->numoffiles;
  6293. // Show links to link elements
  6294. $linktoelem = $form->showLinkToObjectBlock($object, null, array('invoice'));
  6295. $compatibleImportElementsList = false;
  6296. if (
  6297. $usercancreate
  6298. && $object->statut == Facture::STATUS_DRAFT
  6299. && ($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 || $object->type == Facture::TYPE_RECEIPT)
  6300. ) {
  6301. $compatibleImportElementsList = array('commande', 'propal'); // import from linked elements
  6302. }
  6303. $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem, $compatibleImportElementsList);
  6304. // Show online payment link
  6305. $useonlinepayment = (isModEnabled('paypal') || isModEnabled('stripe') || isModEnabled('paybox'));
  6306. if ($object->statut != Facture::STATUS_DRAFT && $useonlinepayment) {
  6307. print '<br><!-- Link to pay -->' . "\n";
  6308. require_once DOL_DOCUMENT_ROOT . '/core/lib/payments.lib.php';
  6309. print showOnlinePaymentUrl('invoice', $object->ref) . '<br>';
  6310. }
  6311. print '</div><div class="fichehalfright">';
  6312. // List of actions on element
  6313. include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php';
  6314. $formactions = new FormActions($db);
  6315. $somethingshown = $formactions->showactions($object, 'invoice', $socid, 1);
  6316. print '</div></div>';
  6317. }
  6318. // Presend form
  6319. $modelmail = 'facture_send';
  6320. $defaulttopic = 'SendBillRef';
  6321. $diroutput = $conf->facture->multidir_output[$object->entity];
  6322. $trackid = 'inv' . $object->id;
  6323. include DOL_DOCUMENT_ROOT . '/core/tpl/card_presend.tpl.php';
  6324. }
  6325. // End of page
  6326. llxFooter();
  6327. $db->close();
  6328. ?>
  6329. <script src="/custom/bbus/js/bbus.js"></script>;
  6330. <link rel="stylesheet" type="text/css" href="/custom/bbus/views/bbus.css">
  6331. <script>
  6332. $(document).ready(function () {
  6333. $('#remise_percent').attr('readonly', true);
  6334. $('#options_discount_percent').change(function () {
  6335. var selectedValue = $(this).val();
  6336. $("#remise_percent").val(selectedValue);
  6337. $('#remise_percent').attr('readonly', true);
  6338. });
  6339. });
  6340. </script>