card.php 254 KB

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