facture.class.php 227 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322
  1. <?php
  2. /* Copyright (C) 2002-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004-2013 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
  5. * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
  6. * Copyright (C) 2005 Marc Barilley / Ocebo <marc@ocebo.com>
  7. * Copyright (C) 2005-2014 Regis Houssin <regis.houssin@inodbox.com>
  8. * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
  9. * Copyright (C) 2007 Franky Van Liedekerke <franky.van.liedekerke@telenet.be>
  10. * Copyright (C) 2010-2020 Juanjo Menent <jmenent@2byte.es>
  11. * Copyright (C) 2012-2014 Christophe Battarel <christophe.battarel@altairis.fr>
  12. * Copyright (C) 2012-2015 Marcos García <marcosgdf@gmail.com>
  13. * Copyright (C) 2012 Cédric Salvador <csalvador@gpcsolutions.fr>
  14. * Copyright (C) 2012-2014 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
  15. * Copyright (C) 2013 Cedric Gross <c.gross@kreiz-it.fr>
  16. * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
  17. * Copyright (C) 2016-2022 Ferran Marcet <fmarcet@2byte.es>
  18. * Copyright (C) 2018 Alexandre Spangaro <aspangaro@open-dsi.fr>
  19. * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
  20. * Copyright (C) 2022 Sylvain Legrand <contact@infras.fr>
  21. * Copyright (C) 2022 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
  22. *
  23. * This program is free software; you can redistribute it and/or modify
  24. * it under the terms of the GNU General Public License as published by
  25. * the Free Software Foundation; either version 3 of the License, or
  26. * (at your option) any later version.
  27. *
  28. * This program is distributed in the hope that it will be useful,
  29. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  30. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  31. * GNU General Public License for more details.
  32. *
  33. * You should have received a copy of the GNU General Public License
  34. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  35. */
  36. /**
  37. * \file htdocs/compta/facture/class/facture.class.php
  38. * \ingroup facture
  39. * \brief File of class to manage invoices
  40. */
  41. include_once DOL_DOCUMENT_ROOT.'/core/class/commoninvoice.class.php';
  42. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php';
  43. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  44. require_once DOL_DOCUMENT_ROOT.'/societe/class/client.class.php';
  45. require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php';
  46. require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
  47. if (!empty($conf->accounting->enabled)) {
  48. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php';
  49. }
  50. if (!empty($conf->accounting->enabled)) {
  51. require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php';
  52. }
  53. /**
  54. * Class to manage invoices
  55. */
  56. class Facture extends CommonInvoice
  57. {
  58. /**
  59. * @var string ID to identify managed object
  60. */
  61. public $element = 'facture';
  62. /**
  63. * @var string Name of table without prefix where object is stored
  64. */
  65. public $table_element = 'facture';
  66. /**
  67. * @var string Name of subtable line
  68. */
  69. public $table_element_line = 'facturedet';
  70. /**
  71. * @var string Fieldname with ID of parent key if this field has a parent
  72. */
  73. public $fk_element = 'fk_facture';
  74. /**
  75. * @var string String with name of icon for myobject.
  76. */
  77. public $picto = 'bill';
  78. /**
  79. * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
  80. * @var int
  81. */
  82. public $ismultientitymanaged = 1;
  83. /**
  84. * 0=Default, 1=View may be restricted to sales representative only if no permission to see all or to company of external user if external user
  85. * @var integer
  86. */
  87. public $restrictiononfksoc = 1;
  88. /**
  89. * {@inheritdoc}
  90. */
  91. protected $table_ref_field = 'ref';
  92. /**
  93. * @var int 1 if status is draft
  94. * @deprecated
  95. */
  96. public $brouillon;
  97. /**
  98. * @var int thirdparty ID
  99. */
  100. public $socid;
  101. public $author;
  102. /**
  103. * @var int ID
  104. */
  105. public $fk_user_author;
  106. /**
  107. * @var int ID
  108. */
  109. public $fk_user_valid;
  110. public $date; // Date invoice
  111. public $datem;
  112. /**
  113. * @var int Date expected for delivery
  114. * @deprecated
  115. */
  116. public $date_livraison; // deprecated; Use delivery_date instead.
  117. public $delivery_date; // Date expected of shipment (date starting shipment, not the reception that occurs some days after)
  118. /**
  119. * @var string customer ref
  120. */
  121. public $ref_client;
  122. /**
  123. * @var int Ref Int
  124. * @deprecated
  125. */
  126. public $ref_int; // deprecated
  127. //Check constants for types
  128. public $type = self::TYPE_STANDARD;
  129. // Warning: Do not set default value into property defintion. it must stay null.
  130. // For example to avoid to have substition done when object is generic and not yet defined.
  131. public $remise_absolue;
  132. public $remise_percent;
  133. public $total_ht;
  134. public $total_tva;
  135. public $total_localtax1;
  136. public $total_localtax2;
  137. public $total_ttc;
  138. public $revenuestamp;
  139. /**
  140. * ! Closing after partial payment: discount_vat, badsupplier, abandon
  141. * ! Closing when no payment: replaced, abandoned
  142. * @var string Close code
  143. */
  144. public $close_code;
  145. /**
  146. * ! Comment if paid without full payment
  147. * @var string Close note
  148. */
  149. public $close_note;
  150. /**
  151. * 1 if invoice paid COMPLETELY, 0 otherwise (do not use it anymore, use statut and close_code)
  152. */
  153. public $paye;
  154. //! key of module source when invoice generated from a dedicated module ('cashdesk', 'takepos', ...)
  155. public $module_source;
  156. //! key of pos source ('0', '1', ...)
  157. public $pos_source;
  158. //! id of template invoice when generated from a template invoice
  159. public $fk_fac_rec_source;
  160. //! id of source invoice if replacement invoice or credit note
  161. public $fk_facture_source;
  162. public $linked_objects = array();
  163. public $date_lim_reglement;
  164. public $cond_reglement_code; // Code in llx_c_paiement
  165. public $mode_reglement_code; // Code in llx_c_paiement
  166. /**
  167. * @var int ID Field to store bank id to use when payment mode is withdraw
  168. */
  169. public $fk_bank;
  170. /**
  171. * @var FactureLigne[]
  172. */
  173. public $lines = array();
  174. public $line;
  175. public $extraparams = array();
  176. public $fac_rec;
  177. public $date_pointoftax;
  178. // Multicurrency
  179. /**
  180. * @var int ID
  181. */
  182. public $fk_multicurrency;
  183. public $multicurrency_code;
  184. public $multicurrency_tx;
  185. public $multicurrency_total_ht;
  186. public $multicurrency_total_tva;
  187. public $multicurrency_total_ttc;
  188. /**
  189. * @var int Situation cycle reference number
  190. */
  191. public $situation_cycle_ref;
  192. /**
  193. * @var int Situation counter inside the cycle
  194. */
  195. public $situation_counter;
  196. /**
  197. * @var int Final situation flag
  198. */
  199. public $situation_final;
  200. /**
  201. * @var array Table of previous situations
  202. */
  203. public $tab_previous_situation_invoice = array();
  204. /**
  205. * @var array Table of next situations
  206. */
  207. public $tab_next_situation_invoice = array();
  208. public $oldcopy;
  209. /**
  210. * @var double percentage of retainage
  211. */
  212. public $retained_warranty;
  213. /**
  214. * @var int timestamp of date limit of retainage
  215. */
  216. public $retained_warranty_date_limit;
  217. /**
  218. * @var int Code in llx_c_paiement
  219. */
  220. public $retained_warranty_fk_cond_reglement;
  221. /**
  222. * 'type' if the field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password')
  223. * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
  224. * 'label' the translation key.
  225. * 'enabled' is a condition when the field must be managed.
  226. * 'position' is the sort order of field.
  227. * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  228. * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing)
  229. * 'noteditable' says if field is not editable (1 or 0)
  230. * 'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created.
  231. * 'index' if we want an index in database.
  232. * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
  233. * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
  234. * 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8).
  235. * 'css' is the CSS style to use on field. For example: 'maxwidth200'
  236. * 'help' is a string visible as a tooltip on field
  237. * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
  238. * 'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code.
  239. * 'arrayofkeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel")
  240. * 'comment' is not used. You can store here any text of your choice. It is not used by application.
  241. *
  242. * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
  243. */
  244. // BEGIN MODULEBUILDER PROPERTIES
  245. /**
  246. * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
  247. */
  248. public $fields = array(
  249. 'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>1),
  250. 'ref' =>array('type'=>'varchar(30)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'position'=>5),
  251. 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>20, 'index'=>1),
  252. 'ref_client' =>array('type'=>'varchar(255)', 'label'=>'RefCustomer', 'enabled'=>1, 'visible'=>-1, 'position'=>10),
  253. 'ref_ext' =>array('type'=>'varchar(255)', 'label'=>'Ref ext', 'enabled'=>1, 'visible'=>0, 'position'=>12),
  254. //'ref_int' =>array('type'=>'varchar(255)', 'label'=>'Ref int', 'enabled'=>1, 'visible'=>0, 'position'=>30), // deprecated
  255. 'type' =>array('type'=>'smallint(6)', 'label'=>'Type', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>15),
  256. //'increment' =>array('type'=>'varchar(10)', 'label'=>'Increment', 'enabled'=>1, 'visible'=>-1, 'position'=>45),
  257. 'fk_soc' =>array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>50),
  258. 'datef' =>array('type'=>'date', 'label'=>'DateInvoice', 'enabled'=>1, 'visible'=>1, 'position'=>20),
  259. 'date_valid' =>array('type'=>'date', 'label'=>'DateValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>22),
  260. 'date_lim_reglement' =>array('type'=>'date', 'label'=>'DateDue', 'enabled'=>1, 'visible'=>1, 'position'=>25),
  261. 'date_closing' =>array('type'=>'datetime', 'label'=>'Date closing', 'enabled'=>1, 'visible'=>-1, 'position'=>30),
  262. 'paye' =>array('type'=>'smallint(6)', 'label'=>'InvoicePaidCompletely', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>80),
  263. //'amount' =>array('type'=>'double(24,8)', 'label'=>'Amount', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>85),
  264. 'remise_percent' =>array('type'=>'double', 'label'=>'RelativeDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>90),
  265. 'remise_absolue' =>array('type'=>'double', 'label'=>'CustomerRelativeDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>91),
  266. //'remise' =>array('type'=>'double', 'label'=>'Remise', 'enabled'=>1, 'visible'=>-1, 'position'=>100),
  267. 'close_code' =>array('type'=>'varchar(16)', 'label'=>'EarlyClosingReason', 'enabled'=>1, 'visible'=>-1, 'position'=>92),
  268. 'close_note' =>array('type'=>'varchar(128)', 'label'=>'EarlyClosingComment', 'enabled'=>1, 'visible'=>-1, 'position'=>93),
  269. 'total_ht' =>array('type'=>'double(24,8)', 'label'=>'AmountHT', 'enabled'=>1, 'visible'=>1, 'position'=>95, 'isameasure'=>1),
  270. 'total_tva' =>array('type'=>'double(24,8)', 'label'=>'AmountVAT', 'enabled'=>1, 'visible'=>-1, 'position'=>100, 'isameasure'=>1),
  271. 'localtax1' =>array('type'=>'double(24,8)', 'label'=>'LT1', 'enabled'=>1, 'visible'=>-1, 'position'=>110, 'isameasure'=>1),
  272. 'localtax2' =>array('type'=>'double(24,8)', 'label'=>'LT2', 'enabled'=>1, 'visible'=>-1, 'position'=>120, 'isameasure'=>1),
  273. 'revenuestamp' =>array('type'=>'double(24,8)', 'label'=>'RevenueStamp', 'enabled'=>1, 'visible'=>-1, 'position'=>115, 'isameasure'=>1),
  274. 'total_ttc' =>array('type'=>'double(24,8)', 'label'=>'AmountTTC', 'enabled'=>1, 'visible'=>1, 'position'=>130, 'isameasure'=>1),
  275. 'fk_user_author' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-1, 'position'=>165),
  276. 'fk_user_modif' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>166),
  277. 'fk_user_valid' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>167),
  278. 'fk_user_closing' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserClosing', 'enabled'=>1, 'visible'=>-1, 'position'=>168),
  279. 'fk_facture_source' =>array('type'=>'integer', 'label'=>'SourceInvoice', 'enabled'=>1, 'visible'=>-1, 'position'=>170),
  280. 'fk_projet' =>array('type'=>'integer:Project:projet/class/project.class.php:1:fk_statut=1', 'label'=>'Project', 'enabled'=>1, 'visible'=>-1, 'position'=>175),
  281. 'fk_account' =>array('type'=>'integer', 'label'=>'Fk account', 'enabled'=>1, 'visible'=>-1, 'position'=>180),
  282. 'fk_currency' =>array('type'=>'varchar(3)', 'label'=>'CurrencyCode', 'enabled'=>1, 'visible'=>-1, 'position'=>185),
  283. 'fk_cond_reglement' =>array('type'=>'integer', 'label'=>'PaymentTerm', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>190),
  284. 'fk_mode_reglement' =>array('type'=>'integer', 'label'=>'PaymentMode', 'enabled'=>1, 'visible'=>-1, 'position'=>195),
  285. 'note_private' =>array('type'=>'text', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>205),
  286. 'note_public' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>210),
  287. 'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'position'=>215),
  288. 'extraparams' =>array('type'=>'varchar(255)', 'label'=>'Extraparams', 'enabled'=>1, 'visible'=>-1, 'position'=>225),
  289. 'situation_cycle_ref' =>array('type'=>'smallint(6)', 'label'=>'Situation cycle ref', 'enabled'=>'$conf->global->INVOICE_USE_SITUATION', 'visible'=>-1, 'position'=>230),
  290. 'situation_counter' =>array('type'=>'smallint(6)', 'label'=>'Situation counter', 'enabled'=>'$conf->global->INVOICE_USE_SITUATION', 'visible'=>-1, 'position'=>235),
  291. 'situation_final' =>array('type'=>'smallint(6)', 'label'=>'Situation final', 'enabled'=>'empty($conf->global->INVOICE_USE_SITUATION) ? 0 : 1', 'visible'=>-1, 'position'=>240),
  292. 'retained_warranty' =>array('type'=>'double', 'label'=>'Retained warranty', 'enabled'=>'$conf->global->INVOICE_USE_RETAINED_WARRANTY', 'visible'=>-1, 'position'=>245),
  293. 'retained_warranty_date_limit' =>array('type'=>'date', 'label'=>'Retained warranty date limit', 'enabled'=>'$conf->global->INVOICE_USE_RETAINED_WARRANTY', 'visible'=>-1, 'position'=>250),
  294. 'retained_warranty_fk_cond_reglement' =>array('type'=>'integer', 'label'=>'Retained warranty fk cond reglement', 'enabled'=>'$conf->global->INVOICE_USE_RETAINED_WARRANTY', 'visible'=>-1, 'position'=>255),
  295. 'fk_incoterms' =>array('type'=>'integer', 'label'=>'IncotermCode', 'enabled'=>'$conf->incoterm->enabled', 'visible'=>-1, 'position'=>260),
  296. 'location_incoterms' =>array('type'=>'varchar(255)', 'label'=>'IncotermLabel', 'enabled'=>'$conf->incoterm->enabled', 'visible'=>-1, 'position'=>265),
  297. 'date_pointoftax' =>array('type'=>'date', 'label'=>'DatePointOfTax', 'enabled'=>'$conf->global->INVOICE_POINTOFTAX_DATE', 'visible'=>-1, 'position'=>270),
  298. 'fk_multicurrency' =>array('type'=>'integer', 'label'=>'MulticurrencyID', 'enabled'=>'$conf->multicurrency->enabled', 'visible'=>-1, 'position'=>275),
  299. 'multicurrency_code' =>array('type'=>'varchar(255)', 'label'=>'Currency', 'enabled'=>'$conf->multicurrency->enabled', 'visible'=>-1, 'position'=>280),
  300. 'multicurrency_tx' =>array('type'=>'double(24,8)', 'label'=>'CurrencyRate', 'enabled'=>'$conf->multicurrency->enabled', 'visible'=>-1, 'position'=>285, 'isameasure'=>1),
  301. 'multicurrency_total_ht' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyAmountHT', 'enabled'=>'$conf->multicurrency->enabled', 'visible'=>-1, 'position'=>290, 'isameasure'=>1),
  302. 'multicurrency_total_tva' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyAmountVAT', 'enabled'=>'$conf->multicurrency->enabled', 'visible'=>-1, 'position'=>291, 'isameasure'=>1),
  303. 'multicurrency_total_ttc' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyAmountTTC', 'enabled'=>'$conf->multicurrency->enabled', 'visible'=>-1, 'position'=>292, 'isameasure'=>1),
  304. 'fk_fac_rec_source' =>array('type'=>'integer', 'label'=>'RecurringInvoiceSource', 'enabled'=>1, 'visible'=>-1, 'position'=>305),
  305. 'last_main_doc' =>array('type'=>'varchar(255)', 'label'=>'LastMainDoc', 'enabled'=>1, 'visible'=>-1, 'position'=>310),
  306. 'module_source' =>array('type'=>'varchar(32)', 'label'=>'POSModule', 'enabled'=>1, 'visible'=>-1, 'position'=>315),
  307. 'pos_source' =>array('type'=>'varchar(32)', 'label'=>'POSTerminal', 'enabled'=>1, 'visible'=>-1, 'position'=>320),
  308. 'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>500),
  309. 'tms' =>array('type'=>'timestamp', 'label'=>'DateModificationShort', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>500),
  310. 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>900),
  311. 'fk_statut' =>array('type'=>'smallint(6)', 'label'=>'Status', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'position'=>1000, 'arrayofkeyval'=>array(0=>'Draft', 1=>'Validated', 2=>'Paid', 3=>'Abandonned')),
  312. );
  313. // END MODULEBUILDER PROPERTIES
  314. /**
  315. * Standard invoice
  316. */
  317. const TYPE_STANDARD = 0;
  318. /**
  319. * Replacement invoice
  320. */
  321. const TYPE_REPLACEMENT = 1;
  322. /**
  323. * Credit note invoice
  324. */
  325. const TYPE_CREDIT_NOTE = 2;
  326. /**
  327. * Deposit invoice
  328. */
  329. const TYPE_DEPOSIT = 3;
  330. /**
  331. * Proforma invoice (should not be used. a proforma is an order)
  332. */
  333. const TYPE_PROFORMA = 4;
  334. /**
  335. * Situation invoice
  336. */
  337. const TYPE_SITUATION = 5;
  338. /**
  339. * Draft status
  340. */
  341. const STATUS_DRAFT = 0;
  342. /**
  343. * Validated (need to be paid)
  344. */
  345. const STATUS_VALIDATED = 1;
  346. /**
  347. * Classified paid.
  348. * If paid partially, $this->close_code can be:
  349. * - CLOSECODE_DISCOUNTVAT
  350. * - CLOSECODE_BADDEBT
  351. * If paid completely, this->close_code will be null
  352. */
  353. const STATUS_CLOSED = 2;
  354. /**
  355. * Classified abandoned and no payment done.
  356. * $this->close_code can be:
  357. * - CLOSECODE_BADDEBT
  358. * - CLOSECODE_ABANDONED
  359. * - CLOSECODE_REPLACED
  360. */
  361. const STATUS_ABANDONED = 3;
  362. const CLOSECODE_DISCOUNTVAT = 'discount_vat'; // Abandonned remain - escompte
  363. const CLOSECODE_BADDEBT = 'badcustomer'; // Abandonned - bad
  364. const CLOSECODE_ABANDONED = 'abandon'; // Abandonned - other
  365. const CLOSECODE_REPLACED = 'replaced'; // Closed after doing a replacement invoice
  366. /**
  367. * Constructor
  368. *
  369. * @param DoliDB $db Database handler
  370. */
  371. public function __construct(DoliDB $db)
  372. {
  373. $this->db = $db;
  374. }
  375. /**
  376. * Create invoice in database.
  377. * Note: this->ref can be set or empty. If empty, we will use "(PROV999)"
  378. * Note: this->fac_rec must be set to create invoice from a recurring invoice
  379. *
  380. * @param User $user Object user that create
  381. * @param int $notrigger 1=Does not execute triggers, 0 otherwise
  382. * @param int $forceduedate If set, do not recalculate due date from payment condition but force it with value
  383. * @return int <0 if KO, >0 if OK
  384. */
  385. public function create(User $user, $notrigger = 0, $forceduedate = 0)
  386. {
  387. global $langs, $conf, $mysoc, $hookmanager;
  388. $error = 0;
  389. // Clean parameters
  390. if (empty($this->type)) {
  391. $this->type = self::TYPE_STANDARD;
  392. }
  393. $this->ref_client = trim($this->ref_client);
  394. $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private)); // deprecated
  395. $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note_private));
  396. $this->note_public = trim($this->note_public);
  397. if (!$this->cond_reglement_id) {
  398. $this->cond_reglement_id = 0;
  399. }
  400. if (!$this->mode_reglement_id) {
  401. $this->mode_reglement_id = 0;
  402. }
  403. $this->brouillon = 1;
  404. $this->status = self::STATUS_DRAFT;
  405. $this->statut = self::STATUS_DRAFT;
  406. if (!empty($this->multicurrency_code)) {
  407. // Multicurrency (test on $this->multicurrency_tx because we should take the default rate of multicurrency_code only if not using original rate)
  408. if (empty($this->multicurrency_tx)) {
  409. // If original rate is not set, we take a default value from date
  410. list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $this->date);
  411. } else {
  412. // original rate multicurrency_tx and multicurrency_code are set, we use them
  413. $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
  414. }
  415. } else {
  416. $this->fk_multicurrency = 0;
  417. }
  418. if (empty($this->fk_multicurrency)) {
  419. $this->multicurrency_code = $conf->currency;
  420. $this->fk_multicurrency = 0;
  421. $this->multicurrency_tx = 1;
  422. }
  423. dol_syslog(get_class($this)."::create user=".$user->id." date=".$this->date);
  424. // Check parameters
  425. if (empty($this->date)) {
  426. $this->error = "Try to create an invoice with an empty parameter (date)";
  427. dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
  428. return -3;
  429. }
  430. $soc = new Societe($this->db);
  431. $result = $soc->fetch($this->socid);
  432. if ($result < 0) {
  433. $this->error = "Failed to fetch company: ".$soc->error;
  434. dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
  435. return -2;
  436. }
  437. $now = dol_now();
  438. $this->db->begin();
  439. $originaldatewhen = null;
  440. $nextdatewhen = null;
  441. $previousdaynextdatewhen = null;
  442. // Create invoice from a template recurring invoice
  443. if ($this->fac_rec > 0) {
  444. $this->fk_fac_rec_source = $this->fac_rec;
  445. require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php';
  446. $_facrec = new FactureRec($this->db);
  447. $result = $_facrec->fetch($this->fac_rec);
  448. $result = $_facrec->fetchObjectLinked(null, '', null, '', 'OR', 1, 'sourcetype', 0); // This load $_facrec->linkedObjectsIds
  449. // Define some dates
  450. $originaldatewhen = $_facrec->date_when;
  451. $nextdatewhen = null; $previousdaynextdatewhen = null;
  452. if ($originaldatewhen) {
  453. $nextdatewhen = dol_time_plus_duree($originaldatewhen, $_facrec->frequency, $_facrec->unit_frequency);
  454. $previousdaynextdatewhen = dol_time_plus_duree($nextdatewhen, -1, 'd');
  455. }
  456. if (!empty($_facrec->frequency)) { // Invoice are created on same thirdparty than template when there is a recurrence, but not necessarly when there is no recurrence.
  457. $this->socid = $_facrec->socid;
  458. }
  459. $this->entity = $_facrec->entity; // Invoice created in same entity than template
  460. // Fields coming from GUI (priority on template). TODO Value of template should be used as default value on GUI so we can use here always value from GUI
  461. $this->fk_project = GETPOST('projectid', 'int') > 0 ? ((int) GETPOST('projectid', 'int')) : $_facrec->fk_project;
  462. $this->note_public = GETPOSTISSET('note_public') ? GETPOST('note_public', 'restricthtml') : $_facrec->note_public;
  463. $this->note_private = GETPOSTISSET('note_private') ? GETPOST('note_private', 'restricthtml') : $_facrec->note_private;
  464. $this->model_pdf = GETPOSTISSET('model') ? GETPOST('model', 'alpha') : $_facrec->model_pdf;
  465. $this->cond_reglement_id = GETPOST('cond_reglement_id', 'int') > 0 ? ((int) GETPOST('cond_reglement_id', 'int')) : $_facrec->cond_reglement_id;
  466. $this->mode_reglement_id = GETPOST('mode_reglement_id', 'int') > 0 ? ((int) GETPOST('mode_reglement_id', 'int')) : $_facrec->mode_reglement_id;
  467. $this->fk_account = GETPOST('fk_account') > 0 ? ((int) GETPOST('fk_account')) : $_facrec->fk_account;
  468. // Set here to have this defined for substitution into notes, should be recalculated after adding lines to get same result
  469. $this->total_ht = $_facrec->total_ht;
  470. $this->total_ttc = $_facrec->total_ttc;
  471. // Fields always coming from template
  472. $this->remise_absolue = $_facrec->remise_absolue;
  473. $this->remise_percent = $_facrec->remise_percent;
  474. $this->fk_incoterms = $_facrec->fk_incoterms;
  475. $this->location_incoterms = $_facrec->location_incoterms;
  476. // Clean parameters
  477. if (!$this->type) {
  478. $this->type = self::TYPE_STANDARD;
  479. }
  480. $this->ref_client = trim($this->ref_client);
  481. $this->note_public = trim($this->note_public);
  482. $this->note_private = trim($this->note_private);
  483. $this->note_private = dol_concatdesc($this->note_private, $langs->trans("GeneratedFromRecurringInvoice", $_facrec->ref));
  484. $this->array_options = $_facrec->array_options;
  485. if (!$this->mode_reglement_id) {
  486. $this->mode_reglement_id = 0;
  487. }
  488. $this->brouillon = 1;
  489. $this->status = self::STATUS_DRAFT;
  490. $this->statut = self::STATUS_DRAFT;
  491. $this->linked_objects = $_facrec->linkedObjectsIds;
  492. // We do not add link to template invoice or next invoice will be linked to all generated invoices
  493. //$this->linked_objects['facturerec'][0] = $this->fac_rec;
  494. $forceduedate = $this->calculate_date_lim_reglement();
  495. // For recurring invoices, update date and number of last generation of recurring template invoice, before inserting new invoice
  496. if ($_facrec->frequency > 0) {
  497. dol_syslog("This is a recurring invoice so we set date_last_gen and next date_when");
  498. if (empty($_facrec->date_when)) {
  499. $_facrec->date_when = $now;
  500. }
  501. $next_date = $_facrec->getNextDate(); // Calculate next date
  502. $result = $_facrec->setValueFrom('date_last_gen', $now, '', null, 'date', '', $user, '');
  503. //$_facrec->setValueFrom('nb_gen_done', $_facrec->nb_gen_done + 1); // Not required, +1 already included into setNextDate when second param is 1.
  504. $result = $_facrec->setNextDate($next_date, 1);
  505. }
  506. // Define lang of customer
  507. $outputlangs = $langs;
  508. $newlang = '';
  509. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($this->thirdparty->default_lang)) {
  510. $newlang = $this->thirdparty->default_lang; // for proposal, order, invoice, ...
  511. }
  512. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($this->default_lang)) {
  513. $newlang = $this->default_lang; // for thirdparty
  514. }
  515. if (!empty($newlang)) {
  516. $outputlangs = new Translate("", $conf);
  517. $outputlangs->setDefaultLang($newlang);
  518. }
  519. // Array of possible substitutions (See also file mailing-send.php that should manage same substitutions)
  520. $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $this);
  521. $substitutionarray['__INVOICE_PREVIOUS_MONTH__'] = dol_print_date(dol_time_plus_duree($this->date, -1, 'm'), '%m');
  522. $substitutionarray['__INVOICE_MONTH__'] = dol_print_date($this->date, '%m');
  523. $substitutionarray['__INVOICE_NEXT_MONTH__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'm'), '%m');
  524. $substitutionarray['__INVOICE_PREVIOUS_MONTH_TEXT__'] = dol_print_date(dol_time_plus_duree($this->date, -1, 'm'), '%B');
  525. $substitutionarray['__INVOICE_MONTH_TEXT__'] = dol_print_date($this->date, '%B');
  526. $substitutionarray['__INVOICE_NEXT_MONTH_TEXT__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'm'), '%B');
  527. $substitutionarray['__INVOICE_PREVIOUS_YEAR__'] = dol_print_date(dol_time_plus_duree($this->date, -1, 'y'), '%Y');
  528. $substitutionarray['__INVOICE_YEAR__'] = dol_print_date($this->date, '%Y');
  529. $substitutionarray['__INVOICE_NEXT_YEAR__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'y'), '%Y');
  530. // Only for template invoice
  531. $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = (isset($originaldatewhen) ? dol_print_date($originaldatewhen, 'dayhour') : '');
  532. $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = (isset($nextdatewhen) ? dol_print_date($nextdatewhen, 'dayhour') : '');
  533. $substitutionarray['__INVOICE_PREVIOUS_DATE_NEXT_INVOICE_AFTER_GEN__'] = (isset($previousdaynextdatewhen) ? dol_print_date($previousdaynextdatewhen, 'dayhour') : '');
  534. $substitutionarray['__INVOICE_COUNTER_CURRENT__'] = $_facrec->nb_gen_done;
  535. $substitutionarray['__INVOICE_COUNTER_MAX__'] = $_facrec->nb_gen_max;
  536. //var_dump($substitutionarray);exit;
  537. complete_substitutions_array($substitutionarray, $outputlangs);
  538. $this->note_public = make_substitutions($this->note_public, $substitutionarray);
  539. $this->note_private = make_substitutions($this->note_private, $substitutionarray);
  540. }
  541. // Define due date if not already defined
  542. if (empty($forceduedate)) {
  543. $duedate = $this->calculate_date_lim_reglement();
  544. /*if ($duedate < 0) { Regression, a date can be negative if before 1970.
  545. dol_syslog(__METHOD__ . ' Error in calculate_date_lim_reglement. We got ' . $duedate, LOG_ERR);
  546. return -1;
  547. }*/
  548. $this->date_lim_reglement = $duedate;
  549. } else {
  550. $this->date_lim_reglement = $forceduedate;
  551. }
  552. // Insert into database
  553. $socid = $this->socid;
  554. $sql = "INSERT INTO ".MAIN_DB_PREFIX."facture (";
  555. $sql .= " ref";
  556. $sql .= ", entity";
  557. $sql .= ", ref_ext";
  558. $sql .= ", type";
  559. $sql .= ", fk_soc";
  560. $sql .= ", datec";
  561. $sql .= ", remise_absolue";
  562. $sql .= ", remise_percent";
  563. $sql .= ", datef";
  564. $sql .= ", date_pointoftax";
  565. $sql .= ", note_private";
  566. $sql .= ", note_public";
  567. $sql .= ", ref_client, ref_int";
  568. $sql .= ", fk_account";
  569. $sql .= ", module_source, pos_source, fk_fac_rec_source, fk_facture_source, fk_user_author, fk_projet";
  570. $sql .= ", fk_cond_reglement, fk_mode_reglement, date_lim_reglement, model_pdf";
  571. $sql .= ", situation_cycle_ref, situation_counter, situation_final";
  572. $sql .= ", fk_incoterms, location_incoterms";
  573. $sql .= ", fk_multicurrency";
  574. $sql .= ", multicurrency_code";
  575. $sql .= ", multicurrency_tx";
  576. $sql .= ", retained_warranty";
  577. $sql .= ", retained_warranty_date_limit";
  578. $sql .= ", retained_warranty_fk_cond_reglement";
  579. $sql .= ")";
  580. $sql .= " VALUES (";
  581. $sql .= "'(PROV)'";
  582. $sql .= ", ".setEntity($this);
  583. $sql .= ", ".($this->ref_ext ? "'".$this->db->escape($this->ref_ext)."'" : "null");
  584. $sql .= ", '".$this->db->escape($this->type)."'";
  585. $sql .= ", ".((int) $socid);
  586. $sql .= ", '".$this->db->idate($now)."'";
  587. $sql .= ", ".($this->remise_absolue > 0 ? $this->remise_absolue : 'NULL');
  588. $sql .= ", ".($this->remise_percent > 0 ? $this->remise_percent : 'NULL');
  589. $sql .= ", '".$this->db->idate($this->date)."'";
  590. $sql .= ", ".(empty($this->date_pointoftax) ? "null" : "'".$this->db->idate($this->date_pointoftax)."'");
  591. $sql .= ", ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : "null");
  592. $sql .= ", ".($this->note_public ? "'".$this->db->escape($this->note_public)."'" : "null");
  593. $sql .= ", ".($this->ref_client ? "'".$this->db->escape($this->ref_client)."'" : "null");
  594. $sql .= ", ".($this->ref_int ? "'".$this->db->escape($this->ref_int)."'" : "null");
  595. $sql .= ", ".($this->fk_account > 0 ? $this->fk_account : 'NULL');
  596. $sql .= ", ".($this->module_source ? "'".$this->db->escape($this->module_source)."'" : "null");
  597. $sql .= ", ".($this->pos_source != '' ? "'".$this->db->escape($this->pos_source)."'" : "null");
  598. $sql .= ", ".($this->fk_fac_rec_source ? "'".$this->db->escape($this->fk_fac_rec_source)."'" : "null");
  599. $sql .= ", ".($this->fk_facture_source ? "'".$this->db->escape($this->fk_facture_source)."'" : "null");
  600. $sql .= ", ".($user->id > 0 ? (int) $user->id : "null");
  601. $sql .= ", ".($this->fk_project ? $this->fk_project : "null");
  602. $sql .= ", ".((int) $this->cond_reglement_id);
  603. $sql .= ", ".((int) $this->mode_reglement_id);
  604. $sql .= ", '".$this->db->idate($this->date_lim_reglement)."'";
  605. $sql .= ", ".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null");
  606. $sql .= ", ".($this->situation_cycle_ref ? "'".$this->db->escape($this->situation_cycle_ref)."'" : "null");
  607. $sql .= ", ".($this->situation_counter ? "'".$this->db->escape($this->situation_counter)."'" : "null");
  608. $sql .= ", ".($this->situation_final ? $this->situation_final : 0);
  609. $sql .= ", ".(int) $this->fk_incoterms;
  610. $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
  611. $sql .= ", ".(int) $this->fk_multicurrency;
  612. $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
  613. $sql .= ", ".(double) $this->multicurrency_tx;
  614. $sql .= ", ".(empty($this->retained_warranty) ? "0" : $this->db->escape($this->retained_warranty));
  615. $sql .= ", ".(!empty($this->retained_warranty_date_limit) ? "'".$this->db->idate($this->retained_warranty_date_limit)."'" : 'NULL');
  616. $sql .= ", ".(int) $this->retained_warranty_fk_cond_reglement;
  617. $sql .= ")";
  618. $resql = $this->db->query($sql);
  619. if ($resql) {
  620. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture');
  621. // Update ref with new one
  622. $this->ref = '(PROV'.$this->id.')';
  623. $sql = 'UPDATE '.MAIN_DB_PREFIX."facture SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".((int) $this->id);
  624. $resql = $this->db->query($sql);
  625. if (!$resql) {
  626. $error++;
  627. }
  628. if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects
  629. $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
  630. }
  631. // Add object linked
  632. if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
  633. foreach ($this->linked_objects as $origin => $tmp_origin_id) {
  634. if (is_array($tmp_origin_id)) { // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...))
  635. foreach ($tmp_origin_id as $origin_id) {
  636. $ret = $this->add_object_linked($origin, $origin_id);
  637. if (!$ret) {
  638. $this->error = $this->db->lasterror();
  639. $error++;
  640. }
  641. }
  642. } else // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
  643. {
  644. $origin_id = $tmp_origin_id;
  645. $ret = $this->add_object_linked($origin, $origin_id);
  646. if (!$ret) {
  647. $this->error = $this->db->lasterror();
  648. $error++;
  649. }
  650. }
  651. }
  652. }
  653. // Propagate contacts
  654. if (!$error && $this->id && !empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN) && !empty($this->origin) && !empty($this->origin_id)) { // Get contact from origin object
  655. $originforcontact = $this->origin;
  656. $originidforcontact = $this->origin_id;
  657. if ($originforcontact == 'shipping') { // shipment and order share the same contacts. If creating from shipment we take data of order
  658. require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
  659. $exp = new Expedition($this->db);
  660. $exp->fetch($this->origin_id);
  661. $exp->fetchObjectLinked(null, '', null, '', 'OR', 1, 'sourcetype', 0);
  662. if (count($exp->linkedObjectsIds['commande']) > 0) {
  663. foreach ($exp->linkedObjectsIds['commande'] as $key => $value) {
  664. $originforcontact = 'commande';
  665. if (is_object($value)) {
  666. $originidforcontact = $value->id;
  667. } else {
  668. $originidforcontact = $value;
  669. }
  670. break; // We take first one
  671. }
  672. }
  673. }
  674. $sqlcontact = "SELECT ctc.code, ctc.source, ec.fk_socpeople FROM ".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as ctc";
  675. $sqlcontact .= " WHERE element_id = ".((int) $originidforcontact)." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact)."'";
  676. $resqlcontact = $this->db->query($sqlcontact);
  677. if ($resqlcontact) {
  678. while ($objcontact = $this->db->fetch_object($resqlcontact)) {
  679. //print $objcontact->code.'-'.$objcontact->source.'-'.$objcontact->fk_socpeople."\n";
  680. $this->add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source); // May failed because of duplicate key or because code of contact type does not exists for new object
  681. }
  682. } else {
  683. dol_print_error($resqlcontact);
  684. }
  685. }
  686. /*
  687. * Insert lines of invoices, if not from template invoice, into database
  688. */
  689. if (!$error && empty($this->fac_rec) && count($this->lines) && is_object($this->lines[0])) { // If this->lines is array of InvoiceLines (preferred mode)
  690. $fk_parent_line = 0;
  691. dol_syslog("There is ".count($this->lines)." lines that are invoice lines objects");
  692. foreach ($this->lines as $i => $val) {
  693. $newinvoiceline = $this->lines[$i];
  694. $newinvoiceline->context = $this->context;
  695. $newinvoiceline->fk_facture = $this->id;
  696. $newinvoiceline->origin = $this->lines[$i]->element;
  697. $newinvoiceline->origin_id = $this->lines[$i]->id;
  698. // Auto set date of service ?
  699. if ($this->lines[$i]->date_start_fill == 1 && $originaldatewhen) { // $originaldatewhen is defined when generating from recurring invoice only
  700. $newinvoiceline->date_start = $originaldatewhen;
  701. }
  702. if ($this->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) { // $previousdaynextdatewhen is defined when generating from recurring invoice only
  703. $newinvoiceline->date_end = $previousdaynextdatewhen;
  704. }
  705. if ($result >= 0) {
  706. // Reset fk_parent_line for no child products and special product
  707. if (($newinvoiceline->product_type != 9 && empty($newinvoiceline->fk_parent_line)) || $newinvoiceline->product_type == 9) {
  708. $fk_parent_line = 0;
  709. }
  710. // Complete vat rate with code
  711. $vatrate = $newinvoiceline->tva_tx;
  712. if ($newinvoiceline->vat_src_code && ! preg_match('/\(.*\)/', $vatrate)) $vatrate.=' ('.$newinvoiceline->vat_src_code.')';
  713. $newinvoiceline->fk_parent_line = $fk_parent_line;
  714. if ($this->type === Facture::TYPE_REPLACEMENT && $newinvoiceline->fk_remise_except) {
  715. $discount = new DiscountAbsolute($this->db);
  716. $discount->fetch($newinvoiceline->fk_remise_except);
  717. $discountId = $soc->set_remise_except($discount->amount_ht, $user, $discount->description, $discount->tva_tx);
  718. $newinvoiceline->fk_remise_except = $discountId;
  719. }
  720. $result = $this->addline(
  721. $newinvoiceline->desc,
  722. $newinvoiceline->subprice,
  723. $newinvoiceline->qty,
  724. $vatrate,
  725. $newinvoiceline->localtax1_tx,
  726. $newinvoiceline->localtax2_tx,
  727. $newinvoiceline->fk_product,
  728. $newinvoiceline->remise_percent,
  729. $newinvoiceline->date_start,
  730. $newinvoiceline->date_end,
  731. $newinvoiceline->fk_code_ventilation,
  732. $newinvoiceline->info_bits,
  733. $newinvoiceline->fk_remise_except,
  734. 'HT',
  735. 0,
  736. $newinvoiceline->product_type,
  737. $newinvoiceline->rang,
  738. $newinvoiceline->special_code,
  739. $newinvoiceline->element,
  740. $newinvoiceline->id,
  741. $fk_parent_line,
  742. $newinvoiceline->fk_fournprice,
  743. $newinvoiceline->pa_ht,
  744. $newinvoiceline->label,
  745. $newinvoiceline->array_options,
  746. $newinvoiceline->situation_percent,
  747. $newinvoiceline->fk_prev_id,
  748. $newinvoiceline->fk_unit,
  749. $newinvoiceline->multicurrency_subprice,
  750. $newinvoiceline->ref_ext,
  751. 1
  752. );
  753. // Defined the new fk_parent_line
  754. if ($result > 0) {
  755. $fk_parent_line = $result;
  756. }
  757. }
  758. if ($result < 0) {
  759. $this->error = $newinvoiceline->error;
  760. $this->errors = $newinvoiceline->errors;
  761. $error++;
  762. break;
  763. }
  764. }
  765. } elseif (!$error && empty($this->fac_rec)) { // If this->lines is an array of invoice line arrays
  766. $fk_parent_line = 0;
  767. dol_syslog("There is ".count($this->lines)." lines that are array lines");
  768. foreach ($this->lines as $i => $val) {
  769. $line = $this->lines[$i];
  770. // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
  771. //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
  772. if (!is_object($line)) {
  773. $line = (object) $line;
  774. }
  775. if ($result >= 0) {
  776. // Reset fk_parent_line for no child products and special product
  777. if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
  778. $fk_parent_line = 0;
  779. }
  780. // Complete vat rate with code
  781. $vatrate = $line->tva_tx;
  782. if ($line->vat_src_code && !preg_match('/\(.*\)/', $vatrate)) {
  783. $vatrate .= ' ('.$line->vat_src_code.')';
  784. }
  785. if (!empty($conf->global->MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION)) {
  786. $originid = $line->origin_id;
  787. $origintype = $line->origin;
  788. } else {
  789. $originid = $line->id;
  790. $origintype = $this->element;
  791. }
  792. // init ref_ext
  793. if (empty($line->ref_ext)) {
  794. $line->ref_ext = '';
  795. }
  796. $result = $this->addline(
  797. $line->desc,
  798. $line->subprice,
  799. $line->qty,
  800. $vatrate,
  801. $line->localtax1_tx,
  802. $line->localtax2_tx,
  803. $line->fk_product,
  804. $line->remise_percent,
  805. $line->date_start,
  806. $line->date_end,
  807. $line->fk_code_ventilation,
  808. $line->info_bits,
  809. $line->fk_remise_except,
  810. 'HT',
  811. 0,
  812. $line->product_type,
  813. $line->rang,
  814. $line->special_code,
  815. $origintype,
  816. $originid,
  817. $fk_parent_line,
  818. $line->fk_fournprice,
  819. $line->pa_ht,
  820. $line->label,
  821. $line->array_options,
  822. $line->situation_percent,
  823. $line->fk_prev_id,
  824. $line->fk_unit,
  825. $line->multicurrency_subprice,
  826. $line->ref_ext,
  827. 1
  828. );
  829. if ($result < 0) {
  830. $this->error = $this->db->lasterror();
  831. dol_print_error($this->db);
  832. $this->db->rollback();
  833. return -1;
  834. }
  835. // Defined the new fk_parent_line
  836. if ($result > 0 && $line->product_type == 9) {
  837. $fk_parent_line = $result;
  838. }
  839. }
  840. }
  841. }
  842. /*
  843. * Insert lines of template invoices
  844. */
  845. if (!$error && $this->fac_rec > 0) {
  846. foreach ($_facrec->lines as $i => $val) {
  847. if ($_facrec->lines[$i]->fk_product) {
  848. $prod = new Product($this->db);
  849. $res = $prod->fetch($_facrec->lines[$i]->fk_product);
  850. }
  851. // For line from template invoice, we use data from template invoice
  852. /*
  853. $tva_tx = get_default_tva($mysoc,$soc,$prod->id);
  854. $tva_npr = get_default_npr($mysoc,$soc,$prod->id);
  855. if (empty($tva_tx)) $tva_npr=0;
  856. $localtax1_tx=get_localtax($tva_tx,1,$soc,$mysoc,$tva_npr);
  857. $localtax2_tx=get_localtax($tva_tx,2,$soc,$mysoc,$tva_npr);
  858. */
  859. $tva_tx = $_facrec->lines[$i]->tva_tx.($_facrec->lines[$i]->vat_src_code ? '('.$_facrec->lines[$i]->vat_src_code.')' : '');
  860. $tva_npr = $_facrec->lines[$i]->info_bits;
  861. if (empty($tva_tx)) {
  862. $tva_npr = 0;
  863. }
  864. $localtax1_tx = $_facrec->lines[$i]->localtax1_tx;
  865. $localtax2_tx = $_facrec->lines[$i]->localtax2_tx;
  866. $fk_product_fournisseur_price = empty($_facrec->lines[$i]->fk_product_fournisseur_price) ? null : $_facrec->lines[$i]->fk_product_fournisseur_price;
  867. $buyprice = empty($_facrec->lines[$i]->buyprice) ? 0 : $_facrec->lines[$i]->buyprice;
  868. // If buyprice not defined from template invoice, we try to guess the best value
  869. if (!$buyprice && $_facrec->lines[$i]->fk_product > 0) {
  870. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  871. $producttmp = new ProductFournisseur($this->db);
  872. $producttmp->fetch($_facrec->lines[$i]->fk_product);
  873. // If margin module defined on costprice, we try the costprice
  874. // If not defined or if module margin defined and pmp and stock module enabled, we try pmp price
  875. // else we get the best supplier price
  876. if ($conf->global->MARGIN_TYPE == 'costprice' && !empty($producttmp->cost_price)) {
  877. $buyprice = $producttmp->cost_price;
  878. } elseif (!empty($conf->stock->enabled) && ($conf->global->MARGIN_TYPE == 'costprice' || $conf->global->MARGIN_TYPE == 'pmp') && !empty($producttmp->pmp)) {
  879. $buyprice = $producttmp->pmp;
  880. } else {
  881. if ($producttmp->find_min_price_product_fournisseur($_facrec->lines[$i]->fk_product) > 0) {
  882. if ($producttmp->product_fourn_price_id > 0) {
  883. $buyprice = price2num($producttmp->fourn_unitprice * (1 - $producttmp->fourn_remise_percent / 100) + $producttmp->fourn_remise, 'MU');
  884. }
  885. }
  886. }
  887. }
  888. $result_insert = $this->addline(
  889. $_facrec->lines[$i]->desc,
  890. $_facrec->lines[$i]->subprice,
  891. $_facrec->lines[$i]->qty,
  892. $tva_tx,
  893. $localtax1_tx,
  894. $localtax2_tx,
  895. $_facrec->lines[$i]->fk_product,
  896. $_facrec->lines[$i]->remise_percent,
  897. ($_facrec->lines[$i]->date_start_fill == 1 && $originaldatewhen) ? $originaldatewhen : '',
  898. ($_facrec->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) ? $previousdaynextdatewhen : '',
  899. 0,
  900. $tva_npr,
  901. '',
  902. 'HT',
  903. 0,
  904. $_facrec->lines[$i]->product_type,
  905. $_facrec->lines[$i]->rang,
  906. $_facrec->lines[$i]->special_code,
  907. '',
  908. 0,
  909. 0,
  910. $fk_product_fournisseur_price,
  911. $buyprice,
  912. $_facrec->lines[$i]->label,
  913. empty($_facrec->lines[$i]->array_options) ?null:$_facrec->lines[$i]->array_options,
  914. $_facrec->lines[$i]->situation_percent,
  915. '',
  916. $_facrec->lines[$i]->fk_unit,
  917. $_facrec->lines[$i]->multicurrency_subprice,
  918. $_facrec->lines[$i]->ref_ext,
  919. 1
  920. );
  921. if ($result_insert < 0) {
  922. $error++;
  923. $this->error = $this->db->error();
  924. break;
  925. }
  926. }
  927. }
  928. if (!$error) {
  929. $result = $this->update_price(1, 'auto', 0, $mysoc);
  930. if ($result > 0) {
  931. $action = 'create';
  932. // Actions on extra fields
  933. if (!$error) {
  934. $result = $this->insertExtraFields();
  935. if ($result < 0) {
  936. $error++;
  937. }
  938. }
  939. if (!$error && !$notrigger) {
  940. // Call trigger
  941. $result = $this->call_trigger('BILL_CREATE', $user);
  942. if ($result < 0) {
  943. $error++;
  944. }
  945. // End call triggers
  946. }
  947. if (!$error) {
  948. $this->db->commit();
  949. return $this->id;
  950. } else {
  951. $this->db->rollback();
  952. return -4;
  953. }
  954. } else {
  955. $this->error = $langs->trans('FailedToUpdatePrice');
  956. $this->db->rollback();
  957. return -3;
  958. }
  959. } else {
  960. dol_syslog(get_class($this)."::create error ".$this->error, LOG_ERR);
  961. $this->db->rollback();
  962. return -2;
  963. }
  964. } else {
  965. $this->error = $this->db->error();
  966. $this->db->rollback();
  967. return -1;
  968. }
  969. }
  970. /**
  971. * Create a new invoice in database from current invoice
  972. *
  973. * @param User $user Object user that ask creation
  974. * @param int $invertdetail Reverse sign of amounts for lines
  975. * @return int <0 if KO, >0 if OK
  976. */
  977. public function createFromCurrent(User $user, $invertdetail = 0)
  978. {
  979. global $conf;
  980. // Source invoice load
  981. $facture = new Facture($this->db);
  982. // Retrieve all extrafield
  983. // fetch optionals attributes and labels
  984. $this->fetch_optionals();
  985. if (!empty($this->array_options)) {
  986. $facture->array_options = $this->array_options;
  987. }
  988. foreach ($this->lines as &$line) {
  989. $line->fetch_optionals(); //fetch extrafields
  990. }
  991. $facture->fk_facture_source = $this->fk_facture_source;
  992. $facture->type = $this->type;
  993. $facture->socid = $this->socid;
  994. $facture->date = $this->date;
  995. $facture->date_pointoftax = $this->date_pointoftax;
  996. $facture->note_public = $this->note_public;
  997. $facture->note_private = $this->note_private;
  998. $facture->ref_client = $this->ref_client;
  999. $facture->modelpdf = $this->model_pdf; // deprecated
  1000. $facture->model_pdf = $this->model_pdf;
  1001. $facture->fk_project = $this->fk_project;
  1002. $facture->cond_reglement_id = $this->cond_reglement_id;
  1003. $facture->mode_reglement_id = $this->mode_reglement_id;
  1004. $facture->remise_absolue = $this->remise_absolue;
  1005. $facture->remise_percent = $this->remise_percent;
  1006. $facture->origin = $this->origin;
  1007. $facture->origin_id = $this->origin_id;
  1008. $facture->lines = $this->lines; // Array of lines of invoice
  1009. $facture->situation_counter = $this->situation_counter;
  1010. $facture->situation_cycle_ref = $this->situation_cycle_ref;
  1011. $facture->situation_final = $this->situation_final;
  1012. $facture->retained_warranty = $this->retained_warranty;
  1013. $facture->retained_warranty_fk_cond_reglement = $this->retained_warranty_fk_cond_reglement;
  1014. $facture->retained_warranty_date_limit = $this->retained_warranty_date_limit;
  1015. $facture->fk_user_author = $user->id;
  1016. // Loop on each line of new invoice
  1017. foreach ($facture->lines as $i => $tmpline) {
  1018. $facture->lines[$i]->fk_prev_id = $this->lines[$i]->rowid;
  1019. if ($invertdetail) {
  1020. $facture->lines[$i]->subprice = -$facture->lines[$i]->subprice;
  1021. $facture->lines[$i]->total_ht = -$facture->lines[$i]->total_ht;
  1022. $facture->lines[$i]->total_tva = -$facture->lines[$i]->total_tva;
  1023. $facture->lines[$i]->total_localtax1 = -$facture->lines[$i]->total_localtax1;
  1024. $facture->lines[$i]->total_localtax2 = -$facture->lines[$i]->total_localtax2;
  1025. $facture->lines[$i]->total_ttc = -$facture->lines[$i]->total_ttc;
  1026. $facture->lines[$i]->ref_ext = '';
  1027. }
  1028. }
  1029. dol_syslog(get_class($this)."::createFromCurrent invertdetail=".$invertdetail." socid=".$this->socid." nboflines=".count($facture->lines));
  1030. $facid = $facture->create($user);
  1031. if ($facid <= 0) {
  1032. $this->error = $facture->error;
  1033. $this->errors = $facture->errors;
  1034. } elseif ($this->type == self::TYPE_SITUATION && !empty($conf->global->INVOICE_USE_SITUATION)) {
  1035. $this->fetchObjectLinked('', '', $this->id, 'facture');
  1036. foreach ($this->linkedObjectsIds as $typeObject => $Tfk_object) {
  1037. foreach ($Tfk_object as $fk_object) {
  1038. $facture->add_object_linked($typeObject, $fk_object);
  1039. }
  1040. }
  1041. $facture->add_object_linked('facture', $this->fk_facture_source);
  1042. }
  1043. return $facid;
  1044. }
  1045. /**
  1046. * Load an object from its id and create a new one in database
  1047. *
  1048. * @param User $user User that clone
  1049. * @param int $fromid Id of object to clone
  1050. * @return int New id of clone
  1051. */
  1052. public function createFromClone(User $user, $fromid = 0)
  1053. {
  1054. global $conf, $hookmanager;
  1055. $error = 0;
  1056. $object = new Facture($this->db);
  1057. $this->db->begin();
  1058. $object->fetch($fromid);
  1059. // Load source object
  1060. $objFrom = clone $object;
  1061. // Change socid if needed
  1062. if (!empty($this->socid) && $this->socid != $object->socid) {
  1063. $objsoc = new Societe($this->db);
  1064. if ($objsoc->fetch($this->socid) > 0) {
  1065. $object->socid = $objsoc->id;
  1066. $object->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
  1067. $object->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
  1068. $object->fk_project = '';
  1069. $object->fk_delivery_address = '';
  1070. }
  1071. // TODO Change product price if multi-prices
  1072. }
  1073. $object->id = 0;
  1074. $object->statut = self::STATUS_DRAFT;
  1075. $object->status = self::STATUS_DRAFT;
  1076. // Clear fields
  1077. $object->date = (empty($this->date) ? dol_now() : $this->date);
  1078. $object->user_author = $user->id; // deprecated
  1079. $object->user_valid = null; // deprecated
  1080. $object->fk_user_author = $user->id;
  1081. $object->fk_user_valid = null;
  1082. $object->fk_facture_source = 0;
  1083. $object->date_creation = '';
  1084. $object->date_modification = '';
  1085. $object->date_validation = '';
  1086. $object->ref_client = '';
  1087. $object->close_code = '';
  1088. $object->close_note = '';
  1089. if ($conf->global->MAIN_DONT_KEEP_NOTE_ON_CLONING == 1) {
  1090. $object->note_private = '';
  1091. $object->note_public = '';
  1092. }
  1093. // Loop on each line of new invoice
  1094. foreach ($object->lines as $i => $line) {
  1095. if (($object->lines[$i]->info_bits & 0x02) == 0x02) { // We do not clone line of discounts
  1096. unset($object->lines[$i]);
  1097. continue;
  1098. }
  1099. // Bloc to update dates of service (month by month only if previously filled and similare to start and end of month)
  1100. // If it's a service with start and end dates
  1101. if (!empty($conf->global->INVOICE_AUTO_NEXT_MONTH_ON_LINES) && !empty($line->date_start) && !empty($line->date_end)) {
  1102. // Get the dates
  1103. $start = dol_getdate($line->date_start);
  1104. $end = dol_getdate($line->date_end);
  1105. // Get the first and last day of the month
  1106. $first = dol_get_first_day($start['year'], $start['mon']);
  1107. $last = dol_get_last_day($end['year'], $end['mon']);
  1108. //print dol_print_date(dol_mktime(0, 0, 0, $start['mon'], $start['mday'], $start['year'], 'gmt'), 'dayhour').' '.dol_print_date($first, 'dayhour').'<br>';
  1109. //print dol_mktime(23, 59, 59, $end['mon'], $end['mday'], $end['year'], 'gmt').' '.$last.'<br>';exit;
  1110. // If start date is first date of month and end date is last date of month
  1111. if (dol_mktime(0, 0, 0, $start['mon'], $start['mday'], $start['year'], 'gmt') == $first
  1112. && dol_mktime(23, 59, 59, $end['mon'], $end['mday'], $end['year'], 'gmt') == $last) {
  1113. $nextMonth = dol_get_next_month($end['mon'], $end['year']);
  1114. $newFirst = dol_get_first_day($nextMonth['year'], $nextMonth['month']);
  1115. $newLast = dol_get_last_day($nextMonth['year'], $nextMonth['month']);
  1116. $object->lines[$i]->date_start = $newFirst;
  1117. $object->lines[$i]->date_end = $newLast;
  1118. }
  1119. }
  1120. $object->lines[$i]->ref_ext = ''; // Do not clone ref_ext
  1121. }
  1122. // Create clone
  1123. $object->context['createfromclone'] = 'createfromclone';
  1124. $result = $object->create($user);
  1125. if ($result < 0) {
  1126. $error++;
  1127. $this->error = $object->error;
  1128. $this->errors = $object->errors;
  1129. } else {
  1130. // copy internal contacts
  1131. if ($object->copy_linked_contact($objFrom, 'internal') < 0) {
  1132. $error++;
  1133. $this->error = $object->error;
  1134. $this->errors = $object->errors;
  1135. } elseif ($object->socid == $objFrom->socid) {
  1136. // copy external contacts if same company
  1137. if ($object->copy_linked_contact($objFrom, 'external') < 0) {
  1138. $error++;
  1139. $this->error = $object->error;
  1140. $this->errors = $object->errors;
  1141. }
  1142. }
  1143. }
  1144. if (!$error) {
  1145. // Hook of thirdparty module
  1146. if (is_object($hookmanager)) {
  1147. $parameters = array('objFrom'=>$objFrom);
  1148. $action = '';
  1149. $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  1150. if ($reshook < 0) {
  1151. $error++;
  1152. }
  1153. }
  1154. }
  1155. unset($object->context['createfromclone']);
  1156. // End
  1157. if (!$error) {
  1158. $this->db->commit();
  1159. return $object->id;
  1160. } else {
  1161. $this->db->rollback();
  1162. return -1;
  1163. }
  1164. }
  1165. /**
  1166. * Load an object from an order and create a new invoice into database
  1167. *
  1168. * @param Object $object Object source
  1169. * @param User $user Object user
  1170. * @return int <0 if KO, 0 if nothing done, 1 if OK
  1171. */
  1172. public function createFromOrder($object, User $user)
  1173. {
  1174. global $conf, $hookmanager;
  1175. $error = 0;
  1176. // Closed order
  1177. $this->date = dol_now();
  1178. $this->source = 0;
  1179. $num = count($object->lines);
  1180. for ($i = 0; $i < $num; $i++) {
  1181. $line = new FactureLigne($this->db);
  1182. $line->libelle = $object->lines[$i]->libelle; // deprecated
  1183. $line->label = $object->lines[$i]->label;
  1184. $line->desc = $object->lines[$i]->desc;
  1185. $line->subprice = $object->lines[$i]->subprice;
  1186. $line->total_ht = $object->lines[$i]->total_ht;
  1187. $line->total_tva = $object->lines[$i]->total_tva;
  1188. $line->total_localtax1 = $object->lines[$i]->total_localtax1;
  1189. $line->total_localtax2 = $object->lines[$i]->total_localtax2;
  1190. $line->total_ttc = $object->lines[$i]->total_ttc;
  1191. $line->vat_src_code = $object->lines[$i]->vat_src_code;
  1192. $line->tva_tx = $object->lines[$i]->tva_tx;
  1193. $line->localtax1_tx = $object->lines[$i]->localtax1_tx;
  1194. $line->localtax2_tx = $object->lines[$i]->localtax2_tx;
  1195. $line->qty = $object->lines[$i]->qty;
  1196. $line->fk_remise_except = $object->lines[$i]->fk_remise_except;
  1197. $line->remise_percent = $object->lines[$i]->remise_percent;
  1198. $line->fk_product = $object->lines[$i]->fk_product;
  1199. $line->info_bits = $object->lines[$i]->info_bits;
  1200. $line->product_type = $object->lines[$i]->product_type;
  1201. $line->rang = $object->lines[$i]->rang;
  1202. $line->special_code = $object->lines[$i]->special_code;
  1203. $line->fk_parent_line = $object->lines[$i]->fk_parent_line;
  1204. $line->fk_unit = $object->lines[$i]->fk_unit;
  1205. $line->date_start = $object->lines[$i]->date_start;
  1206. $line->date_end = $object->lines[$i]->date_end;
  1207. // Multicurrency
  1208. $line->fk_multicurrency = $object->lines[$i]->fk_multicurrency;
  1209. $line->multicurrency_code = $object->lines[$i]->multicurrency_code;
  1210. $line->multicurrency_subprice = $object->lines[$i]->multicurrency_subprice;
  1211. $line->multicurrency_total_ht = $object->lines[$i]->multicurrency_total_ht;
  1212. $line->multicurrency_total_tva = $object->lines[$i]->multicurrency_total_tva;
  1213. $line->multicurrency_total_ttc = $object->lines[$i]->multicurrency_total_ttc;
  1214. $line->fk_fournprice = $object->lines[$i]->fk_fournprice;
  1215. $marginInfos = getMarginInfos($object->lines[$i]->subprice, $object->lines[$i]->remise_percent, $object->lines[$i]->tva_tx, $object->lines[$i]->localtax1_tx, $object->lines[$i]->localtax2_tx, $object->lines[$i]->fk_fournprice, $object->lines[$i]->pa_ht);
  1216. $line->pa_ht = $marginInfos[0];
  1217. // get extrafields from original line
  1218. $object->lines[$i]->fetch_optionals();
  1219. foreach ($object->lines[$i]->array_options as $options_key => $value) {
  1220. $line->array_options[$options_key] = $value;
  1221. }
  1222. $this->lines[$i] = $line;
  1223. }
  1224. $this->socid = $object->socid;
  1225. $this->fk_project = $object->fk_project;
  1226. $this->fk_account = $object->fk_account;
  1227. $this->cond_reglement_id = $object->cond_reglement_id;
  1228. $this->mode_reglement_id = $object->mode_reglement_id;
  1229. $this->availability_id = $object->availability_id;
  1230. $this->demand_reason_id = $object->demand_reason_id;
  1231. $this->delivery_date = (empty($object->delivery_date) ? $object->date_livraison : $object->delivery_date);
  1232. $this->date_livraison = $object->delivery_date; // deprecated
  1233. $this->fk_delivery_address = $object->fk_delivery_address; // deprecated
  1234. $this->contact_id = $object->contact_id;
  1235. $this->ref_client = $object->ref_client;
  1236. if (empty($conf->global->MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN)) {
  1237. $this->note_private = $object->note_private;
  1238. $this->note_public = $object->note_public;
  1239. }
  1240. $this->module_source = $object->module_source;
  1241. $this->pos_source = $object->pos_source;
  1242. $this->origin = $object->element;
  1243. $this->origin_id = $object->id;
  1244. $this->fk_user_author = $user->id;
  1245. // get extrafields from original line
  1246. $object->fetch_optionals();
  1247. foreach ($object->array_options as $options_key => $value) {
  1248. $this->array_options[$options_key] = $value;
  1249. }
  1250. // Possibility to add external linked objects with hooks
  1251. $this->linked_objects[$this->origin] = $this->origin_id;
  1252. if (!empty($object->other_linked_objects) && is_array($object->other_linked_objects)) {
  1253. $this->linked_objects = array_merge($this->linked_objects, $object->other_linked_objects);
  1254. }
  1255. $ret = $this->create($user);
  1256. if ($ret > 0) {
  1257. // Actions hooked (by external module)
  1258. $hookmanager->initHooks(array('invoicedao'));
  1259. $parameters = array('objFrom'=>$object);
  1260. $action = '';
  1261. $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1262. if ($reshook < 0) {
  1263. $error++;
  1264. }
  1265. if (!$error) {
  1266. return 1;
  1267. } else {
  1268. return -1;
  1269. }
  1270. } else {
  1271. return -1;
  1272. }
  1273. }
  1274. /**
  1275. * Creates a deposit from a proposal or an order by grouping lines by VAT rates
  1276. *
  1277. * @param Propal|Commande $origin The original proposal or order
  1278. * @param int $date Invoice date
  1279. * @param int $payment_terms_id Invoice payment terms
  1280. * @param User $user Object user
  1281. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  1282. * @param bool $autoValidateDeposit Whether to aumatically validate the deposit created
  1283. * @param array $overrideFields Array of fields to force values
  1284. * @return Facture|null The deposit created, or null if error (populates $origin->error in this case)
  1285. */
  1286. static public function createDepositFromOrigin(CommonObject $origin, $date, $payment_terms_id, User $user, $notrigger = 0, $autoValidateDeposit = false, $overrideFields = array())
  1287. {
  1288. global $conf, $langs, $hookmanager, $action;
  1289. if (! in_array($origin->element, array('propal', 'commande'))) {
  1290. $origin->error = 'ErrorCanOnlyAutomaticallyGenerateADepositFromProposalOrOrder';
  1291. return null;
  1292. }
  1293. if (empty($date)) {
  1294. $origin->error = $langs->trans('ErrorFieldRequired', $langs->transnoentities('DateInvoice'));
  1295. return null;
  1296. }
  1297. require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
  1298. if ($date > (dol_get_last_hour(dol_now('tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
  1299. $origin->error = 'ErrorDateIsInFuture';
  1300. return null;
  1301. }
  1302. if ($payment_terms_id <= 0) {
  1303. $origin->error = $langs->trans('ErrorFieldRequired', $langs->transnoentities('PaymentConditionsShort'));
  1304. return null;
  1305. }
  1306. $payment_conditions_deposit_percent = getDictionaryValue('c_payment_term', 'deposit_percent', $origin->cond_reglement_id);
  1307. if (empty($payment_conditions_deposit_percent)) {
  1308. $origin->error = 'ErrorPaymentConditionsNotEligibleToDepositCreation';
  1309. return null;
  1310. }
  1311. if (empty($origin->deposit_percent)) {
  1312. $origin->error = $langs->trans('ErrorFieldRequired', $langs->transnoentities('DepositPercent'));
  1313. return null;
  1314. }
  1315. $deposit = new self($origin->db);
  1316. $deposit->socid = $origin->socid;
  1317. $deposit->type = self::TYPE_DEPOSIT;
  1318. $deposit->fk_project = $origin->fk_project;
  1319. $deposit->ref_client = $origin->ref_client;
  1320. $deposit->date = $date;
  1321. $deposit->mode_reglement_id = $origin->mode_reglement_id;
  1322. $deposit->cond_reglement_id = $payment_terms_id;
  1323. $deposit->availability_id = $origin->availability_id;
  1324. $deposit->demand_reason_id = $origin->demand_reason_id;
  1325. $deposit->fk_account = $origin->fk_account;
  1326. $deposit->fk_incoterms = $origin->fk_incoterms;
  1327. $deposit->location_incoterms = $origin->location_incoterms;
  1328. $deposit->fk_multicurrency = $origin->fk_multicurrency;
  1329. $deposit->multicurrency_code = $origin->multicurrency_code;
  1330. $deposit->multicurrency_tx = $origin->multicurrency_tx;
  1331. $deposit->module_source = $origin->module_source;
  1332. $deposit->pos_source = $origin->pos_source;
  1333. $deposit->model_pdf = 'crabe';
  1334. $modelByTypeConfName = 'FACTURE_ADDON_PDF_' . $deposit->type;
  1335. if (!empty($conf->global->$modelByTypeConfName)) {
  1336. $deposit->model_pdf = $conf->global->$modelByTypeConfName;
  1337. } elseif (!empty($conf->global->FACTURE_ADDON_PDF)) {
  1338. $deposit->model_pdf = $conf->global->FACTURE_ADDON_PDF;
  1339. }
  1340. if (empty($conf->global->MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN)) {
  1341. $deposit->note_private = $origin->note_private;
  1342. $deposit->note_public = $origin->note_public;
  1343. }
  1344. $deposit->origin = $origin->element;
  1345. $deposit->origin_id = $origin->id;
  1346. $origin->fetch_optionals();
  1347. foreach ($origin->array_options as $extrakey => $value) {
  1348. $deposit->array_options[$extrakey] = $value;
  1349. }
  1350. $deposit->linked_objects[$deposit->origin] = $deposit->origin_id;
  1351. foreach ($overrideFields as $key => $value) {
  1352. $deposit->$key = $value;
  1353. }
  1354. $deposit->context['createdepositfromorigin'] = 'createdepositfromorigin';
  1355. $origin->db->begin();
  1356. // Facture::create() also imports contact from origin
  1357. $createReturn = $deposit->create($user, $notrigger);
  1358. if ($createReturn <= 0) {
  1359. $origin->db->rollback();
  1360. $origin->error = $deposit->error;
  1361. $origin->errors = $deposit->errors;
  1362. return null;
  1363. }
  1364. $amount_ttc_diff = 0;
  1365. $amountdeposit = array();
  1366. $descriptions = array();
  1367. if (! empty($conf->global->MAIN_DEPOSIT_MULTI_TVA)) {
  1368. $amount = $origin->total_ttc * ($origin->deposit_percent / 100);
  1369. $TTotalByTva = array();
  1370. foreach ($origin->lines as &$line) {
  1371. if (!empty($line->special_code)) {
  1372. continue;
  1373. }
  1374. $TTotalByTva[$line->tva_tx] += $line->total_ttc;
  1375. $descriptions[$line->tva_tx] .= '<li>' . (! empty($line->product_ref) ? $line->product_ref . ' - ' : '');
  1376. $descriptions[$line->tva_tx] .= (! empty($line->product_label) ? $line->product_label . ' - ' : '');
  1377. $descriptions[$line->tva_tx] .= $langs->trans('Qty') . ' : ' . $line->qty;
  1378. $descriptions[$line->tva_tx] .= ' - ' . $langs->trans('TotalHT') . ' : ' . price($line->total_ht) . '</li>';
  1379. }
  1380. foreach ($TTotalByTva as $tva => &$total) {
  1381. $coef = $total / $origin->total_ttc; // Calc coef
  1382. $am = $amount * $coef;
  1383. $amount_ttc_diff += $am;
  1384. $amountdeposit[$tva] += $am / (1 + $tva / 100); // Convert into HT for the addline
  1385. }
  1386. } else {
  1387. $totalamount = 0;
  1388. $lines = $origin->lines;
  1389. $numlines = count($lines);
  1390. for ($i = 0; $i < $numlines; $i++) {
  1391. if (empty($lines[$i]->qty)) {
  1392. continue; // We discard qty=0, it is an option
  1393. }
  1394. if (!empty($lines[$i]->special_code)) {
  1395. continue; // We discard special_code (frais port, ecotaxe, option, ...)
  1396. }
  1397. $totalamount += $lines[$i]->total_ht; // Fixme : is it not for the customer ? Shouldn't we take total_ttc ?
  1398. $tva_tx = $lines[$i]->tva_tx;
  1399. $amountdeposit[$tva_tx] += ($lines[$i]->total_ht * $origin->deposit_percent) / 100;
  1400. $descriptions[$tva_tx] .= '<li>' . (! empty($lines[$i]->product_ref) ? $lines[$i]->product_ref . ' - ' : '');
  1401. $descriptions[$tva_tx] .= (! empty($lines[$i]->product_label) ? $lines[$i]->product_label . ' - ' : '');
  1402. $descriptions[$tva_tx] .= $langs->trans('Qty') . ' : ' . $lines[$i]->qty;
  1403. $descriptions[$tva_tx] .= ' - ' . $langs->trans('TotalHT') . ' : ' . price($lines[$i]->total_ht) . '</li>';
  1404. }
  1405. if ($totalamount == 0) {
  1406. $amountdeposit[0] = 0;
  1407. }
  1408. $amount_ttc_diff = $amountdeposit[0];
  1409. }
  1410. foreach ($amountdeposit as $tva => $amount) {
  1411. if (empty($amount)) {
  1412. continue;
  1413. }
  1414. $descline = '(DEPOSIT) ('. $origin->deposit_percent .'%) - '.$origin->ref;
  1415. // Hidden conf
  1416. if (! empty($conf->global->INVOICE_DEPOSIT_VARIABLE_MODE_DETAIL_LINES_IN_DESCRIPTION) && ! empty($descriptions[$tva])) {
  1417. $descline .= '<ul>' . $descriptions[$tva] . '</ul>';
  1418. }
  1419. $addlineResult = $deposit->addline(
  1420. $descline,
  1421. $amount, // subprice
  1422. 1, // quantity
  1423. $tva, // vat rate
  1424. 0, // localtax1_tx
  1425. 0, // localtax2_tx
  1426. (empty($conf->global->INVOICE_PRODUCTID_DEPOSIT) ? 0 : $conf->global->INVOICE_PRODUCTID_DEPOSIT), // fk_product
  1427. 0, // remise_percent
  1428. 0, // date_start
  1429. 0, // date_end
  1430. 0,
  1431. 0, // info_bits
  1432. 0,
  1433. 'HT',
  1434. 0,
  1435. 0, // product_type
  1436. 1,
  1437. 0, // special_code
  1438. $deposit->origin,
  1439. 0,
  1440. 0,
  1441. 0,
  1442. 0
  1443. //,$langs->trans('Deposit') //Deprecated
  1444. );
  1445. if ($addlineResult < 0) {
  1446. $origin->db->rollback();
  1447. $origin->error = $deposit->error;
  1448. $origin->errors = $deposit->errors;
  1449. return null;
  1450. }
  1451. }
  1452. $diff = $deposit->total_ttc - $amount_ttc_diff;
  1453. if (!empty($conf->global->MAIN_DEPOSIT_MULTI_TVA) && $diff != 0) {
  1454. $deposit->fetch_lines();
  1455. $subprice_diff = $deposit->lines[0]->subprice - $diff / (1 + $deposit->lines[0]->tva_tx / 100);
  1456. $updatelineResult = $deposit->updateline(
  1457. $deposit->lines[0]->id,
  1458. $deposit->lines[0]->desc,
  1459. $subprice_diff,
  1460. $deposit->lines[0]->qty,
  1461. $deposit->lines[0]->remise_percent,
  1462. $deposit->lines[0]->date_start,
  1463. $deposit->lines[0]->date_end,
  1464. $deposit->lines[0]->tva_tx,
  1465. 0,
  1466. 0,
  1467. 'HT',
  1468. $deposit->lines[0]->info_bits,
  1469. $deposit->lines[0]->product_type,
  1470. 0,
  1471. 0,
  1472. 0,
  1473. $deposit->lines[0]->pa_ht,
  1474. $deposit->lines[0]->label,
  1475. 0,
  1476. array(),
  1477. 100
  1478. );
  1479. if ($updatelineResult < 0) {
  1480. $origin->db->rollback();
  1481. $origin->error = $deposit->error;
  1482. $origin->errors = $deposit->errors;
  1483. return null;
  1484. }
  1485. }
  1486. if (! is_object($hookmanager)) {
  1487. require_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
  1488. $hookmanager = new HookManager($origin->db);
  1489. }
  1490. $hookmanager->initHooks(array('invoicedao'));
  1491. $parameters = array('objFrom' => $origin);
  1492. $reshook = $hookmanager->executeHooks('createFrom', $parameters, $deposit, $action); // Note that $action and $object may have been
  1493. // modified by hook
  1494. if ($reshook < 0) {
  1495. $origin->db->rollback();
  1496. $origin->error = $hookmanager->error;
  1497. $origin->errors = $hookmanager->errors;
  1498. return null;
  1499. }
  1500. if (! empty($autoValidateDeposit)) {
  1501. $validateReturn = $deposit->validate($user, '', 0, $notrigger);
  1502. if ($validateReturn < 0) {
  1503. $origin->db->rollback();
  1504. $origin->error = $deposit->error;
  1505. $origin->errors = $deposit->errors;
  1506. return null;
  1507. }
  1508. }
  1509. unset($deposit->context['createdepositfromorigin']);
  1510. $origin->db->commit();
  1511. return $deposit;
  1512. }
  1513. /**
  1514. * Return clicable link of object (with eventually picto)
  1515. *
  1516. * @param int $withpicto Add picto into link
  1517. * @param string $option Where point the link
  1518. * @param int $max Maxlength of ref
  1519. * @param int $short 1=Return just URL
  1520. * @param string $moretitle Add more text to title tooltip
  1521. * @param int $notooltip 1=Disable tooltip
  1522. * @param int $addlinktonotes 1=Add link to notes
  1523. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  1524. * @param string $target Target of link ('', '_self', '_blank', '_parent', '_backoffice', ...)
  1525. * @return string String with URL
  1526. */
  1527. public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $addlinktonotes = 0, $save_lastsearch_value = -1, $target = '')
  1528. {
  1529. global $langs, $conf, $user, $mysoc;
  1530. if (!empty($conf->dol_no_mouse_hover)) {
  1531. $notooltip = 1; // Force disable tooltips
  1532. }
  1533. $result = '';
  1534. if ($option == 'withdraw') {
  1535. $url = DOL_URL_ROOT.'/compta/facture/prelevement.php?facid='.$this->id;
  1536. } else {
  1537. $url = DOL_URL_ROOT.'/compta/facture/card.php?facid='.$this->id;
  1538. }
  1539. if (!$user->rights->facture->lire) {
  1540. $option = 'nolink';
  1541. }
  1542. if ($option !== 'nolink') {
  1543. // Add param to save lastsearch_values or not
  1544. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  1545. if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  1546. $add_save_lastsearch_values = 1;
  1547. }
  1548. if ($add_save_lastsearch_values) {
  1549. $url .= '&save_lastsearch_values=1';
  1550. }
  1551. }
  1552. if ($short) {
  1553. return $url;
  1554. }
  1555. $picto = $this->picto;
  1556. if ($this->type == self::TYPE_REPLACEMENT) {
  1557. $picto .= 'r'; // Replacement invoice
  1558. }
  1559. if ($this->type == self::TYPE_CREDIT_NOTE) {
  1560. $picto .= 'a'; // Credit note
  1561. }
  1562. if ($this->type == self::TYPE_DEPOSIT) {
  1563. $picto .= 'd'; // Deposit invoice
  1564. }
  1565. $label = '';
  1566. if ($user->rights->facture->lire) {
  1567. $label = img_picto('', $picto).' <u class="paddingrightonly">'.$langs->trans("Invoice").'</u>';
  1568. if ($this->type == self::TYPE_REPLACEMENT) {
  1569. $label = img_picto('', $picto).' <u class="paddingrightonly">'.$langs->transnoentitiesnoconv("ReplacementInvoice").'</u>';
  1570. }
  1571. if ($this->type == self::TYPE_CREDIT_NOTE) {
  1572. $label = img_picto('', $picto).' <u class="paddingrightonly">'.$langs->transnoentitiesnoconv("CreditNote").'</u>';
  1573. }
  1574. if ($this->type == self::TYPE_DEPOSIT) {
  1575. $label = img_picto('', $picto).' <u class="paddingrightonly">'.$langs->transnoentitiesnoconv("Deposit").'</u>';
  1576. }
  1577. if ($this->type == self::TYPE_SITUATION) {
  1578. $label = img_picto('', $picto).' <u class="paddingrightonly">'.$langs->transnoentitiesnoconv("InvoiceSituation").'</u>';
  1579. }
  1580. if (isset($this->statut) && isset($this->alreadypaid)) {
  1581. $label .= ' '.$this->getLibStatut(5, $this->alreadypaid);
  1582. }
  1583. if (!empty($this->ref)) {
  1584. $label .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
  1585. }
  1586. if (!empty($this->ref_client)) {
  1587. $label .= '<br><b>'.$langs->trans('RefCustomer').':</b> '.$this->ref_client;
  1588. }
  1589. if (!empty($this->date)) {
  1590. $label .= '<br><b>'.$langs->trans('Date').':</b> '.dol_print_date($this->date, 'day');
  1591. }
  1592. if (!empty($this->total_ht)) {
  1593. $label .= '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
  1594. }
  1595. if (!empty($this->total_tva)) {
  1596. $label .= '<br><b>'.$langs->trans('AmountVAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
  1597. }
  1598. if (!empty($this->total_localtax1) && $this->total_localtax1 != 0) { // We keep test != 0 because $this->total_localtax1 can be '0.00000000'
  1599. $label .= '<br><b>'.$langs->transcountry('AmountLT1', $mysoc->country_code).':</b> '.price($this->total_localtax1, 0, $langs, 0, -1, -1, $conf->currency);
  1600. }
  1601. if (!empty($this->total_localtax2) && $this->total_localtax2 != 0) {
  1602. $label .= '<br><b>'.$langs->transcountry('AmountLT2', $mysoc->country_code).':</b> '.price($this->total_localtax2, 0, $langs, 0, -1, -1, $conf->currency);
  1603. }
  1604. if (!empty($this->total_ttc)) {
  1605. $label .= '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
  1606. }
  1607. if ($moretitle) {
  1608. $label .= ' - '.$moretitle;
  1609. }
  1610. }
  1611. $linkclose = ($target ? ' target="'.$target.'"' : '');
  1612. if (empty($notooltip) && $user->rights->facture->lire) {
  1613. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  1614. $label = $langs->trans("Invoice");
  1615. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  1616. }
  1617. $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
  1618. $linkclose .= ' class="classfortooltip"';
  1619. }
  1620. $linkstart = '<a href="'.$url.'"';
  1621. $linkstart .= $linkclose.'>';
  1622. $linkend = '</a>';
  1623. if ($option == 'nolink') {
  1624. $linkstart = '';
  1625. $linkend = '';
  1626. }
  1627. $result .= $linkstart;
  1628. if ($withpicto) {
  1629. $result .= img_object(($notooltip ? '' : $label), $picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
  1630. }
  1631. if ($withpicto != 2) {
  1632. $result .= ($max ?dol_trunc($this->ref, $max) : $this->ref);
  1633. }
  1634. $result .= $linkend;
  1635. if ($addlinktonotes) {
  1636. $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
  1637. if ($txttoshow) {
  1638. //$notetoshow = $langs->trans("ViewPrivateNote").':<br>'.dol_string_nohtmltag($txttoshow, 1);
  1639. $notetoshow = $langs->trans("ViewPrivateNote").':<br>'.$txttoshow;
  1640. $result .= ' <span class="note inline-block">';
  1641. $result .= '<a href="'.DOL_URL_ROOT.'/compta/facture/note.php?id='.$this->id.'" class="classfortooltip" title="'.dol_escape_htmltag($notetoshow, 1, 1).'">';
  1642. $result .= img_picto('', 'note');
  1643. $result .= '</a>';
  1644. //$result.=img_picto($langs->trans("ViewNote"),'object_generic');
  1645. //$result.='</a>';
  1646. $result .= '</span>';
  1647. }
  1648. }
  1649. global $action, $hookmanager;
  1650. $hookmanager->initHooks(array('invoicedao'));
  1651. $parameters = array('id'=>$this->id, 'getnomurl' => &$result, 'notooltip' => $notooltip, 'addlinktonotes' => $addlinktonotes, 'save_lastsearch_value'=> $save_lastsearch_value, 'target' => $target);
  1652. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1653. if ($reshook > 0) {
  1654. $result = $hookmanager->resPrint;
  1655. } else {
  1656. $result .= $hookmanager->resPrint;
  1657. }
  1658. return $result;
  1659. }
  1660. /**
  1661. * Get object from database. Get also lines.
  1662. *
  1663. * @param int $rowid Id of object to load
  1664. * @param string $ref Reference of invoice
  1665. * @param string $ref_ext External reference of invoice
  1666. * @param int $notused Not used
  1667. * @param bool $fetch_situation Load also the previous and next situation invoice into $tab_previous_situation_invoice and $tab_next_situation_invoice
  1668. * @return int >0 if OK, <0 if KO, 0 if not found
  1669. */
  1670. public function fetch($rowid, $ref = '', $ref_ext = '', $notused = '', $fetch_situation = false)
  1671. {
  1672. if (empty($rowid) && empty($ref) && empty($ref_ext)) {
  1673. return -1;
  1674. }
  1675. $sql = 'SELECT f.rowid,f.entity,f.ref,f.ref_client,f.ref_ext,f.ref_int,f.type,f.fk_soc';
  1676. $sql .= ', f.total_tva, f.localtax1, f.localtax2, f.total_ht, f.total_ttc, f.revenuestamp';
  1677. $sql .= ', f.remise_percent, f.remise_absolue, f.remise';
  1678. $sql .= ', f.datef as df, f.date_pointoftax';
  1679. $sql .= ', f.date_lim_reglement as dlr';
  1680. $sql .= ', f.datec as datec';
  1681. $sql .= ', f.date_valid as datev';
  1682. $sql .= ', f.tms as datem';
  1683. $sql .= ', f.note_private, f.note_public, f.fk_statut, f.paye, f.close_code, f.close_note, f.fk_user_author, f.fk_user_valid, f.model_pdf, f.last_main_doc';
  1684. $sql .= ', f.fk_facture_source, f.fk_fac_rec_source';
  1685. $sql .= ', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet as fk_project, f.extraparams';
  1686. $sql .= ', f.situation_cycle_ref, f.situation_counter, f.situation_final';
  1687. $sql .= ', f.fk_account';
  1688. $sql .= ", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc";
  1689. $sql .= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
  1690. $sql .= ', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc';
  1691. $sql .= ', f.fk_incoterms, f.location_incoterms';
  1692. $sql .= ', f.module_source, f.pos_source';
  1693. $sql .= ", i.libelle as label_incoterms";
  1694. $sql .= ", f.retained_warranty as retained_warranty, f.retained_warranty_date_limit as retained_warranty_date_limit, f.retained_warranty_fk_cond_reglement as retained_warranty_fk_cond_reglement";
  1695. $sql .= ' FROM '.MAIN_DB_PREFIX.'facture as f';
  1696. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid';
  1697. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id';
  1698. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON f.fk_incoterms = i.rowid';
  1699. if ($rowid) {
  1700. $sql .= " WHERE f.rowid=".((int) $rowid);
  1701. } else {
  1702. $sql .= ' WHERE f.entity IN ('.getEntity('invoice').')'; // Don't use entity if you use rowid
  1703. if ($ref) {
  1704. $sql .= " AND f.ref='".$this->db->escape($ref)."'";
  1705. }
  1706. if ($ref_ext) {
  1707. $sql .= " AND f.ref_ext='".$this->db->escape($ref_ext)."'";
  1708. }
  1709. if ($notused) {
  1710. $sql .= " AND f.ref_int='".$this->db->escape($notused)."'"; // deprecated
  1711. }
  1712. }
  1713. dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
  1714. $resql = $this->db->query($sql);
  1715. if ($resql) {
  1716. if ($this->db->num_rows($resql)) {
  1717. $obj = $this->db->fetch_object($resql);
  1718. $this->id = $obj->rowid;
  1719. $this->entity = $obj->entity;
  1720. $this->ref = $obj->ref;
  1721. $this->ref_client = $obj->ref_client;
  1722. $this->ref_ext = $obj->ref_ext;
  1723. $this->type = $obj->type;
  1724. $this->date = $this->db->jdate($obj->df);
  1725. $this->date_pointoftax = $this->db->jdate($obj->date_pointoftax);
  1726. $this->date_creation = $this->db->jdate($obj->datec);
  1727. $this->date_validation = $this->db->jdate($obj->datev);
  1728. $this->date_modification = $this->db->jdate($obj->datem);
  1729. $this->datem = $this->db->jdate($obj->datem);
  1730. $this->remise_percent = $obj->remise_percent;
  1731. $this->remise_absolue = $obj->remise_absolue;
  1732. $this->total_ht = $obj->total_ht;
  1733. $this->total_tva = $obj->total_tva;
  1734. $this->total_localtax1 = $obj->localtax1;
  1735. $this->total_localtax2 = $obj->localtax2;
  1736. $this->total_ttc = $obj->total_ttc;
  1737. $this->revenuestamp = $obj->revenuestamp;
  1738. $this->paye = $obj->paye;
  1739. $this->close_code = $obj->close_code;
  1740. $this->close_note = $obj->close_note;
  1741. $this->socid = $obj->fk_soc;
  1742. $this->thirdparty = null; // Clear if another value was already set by fetch_thirdparty
  1743. $this->fk_project = $obj->fk_project;
  1744. $this->project = null; // Clear if another value was already set by fetch_projet
  1745. $this->statut = $obj->fk_statut;
  1746. $this->status = $obj->fk_statut;
  1747. $this->date_lim_reglement = $this->db->jdate($obj->dlr);
  1748. $this->mode_reglement_id = $obj->fk_mode_reglement;
  1749. $this->mode_reglement_code = $obj->mode_reglement_code;
  1750. $this->mode_reglement = $obj->mode_reglement_libelle;
  1751. $this->cond_reglement_id = $obj->fk_cond_reglement;
  1752. $this->cond_reglement_code = $obj->cond_reglement_code;
  1753. $this->cond_reglement = $obj->cond_reglement_libelle;
  1754. $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
  1755. $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account : null;
  1756. $this->fk_facture_source = $obj->fk_facture_source;
  1757. $this->fk_fac_rec_source = $obj->fk_fac_rec_source;
  1758. $this->note = $obj->note_private; // deprecated
  1759. $this->note_private = $obj->note_private;
  1760. $this->note_public = $obj->note_public;
  1761. $this->user_author = $obj->fk_user_author; // deprecated
  1762. $this->user_valid = $obj->fk_user_valid; // deprecated
  1763. $this->fk_user_author = $obj->fk_user_author;
  1764. $this->fk_user_valid = $obj->fk_user_valid;
  1765. $this->model_pdf = $obj->model_pdf;
  1766. $this->modelpdf = $obj->model_pdf; // deprecated
  1767. $this->last_main_doc = $obj->last_main_doc;
  1768. $this->situation_cycle_ref = $obj->situation_cycle_ref;
  1769. $this->situation_counter = $obj->situation_counter;
  1770. $this->situation_final = $obj->situation_final;
  1771. $this->retained_warranty = $obj->retained_warranty;
  1772. $this->retained_warranty_date_limit = $this->db->jdate($obj->retained_warranty_date_limit);
  1773. $this->retained_warranty_fk_cond_reglement = $obj->retained_warranty_fk_cond_reglement;
  1774. $this->extraparams = (array) json_decode($obj->extraparams, true);
  1775. //Incoterms
  1776. $this->fk_incoterms = $obj->fk_incoterms;
  1777. $this->location_incoterms = $obj->location_incoterms;
  1778. $this->label_incoterms = $obj->label_incoterms;
  1779. $this->module_source = $obj->module_source;
  1780. $this->pos_source = $obj->pos_source;
  1781. // Multicurrency
  1782. $this->fk_multicurrency = $obj->fk_multicurrency;
  1783. $this->multicurrency_code = $obj->multicurrency_code;
  1784. $this->multicurrency_tx = $obj->multicurrency_tx;
  1785. $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
  1786. $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
  1787. $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
  1788. if (($this->type == self::TYPE_SITUATION || ($this->type == self::TYPE_CREDIT_NOTE && $this->situation_cycle_ref > 0)) && $fetch_situation) {
  1789. $this->fetchPreviousNextSituationInvoice();
  1790. }
  1791. if ($this->status == self::STATUS_DRAFT) {
  1792. $this->brouillon = 1;
  1793. }
  1794. // Retrieve all extrafield
  1795. // fetch optionals attributes and labels
  1796. $this->fetch_optionals();
  1797. // Lines
  1798. $this->lines = array();
  1799. $result = $this->fetch_lines();
  1800. if ($result < 0) {
  1801. $this->error = $this->db->error();
  1802. return -3;
  1803. }
  1804. $this->db->free($resql);
  1805. return 1;
  1806. } else {
  1807. $this->error = 'Invoice with id='.$rowid.' or ref='.$ref.' or ref_ext='.$ref_ext.' not found';
  1808. dol_syslog(__METHOD__.$this->error, LOG_WARNING);
  1809. return 0;
  1810. }
  1811. } else {
  1812. $this->error = $this->db->lasterror();
  1813. return -1;
  1814. }
  1815. }
  1816. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1817. /**
  1818. * Load all detailed lines into this->lines
  1819. *
  1820. * @param int $only_product Return only physical products
  1821. * @param int $loadalsotranslation Return translation for products
  1822. *
  1823. * @return int 1 if OK, < 0 if KO
  1824. */
  1825. public function fetch_lines($only_product = 0, $loadalsotranslation = 0)
  1826. {
  1827. // phpcs:enable
  1828. global $langs, $conf;
  1829. $this->lines = array();
  1830. $sql = 'SELECT l.rowid, l.fk_facture, l.fk_product, l.fk_parent_line, l.label as custom_label, l.description, l.product_type, l.price, l.qty, l.vat_src_code, l.tva_tx,';
  1831. $sql .= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise_percent, l.fk_remise_except, l.subprice, l.ref_ext,';
  1832. $sql .= ' l.situation_percent, l.fk_prev_id,';
  1833. $sql .= ' l.rang, l.special_code,';
  1834. $sql .= ' l.date_start as date_start, l.date_end as date_end,';
  1835. $sql .= ' l.info_bits, l.total_ht, l.total_tva, l.total_localtax1, l.total_localtax2, l.total_ttc, l.fk_code_ventilation, l.fk_product_fournisseur_price as fk_fournprice, l.buy_price_ht as pa_ht,';
  1836. $sql .= ' l.fk_unit,';
  1837. $sql .= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
  1838. $sql .= ' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc';
  1839. $sql .= ' FROM '.MAIN_DB_PREFIX.'facturedet as l';
  1840. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid';
  1841. $sql .= ' WHERE l.fk_facture = '.((int) $this->id);
  1842. $sql .= ' ORDER BY l.rang, l.rowid';
  1843. dol_syslog(get_class($this).'::fetch_lines', LOG_DEBUG);
  1844. $result = $this->db->query($sql);
  1845. if ($result) {
  1846. $num = $this->db->num_rows($result);
  1847. $i = 0;
  1848. while ($i < $num) {
  1849. $objp = $this->db->fetch_object($result);
  1850. $line = new FactureLigne($this->db);
  1851. $line->id = $objp->rowid;
  1852. $line->rowid = $objp->rowid; // deprecated
  1853. $line->fk_facture = $objp->fk_facture;
  1854. $line->label = $objp->custom_label; // deprecated
  1855. $line->desc = $objp->description; // Description line
  1856. $line->description = $objp->description; // Description line
  1857. $line->product_type = $objp->product_type; // Type of line
  1858. $line->ref = $objp->product_ref; // Ref product
  1859. $line->product_ref = $objp->product_ref; // Ref product
  1860. $line->libelle = $objp->product_label; // deprecated
  1861. $line->product_label = $objp->product_label; // Label product
  1862. $line->product_desc = $objp->product_desc; // Description product
  1863. $line->fk_product_type = $objp->fk_product_type; // Type of product
  1864. $line->qty = $objp->qty;
  1865. $line->subprice = $objp->subprice;
  1866. $line->ref_ext = $objp->ref_ext; // line external ref
  1867. $line->vat_src_code = $objp->vat_src_code;
  1868. $line->tva_tx = $objp->tva_tx;
  1869. $line->localtax1_tx = $objp->localtax1_tx;
  1870. $line->localtax2_tx = $objp->localtax2_tx;
  1871. $line->localtax1_type = $objp->localtax1_type;
  1872. $line->localtax2_type = $objp->localtax2_type;
  1873. $line->remise_percent = $objp->remise_percent;
  1874. $line->fk_remise_except = $objp->fk_remise_except;
  1875. $line->fk_product = $objp->fk_product;
  1876. $line->date_start = $this->db->jdate($objp->date_start);
  1877. $line->date_end = $this->db->jdate($objp->date_end);
  1878. $line->date_start = $this->db->jdate($objp->date_start);
  1879. $line->date_end = $this->db->jdate($objp->date_end);
  1880. $line->info_bits = $objp->info_bits;
  1881. $line->total_ht = $objp->total_ht;
  1882. $line->total_tva = $objp->total_tva;
  1883. $line->total_localtax1 = $objp->total_localtax1;
  1884. $line->total_localtax2 = $objp->total_localtax2;
  1885. $line->total_ttc = $objp->total_ttc;
  1886. $line->code_ventilation = $objp->fk_code_ventilation;
  1887. $line->fk_fournprice = $objp->fk_fournprice;
  1888. $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
  1889. $line->pa_ht = $marginInfos[0];
  1890. $line->marge_tx = $marginInfos[1];
  1891. $line->marque_tx = $marginInfos[2];
  1892. $line->rang = $objp->rang;
  1893. $line->special_code = $objp->special_code;
  1894. $line->fk_parent_line = $objp->fk_parent_line;
  1895. $line->situation_percent = $objp->situation_percent;
  1896. $line->fk_prev_id = $objp->fk_prev_id;
  1897. $line->fk_unit = $objp->fk_unit;
  1898. // Accountancy
  1899. $line->fk_accounting_account = $objp->fk_code_ventilation;
  1900. // Multicurrency
  1901. $line->fk_multicurrency = $objp->fk_multicurrency;
  1902. $line->multicurrency_code = $objp->multicurrency_code;
  1903. $line->multicurrency_subprice = $objp->multicurrency_subprice;
  1904. $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
  1905. $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
  1906. $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
  1907. $line->fetch_optionals();
  1908. // multilangs
  1909. if (!empty($conf->global->MAIN_MULTILANGS) && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
  1910. $tmpproduct = new Product($this->db);
  1911. $tmpproduct->fetch($objp->fk_product);
  1912. $tmpproduct->getMultiLangs();
  1913. $line->multilangs = $tmpproduct->multilangs;
  1914. }
  1915. $this->lines[$i] = $line;
  1916. $i++;
  1917. }
  1918. $this->db->free($result);
  1919. return 1;
  1920. } else {
  1921. $this->error = $this->db->error();
  1922. return -3;
  1923. }
  1924. }
  1925. /**
  1926. * Fetch previous and next situations invoices.
  1927. * Return all previous and next invoices (both standard and credit notes).
  1928. *
  1929. * @return void
  1930. */
  1931. public function fetchPreviousNextSituationInvoice()
  1932. {
  1933. global $conf;
  1934. $this->tab_previous_situation_invoice = array();
  1935. $this->tab_next_situation_invoice = array();
  1936. $sql = 'SELECT rowid, type, situation_cycle_ref, situation_counter FROM '.MAIN_DB_PREFIX.'facture';
  1937. $sql .= " WHERE rowid <> ".((int) $this->id);
  1938. $sql .= ' AND entity = '.((int) $this->entity);
  1939. $sql .= ' AND situation_cycle_ref = '.(int) $this->situation_cycle_ref;
  1940. $sql .= ' ORDER BY situation_counter ASC';
  1941. dol_syslog(get_class($this).'::fetchPreviousNextSituationInvoice ', LOG_DEBUG);
  1942. $result = $this->db->query($sql);
  1943. if ($result && $this->db->num_rows($result) > 0) {
  1944. while ($objp = $this->db->fetch_object($result)) {
  1945. $invoice = new Facture($this->db);
  1946. if ($invoice->fetch($objp->rowid) > 0) {
  1947. if ($objp->situation_counter < $this->situation_counter
  1948. || ($objp->situation_counter == $this->situation_counter && $objp->rowid < $this->id) // This case appear when there are credit notes
  1949. ) {
  1950. $this->tab_previous_situation_invoice[] = $invoice;
  1951. } else {
  1952. $this->tab_next_situation_invoice[] = $invoice;
  1953. }
  1954. }
  1955. }
  1956. }
  1957. }
  1958. /**
  1959. * Update database
  1960. *
  1961. * @param User $user User that modify
  1962. * @param int $notrigger 0=launch triggers after, 1=disable triggers
  1963. * @return int <0 if KO, >0 if OK
  1964. */
  1965. public function update(User $user, $notrigger = 0)
  1966. {
  1967. global $conf;
  1968. $error = 0;
  1969. // Clean parameters
  1970. if (empty($this->type)) {
  1971. $this->type = self::TYPE_STANDARD;
  1972. }
  1973. if (isset($this->ref)) {
  1974. $this->ref = trim($this->ref);
  1975. }
  1976. if (isset($this->ref_ext)) {
  1977. $this->ref_ext = trim($this->ref_ext);
  1978. }
  1979. if (isset($this->ref_client)) {
  1980. $this->ref_client = trim($this->ref_client);
  1981. }
  1982. if (isset($this->increment)) {
  1983. $this->increment = trim($this->increment);
  1984. }
  1985. if (isset($this->close_code)) {
  1986. $this->close_code = trim($this->close_code);
  1987. }
  1988. if (isset($this->close_note)) {
  1989. $this->close_note = trim($this->close_note);
  1990. }
  1991. if (isset($this->note) || isset($this->note_private)) {
  1992. $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private)); // deprecated
  1993. }
  1994. if (isset($this->note) || isset($this->note_private)) {
  1995. $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note));
  1996. }
  1997. if (isset($this->note_public)) {
  1998. $this->note_public = trim($this->note_public);
  1999. }
  2000. if (isset($this->model_pdf)) {
  2001. $this->model_pdf = trim($this->model_pdf);
  2002. }
  2003. if (isset($this->import_key)) {
  2004. $this->import_key = trim($this->import_key);
  2005. }
  2006. if (isset($this->retained_warranty)) {
  2007. $this->retained_warranty = floatval($this->retained_warranty);
  2008. }
  2009. // Check parameters
  2010. // Put here code to add control on parameters values
  2011. // Update request
  2012. $sql = "UPDATE ".MAIN_DB_PREFIX."facture SET";
  2013. $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
  2014. $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
  2015. $sql .= " type=".(isset($this->type) ? $this->db->escape($this->type) : "null").",";
  2016. $sql .= " ref_client=".(isset($this->ref_client) ? "'".$this->db->escape($this->ref_client)."'" : "null").",";
  2017. $sql .= " increment=".(isset($this->increment) ? "'".$this->db->escape($this->increment)."'" : "null").",";
  2018. $sql .= " fk_soc=".(isset($this->socid) ? $this->db->escape($this->socid) : "null").",";
  2019. $sql .= " datec=".(strval($this->date_creation) != '' ? "'".$this->db->idate($this->date_creation)."'" : 'null').",";
  2020. $sql .= " datef=".(strval($this->date) != '' ? "'".$this->db->idate($this->date)."'" : 'null').",";
  2021. $sql .= " date_pointoftax=".(strval($this->date_pointoftax) != '' ? "'".$this->db->idate($this->date_pointoftax)."'" : 'null').",";
  2022. $sql .= " date_valid=".(strval($this->date_validation) != '' ? "'".$this->db->idate($this->date_validation)."'" : 'null').",";
  2023. $sql .= " paye=".(isset($this->paye) ? $this->db->escape($this->paye) : 0).",";
  2024. $sql .= " remise_percent=".(isset($this->remise_percent) ? $this->db->escape($this->remise_percent) : "null").",";
  2025. $sql .= " remise_absolue=".(isset($this->remise_absolue) ? $this->db->escape($this->remise_absolue) : "null").",";
  2026. $sql .= " close_code=".(isset($this->close_code) ? "'".$this->db->escape($this->close_code)."'" : "null").",";
  2027. $sql .= " close_note=".(isset($this->close_note) ? "'".$this->db->escape($this->close_note)."'" : "null").",";
  2028. $sql .= " total_tva=".(isset($this->total_tva) ? $this->total_tva : "null").",";
  2029. $sql .= " localtax1=".(isset($this->total_localtax1) ? $this->total_localtax1 : "null").",";
  2030. $sql .= " localtax2=".(isset($this->total_localtax2) ? $this->total_localtax2 : "null").",";
  2031. $sql .= " total_ht=".(isset($this->total_ht) ? $this->total_ht : "null").",";
  2032. $sql .= " total_ttc=".(isset($this->total_ttc) ? $this->total_ttc : "null").",";
  2033. $sql .= " revenuestamp=".((isset($this->revenuestamp) && $this->revenuestamp != '') ? $this->db->escape($this->revenuestamp) : "null").",";
  2034. $sql .= " fk_statut=".(isset($this->statut) ? $this->db->escape($this->statut) : "null").",";
  2035. $sql .= " fk_user_author=".(isset($this->user_author) ? $this->db->escape($this->user_author) : "null").",";
  2036. $sql .= " fk_user_valid=".(isset($this->fk_user_valid) ? $this->db->escape($this->fk_user_valid) : "null").",";
  2037. $sql .= " fk_facture_source=".(isset($this->fk_facture_source) ? $this->db->escape($this->fk_facture_source) : "null").",";
  2038. $sql .= " fk_projet=".(isset($this->fk_project) ? $this->db->escape($this->fk_project) : "null").",";
  2039. $sql .= " fk_cond_reglement=".(isset($this->cond_reglement_id) ? $this->db->escape($this->cond_reglement_id) : "null").",";
  2040. $sql .= " fk_mode_reglement=".(isset($this->mode_reglement_id) ? $this->db->escape($this->mode_reglement_id) : "null").",";
  2041. $sql .= " date_lim_reglement=".(strval($this->date_lim_reglement) != '' ? "'".$this->db->idate($this->date_lim_reglement)."'" : 'null').",";
  2042. $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
  2043. $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
  2044. $sql .= " model_pdf=".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").",";
  2045. $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null").",";
  2046. $sql .= " situation_cycle_ref=".(empty($this->situation_cycle_ref) ? "null" : $this->db->escape($this->situation_cycle_ref)).",";
  2047. $sql .= " situation_counter=".(empty($this->situation_counter) ? "null" : $this->db->escape($this->situation_counter)).",";
  2048. $sql .= " situation_final=".(empty($this->situation_final) ? "0" : $this->db->escape($this->situation_final)).",";
  2049. $sql .= " retained_warranty=".(empty($this->retained_warranty) ? "0" : $this->db->escape($this->retained_warranty)).",";
  2050. $sql .= " retained_warranty_date_limit=".(strval($this->retained_warranty_date_limit) != '' ? "'".$this->db->idate($this->retained_warranty_date_limit)."'" : 'null').",";
  2051. $sql .= " retained_warranty_fk_cond_reglement=".(isset($this->retained_warranty_fk_cond_reglement) ?intval($this->retained_warranty_fk_cond_reglement) : "null");
  2052. $sql .= " WHERE rowid=".((int) $this->id);
  2053. $this->db->begin();
  2054. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  2055. $resql = $this->db->query($sql);
  2056. if (!$resql) {
  2057. $error++;
  2058. $this->errors[] = "Error ".$this->db->lasterror();
  2059. }
  2060. if (!$error) {
  2061. $result = $this->insertExtraFields();
  2062. if ($result < 0) {
  2063. $error++;
  2064. }
  2065. }
  2066. if (!$error && !$notrigger) {
  2067. // Call trigger
  2068. $result = $this->call_trigger('BILL_MODIFY', $user);
  2069. if ($result < 0) {
  2070. $error++;
  2071. }
  2072. // End call triggers
  2073. }
  2074. // Commit or rollback
  2075. if ($error) {
  2076. foreach ($this->errors as $errmsg) {
  2077. dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
  2078. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  2079. }
  2080. $this->db->rollback();
  2081. return -1 * $error;
  2082. } else {
  2083. $this->db->commit();
  2084. return 1;
  2085. }
  2086. }
  2087. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2088. /**
  2089. * Add a discount line into an invoice (as an invoice line) using an existing absolute discount (Consume the discount)
  2090. *
  2091. * @param int $idremise Id of absolute discount
  2092. * @return int >0 if OK, <0 if KO
  2093. */
  2094. public function insert_discount($idremise)
  2095. {
  2096. // phpcs:enable
  2097. global $conf, $langs;
  2098. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  2099. include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
  2100. $this->db->begin();
  2101. $remise = new DiscountAbsolute($this->db);
  2102. $result = $remise->fetch($idremise);
  2103. if ($result > 0) {
  2104. if ($remise->fk_facture) { // Protection against multiple submission
  2105. $this->error = $langs->trans("ErrorDiscountAlreadyUsed");
  2106. $this->db->rollback();
  2107. return -5;
  2108. }
  2109. $facligne = new FactureLigne($this->db);
  2110. $facligne->fk_facture = $this->id;
  2111. $facligne->fk_remise_except = $remise->id;
  2112. $facligne->desc = $remise->description; // Description ligne
  2113. $facligne->vat_src_code = $remise->vat_src_code;
  2114. $facligne->tva_tx = $remise->tva_tx;
  2115. $facligne->subprice = -$remise->amount_ht;
  2116. $facligne->fk_product = 0; // Id produit predefini
  2117. $facligne->qty = 1;
  2118. $facligne->remise_percent = 0;
  2119. $facligne->rang = -1;
  2120. $facligne->info_bits = 2;
  2121. if (!empty($conf->global->MAIN_ADD_LINE_AT_POSITION)) {
  2122. $facligne->rang = 1;
  2123. $linecount = count($this->lines);
  2124. for ($ii = 1; $ii <= $linecount; $ii++) {
  2125. $this->updateRangOfLine($this->lines[$ii - 1]->id, $ii+1);
  2126. }
  2127. }
  2128. // Get buy/cost price of invoice that is source of discount
  2129. if ($remise->fk_facture_source > 0) {
  2130. $srcinvoice = new Facture($this->db);
  2131. $srcinvoice->fetch($remise->fk_facture_source);
  2132. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php'; // TODO Move this into commonobject
  2133. $formmargin = new FormMargin($this->db);
  2134. $arraytmp = $formmargin->getMarginInfosArray($srcinvoice, false);
  2135. $facligne->pa_ht = $arraytmp['pa_total'];
  2136. }
  2137. $facligne->total_ht = -$remise->amount_ht;
  2138. $facligne->total_tva = -$remise->amount_tva;
  2139. $facligne->total_ttc = -$remise->amount_ttc;
  2140. $facligne->multicurrency_subprice = -$remise->multicurrency_subprice;
  2141. $facligne->multicurrency_total_ht = -$remise->multicurrency_amount_ht;
  2142. $facligne->multicurrency_total_tva = -$remise->multicurrency_amount_tva;
  2143. $facligne->multicurrency_total_ttc = -$remise->multicurrency_amount_ttc;
  2144. $lineid = $facligne->insert();
  2145. if ($lineid > 0) {
  2146. $result = $this->update_price(1);
  2147. if ($result > 0) {
  2148. // Create link between discount and invoice line
  2149. $result = $remise->link_to_invoice($lineid, 0);
  2150. if ($result < 0) {
  2151. $this->error = $remise->error;
  2152. $this->db->rollback();
  2153. return -4;
  2154. }
  2155. $this->db->commit();
  2156. return 1;
  2157. } else {
  2158. $this->error = $facligne->error;
  2159. $this->db->rollback();
  2160. return -1;
  2161. }
  2162. } else {
  2163. $this->error = $facligne->error;
  2164. $this->db->rollback();
  2165. return -2;
  2166. }
  2167. } else {
  2168. $this->db->rollback();
  2169. return -3;
  2170. }
  2171. }
  2172. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2173. /**
  2174. * Set customer ref
  2175. *
  2176. * @param string $ref_client Customer ref
  2177. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  2178. * @return int <0 if KO, >0 if OK
  2179. */
  2180. public function set_ref_client($ref_client, $notrigger = 0)
  2181. {
  2182. // phpcs:enable
  2183. global $user;
  2184. $error = 0;
  2185. $this->db->begin();
  2186. $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
  2187. if (empty($ref_client)) {
  2188. $sql .= ' SET ref_client = NULL';
  2189. } else {
  2190. $sql .= ' SET ref_client = \''.$this->db->escape($ref_client).'\'';
  2191. }
  2192. $sql .= " WHERE rowid = ".((int) $this->id);
  2193. dol_syslog(__METHOD__.' this->id='.$this->id.', ref_client='.$ref_client, LOG_DEBUG);
  2194. $resql = $this->db->query($sql);
  2195. if (!$resql) {
  2196. $this->errors[] = $this->db->error();
  2197. $error++;
  2198. }
  2199. if (!$error) {
  2200. $this->ref_client = $ref_client;
  2201. }
  2202. if (!$notrigger && empty($error)) {
  2203. // Call trigger
  2204. $result = $this->call_trigger('BILL_MODIFY', $user);
  2205. if ($result < 0) {
  2206. $error++;
  2207. }
  2208. // End call triggers
  2209. }
  2210. if (!$error) {
  2211. $this->ref_client = $ref_client;
  2212. $this->db->commit();
  2213. return 1;
  2214. } else {
  2215. foreach ($this->errors as $errmsg) {
  2216. dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
  2217. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  2218. }
  2219. $this->db->rollback();
  2220. return -1 * $error;
  2221. }
  2222. }
  2223. /**
  2224. * Delete invoice
  2225. *
  2226. * @param User $user User making the deletion.
  2227. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  2228. * @param int $idwarehouse Id warehouse to use for stock change.
  2229. * @return int <0 if KO, 0=Refused, >0 if OK
  2230. */
  2231. public function delete($user, $notrigger = 0, $idwarehouse = -1)
  2232. {
  2233. global $langs, $conf;
  2234. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  2235. $rowid = $this->id;
  2236. dol_syslog(get_class($this)."::delete rowid=".$rowid.", ref=".$this->ref.", thirdparty=".(empty($this->thirdparty) ? '' : $this->thirdparty->name), LOG_DEBUG);
  2237. // Test to avoid invoice deletion (allowed if draft)
  2238. $result = $this->is_erasable();
  2239. if ($result <= 0) {
  2240. return 0;
  2241. }
  2242. $error = 0;
  2243. $this->db->begin();
  2244. if (!$error && !$notrigger) {
  2245. // Call trigger
  2246. $result = $this->call_trigger('BILL_DELETE', $user);
  2247. if ($result < 0) {
  2248. $error++;
  2249. }
  2250. // End call triggers
  2251. }
  2252. // Removed extrafields
  2253. if (!$error) {
  2254. $result = $this->deleteExtraFields();
  2255. if ($result < 0) {
  2256. $error++;
  2257. dol_syslog(get_class($this)."::delete error deleteExtraFields ".$this->error, LOG_ERR);
  2258. }
  2259. }
  2260. if (!$error) {
  2261. // Delete linked object
  2262. $res = $this->deleteObjectLinked();
  2263. if ($res < 0) {
  2264. $error++;
  2265. }
  2266. }
  2267. if (!$error) {
  2268. // If invoice was converted into a discount not yet consumed, we remove discount
  2269. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'societe_remise_except';
  2270. $sql .= ' WHERE fk_facture_source = '.((int) $rowid);
  2271. $sql .= ' AND fk_facture_line IS NULL';
  2272. $resql = $this->db->query($sql);
  2273. // If invoice has consumed discounts
  2274. $this->fetch_lines();
  2275. $list_rowid_det = array();
  2276. foreach ($this->lines as $key => $invoiceline) {
  2277. $list_rowid_det[] = $invoiceline->id;
  2278. }
  2279. // Consumed discounts are freed
  2280. if (count($list_rowid_det)) {
  2281. $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
  2282. $sql .= ' SET fk_facture = NULL, fk_facture_line = NULL';
  2283. $sql .= ' WHERE fk_facture_line IN ('.$this->db->sanitize(join(',', $list_rowid_det)).')';
  2284. if (!$this->db->query($sql)) {
  2285. $this->error = $this->db->error()." sql=".$sql;
  2286. $this->errors[] = $this->error;
  2287. $this->db->rollback();
  2288. return -5;
  2289. }
  2290. }
  2291. // Remove other links to the deleted invoice
  2292. $sql = 'UPDATE '.MAIN_DB_PREFIX.'eventorganization_conferenceorboothattendee';
  2293. $sql .= ' SET fk_invoice = NULL';
  2294. $sql .= ' WHERE fk_invoice = '.((int) $rowid);
  2295. if (!$this->db->query($sql)) {
  2296. $this->error = $this->db->error()." sql=".$sql;
  2297. $this->errors[] = $this->error;
  2298. $this->db->rollback();
  2299. return -5;
  2300. }
  2301. $sql = 'UPDATE '.MAIN_DB_PREFIX.'projet_task_time';
  2302. $sql .= ' SET invoice_id = NULL, invoice_line_id = NULL';
  2303. $sql .= ' WHERE invoice_id = '.((int) $rowid);
  2304. if (!$this->db->query($sql)) {
  2305. $this->error = $this->db->error()." sql=".$sql;
  2306. $this->errors[] = $this->error;
  2307. $this->db->rollback();
  2308. return -5;
  2309. }
  2310. // If we decrease stock on invoice validation, we increase back if a warehouse id was provided
  2311. if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL) && $idwarehouse != -1) {
  2312. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  2313. $langs->load("agenda");
  2314. $num = count($this->lines);
  2315. for ($i = 0; $i < $num; $i++) {
  2316. if ($this->lines[$i]->fk_product > 0) {
  2317. $mouvP = new MouvementStock($this->db);
  2318. $mouvP->origin = &$this;
  2319. $mouvP->setOrigin($this->element, $this->id);
  2320. // We decrease stock for product
  2321. if ($this->type == self::TYPE_CREDIT_NOTE) {
  2322. $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceDeleteDolibarr", $this->ref));
  2323. } else {
  2324. $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("InvoiceDeleteDolibarr", $this->ref)); // we use 0 for price, to not change the weighted average value
  2325. }
  2326. }
  2327. }
  2328. }
  2329. // Invoice line extrafileds
  2330. $main = MAIN_DB_PREFIX.'facturedet';
  2331. $ef = $main."_extrafields";
  2332. $sqlef = "DELETE FROM ".$ef." WHERE fk_object IN (SELECT rowid FROM ".$main." WHERE fk_facture = ".((int) $rowid).")";
  2333. // Delete invoice line
  2334. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facturedet WHERE fk_facture = '.((int) $rowid);
  2335. if ($this->db->query($sqlef) && $this->db->query($sql) && $this->delete_linked_contact()) {
  2336. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture WHERE rowid = '.((int) $rowid);
  2337. $resql = $this->db->query($sql);
  2338. if ($resql) {
  2339. // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive
  2340. $this->deleteEcmFiles();
  2341. // On efface le repertoire de pdf provisoire
  2342. $ref = dol_sanitizeFileName($this->ref);
  2343. if ($conf->facture->dir_output && !empty($this->ref)) {
  2344. $dir = $conf->facture->dir_output."/".$ref;
  2345. $file = $conf->facture->dir_output."/".$ref."/".$ref.".pdf";
  2346. if (file_exists($file)) { // We must delete all files before deleting directory
  2347. $ret = dol_delete_preview($this);
  2348. if (!dol_delete_file($file, 0, 0, 0, $this)) { // For triggers
  2349. $langs->load("errors");
  2350. $this->error = $langs->trans("ErrorFailToDeleteFile", $file);
  2351. $this->errors[] = $this->error;
  2352. $this->db->rollback();
  2353. return 0;
  2354. }
  2355. }
  2356. if (file_exists($dir)) {
  2357. if (!dol_delete_dir_recursive($dir)) { // For remove dir and meta
  2358. $langs->load("errors");
  2359. $this->error = $langs->trans("ErrorFailToDeleteDir", $dir);
  2360. $this->errors[] = $this->error;
  2361. $this->db->rollback();
  2362. return 0;
  2363. }
  2364. }
  2365. }
  2366. $this->db->commit();
  2367. return 1;
  2368. } else {
  2369. $this->error = $this->db->lasterror()." sql=".$sql;
  2370. $this->errors[] = $this->error;
  2371. $this->db->rollback();
  2372. return -6;
  2373. }
  2374. } else {
  2375. $this->error = $this->db->lasterror()." sql=".$sql;
  2376. $this->errors[] = $this->error;
  2377. $this->db->rollback();
  2378. return -4;
  2379. }
  2380. } else {
  2381. $this->db->rollback();
  2382. return -2;
  2383. }
  2384. }
  2385. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2386. /**
  2387. * Tag the invoice as paid completely (if close_code is filled) => this->fk_statut=2, this->paye=1
  2388. * or partialy (if close_code filled) + appel trigger BILL_PAYED => this->fk_statut=2, this->paye stay 0
  2389. *
  2390. * @deprecated
  2391. * @see setPaid()
  2392. * @param User $user Object user that modify
  2393. * @param string $close_code Code renseigne si on classe a payee completement alors que paiement incomplet (cas escompte par exemple)
  2394. * @param string $close_note Commentaire renseigne si on classe a payee alors que paiement incomplet (cas escompte par exemple)
  2395. * @return int <0 if KO, >0 if OK
  2396. */
  2397. public function set_paid($user, $close_code = '', $close_note = '')
  2398. {
  2399. // phpcs:enable
  2400. dol_syslog(get_class($this)."::set_paid is deprecated, use setPaid instead", LOG_NOTICE);
  2401. return $this->setPaid($user, $close_code, $close_note);
  2402. }
  2403. /**
  2404. * Tag the invoice as paid completely (if close_code is filled) => this->fk_statut=2, this->paye=1
  2405. * or partially (if close_code filled) + appel trigger BILL_PAYED => this->fk_statut=2, this->paye stay 0
  2406. *
  2407. * @param User $user Object user that modify
  2408. * @param string $close_code Code renseigne si on classe a payee completement alors que paiement incomplet (cas escompte par exemple)
  2409. * @param string $close_note Commentaire renseigne si on classe a payee alors que paiement incomplet (cas escompte par exemple)
  2410. * @return int <0 if KO, >0 if OK
  2411. */
  2412. public function setPaid($user, $close_code = '', $close_note = '')
  2413. {
  2414. $error = 0;
  2415. if ($this->paye != 1) {
  2416. $this->db->begin();
  2417. $now = dol_now();
  2418. dol_syslog(get_class($this)."::setPaid rowid=".((int) $this->id), LOG_DEBUG);
  2419. $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET';
  2420. $sql .= ' fk_statut='.self::STATUS_CLOSED;
  2421. if (!$close_code) {
  2422. $sql .= ', paye=1';
  2423. }
  2424. if ($close_code) {
  2425. $sql .= ", close_code='".$this->db->escape($close_code)."'";
  2426. }
  2427. if ($close_note) {
  2428. $sql .= ", close_note='".$this->db->escape($close_note)."'";
  2429. }
  2430. $sql .= ', fk_user_closing = '.((int) $user->id);
  2431. $sql .= ", date_closing = '".$this->db->idate($now)."'";
  2432. $sql .= " WHERE rowid = ".((int) $this->id);
  2433. $resql = $this->db->query($sql);
  2434. if ($resql) {
  2435. // Call trigger
  2436. $result = $this->call_trigger('BILL_PAYED', $user);
  2437. if ($result < 0) {
  2438. $error++;
  2439. }
  2440. // End call triggers
  2441. } else {
  2442. $error++;
  2443. $this->error = $this->db->lasterror();
  2444. }
  2445. if (!$error) {
  2446. $this->db->commit();
  2447. return 1;
  2448. } else {
  2449. $this->db->rollback();
  2450. return -1;
  2451. }
  2452. } else {
  2453. return 0;
  2454. }
  2455. }
  2456. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2457. /**
  2458. * Tag la facture comme non payee completement + appel trigger BILL_UNPAYED
  2459. * Fonction utilisee quand un paiement prelevement est refuse,
  2460. * ou quand une facture annulee et reouverte.
  2461. *
  2462. * @deprecated
  2463. * @see setUnpaid()
  2464. * @param User $user Object user that change status
  2465. * @return int <0 if KO, >0 if OK
  2466. */
  2467. public function set_unpaid($user)
  2468. {
  2469. // phpcs:enable
  2470. dol_syslog(get_class($this)."::set_unpaid is deprecated, use setUnpaid instead", LOG_NOTICE);
  2471. return $this->setUnpaid($user);
  2472. }
  2473. /**
  2474. * Tag la facture comme non payee completement + appel trigger BILL_UNPAYED
  2475. * Fonction utilisee quand un paiement prelevement est refuse,
  2476. * ou quand une facture annulee et reouverte.
  2477. *
  2478. * @param User $user Object user that change status
  2479. * @return int <0 if KO, >0 if OK
  2480. */
  2481. public function setUnpaid($user)
  2482. {
  2483. $error = 0;
  2484. $this->db->begin();
  2485. $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
  2486. $sql .= ' SET paye=0, fk_statut='.self::STATUS_VALIDATED.', close_code=null, close_note=null,';
  2487. $sql .= ' date_closing=null,';
  2488. $sql .= ' fk_user_closing=null';
  2489. $sql .= " WHERE rowid = ".((int) $this->id);
  2490. dol_syslog(get_class($this)."::setUnpaid", LOG_DEBUG);
  2491. $resql = $this->db->query($sql);
  2492. if ($resql) {
  2493. // Call trigger
  2494. $result = $this->call_trigger('BILL_UNPAYED', $user);
  2495. if ($result < 0) {
  2496. $error++;
  2497. }
  2498. // End call triggers
  2499. } else {
  2500. $error++;
  2501. $this->error = $this->db->error();
  2502. dol_print_error($this->db);
  2503. }
  2504. if (!$error) {
  2505. $this->db->commit();
  2506. return 1;
  2507. } else {
  2508. $this->db->rollback();
  2509. return -1;
  2510. }
  2511. }
  2512. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2513. /**
  2514. * Tag invoice as canceled, with no payment on it (example for replacement invoice or payment never received) + call trigger BILL_CANCEL
  2515. * Warning, if option to decrease stock on invoice was set, this function does not change stock (it might be a cancel because
  2516. * of no payment even if merchandises were sent).
  2517. *
  2518. * @deprecated
  2519. * @see setCanceled()
  2520. * @param User $user Object user making change
  2521. * @param string $close_code Code of closing invoice (CLOSECODE_REPLACED, CLOSECODE_...)
  2522. * @param string $close_note Comment
  2523. * @return int <0 if KO, >0 if OK
  2524. */
  2525. public function set_canceled($user, $close_code = '', $close_note = '')
  2526. {
  2527. // phpcs:enable
  2528. dol_syslog(get_class($this)."::set_canceled is deprecated, use setCanceled instead", LOG_NOTICE);
  2529. return $this->setCanceled($user, $close_code, $close_note);
  2530. }
  2531. /**
  2532. * Tag invoice as canceled, with no payment on it (example for replacement invoice or payment never received) + call trigger BILL_CANCEL
  2533. * Warning, if option to decrease stock on invoice was set, this function does not change stock (it might be a cancel because
  2534. * of no payment even if merchandises were sent).
  2535. *
  2536. * @param User $user Object user making change
  2537. * @param string $close_code Code of closing invoice (CLOSECODE_REPLACED, CLOSECODE_...)
  2538. * @param string $close_note Comment
  2539. * @return int <0 if KO, >0 if OK
  2540. */
  2541. public function setCanceled($user, $close_code = '', $close_note = '')
  2542. {
  2543. dol_syslog(get_class($this)."::setCanceled rowid=".((int) $this->id), LOG_DEBUG);
  2544. $this->db->begin();
  2545. $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET';
  2546. $sql .= ' fk_statut='.self::STATUS_ABANDONED;
  2547. if ($close_code) {
  2548. $sql .= ", close_code='".$this->db->escape($close_code)."'";
  2549. }
  2550. if ($close_note) {
  2551. $sql .= ", close_note='".$this->db->escape($close_note)."'";
  2552. }
  2553. $sql .= " WHERE rowid = ".((int) $this->id);
  2554. $resql = $this->db->query($sql);
  2555. if ($resql) {
  2556. // Bound discounts are deducted from the invoice
  2557. // as they have not been used since the invoice is abandoned.
  2558. $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
  2559. $sql .= ' SET fk_facture = NULL';
  2560. $sql .= ' WHERE fk_facture = '.((int) $this->id);
  2561. $resql = $this->db->query($sql);
  2562. if ($resql) {
  2563. // Call trigger
  2564. $result = $this->call_trigger('BILL_CANCEL', $user);
  2565. if ($result < 0) {
  2566. $this->db->rollback();
  2567. return -1;
  2568. }
  2569. // End call triggers
  2570. $this->db->commit();
  2571. return 1;
  2572. } else {
  2573. $this->error = $this->db->error()." sql=".$sql;
  2574. $this->db->rollback();
  2575. return -1;
  2576. }
  2577. } else {
  2578. $this->error = $this->db->error()." sql=".$sql;
  2579. $this->db->rollback();
  2580. return -2;
  2581. }
  2582. }
  2583. /**
  2584. * Tag invoice as validated + call trigger BILL_VALIDATE
  2585. * Object must have lines loaded with fetch_lines
  2586. *
  2587. * @param User $user Object user that validate
  2588. * @param string $force_number Reference to force on invoice
  2589. * @param int $idwarehouse Id of warehouse to use for stock decrease if option to decreasenon stock is on (0=no decrease)
  2590. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  2591. * @param int $batch_rule 0=do not decrement batch, else batch rule to use, 1=take in batches ordered by sellby and eatby dates
  2592. * @return int <0 if KO, 0=Nothing done because invoice is not a draft, >0 if OK
  2593. */
  2594. public function validate($user, $force_number = '', $idwarehouse = 0, $notrigger = 0, $batch_rule = 0)
  2595. {
  2596. global $conf, $langs, $mysoc;
  2597. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  2598. $productStatic = null;
  2599. $warehouseStatic = null;
  2600. if ($batch_rule > 0) {
  2601. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2602. require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php';
  2603. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
  2604. $productStatic = new Product($this->db);
  2605. $warehouseStatic = new Entrepot($this->db);
  2606. $productbatch = new ProductBatch($this->db);
  2607. }
  2608. $now = dol_now();
  2609. $error = 0;
  2610. dol_syslog(get_class($this).'::validate user='.$user->id.', force_number='.$force_number.', idwarehouse='.$idwarehouse);
  2611. // Force to have object complete for checks
  2612. $this->fetch_thirdparty();
  2613. $this->fetch_lines();
  2614. // Check parameters
  2615. if ($this->statut != self::STATUS_DRAFT) {
  2616. dol_syslog(get_class($this)."::validate status is not draft. operation canceled.", LOG_WARNING);
  2617. return 0;
  2618. }
  2619. if (count($this->lines) <= 0) {
  2620. $langs->load("errors");
  2621. $this->error = $langs->trans("ErrorObjectMustHaveLinesToBeValidated", $this->ref);
  2622. return -1;
  2623. }
  2624. if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->creer))
  2625. || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->invoice_advance->validate))) {
  2626. $this->error = 'Permission denied';
  2627. dol_syslog(get_class($this)."::validate ".$this->error.' MAIN_USE_ADVANCED_PERMS='.$conf->global->MAIN_USE_ADVANCED_PERMS, LOG_ERR);
  2628. return -1;
  2629. }
  2630. if (!empty($conf->global-> INVOICE_CHECK_POSTERIOR_DATE)) {
  2631. $last_of_type = $this->willBeLastOfSameType(true);
  2632. if (!$last_of_type[0]) {
  2633. $this->error = $langs->transnoentities("ErrorInvoiceIsNotLastOfSameType", $this->ref, dol_print_date($this->date, 'day'), dol_print_date($last_of_type[1], 'day'));
  2634. return -1;
  2635. }
  2636. }
  2637. // Check for mandatory fields in thirdparty (defined into setup)
  2638. if (!empty($this->thirdparty) && is_object($this->thirdparty)) {
  2639. $array_to_check = array('IDPROF1', 'IDPROF2', 'IDPROF3', 'IDPROF4', 'IDPROF5', 'IDPROF6', 'EMAIL', 'ACCOUNTANCY_CODE_CUSTOMER');
  2640. foreach ($array_to_check as $key) {
  2641. $keymin = strtolower($key);
  2642. if (!property_exists($this->thirdparty, $keymin)) {
  2643. continue;
  2644. }
  2645. $vallabel = $this->thirdparty->$keymin;
  2646. $i = (int) preg_replace('/[^0-9]/', '', $key);
  2647. if ($i > 0) {
  2648. if ($this->thirdparty->isACompany()) {
  2649. // Check for mandatory prof id (but only if country is other than ours)
  2650. if ($mysoc->country_id > 0 && $this->thirdparty->country_id == $mysoc->country_id) {
  2651. $idprof_mandatory = 'SOCIETE_'.$key.'_INVOICE_MANDATORY';
  2652. if (!$vallabel && !empty($conf->global->$idprof_mandatory)) {
  2653. $langs->load("errors");
  2654. $this->error = $langs->trans('ErrorProdIdIsMandatory', $langs->transcountry('ProfId'.$i, $this->thirdparty->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").') ['.$langs->trans('Company').' : '.$this->thirdparty->name.']';
  2655. dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
  2656. return -1;
  2657. }
  2658. }
  2659. }
  2660. } else {
  2661. if ($key == 'EMAIL') {
  2662. // Check for mandatory
  2663. if (!empty($conf->global->SOCIETE_EMAIL_INVOICE_MANDATORY) && !isValidEMail($this->thirdparty->email)) {
  2664. $langs->load("errors");
  2665. $this->error = $langs->trans("ErrorBadEMail", $this->thirdparty->email).' ('.$langs->trans("ForbiddenBySetupRules").') ['.$langs->trans('Company').' : '.$this->thirdparty->name.']';
  2666. dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
  2667. return -1;
  2668. }
  2669. }
  2670. if ($key == 'ACCOUNTANCY_CODE_CUSTOMER') {
  2671. // Check for mandatory
  2672. if (!empty($conf->global->SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_INVOICE_MANDATORY) && empty($this->thirdparty->code_compta)) {
  2673. $langs->load("errors");
  2674. $this->error = $langs->trans("ErrorAccountancyCodeCustomerIsMandatory", $this->thirdparty->name).' ('.$langs->trans("ForbiddenBySetupRules").')';
  2675. dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
  2676. return -1;
  2677. }
  2678. }
  2679. }
  2680. }
  2681. }
  2682. // Check for mandatory fields in $this
  2683. $array_to_check = array('REF_CLIENT'=>'RefCustomer');
  2684. foreach ($array_to_check as $key => $val) {
  2685. $keymin = strtolower($key);
  2686. $vallabel = $this->$keymin;
  2687. // Check for mandatory
  2688. $keymandatory = 'INVOICE_'.$key.'_MANDATORY_FOR_VALIDATION';
  2689. if (!$vallabel && !empty($conf->global->$keymandatory)) {
  2690. $langs->load("errors");
  2691. $error++;
  2692. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv($val)), null, 'errors');
  2693. }
  2694. }
  2695. $this->db->begin();
  2696. // Check parameters
  2697. if ($this->type == self::TYPE_REPLACEMENT) { // if this is a replacement invoice
  2698. // Check that source invoice is known
  2699. if ($this->fk_facture_source <= 0) {
  2700. $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("InvoiceReplacement"));
  2701. $this->db->rollback();
  2702. return -10;
  2703. }
  2704. // Load source invoice that has been replaced
  2705. $facreplaced = new Facture($this->db);
  2706. $result = $facreplaced->fetch($this->fk_facture_source);
  2707. if ($result <= 0) {
  2708. $this->error = $langs->trans("ErrorBadInvoice");
  2709. $this->db->rollback();
  2710. return -11;
  2711. }
  2712. // Check that source invoice not already replaced by another one.
  2713. $idreplacement = $facreplaced->getIdReplacingInvoice('validated');
  2714. if ($idreplacement && $idreplacement != $this->id) {
  2715. $facreplacement = new Facture($this->db);
  2716. $facreplacement->fetch($idreplacement);
  2717. $this->error = $langs->trans("ErrorInvoiceAlreadyReplaced", $facreplaced->ref, $facreplacement->ref);
  2718. $this->db->rollback();
  2719. return -12;
  2720. }
  2721. $result = $facreplaced->setCanceled($user, self::CLOSECODE_REPLACED, '');
  2722. if ($result < 0) {
  2723. $this->error = $facreplaced->error;
  2724. $this->db->rollback();
  2725. return -13;
  2726. }
  2727. }
  2728. // Define new ref
  2729. if ($force_number) {
  2730. $num = $force_number;
  2731. } elseif (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
  2732. if (!empty($conf->global->FAC_FORCE_DATE_VALIDATION)) { // If option enabled, we force invoice date
  2733. $this->date = dol_now();
  2734. $this->date_lim_reglement = $this->calculate_date_lim_reglement();
  2735. }
  2736. $num = $this->getNextNumRef($this->thirdparty);
  2737. } else {
  2738. $num = $this->ref;
  2739. }
  2740. $this->newref = dol_sanitizeFileName($num);
  2741. if ($num) {
  2742. $this->update_price(1);
  2743. // Validate
  2744. $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
  2745. $sql .= " SET ref='".$num."', fk_statut = ".self::STATUS_VALIDATED.", fk_user_valid = ".($user->id > 0 ? $user->id : "null").", date_valid = '".$this->db->idate($now)."'";
  2746. if (!empty($conf->global->FAC_FORCE_DATE_VALIDATION)) { // If option enabled, we force invoice date
  2747. $sql .= ", datef='".$this->db->idate($this->date)."'";
  2748. $sql .= ", date_lim_reglement='".$this->db->idate($this->date_lim_reglement)."'";
  2749. }
  2750. $sql .= " WHERE rowid = ".((int) $this->id);
  2751. dol_syslog(get_class($this)."::validate", LOG_DEBUG);
  2752. $resql = $this->db->query($sql);
  2753. if (!$resql) {
  2754. dol_print_error($this->db);
  2755. $error++;
  2756. }
  2757. // We check if the invoice was provisional
  2758. if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref))) {
  2759. // La verif qu'une remise n'est pas utilisee 2 fois est faite au moment de l'insertion de ligne
  2760. }
  2761. if (!$error) {
  2762. // Define third party as a customer
  2763. $result = $this->thirdparty->set_as_client();
  2764. // If active we decrement the main product and its components at invoice validation
  2765. if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL) && $idwarehouse > 0) {
  2766. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  2767. $langs->load("agenda");
  2768. // Loop on each line
  2769. $cpt = count($this->lines);
  2770. for ($i = 0; $i < $cpt; $i++) {
  2771. if ($this->lines[$i]->fk_product > 0) {
  2772. $mouvP = new MouvementStock($this->db);
  2773. $mouvP->origin = &$this;
  2774. $mouvP->setOrigin($this->element, $this->id);
  2775. // We decrease stock for product
  2776. if ($this->type == self::TYPE_CREDIT_NOTE) {
  2777. $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("InvoiceValidatedInDolibarr", $num));
  2778. if ($result < 0) {
  2779. $error++;
  2780. $this->error = $mouvP->error;
  2781. }
  2782. } else {
  2783. $is_batch_line = false;
  2784. if ($batch_rule > 0) {
  2785. $productStatic->fetch($this->lines[$i]->fk_product);
  2786. if ($productStatic->hasbatch()) {
  2787. $is_batch_line = true;
  2788. $product_qty_remain = $this->lines[$i]->qty;
  2789. $sortfield = null;
  2790. $sortorder = null;
  2791. // find all batch order by sellby (DLC) and eatby dates (DLUO) first
  2792. if ($batch_rule == Productbatch::BATCH_RULE_SELLBY_EATBY_DATES_FIRST) {
  2793. $sortfield = 'pl.sellby,pl.eatby,pb.qty,pl.rowid';
  2794. $sortorder = 'ASC,ASC,ASC,ASC';
  2795. }
  2796. $resBatchList = $productbatch->findAllForProduct($productStatic->id, $idwarehouse, (!empty($conf->global->STOCK_ALLOW_NEGATIVE_TRANSFER) ? null : 0), $sortfield, $sortorder);
  2797. if (!is_array($resBatchList)) {
  2798. $error++;
  2799. $this->error = $this->db->lasterror();
  2800. }
  2801. if (!$error) {
  2802. $batchList = $resBatchList;
  2803. if (empty($batchList)) {
  2804. $error++;
  2805. $langs->load('errors');
  2806. $warehouseStatic->fetch($idwarehouse);
  2807. $this->error = $langs->trans('ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
  2808. dol_syslog(__METHOD__.' Error: '.$langs->transnoentitiesnoconv('ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
  2809. }
  2810. foreach ($batchList as $batch) {
  2811. if ($batch->qty <= 0) {
  2812. continue; // try to decrement only batches have positive quantity first
  2813. }
  2814. // enough quantity in this batch
  2815. if ($batch->qty >= $product_qty_remain) {
  2816. $product_batch_qty = $product_qty_remain;
  2817. } else {
  2818. // not enough (take all in batch)
  2819. $product_batch_qty = $batch->qty;
  2820. }
  2821. $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_batch_qty, $this->lines[$i]->subprice, $langs->trans('InvoiceValidatedInDolibarr', $num), '', '', '', $batch->batch);
  2822. if ($result < 0) {
  2823. $error++;
  2824. $this->error = $mouvP->error;
  2825. break;
  2826. }
  2827. $product_qty_remain -= $product_batch_qty;
  2828. // all product quantity was decremented
  2829. if ($product_qty_remain <= 0) {
  2830. break;
  2831. }
  2832. }
  2833. if (!$error && $product_qty_remain > 0) {
  2834. if ($conf->global->STOCK_ALLOW_NEGATIVE_TRANSFER) {
  2835. // take in the first batch
  2836. $batch = $batchList[0];
  2837. $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_qty_remain, $this->lines[$i]->subprice, $langs->trans('InvoiceValidatedInDolibarr', $num), '', '', '', $batch->batch);
  2838. if ($result < 0) {
  2839. $error++;
  2840. $this->error = $mouvP->error;
  2841. }
  2842. } else {
  2843. $error++;
  2844. $langs->load('errors');
  2845. $warehouseStatic->fetch($idwarehouse);
  2846. $this->error = $langs->trans('ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
  2847. dol_syslog(__METHOD__.' Error: '.$langs->transnoentitiesnoconv('ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
  2848. }
  2849. }
  2850. }
  2851. }
  2852. }
  2853. if (!$is_batch_line) {
  2854. $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarr", $num));
  2855. if ($result < 0) {
  2856. $error++;
  2857. $this->error = $mouvP->error;
  2858. }
  2859. }
  2860. }
  2861. }
  2862. }
  2863. }
  2864. }
  2865. // Trigger calls
  2866. if (!$error && !$notrigger) {
  2867. // Call trigger
  2868. $result = $this->call_trigger('BILL_VALIDATE', $user);
  2869. if ($result < 0) {
  2870. $error++;
  2871. }
  2872. // End call triggers
  2873. }
  2874. if (!$error) {
  2875. $this->oldref = $this->ref;
  2876. // Rename directory if dir was a temporary ref
  2877. if (preg_match('/^[\(]?PROV/i', $this->ref)) {
  2878. // Now we rename also files into index
  2879. $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'facture/".$this->db->escape($this->newref)."'";
  2880. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'facture/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
  2881. $resql = $this->db->query($sql);
  2882. if (!$resql) {
  2883. $error++;
  2884. $this->error = $this->db->lasterror();
  2885. }
  2886. // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
  2887. $oldref = dol_sanitizeFileName($this->ref);
  2888. $newref = dol_sanitizeFileName($num);
  2889. $dirsource = $conf->facture->dir_output.'/'.$oldref;
  2890. $dirdest = $conf->facture->dir_output.'/'.$newref;
  2891. if (!$error && file_exists($dirsource)) {
  2892. dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest);
  2893. if (@rename($dirsource, $dirdest)) {
  2894. dol_syslog("Rename ok");
  2895. // Rename docs starting with $oldref with $newref
  2896. $listoffiles = dol_dir_list($conf->facture->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
  2897. foreach ($listoffiles as $fileentry) {
  2898. $dirsource = $fileentry['name'];
  2899. $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
  2900. $dirsource = $fileentry['path'].'/'.$dirsource;
  2901. $dirdest = $fileentry['path'].'/'.$dirdest;
  2902. @rename($dirsource, $dirdest);
  2903. }
  2904. }
  2905. }
  2906. }
  2907. }
  2908. if (!$error && !$this->is_last_in_cycle()) {
  2909. if (!$this->updatePriceNextInvoice($langs)) {
  2910. $error++;
  2911. }
  2912. }
  2913. // Set new ref and define current status
  2914. if (!$error) {
  2915. $this->ref = $num;
  2916. $this->ref = $num;
  2917. $this->statut = self::STATUS_VALIDATED;
  2918. $this->status = self::STATUS_VALIDATED;
  2919. $this->brouillon = 0;
  2920. $this->date_validation = $now;
  2921. $i = 0;
  2922. if (!empty($conf->global->INVOICE_USE_SITUATION)) {
  2923. $final = true;
  2924. $nboflines = count($this->lines);
  2925. while (($i < $nboflines) && $final) {
  2926. $final = ($this->lines[$i]->situation_percent == 100);
  2927. $i++;
  2928. }
  2929. if (empty($final)) {
  2930. $this->situation_final = 0;
  2931. } else {
  2932. $this->situation_final = 1;
  2933. }
  2934. $this->setFinal($user);
  2935. }
  2936. }
  2937. } else {
  2938. $error++;
  2939. }
  2940. if (!$error) {
  2941. $this->db->commit();
  2942. return 1;
  2943. } else {
  2944. $this->db->rollback();
  2945. return -1;
  2946. }
  2947. }
  2948. /**
  2949. * Update price of next invoice
  2950. *
  2951. * @param Translate $langs Translate object
  2952. * @return bool false if KO, true if OK
  2953. */
  2954. public function updatePriceNextInvoice(&$langs)
  2955. {
  2956. foreach ($this->tab_next_situation_invoice as $next_invoice) {
  2957. $is_last = $next_invoice->is_last_in_cycle();
  2958. if ($next_invoice->statut == self::STATUS_DRAFT && $is_last != 1) {
  2959. $this->error = $langs->trans('updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
  2960. return false;
  2961. }
  2962. $next_invoice->brouillon = 1;
  2963. foreach ($next_invoice->lines as $line) {
  2964. $result = $next_invoice->updateline(
  2965. $line->id,
  2966. $line->desc,
  2967. $line->subprice,
  2968. $line->qty,
  2969. $line->remise_percent,
  2970. $line->date_start,
  2971. $line->date_end,
  2972. $line->tva_tx,
  2973. $line->localtax1_tx,
  2974. $line->localtax2_tx,
  2975. 'HT',
  2976. $line->info_bits,
  2977. $line->product_type,
  2978. $line->fk_parent_line,
  2979. 0,
  2980. $line->fk_fournprice,
  2981. $line->pa_ht,
  2982. $line->label,
  2983. $line->special_code,
  2984. $line->array_options,
  2985. $line->situation_percent,
  2986. $line->fk_unit
  2987. );
  2988. if ($result < 0) {
  2989. $this->error = $langs->trans('updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
  2990. return false;
  2991. }
  2992. }
  2993. break; // Only the next invoice and not each next invoice
  2994. }
  2995. return true;
  2996. }
  2997. /**
  2998. * Set draft status
  2999. *
  3000. * @param User $user Object user that modify
  3001. * @param int $idwarehouse Id warehouse to use for stock change.
  3002. * @return int <0 if KO, >0 if OK
  3003. */
  3004. public function setDraft($user, $idwarehouse = -1)
  3005. {
  3006. // phpcs:enable
  3007. global $conf, $langs;
  3008. $error = 0;
  3009. if ($this->statut == self::STATUS_DRAFT) {
  3010. dol_syslog(__METHOD__." already draft status", LOG_WARNING);
  3011. return 0;
  3012. }
  3013. dol_syslog(__METHOD__, LOG_DEBUG);
  3014. $this->db->begin();
  3015. $sql = "UPDATE ".MAIN_DB_PREFIX."facture";
  3016. $sql .= " SET fk_statut = ".self::STATUS_DRAFT;
  3017. $sql .= " WHERE rowid = ".((int) $this->id);
  3018. $result = $this->db->query($sql);
  3019. if ($result) {
  3020. if (!$error) {
  3021. $this->oldcopy = clone $this;
  3022. }
  3023. // If we decrease stock on invoice validation, we increase back
  3024. if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
  3025. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  3026. $langs->load("agenda");
  3027. $num = count($this->lines);
  3028. for ($i = 0; $i < $num; $i++) {
  3029. if ($this->lines[$i]->fk_product > 0) {
  3030. $mouvP = new MouvementStock($this->db);
  3031. $mouvP->origin = &$this;
  3032. $mouvP->setOrigin($this->element, $this->id);
  3033. // We decrease stock for product
  3034. if ($this->type == self::TYPE_CREDIT_NOTE) {
  3035. $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref));
  3036. } else {
  3037. $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref)); // we use 0 for price, to not change the weighted average value
  3038. }
  3039. }
  3040. }
  3041. }
  3042. if ($error == 0) {
  3043. $old_statut = $this->statut;
  3044. $this->brouillon = 1;
  3045. $this->statut = self::STATUS_DRAFT;
  3046. $this->status = self::STATUS_DRAFT;
  3047. // Call trigger
  3048. $result = $this->call_trigger('BILL_UNVALIDATE', $user);
  3049. if ($result < 0) {
  3050. $error++;
  3051. $this->statut = $old_statut;
  3052. $this->status = $old_statut;
  3053. $this->brouillon = 0;
  3054. }
  3055. // End call triggers
  3056. } else {
  3057. $this->db->rollback();
  3058. return -1;
  3059. }
  3060. if ($error == 0) {
  3061. $this->db->commit();
  3062. return 1;
  3063. } else {
  3064. $this->db->rollback();
  3065. return -1;
  3066. }
  3067. } else {
  3068. $this->error = $this->db->error();
  3069. $this->db->rollback();
  3070. return -1;
  3071. }
  3072. }
  3073. /**
  3074. * Add an invoice line into database (linked to product/service or not).
  3075. * Les parametres sont deja cense etre juste et avec valeurs finales a l'appel
  3076. * de cette methode. Aussi, pour le taux tva, il doit deja avoir ete defini
  3077. * par l'appelant par la methode get_default_tva(societe_vendeuse,societe_acheteuse,produit)
  3078. * et le desc doit deja avoir la bonne valeur (a l'appelant de gerer le multilangue)
  3079. *
  3080. * @param string $desc Description of line
  3081. * @param double $pu_ht Unit price without tax (> 0 even for credit note)
  3082. * @param double $qty Quantity
  3083. * @param double $txtva Force Vat rate, -1 for auto (Can contain the vat_src_code too with syntax '9.9 (CODE)')
  3084. * @param double $txlocaltax1 Local tax 1 rate (deprecated, use instead txtva with code inside)
  3085. * @param double $txlocaltax2 Local tax 2 rate (deprecated, use instead txtva with code inside)
  3086. * @param int $fk_product Id of predefined product/service
  3087. * @param double $remise_percent Percent of discount on line
  3088. * @param int $date_start Date start of service
  3089. * @param int $date_end Date end of service
  3090. * @param int $ventil Code of dispatching into accountancy
  3091. * @param int $info_bits Bits of type of lines
  3092. * @param int $fk_remise_except Id discount used
  3093. * @param string $price_base_type 'HT' or 'TTC'
  3094. * @param double $pu_ttc Unit price with tax (> 0 even for credit note)
  3095. * @param int $type Type of line (0=product, 1=service). Not used if fk_product is defined, the type of product is used.
  3096. * @param int $rang Position of line (-1 means last value + 1)
  3097. * @param int $special_code Special code (also used by externals modules!)
  3098. * @param string $origin Depend on global conf MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION can be 'orderdet', 'propaldet'..., else 'order','propal,'....
  3099. * @param int $origin_id Depend on global conf MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION can be Id of origin object (aka line id), else object id
  3100. * @param int $fk_parent_line Id of parent line
  3101. * @param int $fk_fournprice Supplier price id (to calculate margin) or ''
  3102. * @param int $pa_ht Buying price of line (to calculate margin) or ''
  3103. * @param string $label Label of the line (deprecated, do not use)
  3104. * @param array $array_options extrafields array
  3105. * @param int $situation_percent Situation advance percentage
  3106. * @param int $fk_prev_id Previous situation line id reference
  3107. * @param string $fk_unit Code of the unit to use. Null to use the default one
  3108. * @param double $pu_ht_devise Unit price in foreign currency
  3109. * @param string $ref_ext External reference of the line
  3110. * @param int $noupdateafterinsertline No update after insert of line
  3111. * @return int <0 if KO, Id of line if OK
  3112. */
  3113. public function addline(
  3114. $desc,
  3115. $pu_ht,
  3116. $qty,
  3117. $txtva,
  3118. $txlocaltax1 = 0,
  3119. $txlocaltax2 = 0,
  3120. $fk_product = 0,
  3121. $remise_percent = 0,
  3122. $date_start = '',
  3123. $date_end = '',
  3124. $ventil = 0,
  3125. $info_bits = 0,
  3126. $fk_remise_except = '',
  3127. $price_base_type = 'HT',
  3128. $pu_ttc = 0,
  3129. $type = 0,
  3130. $rang = -1,
  3131. $special_code = 0,
  3132. $origin = '',
  3133. $origin_id = 0,
  3134. $fk_parent_line = 0,
  3135. $fk_fournprice = null,
  3136. $pa_ht = 0,
  3137. $label = '',
  3138. $array_options = 0,
  3139. $situation_percent = 100,
  3140. $fk_prev_id = 0,
  3141. $fk_unit = null,
  3142. $pu_ht_devise = 0,
  3143. $ref_ext = '',
  3144. $noupdateafterinsertline = 0
  3145. ) {
  3146. // Deprecation warning
  3147. if ($label) {
  3148. dol_syslog(__METHOD__.": using line label is deprecated", LOG_WARNING);
  3149. //var_dump(debug_backtrace(false));exit;
  3150. }
  3151. global $mysoc, $conf, $langs;
  3152. dol_syslog(get_class($this)."::addline id=$this->id,desc=$desc,pu_ht=$pu_ht,qty=$qty,txtva=$txtva, txlocaltax1=$txlocaltax1, txlocaltax2=$txlocaltax2, fk_product=$fk_product,remise_percent=$remise_percent,date_start=$date_start,date_end=$date_end,ventil=$ventil,info_bits=$info_bits,fk_remise_except=$fk_remise_except,price_base_type=$price_base_type,pu_ttc=$pu_ttc,type=$type, fk_unit=$fk_unit", LOG_DEBUG);
  3153. if ($this->statut == self::STATUS_DRAFT) {
  3154. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  3155. // Clean parameters
  3156. if (empty($remise_percent)) {
  3157. $remise_percent = 0;
  3158. }
  3159. if (empty($qty)) {
  3160. $qty = 0;
  3161. }
  3162. if (empty($info_bits)) {
  3163. $info_bits = 0;
  3164. }
  3165. if (empty($rang)) {
  3166. $rang = 0;
  3167. }
  3168. if (empty($ventil)) {
  3169. $ventil = 0;
  3170. }
  3171. if (empty($txtva)) {
  3172. $txtva = 0;
  3173. }
  3174. if (empty($txlocaltax1)) {
  3175. $txlocaltax1 = 0;
  3176. }
  3177. if (empty($txlocaltax2)) {
  3178. $txlocaltax2 = 0;
  3179. }
  3180. if (empty($fk_parent_line) || $fk_parent_line < 0) {
  3181. $fk_parent_line = 0;
  3182. }
  3183. if (empty($fk_prev_id)) {
  3184. $fk_prev_id = 'null';
  3185. }
  3186. if (!isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '') {
  3187. $situation_percent = 100;
  3188. }
  3189. if (empty($ref_ext)) {
  3190. $ref_ext = '';
  3191. }
  3192. $remise_percent = price2num($remise_percent);
  3193. $qty = price2num($qty);
  3194. $pu_ht = price2num($pu_ht);
  3195. $pu_ht_devise = price2num($pu_ht_devise);
  3196. $pu_ttc = price2num($pu_ttc);
  3197. $pa_ht = price2num($pa_ht);
  3198. if (!preg_match('/\((.*)\)/', $txtva)) {
  3199. $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
  3200. }
  3201. $txlocaltax1 = price2num($txlocaltax1);
  3202. $txlocaltax2 = price2num($txlocaltax2);
  3203. if ($price_base_type == 'HT') {
  3204. $pu = $pu_ht;
  3205. } else {
  3206. $pu = $pu_ttc;
  3207. }
  3208. // Check parameters
  3209. if ($type < 0) {
  3210. return -1;
  3211. }
  3212. if ($date_start && $date_end && $date_start > $date_end) {
  3213. $langs->load("errors");
  3214. $this->error = $langs->trans('ErrorStartDateGreaterEnd');
  3215. return -1;
  3216. }
  3217. $this->db->begin();
  3218. $product_type = $type;
  3219. if (!empty($fk_product) && $fk_product > 0) {
  3220. $product = new Product($this->db);
  3221. $result = $product->fetch($fk_product);
  3222. $product_type = $product->type;
  3223. if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_INVOICE) && $product_type == 0 && $product->stock_reel < $qty) {
  3224. $langs->load("errors");
  3225. $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
  3226. $this->db->rollback();
  3227. return -3;
  3228. }
  3229. }
  3230. $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
  3231. // Clean vat code
  3232. $reg = array();
  3233. $vat_src_code = '';
  3234. if (preg_match('/\((.*)\)/', $txtva, $reg)) {
  3235. $vat_src_code = $reg[1];
  3236. $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
  3237. }
  3238. // Calcul du total TTC et de la TVA pour la ligne a partir de
  3239. // qty, pu, remise_percent et txtva
  3240. // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
  3241. // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
  3242. $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $product_type, $mysoc, $localtaxes_type, $situation_percent, $this->multicurrency_tx, $pu_ht_devise);
  3243. $total_ht = $tabprice[0];
  3244. $total_tva = $tabprice[1];
  3245. $total_ttc = $tabprice[2];
  3246. $total_localtax1 = $tabprice[9];
  3247. $total_localtax2 = $tabprice[10];
  3248. $pu_ht = $tabprice[3];
  3249. // MultiCurrency
  3250. $multicurrency_total_ht = $tabprice[16];
  3251. $multicurrency_total_tva = $tabprice[17];
  3252. $multicurrency_total_ttc = $tabprice[18];
  3253. $pu_ht_devise = $tabprice[19];
  3254. // Rank to use
  3255. $ranktouse = $rang;
  3256. if ($ranktouse == -1) {
  3257. $rangmax = $this->line_max($fk_parent_line);
  3258. $ranktouse = $rangmax + 1;
  3259. }
  3260. // Insert line
  3261. $this->line = new FactureLigne($this->db);
  3262. $this->line->context = $this->context;
  3263. $this->line->fk_facture = $this->id;
  3264. $this->line->label = $label; // deprecated
  3265. $this->line->desc = $desc;
  3266. $this->line->ref_ext = $ref_ext;
  3267. $this->line->qty = ($this->type == self::TYPE_CREDIT_NOTE ? abs($qty) : $qty); // For credit note, quantity is always positive and unit price negative
  3268. $this->line->subprice = ($this->type == self::TYPE_CREDIT_NOTE ? -abs($pu_ht) : $pu_ht); // For credit note, unit price always negative, always positive otherwise
  3269. $this->line->vat_src_code = $vat_src_code;
  3270. $this->line->tva_tx = $txtva;
  3271. $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
  3272. $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
  3273. $this->line->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
  3274. $this->line->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
  3275. $this->line->total_ht = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_ht) : $total_ht); // For credit note and if qty is negative, total is negative
  3276. $this->line->total_ttc = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_ttc) : $total_ttc); // For credit note and if qty is negative, total is negative
  3277. $this->line->total_tva = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_tva) : $total_tva); // For credit note and if qty is negative, total is negative
  3278. $this->line->total_localtax1 = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_localtax1) : $total_localtax1); // For credit note and if qty is negative, total is negative
  3279. $this->line->total_localtax2 = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_localtax2) : $total_localtax2); // For credit note and if qty is negative, total is negative
  3280. $this->line->fk_product = $fk_product;
  3281. $this->line->product_type = $product_type;
  3282. $this->line->remise_percent = $remise_percent;
  3283. $this->line->date_start = $date_start;
  3284. $this->line->date_end = $date_end;
  3285. $this->line->ventil = $ventil;
  3286. $this->line->rang = $ranktouse;
  3287. $this->line->info_bits = $info_bits;
  3288. $this->line->fk_remise_except = $fk_remise_except;
  3289. $this->line->special_code = $special_code;
  3290. $this->line->fk_parent_line = $fk_parent_line;
  3291. $this->line->origin = $origin;
  3292. $this->line->origin_id = $origin_id;
  3293. $this->line->situation_percent = $situation_percent;
  3294. $this->line->fk_prev_id = $fk_prev_id;
  3295. $this->line->fk_unit = $fk_unit;
  3296. // infos marge
  3297. $this->line->fk_fournprice = $fk_fournprice;
  3298. $this->line->pa_ht = $pa_ht;
  3299. // Multicurrency
  3300. $this->line->fk_multicurrency = $this->fk_multicurrency;
  3301. $this->line->multicurrency_code = $this->multicurrency_code;
  3302. $this->line->multicurrency_subprice = ($this->type == self::TYPE_CREDIT_NOTE ? -abs($pu_ht_devise) : $pu_ht_devise); // For credit note, unit price always negative, always positive otherwise
  3303. $this->line->multicurrency_total_ht = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_ht) : $multicurrency_total_ht); // For credit note and if qty is negative, total is negative
  3304. $this->line->multicurrency_total_tva = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_tva) : $multicurrency_total_tva); // For credit note and if qty is negative, total is negative
  3305. $this->line->multicurrency_total_ttc = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_ttc) : $multicurrency_total_ttc); // For credit note and if qty is negative, total is negative
  3306. if (is_array($array_options) && count($array_options) > 0) {
  3307. $this->line->array_options = $array_options;
  3308. }
  3309. $result = $this->line->insert();
  3310. if ($result > 0) {
  3311. // Reorder if child line
  3312. if (!empty($fk_parent_line)) {
  3313. $this->line_order(true, 'DESC');
  3314. } elseif ($ranktouse > 0 && $ranktouse <= count($this->lines)) { // Update all rank of all other lines
  3315. $linecount = count($this->lines);
  3316. for ($ii = $ranktouse; $ii <= $linecount; $ii++) {
  3317. $this->updateRangOfLine($this->lines[$ii - 1]->id, $ii + 1);
  3318. }
  3319. }
  3320. // Mise a jour informations denormalisees au niveau de la facture meme
  3321. if (empty($noupdateafterinsertline)) {
  3322. $result = $this->update_price(1, 'auto', 0, $mysoc); // The addline method is designed to add line from user input so total calculation with update_price must be done using 'auto' mode.
  3323. }
  3324. if ($result > 0) {
  3325. $this->db->commit();
  3326. return $this->line->id;
  3327. } else {
  3328. $this->error = $this->db->lasterror();
  3329. $this->db->rollback();
  3330. return -1;
  3331. }
  3332. } else {
  3333. $this->error = $this->line->error;
  3334. $this->errors = $this->line->errors;
  3335. $this->db->rollback();
  3336. return -2;
  3337. }
  3338. } else {
  3339. dol_syslog(get_class($this)."::addline status of invoice must be Draft to allow use of ->addline()", LOG_ERR);
  3340. return -3;
  3341. }
  3342. }
  3343. /**
  3344. * Update a detail line
  3345. *
  3346. * @param int $rowid Id of line to update
  3347. * @param string $desc Description of line
  3348. * @param double $pu Prix unitaire (HT ou TTC selon price_base_type) (> 0 even for credit note lines)
  3349. * @param double $qty Quantity
  3350. * @param double $remise_percent Percentage discount of the line
  3351. * @param int $date_start Date de debut de validite du service
  3352. * @param int $date_end Date de fin de validite du service
  3353. * @param double $txtva VAT Rate (Can be '8.5', '8.5 (ABC)')
  3354. * @param double $txlocaltax1 Local tax 1 rate
  3355. * @param double $txlocaltax2 Local tax 2 rate
  3356. * @param string $price_base_type HT or TTC
  3357. * @param int $info_bits Miscellaneous informations
  3358. * @param int $type Type of line (0=product, 1=service)
  3359. * @param int $fk_parent_line Id of parent line (0 in most cases, used by modules adding sublevels into lines).
  3360. * @param int $skip_update_total Keep fields total_xxx to 0 (used for special lines by some modules)
  3361. * @param int $fk_fournprice Id of origin supplier price
  3362. * @param int $pa_ht Price (without tax) of product when it was bought
  3363. * @param string $label Label of the line (deprecated, do not use)
  3364. * @param int $special_code Special code (also used by externals modules!)
  3365. * @param array $array_options extrafields array
  3366. * @param int $situation_percent Situation advance percentage
  3367. * @param string $fk_unit Code of the unit to use. Null to use the default one
  3368. * @param double $pu_ht_devise Unit price in currency
  3369. * @param int $notrigger disable line update trigger
  3370. * @param string $ref_ext External reference of the line
  3371. * @param integer $rang rank of line
  3372. * @return int < 0 if KO, > 0 if OK
  3373. */
  3374. public function updateline($rowid, $desc, $pu, $qty, $remise_percent, $date_start, $date_end, $txtva, $txlocaltax1 = 0, $txlocaltax2 = 0, $price_base_type = 'HT', $info_bits = 0, $type = self::TYPE_STANDARD, $fk_parent_line = 0, $skip_update_total = 0, $fk_fournprice = null, $pa_ht = 0, $label = '', $special_code = 0, $array_options = 0, $situation_percent = 100, $fk_unit = null, $pu_ht_devise = 0, $notrigger = 0, $ref_ext = '', $rang = 0)
  3375. {
  3376. global $conf, $user;
  3377. // Deprecation warning
  3378. if ($label) {
  3379. dol_syslog(__METHOD__.": using line label is deprecated", LOG_WARNING);
  3380. }
  3381. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  3382. global $mysoc, $langs;
  3383. dol_syslog(get_class($this)."::updateline rowid=$rowid, desc=$desc, pu=$pu, qty=$qty, remise_percent=$remise_percent, date_start=$date_start, date_end=$date_end, txtva=$txtva, txlocaltax1=$txlocaltax1, txlocaltax2=$txlocaltax2, price_base_type=$price_base_type, info_bits=$info_bits, type=$type, fk_parent_line=$fk_parent_line pa_ht=$pa_ht, special_code=$special_code, fk_unit=$fk_unit, pu_ht_devise=$pu_ht_devise", LOG_DEBUG);
  3384. if ($this->statut == self::STATUS_DRAFT) {
  3385. if (!$this->is_last_in_cycle() && empty($this->error)) {
  3386. if (!$this->checkProgressLine($rowid, $situation_percent)) {
  3387. if (!$this->error) {
  3388. $this->error = $langs->trans('invoiceLineProgressError');
  3389. }
  3390. return -3;
  3391. }
  3392. }
  3393. if ($date_start && $date_end && $date_start > $date_end) {
  3394. $langs->load("errors");
  3395. $this->error = $langs->trans('ErrorStartDateGreaterEnd');
  3396. return -1;
  3397. }
  3398. $this->db->begin();
  3399. // Clean parameters
  3400. if (empty($qty)) {
  3401. $qty = 0;
  3402. }
  3403. if (empty($fk_parent_line) || $fk_parent_line < 0) {
  3404. $fk_parent_line = 0;
  3405. }
  3406. if (empty($special_code) || $special_code == 3) {
  3407. $special_code = 0;
  3408. }
  3409. if (!isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '') {
  3410. $situation_percent = 100;
  3411. }
  3412. if (empty($ref_ext)) {
  3413. $ref_ext = '';
  3414. }
  3415. $remise_percent = price2num($remise_percent);
  3416. $qty = price2num($qty);
  3417. $pu = price2num($pu);
  3418. $pu_ht_devise = price2num($pu_ht_devise);
  3419. $pa_ht = price2num($pa_ht);
  3420. if (!preg_match('/\((.*)\)/', $txtva)) {
  3421. $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
  3422. }
  3423. $txlocaltax1 = price2num($txlocaltax1);
  3424. $txlocaltax2 = price2num($txlocaltax2);
  3425. // Check parameters
  3426. if ($type < 0) {
  3427. return -1;
  3428. }
  3429. // Calculate total with, without tax and tax from qty, pu, remise_percent and txtva
  3430. // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
  3431. // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
  3432. $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
  3433. // Clean vat code
  3434. $reg = array();
  3435. $vat_src_code = '';
  3436. if (preg_match('/\((.*)\)/', $txtva, $reg)) {
  3437. $vat_src_code = $reg[1];
  3438. $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
  3439. }
  3440. $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, $situation_percent, $this->multicurrency_tx, $pu_ht_devise);
  3441. $total_ht = $tabprice[0];
  3442. $total_tva = $tabprice[1];
  3443. $total_ttc = $tabprice[2];
  3444. $total_localtax1 = $tabprice[9];
  3445. $total_localtax2 = $tabprice[10];
  3446. $pu_ht = $tabprice[3];
  3447. $pu_tva = $tabprice[4];
  3448. $pu_ttc = $tabprice[5];
  3449. // MultiCurrency
  3450. $multicurrency_total_ht = $tabprice[16];
  3451. $multicurrency_total_tva = $tabprice[17];
  3452. $multicurrency_total_ttc = $tabprice[18];
  3453. $pu_ht_devise = $tabprice[19];
  3454. // Old properties: $price, $remise (deprecated)
  3455. $price = $pu;
  3456. $remise = 0;
  3457. if ($remise_percent > 0) {
  3458. $remise = round(($pu * $remise_percent / 100), 2);
  3459. $price = ($pu - $remise);
  3460. }
  3461. $price = price2num($price);
  3462. //Fetch current line from the database and then clone the object and set it in $oldline property
  3463. $line = new FactureLigne($this->db);
  3464. $line->fetch($rowid);
  3465. $line->fetch_optionals();
  3466. if (!empty($line->fk_product)) {
  3467. $product = new Product($this->db);
  3468. $result = $product->fetch($line->fk_product);
  3469. $product_type = $product->type;
  3470. if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_INVOICE) && $product_type == 0 && $product->stock_reel < $qty) {
  3471. $langs->load("errors");
  3472. $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
  3473. $this->db->rollback();
  3474. return -3;
  3475. }
  3476. }
  3477. $staticline = clone $line;
  3478. $line->oldline = $staticline;
  3479. $this->line = $line;
  3480. $this->line->context = $this->context;
  3481. $this->line->rang = $rang;
  3482. // Reorder if fk_parent_line change
  3483. if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) {
  3484. $rangmax = $this->line_max($fk_parent_line);
  3485. $this->line->rang = $rangmax + 1;
  3486. }
  3487. $this->line->id = $rowid;
  3488. $this->line->rowid = $rowid;
  3489. $this->line->label = $label;
  3490. $this->line->desc = $desc;
  3491. $this->line->ref_ext = $ref_ext;
  3492. $this->line->qty = ($this->type == self::TYPE_CREDIT_NOTE ?abs($qty) : $qty); // For credit note, quantity is always positive and unit price negative
  3493. $this->line->vat_src_code = $vat_src_code;
  3494. $this->line->tva_tx = $txtva;
  3495. $this->line->localtax1_tx = $txlocaltax1;
  3496. $this->line->localtax2_tx = $txlocaltax2;
  3497. $this->line->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
  3498. $this->line->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
  3499. $this->line->remise_percent = $remise_percent;
  3500. $this->line->subprice = ($this->type == self::TYPE_CREDIT_NOTE ?-abs($pu_ht) : $pu_ht); // For credit note, unit price always negative, always positive otherwise
  3501. $this->line->date_start = $date_start;
  3502. $this->line->date_end = $date_end;
  3503. $this->line->total_ht = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_ht) : $total_ht); // For credit note and if qty is negative, total is negative
  3504. $this->line->total_tva = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_tva) : $total_tva);
  3505. $this->line->total_localtax1 = $total_localtax1;
  3506. $this->line->total_localtax2 = $total_localtax2;
  3507. $this->line->total_ttc = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_ttc) : $total_ttc);
  3508. $this->line->info_bits = $info_bits;
  3509. $this->line->special_code = $special_code;
  3510. $this->line->product_type = $type;
  3511. $this->line->fk_parent_line = $fk_parent_line;
  3512. $this->line->skip_update_total = $skip_update_total;
  3513. $this->line->situation_percent = $situation_percent;
  3514. $this->line->fk_unit = $fk_unit;
  3515. $this->line->fk_fournprice = $fk_fournprice;
  3516. $this->line->pa_ht = $pa_ht;
  3517. // Multicurrency
  3518. $this->line->multicurrency_subprice = ($this->type == self::TYPE_CREDIT_NOTE ?-abs($pu_ht_devise) : $pu_ht_devise); // For credit note, unit price always negative, always positive otherwise
  3519. $this->line->multicurrency_total_ht = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($multicurrency_total_ht) : $multicurrency_total_ht); // For credit note and if qty is negative, total is negative
  3520. $this->line->multicurrency_total_tva = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($multicurrency_total_tva) : $multicurrency_total_tva);
  3521. $this->line->multicurrency_total_ttc = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($multicurrency_total_ttc) : $multicurrency_total_ttc);
  3522. if (is_array($array_options) && count($array_options) > 0) {
  3523. // We replace values in this->line->array_options only for entries defined into $array_options
  3524. foreach ($array_options as $key => $value) {
  3525. $this->line->array_options[$key] = $array_options[$key];
  3526. }
  3527. }
  3528. $result = $this->line->update($user, $notrigger);
  3529. if ($result > 0) {
  3530. // Reorder if child line
  3531. if (!empty($fk_parent_line)) {
  3532. $this->line_order(true, 'DESC');
  3533. }
  3534. // Mise a jour info denormalisees au niveau facture
  3535. $this->update_price(1);
  3536. $this->db->commit();
  3537. return $result;
  3538. } else {
  3539. $this->error = $this->line->error;
  3540. $this->db->rollback();
  3541. return -1;
  3542. }
  3543. } else {
  3544. $this->error = "Invoice statut makes operation forbidden";
  3545. return -2;
  3546. }
  3547. }
  3548. /**
  3549. * Check if the percent edited is lower of next invoice line
  3550. *
  3551. * @param int $idline id of line to check
  3552. * @param float $situation_percent progress percentage need to be test
  3553. * @return false if KO, true if OK
  3554. */
  3555. public function checkProgressLine($idline, $situation_percent)
  3556. {
  3557. $sql = 'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.'facturedet fd
  3558. INNER JOIN '.MAIN_DB_PREFIX.'facture f ON (fd.fk_facture = f.rowid)
  3559. WHERE fd.fk_prev_id = '.((int) $idline).' AND f.fk_statut <> 0';
  3560. $result = $this->db->query($sql);
  3561. if (!$result) {
  3562. $this->error = $this->db->error();
  3563. return false;
  3564. }
  3565. $obj = $this->db->fetch_object($result);
  3566. if ($obj === null) {
  3567. return true;
  3568. } else {
  3569. return $situation_percent < $obj->situation_percent;
  3570. }
  3571. }
  3572. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3573. /**
  3574. * Update invoice line with percentage
  3575. *
  3576. * @param FactureLigne $line Invoice line
  3577. * @param int $percent Percentage
  3578. * @param boolean $update_price Update object price
  3579. * @return void
  3580. */
  3581. public function update_percent($line, $percent, $update_price = true)
  3582. {
  3583. // phpcs:enable
  3584. global $mysoc, $user;
  3585. // Progress should never be changed for discount lines
  3586. if (($line->info_bits & 2) == 2) {
  3587. return;
  3588. }
  3589. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  3590. // Cap percentages to 100
  3591. if ($percent > 100) {
  3592. $percent = 100;
  3593. }
  3594. $line->situation_percent = $percent;
  3595. $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, '', $percent);
  3596. $line->total_ht = $tabprice[0];
  3597. $line->total_tva = $tabprice[1];
  3598. $line->total_ttc = $tabprice[2];
  3599. $line->total_localtax1 = $tabprice[9];
  3600. $line->total_localtax2 = $tabprice[10];
  3601. $line->multicurrency_total_ht = $tabprice[16];
  3602. $line->multicurrency_total_tva = $tabprice[17];
  3603. $line->multicurrency_total_ttc = $tabprice[18];
  3604. $line->update($user);
  3605. // sometimes it is better to not update price for each line, ie when updating situation on all lines
  3606. if ($update_price) {
  3607. $this->update_price(1);
  3608. }
  3609. }
  3610. /**
  3611. * Delete line in database
  3612. *
  3613. * @param int $rowid Id of line to delete
  3614. * @return int <0 if KO, >0 if OK
  3615. */
  3616. public function deleteline($rowid)
  3617. {
  3618. global $user;
  3619. dol_syslog(get_class($this)."::deleteline rowid=".((int) $rowid), LOG_DEBUG);
  3620. if ($this->statut != self::STATUS_DRAFT) {
  3621. $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
  3622. return -1;
  3623. }
  3624. $this->db->begin();
  3625. // Free discount linked to invoice line
  3626. $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
  3627. $sql .= ' SET fk_facture_line = NULL';
  3628. $sql .= ' WHERE fk_facture_line = '.((int) $rowid);
  3629. dol_syslog(get_class($this)."::deleteline", LOG_DEBUG);
  3630. $result = $this->db->query($sql);
  3631. if (!$result) {
  3632. $this->error = $this->db->error();
  3633. $this->db->rollback();
  3634. return -1;
  3635. }
  3636. $line = new FactureLigne($this->db);
  3637. $line->context = $this->context;
  3638. // For triggers
  3639. $result = $line->fetch($rowid);
  3640. if (!($result > 0)) {
  3641. dol_print_error($this->db, $line->error, $line->errors);
  3642. }
  3643. if ($line->delete($user) > 0) {
  3644. $result = $this->update_price(1);
  3645. if ($result > 0) {
  3646. $this->db->commit();
  3647. return 1;
  3648. } else {
  3649. $this->db->rollback();
  3650. $this->error = $this->db->lasterror();
  3651. return -1;
  3652. }
  3653. } else {
  3654. $this->db->rollback();
  3655. $this->error = $line->error;
  3656. return -1;
  3657. }
  3658. }
  3659. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3660. /**
  3661. * Set percent discount
  3662. *
  3663. * @deprecated
  3664. * @see setDiscount()
  3665. * @param User $user User that set discount
  3666. * @param double $remise Discount
  3667. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3668. * @return int <0 if ko, >0 if ok
  3669. */
  3670. public function set_remise($user, $remise, $notrigger = 0)
  3671. {
  3672. // phpcs:enable
  3673. dol_syslog(get_class($this)."::set_remise is deprecated, use setDiscount instead", LOG_NOTICE);
  3674. return $this->setDiscount($user, $remise, $notrigger);
  3675. }
  3676. /**
  3677. * Set percent discount
  3678. *
  3679. * @param User $user User that set discount
  3680. * @param double $remise Discount
  3681. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3682. * @return int <0 if ko, >0 if ok
  3683. */
  3684. public function setDiscount($user, $remise, $notrigger = 0)
  3685. {
  3686. // Clean parameters
  3687. if (empty($remise)) {
  3688. $remise = 0;
  3689. }
  3690. if ($user->rights->facture->creer) {
  3691. $remise = price2num($remise, 2);
  3692. $error = 0;
  3693. $this->db->begin();
  3694. $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
  3695. $sql .= ' SET remise_percent = '.((float) $remise);
  3696. $sql .= " WHERE rowid = ".((int) $this->id);
  3697. $sql .= ' AND fk_statut = '.self::STATUS_DRAFT;
  3698. dol_syslog(__METHOD__, LOG_DEBUG);
  3699. $resql = $this->db->query($sql);
  3700. if (!$resql) {
  3701. $this->errors[] = $this->db->error();
  3702. $error++;
  3703. }
  3704. if (!$notrigger && empty($error)) {
  3705. // Call trigger
  3706. $result = $this->call_trigger('BILL_MODIFY', $user);
  3707. if ($result < 0) {
  3708. $error++;
  3709. }
  3710. // End call triggers
  3711. }
  3712. if (!$error) {
  3713. $this->remise_percent = $remise;
  3714. $this->update_price(1);
  3715. $this->db->commit();
  3716. return 1;
  3717. } else {
  3718. foreach ($this->errors as $errmsg) {
  3719. dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
  3720. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  3721. }
  3722. $this->db->rollback();
  3723. return -1 * $error;
  3724. }
  3725. }
  3726. }
  3727. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3728. /**
  3729. * Set absolute discount
  3730. *
  3731. * @param User $user User that set discount
  3732. * @param double $remise Discount
  3733. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3734. * @return int <0 if KO, >0 if OK
  3735. */
  3736. public function set_remise_absolue($user, $remise, $notrigger = 0)
  3737. {
  3738. // phpcs:enable
  3739. if (empty($remise)) {
  3740. $remise = 0;
  3741. }
  3742. if ($user->rights->facture->creer) {
  3743. $error = 0;
  3744. $this->db->begin();
  3745. $remise = price2num($remise);
  3746. $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
  3747. $sql .= ' SET remise_absolue = '.((float) $remise);
  3748. $sql .= " WHERE rowid = ".((int) $this->id);
  3749. $sql .= ' AND fk_statut = '.self::STATUS_DRAFT;
  3750. dol_syslog(__METHOD__, LOG_DEBUG);
  3751. $resql = $this->db->query($sql);
  3752. if (!$resql) {
  3753. $this->errors[] = $this->db->error();
  3754. $error++;
  3755. }
  3756. if (!$error) {
  3757. $this->oldcopy = clone $this;
  3758. $this->remise_absolue = $remise;
  3759. $this->update_price(1);
  3760. }
  3761. if (!$notrigger && empty($error)) {
  3762. // Call trigger
  3763. $result = $this->call_trigger('BILL_MODIFY', $user);
  3764. if ($result < 0) {
  3765. $error++;
  3766. }
  3767. // End call triggers
  3768. }
  3769. if (!$error) {
  3770. $this->db->commit();
  3771. return 1;
  3772. } else {
  3773. foreach ($this->errors as $errmsg) {
  3774. dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
  3775. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  3776. }
  3777. $this->db->rollback();
  3778. return -1 * $error;
  3779. }
  3780. }
  3781. }
  3782. /**
  3783. * Return next reference of customer invoice not already used (or last reference)
  3784. * according to numbering module defined into constant FACTURE_ADDON
  3785. *
  3786. * @param Societe $soc object company
  3787. * @param string $mode 'next' for next value or 'last' for last value
  3788. * @return string free ref or last ref
  3789. */
  3790. public function getNextNumRef($soc, $mode = 'next')
  3791. {
  3792. global $conf, $langs;
  3793. if ($this->module_source == 'takepos') {
  3794. $langs->load('cashdesk');
  3795. $moduleName = 'takepos';
  3796. $moduleSourceName = 'Takepos';
  3797. $addonConstName = 'TAKEPOS_REF_ADDON';
  3798. // Clean parameters (if not defined or using deprecated value)
  3799. if (empty($conf->global->TAKEPOS_REF_ADDON)) {
  3800. $conf->global->TAKEPOS_REF_ADDON = 'mod_takepos_ref_simple';
  3801. }
  3802. $addon = $conf->global->TAKEPOS_REF_ADDON;
  3803. } else {
  3804. $langs->load('bills');
  3805. $moduleName = 'facture';
  3806. $moduleSourceName = 'Invoice';
  3807. $addonConstName = 'FACTURE_ADDON';
  3808. // Clean parameters (if not defined or using deprecated value)
  3809. if (empty($conf->global->FACTURE_ADDON)) {
  3810. $conf->global->FACTURE_ADDON = 'mod_facture_terre';
  3811. } elseif ($conf->global->FACTURE_ADDON == 'terre') {
  3812. $conf->global->FACTURE_ADDON = 'mod_facture_terre';
  3813. } elseif ($conf->global->FACTURE_ADDON == 'mercure') {
  3814. $conf->global->FACTURE_ADDON = 'mod_facture_mercure';
  3815. }
  3816. $addon = $conf->global->FACTURE_ADDON;
  3817. }
  3818. if (!empty($addon)) {
  3819. dol_syslog("Call getNextNumRef with ".$addonConstName." = ".$conf->global->FACTURE_ADDON.", thirdparty=".$soc->name.", type=".$soc->typent_code.", mode=".$mode, LOG_DEBUG);
  3820. $mybool = false;
  3821. $file = $addon.'.php';
  3822. $classname = $addon;
  3823. // Include file with class
  3824. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  3825. foreach ($dirmodels as $reldir) {
  3826. $dir = dol_buildpath($reldir.'core/modules/'.$moduleName.'/');
  3827. // Load file with numbering class (if found)
  3828. if (is_file($dir.$file) && is_readable($dir.$file)) {
  3829. $mybool |= include_once $dir.$file;
  3830. }
  3831. }
  3832. // For compatibility
  3833. if (!$mybool) {
  3834. $file = $addon.'/'.$addon.'.modules.php';
  3835. $classname = 'mod_'.$moduleName.'_'.$addon;
  3836. $classname = preg_replace('/\-.*$/', '', $classname);
  3837. // Include file with class
  3838. foreach ($conf->file->dol_document_root as $dirroot) {
  3839. $dir = $dirroot.'/core/modules/'.$moduleName.'/';
  3840. // Load file with numbering class (if found)
  3841. if (is_file($dir.$file) && is_readable($dir.$file)) {
  3842. $mybool |= include_once $dir.$file;
  3843. }
  3844. }
  3845. }
  3846. if (!$mybool) {
  3847. dol_print_error('', 'Failed to include file '.$file);
  3848. return '';
  3849. }
  3850. $obj = new $classname();
  3851. $numref = $obj->getNextValue($soc, $this, $mode);
  3852. /**
  3853. * $numref can be empty in case we ask for the last value because if there is no invoice created with the
  3854. * set up mask.
  3855. */
  3856. if ($mode != 'last' && !$numref) {
  3857. $this->error = $obj->error;
  3858. return '';
  3859. }
  3860. return $numref;
  3861. } else {
  3862. $langs->load('errors');
  3863. print $langs->trans('Error').' '.$langs->trans('ErrorModuleSetupNotComplete', $langs->transnoentitiesnoconv($moduleSourceName));
  3864. return '';
  3865. }
  3866. }
  3867. /**
  3868. * Load miscellaneous information for tab "Info"
  3869. *
  3870. * @param int $id Id of object to load
  3871. * @return void
  3872. */
  3873. public function info($id)
  3874. {
  3875. $sql = 'SELECT c.rowid, datec, date_valid as datev, tms as datem,';
  3876. $sql .= ' date_closing as dateclosing,';
  3877. $sql .= ' fk_user_author, fk_user_valid, fk_user_closing';
  3878. $sql .= ' FROM '.MAIN_DB_PREFIX.'facture as c';
  3879. $sql .= ' WHERE c.rowid = '.((int) $id);
  3880. $result = $this->db->query($sql);
  3881. if ($result) {
  3882. if ($this->db->num_rows($result)) {
  3883. $obj = $this->db->fetch_object($result);
  3884. $this->id = $obj->rowid;
  3885. if ($obj->fk_user_author) {
  3886. $cuser = new User($this->db);
  3887. $cuser->fetch($obj->fk_user_author);
  3888. $this->user_creation = $cuser;
  3889. }
  3890. if ($obj->fk_user_valid) {
  3891. $vuser = new User($this->db);
  3892. $vuser->fetch($obj->fk_user_valid);
  3893. $this->user_validation = $vuser;
  3894. }
  3895. if ($obj->fk_user_closing) {
  3896. $cluser = new User($this->db);
  3897. $cluser->fetch($obj->fk_user_closing);
  3898. $this->user_closing = $cluser;
  3899. }
  3900. $this->date_creation = $this->db->jdate($obj->datec);
  3901. $this->date_modification = $this->db->jdate($obj->datem);
  3902. $this->date_validation = $this->db->jdate($obj->datev);
  3903. $this->date_closing = $this->db->jdate($obj->dateclosing);
  3904. }
  3905. $this->db->free($result);
  3906. } else {
  3907. dol_print_error($this->db);
  3908. }
  3909. }
  3910. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3911. /**
  3912. * Return list of invoices (eventually filtered on a user) into an array
  3913. *
  3914. * @param int $shortlist 0=Return array[id]=ref, 1=Return array[](id=>id,ref=>ref,name=>name)
  3915. * @param int $draft 0=not draft, 1=draft
  3916. * @param User $excluser Objet user to exclude
  3917. * @param int $socid Id third pary
  3918. * @param int $limit For pagination
  3919. * @param int $offset For pagination
  3920. * @param string $sortfield Sort criteria
  3921. * @param string $sortorder Sort order
  3922. * @return array|int -1 if KO, array with result if OK
  3923. */
  3924. public function liste_array($shortlist = 0, $draft = 0, $excluser = '', $socid = 0, $limit = 0, $offset = 0, $sortfield = 'f.datef,f.rowid', $sortorder = 'DESC')
  3925. {
  3926. // phpcs:enable
  3927. global $conf, $user;
  3928. $ga = array();
  3929. $sql = "SELECT s.rowid, s.nom as name, s.client,";
  3930. $sql .= " f.rowid as fid, f.ref as ref, f.datef as df";
  3931. if (empty($user->rights->societe->client->voir) && !$socid) {
  3932. $sql .= ", sc.fk_soc, sc.fk_user";
  3933. }
  3934. $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture as f";
  3935. if (empty($user->rights->societe->client->voir) && !$socid) {
  3936. $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
  3937. }
  3938. $sql .= " WHERE f.entity IN (".getEntity('invoice').")";
  3939. $sql .= " AND f.fk_soc = s.rowid";
  3940. if (empty($user->rights->societe->client->voir) && !$socid) { //restriction
  3941. $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  3942. }
  3943. if ($socid) {
  3944. $sql .= " AND s.rowid = ".((int) $socid);
  3945. }
  3946. if ($draft) {
  3947. $sql .= " AND f.fk_statut = ".self::STATUS_DRAFT;
  3948. }
  3949. if (is_object($excluser)) {
  3950. $sql .= " AND f.fk_user_author <> ".((int) $excluser->id);
  3951. }
  3952. $sql .= $this->db->order($sortfield, $sortorder);
  3953. $sql .= $this->db->plimit($limit, $offset);
  3954. $result = $this->db->query($sql);
  3955. if ($result) {
  3956. $numc = $this->db->num_rows($result);
  3957. if ($numc) {
  3958. $i = 0;
  3959. while ($i < $numc) {
  3960. $obj = $this->db->fetch_object($result);
  3961. if ($shortlist == 1) {
  3962. $ga[$obj->fid] = $obj->ref;
  3963. } elseif ($shortlist == 2) {
  3964. $ga[$obj->fid] = $obj->ref.' ('.$obj->name.')';
  3965. } else {
  3966. $ga[$i]['id'] = $obj->fid;
  3967. $ga[$i]['ref'] = $obj->ref;
  3968. $ga[$i]['name'] = $obj->name;
  3969. }
  3970. $i++;
  3971. }
  3972. }
  3973. return $ga;
  3974. } else {
  3975. dol_print_error($this->db);
  3976. return -1;
  3977. }
  3978. }
  3979. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3980. /**
  3981. * Return list of invoices qualified to be replaced by another invoice.
  3982. * Invoices matching the following rules are returned:
  3983. * (Status validated or abandonned for a reason 'other') + not payed + no payment at all + not already replaced
  3984. *
  3985. * @param int $socid Id thirdparty
  3986. * @return array|int Array of invoices ('id'=>id, 'ref'=>ref, 'status'=>status, 'paymentornot'=>0/1)
  3987. */
  3988. public function list_replacable_invoices($socid = 0)
  3989. {
  3990. // phpcs:enable
  3991. global $conf;
  3992. $return = array();
  3993. $sql = "SELECT f.rowid as rowid, f.ref, f.fk_statut as status, f.paye as paid,";
  3994. $sql .= " ff.rowid as rowidnext";
  3995. //$sql .= ", SUM(pf.amount) as alreadypaid";
  3996. $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
  3997. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
  3998. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as ff ON f.rowid = ff.fk_facture_source";
  3999. $sql .= " WHERE (f.fk_statut = ".self::STATUS_VALIDATED." OR (f.fk_statut = ".self::STATUS_ABANDONED." AND f.close_code = '".self::CLOSECODE_ABANDONED."'))";
  4000. $sql .= " AND f.entity IN (".getEntity('invoice').")";
  4001. $sql .= " AND f.paye = 0"; // Not paid completely
  4002. $sql .= " AND pf.fk_paiement IS NULL"; // No payment already done
  4003. $sql .= " AND ff.fk_statut IS NULL"; // Return true if it is not a replacement invoice
  4004. if ($socid > 0) {
  4005. $sql .= " AND f.fk_soc = ".((int) $socid);
  4006. }
  4007. //$sql .= " GROUP BY f.rowid, f.ref, f.fk_statut, f.paye, ff.rowid";
  4008. $sql .= " ORDER BY f.ref";
  4009. dol_syslog(get_class($this)."::list_replacable_invoices", LOG_DEBUG);
  4010. $resql = $this->db->query($sql);
  4011. if ($resql) {
  4012. while ($obj = $this->db->fetch_object($resql)) {
  4013. $return[$obj->rowid] = array(
  4014. 'id' => $obj->rowid,
  4015. 'ref' => $obj->ref,
  4016. 'status' => $obj->status,
  4017. 'paid' => $obj->paid,
  4018. 'alreadypaid' => 0
  4019. );
  4020. }
  4021. //print_r($return);
  4022. return $return;
  4023. } else {
  4024. $this->error = $this->db->error();
  4025. return -1;
  4026. }
  4027. }
  4028. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4029. /**
  4030. * Return list of invoices qualified to be corrected by a credit note.
  4031. * Invoices matching the following rules are returned:
  4032. * (validated + payment on process) or classified (payed completely or payed partiely) + not already replaced + not already a credit note
  4033. *
  4034. * @param int $socid Id thirdparty
  4035. * @return array Array of invoices ($id => array('ref'=>,'paymentornot'=>,'status'=>,'paye'=>)
  4036. */
  4037. public function list_qualified_avoir_invoices($socid = 0)
  4038. {
  4039. // phpcs:enable
  4040. global $conf;
  4041. $return = array();
  4042. $sql = "SELECT f.rowid as rowid, f.ref, f.fk_statut, f.type, f.paye, pf.fk_paiement";
  4043. $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
  4044. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
  4045. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as ff ON (f.rowid = ff.fk_facture_source AND ff.type=".self::TYPE_REPLACEMENT.")";
  4046. $sql .= " WHERE f.entity IN (".getEntity('invoice').")";
  4047. $sql .= " AND f.fk_statut in (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")";
  4048. // $sql.= " WHERE f.fk_statut >= 1";
  4049. // $sql.= " AND (f.paye = 1"; // Classee payee completement
  4050. // $sql.= " OR f.close_code IS NOT NULL)"; // Classee payee partiellement
  4051. $sql .= " AND ff.type IS NULL"; // Renvoi vrai si pas facture de remplacement
  4052. $sql .= " AND f.type <> ".self::TYPE_CREDIT_NOTE; // Exclude credit note invoices from selection
  4053. if (!empty($conf->global->INVOICE_USE_SITUATION_CREDIT_NOTE)) {
  4054. // Keep invoices that are not situation invoices or that are the last in serie if it is a situation invoice
  4055. $sql .= " AND (f.type <> ".self::TYPE_SITUATION." OR f.rowid IN ";
  4056. $sql .= '(SELECT MAX(fs.rowid)'; // This select returns several ID becasue of the group by later
  4057. $sql .= " FROM ".MAIN_DB_PREFIX."facture as fs";
  4058. $sql .= " WHERE fs.entity IN (".getEntity('invoice').")";
  4059. $sql .= " AND fs.type = ".self::TYPE_SITUATION;
  4060. $sql .= " AND fs.fk_statut IN (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")";
  4061. if ($socid > 0) {
  4062. $sql .= " AND fs.fk_soc = ".((int) $socid);
  4063. }
  4064. $sql .= " GROUP BY fs.situation_cycle_ref)"; // For each situation_cycle_ref, we take the higher rowid
  4065. $sql .= ")";
  4066. } else {
  4067. $sql .= " AND f.type <> ".self::TYPE_SITUATION; // Keep invoices that are not situation invoices
  4068. }
  4069. if ($socid > 0) {
  4070. $sql .= " AND f.fk_soc = ".((int) $socid);
  4071. }
  4072. $sql .= " ORDER BY f.ref";
  4073. dol_syslog(get_class($this)."::list_qualified_avoir_invoices", LOG_DEBUG);
  4074. $resql = $this->db->query($sql);
  4075. if ($resql) {
  4076. while ($obj = $this->db->fetch_object($resql)) {
  4077. $qualified = 0;
  4078. if ($obj->fk_statut == self::STATUS_VALIDATED) {
  4079. $qualified = 1;
  4080. }
  4081. if ($obj->fk_statut == self::STATUS_CLOSED) {
  4082. $qualified = 1;
  4083. }
  4084. if ($qualified) {
  4085. //$ref=$obj->ref;
  4086. $paymentornot = ($obj->fk_paiement ? 1 : 0);
  4087. $return[$obj->rowid] = array('ref'=>$obj->ref, 'status'=>$obj->fk_statut, 'type'=>$obj->type, 'paye'=>$obj->paye, 'paymentornot'=>$paymentornot);
  4088. }
  4089. }
  4090. return $return;
  4091. } else {
  4092. $this->error = $this->db->error();
  4093. return -1;
  4094. }
  4095. }
  4096. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4097. /**
  4098. * Load indicators for dashboard (this->nbtodo and this->nbtodolate)
  4099. *
  4100. * @param User $user Object user
  4101. * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK
  4102. */
  4103. public function load_board($user)
  4104. {
  4105. // phpcs:enable
  4106. global $conf, $langs;
  4107. $clause = " WHERE";
  4108. $sql = "SELECT f.rowid, f.date_lim_reglement as datefin, f.fk_statut, f.total_ht";
  4109. $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
  4110. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  4111. $sql .= " JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON f.fk_soc = sc.fk_soc";
  4112. $sql .= " WHERE sc.fk_user = ".((int) $user->id);
  4113. $clause = " AND";
  4114. }
  4115. $sql .= $clause." f.paye=0";
  4116. $sql .= " AND f.entity IN (".getEntity('invoice').")";
  4117. $sql .= " AND f.fk_statut = ".self::STATUS_VALIDATED;
  4118. if ($user->socid) {
  4119. $sql .= " AND f.fk_soc = ".((int) $user->socid);
  4120. }
  4121. $resql = $this->db->query($sql);
  4122. if ($resql) {
  4123. $langs->load("bills");
  4124. $now = dol_now();
  4125. $response = new WorkboardResponse();
  4126. $response->warning_delay = $conf->facture->client->warning_delay / 60 / 60 / 24;
  4127. $response->label = $langs->trans("CustomerBillsUnpaid");
  4128. $response->labelShort = $langs->trans("Unpaid");
  4129. $response->url = DOL_URL_ROOT.'/compta/facture/list.php?search_status=1&mainmenu=billing&leftmenu=customers_bills';
  4130. $response->img = img_object('', "bill");
  4131. $generic_facture = new Facture($this->db);
  4132. while ($obj = $this->db->fetch_object($resql)) {
  4133. $generic_facture->date_lim_reglement = $this->db->jdate($obj->datefin);
  4134. $generic_facture->statut = $obj->fk_statut;
  4135. $response->nbtodo++;
  4136. $response->total += $obj->total_ht;
  4137. if ($generic_facture->hasDelay()) {
  4138. $response->nbtodolate++;
  4139. $response->url_late = DOL_URL_ROOT.'/compta/facture/list.php?search_option=late&mainmenu=billing&leftmenu=customers_bills';
  4140. }
  4141. }
  4142. $this->db->free($resql);
  4143. return $response;
  4144. } else {
  4145. dol_print_error($this->db);
  4146. $this->error = $this->db->error();
  4147. return -1;
  4148. }
  4149. }
  4150. /* gestion des contacts d'une facture */
  4151. /**
  4152. * Retourne id des contacts clients de facturation
  4153. *
  4154. * @return array Liste des id contacts facturation
  4155. */
  4156. public function getIdBillingContact()
  4157. {
  4158. return $this->getIdContact('external', 'BILLING');
  4159. }
  4160. /**
  4161. * Retourne id des contacts clients de livraison
  4162. *
  4163. * @return array Liste des id contacts livraison
  4164. */
  4165. public function getIdShippingContact()
  4166. {
  4167. return $this->getIdContact('external', 'SHIPPING');
  4168. }
  4169. /**
  4170. * Initialise an instance with random values.
  4171. * Used to build previews or test instances.
  4172. * id must be 0 if object instance is a specimen.
  4173. *
  4174. * @param string $option ''=Create a specimen invoice with lines, 'nolines'=No lines
  4175. * @return void
  4176. */
  4177. public function initAsSpecimen($option = '')
  4178. {
  4179. global $conf, $langs, $user;
  4180. $now = dol_now();
  4181. $arraynow = dol_getdate($now);
  4182. $nownotime = dol_mktime(0, 0, 0, $arraynow['mon'], $arraynow['mday'], $arraynow['year']);
  4183. // Load array of products prodids
  4184. $num_prods = 0;
  4185. $prodids = array();
  4186. $sql = "SELECT rowid";
  4187. $sql .= " FROM ".MAIN_DB_PREFIX."product";
  4188. $sql .= " WHERE entity IN (".getEntity('product').")";
  4189. $sql .= $this->db->plimit(100);
  4190. $resql = $this->db->query($sql);
  4191. if ($resql) {
  4192. $num_prods = $this->db->num_rows($resql);
  4193. $i = 0;
  4194. while ($i < $num_prods) {
  4195. $i++;
  4196. $row = $this->db->fetch_row($resql);
  4197. $prodids[$i] = $row[0];
  4198. }
  4199. }
  4200. //Avoid php warning Warning: mt_rand(): max(0) is smaller than min(1) when no product exists
  4201. if (empty($num_prods)) {
  4202. $num_prods = 1;
  4203. }
  4204. // Initialize parameters
  4205. $this->id = 0;
  4206. $this->entity = 1;
  4207. $this->ref = 'SPECIMEN';
  4208. $this->specimen = 1;
  4209. $this->socid = 1;
  4210. $this->date = $nownotime;
  4211. $this->date_lim_reglement = $nownotime + 3600 * 24 * 30;
  4212. $this->cond_reglement_id = 1;
  4213. $this->cond_reglement_code = 'RECEP';
  4214. $this->date_lim_reglement = $this->calculate_date_lim_reglement();
  4215. $this->mode_reglement_id = 0; // Not forced to show payment mode CHQ + VIR
  4216. $this->mode_reglement_code = ''; // Not forced to show payment mode CHQ + VIR
  4217. $this->note_public = 'This is a comment (public)';
  4218. $this->note_private = 'This is a comment (private)';
  4219. $this->note = 'This is a comment (private)';
  4220. $this->fk_user_author = $user->id;
  4221. $this->multicurrency_tx = 1;
  4222. $this->multicurrency_code = $conf->currency;
  4223. $this->fk_incoterms = 0;
  4224. $this->location_incoterms = '';
  4225. if (empty($option) || $option != 'nolines') {
  4226. // Lines
  4227. $nbp = 5;
  4228. $xnbp = 0;
  4229. while ($xnbp < $nbp) {
  4230. $line = new FactureLigne($this->db);
  4231. $line->desc = $langs->trans("Description")." ".$xnbp;
  4232. $line->qty = 1;
  4233. $line->subprice = 100;
  4234. $line->tva_tx = 19.6;
  4235. $line->localtax1_tx = 0;
  4236. $line->localtax2_tx = 0;
  4237. $line->remise_percent = 0;
  4238. if ($xnbp == 1) { // Qty is negative (product line)
  4239. $prodid = mt_rand(1, $num_prods);
  4240. $line->fk_product = $prodids[$prodid];
  4241. $line->qty = -1;
  4242. $line->total_ht = -100;
  4243. $line->total_ttc = -119.6;
  4244. $line->total_tva = -19.6;
  4245. $line->multicurrency_total_ht = -200;
  4246. $line->multicurrency_total_ttc = -239.2;
  4247. $line->multicurrency_total_tva = -39.2;
  4248. } elseif ($xnbp == 2) { // UP is negative (free line)
  4249. $line->subprice = -100;
  4250. $line->total_ht = -100;
  4251. $line->total_ttc = -119.6;
  4252. $line->total_tva = -19.6;
  4253. $line->remise_percent = 0;
  4254. $line->multicurrency_total_ht = -200;
  4255. $line->multicurrency_total_ttc = -239.2;
  4256. $line->multicurrency_total_tva = -39.2;
  4257. } elseif ($xnbp == 3) { // Discount is 50% (product line)
  4258. $prodid = mt_rand(1, $num_prods);
  4259. $line->fk_product = $prodids[$prodid];
  4260. $line->total_ht = 50;
  4261. $line->total_ttc = 59.8;
  4262. $line->total_tva = 9.8;
  4263. $line->multicurrency_total_ht = 100;
  4264. $line->multicurrency_total_ttc = 119.6;
  4265. $line->multicurrency_total_tva = 19.6;
  4266. $line->remise_percent = 50;
  4267. } else // (product line)
  4268. {
  4269. $prodid = mt_rand(1, $num_prods);
  4270. $line->fk_product = $prodids[$prodid];
  4271. $line->total_ht = 100;
  4272. $line->total_ttc = 119.6;
  4273. $line->total_tva = 19.6;
  4274. $line->multicurrency_total_ht = 200;
  4275. $line->multicurrency_total_ttc = 239.2;
  4276. $line->multicurrency_total_tva = 39.2;
  4277. $line->remise_percent = 0;
  4278. }
  4279. $this->lines[$xnbp] = $line;
  4280. $this->total_ht += $line->total_ht;
  4281. $this->total_tva += $line->total_tva;
  4282. $this->total_ttc += $line->total_ttc;
  4283. $this->multicurrency_total_ht += $line->multicurrency_total_ht;
  4284. $this->multicurrency_total_tva += $line->multicurrency_total_tva;
  4285. $this->multicurrency_total_ttc += $line->multicurrency_total_ttc;
  4286. $xnbp++;
  4287. }
  4288. $this->revenuestamp = 0;
  4289. // Add a line "offered"
  4290. $line = new FactureLigne($this->db);
  4291. $line->desc = $langs->trans("Description")." (offered line)";
  4292. $line->qty = 1;
  4293. $line->subprice = 100;
  4294. $line->tva_tx = 19.6;
  4295. $line->localtax1_tx = 0;
  4296. $line->localtax2_tx = 0;
  4297. $line->remise_percent = 100;
  4298. $line->total_ht = 0;
  4299. $line->total_ttc = 0; // 90 * 1.196
  4300. $line->total_tva = 0;
  4301. $line->multicurrency_total_ht = 0;
  4302. $line->multicurrency_total_ttc = 0;
  4303. $line->multicurrency_total_tva = 0;
  4304. $prodid = mt_rand(1, $num_prods);
  4305. $line->fk_product = $prodids[$prodid];
  4306. $this->lines[$xnbp] = $line;
  4307. $xnbp++;
  4308. }
  4309. }
  4310. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4311. /**
  4312. * Load indicators for dashboard (this->nbtodo and this->nbtodolate)
  4313. *
  4314. * @return int <0 if KO, >0 if OK
  4315. */
  4316. public function load_state_board()
  4317. {
  4318. // phpcs:enable
  4319. global $conf, $user;
  4320. $this->nb = array();
  4321. $clause = "WHERE";
  4322. $sql = "SELECT count(f.rowid) as nb";
  4323. $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
  4324. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON f.fk_soc = s.rowid";
  4325. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  4326. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
  4327. $sql .= " WHERE sc.fk_user = ".((int) $user->id);
  4328. $clause = "AND";
  4329. }
  4330. $sql .= " ".$clause." f.entity IN (".getEntity('invoice').")";
  4331. $resql = $this->db->query($sql);
  4332. if ($resql) {
  4333. while ($obj = $this->db->fetch_object($resql)) {
  4334. $this->nb["invoices"] = $obj->nb;
  4335. }
  4336. $this->db->free($resql);
  4337. return 1;
  4338. } else {
  4339. dol_print_error($this->db);
  4340. $this->error = $this->db->error();
  4341. return -1;
  4342. }
  4343. }
  4344. /**
  4345. * Create an array of invoice lines
  4346. *
  4347. * @return int >0 if OK, <0 if KO
  4348. */
  4349. public function getLinesArray()
  4350. {
  4351. return $this->fetch_lines();
  4352. }
  4353. /**
  4354. * Create a document onto disk according to template module.
  4355. *
  4356. * @param string $modele Generator to use. Caller must set it to obj->model_pdf or GETPOST('model','alpha') for example.
  4357. * @param Translate $outputlangs Object lang to use for translation
  4358. * @param int $hidedetails Hide details of lines
  4359. * @param int $hidedesc Hide description
  4360. * @param int $hideref Hide ref
  4361. * @param null|array $moreparams Array to provide more information
  4362. * @return int <0 if KO, >0 if OK
  4363. */
  4364. public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
  4365. {
  4366. global $conf, $langs;
  4367. $outputlangs->loadLangs(array("bills", "products"));
  4368. if (!dol_strlen($modele)) {
  4369. $modele = 'crabe';
  4370. $thisTypeConfName = 'FACTURE_ADDON_PDF_'.$this->type;
  4371. if (!empty($this->model_pdf)) {
  4372. $modele = $this->model_pdf;
  4373. } elseif (!empty($this->modelpdf)) { // deprecated
  4374. $modele = $this->modelpdf;
  4375. } elseif (!empty($conf->global->$thisTypeConfName)) {
  4376. $modele = $conf->global->$thisTypeConfName;
  4377. } elseif (!empty($conf->global->FACTURE_ADDON_PDF)) {
  4378. $modele = $conf->global->FACTURE_ADDON_PDF;
  4379. }
  4380. }
  4381. $modelpath = "core/modules/facture/doc/";
  4382. return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
  4383. }
  4384. /**
  4385. * Gets the smallest reference available for a new cycle
  4386. *
  4387. * @return int >= 1 if OK, -1 if error
  4388. */
  4389. public function newCycle()
  4390. {
  4391. $sql = 'SELECT max(situation_cycle_ref) FROM '.MAIN_DB_PREFIX.'facture as f';
  4392. $sql .= " WHERE f.entity IN (".getEntity('invoice', 0).")";
  4393. $resql = $this->db->query($sql);
  4394. if ($resql) {
  4395. if ($this->db->num_rows($resql) > 0) {
  4396. $res = $this->db->fetch_array($resql);
  4397. $ref = $res['max(situation_cycle_ref)'];
  4398. $ref++;
  4399. } else {
  4400. $ref = 1;
  4401. }
  4402. $this->db->free($resql);
  4403. return $ref;
  4404. } else {
  4405. $this->error = $this->db->lasterror();
  4406. dol_syslog("Error sql=".$sql.", error=".$this->error, LOG_ERR);
  4407. return -1;
  4408. }
  4409. }
  4410. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4411. /**
  4412. * Checks if the invoice is the first of a cycle
  4413. *
  4414. * @return boolean
  4415. */
  4416. public function is_first()
  4417. {
  4418. // phpcs:enable
  4419. return ($this->situation_counter == 1);
  4420. }
  4421. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4422. /**
  4423. * Returns an array containing the previous situations as Facture objects
  4424. *
  4425. * @return mixed -1 if error, array of previous situations
  4426. */
  4427. public function get_prev_sits()
  4428. {
  4429. // phpcs:enable
  4430. global $conf;
  4431. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'facture';
  4432. $sql .= ' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
  4433. $sql .= ' AND situation_counter < '.((int) $this->situation_counter);
  4434. $sql .= ' AND entity = '.($this->entity > 0 ? $this->entity : $conf->entity);
  4435. $resql = $this->db->query($sql);
  4436. $res = array();
  4437. if ($resql && $this->db->num_rows($resql) > 0) {
  4438. while ($row = $this->db->fetch_object($resql)) {
  4439. $id = $row->rowid;
  4440. $situation = new Facture($this->db);
  4441. $situation->fetch($id);
  4442. $res[] = $situation;
  4443. }
  4444. } else {
  4445. $this->error = $this->db->error();
  4446. dol_syslog("Error sql=".$sql.", error=".$this->error, LOG_ERR);
  4447. return -1;
  4448. }
  4449. return $res;
  4450. }
  4451. /**
  4452. * Sets the invoice as a final situation
  4453. *
  4454. * @param User $user Object user
  4455. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  4456. * @return int <0 if KO, >0 if OK
  4457. */
  4458. public function setFinal(User $user, $notrigger = 0)
  4459. {
  4460. $error = 0;
  4461. $this->db->begin();
  4462. $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET situation_final = '.((int) $this->situation_final).' WHERE rowid = '.((int) $this->id);
  4463. dol_syslog(__METHOD__, LOG_DEBUG);
  4464. $resql = $this->db->query($sql);
  4465. if (!$resql) {
  4466. $this->errors[] = $this->db->error();
  4467. $error++;
  4468. }
  4469. if (!$notrigger && empty($error)) {
  4470. // Call trigger
  4471. $result = $this->call_trigger('BILL_MODIFY', $user);
  4472. if ($result < 0) {
  4473. $error++;
  4474. }
  4475. // End call triggers
  4476. }
  4477. if (!$error) {
  4478. $this->db->commit();
  4479. return 1;
  4480. } else {
  4481. foreach ($this->errors as $errmsg) {
  4482. dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
  4483. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  4484. }
  4485. $this->db->rollback();
  4486. return -1 * $error;
  4487. }
  4488. }
  4489. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4490. /**
  4491. * Checks if the invoice is the last in its cycle
  4492. *
  4493. * @return bool Last of the cycle status
  4494. */
  4495. public function is_last_in_cycle()
  4496. {
  4497. // phpcs:enable
  4498. global $conf;
  4499. if (!empty($this->situation_cycle_ref)) {
  4500. // No point in testing anything if we're not inside a cycle
  4501. $sql = 'SELECT max(situation_counter) FROM '.MAIN_DB_PREFIX.'facture';
  4502. $sql .= ' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
  4503. $sql .= ' AND entity = '.($this->entity > 0 ? $this->entity : $conf->entity);
  4504. $resql = $this->db->query($sql);
  4505. if ($resql && $this->db->num_rows($resql) > 0) {
  4506. $res = $this->db->fetch_array($resql);
  4507. $last = $res['max(situation_counter)'];
  4508. return ($last == $this->situation_counter);
  4509. } else {
  4510. $this->error = $this->db->lasterror();
  4511. dol_syslog(get_class($this)."::select Error ".$this->error, LOG_ERR);
  4512. return false;
  4513. }
  4514. } else {
  4515. return true;
  4516. }
  4517. }
  4518. /**
  4519. * Function used to replace a thirdparty id with another one.
  4520. *
  4521. * @param DoliDB $db Database handler
  4522. * @param int $origin_id Old third-party id
  4523. * @param int $dest_id New third-party id
  4524. * @return bool
  4525. */
  4526. public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
  4527. {
  4528. $tables = array(
  4529. 'facture'
  4530. );
  4531. return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
  4532. }
  4533. /**
  4534. * Function used to replace a product id with another one.
  4535. *
  4536. * @param DoliDB $db Database handler
  4537. * @param int $origin_id Old product id
  4538. * @param int $dest_id New product id
  4539. * @return bool
  4540. */
  4541. public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
  4542. {
  4543. $tables = array(
  4544. 'facturedet'
  4545. );
  4546. return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
  4547. }
  4548. /**
  4549. * Is the customer invoice delayed?
  4550. *
  4551. * @return bool
  4552. */
  4553. public function hasDelay()
  4554. {
  4555. global $conf;
  4556. $now = dol_now();
  4557. // Paid invoices have status STATUS_CLOSED
  4558. if ($this->statut != Facture::STATUS_VALIDATED) {
  4559. return false;
  4560. }
  4561. $hasDelay = $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay);
  4562. if ($hasDelay && !empty($this->retained_warranty) && !empty($this->retained_warranty_date_limit)) {
  4563. $totalpaid = $this->getSommePaiement();
  4564. $totalpaid = floatval($totalpaid);
  4565. $RetainedWarrantyAmount = $this->getRetainedWarrantyAmount();
  4566. if ($totalpaid >= 0 && $RetainedWarrantyAmount >= 0) {
  4567. if (($totalpaid < $this->total_ttc - $RetainedWarrantyAmount) && $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay)) {
  4568. $hasDelay = 1;
  4569. } elseif ($totalpaid < $this->total_ttc && $this->retained_warranty_date_limit < ($now - $conf->facture->client->warning_delay)) {
  4570. $hasDelay = 1;
  4571. } else {
  4572. $hasDelay = 0;
  4573. }
  4574. }
  4575. }
  4576. return $hasDelay;
  4577. }
  4578. /**
  4579. * Currently used for documents generation : to know if retained warranty need to be displayed
  4580. * @return bool
  4581. */
  4582. public function displayRetainedWarranty()
  4583. {
  4584. global $conf;
  4585. // TODO : add a flag on invoices to store this conf : INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION
  4586. // note : we don't need to test INVOICE_USE_RETAINED_WARRANTY because if $this->retained_warranty is not empty it's because it was set when this conf was active
  4587. $displayWarranty = false;
  4588. if (!empty($this->retained_warranty)) {
  4589. $displayWarranty = true;
  4590. if ($this->type == Facture::TYPE_SITUATION && !empty($conf->global->INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION)) {
  4591. // Check if this situation invoice is 100% for real
  4592. $displayWarranty = false;
  4593. if (!empty($this->situation_final)) {
  4594. $displayWarranty = true;
  4595. } elseif (!empty($this->lines) && $this->status == Facture::STATUS_DRAFT) {
  4596. // $object->situation_final need validation to be done so this test is need for draft
  4597. $displayWarranty = true;
  4598. foreach ($this->lines as $i => $line) {
  4599. if ($line->product_type < 2 && $line->situation_percent < 100) {
  4600. $displayWarranty = false;
  4601. break;
  4602. }
  4603. }
  4604. }
  4605. }
  4606. }
  4607. return $displayWarranty;
  4608. }
  4609. /**
  4610. * @param int $rounding Minimum number of decimal to show. If 0, no change, if -1, we use min($conf->global->MAIN_MAX_DECIMALS_UNIT,$conf->global->MAIN_MAX_DECIMALS_TOT)
  4611. * @return number or -1 if not available
  4612. */
  4613. public function getRetainedWarrantyAmount($rounding = -1)
  4614. {
  4615. global $conf;
  4616. if (empty($this->retained_warranty)) {
  4617. return -1;
  4618. }
  4619. $retainedWarrantyAmount = 0;
  4620. // Billed - retained warranty
  4621. if ($this->type == Facture::TYPE_SITUATION && !empty($conf->global->INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION)) {
  4622. $displayWarranty = true;
  4623. // Check if this situation invoice is 100% for real
  4624. if (!empty($this->lines)) {
  4625. foreach ($this->lines as $i => $line) {
  4626. if ($line->product_type < 2 && $line->situation_percent < 100) {
  4627. $displayWarranty = false;
  4628. break;
  4629. }
  4630. }
  4631. }
  4632. if ($displayWarranty && !empty($this->situation_final)) {
  4633. $this->fetchPreviousNextSituationInvoice();
  4634. $TPreviousIncoice = $this->tab_previous_situation_invoice;
  4635. $total2BillWT = 0;
  4636. foreach ($TPreviousIncoice as &$fac) {
  4637. $total2BillWT += $fac->total_ttc;
  4638. }
  4639. $total2BillWT += $this->total_ttc;
  4640. $retainedWarrantyAmount = $total2BillWT * $this->retained_warranty / 100;
  4641. } else {
  4642. return -1;
  4643. }
  4644. } else {
  4645. // Because one day retained warranty could be used on standard invoices
  4646. $retainedWarrantyAmount = $this->total_ttc * $this->retained_warranty / 100;
  4647. }
  4648. if ($rounding < 0) {
  4649. $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT);
  4650. }
  4651. if ($rounding > 0) {
  4652. return round($retainedWarrantyAmount, $rounding);
  4653. }
  4654. return $retainedWarrantyAmount;
  4655. }
  4656. /**
  4657. * Change the retained warranty
  4658. *
  4659. * @param float $value value of retained warranty
  4660. * @return int >0 if OK, <0 if KO
  4661. */
  4662. public function setRetainedWarranty($value)
  4663. {
  4664. dol_syslog(get_class($this).'::setRetainedWarranty('.$value.')');
  4665. if ($this->statut >= 0) {
  4666. $fieldname = 'retained_warranty';
  4667. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  4668. $sql .= " SET ".$fieldname." = ".((float) $value);
  4669. $sql .= ' WHERE rowid='.((int) $this->id);
  4670. if ($this->db->query($sql)) {
  4671. $this->retained_warranty = floatval($value);
  4672. return 1;
  4673. } else {
  4674. dol_syslog(get_class($this).'::setRetainedWarranty Erreur '.$sql.' - '.$this->db->error());
  4675. $this->error = $this->db->error();
  4676. return -1;
  4677. }
  4678. } else {
  4679. dol_syslog(get_class($this).'::setRetainedWarranty, status of the object is incompatible');
  4680. $this->error = 'Status of the object is incompatible '.$this->statut;
  4681. return -2;
  4682. }
  4683. }
  4684. /**
  4685. * Change the retained_warranty_date_limit
  4686. *
  4687. * @param int $timestamp date limit of retained warranty in timestamp format
  4688. * @param string $dateYmd date limit of retained warranty in Y m d format
  4689. * @return int >0 if OK, <0 if KO
  4690. */
  4691. public function setRetainedWarrantyDateLimit($timestamp, $dateYmd = false)
  4692. {
  4693. if (!$timestamp && $dateYmd) {
  4694. $timestamp = $this->db->jdate($dateYmd);
  4695. }
  4696. dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit('.$timestamp.')');
  4697. if ($this->statut >= 0) {
  4698. $fieldname = 'retained_warranty_date_limit';
  4699. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  4700. $sql .= " SET ".$fieldname." = ".(strval($timestamp) != '' ? "'".$this->db->idate($timestamp)."'" : 'null');
  4701. $sql .= ' WHERE rowid = '.((int) $this->id);
  4702. if ($this->db->query($sql)) {
  4703. $this->retained_warranty_date_limit = $timestamp;
  4704. return 1;
  4705. } else {
  4706. dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit Erreur '.$sql.' - '.$this->db->error());
  4707. $this->error = $this->db->error();
  4708. return -1;
  4709. }
  4710. } else {
  4711. dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit, status of the object is incompatible');
  4712. $this->error = 'Status of the object is incompatible '.$this->statut;
  4713. return -2;
  4714. }
  4715. }
  4716. /**
  4717. * Send reminders by emails for ivoices that are due
  4718. * CAN BE A CRON TASK
  4719. *
  4720. * @param int $nbdays Delay after due date (or before if delay is negative)
  4721. * @param string $paymentmode '' or 'all' by default (no filter), or 'LIQ', 'CHQ', CB', ...
  4722. * @param int|string $template Name (or id) of email template (Must be a template of type 'facture_send')
  4723. * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
  4724. */
  4725. public function sendEmailsRemindersOnInvoiceDueDate($nbdays = 0, $paymentmode = 'all', $template = '')
  4726. {
  4727. global $conf, $langs, $user;
  4728. $error = 0;
  4729. $this->output = '';
  4730. $this->error = '';
  4731. $nbMailSend = 0;
  4732. $errorsMsg = array();
  4733. $langs->load("bills");
  4734. if (empty($conf->facture->enabled)) { // Should not happen. If module disabled, cron job should not be visible.
  4735. $this->output .= $langs->trans('ModuleNotEnabled', $langs->transnoentitiesnoconv("Facture"));
  4736. return 0;
  4737. }
  4738. /*if (empty($conf->global->FACTURE_REMINDER_EMAIL)) {
  4739. $langs->load("bills");
  4740. $this->output .= $langs->trans('EventRemindersByEmailNotEnabled', $langs->transnoentitiesnoconv("Facture"));
  4741. return 0;
  4742. }
  4743. */
  4744. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  4745. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
  4746. require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
  4747. $formmail = new FormMail($this->db);
  4748. $now = dol_now();
  4749. $tmpidate = dol_get_first_hour(dol_time_plus_duree($now, $nbdays, 'd'), 'gmt');
  4750. $tmpinvoice = new Facture($this->db);
  4751. dol_syslog(__METHOD__, LOG_DEBUG);
  4752. $this->db->begin();
  4753. // Select all action comm reminder
  4754. $sql = "SELECT rowid as id FROM ".MAIN_DB_PREFIX."facture as f";
  4755. if (!empty($paymentmode) && $paymentmode != 'all') {
  4756. $sql .= ", ".MAIN_DB_PREFIX."c_paiement as cp";
  4757. }
  4758. $sql .= " WHERE f.paye = 0";
  4759. $sql .= " AND f.date_lim_reglement = '".$this->db->idate($tmpidate, 'gmt')."'";
  4760. $sql .= " AND f.entity IN (".getEntity('facture').")";
  4761. if (!empty($paymentmode) && $paymentmode != 'all') {
  4762. $sql .= " AND f.fk_mode_reglement = cp.id AND cp.code = '".$this->db->escape($paymentmode)."'";
  4763. }
  4764. // TODO Add filter to check there is no payment started
  4765. $sql .= $this->db->order("date_lim_reglement", "ASC");
  4766. $resql = $this->db->query($sql);
  4767. $stmpidate = dol_print_date($tmpidate, 'day', 'gmt');
  4768. $this->output .= $langs->transnoentitiesnoconv("SearchUnpaidInvoicesWithDueDate", $stmpidate);
  4769. if (!empty($paymentmode) && $paymentmode != 'all') {
  4770. $this->output .= ' ('.$langs->transnoentitiesnoconv("PaymentMode").' '.$paymentmode.')';
  4771. }
  4772. $this->output .= '<br>';
  4773. if ($resql) {
  4774. while ($obj = $this->db->fetch_object($resql)) {
  4775. if (!$error) {
  4776. // Load event
  4777. $res = $tmpinvoice->fetch($obj->id);
  4778. if ($res > 0) {
  4779. $tmpinvoice->fetch_thirdparty();
  4780. $outputlangs = new Translate('', $conf);
  4781. if ($tmpinvoice->thirdparty->default_lang) {
  4782. $outputlangs->setDefaultLang($tmpinvoice->thirdparty->default_lang);
  4783. $outputlangs->loadLangs(array("main", "bills"));
  4784. } else {
  4785. $outputlangs = $langs;
  4786. }
  4787. // Select email template
  4788. $arraymessage = $formmail->getEMailTemplate($this->db, 'facture_send', $user, $outputlangs, (is_numeric($template) ? $template : 0), 1, (is_numeric($template) ? '' : $template));
  4789. if (is_numeric($arraymessage) && $arraymessage <= 0) {
  4790. $langs->load("errors");
  4791. $this->output .= $langs->trans('ErrorFailedToFindEmailTemplate', $template);
  4792. return 0;
  4793. }
  4794. // PREPARE EMAIL
  4795. $errormesg = '';
  4796. // Make substitution in email content
  4797. $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, '', $tmpinvoice);
  4798. complete_substitutions_array($substitutionarray, $outputlangs, $tmpinvoice);
  4799. // Topic
  4800. $sendTopic = make_substitutions(empty($arraymessage->topic) ? $outputlangs->transnoentitiesnoconv('InformationMessage') : $arraymessage->topic, $substitutionarray, $outputlangs, 1);
  4801. // Content
  4802. $content = $outputlangs->transnoentitiesnoconv($arraymessage->content);
  4803. $sendContent = make_substitutions($content, $substitutionarray, $outputlangs, 1);
  4804. // Recipient
  4805. $to = '';
  4806. $res = $tmpinvoice->fetch_thirdparty();
  4807. $recipient = $tmpinvoice->thirdparty;
  4808. if ($res > 0) {
  4809. if (!empty($recipient->email)) {
  4810. $to = $recipient->email;
  4811. } else {
  4812. $errormesg = "Failed to send remind to thirdparty id=".$tmpinvoice->socid.". No email defined for user.";
  4813. $error++;
  4814. }
  4815. } else {
  4816. $errormesg = "Failed to load recipient with thirdparty id=".$tmpinvoice->socid;
  4817. $error++;
  4818. }
  4819. // Sender
  4820. $from = $conf->global->MAIN_MAIL_EMAIL_FROM;
  4821. if (empty($from)) {
  4822. $errormesg = "Failed to get sender into global setup MAIN_MAIL_EMAIL_FROM";
  4823. $error++;
  4824. }
  4825. if (!$error && $to) {
  4826. // Errors Recipient
  4827. $errors_to = $conf->global->MAIN_MAIL_ERRORS_TO;
  4828. $trackid = 'inv'.$tmpinvoice->id;
  4829. // Mail Creation
  4830. $cMailFile = new CMailFile($sendTopic, $to, $from, $sendContent, array(), array(), array(), '', "", 0, 1, $errors_to, '', $trackid, '', '', '');
  4831. // Sending Mail
  4832. if ($cMailFile->sendfile()) {
  4833. $nbMailSend++;
  4834. } else {
  4835. $errormesg = $cMailFile->error.' : '.$to;
  4836. $error++;
  4837. }
  4838. }
  4839. if ($errormesg) {
  4840. $errorsMsg[] = $errormesg;
  4841. }
  4842. } else {
  4843. $errorsMsg[] = 'Failed to fetch record invoice with ID = '.$obj->id;
  4844. $error++;
  4845. }
  4846. }
  4847. }
  4848. } else {
  4849. $error++;
  4850. }
  4851. if (!$error) {
  4852. $this->output .= 'Nb of emails sent : '.$nbMailSend;
  4853. $this->db->commit();
  4854. return 0;
  4855. } else {
  4856. $this->db->commit(); // We commit also on error, to have the error message recorded.
  4857. $this->error = 'Nb of emails sent : '.$nbMailSend.', '.(!empty($errorsMsg)) ? join(', ', $errorsMsg) : $error;
  4858. return $error;
  4859. }
  4860. }
  4861. /**
  4862. * See if current invoice date is posterior to the last invoice date among validated invoices of same type.
  4863. * @param boolean $allow_validated_drafts return true if the invoice has been validated before returning to DRAFT state.
  4864. * @return boolean
  4865. */
  4866. public function willBeLastOfSameType($allow_validated_drafts = false)
  4867. {
  4868. // get date of last validated invoices of same type
  4869. $sql = "SELECT datef";
  4870. $sql .= " FROM ".MAIN_DB_PREFIX."facture";
  4871. $sql .= " WHERE type = " . (int) $this->type ;
  4872. $sql .= " AND date_valid IS NOT NULL";
  4873. $sql .= " ORDER BY datef DESC LIMIT 1";
  4874. $result = $this->db->query($sql);
  4875. if ($result) {
  4876. // compare with current validation date
  4877. if ($this->db->num_rows($result)) {
  4878. $obj = $this->db->fetch_object($result);
  4879. $last_date = $this->db->jdate($obj->datef);
  4880. $invoice_date = $this->date;
  4881. $is_last_of_same_type = $invoice_date >= $last_date;
  4882. if ($allow_validated_drafts) {
  4883. $is_last_of_same_type = $is_last_of_same_type || (!strpos($this->ref, 'PROV') && $this->status == self::STATUS_DRAFT);
  4884. }
  4885. return [$is_last_of_same_type, $last_date];
  4886. } else {
  4887. // element is first of type to be validated
  4888. return [true];
  4889. }
  4890. } else {
  4891. dol_print_error($this->db);
  4892. }
  4893. }
  4894. }
  4895. /**
  4896. * Class to manage invoice lines.
  4897. * Saved into database table llx_facturedet
  4898. */
  4899. class FactureLigne extends CommonInvoiceLine
  4900. {
  4901. /**
  4902. * @var string ID to identify managed object
  4903. */
  4904. public $element = 'facturedet';
  4905. /**
  4906. * @var string Name of table without prefix where object is stored
  4907. */
  4908. public $table_element = 'facturedet';
  4909. public $oldline;
  4910. //! From llx_facturedet
  4911. //! Id facture
  4912. public $fk_facture;
  4913. //! Id parent line
  4914. public $fk_parent_line;
  4915. //! Description ligne
  4916. public $desc;
  4917. public $ref_ext; // External reference of the line
  4918. public $localtax1_type; // Local tax 1 type
  4919. public $localtax2_type; // Local tax 2 type
  4920. public $fk_remise_except; // Link to line into llx_remise_except
  4921. public $rang = 0;
  4922. public $fk_fournprice;
  4923. public $pa_ht;
  4924. public $marge_tx;
  4925. public $marque_tx;
  4926. public $remise_percent;
  4927. public $special_code; // Liste d'options non cumulabels:
  4928. // 1: frais de port
  4929. // 2: ecotaxe
  4930. // 3: ??
  4931. public $origin;
  4932. public $origin_id;
  4933. public $fk_code_ventilation = 0;
  4934. public $date_start;
  4935. public $date_end;
  4936. public $skip_update_total; // Skip update price total for special lines
  4937. /**
  4938. * @var int Situation advance percentage
  4939. */
  4940. public $situation_percent;
  4941. /**
  4942. * @var int Previous situation line id reference
  4943. */
  4944. public $fk_prev_id;
  4945. // Multicurrency
  4946. public $fk_multicurrency;
  4947. public $multicurrency_code;
  4948. public $multicurrency_subprice;
  4949. public $multicurrency_total_ht;
  4950. public $multicurrency_total_tva;
  4951. public $multicurrency_total_ttc;
  4952. /**
  4953. * Load invoice line from database
  4954. *
  4955. * @param int $rowid id of invoice line to get
  4956. * @return int <0 if KO, >0 if OK
  4957. */
  4958. public function fetch($rowid)
  4959. {
  4960. $sql = 'SELECT fd.rowid, fd.fk_facture, fd.fk_parent_line, fd.fk_product, fd.product_type, fd.label as custom_label, fd.description, fd.price, fd.qty, fd.vat_src_code, fd.tva_tx,';
  4961. $sql .= ' fd.localtax1_tx, fd. localtax2_tx, fd.remise, fd.remise_percent, fd.fk_remise_except, fd.subprice, fd.ref_ext,';
  4962. $sql .= ' fd.date_start as date_start, fd.date_end as date_end, fd.fk_product_fournisseur_price as fk_fournprice, fd.buy_price_ht as pa_ht,';
  4963. $sql .= ' fd.info_bits, fd.special_code, fd.total_ht, fd.total_tva, fd.total_ttc, fd.total_localtax1, fd.total_localtax2, fd.rang,';
  4964. $sql .= ' fd.fk_code_ventilation,';
  4965. $sql .= ' fd.fk_unit, fd.fk_user_author, fd.fk_user_modif,';
  4966. $sql .= ' fd.situation_percent, fd.fk_prev_id,';
  4967. $sql .= ' fd.multicurrency_subprice,';
  4968. $sql .= ' fd.multicurrency_total_ht,';
  4969. $sql .= ' fd.multicurrency_total_tva,';
  4970. $sql .= ' fd.multicurrency_total_ttc,';
  4971. $sql .= ' p.ref as product_ref, p.label as product_label, p.description as product_desc';
  4972. $sql .= ' FROM '.MAIN_DB_PREFIX.'facturedet as fd';
  4973. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON fd.fk_product = p.rowid';
  4974. $sql .= ' WHERE fd.rowid = '.((int) $rowid);
  4975. $result = $this->db->query($sql);
  4976. if ($result) {
  4977. $objp = $this->db->fetch_object($result);
  4978. $this->rowid = $objp->rowid;
  4979. $this->id = $objp->rowid;
  4980. $this->fk_facture = $objp->fk_facture;
  4981. $this->fk_parent_line = $objp->fk_parent_line;
  4982. $this->label = $objp->custom_label;
  4983. $this->desc = $objp->description;
  4984. $this->qty = $objp->qty;
  4985. $this->subprice = $objp->subprice;
  4986. $this->ref_ext = $objp->ref_ext;
  4987. $this->vat_src_code = $objp->vat_src_code;
  4988. $this->tva_tx = $objp->tva_tx;
  4989. $this->localtax1_tx = $objp->localtax1_tx;
  4990. $this->localtax2_tx = $objp->localtax2_tx;
  4991. $this->remise_percent = $objp->remise_percent;
  4992. $this->fk_remise_except = $objp->fk_remise_except;
  4993. $this->fk_product = $objp->fk_product;
  4994. $this->product_type = $objp->product_type;
  4995. $this->date_start = $this->db->jdate($objp->date_start);
  4996. $this->date_end = $this->db->jdate($objp->date_end);
  4997. $this->info_bits = $objp->info_bits;
  4998. $this->tva_npr = ($objp->info_bits & 1 == 1) ? 1 : 0;
  4999. $this->special_code = $objp->special_code;
  5000. $this->total_ht = $objp->total_ht;
  5001. $this->total_tva = $objp->total_tva;
  5002. $this->total_localtax1 = $objp->total_localtax1;
  5003. $this->total_localtax2 = $objp->total_localtax2;
  5004. $this->total_ttc = $objp->total_ttc;
  5005. $this->fk_code_ventilation = $objp->fk_code_ventilation;
  5006. $this->rang = $objp->rang;
  5007. $this->fk_fournprice = $objp->fk_fournprice;
  5008. $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $this->fk_fournprice, $objp->pa_ht);
  5009. $this->pa_ht = $marginInfos[0];
  5010. $this->marge_tx = $marginInfos[1];
  5011. $this->marque_tx = $marginInfos[2];
  5012. $this->ref = $objp->product_ref; // deprecated
  5013. $this->product_ref = $objp->product_ref;
  5014. $this->product_label = $objp->product_label;
  5015. $this->product_desc = $objp->product_desc;
  5016. $this->fk_unit = $objp->fk_unit;
  5017. $this->fk_user_modif = $objp->fk_user_modif;
  5018. $this->fk_user_author = $objp->fk_user_author;
  5019. $this->situation_percent = $objp->situation_percent;
  5020. $this->fk_prev_id = $objp->fk_prev_id;
  5021. $this->multicurrency_subprice = $objp->multicurrency_subprice;
  5022. $this->multicurrency_total_ht = $objp->multicurrency_total_ht;
  5023. $this->multicurrency_total_tva = $objp->multicurrency_total_tva;
  5024. $this->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
  5025. $this->db->free($result);
  5026. return 1;
  5027. } else {
  5028. $this->error = $this->db->lasterror();
  5029. return -1;
  5030. }
  5031. }
  5032. /**
  5033. * Insert line into database
  5034. *
  5035. * @param int $notrigger 1 no triggers
  5036. * @param int $noerrorifdiscountalreadylinked 1=Do not make error if lines is linked to a discount and discount already linked to another
  5037. * @return int <0 if KO, >0 if OK
  5038. */
  5039. public function insert($notrigger = 0, $noerrorifdiscountalreadylinked = 0)
  5040. {
  5041. global $langs, $user, $conf;
  5042. $error = 0;
  5043. $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'.
  5044. dol_syslog(get_class($this)."::insert rang=".$this->rang, LOG_DEBUG);
  5045. // Clean parameters
  5046. $this->desc = trim($this->desc);
  5047. if (empty($this->tva_tx)) {
  5048. $this->tva_tx = 0;
  5049. }
  5050. if (empty($this->localtax1_tx)) {
  5051. $this->localtax1_tx = 0;
  5052. }
  5053. if (empty($this->localtax2_tx)) {
  5054. $this->localtax2_tx = 0;
  5055. }
  5056. if (empty($this->localtax1_type)) {
  5057. $this->localtax1_type = 0;
  5058. }
  5059. if (empty($this->localtax2_type)) {
  5060. $this->localtax2_type = 0;
  5061. }
  5062. if (empty($this->total_localtax1)) {
  5063. $this->total_localtax1 = 0;
  5064. }
  5065. if (empty($this->total_localtax2)) {
  5066. $this->total_localtax2 = 0;
  5067. }
  5068. if (empty($this->rang)) {
  5069. $this->rang = 0;
  5070. }
  5071. if (empty($this->remise_percent)) {
  5072. $this->remise_percent = 0;
  5073. }
  5074. if (empty($this->info_bits)) {
  5075. $this->info_bits = 0;
  5076. }
  5077. if (empty($this->subprice)) {
  5078. $this->subprice = 0;
  5079. }
  5080. if (empty($this->ref_ext)) {
  5081. $this->ref_ext = '';
  5082. }
  5083. if (empty($this->special_code)) {
  5084. $this->special_code = 0;
  5085. }
  5086. if (empty($this->fk_parent_line)) {
  5087. $this->fk_parent_line = 0;
  5088. }
  5089. if (empty($this->fk_prev_id)) {
  5090. $this->fk_prev_id = 0;
  5091. }
  5092. if (!isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') {
  5093. $this->situation_percent = 100;
  5094. }
  5095. if (empty($this->pa_ht)) {
  5096. $this->pa_ht = 0;
  5097. }
  5098. if (empty($this->multicurrency_subprice)) {
  5099. $this->multicurrency_subprice = 0;
  5100. }
  5101. if (empty($this->multicurrency_total_ht)) {
  5102. $this->multicurrency_total_ht = 0;
  5103. }
  5104. if (empty($this->multicurrency_total_tva)) {
  5105. $this->multicurrency_total_tva = 0;
  5106. }
  5107. if (empty($this->multicurrency_total_ttc)) {
  5108. $this->multicurrency_total_ttc = 0;
  5109. }
  5110. // if buy price not defined, define buyprice as configured in margin admin
  5111. if ($this->pa_ht == 0 && $pa_ht_isemptystring) {
  5112. if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) {
  5113. return $result;
  5114. } else {
  5115. $this->pa_ht = $result;
  5116. }
  5117. }
  5118. // Check parameters
  5119. if ($this->product_type < 0) {
  5120. $this->error = 'ErrorProductTypeMustBe0orMore';
  5121. return -1;
  5122. }
  5123. if (!empty($this->fk_product) && $this->fk_product > 0) {
  5124. // Check product exists
  5125. $result = Product::isExistingObject('product', $this->fk_product);
  5126. if ($result <= 0) {
  5127. $this->error = 'ErrorProductIdDoesNotExists';
  5128. dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
  5129. return -1;
  5130. }
  5131. }
  5132. $this->db->begin();
  5133. // Update line in database
  5134. $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facturedet';
  5135. $sql .= ' (fk_facture, fk_parent_line, label, description, qty,';
  5136. $sql .= ' vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
  5137. $sql .= ' fk_product, product_type, remise_percent, subprice, ref_ext, fk_remise_except,';
  5138. $sql .= ' date_start, date_end, fk_code_ventilation, ';
  5139. $sql .= ' rang, special_code, fk_product_fournisseur_price, buy_price_ht,';
  5140. $sql .= ' info_bits, total_ht, total_tva, total_ttc, total_localtax1, total_localtax2,';
  5141. $sql .= ' situation_percent, fk_prev_id,';
  5142. $sql .= ' fk_unit, fk_user_author, fk_user_modif,';
  5143. $sql .= ' fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
  5144. $sql .= ')';
  5145. $sql .= " VALUES (".$this->fk_facture.",";
  5146. $sql .= " ".($this->fk_parent_line > 0 ? $this->fk_parent_line : "null").",";
  5147. $sql .= " ".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null").",";
  5148. $sql .= " '".$this->db->escape($this->desc)."',";
  5149. $sql .= " ".price2num($this->qty).",";
  5150. $sql .= " ".(empty($this->vat_src_code) ? "''" : "'".$this->db->escape($this->vat_src_code)."'").",";
  5151. $sql .= " ".price2num($this->tva_tx).",";
  5152. $sql .= " ".price2num($this->localtax1_tx).",";
  5153. $sql .= " ".price2num($this->localtax2_tx).",";
  5154. $sql .= " '".$this->db->escape($this->localtax1_type)."',";
  5155. $sql .= " '".$this->db->escape($this->localtax2_type)."',";
  5156. $sql .= ' '.((!empty($this->fk_product) && $this->fk_product > 0) ? $this->fk_product : "null").',';
  5157. $sql .= " ".((int) $this->product_type).",";
  5158. $sql .= " ".price2num($this->remise_percent).",";
  5159. $sql .= " ".price2num($this->subprice).",";
  5160. $sql .= " '".$this->db->escape($this->ref_ext)."',";
  5161. $sql .= ' '.(!empty($this->fk_remise_except) ? $this->fk_remise_except : "null").',';
  5162. $sql .= " ".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null").",";
  5163. $sql .= " ".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null").",";
  5164. $sql .= ' '.((int) $this->fk_code_ventilation).',';
  5165. $sql .= ' '.((int) $this->rang).',';
  5166. $sql .= ' '.((int) $this->special_code).',';
  5167. $sql .= ' '.(!empty($this->fk_fournprice) ? $this->fk_fournprice : "null").',';
  5168. $sql .= ' '.price2num($this->pa_ht).',';
  5169. $sql .= " '".$this->db->escape($this->info_bits)."',";
  5170. $sql .= " ".price2num($this->total_ht).",";
  5171. $sql .= " ".price2num($this->total_tva).",";
  5172. $sql .= " ".price2num($this->total_ttc).",";
  5173. $sql .= " ".price2num($this->total_localtax1).",";
  5174. $sql .= " ".price2num($this->total_localtax2);
  5175. $sql .= ", ".((float) $this->situation_percent);
  5176. $sql .= ", ".(!empty($this->fk_prev_id) ? $this->fk_prev_id : "null");
  5177. $sql .= ", ".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
  5178. $sql .= ", ".((int) $user->id);
  5179. $sql .= ", ".((int) $user->id);
  5180. $sql .= ", ".(int) $this->fk_multicurrency;
  5181. $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
  5182. $sql .= ", ".price2num($this->multicurrency_subprice);
  5183. $sql .= ", ".price2num($this->multicurrency_total_ht);
  5184. $sql .= ", ".price2num($this->multicurrency_total_tva);
  5185. $sql .= ", ".price2num($this->multicurrency_total_ttc);
  5186. $sql .= ')';
  5187. dol_syslog(get_class($this)."::insert", LOG_DEBUG);
  5188. $resql = $this->db->query($sql);
  5189. if ($resql) {
  5190. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'facturedet');
  5191. $this->rowid = $this->id; // For backward compatibility
  5192. if (!$error) {
  5193. $result = $this->insertExtraFields();
  5194. if ($result < 0) {
  5195. $error++;
  5196. }
  5197. }
  5198. // If fk_remise_except is defined, the discount is linked to the invoice
  5199. // which flags it as "consumed".
  5200. if ($this->fk_remise_except) {
  5201. $discount = new DiscountAbsolute($this->db);
  5202. $result = $discount->fetch($this->fk_remise_except);
  5203. if ($result >= 0) {
  5204. // Check if discount was found
  5205. if ($result > 0) {
  5206. // Check if discount not already affected to another invoice
  5207. if ($discount->fk_facture_line > 0) {
  5208. if (empty($noerrorifdiscountalreadylinked)) {
  5209. $this->error = $langs->trans("ErrorDiscountAlreadyUsed", $discount->id);
  5210. dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
  5211. $this->db->rollback();
  5212. return -3;
  5213. }
  5214. } else {
  5215. $result = $discount->link_to_invoice($this->rowid, 0);
  5216. if ($result < 0) {
  5217. $this->error = $discount->error;
  5218. dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
  5219. $this->db->rollback();
  5220. return -3;
  5221. }
  5222. }
  5223. } else {
  5224. $this->error = $langs->trans("ErrorADiscountThatHasBeenRemovedIsIncluded");
  5225. dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
  5226. $this->db->rollback();
  5227. return -3;
  5228. }
  5229. } else {
  5230. $this->error = $discount->error;
  5231. dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
  5232. $this->db->rollback();
  5233. return -3;
  5234. }
  5235. }
  5236. if (!$notrigger) {
  5237. // Call trigger
  5238. $result = $this->call_trigger('LINEBILL_INSERT', $user);
  5239. if ($result < 0) {
  5240. $this->db->rollback();
  5241. return -2;
  5242. }
  5243. // End call triggers
  5244. }
  5245. $this->db->commit();
  5246. return $this->id;
  5247. } else {
  5248. $this->error = $this->db->lasterror();
  5249. $this->db->rollback();
  5250. return -2;
  5251. }
  5252. }
  5253. /**
  5254. * Update line into database
  5255. *
  5256. * @param User $user User object
  5257. * @param int $notrigger Disable triggers
  5258. * @return int <0 if KO, >0 if OK
  5259. */
  5260. public function update($user = '', $notrigger = 0)
  5261. {
  5262. global $user, $conf;
  5263. $error = 0;
  5264. $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'.
  5265. // Clean parameters
  5266. $this->desc = trim($this->desc);
  5267. if (empty($this->ref_ext)) {
  5268. $this->ref_ext = '';
  5269. }
  5270. if (empty($this->tva_tx)) {
  5271. $this->tva_tx = 0;
  5272. }
  5273. if (empty($this->localtax1_tx)) {
  5274. $this->localtax1_tx = 0;
  5275. }
  5276. if (empty($this->localtax2_tx)) {
  5277. $this->localtax2_tx = 0;
  5278. }
  5279. if (empty($this->localtax1_type)) {
  5280. $this->localtax1_type = 0;
  5281. }
  5282. if (empty($this->localtax2_type)) {
  5283. $this->localtax2_type = 0;
  5284. }
  5285. if (empty($this->total_localtax1)) {
  5286. $this->total_localtax1 = 0;
  5287. }
  5288. if (empty($this->total_localtax2)) {
  5289. $this->total_localtax2 = 0;
  5290. }
  5291. if (empty($this->remise_percent)) {
  5292. $this->remise_percent = 0;
  5293. }
  5294. if (empty($this->info_bits)) {
  5295. $this->info_bits = 0;
  5296. }
  5297. if (empty($this->special_code)) {
  5298. $this->special_code = 0;
  5299. }
  5300. if (empty($this->product_type)) {
  5301. $this->product_type = 0;
  5302. }
  5303. if (empty($this->fk_parent_line)) {
  5304. $this->fk_parent_line = 0;
  5305. }
  5306. if (!isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') {
  5307. $this->situation_percent = 100;
  5308. }
  5309. if (empty($this->pa_ht)) {
  5310. $this->pa_ht = 0;
  5311. }
  5312. if (empty($this->multicurrency_subprice)) {
  5313. $this->multicurrency_subprice = 0;
  5314. }
  5315. if (empty($this->multicurrency_total_ht)) {
  5316. $this->multicurrency_total_ht = 0;
  5317. }
  5318. if (empty($this->multicurrency_total_tva)) {
  5319. $this->multicurrency_total_tva = 0;
  5320. }
  5321. if (empty($this->multicurrency_total_ttc)) {
  5322. $this->multicurrency_total_ttc = 0;
  5323. }
  5324. // Check parameters
  5325. if ($this->product_type < 0) {
  5326. return -1;
  5327. }
  5328. // if buy price not provided, define buyprice as configured in margin admin
  5329. if ($this->pa_ht == 0 && $pa_ht_isemptystring) {
  5330. // We call defineBuyPrice only if data was not provided (if input was '0', we will not go here and value will remaine '0')
  5331. $result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product);
  5332. if ($result < 0) {
  5333. return $result;
  5334. } else {
  5335. $this->pa_ht = $result;
  5336. }
  5337. }
  5338. $this->db->begin();
  5339. // Update line in database
  5340. $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet SET";
  5341. $sql .= " description='".$this->db->escape($this->desc)."'";
  5342. $sql .= ", ref_ext='".$this->db->escape($this->ref_ext)."'";
  5343. $sql .= ", label=".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null");
  5344. $sql .= ", subprice=".price2num($this->subprice);
  5345. $sql .= ", remise_percent=".price2num($this->remise_percent);
  5346. if ($this->fk_remise_except) {
  5347. $sql .= ", fk_remise_except=".$this->fk_remise_except;
  5348. } else {
  5349. $sql .= ", fk_remise_except=null";
  5350. }
  5351. $sql .= ", vat_src_code = '".(empty($this->vat_src_code) ? '' : $this->db->escape($this->vat_src_code))."'";
  5352. $sql .= ", tva_tx=".price2num($this->tva_tx);
  5353. $sql .= ", localtax1_tx=".price2num($this->localtax1_tx);
  5354. $sql .= ", localtax2_tx=".price2num($this->localtax2_tx);
  5355. $sql .= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'";
  5356. $sql .= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'";
  5357. $sql .= ", qty=".price2num($this->qty);
  5358. $sql .= ", date_start=".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null");
  5359. $sql .= ", date_end=".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null");
  5360. $sql .= ", product_type=".$this->product_type;
  5361. $sql .= ", info_bits='".$this->db->escape($this->info_bits)."'";
  5362. $sql .= ", special_code='".$this->db->escape($this->special_code)."'";
  5363. if (empty($this->skip_update_total)) {
  5364. $sql .= ", total_ht=".price2num($this->total_ht);
  5365. $sql .= ", total_tva=".price2num($this->total_tva);
  5366. $sql .= ", total_ttc=".price2num($this->total_ttc);
  5367. $sql .= ", total_localtax1=".price2num($this->total_localtax1);
  5368. $sql .= ", total_localtax2=".price2num($this->total_localtax2);
  5369. }
  5370. $sql .= ", fk_product_fournisseur_price=".(!empty($this->fk_fournprice) ? "'".$this->db->escape($this->fk_fournprice)."'" : "null");
  5371. $sql .= ", buy_price_ht=".(($this->pa_ht || $this->pa_ht === 0 || $this->pa_ht === '0') ? price2num($this->pa_ht) : "null"); // $this->pa_ht should always be defined (set to 0 or to sell price depending on option)
  5372. $sql .= ", fk_parent_line=".($this->fk_parent_line > 0 ? $this->fk_parent_line : "null");
  5373. if (!empty($this->rang)) {
  5374. $sql .= ", rang=".((int) $this->rang);
  5375. }
  5376. $sql .= ", situation_percent = ".((float) $this->situation_percent);
  5377. $sql .= ", fk_unit = ".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
  5378. $sql .= ", fk_user_modif = ".((int) $user->id);
  5379. // Multicurrency
  5380. $sql .= ", multicurrency_subprice=".price2num($this->multicurrency_subprice);
  5381. $sql .= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht);
  5382. $sql .= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva);
  5383. $sql .= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc);
  5384. $sql .= " WHERE rowid = ".((int) $this->rowid);
  5385. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  5386. $resql = $this->db->query($sql);
  5387. if ($resql) {
  5388. if (!$error) {
  5389. $this->id = $this->rowid;
  5390. $result = $this->insertExtraFields();
  5391. if ($result < 0) {
  5392. $error++;
  5393. }
  5394. }
  5395. if (!$error && !$notrigger) {
  5396. // Call trigger
  5397. $result = $this->call_trigger('LINEBILL_MODIFY', $user);
  5398. if ($result < 0) {
  5399. $this->db->rollback();
  5400. return -2;
  5401. }
  5402. // End call triggers
  5403. }
  5404. $this->db->commit();
  5405. return 1;
  5406. } else {
  5407. $this->error = $this->db->error();
  5408. $this->db->rollback();
  5409. return -2;
  5410. }
  5411. }
  5412. /**
  5413. * Delete line in database
  5414. *
  5415. * @param User $tmpuser User that deletes
  5416. * @param bool $notrigger false=launch triggers after, true=disable triggers
  5417. * @return int <0 if KO, >0 if OK
  5418. */
  5419. public function delete($tmpuser = null, $notrigger = false)
  5420. {
  5421. global $user;
  5422. $this->db->begin();
  5423. // Call trigger
  5424. if (empty($notrigger)) {
  5425. $result = $this->call_trigger('LINEBILL_DELETE', $user);
  5426. if ($result < 0) {
  5427. $this->db->rollback();
  5428. return -1;
  5429. }
  5430. }
  5431. // End call triggers
  5432. // extrafields
  5433. $result = $this->deleteExtraFields();
  5434. if ($result < 0) {
  5435. $this->db->rollback();
  5436. return -1;
  5437. }
  5438. $sql = "DELETE FROM ".MAIN_DB_PREFIX."facturedet WHERE rowid = ".((int) $this->rowid);
  5439. if ($this->db->query($sql)) {
  5440. $this->db->commit();
  5441. return 1;
  5442. } else {
  5443. $this->error = $this->db->error()." sql=".$sql;
  5444. $this->db->rollback();
  5445. return -1;
  5446. }
  5447. }
  5448. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5449. /**
  5450. * Update DB line fields total_xxx
  5451. * Used by migration
  5452. *
  5453. * @return int <0 if KO, >0 if OK
  5454. */
  5455. public function update_total()
  5456. {
  5457. // phpcs:enable
  5458. $this->db->begin();
  5459. dol_syslog(get_class($this)."::update_total", LOG_DEBUG);
  5460. // Clean parameters
  5461. if (empty($this->total_localtax1)) {
  5462. $this->total_localtax1 = 0;
  5463. }
  5464. if (empty($this->total_localtax2)) {
  5465. $this->total_localtax2 = 0;
  5466. }
  5467. // Update line in database
  5468. $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet SET";
  5469. $sql .= " total_ht=".price2num($this->total_ht)."";
  5470. $sql .= ",total_tva=".price2num($this->total_tva)."";
  5471. $sql .= ",total_localtax1=".price2num($this->total_localtax1)."";
  5472. $sql .= ",total_localtax2=".price2num($this->total_localtax2)."";
  5473. $sql .= ",total_ttc=".price2num($this->total_ttc)."";
  5474. $sql .= " WHERE rowid = ".((int) $this->rowid);
  5475. dol_syslog(get_class($this)."::update_total", LOG_DEBUG);
  5476. $resql = $this->db->query($sql);
  5477. if ($resql) {
  5478. $this->db->commit();
  5479. return 1;
  5480. } else {
  5481. $this->error = $this->db->error();
  5482. $this->db->rollback();
  5483. return -2;
  5484. }
  5485. }
  5486. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5487. /**
  5488. * Returns situation_percent of the previous line.
  5489. * Warning: If invoice is a replacement invoice, this->fk_prev_id is id of the replaced line.
  5490. *
  5491. * @param int $invoiceid Invoice id
  5492. * @param bool $include_credit_note Include credit note or not
  5493. * @return int >= 0
  5494. */
  5495. public function get_prev_progress($invoiceid, $include_credit_note = true)
  5496. {
  5497. // phpcs:enable
  5498. global $invoicecache;
  5499. if (is_null($this->fk_prev_id) || empty($this->fk_prev_id) || $this->fk_prev_id == "") {
  5500. return 0;
  5501. } else {
  5502. // If invoice is not a situation invoice, this->fk_prev_id is used for something else
  5503. if (!isset($invoicecache[$invoiceid])) {
  5504. $invoicecache[$invoiceid] = new Facture($this->db);
  5505. $invoicecache[$invoiceid]->fetch($invoiceid);
  5506. }
  5507. if ($invoicecache[$invoiceid]->type != Facture::TYPE_SITUATION) {
  5508. return 0;
  5509. }
  5510. $sql = "SELECT situation_percent FROM ".MAIN_DB_PREFIX."facturedet WHERE rowid = ".((int) $this->fk_prev_id);
  5511. $resql = $this->db->query($sql);
  5512. if ($resql && $this->db->num_rows($resql) > 0) {
  5513. $res = $this->db->fetch_array($resql);
  5514. $returnPercent = floatval($res['situation_percent']);
  5515. if ($include_credit_note) {
  5516. $sql = 'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.'facturedet fd';
  5517. $sql .= ' JOIN '.MAIN_DB_PREFIX.'facture f ON (f.rowid = fd.fk_facture) ';
  5518. $sql .= " WHERE fd.fk_prev_id = ".((int) $this->fk_prev_id);
  5519. $sql .= " AND f.situation_cycle_ref = ".((int) $invoicecache[$invoiceid]->situation_cycle_ref); // Prevent cycle outed
  5520. $sql .= " AND f.type = ".Facture::TYPE_CREDIT_NOTE;
  5521. $res = $this->db->query($sql);
  5522. if ($res) {
  5523. while ($obj = $this->db->fetch_object($res)) {
  5524. $returnPercent = $returnPercent + floatval($obj->situation_percent);
  5525. }
  5526. } else {
  5527. dol_print_error($this->db);
  5528. }
  5529. }
  5530. return $returnPercent;
  5531. } else {
  5532. $this->error = $this->db->error();
  5533. dol_syslog(get_class($this)."::select Error ".$this->error, LOG_ERR);
  5534. $this->db->rollback();
  5535. return -1;
  5536. }
  5537. }
  5538. }
  5539. }