facture.class.php 237 KB

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