card.php 251 KB

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