card.php 265 KB

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