facture.class.php 231 KB

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